id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
19,500
|
mage/mage
|
lib/msgServer/msgStream/index.js
|
MsgStream
|
function MsgStream(cfg) {
assert(cfg, 'Cannot set up a message stream without configuration');
assert(cfg.transports, 'Cannot set up a message stream without transports configured');
EventEmitter.call(this);
this.cfg = cfg;
this.addressMap = {};
this.closing = false;
}
|
javascript
|
function MsgStream(cfg) {
assert(cfg, 'Cannot set up a message stream without configuration');
assert(cfg.transports, 'Cannot set up a message stream without transports configured');
EventEmitter.call(this);
this.cfg = cfg;
this.addressMap = {};
this.closing = false;
}
|
[
"function",
"MsgStream",
"(",
"cfg",
")",
"{",
"assert",
"(",
"cfg",
",",
"'Cannot set up a message stream without configuration'",
")",
";",
"assert",
"(",
"cfg",
".",
"transports",
",",
"'Cannot set up a message stream without transports configured'",
")",
";",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"cfg",
"=",
"cfg",
";",
"this",
".",
"addressMap",
"=",
"{",
"}",
";",
"this",
".",
"closing",
"=",
"false",
";",
"}"
] |
The Message Stream handler which wraps around all supported transport types
@param {Object} cfg
@constructor
|
[
"The",
"Message",
"Stream",
"handler",
"which",
"wraps",
"around",
"all",
"supported",
"transport",
"types"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/msgServer/msgStream/index.js#L60-L69
|
19,501
|
mage/mage
|
lib/state/state.js
|
lookupAddresses
|
function lookupAddresses(state, actorIds, cb) {
if (!mage.session) {
return cb(new StateError('Cannot find actors without the "session" module set up.', {
actorIds: actorIds
}));
}
mage.session.getActorAddresses(state, actorIds, cb);
}
|
javascript
|
function lookupAddresses(state, actorIds, cb) {
if (!mage.session) {
return cb(new StateError('Cannot find actors without the "session" module set up.', {
actorIds: actorIds
}));
}
mage.session.getActorAddresses(state, actorIds, cb);
}
|
[
"function",
"lookupAddresses",
"(",
"state",
",",
"actorIds",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"mage",
".",
"session",
")",
"{",
"return",
"cb",
"(",
"new",
"StateError",
"(",
"'Cannot find actors without the \"session\" module set up.'",
",",
"{",
"actorIds",
":",
"actorIds",
"}",
")",
")",
";",
"}",
"mage",
".",
"session",
".",
"getActorAddresses",
"(",
"state",
",",
"actorIds",
",",
"cb",
")",
";",
"}"
] |
Utility method to lookup and cache addresses
to send messages to given actorIds
@param {*} state
@param {*} actorIds
@param {*} cb
|
[
"Utility",
"method",
"to",
"lookup",
"and",
"cache",
"addresses",
"to",
"send",
"messages",
"to",
"given",
"actorIds"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/state/state.js#L44-L52
|
19,502
|
mage/mage
|
lib/serviceDiscovery/engines/mdns/index.js
|
normalizeHost
|
function normalizeHost(host) {
if (!host) {
return host;
}
if (host[host.length - 1] === '.') {
host = host.substring(0, host.length - 1);
}
return host;
}
|
javascript
|
function normalizeHost(host) {
if (!host) {
return host;
}
if (host[host.length - 1] === '.') {
host = host.substring(0, host.length - 1);
}
return host;
}
|
[
"function",
"normalizeHost",
"(",
"host",
")",
"{",
"if",
"(",
"!",
"host",
")",
"{",
"return",
"host",
";",
"}",
"if",
"(",
"host",
"[",
"host",
".",
"length",
"-",
"1",
"]",
"===",
"'.'",
")",
"{",
"host",
"=",
"host",
".",
"substring",
"(",
"0",
",",
"host",
".",
"length",
"-",
"1",
")",
";",
"}",
"return",
"host",
";",
"}"
] |
Hosts in mDNS are announced with a trailing dot, remove it
@param {string} host
@returns {string}
|
[
"Hosts",
"in",
"mDNS",
"are",
"announced",
"with",
"a",
"trailing",
"dot",
"remove",
"it"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/serviceDiscovery/engines/mdns/index.js#L20-L30
|
19,503
|
mage/mage
|
lib/serviceDiscovery/engines/mdns/index.js
|
getUniqueName
|
function getUniqueName(service) {
return service.name + service.type.name + service.type.protocol + service.replyDomain;
}
|
javascript
|
function getUniqueName(service) {
return service.name + service.type.name + service.type.protocol + service.replyDomain;
}
|
[
"function",
"getUniqueName",
"(",
"service",
")",
"{",
"return",
"service",
".",
"name",
"+",
"service",
".",
"type",
".",
"name",
"+",
"service",
".",
"type",
".",
"protocol",
"+",
"service",
".",
"replyDomain",
";",
"}"
] |
Generates a name supposed to be unique on a mDNS network
For more information on name registration, see:
https://developer.apple.com/library/mac/documentation/Networking/Conceptual/dns_discovery_api/Articles/registering.html
@param {Service} service
@returns {string}
|
[
"Generates",
"a",
"name",
"supposed",
"to",
"be",
"unique",
"on",
"a",
"mDNS",
"network"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/serviceDiscovery/engines/mdns/index.js#L41-L43
|
19,504
|
mage/mage
|
lib/serviceDiscovery/engines/mdns/index.js
|
MDNSService
|
function MDNSService(name, type, options) {
var that = this;
this.name = name;
this.type = type;
this.options = options;
this.advertisement = null;
this.browser = new mdns.Browser(mdns.makeServiceType(this.name, this.type));
this.browser.on('serviceUp', function (service) {
// we know that node, don't re-announce it
if (services[getUniqueName(service)]) {
return;
}
// this is our representation of a node, it contains the host, ips, port and metadata of a service
var node = new ServiceNode(normalizeHost(service.host), service.port, service.addresses, service.txtRecord);
services[getUniqueName(service)] = node;
that.emit('up', node);
});
this.browser.on('serviceDown', function (service) {
// retrieve the service object
var node = services[getUniqueName(service)];
// we never saw that node go up, don't emit a down
if (!node) {
return;
}
that.emit('down', node);
// remove the data we knew about it
delete services[getUniqueName(service)];
});
this.browser.on('error', function (error, service) {
that.emit('error', error, service);
});
}
|
javascript
|
function MDNSService(name, type, options) {
var that = this;
this.name = name;
this.type = type;
this.options = options;
this.advertisement = null;
this.browser = new mdns.Browser(mdns.makeServiceType(this.name, this.type));
this.browser.on('serviceUp', function (service) {
// we know that node, don't re-announce it
if (services[getUniqueName(service)]) {
return;
}
// this is our representation of a node, it contains the host, ips, port and metadata of a service
var node = new ServiceNode(normalizeHost(service.host), service.port, service.addresses, service.txtRecord);
services[getUniqueName(service)] = node;
that.emit('up', node);
});
this.browser.on('serviceDown', function (service) {
// retrieve the service object
var node = services[getUniqueName(service)];
// we never saw that node go up, don't emit a down
if (!node) {
return;
}
that.emit('down', node);
// remove the data we knew about it
delete services[getUniqueName(service)];
});
this.browser.on('error', function (error, service) {
that.emit('error', error, service);
});
}
|
[
"function",
"MDNSService",
"(",
"name",
",",
"type",
",",
"options",
")",
"{",
"var",
"that",
"=",
"this",
";",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"type",
"=",
"type",
";",
"this",
".",
"options",
"=",
"options",
";",
"this",
".",
"advertisement",
"=",
"null",
";",
"this",
".",
"browser",
"=",
"new",
"mdns",
".",
"Browser",
"(",
"mdns",
".",
"makeServiceType",
"(",
"this",
".",
"name",
",",
"this",
".",
"type",
")",
")",
";",
"this",
".",
"browser",
".",
"on",
"(",
"'serviceUp'",
",",
"function",
"(",
"service",
")",
"{",
"// we know that node, don't re-announce it",
"if",
"(",
"services",
"[",
"getUniqueName",
"(",
"service",
")",
"]",
")",
"{",
"return",
";",
"}",
"// this is our representation of a node, it contains the host, ips, port and metadata of a service",
"var",
"node",
"=",
"new",
"ServiceNode",
"(",
"normalizeHost",
"(",
"service",
".",
"host",
")",
",",
"service",
".",
"port",
",",
"service",
".",
"addresses",
",",
"service",
".",
"txtRecord",
")",
";",
"services",
"[",
"getUniqueName",
"(",
"service",
")",
"]",
"=",
"node",
";",
"that",
".",
"emit",
"(",
"'up'",
",",
"node",
")",
";",
"}",
")",
";",
"this",
".",
"browser",
".",
"on",
"(",
"'serviceDown'",
",",
"function",
"(",
"service",
")",
"{",
"// retrieve the service object",
"var",
"node",
"=",
"services",
"[",
"getUniqueName",
"(",
"service",
")",
"]",
";",
"// we never saw that node go up, don't emit a down",
"if",
"(",
"!",
"node",
")",
"{",
"return",
";",
"}",
"that",
".",
"emit",
"(",
"'down'",
",",
"node",
")",
";",
"// remove the data we knew about it",
"delete",
"services",
"[",
"getUniqueName",
"(",
"service",
")",
"]",
";",
"}",
")",
";",
"this",
".",
"browser",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"error",
",",
"service",
")",
"{",
"that",
".",
"emit",
"(",
"'error'",
",",
"error",
",",
"service",
")",
";",
"}",
")",
";",
"}"
] |
This is our service object, it starts a browser object so that if can forward up and down events
when nodes appear on the network.
@param {string} name The name of the service
@param {string} type The protocol used (eg: tcp)
@param {Object} options Options
@param {string} options.description Used to override the service name generated by the engine.
It needs to be unique on the network!
@constructor
|
[
"This",
"is",
"our",
"service",
"object",
"it",
"starts",
"a",
"browser",
"object",
"so",
"that",
"if",
"can",
"forward",
"up",
"and",
"down",
"events",
"when",
"nodes",
"appear",
"on",
"the",
"network",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/serviceDiscovery/engines/mdns/index.js#L56-L97
|
19,505
|
mage/mage
|
lib/archivist/vaults/redis/index.js
|
RedisVault
|
function RedisVault(name, logger) {
// required exposed properties
this.name = name; // the unique vault name
this.archive = new Archive(this); // archivist bindings
this.client = null; // node-redis instance
this.logger = logger;
}
|
javascript
|
function RedisVault(name, logger) {
// required exposed properties
this.name = name; // the unique vault name
this.archive = new Archive(this); // archivist bindings
this.client = null; // node-redis instance
this.logger = logger;
}
|
[
"function",
"RedisVault",
"(",
"name",
",",
"logger",
")",
"{",
"// required exposed properties",
"this",
".",
"name",
"=",
"name",
";",
"// the unique vault name",
"this",
".",
"archive",
"=",
"new",
"Archive",
"(",
"this",
")",
";",
"// archivist bindings",
"this",
".",
"client",
"=",
"null",
";",
"// node-redis instance",
"this",
".",
"logger",
"=",
"logger",
";",
"}"
] |
Vault wrapper around node-redis
|
[
"Vault",
"wrapper",
"around",
"node",
"-",
"redis"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/vaults/redis/index.js#L19-L27
|
19,506
|
mage/mage
|
docs-sources/javascripts/app/_lang.js
|
getLanguageFromQueryString
|
function getLanguageFromQueryString() {
if (location.search.length >= 1) {
var language = parseURL(location.search).language
if (language) {
return language;
} else if (jQuery.inArray(location.search.substr(1), languages) != -1) {
return location.search.substr(1);
}
}
return false;
}
|
javascript
|
function getLanguageFromQueryString() {
if (location.search.length >= 1) {
var language = parseURL(location.search).language
if (language) {
return language;
} else if (jQuery.inArray(location.search.substr(1), languages) != -1) {
return location.search.substr(1);
}
}
return false;
}
|
[
"function",
"getLanguageFromQueryString",
"(",
")",
"{",
"if",
"(",
"location",
".",
"search",
".",
"length",
">=",
"1",
")",
"{",
"var",
"language",
"=",
"parseURL",
"(",
"location",
".",
"search",
")",
".",
"language",
"if",
"(",
"language",
")",
"{",
"return",
"language",
";",
"}",
"else",
"if",
"(",
"jQuery",
".",
"inArray",
"(",
"location",
".",
"search",
".",
"substr",
"(",
"1",
")",
",",
"languages",
")",
"!=",
"-",
"1",
")",
"{",
"return",
"location",
".",
"search",
".",
"substr",
"(",
"1",
")",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
gets the language set in the query string
|
[
"gets",
"the",
"language",
"set",
"in",
"the",
"query",
"string"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/docs-sources/javascripts/app/_lang.js#L98-L109
|
19,507
|
mage/mage
|
docs-sources/javascripts/app/_lang.js
|
generateNewQueryString
|
function generateNewQueryString(language) {
var url = parseURL(location.search);
if (url.language) {
url.language = language;
return stringifyURL(url);
}
return language;
}
|
javascript
|
function generateNewQueryString(language) {
var url = parseURL(location.search);
if (url.language) {
url.language = language;
return stringifyURL(url);
}
return language;
}
|
[
"function",
"generateNewQueryString",
"(",
"language",
")",
"{",
"var",
"url",
"=",
"parseURL",
"(",
"location",
".",
"search",
")",
";",
"if",
"(",
"url",
".",
"language",
")",
"{",
"url",
".",
"language",
"=",
"language",
";",
"return",
"stringifyURL",
"(",
"url",
")",
";",
"}",
"return",
"language",
";",
"}"
] |
returns a new query string with the new language in it
|
[
"returns",
"a",
"new",
"query",
"string",
"with",
"the",
"new",
"language",
"in",
"it"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/docs-sources/javascripts/app/_lang.js#L112-L119
|
19,508
|
mage/mage
|
docs-sources/javascripts/app/_lang.js
|
pushURL
|
function pushURL(language) {
if (!history) { return; }
var hash = window.location.hash;
if (hash) {
hash = hash.replace(/^#+/, '');
}
history.pushState({}, '', '?' + generateNewQueryString(language) + '#' + hash);
// save language as next default
localStorage.setItem("language", language);
}
|
javascript
|
function pushURL(language) {
if (!history) { return; }
var hash = window.location.hash;
if (hash) {
hash = hash.replace(/^#+/, '');
}
history.pushState({}, '', '?' + generateNewQueryString(language) + '#' + hash);
// save language as next default
localStorage.setItem("language", language);
}
|
[
"function",
"pushURL",
"(",
"language",
")",
"{",
"if",
"(",
"!",
"history",
")",
"{",
"return",
";",
"}",
"var",
"hash",
"=",
"window",
".",
"location",
".",
"hash",
";",
"if",
"(",
"hash",
")",
"{",
"hash",
"=",
"hash",
".",
"replace",
"(",
"/",
"^#+",
"/",
",",
"''",
")",
";",
"}",
"history",
".",
"pushState",
"(",
"{",
"}",
",",
"''",
",",
"'?'",
"+",
"generateNewQueryString",
"(",
"language",
")",
"+",
"'#'",
"+",
"hash",
")",
";",
"// save language as next default",
"localStorage",
".",
"setItem",
"(",
"\"language\"",
",",
"language",
")",
";",
"}"
] |
if a button is clicked, add the state to the history
|
[
"if",
"a",
"button",
"is",
"clicked",
"add",
"the",
"state",
"to",
"the",
"history"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/docs-sources/javascripts/app/_lang.js#L122-L132
|
19,509
|
mage/mage
|
lib/httpServer/transports/http/index.js
|
bindToFile
|
function bindToFile(filePath, cb) {
// resolve the path and shorten it to avoid long-path bind errors
// NOTE: only do so on non-windows systems
if (process.platform !== 'win32') {
filePath = pathRelative(process.cwd(), pathResolve(filePath));
}
function callback(error) {
server.removeListener('error', callback);
if (error) {
if (error.code === 'EADDRINUSE') {
error.message =
filePath + ' already exists. Perhaps the server did not shut down ' +
'cleanly. Try removing the file and starting again. (' + error.code + ')';
} else {
error.message = 'Error while binding to ' + filePath + ' (' + error.code + ')';
}
return cb(error);
}
logger.notice('HTTP Server bound to', filePath);
return cb();
}
// listen() can throw, despite the error listener
// this happens in cluster mode if the stdio channels have been closed by the master
server.on('error', callback);
try {
server.listen(filePath, function (error) {
if (error) {
return callback(error);
}
fs.chmod(filePath, parseInt('777', 8), callback);
});
} catch (error) {
// listen() can throw, despite the error listener
// this happens in cluster mode if the stdio channels have been closed by the master
setImmediate(function () {
callback(error);
});
}
}
|
javascript
|
function bindToFile(filePath, cb) {
// resolve the path and shorten it to avoid long-path bind errors
// NOTE: only do so on non-windows systems
if (process.platform !== 'win32') {
filePath = pathRelative(process.cwd(), pathResolve(filePath));
}
function callback(error) {
server.removeListener('error', callback);
if (error) {
if (error.code === 'EADDRINUSE') {
error.message =
filePath + ' already exists. Perhaps the server did not shut down ' +
'cleanly. Try removing the file and starting again. (' + error.code + ')';
} else {
error.message = 'Error while binding to ' + filePath + ' (' + error.code + ')';
}
return cb(error);
}
logger.notice('HTTP Server bound to', filePath);
return cb();
}
// listen() can throw, despite the error listener
// this happens in cluster mode if the stdio channels have been closed by the master
server.on('error', callback);
try {
server.listen(filePath, function (error) {
if (error) {
return callback(error);
}
fs.chmod(filePath, parseInt('777', 8), callback);
});
} catch (error) {
// listen() can throw, despite the error listener
// this happens in cluster mode if the stdio channels have been closed by the master
setImmediate(function () {
callback(error);
});
}
}
|
[
"function",
"bindToFile",
"(",
"filePath",
",",
"cb",
")",
"{",
"// resolve the path and shorten it to avoid long-path bind errors",
"// NOTE: only do so on non-windows systems",
"if",
"(",
"process",
".",
"platform",
"!==",
"'win32'",
")",
"{",
"filePath",
"=",
"pathRelative",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"pathResolve",
"(",
"filePath",
")",
")",
";",
"}",
"function",
"callback",
"(",
"error",
")",
"{",
"server",
".",
"removeListener",
"(",
"'error'",
",",
"callback",
")",
";",
"if",
"(",
"error",
")",
"{",
"if",
"(",
"error",
".",
"code",
"===",
"'EADDRINUSE'",
")",
"{",
"error",
".",
"message",
"=",
"filePath",
"+",
"' already exists. Perhaps the server did not shut down '",
"+",
"'cleanly. Try removing the file and starting again. ('",
"+",
"error",
".",
"code",
"+",
"')'",
";",
"}",
"else",
"{",
"error",
".",
"message",
"=",
"'Error while binding to '",
"+",
"filePath",
"+",
"' ('",
"+",
"error",
".",
"code",
"+",
"')'",
";",
"}",
"return",
"cb",
"(",
"error",
")",
";",
"}",
"logger",
".",
"notice",
"(",
"'HTTP Server bound to'",
",",
"filePath",
")",
";",
"return",
"cb",
"(",
")",
";",
"}",
"// listen() can throw, despite the error listener",
"// this happens in cluster mode if the stdio channels have been closed by the master",
"server",
".",
"on",
"(",
"'error'",
",",
"callback",
")",
";",
"try",
"{",
"server",
".",
"listen",
"(",
"filePath",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"callback",
"(",
"error",
")",
";",
"}",
"fs",
".",
"chmod",
"(",
"filePath",
",",
"parseInt",
"(",
"'777'",
",",
"8",
")",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"// listen() can throw, despite the error listener",
"// this happens in cluster mode if the stdio channels have been closed by the master",
"setImmediate",
"(",
"function",
"(",
")",
"{",
"callback",
"(",
"error",
")",
";",
"}",
")",
";",
"}",
"}"
] |
functions for listening on port or socket file
|
[
"functions",
"for",
"listening",
"on",
"port",
"or",
"socket",
"file"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/httpServer/transports/http/index.js#L802-L851
|
19,510
|
mage/mage
|
lib/modules/auth/index.js
|
makePasswordHash
|
function makePasswordHash(password, cb) {
try {
const hash = hashes.create(exports.getHashConfiguration());
hash.fill(password, function (error) {
cb(error, hash);
});
} catch (error) {
return cb(error);
}
}
|
javascript
|
function makePasswordHash(password, cb) {
try {
const hash = hashes.create(exports.getHashConfiguration());
hash.fill(password, function (error) {
cb(error, hash);
});
} catch (error) {
return cb(error);
}
}
|
[
"function",
"makePasswordHash",
"(",
"password",
",",
"cb",
")",
"{",
"try",
"{",
"const",
"hash",
"=",
"hashes",
".",
"create",
"(",
"exports",
".",
"getHashConfiguration",
"(",
")",
")",
";",
"hash",
".",
"fill",
"(",
"password",
",",
"function",
"(",
"error",
")",
"{",
"cb",
"(",
"error",
",",
"hash",
")",
";",
"}",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"cb",
"(",
"error",
")",
";",
"}",
"}"
] |
Generates a hashed password.
@param {string} password Password to hash
@param {Function} cb Receives (error, hashedPassword)
|
[
"Generates",
"a",
"hashed",
"password",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/modules/auth/index.js#L255-L264
|
19,511
|
mage/mage
|
lib/serviceDiscovery/helpers.js
|
pushIps
|
function pushIps(addresses, announced, useInternalAddresses) {
if (!useInternalAddresses) {
addresses = addresses.filter((address) => address.internal === false);
}
addresses = addresses
.filter((address) => address.family === 'IPv4')
.map((address) => address.address);
return announced.concat(addresses);
}
|
javascript
|
function pushIps(addresses, announced, useInternalAddresses) {
if (!useInternalAddresses) {
addresses = addresses.filter((address) => address.internal === false);
}
addresses = addresses
.filter((address) => address.family === 'IPv4')
.map((address) => address.address);
return announced.concat(addresses);
}
|
[
"function",
"pushIps",
"(",
"addresses",
",",
"announced",
",",
"useInternalAddresses",
")",
"{",
"if",
"(",
"!",
"useInternalAddresses",
")",
"{",
"addresses",
"=",
"addresses",
".",
"filter",
"(",
"(",
"address",
")",
"=>",
"address",
".",
"internal",
"===",
"false",
")",
";",
"}",
"addresses",
"=",
"addresses",
".",
"filter",
"(",
"(",
"address",
")",
"=>",
"address",
".",
"family",
"===",
"'IPv4'",
")",
".",
"map",
"(",
"(",
"address",
")",
"=>",
"address",
".",
"address",
")",
";",
"return",
"announced",
".",
"concat",
"(",
"addresses",
")",
";",
"}"
] |
Add all valid IP to an existing list of IP
@param {*} addresses
@param {*} announced
@param {*} useInternalAddresses
|
[
"Add",
"all",
"valid",
"IP",
"to",
"an",
"existing",
"list",
"of",
"IP"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/serviceDiscovery/helpers.js#L29-L39
|
19,512
|
mage/mage
|
lib/serviceDiscovery/helpers.js
|
getAnnouncedIpsForInterface
|
function getAnnouncedIpsForInterface(ifaceName) {
const addresses = interfaces[ifaceName];
if (!addresses) {
throw new Error('Interface ' + ifaceName + ' could not be found');
}
const announced = pushIps(addresses, [], true);
assertNotEmpty(announced, 'Interface ' + ifaceName + ' does not define any IP addresses');
return announced;
}
|
javascript
|
function getAnnouncedIpsForInterface(ifaceName) {
const addresses = interfaces[ifaceName];
if (!addresses) {
throw new Error('Interface ' + ifaceName + ' could not be found');
}
const announced = pushIps(addresses, [], true);
assertNotEmpty(announced, 'Interface ' + ifaceName + ' does not define any IP addresses');
return announced;
}
|
[
"function",
"getAnnouncedIpsForInterface",
"(",
"ifaceName",
")",
"{",
"const",
"addresses",
"=",
"interfaces",
"[",
"ifaceName",
"]",
";",
"if",
"(",
"!",
"addresses",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Interface '",
"+",
"ifaceName",
"+",
"' could not be found'",
")",
";",
"}",
"const",
"announced",
"=",
"pushIps",
"(",
"addresses",
",",
"[",
"]",
",",
"true",
")",
";",
"assertNotEmpty",
"(",
"announced",
",",
"'Interface '",
"+",
"ifaceName",
"+",
"' does not define any IP addresses'",
")",
";",
"return",
"announced",
";",
"}"
] |
Return all valid IP for a single interface
@param {*} ifaceName
|
[
"Return",
"all",
"valid",
"IP",
"for",
"a",
"single",
"interface"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/serviceDiscovery/helpers.js#L46-L57
|
19,513
|
mage/mage
|
lib/archivist/vaults/file/Archive.js
|
sortIndexes
|
function sortIndexes(indexes, sort) {
function compare(a, b) {
return a > b ? -1 : (b > a ? 1 : 0);
}
// format: [{ name: 'colName', direction: 'asc' }, { name: 'colName2', direction: 'desc' }]
// direction is 'asc' by default
indexes.sort(function (a, b) {
var result = 0;
for (var i = 0; i < sort.length && result === 0; i++) {
var prop = sort[i].name;
var factor = sort[i].direction === 'desc' ? -1 : 1;
result = factor * compare(a[prop], b[prop]);
}
return result;
});
}
|
javascript
|
function sortIndexes(indexes, sort) {
function compare(a, b) {
return a > b ? -1 : (b > a ? 1 : 0);
}
// format: [{ name: 'colName', direction: 'asc' }, { name: 'colName2', direction: 'desc' }]
// direction is 'asc' by default
indexes.sort(function (a, b) {
var result = 0;
for (var i = 0; i < sort.length && result === 0; i++) {
var prop = sort[i].name;
var factor = sort[i].direction === 'desc' ? -1 : 1;
result = factor * compare(a[prop], b[prop]);
}
return result;
});
}
|
[
"function",
"sortIndexes",
"(",
"indexes",
",",
"sort",
")",
"{",
"function",
"compare",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
">",
"b",
"?",
"-",
"1",
":",
"(",
"b",
">",
"a",
"?",
"1",
":",
"0",
")",
";",
"}",
"// format: [{ name: 'colName', direction: 'asc' }, { name: 'colName2', direction: 'desc' }]",
"// direction is 'asc' by default",
"indexes",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"var",
"result",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"sort",
".",
"length",
"&&",
"result",
"===",
"0",
";",
"i",
"++",
")",
"{",
"var",
"prop",
"=",
"sort",
"[",
"i",
"]",
".",
"name",
";",
"var",
"factor",
"=",
"sort",
"[",
"i",
"]",
".",
"direction",
"===",
"'desc'",
"?",
"-",
"1",
":",
"1",
";",
"result",
"=",
"factor",
"*",
"compare",
"(",
"a",
"[",
"prop",
"]",
",",
"b",
"[",
"prop",
"]",
")",
";",
"}",
"return",
"result",
";",
"}",
")",
";",
"}"
] |
Archivist bindings for the FileVault API
|
[
"Archivist",
"bindings",
"for",
"the",
"FileVault",
"API"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/vaults/file/Archive.js#L4-L24
|
19,514
|
mage/mage
|
lib/tasks/show-versions.js
|
objMerge
|
function objMerge(a, b) {
var obj = {};
Object.keys(a).forEach(function (key) {
obj[key] = a[key];
});
Object.keys(b).forEach(function (key) {
obj[key] = b[key];
});
return obj;
}
|
javascript
|
function objMerge(a, b) {
var obj = {};
Object.keys(a).forEach(function (key) {
obj[key] = a[key];
});
Object.keys(b).forEach(function (key) {
obj[key] = b[key];
});
return obj;
}
|
[
"function",
"objMerge",
"(",
"a",
",",
"b",
")",
"{",
"var",
"obj",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"a",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"obj",
"[",
"key",
"]",
"=",
"a",
"[",
"key",
"]",
";",
"}",
")",
";",
"Object",
".",
"keys",
"(",
"b",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"obj",
"[",
"key",
"]",
"=",
"b",
"[",
"key",
"]",
";",
"}",
")",
";",
"return",
"obj",
";",
"}"
] |
Merges a and b into a new object and returns it. In the case of conflict, b wins.
@param {Object} a
@param {Object} b
@returns {Object}
|
[
"Merges",
"a",
"and",
"b",
"into",
"a",
"new",
"object",
"and",
"returns",
"it",
".",
"In",
"the",
"case",
"of",
"conflict",
"b",
"wins",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/tasks/show-versions.js#L12-L24
|
19,515
|
mage/mage
|
lib/daemon/index.js
|
lockAndLoad
|
function lockAndLoad() {
// lock command execution
if (!setFilePid(CMD_LOCK_FILE)) {
err(chalk.red.bold('A command is already running, aborting...'));
process.exit(EXIT_LOCKED);
// abort the normal code flow
return interrupt();
}
process.once('exit', function () {
// using "exit" ensures that it gets removed, even if there was an exception
destroyFilePid(CMD_LOCK_FILE);
});
return loadAppStatus();
}
|
javascript
|
function lockAndLoad() {
// lock command execution
if (!setFilePid(CMD_LOCK_FILE)) {
err(chalk.red.bold('A command is already running, aborting...'));
process.exit(EXIT_LOCKED);
// abort the normal code flow
return interrupt();
}
process.once('exit', function () {
// using "exit" ensures that it gets removed, even if there was an exception
destroyFilePid(CMD_LOCK_FILE);
});
return loadAppStatus();
}
|
[
"function",
"lockAndLoad",
"(",
")",
"{",
"// lock command execution",
"if",
"(",
"!",
"setFilePid",
"(",
"CMD_LOCK_FILE",
")",
")",
"{",
"err",
"(",
"chalk",
".",
"red",
".",
"bold",
"(",
"'A command is already running, aborting...'",
")",
")",
";",
"process",
".",
"exit",
"(",
"EXIT_LOCKED",
")",
";",
"// abort the normal code flow",
"return",
"interrupt",
"(",
")",
";",
"}",
"process",
".",
"once",
"(",
"'exit'",
",",
"function",
"(",
")",
"{",
"// using \"exit\" ensures that it gets removed, even if there was an exception",
"destroyFilePid",
"(",
"CMD_LOCK_FILE",
")",
";",
"}",
")",
";",
"return",
"loadAppStatus",
"(",
")",
";",
"}"
] |
The user is trying to run a daemonizer command. Lock daemon command execution for the duration of the process, and return the app's current state from APP_LOCK_FILE.
|
[
"The",
"user",
"is",
"trying",
"to",
"run",
"a",
"daemonizer",
"command",
".",
"Lock",
"daemon",
"command",
"execution",
"for",
"the",
"duration",
"of",
"the",
"process",
"and",
"return",
"the",
"app",
"s",
"current",
"state",
"from",
"APP_LOCK_FILE",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/daemon/index.js#L376-L396
|
19,516
|
mage/mage
|
lib/msgServer/index.js
|
assertMsgServerIsEnabled
|
function assertMsgServerIsEnabled() {
assert(cfgMmrp.bind, 'No MMRP bindings configured');
assert(cfgMsgStream, 'The message stream has been disabled.');
assert(cfgMsgStream.transports, 'The message stream has no configured transports.');
assert(serviceDiscovery.isEnabled(), 'Service discovery has not been configured');
}
|
javascript
|
function assertMsgServerIsEnabled() {
assert(cfgMmrp.bind, 'No MMRP bindings configured');
assert(cfgMsgStream, 'The message stream has been disabled.');
assert(cfgMsgStream.transports, 'The message stream has no configured transports.');
assert(serviceDiscovery.isEnabled(), 'Service discovery has not been configured');
}
|
[
"function",
"assertMsgServerIsEnabled",
"(",
")",
"{",
"assert",
"(",
"cfgMmrp",
".",
"bind",
",",
"'No MMRP bindings configured'",
")",
";",
"assert",
"(",
"cfgMsgStream",
",",
"'The message stream has been disabled.'",
")",
";",
"assert",
"(",
"cfgMsgStream",
".",
"transports",
",",
"'The message stream has no configured transports.'",
")",
";",
"assert",
"(",
"serviceDiscovery",
".",
"isEnabled",
"(",
")",
",",
"'Service discovery has not been configured'",
")",
";",
"}"
] |
Throws an error if the message server is not enabled due to missing configuration
|
[
"Throws",
"an",
"error",
"if",
"the",
"message",
"server",
"is",
"not",
"enabled",
"due",
"to",
"missing",
"configuration"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/msgServer/index.js#L49-L54
|
19,517
|
mage/mage
|
lib/config/config.js
|
lintJson
|
function lintJson(content) {
try {
jsonlint.parse(content);
} catch (lintError) {
if (typeof lintError.message === 'string') {
lintError.message = lintError.message.replace(/\t/g, ' ');
}
throw lintError;
}
}
|
javascript
|
function lintJson(content) {
try {
jsonlint.parse(content);
} catch (lintError) {
if (typeof lintError.message === 'string') {
lintError.message = lintError.message.replace(/\t/g, ' ');
}
throw lintError;
}
}
|
[
"function",
"lintJson",
"(",
"content",
")",
"{",
"try",
"{",
"jsonlint",
".",
"parse",
"(",
"content",
")",
";",
"}",
"catch",
"(",
"lintError",
")",
"{",
"if",
"(",
"typeof",
"lintError",
".",
"message",
"===",
"'string'",
")",
"{",
"lintError",
".",
"message",
"=",
"lintError",
".",
"message",
".",
"replace",
"(",
"/",
"\\t",
"/",
"g",
",",
"' '",
")",
";",
"}",
"throw",
"lintError",
";",
"}",
"}"
] |
Lint a JSON file, and throw if an error is found
@param {*} configPath
|
[
"Lint",
"a",
"JSON",
"file",
"and",
"throw",
"if",
"an",
"error",
"is",
"found"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/config/config.js#L51-L61
|
19,518
|
mage/mage
|
lib/config/config.js
|
loadConfigFile
|
function loadConfigFile(configPath) {
logger.debug('Loading configuration file at:', configPath);
function loadConfig() {
return fs.readFileSync(configPath, { encoding: 'utf8' });
}
function parseConfig(content, extension) {
switch (extension) {
case '.js':
return require(configPath);
case '.yaml':
return jsYaml.safeLoad(content, { filename: configPath });
case '.json':
try {
return JSON.parse(content);
} catch (error) {
// Try to provide more specific syntax errors
lintJson(content);
// If no syntax errors are found, throw a generic error
throw new Error('There was a problem loading a configuration file: ' + configPath);
}
case '.json5':
return JSON5.parse(content);
default:
throw new Error(`Configuration file is an unsupported type [${supportedTypes.join(', ')}]: ` + configPath);
}
}
var extension = path.extname(configPath);
var content;
try {
content = loadConfig();
} catch (error) {
throw new ConfigurationError('Failed to read configuration file', configPath, error);
}
try {
return parseConfig(content, extension);
} catch (error) {
throw new ConfigurationError('Failed to parse configuration file', configPath, error);
}
}
|
javascript
|
function loadConfigFile(configPath) {
logger.debug('Loading configuration file at:', configPath);
function loadConfig() {
return fs.readFileSync(configPath, { encoding: 'utf8' });
}
function parseConfig(content, extension) {
switch (extension) {
case '.js':
return require(configPath);
case '.yaml':
return jsYaml.safeLoad(content, { filename: configPath });
case '.json':
try {
return JSON.parse(content);
} catch (error) {
// Try to provide more specific syntax errors
lintJson(content);
// If no syntax errors are found, throw a generic error
throw new Error('There was a problem loading a configuration file: ' + configPath);
}
case '.json5':
return JSON5.parse(content);
default:
throw new Error(`Configuration file is an unsupported type [${supportedTypes.join(', ')}]: ` + configPath);
}
}
var extension = path.extname(configPath);
var content;
try {
content = loadConfig();
} catch (error) {
throw new ConfigurationError('Failed to read configuration file', configPath, error);
}
try {
return parseConfig(content, extension);
} catch (error) {
throw new ConfigurationError('Failed to parse configuration file', configPath, error);
}
}
|
[
"function",
"loadConfigFile",
"(",
"configPath",
")",
"{",
"logger",
".",
"debug",
"(",
"'Loading configuration file at:'",
",",
"configPath",
")",
";",
"function",
"loadConfig",
"(",
")",
"{",
"return",
"fs",
".",
"readFileSync",
"(",
"configPath",
",",
"{",
"encoding",
":",
"'utf8'",
"}",
")",
";",
"}",
"function",
"parseConfig",
"(",
"content",
",",
"extension",
")",
"{",
"switch",
"(",
"extension",
")",
"{",
"case",
"'.js'",
":",
"return",
"require",
"(",
"configPath",
")",
";",
"case",
"'.yaml'",
":",
"return",
"jsYaml",
".",
"safeLoad",
"(",
"content",
",",
"{",
"filename",
":",
"configPath",
"}",
")",
";",
"case",
"'.json'",
":",
"try",
"{",
"return",
"JSON",
".",
"parse",
"(",
"content",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"// Try to provide more specific syntax errors",
"lintJson",
"(",
"content",
")",
";",
"// If no syntax errors are found, throw a generic error",
"throw",
"new",
"Error",
"(",
"'There was a problem loading a configuration file: '",
"+",
"configPath",
")",
";",
"}",
"case",
"'.json5'",
":",
"return",
"JSON5",
".",
"parse",
"(",
"content",
")",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"`",
"${",
"supportedTypes",
".",
"join",
"(",
"', '",
")",
"}",
"`",
"+",
"configPath",
")",
";",
"}",
"}",
"var",
"extension",
"=",
"path",
".",
"extname",
"(",
"configPath",
")",
";",
"var",
"content",
";",
"try",
"{",
"content",
"=",
"loadConfig",
"(",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"throw",
"new",
"ConfigurationError",
"(",
"'Failed to read configuration file'",
",",
"configPath",
",",
"error",
")",
";",
"}",
"try",
"{",
"return",
"parseConfig",
"(",
"content",
",",
"extension",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"throw",
"new",
"ConfigurationError",
"(",
"'Failed to parse configuration file'",
",",
"configPath",
",",
"error",
")",
";",
"}",
"}"
] |
Attempt to load a config file, and provide some helpful output if the file cannot be parsed.
@param {String} configPath A filesystem path to the configuration file.
@return {Object} The loaded configuration object.
|
[
"Attempt",
"to",
"load",
"a",
"config",
"file",
"and",
"provide",
"some",
"helpful",
"output",
"if",
"the",
"file",
"cannot",
"be",
"parsed",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/config/config.js#L70-L118
|
19,519
|
mage/mage
|
lib/config/config.js
|
loadConfig
|
function loadConfig(dir, name, warn, defaultEmpty, isEnvironment) {
var extensionlessSource = path.join(dir, name);
var rawSource;
var rawConfig;
for (var i = 0; i < supportedTypes.length && !rawConfig; i++) {
rawSource = extensionlessSource + supportedTypes[i];
if (fs.existsSync(rawSource)) {
rawConfig = loadConfigFile(rawSource);
}
}
if (!rawConfig) {
if (warn) {
logger.info(
'No configuration content of name "' + name + '" was loaded from directory:',
configDir
);
}
if (!defaultEmpty) {
return;
}
rawSource = module.filename;
rawConfig = {};
}
if (rawConfig && isEnvironment) {
rawConfig = loadEnvironment(rawConfig);
}
return { source: rawSource, config: rawConfig };
}
|
javascript
|
function loadConfig(dir, name, warn, defaultEmpty, isEnvironment) {
var extensionlessSource = path.join(dir, name);
var rawSource;
var rawConfig;
for (var i = 0; i < supportedTypes.length && !rawConfig; i++) {
rawSource = extensionlessSource + supportedTypes[i];
if (fs.existsSync(rawSource)) {
rawConfig = loadConfigFile(rawSource);
}
}
if (!rawConfig) {
if (warn) {
logger.info(
'No configuration content of name "' + name + '" was loaded from directory:',
configDir
);
}
if (!defaultEmpty) {
return;
}
rawSource = module.filename;
rawConfig = {};
}
if (rawConfig && isEnvironment) {
rawConfig = loadEnvironment(rawConfig);
}
return { source: rawSource, config: rawConfig };
}
|
[
"function",
"loadConfig",
"(",
"dir",
",",
"name",
",",
"warn",
",",
"defaultEmpty",
",",
"isEnvironment",
")",
"{",
"var",
"extensionlessSource",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"name",
")",
";",
"var",
"rawSource",
";",
"var",
"rawConfig",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"supportedTypes",
".",
"length",
"&&",
"!",
"rawConfig",
";",
"i",
"++",
")",
"{",
"rawSource",
"=",
"extensionlessSource",
"+",
"supportedTypes",
"[",
"i",
"]",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"rawSource",
")",
")",
"{",
"rawConfig",
"=",
"loadConfigFile",
"(",
"rawSource",
")",
";",
"}",
"}",
"if",
"(",
"!",
"rawConfig",
")",
"{",
"if",
"(",
"warn",
")",
"{",
"logger",
".",
"info",
"(",
"'No configuration content of name \"'",
"+",
"name",
"+",
"'\" was loaded from directory:'",
",",
"configDir",
")",
";",
"}",
"if",
"(",
"!",
"defaultEmpty",
")",
"{",
"return",
";",
"}",
"rawSource",
"=",
"module",
".",
"filename",
";",
"rawConfig",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"rawConfig",
"&&",
"isEnvironment",
")",
"{",
"rawConfig",
"=",
"loadEnvironment",
"(",
"rawConfig",
")",
";",
"}",
"return",
"{",
"source",
":",
"rawSource",
",",
"config",
":",
"rawConfig",
"}",
";",
"}"
] |
Given a file name without extension, attempt to load the file. The files are assumed to be in a
folder called 'config' that lives in the same directory that you booted your game in.
@param {String} dir An absolute path to the directory containing the config file.
@param {String} name The file name (without extension).
@param {Boolean} warn Warn if configuration file was not found.
@param {Boolean} defaultEmpty Set to true to return undefined rather than a fresh empty config.
@param {Boolean} isEnvironment Set to true if the file describe environment variables
@return {Object} Contains "source" (the complete file path) and "config" keys.
|
[
"Given",
"a",
"file",
"name",
"without",
"extension",
"attempt",
"to",
"load",
"the",
"file",
".",
"The",
"files",
"are",
"assumed",
"to",
"be",
"in",
"a",
"folder",
"called",
"config",
"that",
"lives",
"in",
"the",
"same",
"directory",
"that",
"you",
"booted",
"your",
"game",
"in",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/config/config.js#L190-L224
|
19,520
|
mage/mage
|
lib/msgServer/mmrp/index.js
|
MmrpNode
|
function MmrpNode(role, cfg) {
EventEmitter.call(this);
this.isRelay = (role === 'relay' || role === 'both');
this.isClient = (role === 'client' || role === 'both');
assert(this.isRelay || this.isClient, 'MmrpNode must be relay, client or both');
// keeping track of who we're connected to
this.relays = {}; // my peers, master-relay or both { identity: RelayConnection }
this.clients = {}; // my clients { identity: ClientConnection }
// router
this.routerPort = null;
this.router = null;
if (this.isRelay) {
this.router = createRouter(cfg);
var routerUri = this.router.getsockopt(zmq.ZMQ_LAST_ENDPOINT);
if (routerUri) {
this.routerPort = parseInt(routerUri.substr(routerUri.lastIndexOf(':') + 1), 10);
// Share MMRP master port through the environment
process.env[ENV_MAGE_MMRP_MASTER_PORT] = this.routerPort;
// Generate the cluster ID based on the port the master listens on
this.clusterId = serviceDiscovery.helpers.generateId(this.routerPort);
// Set the identity of the router socket to the cluster ID
this.router.setsockopt(zmq.ZMQ_IDENTITY, new Buffer(this.clusterId));
}
} else {
// Retrieve the cluster ID from the environment
const masterPort = parseInt(process.env[ENV_MAGE_MMRP_MASTER_PORT], 10);
// Generate the cluster ID based on the port the master listens on
this.clusterId = serviceDiscovery.helpers.generateId(masterPort);
}
// dealer
this.identity = this.isRelay ? this.clusterId : createDealerIdentity(this.clusterId);
this.dealer = createDealer(this.identity);
assert.equal(this.identity, this.dealer.getsockopt(zmq.ZMQ_IDENTITY));
// mmrp socket event handling
this._setupSocketEventHandling();
// mmrp internal message handling
this.on('delivery.mmrp.handshake', this._handleHandshake);
}
|
javascript
|
function MmrpNode(role, cfg) {
EventEmitter.call(this);
this.isRelay = (role === 'relay' || role === 'both');
this.isClient = (role === 'client' || role === 'both');
assert(this.isRelay || this.isClient, 'MmrpNode must be relay, client or both');
// keeping track of who we're connected to
this.relays = {}; // my peers, master-relay or both { identity: RelayConnection }
this.clients = {}; // my clients { identity: ClientConnection }
// router
this.routerPort = null;
this.router = null;
if (this.isRelay) {
this.router = createRouter(cfg);
var routerUri = this.router.getsockopt(zmq.ZMQ_LAST_ENDPOINT);
if (routerUri) {
this.routerPort = parseInt(routerUri.substr(routerUri.lastIndexOf(':') + 1), 10);
// Share MMRP master port through the environment
process.env[ENV_MAGE_MMRP_MASTER_PORT] = this.routerPort;
// Generate the cluster ID based on the port the master listens on
this.clusterId = serviceDiscovery.helpers.generateId(this.routerPort);
// Set the identity of the router socket to the cluster ID
this.router.setsockopt(zmq.ZMQ_IDENTITY, new Buffer(this.clusterId));
}
} else {
// Retrieve the cluster ID from the environment
const masterPort = parseInt(process.env[ENV_MAGE_MMRP_MASTER_PORT], 10);
// Generate the cluster ID based on the port the master listens on
this.clusterId = serviceDiscovery.helpers.generateId(masterPort);
}
// dealer
this.identity = this.isRelay ? this.clusterId : createDealerIdentity(this.clusterId);
this.dealer = createDealer(this.identity);
assert.equal(this.identity, this.dealer.getsockopt(zmq.ZMQ_IDENTITY));
// mmrp socket event handling
this._setupSocketEventHandling();
// mmrp internal message handling
this.on('delivery.mmrp.handshake', this._handleHandshake);
}
|
[
"function",
"MmrpNode",
"(",
"role",
",",
"cfg",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"isRelay",
"=",
"(",
"role",
"===",
"'relay'",
"||",
"role",
"===",
"'both'",
")",
";",
"this",
".",
"isClient",
"=",
"(",
"role",
"===",
"'client'",
"||",
"role",
"===",
"'both'",
")",
";",
"assert",
"(",
"this",
".",
"isRelay",
"||",
"this",
".",
"isClient",
",",
"'MmrpNode must be relay, client or both'",
")",
";",
"// keeping track of who we're connected to",
"this",
".",
"relays",
"=",
"{",
"}",
";",
"// my peers, master-relay or both { identity: RelayConnection }",
"this",
".",
"clients",
"=",
"{",
"}",
";",
"// my clients { identity: ClientConnection }",
"// router",
"this",
".",
"routerPort",
"=",
"null",
";",
"this",
".",
"router",
"=",
"null",
";",
"if",
"(",
"this",
".",
"isRelay",
")",
"{",
"this",
".",
"router",
"=",
"createRouter",
"(",
"cfg",
")",
";",
"var",
"routerUri",
"=",
"this",
".",
"router",
".",
"getsockopt",
"(",
"zmq",
".",
"ZMQ_LAST_ENDPOINT",
")",
";",
"if",
"(",
"routerUri",
")",
"{",
"this",
".",
"routerPort",
"=",
"parseInt",
"(",
"routerUri",
".",
"substr",
"(",
"routerUri",
".",
"lastIndexOf",
"(",
"':'",
")",
"+",
"1",
")",
",",
"10",
")",
";",
"// Share MMRP master port through the environment",
"process",
".",
"env",
"[",
"ENV_MAGE_MMRP_MASTER_PORT",
"]",
"=",
"this",
".",
"routerPort",
";",
"// Generate the cluster ID based on the port the master listens on",
"this",
".",
"clusterId",
"=",
"serviceDiscovery",
".",
"helpers",
".",
"generateId",
"(",
"this",
".",
"routerPort",
")",
";",
"// Set the identity of the router socket to the cluster ID",
"this",
".",
"router",
".",
"setsockopt",
"(",
"zmq",
".",
"ZMQ_IDENTITY",
",",
"new",
"Buffer",
"(",
"this",
".",
"clusterId",
")",
")",
";",
"}",
"}",
"else",
"{",
"// Retrieve the cluster ID from the environment",
"const",
"masterPort",
"=",
"parseInt",
"(",
"process",
".",
"env",
"[",
"ENV_MAGE_MMRP_MASTER_PORT",
"]",
",",
"10",
")",
";",
"// Generate the cluster ID based on the port the master listens on",
"this",
".",
"clusterId",
"=",
"serviceDiscovery",
".",
"helpers",
".",
"generateId",
"(",
"masterPort",
")",
";",
"}",
"// dealer",
"this",
".",
"identity",
"=",
"this",
".",
"isRelay",
"?",
"this",
".",
"clusterId",
":",
"createDealerIdentity",
"(",
"this",
".",
"clusterId",
")",
";",
"this",
".",
"dealer",
"=",
"createDealer",
"(",
"this",
".",
"identity",
")",
";",
"assert",
".",
"equal",
"(",
"this",
".",
"identity",
",",
"this",
".",
"dealer",
".",
"getsockopt",
"(",
"zmq",
".",
"ZMQ_IDENTITY",
")",
")",
";",
"// mmrp socket event handling",
"this",
".",
"_setupSocketEventHandling",
"(",
")",
";",
"// mmrp internal message handling",
"this",
".",
"on",
"(",
"'delivery.mmrp.handshake'",
",",
"this",
".",
"_handleHandshake",
")",
";",
"}"
] |
Instantiates an MmrpNode that represents a client, relay or both in a bigger MMRP network.
@param {string} role
@param {Object} cfg
@param {string} clusterId
@constructor
|
[
"Instantiates",
"an",
"MmrpNode",
"that",
"represents",
"a",
"client",
"relay",
"or",
"both",
"in",
"a",
"bigger",
"MMRP",
"network",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/msgServer/mmrp/index.js#L80-L135
|
19,521
|
mage/mage
|
lib/sampler/sampler.js
|
exposePanopticonMethod
|
function exposePanopticonMethod(method) {
exports[method] = function () {
for (var i = 0; i < panoptica.length; i++) {
var panopticon = panoptica[i];
panopticon[method].apply(panopticon, arguments);
}
};
}
|
javascript
|
function exposePanopticonMethod(method) {
exports[method] = function () {
for (var i = 0; i < panoptica.length; i++) {
var panopticon = panoptica[i];
panopticon[method].apply(panopticon, arguments);
}
};
}
|
[
"function",
"exposePanopticonMethod",
"(",
"method",
")",
"{",
"exports",
"[",
"method",
"]",
"=",
"function",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"panoptica",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"panopticon",
"=",
"panoptica",
"[",
"i",
"]",
";",
"panopticon",
"[",
"method",
"]",
".",
"apply",
"(",
"panopticon",
",",
"arguments",
")",
";",
"}",
"}",
";",
"}"
] |
Expose a panopticon instance logger method on this module. This newly exposed method forwards
its arguments to the equivalent method of all panopticon instances.
@param {string} method The name of a panopticon instance logger method.
|
[
"Expose",
"a",
"panopticon",
"instance",
"logger",
"method",
"on",
"this",
"module",
".",
"This",
"newly",
"exposed",
"method",
"forwards",
"its",
"arguments",
"to",
"the",
"equivalent",
"method",
"of",
"all",
"panopticon",
"instances",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/sampler/sampler.js#L80-L88
|
19,522
|
mage/mage
|
lib/sampler/sampler.js
|
transformer
|
function transformer(data, id) {
function checkValue(obj) {
if (!obj || typeof obj !== 'object') {
return;
}
var keys = Object.keys(obj);
if (keys.indexOf('value') !== -1) {
obj.values = {};
obj.values[id] = obj.value;
delete obj.value;
return;
}
for (var i = 0; i < keys.length; i++) {
checkValue(obj[keys[i]]);
}
}
checkValue(data);
return data;
}
|
javascript
|
function transformer(data, id) {
function checkValue(obj) {
if (!obj || typeof obj !== 'object') {
return;
}
var keys = Object.keys(obj);
if (keys.indexOf('value') !== -1) {
obj.values = {};
obj.values[id] = obj.value;
delete obj.value;
return;
}
for (var i = 0; i < keys.length; i++) {
checkValue(obj[keys[i]]);
}
}
checkValue(data);
return data;
}
|
[
"function",
"transformer",
"(",
"data",
",",
"id",
")",
"{",
"function",
"checkValue",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"obj",
"||",
"typeof",
"obj",
"!==",
"'object'",
")",
"{",
"return",
";",
"}",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
";",
"if",
"(",
"keys",
".",
"indexOf",
"(",
"'value'",
")",
"!==",
"-",
"1",
")",
"{",
"obj",
".",
"values",
"=",
"{",
"}",
";",
"obj",
".",
"values",
"[",
"id",
"]",
"=",
"obj",
".",
"value",
";",
"delete",
"obj",
".",
"value",
";",
"return",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"checkValue",
"(",
"obj",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
";",
"}",
"}",
"checkValue",
"(",
"data",
")",
";",
"return",
"data",
";",
"}"
] |
A custom panopticon transformer function. This mutates datasets into a format that is more useful
to observium.
@param {Object} data A panopticon data aggregate.
@param {string} id The ID of a cluster member.
@return {Object} Mutated data.
|
[
"A",
"custom",
"panopticon",
"transformer",
"function",
".",
"This",
"mutates",
"datasets",
"into",
"a",
"format",
"that",
"is",
"more",
"useful",
"to",
"observium",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/sampler/sampler.js#L121-L144
|
19,523
|
mage/mage
|
lib/sampler/sampler.js
|
delivery
|
function delivery(data) {
var name = data.name;
// Update the gatheredData object with the new data for this panopticon and emit its update.
// This emission fires for every delivery, and contains the complete data across all panoptica.
// This means that data may appear to be repeated (unless you check time stamps of course).
gatheredData[name] = data;
exports.emit('updatedData', gatheredData);
// The delivery is data for this panopticon only, the others are not emitted here. That's also
// how we keep the data in our buffer.
var obj = {};
obj[name] = data;
if (bufferLength > 0) {
bufferedData.push(obj);
}
exports.emit('panopticonDelivery', obj);
// Maintain a maximum buffer length for each panopticon (remove the oldest samples).
if (bufferedData.length > bufferLength) {
bufferedData.splice(0, bufferedData.length - bufferLength);
}
}
|
javascript
|
function delivery(data) {
var name = data.name;
// Update the gatheredData object with the new data for this panopticon and emit its update.
// This emission fires for every delivery, and contains the complete data across all panoptica.
// This means that data may appear to be repeated (unless you check time stamps of course).
gatheredData[name] = data;
exports.emit('updatedData', gatheredData);
// The delivery is data for this panopticon only, the others are not emitted here. That's also
// how we keep the data in our buffer.
var obj = {};
obj[name] = data;
if (bufferLength > 0) {
bufferedData.push(obj);
}
exports.emit('panopticonDelivery', obj);
// Maintain a maximum buffer length for each panopticon (remove the oldest samples).
if (bufferedData.length > bufferLength) {
bufferedData.splice(0, bufferedData.length - bufferLength);
}
}
|
[
"function",
"delivery",
"(",
"data",
")",
"{",
"var",
"name",
"=",
"data",
".",
"name",
";",
"// Update the gatheredData object with the new data for this panopticon and emit its update.",
"// This emission fires for every delivery, and contains the complete data across all panoptica.",
"// This means that data may appear to be repeated (unless you check time stamps of course).",
"gatheredData",
"[",
"name",
"]",
"=",
"data",
";",
"exports",
".",
"emit",
"(",
"'updatedData'",
",",
"gatheredData",
")",
";",
"// The delivery is data for this panopticon only, the others are not emitted here. That's also",
"// how we keep the data in our buffer.",
"var",
"obj",
"=",
"{",
"}",
";",
"obj",
"[",
"name",
"]",
"=",
"data",
";",
"if",
"(",
"bufferLength",
">",
"0",
")",
"{",
"bufferedData",
".",
"push",
"(",
"obj",
")",
";",
"}",
"exports",
".",
"emit",
"(",
"'panopticonDelivery'",
",",
"obj",
")",
";",
"// Maintain a maximum buffer length for each panopticon (remove the oldest samples).",
"if",
"(",
"bufferedData",
".",
"length",
">",
"bufferLength",
")",
"{",
"bufferedData",
".",
"splice",
"(",
"0",
",",
"bufferedData",
".",
"length",
"-",
"bufferLength",
")",
";",
"}",
"}"
] |
This function is called when a panopticon emits a data set. It updates the buffer, and emits
the events `'panopticonDelivery'`, which forwards the panopticon data set, and `'updatedData'`,
which emits all data together.
@param {Object} data A panopticon data set.
|
[
"This",
"function",
"is",
"called",
"when",
"a",
"panopticon",
"emits",
"a",
"data",
"set",
".",
"It",
"updates",
"the",
"buffer",
"and",
"emits",
"the",
"events",
"panopticonDelivery",
"which",
"forwards",
"the",
"panopticon",
"data",
"set",
"and",
"updatedData",
"which",
"emits",
"all",
"data",
"together",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/sampler/sampler.js#L155-L183
|
19,524
|
mage/mage
|
lib/sampler/sampler.js
|
pathToQuery
|
function pathToQuery(pathname) {
if (typeof pathname !== 'string') {
throw new Error('Invalid path: ' + pathname);
}
var path = pathname.split('/');
// Remove the useless '' (zeroth) element and the 'sampler' (first) element.
var samplerPos = path.indexOf('sampler');
if (samplerPos !== -1) {
path = path.slice(samplerPos + 1);
}
// If the request had a trailing '/', remove the resulting empty final element in the path.
if (path[path.length - 1] === '') {
path.pop();
}
return path;
}
|
javascript
|
function pathToQuery(pathname) {
if (typeof pathname !== 'string') {
throw new Error('Invalid path: ' + pathname);
}
var path = pathname.split('/');
// Remove the useless '' (zeroth) element and the 'sampler' (first) element.
var samplerPos = path.indexOf('sampler');
if (samplerPos !== -1) {
path = path.slice(samplerPos + 1);
}
// If the request had a trailing '/', remove the resulting empty final element in the path.
if (path[path.length - 1] === '') {
path.pop();
}
return path;
}
|
[
"function",
"pathToQuery",
"(",
"pathname",
")",
"{",
"if",
"(",
"typeof",
"pathname",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid path: '",
"+",
"pathname",
")",
";",
"}",
"var",
"path",
"=",
"pathname",
".",
"split",
"(",
"'/'",
")",
";",
"// Remove the useless '' (zeroth) element and the 'sampler' (first) element.",
"var",
"samplerPos",
"=",
"path",
".",
"indexOf",
"(",
"'sampler'",
")",
";",
"if",
"(",
"samplerPos",
"!==",
"-",
"1",
")",
"{",
"path",
"=",
"path",
".",
"slice",
"(",
"samplerPos",
"+",
"1",
")",
";",
"}",
"// If the request had a trailing '/', remove the resulting empty final element in the path.",
"if",
"(",
"path",
"[",
"path",
".",
"length",
"-",
"1",
"]",
"===",
"''",
")",
"{",
"path",
".",
"pop",
"(",
")",
";",
"}",
"return",
"path",
";",
"}"
] |
Process a url's path into a path array.
@param {string} pathname The path from a URL string.
@return {string[]} An array with elements that are sub-paths of increasing depth to index.
|
[
"Process",
"a",
"url",
"s",
"path",
"into",
"a",
"path",
"array",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/sampler/sampler.js#L193-L213
|
19,525
|
mage/mage
|
lib/sampler/sampler.js
|
requestResponseHandler
|
function requestResponseHandler(req, res, path) {
if (panoptica.length === 0) {
// not set up
res.writeHead(500, { 'content-type': 'text/plain' });
res.end('Sampler has not been configured with any intervals');
return;
}
var queryPath;
try {
queryPath = pathToQuery(path);
} catch (error) {
// bad request
res.writeHead(400, { 'content-type': 'text/plain' });
res.end('Failed to parse query path: ' + path);
return;
}
var data = exports.query(queryPath);
if (data === undefined) {
logger.verbose('Could not find path', queryPath, 'in sampler. Available:', Object.keys(gatheredData));
res.writeHead(404, { 'content-type': 'text/plain' });
res.end('There is no data available at "' + queryPath.join('/') + '" at this time.');
return;
}
try {
data = JSON.stringify(data, null, ' ');
} catch (jsonError) {
logger.error('Error serializing sampler data:', jsonError);
res.writeHead(500, { 'content-type': 'text/plain' });
res.end('Error while serializing data');
return;
}
res.writeHead(200, { 'content-type': 'application/json' });
res.end(data);
}
|
javascript
|
function requestResponseHandler(req, res, path) {
if (panoptica.length === 0) {
// not set up
res.writeHead(500, { 'content-type': 'text/plain' });
res.end('Sampler has not been configured with any intervals');
return;
}
var queryPath;
try {
queryPath = pathToQuery(path);
} catch (error) {
// bad request
res.writeHead(400, { 'content-type': 'text/plain' });
res.end('Failed to parse query path: ' + path);
return;
}
var data = exports.query(queryPath);
if (data === undefined) {
logger.verbose('Could not find path', queryPath, 'in sampler. Available:', Object.keys(gatheredData));
res.writeHead(404, { 'content-type': 'text/plain' });
res.end('There is no data available at "' + queryPath.join('/') + '" at this time.');
return;
}
try {
data = JSON.stringify(data, null, ' ');
} catch (jsonError) {
logger.error('Error serializing sampler data:', jsonError);
res.writeHead(500, { 'content-type': 'text/plain' });
res.end('Error while serializing data');
return;
}
res.writeHead(200, { 'content-type': 'application/json' });
res.end(data);
}
|
[
"function",
"requestResponseHandler",
"(",
"req",
",",
"res",
",",
"path",
")",
"{",
"if",
"(",
"panoptica",
".",
"length",
"===",
"0",
")",
"{",
"// not set up",
"res",
".",
"writeHead",
"(",
"500",
",",
"{",
"'content-type'",
":",
"'text/plain'",
"}",
")",
";",
"res",
".",
"end",
"(",
"'Sampler has not been configured with any intervals'",
")",
";",
"return",
";",
"}",
"var",
"queryPath",
";",
"try",
"{",
"queryPath",
"=",
"pathToQuery",
"(",
"path",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"// bad request",
"res",
".",
"writeHead",
"(",
"400",
",",
"{",
"'content-type'",
":",
"'text/plain'",
"}",
")",
";",
"res",
".",
"end",
"(",
"'Failed to parse query path: '",
"+",
"path",
")",
";",
"return",
";",
"}",
"var",
"data",
"=",
"exports",
".",
"query",
"(",
"queryPath",
")",
";",
"if",
"(",
"data",
"===",
"undefined",
")",
"{",
"logger",
".",
"verbose",
"(",
"'Could not find path'",
",",
"queryPath",
",",
"'in sampler. Available:'",
",",
"Object",
".",
"keys",
"(",
"gatheredData",
")",
")",
";",
"res",
".",
"writeHead",
"(",
"404",
",",
"{",
"'content-type'",
":",
"'text/plain'",
"}",
")",
";",
"res",
".",
"end",
"(",
"'There is no data available at \"'",
"+",
"queryPath",
".",
"join",
"(",
"'/'",
")",
"+",
"'\" at this time.'",
")",
";",
"return",
";",
"}",
"try",
"{",
"data",
"=",
"JSON",
".",
"stringify",
"(",
"data",
",",
"null",
",",
"' '",
")",
";",
"}",
"catch",
"(",
"jsonError",
")",
"{",
"logger",
".",
"error",
"(",
"'Error serializing sampler data:'",
",",
"jsonError",
")",
";",
"res",
".",
"writeHead",
"(",
"500",
",",
"{",
"'content-type'",
":",
"'text/plain'",
"}",
")",
";",
"res",
".",
"end",
"(",
"'Error while serializing data'",
")",
";",
"return",
";",
"}",
"res",
".",
"writeHead",
"(",
"200",
",",
"{",
"'content-type'",
":",
"'application/json'",
"}",
")",
";",
"res",
".",
"end",
"(",
"data",
")",
";",
"}"
] |
A simple HTTP request-response handler to wrap exports.query.
@param {http.ClientRequest} req HTTP client request object.
@param {http.ServerResponse} res HTTP server response object.
@param {string} path The path in the URL.
|
[
"A",
"simple",
"HTTP",
"request",
"-",
"response",
"handler",
"to",
"wrap",
"exports",
".",
"query",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/sampler/sampler.js#L224-L266
|
19,526
|
mage/mage
|
lib/modules/logger/usercommands/sendReport.js
|
prettifyStackTrace
|
function prettifyStackTrace(appName, clientConfig, stack) {
if (!appName || !clientConfig || !Array.isArray(stack)) {
return;
}
var app = mage.core.app.get(appName);
if (!app) {
return;
}
var responses = app.getResponsesForClientConfig(app.getBestConfig(clientConfig));
// On the client side, stacktrace.js has turned each entry into "symbol@file:line:col".
// Now try to source-map our way through it.
function replacer(match, file, line, col) {
line = parseInt(line, 10);
col = parseInt(col, 10);
for (var i = 0; i < responses.length; i++) {
var meta = responses[i].meta;
var sourcemap = meta && meta.sourcemaps && meta.sourcemaps[file];
if (!sourcemap) {
continue;
}
var smc = new SourceMapConsumer(sourcemap);
var pos = smc.originalPositionFor({ line: line, column: col });
if (pos) {
return pos.name + ' (' + file + ':' + pos.line + ':' + pos.column + ')';
}
}
return match;
}
for (var i = 0; i < stack.length; i++) {
var frame = stack[i];
if (typeof frame === 'string') {
// rewrite the stack frame and put it back in the stack
stack[i] = frame.replace(/^.+?@(.+?):([0-9]+):([0-9]+)$/, replacer);
}
}
}
|
javascript
|
function prettifyStackTrace(appName, clientConfig, stack) {
if (!appName || !clientConfig || !Array.isArray(stack)) {
return;
}
var app = mage.core.app.get(appName);
if (!app) {
return;
}
var responses = app.getResponsesForClientConfig(app.getBestConfig(clientConfig));
// On the client side, stacktrace.js has turned each entry into "symbol@file:line:col".
// Now try to source-map our way through it.
function replacer(match, file, line, col) {
line = parseInt(line, 10);
col = parseInt(col, 10);
for (var i = 0; i < responses.length; i++) {
var meta = responses[i].meta;
var sourcemap = meta && meta.sourcemaps && meta.sourcemaps[file];
if (!sourcemap) {
continue;
}
var smc = new SourceMapConsumer(sourcemap);
var pos = smc.originalPositionFor({ line: line, column: col });
if (pos) {
return pos.name + ' (' + file + ':' + pos.line + ':' + pos.column + ')';
}
}
return match;
}
for (var i = 0; i < stack.length; i++) {
var frame = stack[i];
if (typeof frame === 'string') {
// rewrite the stack frame and put it back in the stack
stack[i] = frame.replace(/^.+?@(.+?):([0-9]+):([0-9]+)$/, replacer);
}
}
}
|
[
"function",
"prettifyStackTrace",
"(",
"appName",
",",
"clientConfig",
",",
"stack",
")",
"{",
"if",
"(",
"!",
"appName",
"||",
"!",
"clientConfig",
"||",
"!",
"Array",
".",
"isArray",
"(",
"stack",
")",
")",
"{",
"return",
";",
"}",
"var",
"app",
"=",
"mage",
".",
"core",
".",
"app",
".",
"get",
"(",
"appName",
")",
";",
"if",
"(",
"!",
"app",
")",
"{",
"return",
";",
"}",
"var",
"responses",
"=",
"app",
".",
"getResponsesForClientConfig",
"(",
"app",
".",
"getBestConfig",
"(",
"clientConfig",
")",
")",
";",
"// On the client side, stacktrace.js has turned each entry into \"symbol@file:line:col\".",
"// Now try to source-map our way through it.",
"function",
"replacer",
"(",
"match",
",",
"file",
",",
"line",
",",
"col",
")",
"{",
"line",
"=",
"parseInt",
"(",
"line",
",",
"10",
")",
";",
"col",
"=",
"parseInt",
"(",
"col",
",",
"10",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"responses",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"meta",
"=",
"responses",
"[",
"i",
"]",
".",
"meta",
";",
"var",
"sourcemap",
"=",
"meta",
"&&",
"meta",
".",
"sourcemaps",
"&&",
"meta",
".",
"sourcemaps",
"[",
"file",
"]",
";",
"if",
"(",
"!",
"sourcemap",
")",
"{",
"continue",
";",
"}",
"var",
"smc",
"=",
"new",
"SourceMapConsumer",
"(",
"sourcemap",
")",
";",
"var",
"pos",
"=",
"smc",
".",
"originalPositionFor",
"(",
"{",
"line",
":",
"line",
",",
"column",
":",
"col",
"}",
")",
";",
"if",
"(",
"pos",
")",
"{",
"return",
"pos",
".",
"name",
"+",
"' ('",
"+",
"file",
"+",
"':'",
"+",
"pos",
".",
"line",
"+",
"':'",
"+",
"pos",
".",
"column",
"+",
"')'",
";",
"}",
"}",
"return",
"match",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"stack",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"frame",
"=",
"stack",
"[",
"i",
"]",
";",
"if",
"(",
"typeof",
"frame",
"===",
"'string'",
")",
"{",
"// rewrite the stack frame and put it back in the stack",
"stack",
"[",
"i",
"]",
"=",
"frame",
".",
"replace",
"(",
"/",
"^.+?@(.+?):([0-9]+):([0-9]+)$",
"/",
",",
"replacer",
")",
";",
"}",
"}",
"}"
] |
This function depends on stack traces being formatted by the stacktrace.js library
@param {string} appName
@param {Object} clientConfig
@param {string[]} stack
|
[
"This",
"function",
"depends",
"on",
"stack",
"traces",
"being",
"formatted",
"by",
"the",
"stacktrace",
".",
"js",
"library"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/modules/logger/usercommands/sendReport.js#L14-L61
|
19,527
|
mage/mage
|
lib/modules/logger/usercommands/sendReport.js
|
replacer
|
function replacer(match, file, line, col) {
line = parseInt(line, 10);
col = parseInt(col, 10);
for (var i = 0; i < responses.length; i++) {
var meta = responses[i].meta;
var sourcemap = meta && meta.sourcemaps && meta.sourcemaps[file];
if (!sourcemap) {
continue;
}
var smc = new SourceMapConsumer(sourcemap);
var pos = smc.originalPositionFor({ line: line, column: col });
if (pos) {
return pos.name + ' (' + file + ':' + pos.line + ':' + pos.column + ')';
}
}
return match;
}
|
javascript
|
function replacer(match, file, line, col) {
line = parseInt(line, 10);
col = parseInt(col, 10);
for (var i = 0; i < responses.length; i++) {
var meta = responses[i].meta;
var sourcemap = meta && meta.sourcemaps && meta.sourcemaps[file];
if (!sourcemap) {
continue;
}
var smc = new SourceMapConsumer(sourcemap);
var pos = smc.originalPositionFor({ line: line, column: col });
if (pos) {
return pos.name + ' (' + file + ':' + pos.line + ':' + pos.column + ')';
}
}
return match;
}
|
[
"function",
"replacer",
"(",
"match",
",",
"file",
",",
"line",
",",
"col",
")",
"{",
"line",
"=",
"parseInt",
"(",
"line",
",",
"10",
")",
";",
"col",
"=",
"parseInt",
"(",
"col",
",",
"10",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"responses",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"meta",
"=",
"responses",
"[",
"i",
"]",
".",
"meta",
";",
"var",
"sourcemap",
"=",
"meta",
"&&",
"meta",
".",
"sourcemaps",
"&&",
"meta",
".",
"sourcemaps",
"[",
"file",
"]",
";",
"if",
"(",
"!",
"sourcemap",
")",
"{",
"continue",
";",
"}",
"var",
"smc",
"=",
"new",
"SourceMapConsumer",
"(",
"sourcemap",
")",
";",
"var",
"pos",
"=",
"smc",
".",
"originalPositionFor",
"(",
"{",
"line",
":",
"line",
",",
"column",
":",
"col",
"}",
")",
";",
"if",
"(",
"pos",
")",
"{",
"return",
"pos",
".",
"name",
"+",
"' ('",
"+",
"file",
"+",
"':'",
"+",
"pos",
".",
"line",
"+",
"':'",
"+",
"pos",
".",
"column",
"+",
"')'",
";",
"}",
"}",
"return",
"match",
";",
"}"
] |
On the client side, stacktrace.js has turned each entry into "symbol@file:line:col". Now try to source-map our way through it.
|
[
"On",
"the",
"client",
"side",
"stacktrace",
".",
"js",
"has",
"turned",
"each",
"entry",
"into",
"symbol"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/modules/logger/usercommands/sendReport.js#L29-L50
|
19,528
|
mage/mage
|
lib/serviceDiscovery/node.js
|
ServiceNode
|
function ServiceNode(host, port, addresses, metadata) {
this.host = host;
this.port = port;
this.addresses = addresses;
this.data = metadata || {};
}
|
javascript
|
function ServiceNode(host, port, addresses, metadata) {
this.host = host;
this.port = port;
this.addresses = addresses;
this.data = metadata || {};
}
|
[
"function",
"ServiceNode",
"(",
"host",
",",
"port",
",",
"addresses",
",",
"metadata",
")",
"{",
"this",
".",
"host",
"=",
"host",
";",
"this",
".",
"port",
"=",
"port",
";",
"this",
".",
"addresses",
"=",
"addresses",
";",
"this",
".",
"data",
"=",
"metadata",
"||",
"{",
"}",
";",
"}"
] |
This the representation of a node on the discovery network
@param {string} host The hostname for the node
@param {number} port The port on which the service is reachable
@param {string[]} addresses A list of ips on which the service is reachable
@param {Object} [metadata] The metadata announced by the service
@constructor
|
[
"This",
"the",
"representation",
"of",
"a",
"node",
"on",
"the",
"discovery",
"network"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/serviceDiscovery/node.js#L39-L44
|
19,529
|
mage/mage
|
lib/commandCenter/httpBatchHandler.js
|
resolveFilesInParams
|
function resolveFilesInParams(params, files) {
var fileIds = Object.keys(files || {});
var fileCount = fileIds.length;
if (fileCount === 0) {
return;
}
// scan all members for files, and collect children
function addMembers(list, obj) {
var keys = Object.keys(obj || {});
for (var i = 0; i < keys.length; i++) {
list.push({
owner: obj,
key: keys[i],
value: obj[keys[i]]
});
}
}
var list = [];
addMembers(list, params);
for (var i = 0; i < list.length && fileCount > 0; i++) {
var member = list[i];
if (!member.value) {
continue;
}
var type = typeof member.value;
if (type === 'object') {
// append children to the end of the list
addMembers(list, member.value);
} else if (type === 'string' && files[member.value]) {
// file found for this property, so assign it
var file = files[member.value];
logger.verbose('Accepted file', '"' + file.partName + '":', file.fileName);
member.owner[member.key] = file;
delete files[member.value];
fileCount -= 1;
}
}
}
|
javascript
|
function resolveFilesInParams(params, files) {
var fileIds = Object.keys(files || {});
var fileCount = fileIds.length;
if (fileCount === 0) {
return;
}
// scan all members for files, and collect children
function addMembers(list, obj) {
var keys = Object.keys(obj || {});
for (var i = 0; i < keys.length; i++) {
list.push({
owner: obj,
key: keys[i],
value: obj[keys[i]]
});
}
}
var list = [];
addMembers(list, params);
for (var i = 0; i < list.length && fileCount > 0; i++) {
var member = list[i];
if (!member.value) {
continue;
}
var type = typeof member.value;
if (type === 'object') {
// append children to the end of the list
addMembers(list, member.value);
} else if (type === 'string' && files[member.value]) {
// file found for this property, so assign it
var file = files[member.value];
logger.verbose('Accepted file', '"' + file.partName + '":', file.fileName);
member.owner[member.key] = file;
delete files[member.value];
fileCount -= 1;
}
}
}
|
[
"function",
"resolveFilesInParams",
"(",
"params",
",",
"files",
")",
"{",
"var",
"fileIds",
"=",
"Object",
".",
"keys",
"(",
"files",
"||",
"{",
"}",
")",
";",
"var",
"fileCount",
"=",
"fileIds",
".",
"length",
";",
"if",
"(",
"fileCount",
"===",
"0",
")",
"{",
"return",
";",
"}",
"// scan all members for files, and collect children",
"function",
"addMembers",
"(",
"list",
",",
"obj",
")",
"{",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
"||",
"{",
"}",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"list",
".",
"push",
"(",
"{",
"owner",
":",
"obj",
",",
"key",
":",
"keys",
"[",
"i",
"]",
",",
"value",
":",
"obj",
"[",
"keys",
"[",
"i",
"]",
"]",
"}",
")",
";",
"}",
"}",
"var",
"list",
"=",
"[",
"]",
";",
"addMembers",
"(",
"list",
",",
"params",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"list",
".",
"length",
"&&",
"fileCount",
">",
"0",
";",
"i",
"++",
")",
"{",
"var",
"member",
"=",
"list",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"member",
".",
"value",
")",
"{",
"continue",
";",
"}",
"var",
"type",
"=",
"typeof",
"member",
".",
"value",
";",
"if",
"(",
"type",
"===",
"'object'",
")",
"{",
"// append children to the end of the list",
"addMembers",
"(",
"list",
",",
"member",
".",
"value",
")",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'string'",
"&&",
"files",
"[",
"member",
".",
"value",
"]",
")",
"{",
"// file found for this property, so assign it",
"var",
"file",
"=",
"files",
"[",
"member",
".",
"value",
"]",
";",
"logger",
".",
"verbose",
"(",
"'Accepted file'",
",",
"'\"'",
"+",
"file",
".",
"partName",
"+",
"'\":'",
",",
"file",
".",
"fileName",
")",
";",
"member",
".",
"owner",
"[",
"member",
".",
"key",
"]",
"=",
"file",
";",
"delete",
"files",
"[",
"member",
".",
"value",
"]",
";",
"fileCount",
"-=",
"1",
";",
"}",
"}",
"}"
] |
Replace file placeholders in params with actual file data.
@param {Object} params
@param {Object} files
|
[
"Replace",
"file",
"placeholders",
"in",
"params",
"with",
"actual",
"file",
"data",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/commandCenter/httpBatchHandler.js#L33-L85
|
19,530
|
mage/mage
|
lib/commandCenter/httpBatchHandler.js
|
addMembers
|
function addMembers(list, obj) {
var keys = Object.keys(obj || {});
for (var i = 0; i < keys.length; i++) {
list.push({
owner: obj,
key: keys[i],
value: obj[keys[i]]
});
}
}
|
javascript
|
function addMembers(list, obj) {
var keys = Object.keys(obj || {});
for (var i = 0; i < keys.length; i++) {
list.push({
owner: obj,
key: keys[i],
value: obj[keys[i]]
});
}
}
|
[
"function",
"addMembers",
"(",
"list",
",",
"obj",
")",
"{",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
"||",
"{",
"}",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"list",
".",
"push",
"(",
"{",
"owner",
":",
"obj",
",",
"key",
":",
"keys",
"[",
"i",
"]",
",",
"value",
":",
"obj",
"[",
"keys",
"[",
"i",
"]",
"]",
"}",
")",
";",
"}",
"}"
] |
scan all members for files, and collect children
|
[
"scan",
"all",
"members",
"for",
"files",
"and",
"collect",
"children"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/commandCenter/httpBatchHandler.js#L43-L53
|
19,531
|
mage/mage
|
lib/commandCenter/httpBatchHandler.js
|
parseBatchData
|
function parseBatchData(fullPath, req, rawData, files) {
assert.equal(typeof fullPath, 'string', 'invalidPath');
var commandNames = fullPath.substr(fullPath.lastIndexOf('/') + 1).split(',');
var commandCount = commandNames.length;
var commands = new Array(commandCount);
// split the string into lines
var cmdData = rawData.split('\n');
// line 0 is the header
var header;
try {
header = JSON.parse(cmdData[0]);
} catch (error) {
logger.error
.data('data', cmdData[0])
.data('error', error.message)
.log('Error parsing command header.');
}
assert(Array.isArray(header), 'invalid command header');
for (var i = 0; i < commandCount; i++) {
var commandData = cmdData[i + 1]; // +1 to offset the header at index 0
var params;
try {
params = JSON.parse(commandData) || {};
} catch (e) {
logger.error.data(commandData).log('Error parsing command data.');
throw e;
}
if (files) {
resolveFilesInParams(params, files);
}
commands[i] = {
name: commandNames[i],
params: params
};
}
return {
transport: {
type: 'http',
req: req
},
rawData: rawData, // useful for hashing
header: header,
commands: commands,
commandNames: commandNames // useful for logging
};
}
|
javascript
|
function parseBatchData(fullPath, req, rawData, files) {
assert.equal(typeof fullPath, 'string', 'invalidPath');
var commandNames = fullPath.substr(fullPath.lastIndexOf('/') + 1).split(',');
var commandCount = commandNames.length;
var commands = new Array(commandCount);
// split the string into lines
var cmdData = rawData.split('\n');
// line 0 is the header
var header;
try {
header = JSON.parse(cmdData[0]);
} catch (error) {
logger.error
.data('data', cmdData[0])
.data('error', error.message)
.log('Error parsing command header.');
}
assert(Array.isArray(header), 'invalid command header');
for (var i = 0; i < commandCount; i++) {
var commandData = cmdData[i + 1]; // +1 to offset the header at index 0
var params;
try {
params = JSON.parse(commandData) || {};
} catch (e) {
logger.error.data(commandData).log('Error parsing command data.');
throw e;
}
if (files) {
resolveFilesInParams(params, files);
}
commands[i] = {
name: commandNames[i],
params: params
};
}
return {
transport: {
type: 'http',
req: req
},
rawData: rawData, // useful for hashing
header: header,
commands: commands,
commandNames: commandNames // useful for logging
};
}
|
[
"function",
"parseBatchData",
"(",
"fullPath",
",",
"req",
",",
"rawData",
",",
"files",
")",
"{",
"assert",
".",
"equal",
"(",
"typeof",
"fullPath",
",",
"'string'",
",",
"'invalidPath'",
")",
";",
"var",
"commandNames",
"=",
"fullPath",
".",
"substr",
"(",
"fullPath",
".",
"lastIndexOf",
"(",
"'/'",
")",
"+",
"1",
")",
".",
"split",
"(",
"','",
")",
";",
"var",
"commandCount",
"=",
"commandNames",
".",
"length",
";",
"var",
"commands",
"=",
"new",
"Array",
"(",
"commandCount",
")",
";",
"// split the string into lines",
"var",
"cmdData",
"=",
"rawData",
".",
"split",
"(",
"'\\n'",
")",
";",
"// line 0 is the header",
"var",
"header",
";",
"try",
"{",
"header",
"=",
"JSON",
".",
"parse",
"(",
"cmdData",
"[",
"0",
"]",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"logger",
".",
"error",
".",
"data",
"(",
"'data'",
",",
"cmdData",
"[",
"0",
"]",
")",
".",
"data",
"(",
"'error'",
",",
"error",
".",
"message",
")",
".",
"log",
"(",
"'Error parsing command header.'",
")",
";",
"}",
"assert",
"(",
"Array",
".",
"isArray",
"(",
"header",
")",
",",
"'invalid command header'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"commandCount",
";",
"i",
"++",
")",
"{",
"var",
"commandData",
"=",
"cmdData",
"[",
"i",
"+",
"1",
"]",
";",
"// +1 to offset the header at index 0",
"var",
"params",
";",
"try",
"{",
"params",
"=",
"JSON",
".",
"parse",
"(",
"commandData",
")",
"||",
"{",
"}",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"logger",
".",
"error",
".",
"data",
"(",
"commandData",
")",
".",
"log",
"(",
"'Error parsing command data.'",
")",
";",
"throw",
"e",
";",
"}",
"if",
"(",
"files",
")",
"{",
"resolveFilesInParams",
"(",
"params",
",",
"files",
")",
";",
"}",
"commands",
"[",
"i",
"]",
"=",
"{",
"name",
":",
"commandNames",
"[",
"i",
"]",
",",
"params",
":",
"params",
"}",
";",
"}",
"return",
"{",
"transport",
":",
"{",
"type",
":",
"'http'",
",",
"req",
":",
"req",
"}",
",",
"rawData",
":",
"rawData",
",",
"// useful for hashing",
"header",
":",
"header",
",",
"commands",
":",
"commands",
",",
"commandNames",
":",
"commandNames",
"// useful for logging",
"}",
";",
"}"
] |
Parses the uploaded data and files into a batch object
@param {string} fullPath The full path of the HTTP request.
@param {Object} req The HTTP request object.
@param {string} rawData The POST data that contains the command parameters.
@param {Object} [files] Any uploaded files.
@returns {Object} The batch.
|
[
"Parses",
"the",
"uploaded",
"data",
"and",
"files",
"into",
"a",
"batch",
"object"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/commandCenter/httpBatchHandler.js#L98-L155
|
19,532
|
mage/mage
|
lib/commandCenter/httpBatchHandler.js
|
parseMultipart
|
function parseMultipart(req, boundary, cb) {
// multipart, the first part has to be the same format as single part post data
var parser = MultipartParser.create(boundary);
var files = {};
var cmdData = '';
parser.on('part', function (part) {
var m, disp, partName, fileName, isCmdData;
disp = part.headers['content-disposition'];
if (!disp) {
// unidentifiable parts cannot be used
logger.warning.data('partHeaders', part.headers).log('Received an unidentifyable part, skipping.');
return;
}
m = disp.match(/name="(.+?)"/);
if (!m) {
// unnamed parts cannot be used
logger.warning.data('partHeaders', part.headers).log('Received an unnamed part, skipping.');
return;
}
partName = m[1];
logger.verbose('Receiving multipart-part:', partName);
isCmdData = (partName === 'cmddata');
m = disp.match(/filename="(.+?)"/);
if (m) {
// a filename is optional
fileName = m[1];
}
// the first part is ready and is expected to be the same format as single part post data
var data = [];
part.on('data', function (chunk) {
if (isCmdData) {
// treat as utf8
cmdData += chunk.toString('utf8');
} else {
data.push(chunk);
}
});
if (!isCmdData) {
part.on('end', function () {
// create the files object for the following files, the command center can take care of the rest
files[partName] = {
data: data,
partName: partName,
fileName: fileName,
type: part.headers['content-type']
};
});
}
});
// It has been observed that the "end" event on the parser would fire more than once. This might
// be related to Node.js 0.10 streams. To avoid the situation, we use once('end') instead of
// on('end').
parser.once('end', function () {
logger.verbose('Finished reading multipart', req.method, 'request.');
cb(null, cmdData, files);
});
// pipe all incoming data straight into the multipart parser
req.pipe(parser);
}
|
javascript
|
function parseMultipart(req, boundary, cb) {
// multipart, the first part has to be the same format as single part post data
var parser = MultipartParser.create(boundary);
var files = {};
var cmdData = '';
parser.on('part', function (part) {
var m, disp, partName, fileName, isCmdData;
disp = part.headers['content-disposition'];
if (!disp) {
// unidentifiable parts cannot be used
logger.warning.data('partHeaders', part.headers).log('Received an unidentifyable part, skipping.');
return;
}
m = disp.match(/name="(.+?)"/);
if (!m) {
// unnamed parts cannot be used
logger.warning.data('partHeaders', part.headers).log('Received an unnamed part, skipping.');
return;
}
partName = m[1];
logger.verbose('Receiving multipart-part:', partName);
isCmdData = (partName === 'cmddata');
m = disp.match(/filename="(.+?)"/);
if (m) {
// a filename is optional
fileName = m[1];
}
// the first part is ready and is expected to be the same format as single part post data
var data = [];
part.on('data', function (chunk) {
if (isCmdData) {
// treat as utf8
cmdData += chunk.toString('utf8');
} else {
data.push(chunk);
}
});
if (!isCmdData) {
part.on('end', function () {
// create the files object for the following files, the command center can take care of the rest
files[partName] = {
data: data,
partName: partName,
fileName: fileName,
type: part.headers['content-type']
};
});
}
});
// It has been observed that the "end" event on the parser would fire more than once. This might
// be related to Node.js 0.10 streams. To avoid the situation, we use once('end') instead of
// on('end').
parser.once('end', function () {
logger.verbose('Finished reading multipart', req.method, 'request.');
cb(null, cmdData, files);
});
// pipe all incoming data straight into the multipart parser
req.pipe(parser);
}
|
[
"function",
"parseMultipart",
"(",
"req",
",",
"boundary",
",",
"cb",
")",
"{",
"// multipart, the first part has to be the same format as single part post data",
"var",
"parser",
"=",
"MultipartParser",
".",
"create",
"(",
"boundary",
")",
";",
"var",
"files",
"=",
"{",
"}",
";",
"var",
"cmdData",
"=",
"''",
";",
"parser",
".",
"on",
"(",
"'part'",
",",
"function",
"(",
"part",
")",
"{",
"var",
"m",
",",
"disp",
",",
"partName",
",",
"fileName",
",",
"isCmdData",
";",
"disp",
"=",
"part",
".",
"headers",
"[",
"'content-disposition'",
"]",
";",
"if",
"(",
"!",
"disp",
")",
"{",
"// unidentifiable parts cannot be used",
"logger",
".",
"warning",
".",
"data",
"(",
"'partHeaders'",
",",
"part",
".",
"headers",
")",
".",
"log",
"(",
"'Received an unidentifyable part, skipping.'",
")",
";",
"return",
";",
"}",
"m",
"=",
"disp",
".",
"match",
"(",
"/",
"name=\"(.+?)\"",
"/",
")",
";",
"if",
"(",
"!",
"m",
")",
"{",
"// unnamed parts cannot be used",
"logger",
".",
"warning",
".",
"data",
"(",
"'partHeaders'",
",",
"part",
".",
"headers",
")",
".",
"log",
"(",
"'Received an unnamed part, skipping.'",
")",
";",
"return",
";",
"}",
"partName",
"=",
"m",
"[",
"1",
"]",
";",
"logger",
".",
"verbose",
"(",
"'Receiving multipart-part:'",
",",
"partName",
")",
";",
"isCmdData",
"=",
"(",
"partName",
"===",
"'cmddata'",
")",
";",
"m",
"=",
"disp",
".",
"match",
"(",
"/",
"filename=\"(.+?)\"",
"/",
")",
";",
"if",
"(",
"m",
")",
"{",
"// a filename is optional",
"fileName",
"=",
"m",
"[",
"1",
"]",
";",
"}",
"// the first part is ready and is expected to be the same format as single part post data",
"var",
"data",
"=",
"[",
"]",
";",
"part",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"if",
"(",
"isCmdData",
")",
"{",
"// treat as utf8",
"cmdData",
"+=",
"chunk",
".",
"toString",
"(",
"'utf8'",
")",
";",
"}",
"else",
"{",
"data",
".",
"push",
"(",
"chunk",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"!",
"isCmdData",
")",
"{",
"part",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"// create the files object for the following files, the command center can take care of the rest",
"files",
"[",
"partName",
"]",
"=",
"{",
"data",
":",
"data",
",",
"partName",
":",
"partName",
",",
"fileName",
":",
"fileName",
",",
"type",
":",
"part",
".",
"headers",
"[",
"'content-type'",
"]",
"}",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"// It has been observed that the \"end\" event on the parser would fire more than once. This might",
"// be related to Node.js 0.10 streams. To avoid the situation, we use once('end') instead of",
"// on('end').",
"parser",
".",
"once",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"logger",
".",
"verbose",
"(",
"'Finished reading multipart'",
",",
"req",
".",
"method",
",",
"'request.'",
")",
";",
"cb",
"(",
"null",
",",
"cmdData",
",",
"files",
")",
";",
"}",
")",
";",
"// pipe all incoming data straight into the multipart parser",
"req",
".",
"pipe",
"(",
"parser",
")",
";",
"}"
] |
Streams and parses a multipart request
@param {Object} req The HTTP request.
@param {string} boundary The boundary between the parts.
@param {Function} cb Callback on completion.
|
[
"Streams",
"and",
"parses",
"a",
"multipart",
"request"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/commandCenter/httpBatchHandler.js#L166-L246
|
19,533
|
mage/mage
|
lib/commandCenter/httpBatchHandler.js
|
parseSinglepart
|
function parseSinglepart(req, cb) {
// single part
req.setEncoding('utf8');
var cmdData = '';
req.on('data', function (chunk) {
cmdData += chunk;
});
req.on('end', function () {
logger.verbose('Finished reading', req.method, 'request.');
cb(null, cmdData, null);
});
}
|
javascript
|
function parseSinglepart(req, cb) {
// single part
req.setEncoding('utf8');
var cmdData = '';
req.on('data', function (chunk) {
cmdData += chunk;
});
req.on('end', function () {
logger.verbose('Finished reading', req.method, 'request.');
cb(null, cmdData, null);
});
}
|
[
"function",
"parseSinglepart",
"(",
"req",
",",
"cb",
")",
"{",
"// single part",
"req",
".",
"setEncoding",
"(",
"'utf8'",
")",
";",
"var",
"cmdData",
"=",
"''",
";",
"req",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"cmdData",
"+=",
"chunk",
";",
"}",
")",
";",
"req",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"logger",
".",
"verbose",
"(",
"'Finished reading'",
",",
"req",
".",
"method",
",",
"'request.'",
")",
";",
"cb",
"(",
"null",
",",
"cmdData",
",",
"null",
")",
";",
"}",
")",
";",
"}"
] |
Streams and parses a singlepart request
@param {Object} req The HTTP request.
@param {Function} cb Callback on completion.
|
[
"Streams",
"and",
"parses",
"a",
"singlepart",
"request"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/commandCenter/httpBatchHandler.js#L256-L272
|
19,534
|
mage/mage
|
lib/commandCenter/httpBatchHandler.js
|
parseHttpBody
|
function parseHttpBody(req, cb) {
// check for multipart streams that can contain file uploads
var contentType = req.headers['content-type'];
var m = contentType && contentType.match(/^multipart\/form-data; boundary=(.+)$/);
if (m && m[1]) {
parseMultipart(req, m[1], cb);
} else {
parseSinglepart(req, cb);
}
}
|
javascript
|
function parseHttpBody(req, cb) {
// check for multipart streams that can contain file uploads
var contentType = req.headers['content-type'];
var m = contentType && contentType.match(/^multipart\/form-data; boundary=(.+)$/);
if (m && m[1]) {
parseMultipart(req, m[1], cb);
} else {
parseSinglepart(req, cb);
}
}
|
[
"function",
"parseHttpBody",
"(",
"req",
",",
"cb",
")",
"{",
"// check for multipart streams that can contain file uploads",
"var",
"contentType",
"=",
"req",
".",
"headers",
"[",
"'content-type'",
"]",
";",
"var",
"m",
"=",
"contentType",
"&&",
"contentType",
".",
"match",
"(",
"/",
"^multipart\\/form-data; boundary=(.+)$",
"/",
")",
";",
"if",
"(",
"m",
"&&",
"m",
"[",
"1",
"]",
")",
"{",
"parseMultipart",
"(",
"req",
",",
"m",
"[",
"1",
"]",
",",
"cb",
")",
";",
"}",
"else",
"{",
"parseSinglepart",
"(",
"req",
",",
"cb",
")",
";",
"}",
"}"
] |
Streams and parses an HTTP request by calling into parseSinglepart or parseMultipart.
@param {Object} req The HTTP request.
@param {Function} cb Callback on completion.
|
[
"Streams",
"and",
"parses",
"an",
"HTTP",
"request",
"by",
"calling",
"into",
"parseSinglepart",
"or",
"parseMultipart",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/commandCenter/httpBatchHandler.js#L282-L293
|
19,535
|
mage/mage
|
lib/archivist/index.js
|
mgetAggregate
|
function mgetAggregate(queries, options, retriever, cb) {
// queries: [{ topic: 'foo', index: { id: 1 } }, { topic: 'bar', index: { id: 'abc' } }]
// OR:
// queries: { uniqueID: { topic: 'foo', index: { id: 1 } }, uniqueID2: { etc }
const getQueryOptions = (query) => Object.assign({}, options, query.options);
const arrayQuery = () => async.mapSeries(queries, (query, callback) => {
retriever(query, getQueryOptions(query), callback);
}, cb);
function objectQuery() {
const queryIds = Object.keys(queries);
const result = {};
async.forEachSeries(
queryIds,
(queryId, callback) => {
const query = queries[queryId];
retriever(query, getQueryOptions(query), function (error, data) {
result[queryId] = data;
callback(error);
});
},
(error) => cb(error, error ? null : result)
);
}
if (Array.isArray(queries)) {
arrayQuery();
} else if (queries && typeof queries === 'object') {
objectQuery();
} else {
cb(new TypeError('mget queries must be an Array or an Object'));
}
}
|
javascript
|
function mgetAggregate(queries, options, retriever, cb) {
// queries: [{ topic: 'foo', index: { id: 1 } }, { topic: 'bar', index: { id: 'abc' } }]
// OR:
// queries: { uniqueID: { topic: 'foo', index: { id: 1 } }, uniqueID2: { etc }
const getQueryOptions = (query) => Object.assign({}, options, query.options);
const arrayQuery = () => async.mapSeries(queries, (query, callback) => {
retriever(query, getQueryOptions(query), callback);
}, cb);
function objectQuery() {
const queryIds = Object.keys(queries);
const result = {};
async.forEachSeries(
queryIds,
(queryId, callback) => {
const query = queries[queryId];
retriever(query, getQueryOptions(query), function (error, data) {
result[queryId] = data;
callback(error);
});
},
(error) => cb(error, error ? null : result)
);
}
if (Array.isArray(queries)) {
arrayQuery();
} else if (queries && typeof queries === 'object') {
objectQuery();
} else {
cb(new TypeError('mget queries must be an Array or an Object'));
}
}
|
[
"function",
"mgetAggregate",
"(",
"queries",
",",
"options",
",",
"retriever",
",",
"cb",
")",
"{",
"// queries: [{ topic: 'foo', index: { id: 1 } }, { topic: 'bar', index: { id: 'abc' } }]",
"// OR:",
"// queries: { uniqueID: { topic: 'foo', index: { id: 1 } }, uniqueID2: { etc }",
"const",
"getQueryOptions",
"=",
"(",
"query",
")",
"=>",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
",",
"query",
".",
"options",
")",
";",
"const",
"arrayQuery",
"=",
"(",
")",
"=>",
"async",
".",
"mapSeries",
"(",
"queries",
",",
"(",
"query",
",",
"callback",
")",
"=>",
"{",
"retriever",
"(",
"query",
",",
"getQueryOptions",
"(",
"query",
")",
",",
"callback",
")",
";",
"}",
",",
"cb",
")",
";",
"function",
"objectQuery",
"(",
")",
"{",
"const",
"queryIds",
"=",
"Object",
".",
"keys",
"(",
"queries",
")",
";",
"const",
"result",
"=",
"{",
"}",
";",
"async",
".",
"forEachSeries",
"(",
"queryIds",
",",
"(",
"queryId",
",",
"callback",
")",
"=>",
"{",
"const",
"query",
"=",
"queries",
"[",
"queryId",
"]",
";",
"retriever",
"(",
"query",
",",
"getQueryOptions",
"(",
"query",
")",
",",
"function",
"(",
"error",
",",
"data",
")",
"{",
"result",
"[",
"queryId",
"]",
"=",
"data",
";",
"callback",
"(",
"error",
")",
";",
"}",
")",
";",
"}",
",",
"(",
"error",
")",
"=>",
"cb",
"(",
"error",
",",
"error",
"?",
"null",
":",
"result",
")",
")",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"queries",
")",
")",
"{",
"arrayQuery",
"(",
")",
";",
"}",
"else",
"if",
"(",
"queries",
"&&",
"typeof",
"queries",
"===",
"'object'",
")",
"{",
"objectQuery",
"(",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"new",
"TypeError",
"(",
"'mget queries must be an Array or an Object'",
")",
")",
";",
"}",
"}"
] |
multiget helper function
|
[
"multiget",
"helper",
"function"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/index.js#L551-L587
|
19,536
|
mage/mage
|
lib/archivist/vaults/couchbase/index.js
|
wash
|
function wash(obj) {
if (!obj) {
return {};
}
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (obj[key] === undefined) {
delete obj[key];
}
}
return obj;
}
|
javascript
|
function wash(obj) {
if (!obj) {
return {};
}
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (obj[key] === undefined) {
delete obj[key];
}
}
return obj;
}
|
[
"function",
"wash",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"obj",
")",
"{",
"return",
"{",
"}",
";",
"}",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"if",
"(",
"obj",
"[",
"key",
"]",
"===",
"undefined",
")",
"{",
"delete",
"obj",
"[",
"key",
"]",
";",
"}",
"}",
"return",
"obj",
";",
"}"
] |
Removes properties that are undefined. That makes node-couchbase happy. Hopefully some day, they
won't be as strict with undefined.
@param {Object} obj
|
[
"Removes",
"properties",
"that",
"are",
"undefined",
".",
"That",
"makes",
"node",
"-",
"couchbase",
"happy",
".",
"Hopefully",
"some",
"day",
"they",
"won",
"t",
"be",
"as",
"strict",
"with",
"undefined",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/vaults/couchbase/index.js#L47-L62
|
19,537
|
mage/mage
|
lib/archivist/vaults/client/index.js
|
ClientVault
|
function ClientVault(name, logger) {
this.name = name;
this.archive = new Archive(this); // archivist bindings
this.state = null;
this.logger = logger;
}
|
javascript
|
function ClientVault(name, logger) {
this.name = name;
this.archive = new Archive(this); // archivist bindings
this.state = null;
this.logger = logger;
}
|
[
"function",
"ClientVault",
"(",
"name",
",",
"logger",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"archive",
"=",
"new",
"Archive",
"(",
"this",
")",
";",
"// archivist bindings",
"this",
".",
"state",
"=",
"null",
";",
"this",
".",
"logger",
"=",
"logger",
";",
"}"
] |
Vault wrapper around state.emit
|
[
"Vault",
"wrapper",
"around",
"state",
".",
"emit"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/vaults/client/index.js#L15-L21
|
19,538
|
mage/mage
|
lib/archivist/vaults/file/index.js
|
FileVault
|
function FileVault(name, logger) {
this.name = name;
this.archive = new Archive(this); // archivist bindings
this.allowExpire = true;
this.path = undefined;
this.logger = logger;
this._timers = {};
}
|
javascript
|
function FileVault(name, logger) {
this.name = name;
this.archive = new Archive(this); // archivist bindings
this.allowExpire = true;
this.path = undefined;
this.logger = logger;
this._timers = {};
}
|
[
"function",
"FileVault",
"(",
"name",
",",
"logger",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"archive",
"=",
"new",
"Archive",
"(",
"this",
")",
";",
"// archivist bindings",
"this",
".",
"allowExpire",
"=",
"true",
";",
"this",
".",
"path",
"=",
"undefined",
";",
"this",
".",
"logger",
"=",
"logger",
";",
"this",
".",
"_timers",
"=",
"{",
"}",
";",
"}"
] |
Vault wrapper around node's "fs" module
|
[
"Vault",
"wrapper",
"around",
"node",
"s",
"fs",
"module"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/vaults/file/index.js#L63-L71
|
19,539
|
mage/mage
|
lib/archivist/vaults/file/index.js
|
createKeyFolders
|
function createKeyFolders(key, fullPath, cb) {
// NOTE: We check after first character, since a leading slash will be omitted by path.join
if (key.indexOf(path.sep) <= 0) {
return cb();
}
mkdirp(path.dirname(fullPath), cb);
}
|
javascript
|
function createKeyFolders(key, fullPath, cb) {
// NOTE: We check after first character, since a leading slash will be omitted by path.join
if (key.indexOf(path.sep) <= 0) {
return cb();
}
mkdirp(path.dirname(fullPath), cb);
}
|
[
"function",
"createKeyFolders",
"(",
"key",
",",
"fullPath",
",",
"cb",
")",
"{",
"// NOTE: We check after first character, since a leading slash will be omitted by path.join",
"if",
"(",
"key",
".",
"indexOf",
"(",
"path",
".",
"sep",
")",
"<=",
"0",
")",
"{",
"return",
"cb",
"(",
")",
";",
"}",
"mkdirp",
"(",
"path",
".",
"dirname",
"(",
"fullPath",
")",
",",
"cb",
")",
";",
"}"
] |
Creates any subfolders we need for a given filevault key. If any errors occur during folder
creation an error is returned via the callback.
@param {String} key
@param {String} fullPath
@param {Function} cb
|
[
"Creates",
"any",
"subfolders",
"we",
"need",
"for",
"a",
"given",
"filevault",
"key",
".",
"If",
"any",
"errors",
"occur",
"during",
"folder",
"creation",
"an",
"error",
"is",
"returned",
"via",
"the",
"callback",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/archivist/vaults/file/index.js#L365-L372
|
19,540
|
mage/mage
|
lib/serviceDiscovery/engines/zookeeper/index.js
|
createZooKeeperClient
|
function createZooKeeperClient(options) {
options = options || {};
if (!options.hosts) {
throw new Error('Missing configuration server.discoveryService.options.hosts for ZooKeeper');
}
// client options, with better defaults than node-zookeeper-client provides
var clientOpts = options.options || {};
clientOpts.sessionTimeout = clientOpts.hasOwnProperty('sessionTimeout') ? clientOpts.sessionTimeout : 30000;
clientOpts.spinDelay = clientOpts.hasOwnProperty('spinDelay') ? clientOpts.spinDelay : 1000;
clientOpts.retries = clientOpts.hasOwnProperty('retries') ? clientOpts.retries : 3;
// connect to the database
var client = zooKeeper.createClient(options.hosts, clientOpts);
client.on('connected', function () {
logger.verbose('ZooKeeper connection established');
});
client.on('connectedReadOnly', function () {
logger.error('ZooKeeper connection established to a read-only server');
});
client.on('disconnected', function () {
logger.verbose('ZooKeeper connection dropped');
});
client.on('expired', function () {
logger.verbose('ZooKeeper client session expired');
});
client.on('authenticationFailed', function () {
logger.error('ZooKeeper authentication failed');
});
return client;
}
|
javascript
|
function createZooKeeperClient(options) {
options = options || {};
if (!options.hosts) {
throw new Error('Missing configuration server.discoveryService.options.hosts for ZooKeeper');
}
// client options, with better defaults than node-zookeeper-client provides
var clientOpts = options.options || {};
clientOpts.sessionTimeout = clientOpts.hasOwnProperty('sessionTimeout') ? clientOpts.sessionTimeout : 30000;
clientOpts.spinDelay = clientOpts.hasOwnProperty('spinDelay') ? clientOpts.spinDelay : 1000;
clientOpts.retries = clientOpts.hasOwnProperty('retries') ? clientOpts.retries : 3;
// connect to the database
var client = zooKeeper.createClient(options.hosts, clientOpts);
client.on('connected', function () {
logger.verbose('ZooKeeper connection established');
});
client.on('connectedReadOnly', function () {
logger.error('ZooKeeper connection established to a read-only server');
});
client.on('disconnected', function () {
logger.verbose('ZooKeeper connection dropped');
});
client.on('expired', function () {
logger.verbose('ZooKeeper client session expired');
});
client.on('authenticationFailed', function () {
logger.error('ZooKeeper authentication failed');
});
return client;
}
|
[
"function",
"createZooKeeperClient",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"options",
".",
"hosts",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing configuration server.discoveryService.options.hosts for ZooKeeper'",
")",
";",
"}",
"// client options, with better defaults than node-zookeeper-client provides",
"var",
"clientOpts",
"=",
"options",
".",
"options",
"||",
"{",
"}",
";",
"clientOpts",
".",
"sessionTimeout",
"=",
"clientOpts",
".",
"hasOwnProperty",
"(",
"'sessionTimeout'",
")",
"?",
"clientOpts",
".",
"sessionTimeout",
":",
"30000",
";",
"clientOpts",
".",
"spinDelay",
"=",
"clientOpts",
".",
"hasOwnProperty",
"(",
"'spinDelay'",
")",
"?",
"clientOpts",
".",
"spinDelay",
":",
"1000",
";",
"clientOpts",
".",
"retries",
"=",
"clientOpts",
".",
"hasOwnProperty",
"(",
"'retries'",
")",
"?",
"clientOpts",
".",
"retries",
":",
"3",
";",
"// connect to the database",
"var",
"client",
"=",
"zooKeeper",
".",
"createClient",
"(",
"options",
".",
"hosts",
",",
"clientOpts",
")",
";",
"client",
".",
"on",
"(",
"'connected'",
",",
"function",
"(",
")",
"{",
"logger",
".",
"verbose",
"(",
"'ZooKeeper connection established'",
")",
";",
"}",
")",
";",
"client",
".",
"on",
"(",
"'connectedReadOnly'",
",",
"function",
"(",
")",
"{",
"logger",
".",
"error",
"(",
"'ZooKeeper connection established to a read-only server'",
")",
";",
"}",
")",
";",
"client",
".",
"on",
"(",
"'disconnected'",
",",
"function",
"(",
")",
"{",
"logger",
".",
"verbose",
"(",
"'ZooKeeper connection dropped'",
")",
";",
"}",
")",
";",
"client",
".",
"on",
"(",
"'expired'",
",",
"function",
"(",
")",
"{",
"logger",
".",
"verbose",
"(",
"'ZooKeeper client session expired'",
")",
";",
"}",
")",
";",
"client",
".",
"on",
"(",
"'authenticationFailed'",
",",
"function",
"(",
")",
"{",
"logger",
".",
"error",
"(",
"'ZooKeeper authentication failed'",
")",
";",
"}",
")",
";",
"return",
"client",
";",
"}"
] |
Creates a zookeeper client, sets up relevant event listeners and connects.
@param {Object} options
@returns {zooKeeper.client}
|
[
"Creates",
"a",
"zookeeper",
"client",
"sets",
"up",
"relevant",
"event",
"listeners",
"and",
"connects",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/serviceDiscovery/engines/zookeeper/index.js#L18-L58
|
19,541
|
mage/mage
|
lib/serviceDiscovery/engines/zookeeper/index.js
|
ZooKeeperService
|
function ZooKeeperService(name, type, options) {
this.name = name;
this.type = type;
this.options = options;
this.closed = false;
this.announcing = false;
this.discovering = false;
// this is the base path we will use to announce this service
this.baseAnnouncePath = ['/mage', this.name, this.type].join('/');
// those are the nodes we know on the given path
this.nodes = [];
// node data is stored apart
this.services = {};
this.connectTimer = null;
this.clearCredentialsTimer = null;
// Initial setup
this.reset();
}
|
javascript
|
function ZooKeeperService(name, type, options) {
this.name = name;
this.type = type;
this.options = options;
this.closed = false;
this.announcing = false;
this.discovering = false;
// this is the base path we will use to announce this service
this.baseAnnouncePath = ['/mage', this.name, this.type].join('/');
// those are the nodes we know on the given path
this.nodes = [];
// node data is stored apart
this.services = {};
this.connectTimer = null;
this.clearCredentialsTimer = null;
// Initial setup
this.reset();
}
|
[
"function",
"ZooKeeperService",
"(",
"name",
",",
"type",
",",
"options",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"type",
"=",
"type",
";",
"this",
".",
"options",
"=",
"options",
";",
"this",
".",
"closed",
"=",
"false",
";",
"this",
".",
"announcing",
"=",
"false",
";",
"this",
".",
"discovering",
"=",
"false",
";",
"// this is the base path we will use to announce this service",
"this",
".",
"baseAnnouncePath",
"=",
"[",
"'/mage'",
",",
"this",
".",
"name",
",",
"this",
".",
"type",
"]",
".",
"join",
"(",
"'/'",
")",
";",
"// those are the nodes we know on the given path",
"this",
".",
"nodes",
"=",
"[",
"]",
";",
"// node data is stored apart",
"this",
".",
"services",
"=",
"{",
"}",
";",
"this",
".",
"connectTimer",
"=",
"null",
";",
"this",
".",
"clearCredentialsTimer",
"=",
"null",
";",
"// Initial setup",
"this",
".",
"reset",
"(",
")",
";",
"}"
] |
This is our service instance for zookeeper
@param {string} name The name of the service we want to announce
@param {string} type The type of service (tcp or udp)
@param {Object} options The options to provide to the service
@constructor
|
[
"This",
"is",
"our",
"service",
"instance",
"for",
"zookeeper"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/serviceDiscovery/engines/zookeeper/index.js#L68-L91
|
19,542
|
mage/mage
|
lib/msgServer/store/index.js
|
Store
|
function Store() {
this.cache = new LocalStash(30);
this.ttl = getTTL();
this._forward = function () {
logger.error('No forwarder defined');
};
logger.verbose('Messages will expire after', this.ttl, 'seconds.');
}
|
javascript
|
function Store() {
this.cache = new LocalStash(30);
this.ttl = getTTL();
this._forward = function () {
logger.error('No forwarder defined');
};
logger.verbose('Messages will expire after', this.ttl, 'seconds.');
}
|
[
"function",
"Store",
"(",
")",
"{",
"this",
".",
"cache",
"=",
"new",
"LocalStash",
"(",
"30",
")",
";",
"this",
".",
"ttl",
"=",
"getTTL",
"(",
")",
";",
"this",
".",
"_forward",
"=",
"function",
"(",
")",
"{",
"logger",
".",
"error",
"(",
"'No forwarder defined'",
")",
";",
"}",
";",
"logger",
".",
"verbose",
"(",
"'Messages will expire after'",
",",
"this",
".",
"ttl",
",",
"'seconds.'",
")",
";",
"}"
] |
The Message Store
@constructor
|
[
"The",
"Message",
"Store"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/msgServer/store/index.js#L35-L44
|
19,543
|
mage/mage
|
lib/httpServer/transports/http/proxy.js
|
proxy
|
function proxy(req, endpoint) {
var source = req.connection;
var target;
source.pause();
target = net.connect(endpoint, function proxyHandler() {
// the header has already been consumed, so we must recreate it and send it first
target.write(recreateRequestHeader(req));
target.pipe(source);
source.pipe(target);
source.resume();
});
target.setTimeout(0);
target.setNoDelay(true);
target.setKeepAlive(true, 0);
return target;
}
|
javascript
|
function proxy(req, endpoint) {
var source = req.connection;
var target;
source.pause();
target = net.connect(endpoint, function proxyHandler() {
// the header has already been consumed, so we must recreate it and send it first
target.write(recreateRequestHeader(req));
target.pipe(source);
source.pipe(target);
source.resume();
});
target.setTimeout(0);
target.setNoDelay(true);
target.setKeepAlive(true, 0);
return target;
}
|
[
"function",
"proxy",
"(",
"req",
",",
"endpoint",
")",
"{",
"var",
"source",
"=",
"req",
".",
"connection",
";",
"var",
"target",
";",
"source",
".",
"pause",
"(",
")",
";",
"target",
"=",
"net",
".",
"connect",
"(",
"endpoint",
",",
"function",
"proxyHandler",
"(",
")",
"{",
"// the header has already been consumed, so we must recreate it and send it first",
"target",
".",
"write",
"(",
"recreateRequestHeader",
"(",
"req",
")",
")",
";",
"target",
".",
"pipe",
"(",
"source",
")",
";",
"source",
".",
"pipe",
"(",
"target",
")",
";",
"source",
".",
"resume",
"(",
")",
";",
"}",
")",
";",
"target",
".",
"setTimeout",
"(",
"0",
")",
";",
"target",
".",
"setNoDelay",
"(",
"true",
")",
";",
"target",
".",
"setKeepAlive",
"(",
"true",
",",
"0",
")",
";",
"return",
"target",
";",
"}"
] |
A proxy function to route connections from one HTTP server to another
@param {Object} req The HTTP client request.
|
[
"A",
"proxy",
"function",
"to",
"route",
"connections",
"from",
"one",
"HTTP",
"server",
"to",
"another"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/httpServer/transports/http/proxy.js#L35-L57
|
19,544
|
mage/mage
|
lib/processMessenger/index.js
|
Messenger
|
function Messenger(namespace) {
assert(namespace, 'A namespace is required to use the process messenger.');
assert(Object.prototype.toString.call(namespace) === '[object String]',
'The namespace must be a string.');
this.namespace = namespace;
this.setupWorker();
this.setupMaster();
}
|
javascript
|
function Messenger(namespace) {
assert(namespace, 'A namespace is required to use the process messenger.');
assert(Object.prototype.toString.call(namespace) === '[object String]',
'The namespace must be a string.');
this.namespace = namespace;
this.setupWorker();
this.setupMaster();
}
|
[
"function",
"Messenger",
"(",
"namespace",
")",
"{",
"assert",
"(",
"namespace",
",",
"'A namespace is required to use the process messenger.'",
")",
";",
"assert",
"(",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"namespace",
")",
"===",
"'[object String]'",
",",
"'The namespace must be a string.'",
")",
";",
"this",
".",
"namespace",
"=",
"namespace",
";",
"this",
".",
"setupWorker",
"(",
")",
";",
"this",
".",
"setupMaster",
"(",
")",
";",
"}"
] |
Create a new process messenger.
@param {string} namespace The namespace used by this messenger.
@constructor
|
[
"Create",
"a",
"new",
"process",
"messenger",
"."
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/processMessenger/index.js#L12-L22
|
19,545
|
mage/mage
|
lib/processMessenger/index.js
|
bindMessageListener
|
function bindMessageListener(worker) {
worker.on('message', function (msg) {
// Ignore the message if it doesn't belong to the namespace
if (msg.namespace !== that.namespace) {
return;
}
// If the address is '*', it's a broadcast message
// Send the message to all the workers
if (msg.to === '*') {
that.broadcast(msg.name, msg.data, msg.from);
}
// If the address is 'master', emit an event with the message details
// If the message is a broadcast message, it should also emit an event
if (msg.to === 'master' || msg.to === '*') {
that.emit(msg.name, msg.data, msg.from);
return;
}
// If the master is not the recipient, forward the message
that.send(msg.to, msg.name, msg.data, msg.from);
});
}
|
javascript
|
function bindMessageListener(worker) {
worker.on('message', function (msg) {
// Ignore the message if it doesn't belong to the namespace
if (msg.namespace !== that.namespace) {
return;
}
// If the address is '*', it's a broadcast message
// Send the message to all the workers
if (msg.to === '*') {
that.broadcast(msg.name, msg.data, msg.from);
}
// If the address is 'master', emit an event with the message details
// If the message is a broadcast message, it should also emit an event
if (msg.to === 'master' || msg.to === '*') {
that.emit(msg.name, msg.data, msg.from);
return;
}
// If the master is not the recipient, forward the message
that.send(msg.to, msg.name, msg.data, msg.from);
});
}
|
[
"function",
"bindMessageListener",
"(",
"worker",
")",
"{",
"worker",
".",
"on",
"(",
"'message'",
",",
"function",
"(",
"msg",
")",
"{",
"// Ignore the message if it doesn't belong to the namespace",
"if",
"(",
"msg",
".",
"namespace",
"!==",
"that",
".",
"namespace",
")",
"{",
"return",
";",
"}",
"// If the address is '*', it's a broadcast message",
"// Send the message to all the workers",
"if",
"(",
"msg",
".",
"to",
"===",
"'*'",
")",
"{",
"that",
".",
"broadcast",
"(",
"msg",
".",
"name",
",",
"msg",
".",
"data",
",",
"msg",
".",
"from",
")",
";",
"}",
"// If the address is 'master', emit an event with the message details",
"// If the message is a broadcast message, it should also emit an event",
"if",
"(",
"msg",
".",
"to",
"===",
"'master'",
"||",
"msg",
".",
"to",
"===",
"'*'",
")",
"{",
"that",
".",
"emit",
"(",
"msg",
".",
"name",
",",
"msg",
".",
"data",
",",
"msg",
".",
"from",
")",
";",
"return",
";",
"}",
"// If the master is not the recipient, forward the message",
"that",
".",
"send",
"(",
"msg",
".",
"to",
",",
"msg",
".",
"name",
",",
"msg",
".",
"data",
",",
"msg",
".",
"from",
")",
";",
"}",
")",
";",
"}"
] |
Add a listener to process the message received from the specified worker
|
[
"Add",
"a",
"listener",
"to",
"process",
"the",
"message",
"received",
"from",
"the",
"specified",
"worker"
] |
617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9
|
https://github.com/mage/mage/blob/617968b6b9ebfa5371ae7e9115a5d1e0733a0ff9/lib/processMessenger/index.js#L64-L87
|
19,546
|
mesqueeb/vuex-easy-access
|
dist/index.cjs.js
|
getIdsFromPayload
|
function getIdsFromPayload(payload, conf, path) {
return payload.map(function (payloadPiece) { return getId(payloadPiece, conf, path, payload); });
}
|
javascript
|
function getIdsFromPayload(payload, conf, path) {
return payload.map(function (payloadPiece) { return getId(payloadPiece, conf, path, payload); });
}
|
[
"function",
"getIdsFromPayload",
"(",
"payload",
",",
"conf",
",",
"path",
")",
"{",
"return",
"payload",
".",
"map",
"(",
"function",
"(",
"payloadPiece",
")",
"{",
"return",
"getId",
"(",
"payloadPiece",
",",
"conf",
",",
"path",
",",
"payload",
")",
";",
"}",
")",
";",
"}"
] |
Get all ids from an array payload.
@param {any[]} payload
@param {object} [conf] (optional - for error handling) the vuex-easy-access config
@param {string} [path] (optional - for error handling) the path called
@returns {string[]} all ids
|
[
"Get",
"all",
"ids",
"from",
"an",
"array",
"payload",
"."
] |
68a94b4a9732e196b5bd63592980a92653455169
|
https://github.com/mesqueeb/vuex-easy-access/blob/68a94b4a9732e196b5bd63592980a92653455169/dist/index.cjs.js#L90-L92
|
19,547
|
mesqueeb/vuex-easy-access
|
dist/index.cjs.js
|
setDeepValue
|
function setDeepValue(target, path, value) {
var keys = getKeysFromPath(path);
var lastKey = keys.pop();
var deepRef = getDeepRef(target, keys.join('.'));
if (deepRef && deepRef.hasOwnProperty(lastKey)) {
deepRef[lastKey] = value;
}
return target;
}
|
javascript
|
function setDeepValue(target, path, value) {
var keys = getKeysFromPath(path);
var lastKey = keys.pop();
var deepRef = getDeepRef(target, keys.join('.'));
if (deepRef && deepRef.hasOwnProperty(lastKey)) {
deepRef[lastKey] = value;
}
return target;
}
|
[
"function",
"setDeepValue",
"(",
"target",
",",
"path",
",",
"value",
")",
"{",
"var",
"keys",
"=",
"getKeysFromPath",
"(",
"path",
")",
";",
"var",
"lastKey",
"=",
"keys",
".",
"pop",
"(",
")",
";",
"var",
"deepRef",
"=",
"getDeepRef",
"(",
"target",
",",
"keys",
".",
"join",
"(",
"'.'",
")",
")",
";",
"if",
"(",
"deepRef",
"&&",
"deepRef",
".",
"hasOwnProperty",
"(",
"lastKey",
")",
")",
"{",
"deepRef",
"[",
"lastKey",
"]",
"=",
"value",
";",
"}",
"return",
"target",
";",
"}"
] |
Sets a value to a deep property in an object, based on a path to that property
@param {object} target the Object to set the value on
@param {string} path 'path/to/prop.subprop'
@param {*} value the value to set
@returns {AnyObject} the original target object
|
[
"Sets",
"a",
"value",
"to",
"a",
"deep",
"property",
"in",
"an",
"object",
"based",
"on",
"a",
"path",
"to",
"that",
"property"
] |
68a94b4a9732e196b5bd63592980a92653455169
|
https://github.com/mesqueeb/vuex-easy-access/blob/68a94b4a9732e196b5bd63592980a92653455169/dist/index.cjs.js#L267-L275
|
19,548
|
mesqueeb/vuex-easy-access
|
dist/index.cjs.js
|
pushDeepValue
|
function pushDeepValue(target, path, value) {
var deepRef = getDeepRef(target, path);
if (!isWhat.isArray(deepRef))
return;
return deepRef.push(value);
}
|
javascript
|
function pushDeepValue(target, path, value) {
var deepRef = getDeepRef(target, path);
if (!isWhat.isArray(deepRef))
return;
return deepRef.push(value);
}
|
[
"function",
"pushDeepValue",
"(",
"target",
",",
"path",
",",
"value",
")",
"{",
"var",
"deepRef",
"=",
"getDeepRef",
"(",
"target",
",",
"path",
")",
";",
"if",
"(",
"!",
"isWhat",
".",
"isArray",
"(",
"deepRef",
")",
")",
"return",
";",
"return",
"deepRef",
".",
"push",
"(",
"value",
")",
";",
"}"
] |
Pushes a value in an array which is a deep property in an object, based on a path to that property
@param {object} target the Object to push the value on
@param {string} path 'path/to.sub.prop'
@param {*} value the value to push
@returns {number} the new length of the array
|
[
"Pushes",
"a",
"value",
"in",
"an",
"array",
"which",
"is",
"a",
"deep",
"property",
"in",
"an",
"object",
"based",
"on",
"a",
"path",
"to",
"that",
"property"
] |
68a94b4a9732e196b5bd63592980a92653455169
|
https://github.com/mesqueeb/vuex-easy-access/blob/68a94b4a9732e196b5bd63592980a92653455169/dist/index.cjs.js#L284-L289
|
19,549
|
mesqueeb/vuex-easy-access
|
dist/index.cjs.js
|
popDeepValue
|
function popDeepValue(target, path) {
var deepRef = getDeepRef(target, path);
if (!isWhat.isArray(deepRef))
return;
return deepRef.pop();
}
|
javascript
|
function popDeepValue(target, path) {
var deepRef = getDeepRef(target, path);
if (!isWhat.isArray(deepRef))
return;
return deepRef.pop();
}
|
[
"function",
"popDeepValue",
"(",
"target",
",",
"path",
")",
"{",
"var",
"deepRef",
"=",
"getDeepRef",
"(",
"target",
",",
"path",
")",
";",
"if",
"(",
"!",
"isWhat",
".",
"isArray",
"(",
"deepRef",
")",
")",
"return",
";",
"return",
"deepRef",
".",
"pop",
"(",
")",
";",
"}"
] |
Pops a value of an array which is a deep property in an object, based on a path to that property
@param {object} target the Object to pop the value of
@param {string} path 'path.to.sub.prop'
@returns {*} the popped value
|
[
"Pops",
"a",
"value",
"of",
"an",
"array",
"which",
"is",
"a",
"deep",
"property",
"in",
"an",
"object",
"based",
"on",
"a",
"path",
"to",
"that",
"property"
] |
68a94b4a9732e196b5bd63592980a92653455169
|
https://github.com/mesqueeb/vuex-easy-access/blob/68a94b4a9732e196b5bd63592980a92653455169/dist/index.cjs.js#L297-L302
|
19,550
|
mesqueeb/vuex-easy-access
|
dist/index.esm.js
|
shiftDeepValue
|
function shiftDeepValue(target, path) {
var deepRef = getDeepRef(target, path);
if (!isArray(deepRef))
return;
return deepRef.shift();
}
|
javascript
|
function shiftDeepValue(target, path) {
var deepRef = getDeepRef(target, path);
if (!isArray(deepRef))
return;
return deepRef.shift();
}
|
[
"function",
"shiftDeepValue",
"(",
"target",
",",
"path",
")",
"{",
"var",
"deepRef",
"=",
"getDeepRef",
"(",
"target",
",",
"path",
")",
";",
"if",
"(",
"!",
"isArray",
"(",
"deepRef",
")",
")",
"return",
";",
"return",
"deepRef",
".",
"shift",
"(",
")",
";",
"}"
] |
Shift a value of an array which is a deep property in an object, based on a path to that property
@param {object} target the Object to shift the value of
@param {string} path 'path.to.sub.prop'
@returns {*} the shifted value
|
[
"Shift",
"a",
"value",
"of",
"an",
"array",
"which",
"is",
"a",
"deep",
"property",
"in",
"an",
"object",
"based",
"on",
"a",
"path",
"to",
"that",
"property"
] |
68a94b4a9732e196b5bd63592980a92653455169
|
https://github.com/mesqueeb/vuex-easy-access/blob/68a94b4a9732e196b5bd63592980a92653455169/dist/index.esm.js#L304-L309
|
19,551
|
mesqueeb/vuex-easy-access
|
dist/index.es.js
|
getId
|
function getId(payloadPiece, conf, path, fullPayload) {
if (isObject(payloadPiece)) {
if (payloadPiece.id) return payloadPiece.id;
if (Object.keys(payloadPiece).length === 1) return Object.keys(payloadPiece)[0];
}
if (isString(payloadPiece)) return payloadPiece;
error('wildcardFormatWrong', conf, path, payloadPiece);
return false;
}
|
javascript
|
function getId(payloadPiece, conf, path, fullPayload) {
if (isObject(payloadPiece)) {
if (payloadPiece.id) return payloadPiece.id;
if (Object.keys(payloadPiece).length === 1) return Object.keys(payloadPiece)[0];
}
if (isString(payloadPiece)) return payloadPiece;
error('wildcardFormatWrong', conf, path, payloadPiece);
return false;
}
|
[
"function",
"getId",
"(",
"payloadPiece",
",",
"conf",
",",
"path",
",",
"fullPayload",
")",
"{",
"if",
"(",
"isObject",
"(",
"payloadPiece",
")",
")",
"{",
"if",
"(",
"payloadPiece",
".",
"id",
")",
"return",
"payloadPiece",
".",
"id",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"payloadPiece",
")",
".",
"length",
"===",
"1",
")",
"return",
"Object",
".",
"keys",
"(",
"payloadPiece",
")",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"isString",
"(",
"payloadPiece",
")",
")",
"return",
"payloadPiece",
";",
"error",
"(",
"'wildcardFormatWrong'",
",",
"conf",
",",
"path",
",",
"payloadPiece",
")",
";",
"return",
"false",
";",
"}"
] |
gets an ID from a single piece of payload.
@param {object, string} payload
@param {object} conf (optional - for error handling) the vuex-easy-access config
@param {string} path (optional - for error handling) the path called
@param {array|object|string} fullPayload (optional - for error handling) the full payload on which each was `getId()` called
@returns {string} the id
|
[
"gets",
"an",
"ID",
"from",
"a",
"single",
"piece",
"of",
"payload",
"."
] |
68a94b4a9732e196b5bd63592980a92653455169
|
https://github.com/mesqueeb/vuex-easy-access/blob/68a94b4a9732e196b5bd63592980a92653455169/dist/index.es.js#L90-L99
|
19,552
|
mesqueeb/vuex-easy-access
|
dist/index.es.js
|
checkIdWildcardRatio
|
function checkIdWildcardRatio(ids, path, conf) {
var match = path.match(/\*/g);
var idCount = isArray(match) ? match.length : 0;
if (ids.length === idCount) return true;
error('mutationSetterPropPathWildcardIdCount', conf);
return false;
}
|
javascript
|
function checkIdWildcardRatio(ids, path, conf) {
var match = path.match(/\*/g);
var idCount = isArray(match) ? match.length : 0;
if (ids.length === idCount) return true;
error('mutationSetterPropPathWildcardIdCount', conf);
return false;
}
|
[
"function",
"checkIdWildcardRatio",
"(",
"ids",
",",
"path",
",",
"conf",
")",
"{",
"var",
"match",
"=",
"path",
".",
"match",
"(",
"/",
"\\*",
"/",
"g",
")",
";",
"var",
"idCount",
"=",
"isArray",
"(",
"match",
")",
"?",
"match",
".",
"length",
":",
"0",
";",
"if",
"(",
"ids",
".",
"length",
"===",
"idCount",
")",
"return",
"true",
";",
"error",
"(",
"'mutationSetterPropPathWildcardIdCount'",
",",
"conf",
")",
";",
"return",
"false",
";",
"}"
] |
Checks the ratio between an array of IDs and a path with wildcards
@param {array} ids
@param {string} path
@param {object} conf (optional - for error handling) the vuex-easy-access config
@returns {Bool} true if no problem. false if the ratio is incorrect
|
[
"Checks",
"the",
"ratio",
"between",
"an",
"array",
"of",
"IDs",
"and",
"a",
"path",
"with",
"wildcards"
] |
68a94b4a9732e196b5bd63592980a92653455169
|
https://github.com/mesqueeb/vuex-easy-access/blob/68a94b4a9732e196b5bd63592980a92653455169/dist/index.es.js#L138-L144
|
19,553
|
mesqueeb/vuex-easy-access
|
dist/index.es.js
|
getDeepRef
|
function getDeepRef() {
var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var path = arguments.length > 1 ? arguments[1] : undefined;
var keys = getKeysFromPath(path);
if (!keys.length) return target;
var obj = target;
while (obj && keys.length > 1) {
obj = obj[keys.shift()];
}
var key = keys.shift();
if (obj && obj.hasOwnProperty(key)) {
return obj[key];
}
}
|
javascript
|
function getDeepRef() {
var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var path = arguments.length > 1 ? arguments[1] : undefined;
var keys = getKeysFromPath(path);
if (!keys.length) return target;
var obj = target;
while (obj && keys.length > 1) {
obj = obj[keys.shift()];
}
var key = keys.shift();
if (obj && obj.hasOwnProperty(key)) {
return obj[key];
}
}
|
[
"function",
"getDeepRef",
"(",
")",
"{",
"var",
"target",
"=",
"arguments",
".",
"length",
">",
"0",
"&&",
"arguments",
"[",
"0",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"0",
"]",
":",
"{",
"}",
";",
"var",
"path",
"=",
"arguments",
".",
"length",
">",
"1",
"?",
"arguments",
"[",
"1",
"]",
":",
"undefined",
";",
"var",
"keys",
"=",
"getKeysFromPath",
"(",
"path",
")",
";",
"if",
"(",
"!",
"keys",
".",
"length",
")",
"return",
"target",
";",
"var",
"obj",
"=",
"target",
";",
"while",
"(",
"obj",
"&&",
"keys",
".",
"length",
">",
"1",
")",
"{",
"obj",
"=",
"obj",
"[",
"keys",
".",
"shift",
"(",
")",
"]",
";",
"}",
"var",
"key",
"=",
"keys",
".",
"shift",
"(",
")",
";",
"if",
"(",
"obj",
"&&",
"obj",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"return",
"obj",
"[",
"key",
"]",
";",
"}",
"}"
] |
Gets a deep property in an object, based on a path to that property
@param {object} target an object to wherefrom to retrieve the deep reference of
@param {string} path 'path/to.prop'
@returns {object} the last prop in the path
|
[
"Gets",
"a",
"deep",
"property",
"in",
"an",
"object",
"based",
"on",
"a",
"path",
"to",
"that",
"property"
] |
68a94b4a9732e196b5bd63592980a92653455169
|
https://github.com/mesqueeb/vuex-easy-access/blob/68a94b4a9732e196b5bd63592980a92653455169/dist/index.es.js#L246-L262
|
19,554
|
Siilwyn/css-declaration-sorter
|
src/index.js
|
sortCssDecls
|
function sortCssDecls (cssDecls, sortOrder) {
if (sortOrder === 'alphabetically') {
timsort(cssDecls, (a, b) => {
if (a.type === 'decl' && b.type === 'decl') {
return comparator(a.prop, b.prop);
} else {
return compareDifferentType(a, b);
}
});
} else {
timsort(cssDecls, (a, b) => {
if (a.type === 'decl' && b.type === 'decl') {
const aIndex = sortOrder.indexOf(a.prop);
const bIndex = sortOrder.indexOf(b.prop);
return comparator(aIndex, bIndex);
} else {
return compareDifferentType(a, b);
}
});
}
}
|
javascript
|
function sortCssDecls (cssDecls, sortOrder) {
if (sortOrder === 'alphabetically') {
timsort(cssDecls, (a, b) => {
if (a.type === 'decl' && b.type === 'decl') {
return comparator(a.prop, b.prop);
} else {
return compareDifferentType(a, b);
}
});
} else {
timsort(cssDecls, (a, b) => {
if (a.type === 'decl' && b.type === 'decl') {
const aIndex = sortOrder.indexOf(a.prop);
const bIndex = sortOrder.indexOf(b.prop);
return comparator(aIndex, bIndex);
} else {
return compareDifferentType(a, b);
}
});
}
}
|
[
"function",
"sortCssDecls",
"(",
"cssDecls",
",",
"sortOrder",
")",
"{",
"if",
"(",
"sortOrder",
"===",
"'alphabetically'",
")",
"{",
"timsort",
"(",
"cssDecls",
",",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"if",
"(",
"a",
".",
"type",
"===",
"'decl'",
"&&",
"b",
".",
"type",
"===",
"'decl'",
")",
"{",
"return",
"comparator",
"(",
"a",
".",
"prop",
",",
"b",
".",
"prop",
")",
";",
"}",
"else",
"{",
"return",
"compareDifferentType",
"(",
"a",
",",
"b",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"timsort",
"(",
"cssDecls",
",",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"if",
"(",
"a",
".",
"type",
"===",
"'decl'",
"&&",
"b",
".",
"type",
"===",
"'decl'",
")",
"{",
"const",
"aIndex",
"=",
"sortOrder",
".",
"indexOf",
"(",
"a",
".",
"prop",
")",
";",
"const",
"bIndex",
"=",
"sortOrder",
".",
"indexOf",
"(",
"b",
".",
"prop",
")",
";",
"return",
"comparator",
"(",
"aIndex",
",",
"bIndex",
")",
";",
"}",
"else",
"{",
"return",
"compareDifferentType",
"(",
"a",
",",
"b",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] |
Sort CSS declarations alphabetically or using the set sorting order
|
[
"Sort",
"CSS",
"declarations",
"alphabetically",
"or",
"using",
"the",
"set",
"sorting",
"order"
] |
d4cc3173bef031b303102b0f3ff239561214e97e
|
https://github.com/Siilwyn/css-declaration-sorter/blob/d4cc3173bef031b303102b0f3ff239561214e97e/src/index.js#L97-L117
|
19,555
|
mblarsen/mongoose-hidden
|
lib/mongoose-hidden.js
|
shouldHide
|
function shouldHide(schema, options, target, doc, transformed, pathname) {
let hideTarget = hide + target
// Is hiding turned off?
if (options[hideTarget] === false) {
return false
}
// Test hide by option or schema
return (
testOptions(options, pathname)
|| testSchema(schema, hide, doc, transformed)
|| testSchema(schema, hideTarget, doc, transformed)
)
}
|
javascript
|
function shouldHide(schema, options, target, doc, transformed, pathname) {
let hideTarget = hide + target
// Is hiding turned off?
if (options[hideTarget] === false) {
return false
}
// Test hide by option or schema
return (
testOptions(options, pathname)
|| testSchema(schema, hide, doc, transformed)
|| testSchema(schema, hideTarget, doc, transformed)
)
}
|
[
"function",
"shouldHide",
"(",
"schema",
",",
"options",
",",
"target",
",",
"doc",
",",
"transformed",
",",
"pathname",
")",
"{",
"let",
"hideTarget",
"=",
"hide",
"+",
"target",
"// Is hiding turned off?",
"if",
"(",
"options",
"[",
"hideTarget",
"]",
"===",
"false",
")",
"{",
"return",
"false",
"}",
"// Test hide by option or schema",
"return",
"(",
"testOptions",
"(",
"options",
",",
"pathname",
")",
"||",
"testSchema",
"(",
"schema",
",",
"hide",
",",
"doc",
",",
"transformed",
")",
"||",
"testSchema",
"(",
"schema",
",",
"hideTarget",
",",
"doc",
",",
"transformed",
")",
")",
"}"
] |
Should a property be hidden er not
@access private
@param {Schema} schema a mongoose schema
@param {object} options a set of options
@param {string} target the target to test, e.g 'JSON'
@param {object} doc original document
@param {object} transformed transformed document
@param {string} pathname property path
@returns {Boolen} true of pathname should be hidden
|
[
"Should",
"a",
"property",
"be",
"hidden",
"er",
"not"
] |
be1e93df9621b4f30f15738cc9d5820b2efa4ca5
|
https://github.com/mblarsen/mongoose-hidden/blob/be1e93df9621b4f30f15738cc9d5820b2efa4ca5/lib/mongoose-hidden.js#L58-L72
|
19,556
|
mblarsen/mongoose-hidden
|
lib/mongoose-hidden.js
|
shouldCopyVirtual
|
function shouldCopyVirtual(schema, key, options, target) {
return (
schema.pathType(key) === 'virtual'
&& [hide, `hide${target}`].indexOf(options.virtuals[key]) === -1
)
}
|
javascript
|
function shouldCopyVirtual(schema, key, options, target) {
return (
schema.pathType(key) === 'virtual'
&& [hide, `hide${target}`].indexOf(options.virtuals[key]) === -1
)
}
|
[
"function",
"shouldCopyVirtual",
"(",
"schema",
",",
"key",
",",
"options",
",",
"target",
")",
"{",
"return",
"(",
"schema",
".",
"pathType",
"(",
"key",
")",
"===",
"'virtual'",
"&&",
"[",
"hide",
",",
"`",
"${",
"target",
"}",
"`",
"]",
".",
"indexOf",
"(",
"options",
".",
"virtuals",
"[",
"key",
"]",
")",
"===",
"-",
"1",
")",
"}"
] |
Should a virtual property by be hidden er not
@access private
@param {Schema} schema a mongoose schema
@param {string} key object key name
@param {object} options a set of options
@param {string} target the target to test, e.g 'JSON'
@returns {Boolen} true of pathname should be hidden
|
[
"Should",
"a",
"virtual",
"property",
"by",
"be",
"hidden",
"er",
"not"
] |
be1e93df9621b4f30f15738cc9d5820b2efa4ca5
|
https://github.com/mblarsen/mongoose-hidden/blob/be1e93df9621b4f30f15738cc9d5820b2efa4ca5/lib/mongoose-hidden.js#L84-L89
|
19,557
|
mblarsen/mongoose-hidden
|
lib/mongoose-hidden.js
|
pathsFromTree
|
function pathsFromTree(obj, parentPath) {
if (Array.isArray(obj)) {
return parentPath
}
if (typeof obj === 'object' && obj.constructor.name === 'VirtualType') {
return obj.path
}
if (obj.constructor.name === 'Schema') {
obj = obj.tree
}
return Object.keys(obj).reduce((paths, key) => {
if (typeof obj[key] !== 'object' || typeof obj[key].type !== 'undefined') {
paths.push(joinKey(parentPath, key))
return paths
}
return [].concat(paths, pathsFromTree(obj[key], joinKey(parentPath, key)))
}, [])
}
|
javascript
|
function pathsFromTree(obj, parentPath) {
if (Array.isArray(obj)) {
return parentPath
}
if (typeof obj === 'object' && obj.constructor.name === 'VirtualType') {
return obj.path
}
if (obj.constructor.name === 'Schema') {
obj = obj.tree
}
return Object.keys(obj).reduce((paths, key) => {
if (typeof obj[key] !== 'object' || typeof obj[key].type !== 'undefined') {
paths.push(joinKey(parentPath, key))
return paths
}
return [].concat(paths, pathsFromTree(obj[key], joinKey(parentPath, key)))
}, [])
}
|
[
"function",
"pathsFromTree",
"(",
"obj",
",",
"parentPath",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"obj",
")",
")",
"{",
"return",
"parentPath",
"}",
"if",
"(",
"typeof",
"obj",
"===",
"'object'",
"&&",
"obj",
".",
"constructor",
".",
"name",
"===",
"'VirtualType'",
")",
"{",
"return",
"obj",
".",
"path",
"}",
"if",
"(",
"obj",
".",
"constructor",
".",
"name",
"===",
"'Schema'",
")",
"{",
"obj",
"=",
"obj",
".",
"tree",
"}",
"return",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"reduce",
"(",
"(",
"paths",
",",
"key",
")",
"=>",
"{",
"if",
"(",
"typeof",
"obj",
"[",
"key",
"]",
"!==",
"'object'",
"||",
"typeof",
"obj",
"[",
"key",
"]",
".",
"type",
"!==",
"'undefined'",
")",
"{",
"paths",
".",
"push",
"(",
"joinKey",
"(",
"parentPath",
",",
"key",
")",
")",
"return",
"paths",
"}",
"return",
"[",
"]",
".",
"concat",
"(",
"paths",
",",
"pathsFromTree",
"(",
"obj",
"[",
"key",
"]",
",",
"joinKey",
"(",
"parentPath",
",",
"key",
")",
")",
")",
"}",
",",
"[",
"]",
")",
"}"
] |
Builds a list of paths based on the schema tree. This includes virtuals and nested objects as well
@access private
@param {object} obj the root object
@param {string} parentPath the path taken to get to here
@returns {array} an array of paths from all children of the root object
|
[
"Builds",
"a",
"list",
"of",
"paths",
"based",
"on",
"the",
"schema",
"tree",
".",
"This",
"includes",
"virtuals",
"and",
"nested",
"objects",
"as",
"well"
] |
be1e93df9621b4f30f15738cc9d5820b2efa4ca5
|
https://github.com/mblarsen/mongoose-hidden/blob/be1e93df9621b4f30f15738cc9d5820b2efa4ca5/lib/mongoose-hidden.js#L114-L133
|
19,558
|
mblarsen/mongoose-hidden
|
lib/mongoose-hidden.js
|
getPathnames
|
function getPathnames(options, schema) {
let paths = pathsFromTree(schema.tree)
Object.keys(options['defaultHidden']).forEach(path => {
if (paths.indexOf(path) === -1) {
paths.push(path)
}
})
return paths
}
|
javascript
|
function getPathnames(options, schema) {
let paths = pathsFromTree(schema.tree)
Object.keys(options['defaultHidden']).forEach(path => {
if (paths.indexOf(path) === -1) {
paths.push(path)
}
})
return paths
}
|
[
"function",
"getPathnames",
"(",
"options",
",",
"schema",
")",
"{",
"let",
"paths",
"=",
"pathsFromTree",
"(",
"schema",
".",
"tree",
")",
"Object",
".",
"keys",
"(",
"options",
"[",
"'defaultHidden'",
"]",
")",
".",
"forEach",
"(",
"path",
"=>",
"{",
"if",
"(",
"paths",
".",
"indexOf",
"(",
"path",
")",
"===",
"-",
"1",
")",
"{",
"paths",
".",
"push",
"(",
"path",
")",
"}",
"}",
")",
"return",
"paths",
"}"
] |
Returns an array of pathnames based on the schema and the default settings
@access private
@param {object} options a set of options
@param {Schema} schema a mongoose schema
@returns {array} an array of paths
|
[
"Returns",
"an",
"array",
"of",
"pathnames",
"based",
"on",
"the",
"schema",
"and",
"the",
"default",
"settings"
] |
be1e93df9621b4f30f15738cc9d5820b2efa4ca5
|
https://github.com/mblarsen/mongoose-hidden/blob/be1e93df9621b4f30f15738cc9d5820b2efa4ca5/lib/mongoose-hidden.js#L143-L151
|
19,559
|
mblarsen/mongoose-hidden
|
lib/mongoose-hidden.js
|
prepOptions
|
function prepOptions(options, defaults) {
let _options = (options = options || {})
// Set defaults from options and default
let ensure = ensureOption(options)
options = {
hide: ensure(hide, defaults.autoHide),
hideJSON: ensure(hideJSON, defaults.autoHideJSON),
hideObject: ensure(hideObject, defaults.autoHideObject),
defaultHidden: Object.assign({}, ensure(defaultHidden, defaults.defaultHidden)),
virtuals: ensure(virtuals, defaults.virtuals),
}
// Add to list of default hidden
if (typeof _options[hidden] === 'object') {
options[defaultHidden] = Object.assign(options[defaultHidden], _options[hidden])
}
if (options[hide] === false) {
options[hideJSON] = false
options[hideObject] = false
}
return options
}
|
javascript
|
function prepOptions(options, defaults) {
let _options = (options = options || {})
// Set defaults from options and default
let ensure = ensureOption(options)
options = {
hide: ensure(hide, defaults.autoHide),
hideJSON: ensure(hideJSON, defaults.autoHideJSON),
hideObject: ensure(hideObject, defaults.autoHideObject),
defaultHidden: Object.assign({}, ensure(defaultHidden, defaults.defaultHidden)),
virtuals: ensure(virtuals, defaults.virtuals),
}
// Add to list of default hidden
if (typeof _options[hidden] === 'object') {
options[defaultHidden] = Object.assign(options[defaultHidden], _options[hidden])
}
if (options[hide] === false) {
options[hideJSON] = false
options[hideObject] = false
}
return options
}
|
[
"function",
"prepOptions",
"(",
"options",
",",
"defaults",
")",
"{",
"let",
"_options",
"=",
"(",
"options",
"=",
"options",
"||",
"{",
"}",
")",
"// Set defaults from options and default",
"let",
"ensure",
"=",
"ensureOption",
"(",
"options",
")",
"options",
"=",
"{",
"hide",
":",
"ensure",
"(",
"hide",
",",
"defaults",
".",
"autoHide",
")",
",",
"hideJSON",
":",
"ensure",
"(",
"hideJSON",
",",
"defaults",
".",
"autoHideJSON",
")",
",",
"hideObject",
":",
"ensure",
"(",
"hideObject",
",",
"defaults",
".",
"autoHideObject",
")",
",",
"defaultHidden",
":",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"ensure",
"(",
"defaultHidden",
",",
"defaults",
".",
"defaultHidden",
")",
")",
",",
"virtuals",
":",
"ensure",
"(",
"virtuals",
",",
"defaults",
".",
"virtuals",
")",
",",
"}",
"// Add to list of default hidden",
"if",
"(",
"typeof",
"_options",
"[",
"hidden",
"]",
"===",
"'object'",
")",
"{",
"options",
"[",
"defaultHidden",
"]",
"=",
"Object",
".",
"assign",
"(",
"options",
"[",
"defaultHidden",
"]",
",",
"_options",
"[",
"hidden",
"]",
")",
"}",
"if",
"(",
"options",
"[",
"hide",
"]",
"===",
"false",
")",
"{",
"options",
"[",
"hideJSON",
"]",
"=",
"false",
"options",
"[",
"hideObject",
"]",
"=",
"false",
"}",
"return",
"options",
"}"
] |
Merges options from defaults and instantiation
@access private
@param {Object} options an optional set of options
@param {Object} defaults the default set of options
@returns {Object} a combined options set
|
[
"Merges",
"options",
"from",
"defaults",
"and",
"instantiation"
] |
be1e93df9621b4f30f15738cc9d5820b2efa4ca5
|
https://github.com/mblarsen/mongoose-hidden/blob/be1e93df9621b4f30f15738cc9d5820b2efa4ca5/lib/mongoose-hidden.js#L174-L198
|
19,560
|
mblarsen/mongoose-hidden
|
lib/mongoose-hidden.js
|
function(parts, value) {
if (parts.length === 0) {
return value
}
let obj = {}
obj[parts[0]] = partsToValue(parts.slice(1), value)
return obj
}
|
javascript
|
function(parts, value) {
if (parts.length === 0) {
return value
}
let obj = {}
obj[parts[0]] = partsToValue(parts.slice(1), value)
return obj
}
|
[
"function",
"(",
"parts",
",",
"value",
")",
"{",
"if",
"(",
"parts",
".",
"length",
"===",
"0",
")",
"{",
"return",
"value",
"}",
"let",
"obj",
"=",
"{",
"}",
"obj",
"[",
"parts",
"[",
"0",
"]",
"]",
"=",
"partsToValue",
"(",
"parts",
".",
"slice",
"(",
"1",
")",
",",
"value",
")",
"return",
"obj",
"}"
] |
Convert path parts into a nested object
@access private
@param {array} parts an array of parts on the path
@param {mixed} value the value to set at the end of the path
@returns {object} an object corresponding to the path that the parts represents
|
[
"Convert",
"path",
"parts",
"into",
"a",
"nested",
"object"
] |
be1e93df9621b4f30f15738cc9d5820b2efa4ca5
|
https://github.com/mblarsen/mongoose-hidden/blob/be1e93df9621b4f30f15738cc9d5820b2efa4ca5/lib/mongoose-hidden.js#L208-L215
|
|
19,561
|
mblarsen/mongoose-hidden
|
lib/mongoose-hidden.js
|
function(obj, path, value) {
const parts = path.split('.')
/* traverse existing path to nearest object */
while (parts.length > 1 && typeof obj[parts[0]] === 'object') {
obj = obj[parts.shift()]
}
/* set value */
obj[parts[0]] = partsToValue(parts.slice(1), value)
}
|
javascript
|
function(obj, path, value) {
const parts = path.split('.')
/* traverse existing path to nearest object */
while (parts.length > 1 && typeof obj[parts[0]] === 'object') {
obj = obj[parts.shift()]
}
/* set value */
obj[parts[0]] = partsToValue(parts.slice(1), value)
}
|
[
"function",
"(",
"obj",
",",
"path",
",",
"value",
")",
"{",
"const",
"parts",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"/* traverse existing path to nearest object */",
"while",
"(",
"parts",
".",
"length",
">",
"1",
"&&",
"typeof",
"obj",
"[",
"parts",
"[",
"0",
"]",
"]",
"===",
"'object'",
")",
"{",
"obj",
"=",
"obj",
"[",
"parts",
".",
"shift",
"(",
")",
"]",
"}",
"/* set value */",
"obj",
"[",
"parts",
"[",
"0",
"]",
"]",
"=",
"partsToValue",
"(",
"parts",
".",
"slice",
"(",
"1",
")",
",",
"value",
")",
"}"
] |
Set a value in object denoted by dot-path
@access private
@param {object} obj source object
@param {string} path a dot-path
@param {mixed} value the value to set at the end of the path
|
[
"Set",
"a",
"value",
"in",
"object",
"denoted",
"by",
"dot",
"-",
"path"
] |
be1e93df9621b4f30f15738cc9d5820b2efa4ca5
|
https://github.com/mblarsen/mongoose-hidden/blob/be1e93df9621b4f30f15738cc9d5820b2efa4ca5/lib/mongoose-hidden.js#L225-L235
|
|
19,562
|
cermati/satpam
|
src/data-structures/errors.js
|
InvalidValidationRuleParameter
|
function InvalidValidationRuleParameter(ruleParameter, reason) {
var defaultMessage = sprintf('%s is not a valid rule parameter.', ruleParameter);
this.message = reason ? sprintf('%s. %s', defaultMessage, reason) : defaultMessage;
this.name = 'InvalidValidationRuleParameter';
Error.captureStackTrace(this, InvalidValidationRuleParameter);
}
|
javascript
|
function InvalidValidationRuleParameter(ruleParameter, reason) {
var defaultMessage = sprintf('%s is not a valid rule parameter.', ruleParameter);
this.message = reason ? sprintf('%s. %s', defaultMessage, reason) : defaultMessage;
this.name = 'InvalidValidationRuleParameter';
Error.captureStackTrace(this, InvalidValidationRuleParameter);
}
|
[
"function",
"InvalidValidationRuleParameter",
"(",
"ruleParameter",
",",
"reason",
")",
"{",
"var",
"defaultMessage",
"=",
"sprintf",
"(",
"'%s is not a valid rule parameter.'",
",",
"ruleParameter",
")",
";",
"this",
".",
"message",
"=",
"reason",
"?",
"sprintf",
"(",
"'%s. %s'",
",",
"defaultMessage",
",",
"reason",
")",
":",
"defaultMessage",
";",
"this",
".",
"name",
"=",
"'InvalidValidationRuleParameter'",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"InvalidValidationRuleParameter",
")",
";",
"}"
] |
A class that represents an invalid validation rule pareameter
@constructor
@author Sendy Halim <sendyhalim93@gmail.com>
@param message - The error message.
|
[
"A",
"class",
"that",
"represents",
"an",
"invalid",
"validation",
"rule",
"pareameter"
] |
911c941ff94892d83353ccee24dc9ad0852bd44e
|
https://github.com/cermati/satpam/blob/911c941ff94892d83353ccee24dc9ad0852bd44e/src/data-structures/errors.js#L10-L16
|
19,563
|
Baqend/js-sdk
|
cli/download.js
|
downloadCode
|
function downloadCode(db, codePath) {
return mkdir(codePath)
.then(() => db.code.loadModules())
.then((modules) => Promise.all(modules.map(module => downloadCodeModule(db, module, codePath))));
}
|
javascript
|
function downloadCode(db, codePath) {
return mkdir(codePath)
.then(() => db.code.loadModules())
.then((modules) => Promise.all(modules.map(module => downloadCodeModule(db, module, codePath))));
}
|
[
"function",
"downloadCode",
"(",
"db",
",",
"codePath",
")",
"{",
"return",
"mkdir",
"(",
"codePath",
")",
".",
"then",
"(",
"(",
")",
"=>",
"db",
".",
"code",
".",
"loadModules",
"(",
")",
")",
".",
"then",
"(",
"(",
"modules",
")",
"=>",
"Promise",
".",
"all",
"(",
"modules",
".",
"map",
"(",
"module",
"=>",
"downloadCodeModule",
"(",
"db",
",",
"module",
",",
"codePath",
")",
")",
")",
")",
";",
"}"
] |
Download all Baqend code.
@param {EntityManager} db The entity manager to use.
@param {string} codePath The path where code should be downloaded to.
@return {Promise<void>} Resolves when downloading has been finished.
|
[
"Download",
"all",
"Baqend",
"code",
"."
] |
1c8c86e5da1a28f75718ecde90a05080e2f3538f
|
https://github.com/Baqend/js-sdk/blob/1c8c86e5da1a28f75718ecde90a05080e2f3538f/cli/download.js#L32-L36
|
19,564
|
Baqend/js-sdk
|
cli/download.js
|
downloadCodeModule
|
function downloadCodeModule(db, module, codePath) {
const moduleName = module.replace(/^\/code\//, '').replace(/\/module$/, '');
const fileName = `${moduleName}.js`;
const filePath = path.join(codePath, fileName);
return db.code.loadCode(moduleName, 'module', false)
.then((file) => writeFile(filePath, file))
.then(() => console.log(`Module ${moduleName} downloaded.`));
}
|
javascript
|
function downloadCodeModule(db, module, codePath) {
const moduleName = module.replace(/^\/code\//, '').replace(/\/module$/, '');
const fileName = `${moduleName}.js`;
const filePath = path.join(codePath, fileName);
return db.code.loadCode(moduleName, 'module', false)
.then((file) => writeFile(filePath, file))
.then(() => console.log(`Module ${moduleName} downloaded.`));
}
|
[
"function",
"downloadCodeModule",
"(",
"db",
",",
"module",
",",
"codePath",
")",
"{",
"const",
"moduleName",
"=",
"module",
".",
"replace",
"(",
"/",
"^\\/code\\/",
"/",
",",
"''",
")",
".",
"replace",
"(",
"/",
"\\/module$",
"/",
",",
"''",
")",
";",
"const",
"fileName",
"=",
"`",
"${",
"moduleName",
"}",
"`",
";",
"const",
"filePath",
"=",
"path",
".",
"join",
"(",
"codePath",
",",
"fileName",
")",
";",
"return",
"db",
".",
"code",
".",
"loadCode",
"(",
"moduleName",
",",
"'module'",
",",
"false",
")",
".",
"then",
"(",
"(",
"file",
")",
"=>",
"writeFile",
"(",
"filePath",
",",
"file",
")",
")",
".",
"then",
"(",
"(",
")",
"=>",
"console",
".",
"log",
"(",
"`",
"${",
"moduleName",
"}",
"`",
")",
")",
";",
"}"
] |
Downloads a single code module.
@param {EntityManager} db The entity manager to use.
@param {string} module The module to download.
@param {string} codePath The path where code should be downloaded to.
@return {Promise<void>} Resolves when downloading has been finished.
|
[
"Downloads",
"a",
"single",
"code",
"module",
"."
] |
1c8c86e5da1a28f75718ecde90a05080e2f3538f
|
https://github.com/Baqend/js-sdk/blob/1c8c86e5da1a28f75718ecde90a05080e2f3538f/cli/download.js#L46-L54
|
19,565
|
Baqend/js-sdk
|
cli/download.js
|
mkdir
|
function mkdir(dir) {
return new Promise((resolve, reject) => {
fs.lstat(dir, (err, stats) => {
// Resolve, when already is directory
if (!err) return stats.isDirectory() ? resolve() : reject(new Error(`${dir} is not a direcotry.`));
// Try to create directory
fs.mkdir(dir, (err) => {
err ? reject(err) : resolve();
});
})
})
}
|
javascript
|
function mkdir(dir) {
return new Promise((resolve, reject) => {
fs.lstat(dir, (err, stats) => {
// Resolve, when already is directory
if (!err) return stats.isDirectory() ? resolve() : reject(new Error(`${dir} is not a direcotry.`));
// Try to create directory
fs.mkdir(dir, (err) => {
err ? reject(err) : resolve();
});
})
})
}
|
[
"function",
"mkdir",
"(",
"dir",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"lstat",
"(",
"dir",
",",
"(",
"err",
",",
"stats",
")",
"=>",
"{",
"// Resolve, when already is directory",
"if",
"(",
"!",
"err",
")",
"return",
"stats",
".",
"isDirectory",
"(",
")",
"?",
"resolve",
"(",
")",
":",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"dir",
"}",
"`",
")",
")",
";",
"// Try to create directory",
"fs",
".",
"mkdir",
"(",
"dir",
",",
"(",
"err",
")",
"=>",
"{",
"err",
"?",
"reject",
"(",
"err",
")",
":",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
")",
"}",
")",
"}"
] |
Creates a direcotry or ensures that it exists.
@param {string} dir The path where a directory should exist.
@return {Promise<void>} Resolves when the given directory is existing.
|
[
"Creates",
"a",
"direcotry",
"or",
"ensures",
"that",
"it",
"exists",
"."
] |
1c8c86e5da1a28f75718ecde90a05080e2f3538f
|
https://github.com/Baqend/js-sdk/blob/1c8c86e5da1a28f75718ecde90a05080e2f3538f/cli/download.js#L62-L73
|
19,566
|
Baqend/js-sdk
|
cli/download.js
|
writeFile
|
function writeFile(filePath, contents) {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, contents, 'utf-8', (err, file) => {
err ? reject(err) : resolve();
})
});
}
|
javascript
|
function writeFile(filePath, contents) {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, contents, 'utf-8', (err, file) => {
err ? reject(err) : resolve();
})
});
}
|
[
"function",
"writeFile",
"(",
"filePath",
",",
"contents",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"writeFile",
"(",
"filePath",
",",
"contents",
",",
"'utf-8'",
",",
"(",
"err",
",",
"file",
")",
"=>",
"{",
"err",
"?",
"reject",
"(",
"err",
")",
":",
"resolve",
"(",
")",
";",
"}",
")",
"}",
")",
";",
"}"
] |
Writes a file to disk.
@param {string} filePath The file path to write to.
@param {string} contents A UTF-8 encoded string of the file contents.
@return {Promise<void>} Resolves when the file has been written successfully.
|
[
"Writes",
"a",
"file",
"to",
"disk",
"."
] |
1c8c86e5da1a28f75718ecde90a05080e2f3538f
|
https://github.com/Baqend/js-sdk/blob/1c8c86e5da1a28f75718ecde90a05080e2f3538f/cli/download.js#L82-L88
|
19,567
|
Baqend/js-sdk
|
cli/schema.js
|
createDir
|
function createDir(dir) {
const splitPath = dir.split('/');
splitPath.reduce((path, subPath) => {
let currentPath;
if(subPath != '.'){
currentPath = path + '/' + subPath;
if (!fs.existsSync(currentPath)){
fs.mkdirSync(currentPath);
}
}
else{
currentPath = subPath;
}
return currentPath
}, '')
}
|
javascript
|
function createDir(dir) {
const splitPath = dir.split('/');
splitPath.reduce((path, subPath) => {
let currentPath;
if(subPath != '.'){
currentPath = path + '/' + subPath;
if (!fs.existsSync(currentPath)){
fs.mkdirSync(currentPath);
}
}
else{
currentPath = subPath;
}
return currentPath
}, '')
}
|
[
"function",
"createDir",
"(",
"dir",
")",
"{",
"const",
"splitPath",
"=",
"dir",
".",
"split",
"(",
"'/'",
")",
";",
"splitPath",
".",
"reduce",
"(",
"(",
"path",
",",
"subPath",
")",
"=>",
"{",
"let",
"currentPath",
";",
"if",
"(",
"subPath",
"!=",
"'.'",
")",
"{",
"currentPath",
"=",
"path",
"+",
"'/'",
"+",
"subPath",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"currentPath",
")",
")",
"{",
"fs",
".",
"mkdirSync",
"(",
"currentPath",
")",
";",
"}",
"}",
"else",
"{",
"currentPath",
"=",
"subPath",
";",
"}",
"return",
"currentPath",
"}",
",",
"''",
")",
"}"
] |
recursive directory creation
|
[
"recursive",
"directory",
"creation"
] |
1c8c86e5da1a28f75718ecde90a05080e2f3538f
|
https://github.com/Baqend/js-sdk/blob/1c8c86e5da1a28f75718ecde90a05080e2f3538f/cli/schema.js#L111-L126
|
19,568
|
Baqend/js-sdk
|
cli/copy.js
|
copy
|
function copy(args) {
// TODO: Split arguments with destructure in the future
const source = splitArg(args.source);
const sourceApp = source[0];
const sourcePath = source[1];
const dest = splitArg(args.dest);
const destApp = dest[0];
const destPath = dest[1];
return login(sourceApp, destApp).then((dbs) => {
const sourceDB = dbs[0];
const destDB = dbs[1];
return normalizeArgs(sourceDB, sourcePath, destDB, destPath).then((paths) => {
const sourcePath = paths[0];
const destPath = paths[1];
return streamFrom(sourceDB, sourcePath).then((args) => {
const rs = args[0];
const size = args[1];
return streamTo(destDB, destPath, rs, size);
});
});
});
}
|
javascript
|
function copy(args) {
// TODO: Split arguments with destructure in the future
const source = splitArg(args.source);
const sourceApp = source[0];
const sourcePath = source[1];
const dest = splitArg(args.dest);
const destApp = dest[0];
const destPath = dest[1];
return login(sourceApp, destApp).then((dbs) => {
const sourceDB = dbs[0];
const destDB = dbs[1];
return normalizeArgs(sourceDB, sourcePath, destDB, destPath).then((paths) => {
const sourcePath = paths[0];
const destPath = paths[1];
return streamFrom(sourceDB, sourcePath).then((args) => {
const rs = args[0];
const size = args[1];
return streamTo(destDB, destPath, rs, size);
});
});
});
}
|
[
"function",
"copy",
"(",
"args",
")",
"{",
"// TODO: Split arguments with destructure in the future",
"const",
"source",
"=",
"splitArg",
"(",
"args",
".",
"source",
")",
";",
"const",
"sourceApp",
"=",
"source",
"[",
"0",
"]",
";",
"const",
"sourcePath",
"=",
"source",
"[",
"1",
"]",
";",
"const",
"dest",
"=",
"splitArg",
"(",
"args",
".",
"dest",
")",
";",
"const",
"destApp",
"=",
"dest",
"[",
"0",
"]",
";",
"const",
"destPath",
"=",
"dest",
"[",
"1",
"]",
";",
"return",
"login",
"(",
"sourceApp",
",",
"destApp",
")",
".",
"then",
"(",
"(",
"dbs",
")",
"=>",
"{",
"const",
"sourceDB",
"=",
"dbs",
"[",
"0",
"]",
";",
"const",
"destDB",
"=",
"dbs",
"[",
"1",
"]",
";",
"return",
"normalizeArgs",
"(",
"sourceDB",
",",
"sourcePath",
",",
"destDB",
",",
"destPath",
")",
".",
"then",
"(",
"(",
"paths",
")",
"=>",
"{",
"const",
"sourcePath",
"=",
"paths",
"[",
"0",
"]",
";",
"const",
"destPath",
"=",
"paths",
"[",
"1",
"]",
";",
"return",
"streamFrom",
"(",
"sourceDB",
",",
"sourcePath",
")",
".",
"then",
"(",
"(",
"args",
")",
"=>",
"{",
"const",
"rs",
"=",
"args",
"[",
"0",
"]",
";",
"const",
"size",
"=",
"args",
"[",
"1",
"]",
";",
"return",
"streamTo",
"(",
"destDB",
",",
"destPath",
",",
"rs",
",",
"size",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Copies from arbitrary location to each other.
@param {{ source: string, dest: string }} args
@return {Promise<any>}
|
[
"Copies",
"from",
"arbitrary",
"location",
"to",
"each",
"other",
"."
] |
1c8c86e5da1a28f75718ecde90a05080e2f3538f
|
https://github.com/Baqend/js-sdk/blob/1c8c86e5da1a28f75718ecde90a05080e2f3538f/cli/copy.js#L172-L197
|
19,569
|
junkurihara/jscu
|
packages/js-crypto-aes/src/aes.js
|
assertAlgorithms
|
function assertAlgorithms({name, iv, tagLength}){
if(Object.keys(params.ciphers).indexOf(name) < 0) throw new Error('UnsupportedAlgorithm');
if(params.ciphers[name].ivLength){
if(!(iv instanceof Uint8Array)) throw new Error('InvalidArguments');
if(iv.byteLength < 2 || iv.byteLength > 16) throw new Error('InvalidIVLength');
if(params.ciphers[name].staticIvLength && (params.ciphers[name].ivLength !== iv.byteLength)) throw new Error('InvalidIVLength');
}
if(params.ciphers[name].tagLength && tagLength){
if(!Number.isInteger(tagLength)) throw new Error('InvalidArguments');
if(tagLength < 4 || tagLength > 16) throw new Error('InvalidTagLength');
}
}
|
javascript
|
function assertAlgorithms({name, iv, tagLength}){
if(Object.keys(params.ciphers).indexOf(name) < 0) throw new Error('UnsupportedAlgorithm');
if(params.ciphers[name].ivLength){
if(!(iv instanceof Uint8Array)) throw new Error('InvalidArguments');
if(iv.byteLength < 2 || iv.byteLength > 16) throw new Error('InvalidIVLength');
if(params.ciphers[name].staticIvLength && (params.ciphers[name].ivLength !== iv.byteLength)) throw new Error('InvalidIVLength');
}
if(params.ciphers[name].tagLength && tagLength){
if(!Number.isInteger(tagLength)) throw new Error('InvalidArguments');
if(tagLength < 4 || tagLength > 16) throw new Error('InvalidTagLength');
}
}
|
[
"function",
"assertAlgorithms",
"(",
"{",
"name",
",",
"iv",
",",
"tagLength",
"}",
")",
"{",
"if",
"(",
"Object",
".",
"keys",
"(",
"params",
".",
"ciphers",
")",
".",
"indexOf",
"(",
"name",
")",
"<",
"0",
")",
"throw",
"new",
"Error",
"(",
"'UnsupportedAlgorithm'",
")",
";",
"if",
"(",
"params",
".",
"ciphers",
"[",
"name",
"]",
".",
"ivLength",
")",
"{",
"if",
"(",
"!",
"(",
"iv",
"instanceof",
"Uint8Array",
")",
")",
"throw",
"new",
"Error",
"(",
"'InvalidArguments'",
")",
";",
"if",
"(",
"iv",
".",
"byteLength",
"<",
"2",
"||",
"iv",
".",
"byteLength",
">",
"16",
")",
"throw",
"new",
"Error",
"(",
"'InvalidIVLength'",
")",
";",
"if",
"(",
"params",
".",
"ciphers",
"[",
"name",
"]",
".",
"staticIvLength",
"&&",
"(",
"params",
".",
"ciphers",
"[",
"name",
"]",
".",
"ivLength",
"!==",
"iv",
".",
"byteLength",
")",
")",
"throw",
"new",
"Error",
"(",
"'InvalidIVLength'",
")",
";",
"}",
"if",
"(",
"params",
".",
"ciphers",
"[",
"name",
"]",
".",
"tagLength",
"&&",
"tagLength",
")",
"{",
"if",
"(",
"!",
"Number",
".",
"isInteger",
"(",
"tagLength",
")",
")",
"throw",
"new",
"Error",
"(",
"'InvalidArguments'",
")",
";",
"if",
"(",
"tagLength",
"<",
"4",
"||",
"tagLength",
">",
"16",
")",
"throw",
"new",
"Error",
"(",
"'InvalidTagLength'",
")",
";",
"}",
"}"
] |
Check if the given algorithm spec is valid.
@param {String} name - Name of the specified algorithm like 'AES-GCM'.
@param {Uint8Array} iv - IV byte array if required
@param {Number} tagLength - Authentication tag length if required
@throws {Error} - Throws if UnsupportedAlgorithm, InvalidArguments, InvalidIVLength, or InvalidTagLength.
|
[
"Check",
"if",
"the",
"given",
"algorithm",
"spec",
"is",
"valid",
"."
] |
d9a665d538f9b8bc4b47dc2f22b33e326edeb712
|
https://github.com/junkurihara/jscu/blob/d9a665d538f9b8bc4b47dc2f22b33e326edeb712/packages/js-crypto-aes/src/aes.js#L17-L28
|
19,570
|
junkurihara/jscu
|
packages/js-crypto-rsa/src/rsa.js
|
assertSignVerify
|
function assertSignVerify(msg, jwkey, hash, algorithm, mode){
if (algorithm.name !== 'RSA-PSS' && algorithm.name !== 'RSASSA-PKCS1-v1_5') throw new Error('InvalidAlgorithm');
if (Object.keys(params.hashes).indexOf(hash) < 0) throw new Error('UnsupportedHash');
if (!(msg instanceof Uint8Array)) throw new Error('InvalidMessageFormat');
if (jwkey.kty !== 'RSA') throw new Error('InvalidJwkRsaKey');
if (algorithm.name === 'RSA-PSS'){
checkPssLength(mode, {k: jseu.encoder.decodeBase64Url(jwkey.n).length, hash, saltLength: algorithm.saltLength});
}
return true;
}
|
javascript
|
function assertSignVerify(msg, jwkey, hash, algorithm, mode){
if (algorithm.name !== 'RSA-PSS' && algorithm.name !== 'RSASSA-PKCS1-v1_5') throw new Error('InvalidAlgorithm');
if (Object.keys(params.hashes).indexOf(hash) < 0) throw new Error('UnsupportedHash');
if (!(msg instanceof Uint8Array)) throw new Error('InvalidMessageFormat');
if (jwkey.kty !== 'RSA') throw new Error('InvalidJwkRsaKey');
if (algorithm.name === 'RSA-PSS'){
checkPssLength(mode, {k: jseu.encoder.decodeBase64Url(jwkey.n).length, hash, saltLength: algorithm.saltLength});
}
return true;
}
|
[
"function",
"assertSignVerify",
"(",
"msg",
",",
"jwkey",
",",
"hash",
",",
"algorithm",
",",
"mode",
")",
"{",
"if",
"(",
"algorithm",
".",
"name",
"!==",
"'RSA-PSS'",
"&&",
"algorithm",
".",
"name",
"!==",
"'RSASSA-PKCS1-v1_5'",
")",
"throw",
"new",
"Error",
"(",
"'InvalidAlgorithm'",
")",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"params",
".",
"hashes",
")",
".",
"indexOf",
"(",
"hash",
")",
"<",
"0",
")",
"throw",
"new",
"Error",
"(",
"'UnsupportedHash'",
")",
";",
"if",
"(",
"!",
"(",
"msg",
"instanceof",
"Uint8Array",
")",
")",
"throw",
"new",
"Error",
"(",
"'InvalidMessageFormat'",
")",
";",
"if",
"(",
"jwkey",
".",
"kty",
"!==",
"'RSA'",
")",
"throw",
"new",
"Error",
"(",
"'InvalidJwkRsaKey'",
")",
";",
"if",
"(",
"algorithm",
".",
"name",
"===",
"'RSA-PSS'",
")",
"{",
"checkPssLength",
"(",
"mode",
",",
"{",
"k",
":",
"jseu",
".",
"encoder",
".",
"decodeBase64Url",
"(",
"jwkey",
".",
"n",
")",
".",
"length",
",",
"hash",
",",
"saltLength",
":",
"algorithm",
".",
"saltLength",
"}",
")",
";",
"}",
"return",
"true",
";",
"}"
] |
RSA Signing parameter check.
@param {Uint8Array} msg - Byte array of message to be signed.
@param {JsonWebKey} jwkey - Private/Public key for signing/verifying in JWK format.
@param {String} hash - Name of hash algorithm like 'SHA-256'.
@param {RSASignAlgorithm} algorithm - Object to specify algorithm parameters.
@param {String} mode - 'sign' or 'verify' for PSS parameter check.
@return {boolean} - Always true unless thrown.
@throws {Error} - Throws if InvalidAlgorithm, UnsupportedHash, InvalidMessageFormat or InvalidJwkRsaKey
|
[
"RSA",
"Signing",
"parameter",
"check",
"."
] |
d9a665d538f9b8bc4b47dc2f22b33e326edeb712
|
https://github.com/junkurihara/jscu/blob/d9a665d538f9b8bc4b47dc2f22b33e326edeb712/packages/js-crypto-rsa/src/rsa.js#L52-L61
|
19,571
|
junkurihara/jscu
|
packages/js-x509-utils/src/x509.js
|
setRDNSequence
|
function setRDNSequence(options) {
const encodedArray = Object.keys(options).map((k) => {
if (Object.keys(attributeTypeOIDMap).indexOf(k) < 0) throw new Error('InvalidOptionSpecification');
const type = attributeTypeOIDMap[k];
let value;
if (['dnQualifier, countryName, serialNumber'].indexOf(k) >= 0) {
if (k === 'countryName' && options[k].length !== 2) throw new Error('InvalidCountryNameCode');
value = rfc5280.DirectoryString.encode({type: 'printableString', value: options[k]}, 'der');
}
else value = rfc5280.DirectoryString.encode({type: 'utf8String', value: options[k]}, 'der');
return {type, value};
});
return [encodedArray];
}
|
javascript
|
function setRDNSequence(options) {
const encodedArray = Object.keys(options).map((k) => {
if (Object.keys(attributeTypeOIDMap).indexOf(k) < 0) throw new Error('InvalidOptionSpecification');
const type = attributeTypeOIDMap[k];
let value;
if (['dnQualifier, countryName, serialNumber'].indexOf(k) >= 0) {
if (k === 'countryName' && options[k].length !== 2) throw new Error('InvalidCountryNameCode');
value = rfc5280.DirectoryString.encode({type: 'printableString', value: options[k]}, 'der');
}
else value = rfc5280.DirectoryString.encode({type: 'utf8String', value: options[k]}, 'der');
return {type, value};
});
return [encodedArray];
}
|
[
"function",
"setRDNSequence",
"(",
"options",
")",
"{",
"const",
"encodedArray",
"=",
"Object",
".",
"keys",
"(",
"options",
")",
".",
"map",
"(",
"(",
"k",
")",
"=>",
"{",
"if",
"(",
"Object",
".",
"keys",
"(",
"attributeTypeOIDMap",
")",
".",
"indexOf",
"(",
"k",
")",
"<",
"0",
")",
"throw",
"new",
"Error",
"(",
"'InvalidOptionSpecification'",
")",
";",
"const",
"type",
"=",
"attributeTypeOIDMap",
"[",
"k",
"]",
";",
"let",
"value",
";",
"if",
"(",
"[",
"'dnQualifier, countryName, serialNumber'",
"]",
".",
"indexOf",
"(",
"k",
")",
">=",
"0",
")",
"{",
"if",
"(",
"k",
"===",
"'countryName'",
"&&",
"options",
"[",
"k",
"]",
".",
"length",
"!==",
"2",
")",
"throw",
"new",
"Error",
"(",
"'InvalidCountryNameCode'",
")",
";",
"value",
"=",
"rfc5280",
".",
"DirectoryString",
".",
"encode",
"(",
"{",
"type",
":",
"'printableString'",
",",
"value",
":",
"options",
"[",
"k",
"]",
"}",
",",
"'der'",
")",
";",
"}",
"else",
"value",
"=",
"rfc5280",
".",
"DirectoryString",
".",
"encode",
"(",
"{",
"type",
":",
"'utf8String'",
",",
"value",
":",
"options",
"[",
"k",
"]",
"}",
",",
"'der'",
")",
";",
"return",
"{",
"type",
",",
"value",
"}",
";",
"}",
")",
";",
"return",
"[",
"encodedArray",
"]",
";",
"}"
] |
Set RDN sequence for issuer and subject fields
@param {Object} options - RDN Sequence
@return {{type: *, value: *}[][]}
@throws {Error} - throws if InvalidOptionSpecification or InvalidCountryNameCode.
|
[
"Set",
"RDN",
"sequence",
"for",
"issuer",
"and",
"subject",
"fields"
] |
d9a665d538f9b8bc4b47dc2f22b33e326edeb712
|
https://github.com/junkurihara/jscu/blob/d9a665d538f9b8bc4b47dc2f22b33e326edeb712/packages/js-x509-utils/src/x509.js#L164-L180
|
19,572
|
junkurihara/jscu
|
packages/js-crypto-pbkdf/src/pbkdf.js
|
assertPbkdf
|
function assertPbkdf(p, s, c, dkLen, hash){
if (typeof p !== 'string' && !(p instanceof Uint8Array)) throw new Error('PasswordIsNotUint8ArrayNorString');
if (!(s instanceof Uint8Array)) throw new Error('SaltMustBeUint8Array');
if (typeof c !== 'number' || c <= 0)throw new Error('InvalidIterationCount');
if (typeof dkLen !== 'number' || dkLen <= 0) throw new Error('InvalidDerivedKeyLength');
if (Object.keys(params.hashes).indexOf(hash) < 0) throw new Error('UnsupportedHashAlgorithm');
return true;
}
|
javascript
|
function assertPbkdf(p, s, c, dkLen, hash){
if (typeof p !== 'string' && !(p instanceof Uint8Array)) throw new Error('PasswordIsNotUint8ArrayNorString');
if (!(s instanceof Uint8Array)) throw new Error('SaltMustBeUint8Array');
if (typeof c !== 'number' || c <= 0)throw new Error('InvalidIterationCount');
if (typeof dkLen !== 'number' || dkLen <= 0) throw new Error('InvalidDerivedKeyLength');
if (Object.keys(params.hashes).indexOf(hash) < 0) throw new Error('UnsupportedHashAlgorithm');
return true;
}
|
[
"function",
"assertPbkdf",
"(",
"p",
",",
"s",
",",
"c",
",",
"dkLen",
",",
"hash",
")",
"{",
"if",
"(",
"typeof",
"p",
"!==",
"'string'",
"&&",
"!",
"(",
"p",
"instanceof",
"Uint8Array",
")",
")",
"throw",
"new",
"Error",
"(",
"'PasswordIsNotUint8ArrayNorString'",
")",
";",
"if",
"(",
"!",
"(",
"s",
"instanceof",
"Uint8Array",
")",
")",
"throw",
"new",
"Error",
"(",
"'SaltMustBeUint8Array'",
")",
";",
"if",
"(",
"typeof",
"c",
"!==",
"'number'",
"||",
"c",
"<=",
"0",
")",
"throw",
"new",
"Error",
"(",
"'InvalidIterationCount'",
")",
";",
"if",
"(",
"typeof",
"dkLen",
"!==",
"'number'",
"||",
"dkLen",
"<=",
"0",
")",
"throw",
"new",
"Error",
"(",
"'InvalidDerivedKeyLength'",
")",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"params",
".",
"hashes",
")",
".",
"indexOf",
"(",
"hash",
")",
"<",
"0",
")",
"throw",
"new",
"Error",
"(",
"'UnsupportedHashAlgorithm'",
")",
";",
"return",
"true",
";",
"}"
] |
Assertion for PBKDF 1 and 2
@param {Uint8Array|String} p - Byte array or string of password. if string is given, it will be converted to Uint8Array.
@param {Uint8Array} s - Byte array of salt.
@param {Number} c - Iteration count.
@param {Number} dkLen - Intended output key length in octet.
@param {String} hash - Name of underlying hash function for HMAC like 'SHA-256'
@return {boolean} - True if given params pass the assertion check. Otherwise, throw (not false).
@throws {Error} - Throws if the params doesn't pass the assertion checks for given conditions.
|
[
"Assertion",
"for",
"PBKDF",
"1",
"and",
"2"
] |
d9a665d538f9b8bc4b47dc2f22b33e326edeb712
|
https://github.com/junkurihara/jscu/blob/d9a665d538f9b8bc4b47dc2f22b33e326edeb712/packages/js-crypto-pbkdf/src/pbkdf.js#L98-L105
|
19,573
|
junkurihara/jscu
|
packages/js-crypto-hkdf/src/hkdf.js
|
rfc5869
|
async function rfc5869(master, hash, length, info, salt){
const len = params.hashes[hash].hashSize;
// RFC5869 Step 1 (Extract)
const prk = await hmac.compute(salt, master, hash);
// RFC5869 Step 2 (Expand)
let t = new Uint8Array([]);
const okm = new Uint8Array(Math.ceil(length / len) * len);
const uintInfo = new Uint8Array(info);
for(let i = 0; i < Math.ceil(length / len); i++){
const concat = new Uint8Array(t.length + uintInfo.length + 1);
concat.set(t);
concat.set(uintInfo, t.length);
concat.set(new Uint8Array([i+1]), t.length + uintInfo.length);
t = await hmac.compute(prk, concat, hash);
okm.set(t, len * i);
}
return okm.slice(0, length);
}
|
javascript
|
async function rfc5869(master, hash, length, info, salt){
const len = params.hashes[hash].hashSize;
// RFC5869 Step 1 (Extract)
const prk = await hmac.compute(salt, master, hash);
// RFC5869 Step 2 (Expand)
let t = new Uint8Array([]);
const okm = new Uint8Array(Math.ceil(length / len) * len);
const uintInfo = new Uint8Array(info);
for(let i = 0; i < Math.ceil(length / len); i++){
const concat = new Uint8Array(t.length + uintInfo.length + 1);
concat.set(t);
concat.set(uintInfo, t.length);
concat.set(new Uint8Array([i+1]), t.length + uintInfo.length);
t = await hmac.compute(prk, concat, hash);
okm.set(t, len * i);
}
return okm.slice(0, length);
}
|
[
"async",
"function",
"rfc5869",
"(",
"master",
",",
"hash",
",",
"length",
",",
"info",
",",
"salt",
")",
"{",
"const",
"len",
"=",
"params",
".",
"hashes",
"[",
"hash",
"]",
".",
"hashSize",
";",
"// RFC5869 Step 1 (Extract)",
"const",
"prk",
"=",
"await",
"hmac",
".",
"compute",
"(",
"salt",
",",
"master",
",",
"hash",
")",
";",
"// RFC5869 Step 2 (Expand)",
"let",
"t",
"=",
"new",
"Uint8Array",
"(",
"[",
"]",
")",
";",
"const",
"okm",
"=",
"new",
"Uint8Array",
"(",
"Math",
".",
"ceil",
"(",
"length",
"/",
"len",
")",
"*",
"len",
")",
";",
"const",
"uintInfo",
"=",
"new",
"Uint8Array",
"(",
"info",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"Math",
".",
"ceil",
"(",
"length",
"/",
"len",
")",
";",
"i",
"++",
")",
"{",
"const",
"concat",
"=",
"new",
"Uint8Array",
"(",
"t",
".",
"length",
"+",
"uintInfo",
".",
"length",
"+",
"1",
")",
";",
"concat",
".",
"set",
"(",
"t",
")",
";",
"concat",
".",
"set",
"(",
"uintInfo",
",",
"t",
".",
"length",
")",
";",
"concat",
".",
"set",
"(",
"new",
"Uint8Array",
"(",
"[",
"i",
"+",
"1",
"]",
")",
",",
"t",
".",
"length",
"+",
"uintInfo",
".",
"length",
")",
";",
"t",
"=",
"await",
"hmac",
".",
"compute",
"(",
"prk",
",",
"concat",
",",
"hash",
")",
";",
"okm",
".",
"set",
"(",
"t",
",",
"len",
"*",
"i",
")",
";",
"}",
"return",
"okm",
".",
"slice",
"(",
"0",
",",
"length",
")",
";",
"}"
] |
Naive implementation of RFC5869 in PureJavaScript
@param {Uint8Array} master - Master secret to derive the key.
@param {String} hash - Name of hash algorithm used to derive the key.
@param {Number} length - Intended length of derived key.
@param {String} info - String for information field of HKDF.
@param {Uint8Array} salt - Byte array of salt.
@return {Promise<Uint8Array>} - Derived key.
|
[
"Naive",
"implementation",
"of",
"RFC5869",
"in",
"PureJavaScript"
] |
d9a665d538f9b8bc4b47dc2f22b33e326edeb712
|
https://github.com/junkurihara/jscu/blob/d9a665d538f9b8bc4b47dc2f22b33e326edeb712/packages/js-crypto-hkdf/src/hkdf.js#L63-L82
|
19,574
|
shamadee/wasm-init
|
lib/compileWASM.js
|
compileWASM
|
function compileWASM (config) {
// check that emscripten path is correct
if (!fs.existsSync(config.emscripten_path)) {
return process.stdout.write(colors.red(`Error: Could not find emscripten directory at ${config.emscripten_path}\n`));
}
const shellScript = getShellScript(config);
// format exported functions, if present, from config for shell script
let expFuncStr = '';
if (config.exported_functions && config.exported_functions.length > 0) {
let expFuncs = config.exported_functions.reduce((acc, val) => acc.concat('\'', val, '\'\,'), '[');
expFuncs = expFuncs.substring(0, expFuncs.length - 1).concat(']');
expFuncStr = `-s EXPORTED_FUNCTIONS="${expFuncs}" `;
}
// format flags from config for shell script
const flags = config.flags.reduce((acc, val) => acc.concat(' ', val), '');
// construct the default compile mode string.
let commandStr = `emcc -o ${config.outputfile} ${config.inputfile} ${expFuncStr} ${flags}`;
// generate a command string suitable for cmake
if(config.mode == "build") {
// assuming make
config.generator = config.generator ? config.generator : 'make';
switch(config.generator) {
case 'ninja':
config.gen_flag = 'Ninja';
default:
config.gen_flag = '"Unix Makefiles"';
break;
}
// need to triple escape double quotes
expFuncStr = expFuncStr.replace(/"/g, '\\\"');
let modFlags = flags.replace(/"/g, '\\\"');
let cxxFlagStr = `SET(WASM_CXXFLAGS "${modFlags} ${expFuncStr}" CACHE PATH "")`;
// pass through cmake configuration, inc. compiler flags, exported functions
commandStr = `cd wasm && emcmake cmake -G ${config.gen_flag} `+
`-DWASM_CXXFLAGS=\"${modFlags} ${expFuncStr}\" ` +
`.. && emmake ${config.generator} -j${cpuCount-1}`;
}
process.stdout.write(colors.cyan('Running emscripten...\n'));
// execute shell script
// exec(shellScript, (error, stdout, stderr) => {
exec(`
if [[ :$PATH: != *:"/emsdk":* ]]
then
# use path to emsdk folder, relative to project directory
BASEDIR="${config.emscripten_path}"
EMSDK_ENV=$(find "$BASEDIR" -type f -name "emsdk_env.sh")
source "$EMSDK_ENV"
fi
${commandStr}
`, { shell: '/bin/bash' }, (error, stdout, stderr) => {
// check for emcc compile errors
if (stderr) {
process.stderr.write(colors.red.bold('EMSCRIPTEN COMPILE ERROR\n'));
process.stderr.write(colors.white(stderr));
} else {
process.stdout.write(stdout);
insertEventListener(config);
process.stdout.write(colors.green.bold('Compiled C++ to WASM\n'));
}
});
}
|
javascript
|
function compileWASM (config) {
// check that emscripten path is correct
if (!fs.existsSync(config.emscripten_path)) {
return process.stdout.write(colors.red(`Error: Could not find emscripten directory at ${config.emscripten_path}\n`));
}
const shellScript = getShellScript(config);
// format exported functions, if present, from config for shell script
let expFuncStr = '';
if (config.exported_functions && config.exported_functions.length > 0) {
let expFuncs = config.exported_functions.reduce((acc, val) => acc.concat('\'', val, '\'\,'), '[');
expFuncs = expFuncs.substring(0, expFuncs.length - 1).concat(']');
expFuncStr = `-s EXPORTED_FUNCTIONS="${expFuncs}" `;
}
// format flags from config for shell script
const flags = config.flags.reduce((acc, val) => acc.concat(' ', val), '');
// construct the default compile mode string.
let commandStr = `emcc -o ${config.outputfile} ${config.inputfile} ${expFuncStr} ${flags}`;
// generate a command string suitable for cmake
if(config.mode == "build") {
// assuming make
config.generator = config.generator ? config.generator : 'make';
switch(config.generator) {
case 'ninja':
config.gen_flag = 'Ninja';
default:
config.gen_flag = '"Unix Makefiles"';
break;
}
// need to triple escape double quotes
expFuncStr = expFuncStr.replace(/"/g, '\\\"');
let modFlags = flags.replace(/"/g, '\\\"');
let cxxFlagStr = `SET(WASM_CXXFLAGS "${modFlags} ${expFuncStr}" CACHE PATH "")`;
// pass through cmake configuration, inc. compiler flags, exported functions
commandStr = `cd wasm && emcmake cmake -G ${config.gen_flag} `+
`-DWASM_CXXFLAGS=\"${modFlags} ${expFuncStr}\" ` +
`.. && emmake ${config.generator} -j${cpuCount-1}`;
}
process.stdout.write(colors.cyan('Running emscripten...\n'));
// execute shell script
// exec(shellScript, (error, stdout, stderr) => {
exec(`
if [[ :$PATH: != *:"/emsdk":* ]]
then
# use path to emsdk folder, relative to project directory
BASEDIR="${config.emscripten_path}"
EMSDK_ENV=$(find "$BASEDIR" -type f -name "emsdk_env.sh")
source "$EMSDK_ENV"
fi
${commandStr}
`, { shell: '/bin/bash' }, (error, stdout, stderr) => {
// check for emcc compile errors
if (stderr) {
process.stderr.write(colors.red.bold('EMSCRIPTEN COMPILE ERROR\n'));
process.stderr.write(colors.white(stderr));
} else {
process.stdout.write(stdout);
insertEventListener(config);
process.stdout.write(colors.green.bold('Compiled C++ to WASM\n'));
}
});
}
|
[
"function",
"compileWASM",
"(",
"config",
")",
"{",
"// check that emscripten path is correct",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"config",
".",
"emscripten_path",
")",
")",
"{",
"return",
"process",
".",
"stdout",
".",
"write",
"(",
"colors",
".",
"red",
"(",
"`",
"${",
"config",
".",
"emscripten_path",
"}",
"\\n",
"`",
")",
")",
";",
"}",
"const",
"shellScript",
"=",
"getShellScript",
"(",
"config",
")",
";",
"// format exported functions, if present, from config for shell script",
"let",
"expFuncStr",
"=",
"''",
";",
"if",
"(",
"config",
".",
"exported_functions",
"&&",
"config",
".",
"exported_functions",
".",
"length",
">",
"0",
")",
"{",
"let",
"expFuncs",
"=",
"config",
".",
"exported_functions",
".",
"reduce",
"(",
"(",
"acc",
",",
"val",
")",
"=>",
"acc",
".",
"concat",
"(",
"'\\''",
",",
"val",
",",
"'\\'\\,'",
")",
",",
"'['",
")",
";",
"expFuncs",
"=",
"expFuncs",
".",
"substring",
"(",
"0",
",",
"expFuncs",
".",
"length",
"-",
"1",
")",
".",
"concat",
"(",
"']'",
")",
";",
"expFuncStr",
"=",
"`",
"${",
"expFuncs",
"}",
"`",
";",
"}",
"// format flags from config for shell script",
"const",
"flags",
"=",
"config",
".",
"flags",
".",
"reduce",
"(",
"(",
"acc",
",",
"val",
")",
"=>",
"acc",
".",
"concat",
"(",
"' '",
",",
"val",
")",
",",
"''",
")",
";",
"// construct the default compile mode string.",
"let",
"commandStr",
"=",
"`",
"${",
"config",
".",
"outputfile",
"}",
"${",
"config",
".",
"inputfile",
"}",
"${",
"expFuncStr",
"}",
"${",
"flags",
"}",
"`",
";",
"// generate a command string suitable for cmake",
"if",
"(",
"config",
".",
"mode",
"==",
"\"build\"",
")",
"{",
"// assuming make",
"config",
".",
"generator",
"=",
"config",
".",
"generator",
"?",
"config",
".",
"generator",
":",
"'make'",
";",
"switch",
"(",
"config",
".",
"generator",
")",
"{",
"case",
"'ninja'",
":",
"config",
".",
"gen_flag",
"=",
"'Ninja'",
";",
"default",
":",
"config",
".",
"gen_flag",
"=",
"'\"Unix Makefiles\"'",
";",
"break",
";",
"}",
"// need to triple escape double quotes",
"expFuncStr",
"=",
"expFuncStr",
".",
"replace",
"(",
"/",
"\"",
"/",
"g",
",",
"'\\\\\\\"'",
")",
";",
"let",
"modFlags",
"=",
"flags",
".",
"replace",
"(",
"/",
"\"",
"/",
"g",
",",
"'\\\\\\\"'",
")",
";",
"let",
"cxxFlagStr",
"=",
"`",
"${",
"modFlags",
"}",
"${",
"expFuncStr",
"}",
"`",
";",
"// pass through cmake configuration, inc. compiler flags, exported functions",
"commandStr",
"=",
"`",
"${",
"config",
".",
"gen_flag",
"}",
"`",
"+",
"`",
"\\\"",
"${",
"modFlags",
"}",
"${",
"expFuncStr",
"}",
"\\\"",
"`",
"+",
"`",
"${",
"config",
".",
"generator",
"}",
"${",
"cpuCount",
"-",
"1",
"}",
"`",
";",
"}",
"process",
".",
"stdout",
".",
"write",
"(",
"colors",
".",
"cyan",
"(",
"'Running emscripten...\\n'",
")",
")",
";",
"// execute shell script",
"// exec(shellScript, (error, stdout, stderr) => {",
"exec",
"(",
"`",
"${",
"config",
".",
"emscripten_path",
"}",
"${",
"commandStr",
"}",
"`",
",",
"{",
"shell",
":",
"'/bin/bash'",
"}",
",",
"(",
"error",
",",
"stdout",
",",
"stderr",
")",
"=>",
"{",
"// check for emcc compile errors",
"if",
"(",
"stderr",
")",
"{",
"process",
".",
"stderr",
".",
"write",
"(",
"colors",
".",
"red",
".",
"bold",
"(",
"'EMSCRIPTEN COMPILE ERROR\\n'",
")",
")",
";",
"process",
".",
"stderr",
".",
"write",
"(",
"colors",
".",
"white",
"(",
"stderr",
")",
")",
";",
"}",
"else",
"{",
"process",
".",
"stdout",
".",
"write",
"(",
"stdout",
")",
";",
"insertEventListener",
"(",
"config",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"colors",
".",
"green",
".",
"bold",
"(",
"'Compiled C++ to WASM\\n'",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] |
This function pulls parameters from the wasm.config.js file,
sets the emcc environment and calls the emcc compile arguments
via shell commands
@param {Object} config
|
[
"This",
"function",
"pulls",
"parameters",
"from",
"the",
"wasm",
".",
"config",
".",
"js",
"file",
"sets",
"the",
"emcc",
"environment",
"and",
"calls",
"the",
"emcc",
"compile",
"arguments",
"via",
"shell",
"commands"
] |
ab04ad29d447e29513b7f379876f53e77b3e0222
|
https://github.com/shamadee/wasm-init/blob/ab04ad29d447e29513b7f379876f53e77b3e0222/lib/compileWASM.js#L14-L80
|
19,575
|
shamadee/wasm-init
|
lib/compileWASM.js
|
insertEventListener
|
function insertEventListener (config) {
let outFile = path.join(process.cwd(), config.outputfile);
let tempFile = `${outFile.slice(0, outFile.lastIndexOf('.'), 0)}.temp${outFile.slice(outFile.lastIndexOf('.'))}`;
// read in generated emscripten file
fs.readFile(outFile, 'utf-8', (err1, data) => {
if (err1) process.stderr.write(colors.white(err1));
// insert eventListener
data = data.replace(/else\{doRun\(\)\}/g, 'else{doRun()}script.dispatchEvent(doneEvent);');
// write data to temporary file
fs.writeFile(tempFile, data, (err2) => {
if (err2) process.stderr.write(colors.white(err2));
// rename temporary file to original file name
fs.renameSync(tempFile, outFile);
});
});
}
|
javascript
|
function insertEventListener (config) {
let outFile = path.join(process.cwd(), config.outputfile);
let tempFile = `${outFile.slice(0, outFile.lastIndexOf('.'), 0)}.temp${outFile.slice(outFile.lastIndexOf('.'))}`;
// read in generated emscripten file
fs.readFile(outFile, 'utf-8', (err1, data) => {
if (err1) process.stderr.write(colors.white(err1));
// insert eventListener
data = data.replace(/else\{doRun\(\)\}/g, 'else{doRun()}script.dispatchEvent(doneEvent);');
// write data to temporary file
fs.writeFile(tempFile, data, (err2) => {
if (err2) process.stderr.write(colors.white(err2));
// rename temporary file to original file name
fs.renameSync(tempFile, outFile);
});
});
}
|
[
"function",
"insertEventListener",
"(",
"config",
")",
"{",
"let",
"outFile",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"config",
".",
"outputfile",
")",
";",
"let",
"tempFile",
"=",
"`",
"${",
"outFile",
".",
"slice",
"(",
"0",
",",
"outFile",
".",
"lastIndexOf",
"(",
"'.'",
")",
",",
"0",
")",
"}",
"${",
"outFile",
".",
"slice",
"(",
"outFile",
".",
"lastIndexOf",
"(",
"'.'",
")",
")",
"}",
"`",
";",
"// read in generated emscripten file",
"fs",
".",
"readFile",
"(",
"outFile",
",",
"'utf-8'",
",",
"(",
"err1",
",",
"data",
")",
"=>",
"{",
"if",
"(",
"err1",
")",
"process",
".",
"stderr",
".",
"write",
"(",
"colors",
".",
"white",
"(",
"err1",
")",
")",
";",
"// insert eventListener",
"data",
"=",
"data",
".",
"replace",
"(",
"/",
"else\\{doRun\\(\\)\\}",
"/",
"g",
",",
"'else{doRun()}script.dispatchEvent(doneEvent);'",
")",
";",
"// write data to temporary file",
"fs",
".",
"writeFile",
"(",
"tempFile",
",",
"data",
",",
"(",
"err2",
")",
"=>",
"{",
"if",
"(",
"err2",
")",
"process",
".",
"stderr",
".",
"write",
"(",
"colors",
".",
"white",
"(",
"err2",
")",
")",
";",
"// rename temporary file to original file name",
"fs",
".",
"renameSync",
"(",
"tempFile",
",",
"outFile",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Inserts an event listener into the autogenerated lib.js file
to notify us when WebAssembly has finished loading. As of April 2017,
this is needed because Firefox doesn't reliably emmit a script onload
notification
@param {Object} config
|
[
"Inserts",
"an",
"event",
"listener",
"into",
"the",
"autogenerated",
"lib",
".",
"js",
"file",
"to",
"notify",
"us",
"when",
"WebAssembly",
"has",
"finished",
"loading",
".",
"As",
"of",
"April",
"2017",
"this",
"is",
"needed",
"because",
"Firefox",
"doesn",
"t",
"reliably",
"emmit",
"a",
"script",
"onload",
"notification"
] |
ab04ad29d447e29513b7f379876f53e77b3e0222
|
https://github.com/shamadee/wasm-init/blob/ab04ad29d447e29513b7f379876f53e77b3e0222/lib/compileWASM.js#L89-L104
|
19,576
|
WeAreGenki/minna-ui
|
utils/build-css/index.js
|
cleanDistDir
|
function cleanDistDir(dir) {
/* istanbul ignore else */
if (dir !== process.cwd()) {
fs.stat(dir, (err) => {
if (!err) {
del.sync([dir]);
}
fs.mkdirSync(dir);
});
}
}
|
javascript
|
function cleanDistDir(dir) {
/* istanbul ignore else */
if (dir !== process.cwd()) {
fs.stat(dir, (err) => {
if (!err) {
del.sync([dir]);
}
fs.mkdirSync(dir);
});
}
}
|
[
"function",
"cleanDistDir",
"(",
"dir",
")",
"{",
"/* istanbul ignore else */",
"if",
"(",
"dir",
"!==",
"process",
".",
"cwd",
"(",
")",
")",
"{",
"fs",
".",
"stat",
"(",
"dir",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"del",
".",
"sync",
"(",
"[",
"dir",
"]",
")",
";",
"}",
"fs",
".",
"mkdirSync",
"(",
"dir",
")",
";",
"}",
")",
";",
"}",
"}"
] |
Remove old dist directory and make a new dist directory.
@param {string} dir The dist directory.
|
[
"Remove",
"old",
"dist",
"directory",
"and",
"make",
"a",
"new",
"dist",
"directory",
"."
] |
752e5828c34d133dbb628a6873ad1b886941e2a6
|
https://github.com/WeAreGenki/minna-ui/blob/752e5828c34d133dbb628a6873ad1b886941e2a6/utils/build-css/index.js#L47-L58
|
19,577
|
WeAreGenki/minna-ui
|
utils/build-css/index.js
|
processCss
|
async function processCss({ from, to, banner }) {
const src = await readFile(from, 'utf8');
const { plugins, options } = await postcssLoadConfig({
from,
to,
map: { inline: false },
});
const sourceCss = banner + src;
const result = await postcss(plugins).process(sourceCss, options);
compileWarn('PostCSS', 'WARN', result.warnings());
// minify resulting CSS
const min = await new CleanCSS({
level: {
1: { all: true },
2: { all: true },
},
returnPromise: true,
sourceMap: true,
}).minify(result.css, result.map.toString());
compileWarn('CleanCSS', 'ERR', min.errors);
compileWarn('CleanCSS', 'WARN', min.warnings);
// clean-css removes the source map comment so we need to add it back in
min.styles = `${min.styles}\n/*# sourceMappingURL=${basename(
options.to,
)}.map */`;
writeFile(options.to, min.styles);
writeFile(`${options.to}.map`, min.sourceMap.toString());
return {
min,
result,
};
}
|
javascript
|
async function processCss({ from, to, banner }) {
const src = await readFile(from, 'utf8');
const { plugins, options } = await postcssLoadConfig({
from,
to,
map: { inline: false },
});
const sourceCss = banner + src;
const result = await postcss(plugins).process(sourceCss, options);
compileWarn('PostCSS', 'WARN', result.warnings());
// minify resulting CSS
const min = await new CleanCSS({
level: {
1: { all: true },
2: { all: true },
},
returnPromise: true,
sourceMap: true,
}).minify(result.css, result.map.toString());
compileWarn('CleanCSS', 'ERR', min.errors);
compileWarn('CleanCSS', 'WARN', min.warnings);
// clean-css removes the source map comment so we need to add it back in
min.styles = `${min.styles}\n/*# sourceMappingURL=${basename(
options.to,
)}.map */`;
writeFile(options.to, min.styles);
writeFile(`${options.to}.map`, min.sourceMap.toString());
return {
min,
result,
};
}
|
[
"async",
"function",
"processCss",
"(",
"{",
"from",
",",
"to",
",",
"banner",
"}",
")",
"{",
"const",
"src",
"=",
"await",
"readFile",
"(",
"from",
",",
"'utf8'",
")",
";",
"const",
"{",
"plugins",
",",
"options",
"}",
"=",
"await",
"postcssLoadConfig",
"(",
"{",
"from",
",",
"to",
",",
"map",
":",
"{",
"inline",
":",
"false",
"}",
",",
"}",
")",
";",
"const",
"sourceCss",
"=",
"banner",
"+",
"src",
";",
"const",
"result",
"=",
"await",
"postcss",
"(",
"plugins",
")",
".",
"process",
"(",
"sourceCss",
",",
"options",
")",
";",
"compileWarn",
"(",
"'PostCSS'",
",",
"'WARN'",
",",
"result",
".",
"warnings",
"(",
")",
")",
";",
"// minify resulting CSS",
"const",
"min",
"=",
"await",
"new",
"CleanCSS",
"(",
"{",
"level",
":",
"{",
"1",
":",
"{",
"all",
":",
"true",
"}",
",",
"2",
":",
"{",
"all",
":",
"true",
"}",
",",
"}",
",",
"returnPromise",
":",
"true",
",",
"sourceMap",
":",
"true",
",",
"}",
")",
".",
"minify",
"(",
"result",
".",
"css",
",",
"result",
".",
"map",
".",
"toString",
"(",
")",
")",
";",
"compileWarn",
"(",
"'CleanCSS'",
",",
"'ERR'",
",",
"min",
".",
"errors",
")",
";",
"compileWarn",
"(",
"'CleanCSS'",
",",
"'WARN'",
",",
"min",
".",
"warnings",
")",
";",
"// clean-css removes the source map comment so we need to add it back in",
"min",
".",
"styles",
"=",
"`",
"${",
"min",
".",
"styles",
"}",
"\\n",
"${",
"basename",
"(",
"options",
".",
"to",
",",
")",
"}",
"`",
";",
"writeFile",
"(",
"options",
".",
"to",
",",
"min",
".",
"styles",
")",
";",
"writeFile",
"(",
"`",
"${",
"options",
".",
"to",
"}",
"`",
",",
"min",
".",
"sourceMap",
".",
"toString",
"(",
")",
")",
";",
"return",
"{",
"min",
",",
"result",
",",
"}",
";",
"}"
] |
Process CSS.
@param {Object} opts User defined options.
@param {string} opts.from File from.
@param {string} opts.to File to.
@param {string} opts.banner Banner to prepend to resulting code.
@returns {Promise<{min: Object, result: Object}>}
|
[
"Process",
"CSS",
"."
] |
752e5828c34d133dbb628a6873ad1b886941e2a6
|
https://github.com/WeAreGenki/minna-ui/blob/752e5828c34d133dbb628a6873ad1b886941e2a6/utils/build-css/index.js#L68-L107
|
19,578
|
WeAreGenki/minna-ui
|
utils/rollup-plugins/lib/devserver.js
|
humanizeSize
|
function humanizeSize(bytes) {
const index = Math.floor(Math.log(bytes) / Math.log(1024));
if (index < 0) return '';
return `${+((bytes / 1024) ** index).toFixed(2)} ${units[index]}`;
}
|
javascript
|
function humanizeSize(bytes) {
const index = Math.floor(Math.log(bytes) / Math.log(1024));
if (index < 0) return '';
return `${+((bytes / 1024) ** index).toFixed(2)} ${units[index]}`;
}
|
[
"function",
"humanizeSize",
"(",
"bytes",
")",
"{",
"const",
"index",
"=",
"Math",
".",
"floor",
"(",
"Math",
".",
"log",
"(",
"bytes",
")",
"/",
"Math",
".",
"log",
"(",
"1024",
")",
")",
";",
"if",
"(",
"index",
"<",
"0",
")",
"return",
"''",
";",
"return",
"`",
"${",
"+",
"(",
"(",
"bytes",
"/",
"1024",
")",
"**",
"index",
")",
".",
"toFixed",
"(",
"2",
")",
"}",
"${",
"units",
"[",
"index",
"]",
"}",
"`",
";",
"}"
] |
Convert bytes into a human readable form.
@param {number} bytes Number of bytes to convert.
@returns {string}
|
[
"Convert",
"bytes",
"into",
"a",
"human",
"readable",
"form",
"."
] |
752e5828c34d133dbb628a6873ad1b886941e2a6
|
https://github.com/WeAreGenki/minna-ui/blob/752e5828c34d133dbb628a6873ad1b886941e2a6/utils/rollup-plugins/lib/devserver.js#L32-L36
|
19,579
|
WeAreGenki/minna-ui
|
utils/rollup-plugins/lib/gitDescribe.js
|
gitDescribe
|
function gitDescribe() {
try {
const reference = execSync(
'git describe --always --dirty="-dev"',
).toString().trim();
return reference;
} catch (error) {
/* eslint-disable-next-line no-console */ /* tslint:disable-next-line no-console */
console.log(error);
}
}
|
javascript
|
function gitDescribe() {
try {
const reference = execSync(
'git describe --always --dirty="-dev"',
).toString().trim();
return reference;
} catch (error) {
/* eslint-disable-next-line no-console */ /* tslint:disable-next-line no-console */
console.log(error);
}
}
|
[
"function",
"gitDescribe",
"(",
")",
"{",
"try",
"{",
"const",
"reference",
"=",
"execSync",
"(",
"'git describe --always --dirty=\"-dev\"'",
",",
")",
".",
"toString",
"(",
")",
".",
"trim",
"(",
")",
";",
"return",
"reference",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"/* eslint-disable-next-line no-console */",
"/* tslint:disable-next-line no-console */",
"console",
".",
"log",
"(",
"error",
")",
";",
"}",
"}"
] |
Get the most recent git reference.
@see https://git-scm.com/docs/git-describe
@returns {(string|void)} A human readable git reference.
/* eslint-disable-next-line consistent-return
|
[
"Get",
"the",
"most",
"recent",
"git",
"reference",
"."
] |
752e5828c34d133dbb628a6873ad1b886941e2a6
|
https://github.com/WeAreGenki/minna-ui/blob/752e5828c34d133dbb628a6873ad1b886941e2a6/utils/rollup-plugins/lib/gitDescribe.js#L12-L22
|
19,580
|
WeAreGenki/minna-ui
|
utils/rollup-plugins/lib/makeHtml.js
|
makeHtml
|
function makeHtml({
file,
basePath = '/',
content = '%CSS%\n%JS%',
exclude,
include = ['**/*.css'],
inlineCss = false,
onCss = css => css,
scriptAttr = 'defer',
template = path.join(__dirname, 'template.html'),
title,
...data
}) {
const filter = createFilter(include, exclude);
// if `template` is a path and the file exists use its content otherwise
// assume that `template` is the actual template content itself
const htmlTemplate = existsSync(template)
? readFileSync(template, 'utf8')
: template;
/** @type {Object<string, string>} */
const styles = {};
return {
name: 'makeHtml',
transform(source, id) {
if (!filter(id)) return;
styles[id] = source;
return ''; // eslint-disable-line consistent-return
},
async generateBundle(outputOpts, bundle) {
// combine all style sheets
let css = '';
/* tslint:disable */
/* eslint-disable-next-line */
for (const id in styles) {
css += styles[id] || '';
}
/* tslint:enable */
if (typeof onCss === 'function') {
css = await Promise.resolve(onCss(css));
/* eslint-disable-next-line no-console */
if (!css) this.warn("onCss didn't return anything useful");
}
const jsFile = Object.values(bundle)[0].fileName || outputOpts.file;
const cssFile = jsFile.replace(/js$/, 'css');
/* eslint-disable-next-line no-nested-ternary */
const cssResult = !css.length
? ''
: inlineCss
? `<style>${css}</style>`
: `<link href=${basePath}${cssFile} rel=stylesheet>`;
let body = await Promise.resolve(content);
body = body.replace('%CSS%', cssResult);
body = body.replace(
'%JS%',
`<script src=${basePath}${jsFile} ${scriptAttr}></script>`,
);
const html = compileTemplate(htmlTemplate)({
title,
content: body,
...data,
}).trim();
if (!inlineCss) {
const cssOut = outputOpts.dir
? path.join(outputOpts.dir, cssFile)
: cssFile;
// write CSS file
writeFile(path.join(process.cwd(), cssOut), css, catchErr);
}
const fileOut = outputOpts.dir ? path.join(outputOpts.dir, file) : file;
// write HTML file
writeFile(path.join(process.cwd(), fileOut), html, catchErr);
},
};
}
|
javascript
|
function makeHtml({
file,
basePath = '/',
content = '%CSS%\n%JS%',
exclude,
include = ['**/*.css'],
inlineCss = false,
onCss = css => css,
scriptAttr = 'defer',
template = path.join(__dirname, 'template.html'),
title,
...data
}) {
const filter = createFilter(include, exclude);
// if `template` is a path and the file exists use its content otherwise
// assume that `template` is the actual template content itself
const htmlTemplate = existsSync(template)
? readFileSync(template, 'utf8')
: template;
/** @type {Object<string, string>} */
const styles = {};
return {
name: 'makeHtml',
transform(source, id) {
if (!filter(id)) return;
styles[id] = source;
return ''; // eslint-disable-line consistent-return
},
async generateBundle(outputOpts, bundle) {
// combine all style sheets
let css = '';
/* tslint:disable */
/* eslint-disable-next-line */
for (const id in styles) {
css += styles[id] || '';
}
/* tslint:enable */
if (typeof onCss === 'function') {
css = await Promise.resolve(onCss(css));
/* eslint-disable-next-line no-console */
if (!css) this.warn("onCss didn't return anything useful");
}
const jsFile = Object.values(bundle)[0].fileName || outputOpts.file;
const cssFile = jsFile.replace(/js$/, 'css');
/* eslint-disable-next-line no-nested-ternary */
const cssResult = !css.length
? ''
: inlineCss
? `<style>${css}</style>`
: `<link href=${basePath}${cssFile} rel=stylesheet>`;
let body = await Promise.resolve(content);
body = body.replace('%CSS%', cssResult);
body = body.replace(
'%JS%',
`<script src=${basePath}${jsFile} ${scriptAttr}></script>`,
);
const html = compileTemplate(htmlTemplate)({
title,
content: body,
...data,
}).trim();
if (!inlineCss) {
const cssOut = outputOpts.dir
? path.join(outputOpts.dir, cssFile)
: cssFile;
// write CSS file
writeFile(path.join(process.cwd(), cssOut), css, catchErr);
}
const fileOut = outputOpts.dir ? path.join(outputOpts.dir, file) : file;
// write HTML file
writeFile(path.join(process.cwd(), fileOut), html, catchErr);
},
};
}
|
[
"function",
"makeHtml",
"(",
"{",
"file",
",",
"basePath",
"=",
"'/'",
",",
"content",
"=",
"'%CSS%\\n%JS%'",
",",
"exclude",
",",
"include",
"=",
"[",
"'**/*.css'",
"]",
",",
"inlineCss",
"=",
"false",
",",
"onCss",
"=",
"css",
"=>",
"css",
",",
"scriptAttr",
"=",
"'defer'",
",",
"template",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'template.html'",
")",
",",
"title",
",",
"...",
"data",
"}",
")",
"{",
"const",
"filter",
"=",
"createFilter",
"(",
"include",
",",
"exclude",
")",
";",
"// if `template` is a path and the file exists use its content otherwise",
"// assume that `template` is the actual template content itself",
"const",
"htmlTemplate",
"=",
"existsSync",
"(",
"template",
")",
"?",
"readFileSync",
"(",
"template",
",",
"'utf8'",
")",
":",
"template",
";",
"/** @type {Object<string, string>} */",
"const",
"styles",
"=",
"{",
"}",
";",
"return",
"{",
"name",
":",
"'makeHtml'",
",",
"transform",
"(",
"source",
",",
"id",
")",
"{",
"if",
"(",
"!",
"filter",
"(",
"id",
")",
")",
"return",
";",
"styles",
"[",
"id",
"]",
"=",
"source",
";",
"return",
"''",
";",
"// eslint-disable-line consistent-return",
"}",
",",
"async",
"generateBundle",
"(",
"outputOpts",
",",
"bundle",
")",
"{",
"// combine all style sheets",
"let",
"css",
"=",
"''",
";",
"/* tslint:disable */",
"/* eslint-disable-next-line */",
"for",
"(",
"const",
"id",
"in",
"styles",
")",
"{",
"css",
"+=",
"styles",
"[",
"id",
"]",
"||",
"''",
";",
"}",
"/* tslint:enable */",
"if",
"(",
"typeof",
"onCss",
"===",
"'function'",
")",
"{",
"css",
"=",
"await",
"Promise",
".",
"resolve",
"(",
"onCss",
"(",
"css",
")",
")",
";",
"/* eslint-disable-next-line no-console */",
"if",
"(",
"!",
"css",
")",
"this",
".",
"warn",
"(",
"\"onCss didn't return anything useful\"",
")",
";",
"}",
"const",
"jsFile",
"=",
"Object",
".",
"values",
"(",
"bundle",
")",
"[",
"0",
"]",
".",
"fileName",
"||",
"outputOpts",
".",
"file",
";",
"const",
"cssFile",
"=",
"jsFile",
".",
"replace",
"(",
"/",
"js$",
"/",
",",
"'css'",
")",
";",
"/* eslint-disable-next-line no-nested-ternary */",
"const",
"cssResult",
"=",
"!",
"css",
".",
"length",
"?",
"''",
":",
"inlineCss",
"?",
"`",
"${",
"css",
"}",
"`",
":",
"`",
"${",
"basePath",
"}",
"${",
"cssFile",
"}",
"`",
";",
"let",
"body",
"=",
"await",
"Promise",
".",
"resolve",
"(",
"content",
")",
";",
"body",
"=",
"body",
".",
"replace",
"(",
"'%CSS%'",
",",
"cssResult",
")",
";",
"body",
"=",
"body",
".",
"replace",
"(",
"'%JS%'",
",",
"`",
"${",
"basePath",
"}",
"${",
"jsFile",
"}",
"${",
"scriptAttr",
"}",
"`",
",",
")",
";",
"const",
"html",
"=",
"compileTemplate",
"(",
"htmlTemplate",
")",
"(",
"{",
"title",
",",
"content",
":",
"body",
",",
"...",
"data",
",",
"}",
")",
".",
"trim",
"(",
")",
";",
"if",
"(",
"!",
"inlineCss",
")",
"{",
"const",
"cssOut",
"=",
"outputOpts",
".",
"dir",
"?",
"path",
".",
"join",
"(",
"outputOpts",
".",
"dir",
",",
"cssFile",
")",
":",
"cssFile",
";",
"// write CSS file",
"writeFile",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"cssOut",
")",
",",
"css",
",",
"catchErr",
")",
";",
"}",
"const",
"fileOut",
"=",
"outputOpts",
".",
"dir",
"?",
"path",
".",
"join",
"(",
"outputOpts",
".",
"dir",
",",
"file",
")",
":",
"file",
";",
"// write HTML file",
"writeFile",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"fileOut",
")",
",",
"html",
",",
"catchErr",
")",
";",
"}",
",",
"}",
";",
"}"
] |
Rollup plugin to generate HTML from a template and write it to disk.
@param {Object} opts User defined options.
@param {string} opts.file Path where to save the generated HTML file.
@param {string=} opts.basePath Path prefix for static files.
@param {(string|Promise<string>)=} opts.content Page HTML content. `%CSS%`
and `%JS%` will be replaced with tags referencing the files.
@param {Array<string>=} opts.exclude Files to exclude from CSS processing.
@param {Array<string>=} opts.include Files to include in CSS processing.
@param {boolean=} opts.inlineCss Should CSS be injected into the page instead
of saving an external file?
@param {function(string): (string|Promise<string>)=} opts.onCss Custom hook
to minify or post-processes CSS. Takes a function which has a `css` property
and returns the new CSS string. By default this does nothing.
@param {string=} opts.scriptAttr Attribute/s to add to script tag.
@param {string=} opts.template Absolute file path to a HTML document template
file or the template as a string.
@param {string=} opts.title Page title.
@param {...any=} opts.data Any other data you want available in the template.
@returns {Object} Rollup plugin
|
[
"Rollup",
"plugin",
"to",
"generate",
"HTML",
"from",
"a",
"template",
"and",
"write",
"it",
"to",
"disk",
"."
] |
752e5828c34d133dbb628a6873ad1b886941e2a6
|
https://github.com/WeAreGenki/minna-ui/blob/752e5828c34d133dbb628a6873ad1b886941e2a6/utils/rollup-plugins/lib/makeHtml.js#L45-L135
|
19,581
|
WeAreGenki/minna-ui
|
utils/rollup-plugins/lib/postcss.js
|
postcssRollup
|
function postcssRollup({
content = [
'__sapper__/build/*.html',
'__sapper__/build/*.js',
// FIXME: Using `dist` is the most reliable but requires 2 builds
// 'dist/**/*.html',
// 'dist/**/*.js',
'src/**/*.html',
'src/**/*.js',
],
context = {},
exclude = [],
include = ['**/*.css'],
optimize = process.env.NODE_ENV !== 'development',
whitelist = [],
} = {}) {
const filter = createFilter(include, exclude);
return {
name: 'postcss',
async transform(source, id) {
if (!filter(id)) return;
try {
const ctx = merge(
{ from: id, to: id, map: { inline: false, annotation: false } },
context,
);
const { plugins, options } = await postcssrc(ctx);
const result = await postcss(plugins).process(source, options);
result.warnings().forEach((warn) => {
this.warn(warn.toString(), { line: warn.line, column: warn.column });
});
// register sub-dependencies so rollup can monitor them for changes
if (result.map) {
const basePath = dirname(id);
// TODO: Don't use PostCSS private API
/* eslint-disable-next-line no-underscore-dangle */
result.map._sources._array.forEach((dep) => {
this.addWatchFile(join(basePath, dep));
});
}
if (!optimize) {
/* eslint-disable-next-line consistent-return */
return {
code: result.css,
map: result.map,
};
}
const purgecss = new Purgecss({
content,
whitelist,
css: [{ raw: result.css }],
keyframes: true,
});
const purged = purgecss.purge()[0];
/* eslint-disable-next-line consistent-return */
return {
code: purged.css,
map: purged.map,
};
} catch (err) {
if (err.name === 'CssSyntaxError') {
process.stderr.write(err.message + err.showSourceCode());
} else {
this.error(err);
}
}
},
};
}
|
javascript
|
function postcssRollup({
content = [
'__sapper__/build/*.html',
'__sapper__/build/*.js',
// FIXME: Using `dist` is the most reliable but requires 2 builds
// 'dist/**/*.html',
// 'dist/**/*.js',
'src/**/*.html',
'src/**/*.js',
],
context = {},
exclude = [],
include = ['**/*.css'],
optimize = process.env.NODE_ENV !== 'development',
whitelist = [],
} = {}) {
const filter = createFilter(include, exclude);
return {
name: 'postcss',
async transform(source, id) {
if (!filter(id)) return;
try {
const ctx = merge(
{ from: id, to: id, map: { inline: false, annotation: false } },
context,
);
const { plugins, options } = await postcssrc(ctx);
const result = await postcss(plugins).process(source, options);
result.warnings().forEach((warn) => {
this.warn(warn.toString(), { line: warn.line, column: warn.column });
});
// register sub-dependencies so rollup can monitor them for changes
if (result.map) {
const basePath = dirname(id);
// TODO: Don't use PostCSS private API
/* eslint-disable-next-line no-underscore-dangle */
result.map._sources._array.forEach((dep) => {
this.addWatchFile(join(basePath, dep));
});
}
if (!optimize) {
/* eslint-disable-next-line consistent-return */
return {
code: result.css,
map: result.map,
};
}
const purgecss = new Purgecss({
content,
whitelist,
css: [{ raw: result.css }],
keyframes: true,
});
const purged = purgecss.purge()[0];
/* eslint-disable-next-line consistent-return */
return {
code: purged.css,
map: purged.map,
};
} catch (err) {
if (err.name === 'CssSyntaxError') {
process.stderr.write(err.message + err.showSourceCode());
} else {
this.error(err);
}
}
},
};
}
|
[
"function",
"postcssRollup",
"(",
"{",
"content",
"=",
"[",
"'__sapper__/build/*.html'",
",",
"'__sapper__/build/*.js'",
",",
"// FIXME: Using `dist` is the most reliable but requires 2 builds",
"// 'dist/**/*.html',",
"// 'dist/**/*.js',",
"'src/**/*.html'",
",",
"'src/**/*.js'",
",",
"]",
",",
"context",
"=",
"{",
"}",
",",
"exclude",
"=",
"[",
"]",
",",
"include",
"=",
"[",
"'**/*.css'",
"]",
",",
"optimize",
"=",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'development'",
",",
"whitelist",
"=",
"[",
"]",
",",
"}",
"=",
"{",
"}",
")",
"{",
"const",
"filter",
"=",
"createFilter",
"(",
"include",
",",
"exclude",
")",
";",
"return",
"{",
"name",
":",
"'postcss'",
",",
"async",
"transform",
"(",
"source",
",",
"id",
")",
"{",
"if",
"(",
"!",
"filter",
"(",
"id",
")",
")",
"return",
";",
"try",
"{",
"const",
"ctx",
"=",
"merge",
"(",
"{",
"from",
":",
"id",
",",
"to",
":",
"id",
",",
"map",
":",
"{",
"inline",
":",
"false",
",",
"annotation",
":",
"false",
"}",
"}",
",",
"context",
",",
")",
";",
"const",
"{",
"plugins",
",",
"options",
"}",
"=",
"await",
"postcssrc",
"(",
"ctx",
")",
";",
"const",
"result",
"=",
"await",
"postcss",
"(",
"plugins",
")",
".",
"process",
"(",
"source",
",",
"options",
")",
";",
"result",
".",
"warnings",
"(",
")",
".",
"forEach",
"(",
"(",
"warn",
")",
"=>",
"{",
"this",
".",
"warn",
"(",
"warn",
".",
"toString",
"(",
")",
",",
"{",
"line",
":",
"warn",
".",
"line",
",",
"column",
":",
"warn",
".",
"column",
"}",
")",
";",
"}",
")",
";",
"// register sub-dependencies so rollup can monitor them for changes",
"if",
"(",
"result",
".",
"map",
")",
"{",
"const",
"basePath",
"=",
"dirname",
"(",
"id",
")",
";",
"// TODO: Don't use PostCSS private API",
"/* eslint-disable-next-line no-underscore-dangle */",
"result",
".",
"map",
".",
"_sources",
".",
"_array",
".",
"forEach",
"(",
"(",
"dep",
")",
"=>",
"{",
"this",
".",
"addWatchFile",
"(",
"join",
"(",
"basePath",
",",
"dep",
")",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"!",
"optimize",
")",
"{",
"/* eslint-disable-next-line consistent-return */",
"return",
"{",
"code",
":",
"result",
".",
"css",
",",
"map",
":",
"result",
".",
"map",
",",
"}",
";",
"}",
"const",
"purgecss",
"=",
"new",
"Purgecss",
"(",
"{",
"content",
",",
"whitelist",
",",
"css",
":",
"[",
"{",
"raw",
":",
"result",
".",
"css",
"}",
"]",
",",
"keyframes",
":",
"true",
",",
"}",
")",
";",
"const",
"purged",
"=",
"purgecss",
".",
"purge",
"(",
")",
"[",
"0",
"]",
";",
"/* eslint-disable-next-line consistent-return */",
"return",
"{",
"code",
":",
"purged",
".",
"css",
",",
"map",
":",
"purged",
".",
"map",
",",
"}",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"name",
"===",
"'CssSyntaxError'",
")",
"{",
"process",
".",
"stderr",
".",
"write",
"(",
"err",
".",
"message",
"+",
"err",
".",
"showSourceCode",
"(",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"error",
"(",
"err",
")",
";",
"}",
"}",
"}",
",",
"}",
";",
"}"
] |
Rollup plugin to process any imported CSS via PostCSS and optionally remove
unused styles for significantly smaller CSS bundles.
@param {Object} opts User defined options.
@param {(Array<string>|Function)=} opts.content Page content.
@param {Object=} opts.context Base PostCSS options.
@param {Array<string>=} opts.exclude Files to exclude from CSS processing.
@param {Array<string>=} opts.include Files to include in CSS processing.
@param {Array<string>=} opts.content Files to parse for CSS classes.
@param {boolean=} opts.optimize Should output CSS be minified and cleaned?
@param {Array<string>=} opts.whitelist CSS classes to always keep.
@returns {Object} Rollup plugin
|
[
"Rollup",
"plugin",
"to",
"process",
"any",
"imported",
"CSS",
"via",
"PostCSS",
"and",
"optionally",
"remove",
"unused",
"styles",
"for",
"significantly",
"smaller",
"CSS",
"bundles",
"."
] |
752e5828c34d133dbb628a6873ad1b886941e2a6
|
https://github.com/WeAreGenki/minna-ui/blob/752e5828c34d133dbb628a6873ad1b886941e2a6/utils/rollup-plugins/lib/postcss.js#L23-L100
|
19,582
|
sysgears/webpack-virtual-modules
|
virtual-stats.js
|
VirtualStats
|
function VirtualStats(config) {
for (var key in config) {
if (!config.hasOwnProperty(key)) {
continue;
}
this[key] = config[key];
}
}
|
javascript
|
function VirtualStats(config) {
for (var key in config) {
if (!config.hasOwnProperty(key)) {
continue;
}
this[key] = config[key];
}
}
|
[
"function",
"VirtualStats",
"(",
"config",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"config",
")",
"{",
"if",
"(",
"!",
"config",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"continue",
";",
"}",
"this",
"[",
"key",
"]",
"=",
"config",
"[",
"key",
"]",
";",
"}",
"}"
] |
Create a new stats object.
@param {Object} config Stats properties.
@constructor
|
[
"Create",
"a",
"new",
"stats",
"object",
"."
] |
649ccc0bdfec3faf0b559141e27da02b7225bd3b
|
https://github.com/sysgears/webpack-virtual-modules/blob/649ccc0bdfec3faf0b559141e27da02b7225bd3b/virtual-stats.js#L22-L29
|
19,583
|
auth0/passport-heroku-addon
|
lib/strategy.js
|
HerokuAddonStrategy
|
function HerokuAddonStrategy(options) {
if (!options || !options.sso_salt) throw new Error('Passport Heroku Addon strategy requires a sso_salt');
passport.Strategy.call(this);
this.name = 'heroku-addon';
this._sso_salt = options.sso_salt;
this._passReqToCallback = options.passReqToCallback;
}
|
javascript
|
function HerokuAddonStrategy(options) {
if (!options || !options.sso_salt) throw new Error('Passport Heroku Addon strategy requires a sso_salt');
passport.Strategy.call(this);
this.name = 'heroku-addon';
this._sso_salt = options.sso_salt;
this._passReqToCallback = options.passReqToCallback;
}
|
[
"function",
"HerokuAddonStrategy",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"options",
"||",
"!",
"options",
".",
"sso_salt",
")",
"throw",
"new",
"Error",
"(",
"'Passport Heroku Addon strategy requires a sso_salt'",
")",
";",
"passport",
".",
"Strategy",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"name",
"=",
"'heroku-addon'",
";",
"this",
".",
"_sso_salt",
"=",
"options",
".",
"sso_salt",
";",
"this",
".",
"_passReqToCallback",
"=",
"options",
".",
"passReqToCallback",
";",
"}"
] |
`HerokuAddonStrategy` constructor.
The Heroku Addon authentication strategy authenticates requests based on
request id and timestamp parameters.
Applications must supply a `sso_salt` secret to validate requests.
Examples:
passport.use(new HerokuAddonStrategy({
sso_salt: 'secret'
}));
@param {Object} options
@api public
|
[
"HerokuAddonStrategy",
"constructor",
"."
] |
1da376d5c432f97e21c173efdcc9e4f5293eaae6
|
https://github.com/auth0/passport-heroku-addon/blob/1da376d5c432f97e21c173efdcc9e4f5293eaae6/lib/strategy.js#L25-L33
|
19,584
|
inikulin/publish-please
|
src/reporters/elegant-status-reporter.js
|
reportSuccess
|
function reportSuccess(message) {
const chalk = require('chalk');
console.log(chalk.green(message));
console.log('');
}
|
javascript
|
function reportSuccess(message) {
const chalk = require('chalk');
console.log(chalk.green(message));
console.log('');
}
|
[
"function",
"reportSuccess",
"(",
"message",
")",
"{",
"const",
"chalk",
"=",
"require",
"(",
"'chalk'",
")",
";",
"console",
".",
"log",
"(",
"chalk",
".",
"green",
"(",
"message",
")",
")",
";",
"console",
".",
"log",
"(",
"''",
")",
";",
"}"
] |
report success message
@param {string} message - success message to be reported
|
[
"report",
"success",
"message"
] |
df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7
|
https://github.com/inikulin/publish-please/blob/df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7/src/reporters/elegant-status-reporter.js#L87-L91
|
19,585
|
inikulin/publish-please
|
src/reporters/elegant-status-reporter.js
|
reportSucceededProcess
|
function reportSucceededProcess(_message) {
const emoji = require('node-emoji').emoji;
console.log('');
console.log(emoji.tada, emoji.tada, emoji.tada);
}
|
javascript
|
function reportSucceededProcess(_message) {
const emoji = require('node-emoji').emoji;
console.log('');
console.log(emoji.tada, emoji.tada, emoji.tada);
}
|
[
"function",
"reportSucceededProcess",
"(",
"_message",
")",
"{",
"const",
"emoji",
"=",
"require",
"(",
"'node-emoji'",
")",
".",
"emoji",
";",
"console",
".",
"log",
"(",
"''",
")",
";",
"console",
".",
"log",
"(",
"emoji",
".",
"tada",
",",
"emoji",
".",
"tada",
",",
"emoji",
".",
"tada",
")",
";",
"}"
] |
report a successful execution of a process
@param {string} message
eslint-disable-next-line no-unused-vars
|
[
"report",
"a",
"successful",
"execution",
"of",
"a",
"process"
] |
df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7
|
https://github.com/inikulin/publish-please/blob/df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7/src/reporters/elegant-status-reporter.js#L155-L159
|
19,586
|
inikulin/publish-please
|
lib/reporters/ci-reporter.js
|
reportRunningTask
|
function reportRunningTask(taskname) {
const icon = require('./ci-icon');
function done(success) {
success
? console.log(`${icon.success()} ${taskname}`)
: console.log(`${icon.error()} ${taskname}`);
}
return done;
}
|
javascript
|
function reportRunningTask(taskname) {
const icon = require('./ci-icon');
function done(success) {
success
? console.log(`${icon.success()} ${taskname}`)
: console.log(`${icon.error()} ${taskname}`);
}
return done;
}
|
[
"function",
"reportRunningTask",
"(",
"taskname",
")",
"{",
"const",
"icon",
"=",
"require",
"(",
"'./ci-icon'",
")",
";",
"function",
"done",
"(",
"success",
")",
"{",
"success",
"?",
"console",
".",
"log",
"(",
"`",
"${",
"icon",
".",
"success",
"(",
")",
"}",
"${",
"taskname",
"}",
"`",
")",
":",
"console",
".",
"log",
"(",
"`",
"${",
"icon",
".",
"error",
"(",
")",
"}",
"${",
"taskname",
"}",
"`",
")",
";",
"}",
"return",
"done",
";",
"}"
] |
report a task that is executing and may take some time
@param {string} taskname
@returns {function(boolean): void} done - returns a function to be called when task has finished processing
done(true) -> report success
done(false) -> report failure
|
[
"report",
"a",
"task",
"that",
"is",
"executing",
"and",
"may",
"take",
"some",
"time"
] |
df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7
|
https://github.com/inikulin/publish-please/blob/df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7/lib/reporters/ci-reporter.js#L75-L84
|
19,587
|
inikulin/publish-please
|
src/utils/npm-audit.js
|
processResult
|
function processResult(result) {
return {
whenErrorIs: (errorCode) => {
if (
errorCode === EAUDITNOLOCK &&
packageLockHasNotBeenFound(result)
) {
const summary = result.error.summary || '';
result.error.summary = `package.json file is missing or is badly formatted. ${summary}`;
return result;
}
return result;
},
};
}
|
javascript
|
function processResult(result) {
return {
whenErrorIs: (errorCode) => {
if (
errorCode === EAUDITNOLOCK &&
packageLockHasNotBeenFound(result)
) {
const summary = result.error.summary || '';
result.error.summary = `package.json file is missing or is badly formatted. ${summary}`;
return result;
}
return result;
},
};
}
|
[
"function",
"processResult",
"(",
"result",
")",
"{",
"return",
"{",
"whenErrorIs",
":",
"(",
"errorCode",
")",
"=>",
"{",
"if",
"(",
"errorCode",
"===",
"EAUDITNOLOCK",
"&&",
"packageLockHasNotBeenFound",
"(",
"result",
")",
")",
"{",
"const",
"summary",
"=",
"result",
".",
"error",
".",
"summary",
"||",
"''",
";",
"result",
".",
"error",
".",
"summary",
"=",
"`",
"${",
"summary",
"}",
"`",
";",
"return",
"result",
";",
"}",
"return",
"result",
";",
"}",
",",
"}",
";",
"}"
] |
Middleware that intercept any input error object.
This middleware may modify the inital error message
@param {Object} result - result of the npm audit command
|
[
"Middleware",
"that",
"intercept",
"any",
"input",
"error",
"object",
".",
"This",
"middleware",
"may",
"modify",
"the",
"inital",
"error",
"message"
] |
df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7
|
https://github.com/inikulin/publish-please/blob/df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7/src/utils/npm-audit.js#L118-L132
|
19,588
|
inikulin/publish-please
|
src/utils/npm-audit.js
|
removePackageLockFrom
|
function removePackageLockFrom(projectDir, response) {
try {
const file = pathJoin(projectDir, 'package-lock.json');
unlink(file);
return response;
} catch (error) {
if (error.code === 'ENOENT') {
return response;
}
if (response) {
response.internalErrors = response.internalErrors || [];
response.internalErrors.push(error);
return response;
}
return response;
}
}
|
javascript
|
function removePackageLockFrom(projectDir, response) {
try {
const file = pathJoin(projectDir, 'package-lock.json');
unlink(file);
return response;
} catch (error) {
if (error.code === 'ENOENT') {
return response;
}
if (response) {
response.internalErrors = response.internalErrors || [];
response.internalErrors.push(error);
return response;
}
return response;
}
}
|
[
"function",
"removePackageLockFrom",
"(",
"projectDir",
",",
"response",
")",
"{",
"try",
"{",
"const",
"file",
"=",
"pathJoin",
"(",
"projectDir",
",",
"'package-lock.json'",
")",
";",
"unlink",
"(",
"file",
")",
";",
"return",
"response",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"if",
"(",
"error",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"return",
"response",
";",
"}",
"if",
"(",
"response",
")",
"{",
"response",
".",
"internalErrors",
"=",
"response",
".",
"internalErrors",
"||",
"[",
"]",
";",
"response",
".",
"internalErrors",
".",
"push",
"(",
"error",
")",
";",
"return",
"response",
";",
"}",
"return",
"response",
";",
"}",
"}"
] |
Middleware that removes the auto-generated package-lock.json
@param {string} projectDir - folder where the package-lock.json file has been generated
@param {*} response - result of the npm audit command (eventually modified by previous middlewares execution)
@returns input response if file removal is ok
In case of error it adds or updates into the input response object the property 'internalErrors'
|
[
"Middleware",
"that",
"removes",
"the",
"auto",
"-",
"generated",
"package",
"-",
"lock",
".",
"json"
] |
df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7
|
https://github.com/inikulin/publish-please/blob/df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7/src/utils/npm-audit.js#L141-L157
|
19,589
|
inikulin/publish-please
|
src/utils/npm-audit.js
|
removeIgnoredVulnerabilities
|
function removeIgnoredVulnerabilities(response, options) {
try {
const ignoredVulnerabilities = getIgnoredVulnerabilities(options);
if (ignoredVulnerabilities && ignoredVulnerabilities.length === 0) {
return response;
}
const filteredResponse = JSON.parse(JSON.stringify(response, null, 2));
/* prettier-ignore */
filteredResponse.actions = filteredResponse.actions
? filteredResponse.actions
.map((action) => {
action.resolves = action.resolves.filter(
(resolve) =>
ignoredVulnerabilities.indexOf(`${resolve.id}`) < 0
);
return action;
})
.filter((action) => action.resolves.length > 0)
: [];
ignoredVulnerabilities.forEach(
(ignoredVulnerability) =>
delete filteredResponse.advisories[ignoredVulnerability]
);
const vulnerabilitiesMetadata = {
info: 0,
low: 0,
moderate: 0,
high: 0,
critical: 0,
};
const severities = {};
const advisories = filteredResponse.advisories;
for (const key in advisories) {
if (advisories.hasOwnProperty(key)) {
const advisory = advisories[key];
severities[`${advisory.id}`] = advisory.severity;
}
}
filteredResponse.actions.forEach((action) => {
action.resolves.forEach((resolve) => {
vulnerabilitiesMetadata[severities[`${resolve.id}`]] += 1;
});
});
filteredResponse.metadata.vulnerabilities = vulnerabilitiesMetadata;
return filteredResponse;
} catch (error) {
if (response) {
response.internalErrors = response.internalErrors || [];
response.internalErrors.push(error);
return response;
}
return response;
}
}
|
javascript
|
function removeIgnoredVulnerabilities(response, options) {
try {
const ignoredVulnerabilities = getIgnoredVulnerabilities(options);
if (ignoredVulnerabilities && ignoredVulnerabilities.length === 0) {
return response;
}
const filteredResponse = JSON.parse(JSON.stringify(response, null, 2));
/* prettier-ignore */
filteredResponse.actions = filteredResponse.actions
? filteredResponse.actions
.map((action) => {
action.resolves = action.resolves.filter(
(resolve) =>
ignoredVulnerabilities.indexOf(`${resolve.id}`) < 0
);
return action;
})
.filter((action) => action.resolves.length > 0)
: [];
ignoredVulnerabilities.forEach(
(ignoredVulnerability) =>
delete filteredResponse.advisories[ignoredVulnerability]
);
const vulnerabilitiesMetadata = {
info: 0,
low: 0,
moderate: 0,
high: 0,
critical: 0,
};
const severities = {};
const advisories = filteredResponse.advisories;
for (const key in advisories) {
if (advisories.hasOwnProperty(key)) {
const advisory = advisories[key];
severities[`${advisory.id}`] = advisory.severity;
}
}
filteredResponse.actions.forEach((action) => {
action.resolves.forEach((resolve) => {
vulnerabilitiesMetadata[severities[`${resolve.id}`]] += 1;
});
});
filteredResponse.metadata.vulnerabilities = vulnerabilitiesMetadata;
return filteredResponse;
} catch (error) {
if (response) {
response.internalErrors = response.internalErrors || [];
response.internalErrors.push(error);
return response;
}
return response;
}
}
|
[
"function",
"removeIgnoredVulnerabilities",
"(",
"response",
",",
"options",
")",
"{",
"try",
"{",
"const",
"ignoredVulnerabilities",
"=",
"getIgnoredVulnerabilities",
"(",
"options",
")",
";",
"if",
"(",
"ignoredVulnerabilities",
"&&",
"ignoredVulnerabilities",
".",
"length",
"===",
"0",
")",
"{",
"return",
"response",
";",
"}",
"const",
"filteredResponse",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"response",
",",
"null",
",",
"2",
")",
")",
";",
"/* prettier-ignore */",
"filteredResponse",
".",
"actions",
"=",
"filteredResponse",
".",
"actions",
"?",
"filteredResponse",
".",
"actions",
".",
"map",
"(",
"(",
"action",
")",
"=>",
"{",
"action",
".",
"resolves",
"=",
"action",
".",
"resolves",
".",
"filter",
"(",
"(",
"resolve",
")",
"=>",
"ignoredVulnerabilities",
".",
"indexOf",
"(",
"`",
"${",
"resolve",
".",
"id",
"}",
"`",
")",
"<",
"0",
")",
";",
"return",
"action",
";",
"}",
")",
".",
"filter",
"(",
"(",
"action",
")",
"=>",
"action",
".",
"resolves",
".",
"length",
">",
"0",
")",
":",
"[",
"]",
";",
"ignoredVulnerabilities",
".",
"forEach",
"(",
"(",
"ignoredVulnerability",
")",
"=>",
"delete",
"filteredResponse",
".",
"advisories",
"[",
"ignoredVulnerability",
"]",
")",
";",
"const",
"vulnerabilitiesMetadata",
"=",
"{",
"info",
":",
"0",
",",
"low",
":",
"0",
",",
"moderate",
":",
"0",
",",
"high",
":",
"0",
",",
"critical",
":",
"0",
",",
"}",
";",
"const",
"severities",
"=",
"{",
"}",
";",
"const",
"advisories",
"=",
"filteredResponse",
".",
"advisories",
";",
"for",
"(",
"const",
"key",
"in",
"advisories",
")",
"{",
"if",
"(",
"advisories",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"const",
"advisory",
"=",
"advisories",
"[",
"key",
"]",
";",
"severities",
"[",
"`",
"${",
"advisory",
".",
"id",
"}",
"`",
"]",
"=",
"advisory",
".",
"severity",
";",
"}",
"}",
"filteredResponse",
".",
"actions",
".",
"forEach",
"(",
"(",
"action",
")",
"=>",
"{",
"action",
".",
"resolves",
".",
"forEach",
"(",
"(",
"resolve",
")",
"=>",
"{",
"vulnerabilitiesMetadata",
"[",
"severities",
"[",
"`",
"${",
"resolve",
".",
"id",
"}",
"`",
"]",
"]",
"+=",
"1",
";",
"}",
")",
";",
"}",
")",
";",
"filteredResponse",
".",
"metadata",
".",
"vulnerabilities",
"=",
"vulnerabilitiesMetadata",
";",
"return",
"filteredResponse",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"if",
"(",
"response",
")",
"{",
"response",
".",
"internalErrors",
"=",
"response",
".",
"internalErrors",
"||",
"[",
"]",
";",
"response",
".",
"internalErrors",
".",
"push",
"(",
"error",
")",
";",
"return",
"response",
";",
"}",
"return",
"response",
";",
"}",
"}"
] |
Remove, from npm audit command response, the vulnerabilities defined in .auditignore file
@param {*} response - result of the npm audit command (eventually modified by previous middlewares execution)
@param {DefaultOptions} options - options
|
[
"Remove",
"from",
"npm",
"audit",
"command",
"response",
"the",
"vulnerabilities",
"defined",
"in",
".",
"auditignore",
"file"
] |
df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7
|
https://github.com/inikulin/publish-please/blob/df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7/src/utils/npm-audit.js#L169-L229
|
19,590
|
inikulin/publish-please
|
src/utils/npm-audit.js
|
getLevelsToAudit
|
function getLevelsToAudit(options) {
const auditOptions = getNpmAuditOptions(options);
const auditLevelOption =
auditOptions && auditOptions['--audit-level']
? auditOptions['--audit-level']
: auditLevel.low;
const filteredLevels = [];
// prettier-ignore
switch (auditLevelOption) {
case auditLevel.critical:
filteredLevels.push(auditLevel.critical);
break;
case auditLevel.high:
filteredLevels.push(auditLevel.high);
filteredLevels.push(auditLevel.critical);
break;
case auditLevel.moderate:
filteredLevels.push(auditLevel.moderate);
filteredLevels.push(auditLevel.high);
filteredLevels.push(auditLevel.critical);
break;
default:
filteredLevels.push(auditLevel.low);
filteredLevels.push(auditLevel.moderate);
filteredLevels.push(auditLevel.high);
filteredLevels.push(auditLevel.critical);
}
return filteredLevels;
}
|
javascript
|
function getLevelsToAudit(options) {
const auditOptions = getNpmAuditOptions(options);
const auditLevelOption =
auditOptions && auditOptions['--audit-level']
? auditOptions['--audit-level']
: auditLevel.low;
const filteredLevels = [];
// prettier-ignore
switch (auditLevelOption) {
case auditLevel.critical:
filteredLevels.push(auditLevel.critical);
break;
case auditLevel.high:
filteredLevels.push(auditLevel.high);
filteredLevels.push(auditLevel.critical);
break;
case auditLevel.moderate:
filteredLevels.push(auditLevel.moderate);
filteredLevels.push(auditLevel.high);
filteredLevels.push(auditLevel.critical);
break;
default:
filteredLevels.push(auditLevel.low);
filteredLevels.push(auditLevel.moderate);
filteredLevels.push(auditLevel.high);
filteredLevels.push(auditLevel.critical);
}
return filteredLevels;
}
|
[
"function",
"getLevelsToAudit",
"(",
"options",
")",
"{",
"const",
"auditOptions",
"=",
"getNpmAuditOptions",
"(",
"options",
")",
";",
"const",
"auditLevelOption",
"=",
"auditOptions",
"&&",
"auditOptions",
"[",
"'--audit-level'",
"]",
"?",
"auditOptions",
"[",
"'--audit-level'",
"]",
":",
"auditLevel",
".",
"low",
";",
"const",
"filteredLevels",
"=",
"[",
"]",
";",
"// prettier-ignore",
"switch",
"(",
"auditLevelOption",
")",
"{",
"case",
"auditLevel",
".",
"critical",
":",
"filteredLevels",
".",
"push",
"(",
"auditLevel",
".",
"critical",
")",
";",
"break",
";",
"case",
"auditLevel",
".",
"high",
":",
"filteredLevels",
".",
"push",
"(",
"auditLevel",
".",
"high",
")",
";",
"filteredLevels",
".",
"push",
"(",
"auditLevel",
".",
"critical",
")",
";",
"break",
";",
"case",
"auditLevel",
".",
"moderate",
":",
"filteredLevels",
".",
"push",
"(",
"auditLevel",
".",
"moderate",
")",
";",
"filteredLevels",
".",
"push",
"(",
"auditLevel",
".",
"high",
")",
";",
"filteredLevels",
".",
"push",
"(",
"auditLevel",
".",
"critical",
")",
";",
"break",
";",
"default",
":",
"filteredLevels",
".",
"push",
"(",
"auditLevel",
".",
"low",
")",
";",
"filteredLevels",
".",
"push",
"(",
"auditLevel",
".",
"moderate",
")",
";",
"filteredLevels",
".",
"push",
"(",
"auditLevel",
".",
"high",
")",
";",
"filteredLevels",
".",
"push",
"(",
"auditLevel",
".",
"critical",
")",
";",
"}",
"return",
"filteredLevels",
";",
"}"
] |
Get Audit levels that should be kept in the response given by npm audit command execution
@param {DefaultOptions} options - default options of this module
@returns {[string]}
|
[
"Get",
"Audit",
"levels",
"that",
"should",
"be",
"kept",
"in",
"the",
"response",
"given",
"by",
"npm",
"audit",
"command",
"execution"
] |
df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7
|
https://github.com/inikulin/publish-please/blob/df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7/src/utils/npm-audit.js#L409-L439
|
19,591
|
inikulin/publish-please
|
src/utils/npm-audit.js
|
removeIgnoredLevels
|
function removeIgnoredLevels(response, options) {
try {
const filteredLevels = getLevelsToAudit(options);
if (filteredLevels && filteredLevels.indexOf(auditLevel.low) >= 0) {
return response;
}
const filteredResponse = JSON.parse(JSON.stringify(response, null, 2));
const ignoredVulnerabilities = [];
const advisories = filteredResponse.advisories || {};
for (const key in advisories) {
const advisory = advisories[key];
if (
advisory &&
advisory.severity &&
advisory.id &&
filteredLevels.indexOf(advisory.severity) < 0
) {
ignoredVulnerabilities.push(advisory.id);
}
}
ignoredVulnerabilities.forEach((ignoredVulnerabilityId) => {
delete filteredResponse.advisories[`${ignoredVulnerabilityId}`];
});
const severities = {};
for (const key in advisories) {
const advisory = advisories[key];
if (advisory && advisory.severity && advisory.id) {
severities[`${advisory.id}`] = advisory.severity;
}
}
/* prettier-ignore */
filteredResponse.actions = filteredResponse.actions
? filteredResponse.actions
.map((action) => {
action.resolves = action.resolves.filter(
(resolve) => ignoredVulnerabilities.indexOf(resolve.id) < 0
);
return action;
})
.filter((action) => action.resolves.length > 0)
: [];
const vulnerabilitiesMetadata = {
info: 0,
low: 0,
moderate: 0,
high: 0,
critical: 0,
};
filteredResponse.actions.forEach((action) => {
action.resolves.forEach((resolve) => {
if (resolve && resolve.id) {
vulnerabilitiesMetadata[severities[`${resolve.id}`]] += 1;
}
});
});
filteredResponse.metadata.vulnerabilities = vulnerabilitiesMetadata;
return filteredResponse;
} catch (error) {
if (response) {
response.internalErrors = response.internalErrors || [];
response.internalErrors.push(error);
return response;
}
return response;
}
}
|
javascript
|
function removeIgnoredLevels(response, options) {
try {
const filteredLevels = getLevelsToAudit(options);
if (filteredLevels && filteredLevels.indexOf(auditLevel.low) >= 0) {
return response;
}
const filteredResponse = JSON.parse(JSON.stringify(response, null, 2));
const ignoredVulnerabilities = [];
const advisories = filteredResponse.advisories || {};
for (const key in advisories) {
const advisory = advisories[key];
if (
advisory &&
advisory.severity &&
advisory.id &&
filteredLevels.indexOf(advisory.severity) < 0
) {
ignoredVulnerabilities.push(advisory.id);
}
}
ignoredVulnerabilities.forEach((ignoredVulnerabilityId) => {
delete filteredResponse.advisories[`${ignoredVulnerabilityId}`];
});
const severities = {};
for (const key in advisories) {
const advisory = advisories[key];
if (advisory && advisory.severity && advisory.id) {
severities[`${advisory.id}`] = advisory.severity;
}
}
/* prettier-ignore */
filteredResponse.actions = filteredResponse.actions
? filteredResponse.actions
.map((action) => {
action.resolves = action.resolves.filter(
(resolve) => ignoredVulnerabilities.indexOf(resolve.id) < 0
);
return action;
})
.filter((action) => action.resolves.length > 0)
: [];
const vulnerabilitiesMetadata = {
info: 0,
low: 0,
moderate: 0,
high: 0,
critical: 0,
};
filteredResponse.actions.forEach((action) => {
action.resolves.forEach((resolve) => {
if (resolve && resolve.id) {
vulnerabilitiesMetadata[severities[`${resolve.id}`]] += 1;
}
});
});
filteredResponse.metadata.vulnerabilities = vulnerabilitiesMetadata;
return filteredResponse;
} catch (error) {
if (response) {
response.internalErrors = response.internalErrors || [];
response.internalErrors.push(error);
return response;
}
return response;
}
}
|
[
"function",
"removeIgnoredLevels",
"(",
"response",
",",
"options",
")",
"{",
"try",
"{",
"const",
"filteredLevels",
"=",
"getLevelsToAudit",
"(",
"options",
")",
";",
"if",
"(",
"filteredLevels",
"&&",
"filteredLevels",
".",
"indexOf",
"(",
"auditLevel",
".",
"low",
")",
">=",
"0",
")",
"{",
"return",
"response",
";",
"}",
"const",
"filteredResponse",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"response",
",",
"null",
",",
"2",
")",
")",
";",
"const",
"ignoredVulnerabilities",
"=",
"[",
"]",
";",
"const",
"advisories",
"=",
"filteredResponse",
".",
"advisories",
"||",
"{",
"}",
";",
"for",
"(",
"const",
"key",
"in",
"advisories",
")",
"{",
"const",
"advisory",
"=",
"advisories",
"[",
"key",
"]",
";",
"if",
"(",
"advisory",
"&&",
"advisory",
".",
"severity",
"&&",
"advisory",
".",
"id",
"&&",
"filteredLevels",
".",
"indexOf",
"(",
"advisory",
".",
"severity",
")",
"<",
"0",
")",
"{",
"ignoredVulnerabilities",
".",
"push",
"(",
"advisory",
".",
"id",
")",
";",
"}",
"}",
"ignoredVulnerabilities",
".",
"forEach",
"(",
"(",
"ignoredVulnerabilityId",
")",
"=>",
"{",
"delete",
"filteredResponse",
".",
"advisories",
"[",
"`",
"${",
"ignoredVulnerabilityId",
"}",
"`",
"]",
";",
"}",
")",
";",
"const",
"severities",
"=",
"{",
"}",
";",
"for",
"(",
"const",
"key",
"in",
"advisories",
")",
"{",
"const",
"advisory",
"=",
"advisories",
"[",
"key",
"]",
";",
"if",
"(",
"advisory",
"&&",
"advisory",
".",
"severity",
"&&",
"advisory",
".",
"id",
")",
"{",
"severities",
"[",
"`",
"${",
"advisory",
".",
"id",
"}",
"`",
"]",
"=",
"advisory",
".",
"severity",
";",
"}",
"}",
"/* prettier-ignore */",
"filteredResponse",
".",
"actions",
"=",
"filteredResponse",
".",
"actions",
"?",
"filteredResponse",
".",
"actions",
".",
"map",
"(",
"(",
"action",
")",
"=>",
"{",
"action",
".",
"resolves",
"=",
"action",
".",
"resolves",
".",
"filter",
"(",
"(",
"resolve",
")",
"=>",
"ignoredVulnerabilities",
".",
"indexOf",
"(",
"resolve",
".",
"id",
")",
"<",
"0",
")",
";",
"return",
"action",
";",
"}",
")",
".",
"filter",
"(",
"(",
"action",
")",
"=>",
"action",
".",
"resolves",
".",
"length",
">",
"0",
")",
":",
"[",
"]",
";",
"const",
"vulnerabilitiesMetadata",
"=",
"{",
"info",
":",
"0",
",",
"low",
":",
"0",
",",
"moderate",
":",
"0",
",",
"high",
":",
"0",
",",
"critical",
":",
"0",
",",
"}",
";",
"filteredResponse",
".",
"actions",
".",
"forEach",
"(",
"(",
"action",
")",
"=>",
"{",
"action",
".",
"resolves",
".",
"forEach",
"(",
"(",
"resolve",
")",
"=>",
"{",
"if",
"(",
"resolve",
"&&",
"resolve",
".",
"id",
")",
"{",
"vulnerabilitiesMetadata",
"[",
"severities",
"[",
"`",
"${",
"resolve",
".",
"id",
"}",
"`",
"]",
"]",
"+=",
"1",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"filteredResponse",
".",
"metadata",
".",
"vulnerabilities",
"=",
"vulnerabilitiesMetadata",
";",
"return",
"filteredResponse",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"if",
"(",
"response",
")",
"{",
"response",
".",
"internalErrors",
"=",
"response",
".",
"internalErrors",
"||",
"[",
"]",
";",
"response",
".",
"internalErrors",
".",
"push",
"(",
"error",
")",
";",
"return",
"response",
";",
"}",
"return",
"response",
";",
"}",
"}"
] |
Remove, from npm audit command response, the vulnerabilities whose level is below the one defined in audit.opts file
@param {*} response - result of the npm audit command (eventually modified by previous middlewares execution)
@param {DefaultOptions} options - options
@returns {*} returns a new response object that is a deep copy of input response minus ignored levels.
when --audit-level=low, this method does nothing and returns input response.
|
[
"Remove",
"from",
"npm",
"audit",
"command",
"response",
"the",
"vulnerabilities",
"whose",
"level",
"is",
"below",
"the",
"one",
"defined",
"in",
"audit",
".",
"opts",
"file"
] |
df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7
|
https://github.com/inikulin/publish-please/blob/df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7/src/utils/npm-audit.js#L453-L526
|
19,592
|
inikulin/publish-please
|
src/utils/npm-audit-package.js
|
addSensitiveDataInfosIn
|
function addSensitiveDataInfosIn(response) {
const allSensitiveDataPatterns = getSensitiveData(process.cwd());
const augmentedResponse = JSON.parse(JSON.stringify(response, null, 2));
const files = augmentedResponse.files || [];
files.forEach((file) => {
if (file && isSensitiveData(file.path, allSensitiveDataPatterns)) {
file.isSensitiveData = true;
return;
}
if (file) {
file.isSensitiveData = false;
}
});
return augmentedResponse;
}
|
javascript
|
function addSensitiveDataInfosIn(response) {
const allSensitiveDataPatterns = getSensitiveData(process.cwd());
const augmentedResponse = JSON.parse(JSON.stringify(response, null, 2));
const files = augmentedResponse.files || [];
files.forEach((file) => {
if (file && isSensitiveData(file.path, allSensitiveDataPatterns)) {
file.isSensitiveData = true;
return;
}
if (file) {
file.isSensitiveData = false;
}
});
return augmentedResponse;
}
|
[
"function",
"addSensitiveDataInfosIn",
"(",
"response",
")",
"{",
"const",
"allSensitiveDataPatterns",
"=",
"getSensitiveData",
"(",
"process",
".",
"cwd",
"(",
")",
")",
";",
"const",
"augmentedResponse",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"response",
",",
"null",
",",
"2",
")",
")",
";",
"const",
"files",
"=",
"augmentedResponse",
".",
"files",
"||",
"[",
"]",
";",
"files",
".",
"forEach",
"(",
"(",
"file",
")",
"=>",
"{",
"if",
"(",
"file",
"&&",
"isSensitiveData",
"(",
"file",
".",
"path",
",",
"allSensitiveDataPatterns",
")",
")",
"{",
"file",
".",
"isSensitiveData",
"=",
"true",
";",
"return",
";",
"}",
"if",
"(",
"file",
")",
"{",
"file",
".",
"isSensitiveData",
"=",
"false",
";",
"}",
"}",
")",
";",
"return",
"augmentedResponse",
";",
"}"
] |
Add sensitive data infos for each file included in the package
@param {Object} response - result of the npm pack command (eventually modified by previous middlewares execution)
@returns {Object} returns a new response object that is a deep copy of input response
with each file being tagged with a new boolean property 'isSensitiveData'.
|
[
"Add",
"sensitive",
"data",
"infos",
"for",
"each",
"file",
"included",
"in",
"the",
"package"
] |
df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7
|
https://github.com/inikulin/publish-please/blob/df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7/src/utils/npm-audit-package.js#L96-L111
|
19,593
|
inikulin/publish-please
|
src/utils/npm-audit-package.js
|
isSensitiveData
|
function isSensitiveData(filepath, allSensitiveDataPatterns) {
if (
filepath &&
allSensitiveDataPatterns &&
allSensitiveDataPatterns.ignoredData &&
globMatching.any(filepath, allSensitiveDataPatterns.ignoredData, {
matchBase: true,
nocase: true,
})
) {
return false;
}
if (
filepath &&
allSensitiveDataPatterns &&
allSensitiveDataPatterns.sensitiveData &&
globMatching.any(filepath, allSensitiveDataPatterns.sensitiveData, {
matchBase: true,
nocase: true,
})
) {
return true;
}
return false;
}
|
javascript
|
function isSensitiveData(filepath, allSensitiveDataPatterns) {
if (
filepath &&
allSensitiveDataPatterns &&
allSensitiveDataPatterns.ignoredData &&
globMatching.any(filepath, allSensitiveDataPatterns.ignoredData, {
matchBase: true,
nocase: true,
})
) {
return false;
}
if (
filepath &&
allSensitiveDataPatterns &&
allSensitiveDataPatterns.sensitiveData &&
globMatching.any(filepath, allSensitiveDataPatterns.sensitiveData, {
matchBase: true,
nocase: true,
})
) {
return true;
}
return false;
}
|
[
"function",
"isSensitiveData",
"(",
"filepath",
",",
"allSensitiveDataPatterns",
")",
"{",
"if",
"(",
"filepath",
"&&",
"allSensitiveDataPatterns",
"&&",
"allSensitiveDataPatterns",
".",
"ignoredData",
"&&",
"globMatching",
".",
"any",
"(",
"filepath",
",",
"allSensitiveDataPatterns",
".",
"ignoredData",
",",
"{",
"matchBase",
":",
"true",
",",
"nocase",
":",
"true",
",",
"}",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"filepath",
"&&",
"allSensitiveDataPatterns",
"&&",
"allSensitiveDataPatterns",
".",
"sensitiveData",
"&&",
"globMatching",
".",
"any",
"(",
"filepath",
",",
"allSensitiveDataPatterns",
".",
"sensitiveData",
",",
"{",
"matchBase",
":",
"true",
",",
"nocase",
":",
"true",
",",
"}",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Check if file in filepath is sensitive data
@param {string} filepath
@param {DefaultSensitiveData} allSensitiveDataPatterns
@returns {boolean}
|
[
"Check",
"if",
"file",
"in",
"filepath",
"is",
"sensitive",
"data"
] |
df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7
|
https://github.com/inikulin/publish-please/blob/df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7/src/utils/npm-audit-package.js#L124-L149
|
19,594
|
inikulin/publish-please
|
src/utils/npm-audit-package.js
|
updateSensitiveDataInfosOfIgnoredFilesIn
|
function updateSensitiveDataInfosOfIgnoredFilesIn(response, options) {
const ignoredData = getIgnoredSensitiveData(options);
const updatedResponse = JSON.parse(JSON.stringify(response, null, 2));
const files = updatedResponse.files || [];
files.forEach((file) => {
if (
file &&
file.isSensitiveData &&
isIgnoredData(file.path, ignoredData)
) {
file.isSensitiveData = false;
return;
}
});
return updatedResponse;
}
|
javascript
|
function updateSensitiveDataInfosOfIgnoredFilesIn(response, options) {
const ignoredData = getIgnoredSensitiveData(options);
const updatedResponse = JSON.parse(JSON.stringify(response, null, 2));
const files = updatedResponse.files || [];
files.forEach((file) => {
if (
file &&
file.isSensitiveData &&
isIgnoredData(file.path, ignoredData)
) {
file.isSensitiveData = false;
return;
}
});
return updatedResponse;
}
|
[
"function",
"updateSensitiveDataInfosOfIgnoredFilesIn",
"(",
"response",
",",
"options",
")",
"{",
"const",
"ignoredData",
"=",
"getIgnoredSensitiveData",
"(",
"options",
")",
";",
"const",
"updatedResponse",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"response",
",",
"null",
",",
"2",
")",
")",
";",
"const",
"files",
"=",
"updatedResponse",
".",
"files",
"||",
"[",
"]",
";",
"files",
".",
"forEach",
"(",
"(",
"file",
")",
"=>",
"{",
"if",
"(",
"file",
"&&",
"file",
".",
"isSensitiveData",
"&&",
"isIgnoredData",
"(",
"file",
".",
"path",
",",
"ignoredData",
")",
")",
"{",
"file",
".",
"isSensitiveData",
"=",
"false",
";",
"return",
";",
"}",
"}",
")",
";",
"return",
"updatedResponse",
";",
"}"
] |
Update sensitive data infos for each ignored file included in the package
@param {Object} response - result of the npm pack command (eventually modified by previous middlewares execution)
@returns {Object} returns a new response object that is a deep copy of input response
with each ignored file being tagged with 'isSensitiveData=false'.
|
[
"Update",
"sensitive",
"data",
"infos",
"for",
"each",
"ignored",
"file",
"included",
"in",
"the",
"package"
] |
df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7
|
https://github.com/inikulin/publish-please/blob/df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7/src/utils/npm-audit-package.js#L157-L172
|
19,595
|
inikulin/publish-please
|
src/utils/npm-audit-package.js
|
getIgnoredSensitiveData
|
function getIgnoredSensitiveData(options) {
try {
const sensitiveDataIgnoreFile = pathJoin(
options.directoryToPackage,
'.publishrc'
);
const publishPleaseConfiguration = JSON.parse(
readFile(sensitiveDataIgnoreFile).toString()
);
const result =
publishPleaseConfiguration &&
publishPleaseConfiguration.validations &&
publishPleaseConfiguration.validations.sensitiveData &&
Array.isArray(
publishPleaseConfiguration.validations.sensitiveData.ignore
)
? publishPleaseConfiguration.validations.sensitiveData.ignore
: [];
return result;
} catch (error) {
return [];
}
}
|
javascript
|
function getIgnoredSensitiveData(options) {
try {
const sensitiveDataIgnoreFile = pathJoin(
options.directoryToPackage,
'.publishrc'
);
const publishPleaseConfiguration = JSON.parse(
readFile(sensitiveDataIgnoreFile).toString()
);
const result =
publishPleaseConfiguration &&
publishPleaseConfiguration.validations &&
publishPleaseConfiguration.validations.sensitiveData &&
Array.isArray(
publishPleaseConfiguration.validations.sensitiveData.ignore
)
? publishPleaseConfiguration.validations.sensitiveData.ignore
: [];
return result;
} catch (error) {
return [];
}
}
|
[
"function",
"getIgnoredSensitiveData",
"(",
"options",
")",
"{",
"try",
"{",
"const",
"sensitiveDataIgnoreFile",
"=",
"pathJoin",
"(",
"options",
".",
"directoryToPackage",
",",
"'.publishrc'",
")",
";",
"const",
"publishPleaseConfiguration",
"=",
"JSON",
".",
"parse",
"(",
"readFile",
"(",
"sensitiveDataIgnoreFile",
")",
".",
"toString",
"(",
")",
")",
";",
"const",
"result",
"=",
"publishPleaseConfiguration",
"&&",
"publishPleaseConfiguration",
".",
"validations",
"&&",
"publishPleaseConfiguration",
".",
"validations",
".",
"sensitiveData",
"&&",
"Array",
".",
"isArray",
"(",
"publishPleaseConfiguration",
".",
"validations",
".",
"sensitiveData",
".",
"ignore",
")",
"?",
"publishPleaseConfiguration",
".",
"validations",
".",
"sensitiveData",
".",
"ignore",
":",
"[",
"]",
";",
"return",
"result",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"[",
"]",
";",
"}",
"}"
] |
Get files, in .publishrc configuration file, that should be ignored within the npm package
@param {DefaultOptions} options
@returns {[string]} returns the list of files that should be ignored
|
[
"Get",
"files",
"in",
".",
"publishrc",
"configuration",
"file",
"that",
"should",
"be",
"ignored",
"within",
"the",
"npm",
"package"
] |
df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7
|
https://github.com/inikulin/publish-please/blob/df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7/src/utils/npm-audit-package.js#L266-L288
|
19,596
|
inikulin/publish-please
|
src/utils/npm-audit-package.js
|
removePackageTarFileFrom
|
function removePackageTarFileFrom(projectDir, response) {
try {
const file = pathJoin(projectDir, response.filename);
unlink(file);
return response;
} catch (error) {
if (error.code === 'ENOENT') {
return response;
}
if (response) {
response.internalErrors = response.internalErrors || [];
response.internalErrors.push(error);
return response;
}
return response;
}
}
|
javascript
|
function removePackageTarFileFrom(projectDir, response) {
try {
const file = pathJoin(projectDir, response.filename);
unlink(file);
return response;
} catch (error) {
if (error.code === 'ENOENT') {
return response;
}
if (response) {
response.internalErrors = response.internalErrors || [];
response.internalErrors.push(error);
return response;
}
return response;
}
}
|
[
"function",
"removePackageTarFileFrom",
"(",
"projectDir",
",",
"response",
")",
"{",
"try",
"{",
"const",
"file",
"=",
"pathJoin",
"(",
"projectDir",
",",
"response",
".",
"filename",
")",
";",
"unlink",
"(",
"file",
")",
";",
"return",
"response",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"if",
"(",
"error",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"return",
"response",
";",
"}",
"if",
"(",
"response",
")",
"{",
"response",
".",
"internalErrors",
"=",
"response",
".",
"internalErrors",
"||",
"[",
"]",
";",
"response",
".",
"internalErrors",
".",
"push",
"(",
"error",
")",
";",
"return",
"response",
";",
"}",
"return",
"response",
";",
"}",
"}"
] |
Middleware that removes the auto-generated package tar file
@param {string} projectDir - folder where the tar file has been generated
@param {*} response - result of the npm pack command (eventually modified by previous middlewares execution)
@returns input response if file removal is ok
In case of error it adds or updates into the input response object the property 'internalErrors'
|
[
"Middleware",
"that",
"removes",
"the",
"auto",
"-",
"generated",
"package",
"tar",
"file"
] |
df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7
|
https://github.com/inikulin/publish-please/blob/df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7/src/utils/npm-audit-package.js#L302-L318
|
19,597
|
inikulin/publish-please
|
src/utils/npm-audit-package.js
|
getCustomSensitiveData
|
function getCustomSensitiveData(projectDir) {
const sensitiveDataFile = pathJoin(projectDir, '.sensitivedata');
const content = readFile(sensitiveDataFile).toString();
const allPatterns = content
.split(/\n|\r/)
.map((line) => line.replace(/[\t]/g, ' '))
.map((line) => line.trim())
.filter((line) => line && line.length > 0)
.filter((line) => !line.startsWith('#'));
const sensitiveData = allPatterns.filter(
(pattern) => !pattern.startsWith('!')
);
const ignoredData = allPatterns
.filter((pattern) => pattern.startsWith('!'))
.map((pattern) => pattern.replace('!', ''))
.map((pattern) => pattern.trim());
return {
sensitiveData,
ignoredData,
};
}
|
javascript
|
function getCustomSensitiveData(projectDir) {
const sensitiveDataFile = pathJoin(projectDir, '.sensitivedata');
const content = readFile(sensitiveDataFile).toString();
const allPatterns = content
.split(/\n|\r/)
.map((line) => line.replace(/[\t]/g, ' '))
.map((line) => line.trim())
.filter((line) => line && line.length > 0)
.filter((line) => !line.startsWith('#'));
const sensitiveData = allPatterns.filter(
(pattern) => !pattern.startsWith('!')
);
const ignoredData = allPatterns
.filter((pattern) => pattern.startsWith('!'))
.map((pattern) => pattern.replace('!', ''))
.map((pattern) => pattern.trim());
return {
sensitiveData,
ignoredData,
};
}
|
[
"function",
"getCustomSensitiveData",
"(",
"projectDir",
")",
"{",
"const",
"sensitiveDataFile",
"=",
"pathJoin",
"(",
"projectDir",
",",
"'.sensitivedata'",
")",
";",
"const",
"content",
"=",
"readFile",
"(",
"sensitiveDataFile",
")",
".",
"toString",
"(",
")",
";",
"const",
"allPatterns",
"=",
"content",
".",
"split",
"(",
"/",
"\\n|\\r",
"/",
")",
".",
"map",
"(",
"(",
"line",
")",
"=>",
"line",
".",
"replace",
"(",
"/",
"[\\t]",
"/",
"g",
",",
"' '",
")",
")",
".",
"map",
"(",
"(",
"line",
")",
"=>",
"line",
".",
"trim",
"(",
")",
")",
".",
"filter",
"(",
"(",
"line",
")",
"=>",
"line",
"&&",
"line",
".",
"length",
">",
"0",
")",
".",
"filter",
"(",
"(",
"line",
")",
"=>",
"!",
"line",
".",
"startsWith",
"(",
"'#'",
")",
")",
";",
"const",
"sensitiveData",
"=",
"allPatterns",
".",
"filter",
"(",
"(",
"pattern",
")",
"=>",
"!",
"pattern",
".",
"startsWith",
"(",
"'!'",
")",
")",
";",
"const",
"ignoredData",
"=",
"allPatterns",
".",
"filter",
"(",
"(",
"pattern",
")",
"=>",
"pattern",
".",
"startsWith",
"(",
"'!'",
")",
")",
".",
"map",
"(",
"(",
"pattern",
")",
"=>",
"pattern",
".",
"replace",
"(",
"'!'",
",",
"''",
")",
")",
".",
"map",
"(",
"(",
"pattern",
")",
"=>",
"pattern",
".",
"trim",
"(",
")",
")",
";",
"return",
"{",
"sensitiveData",
",",
"ignoredData",
",",
"}",
";",
"}"
] |
get all sensitive data from the '.sensitivedata' file
@param {string} projectDir - directory that contains a .sensitivedata file
@returns {DefaultSensitiveData}
|
[
"get",
"all",
"sensitive",
"data",
"from",
"the",
".",
"sensitivedata",
"file"
] |
df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7
|
https://github.com/inikulin/publish-please/blob/df6fb07d1ee49de6bdd8e7ffd1d1c96d4171f7f7/src/utils/npm-audit-package.js#L330-L353
|
19,598
|
lastmjs/zwitterion
|
main.js
|
createNodeServer
|
function createNodeServer(http, nodePort, webSocketPort, watchFiles, tsWarning, tsError, target) {
return http.createServer(async (req, res) => {
try {
const fileExtension = req.url.slice(req.url.lastIndexOf('.') + 1);
switch (fileExtension) {
case '/': {
const indexFileContents = (await fs.readFile(`./index.html`)).toString();
const modifiedIndexFileContents = modifyHTML(indexFileContents, 'index.html', watchFiles, webSocketPort);
watchFile(`./index.html`, watchFiles);
res.end(modifiedIndexFileContents);
return;
}
case 'js': {
await handleScriptExtension(req, res, fileExtension);
return;
}
case 'mjs': {
await handleScriptExtension(req, res, fileExtension);
return;
}
case 'ts': {
await handleScriptExtension(req, res, fileExtension);
return;
}
case 'tsx': {
await handleScriptExtension(req, res, fileExtension);
return;
}
case 'jsx': {
await handleScriptExtension(req, res, fileExtension);
return;
}
case 'wast': {
await handleWASTExtension(req, res, fileExtension);
return;
}
case 'wasm': {
await handleWASMExtension(req, res, fileExtension);
return;
}
default: {
await handleGenericFile(req, res, fileExtension);
return;
}
}
}
catch(error) {
console.log(error);
}
});
}
|
javascript
|
function createNodeServer(http, nodePort, webSocketPort, watchFiles, tsWarning, tsError, target) {
return http.createServer(async (req, res) => {
try {
const fileExtension = req.url.slice(req.url.lastIndexOf('.') + 1);
switch (fileExtension) {
case '/': {
const indexFileContents = (await fs.readFile(`./index.html`)).toString();
const modifiedIndexFileContents = modifyHTML(indexFileContents, 'index.html', watchFiles, webSocketPort);
watchFile(`./index.html`, watchFiles);
res.end(modifiedIndexFileContents);
return;
}
case 'js': {
await handleScriptExtension(req, res, fileExtension);
return;
}
case 'mjs': {
await handleScriptExtension(req, res, fileExtension);
return;
}
case 'ts': {
await handleScriptExtension(req, res, fileExtension);
return;
}
case 'tsx': {
await handleScriptExtension(req, res, fileExtension);
return;
}
case 'jsx': {
await handleScriptExtension(req, res, fileExtension);
return;
}
case 'wast': {
await handleWASTExtension(req, res, fileExtension);
return;
}
case 'wasm': {
await handleWASMExtension(req, res, fileExtension);
return;
}
default: {
await handleGenericFile(req, res, fileExtension);
return;
}
}
}
catch(error) {
console.log(error);
}
});
}
|
[
"function",
"createNodeServer",
"(",
"http",
",",
"nodePort",
",",
"webSocketPort",
",",
"watchFiles",
",",
"tsWarning",
",",
"tsError",
",",
"target",
")",
"{",
"return",
"http",
".",
"createServer",
"(",
"async",
"(",
"req",
",",
"res",
")",
"=>",
"{",
"try",
"{",
"const",
"fileExtension",
"=",
"req",
".",
"url",
".",
"slice",
"(",
"req",
".",
"url",
".",
"lastIndexOf",
"(",
"'.'",
")",
"+",
"1",
")",
";",
"switch",
"(",
"fileExtension",
")",
"{",
"case",
"'/'",
":",
"{",
"const",
"indexFileContents",
"=",
"(",
"await",
"fs",
".",
"readFile",
"(",
"`",
"`",
")",
")",
".",
"toString",
"(",
")",
";",
"const",
"modifiedIndexFileContents",
"=",
"modifyHTML",
"(",
"indexFileContents",
",",
"'index.html'",
",",
"watchFiles",
",",
"webSocketPort",
")",
";",
"watchFile",
"(",
"`",
"`",
",",
"watchFiles",
")",
";",
"res",
".",
"end",
"(",
"modifiedIndexFileContents",
")",
";",
"return",
";",
"}",
"case",
"'js'",
":",
"{",
"await",
"handleScriptExtension",
"(",
"req",
",",
"res",
",",
"fileExtension",
")",
";",
"return",
";",
"}",
"case",
"'mjs'",
":",
"{",
"await",
"handleScriptExtension",
"(",
"req",
",",
"res",
",",
"fileExtension",
")",
";",
"return",
";",
"}",
"case",
"'ts'",
":",
"{",
"await",
"handleScriptExtension",
"(",
"req",
",",
"res",
",",
"fileExtension",
")",
";",
"return",
";",
"}",
"case",
"'tsx'",
":",
"{",
"await",
"handleScriptExtension",
"(",
"req",
",",
"res",
",",
"fileExtension",
")",
";",
"return",
";",
"}",
"case",
"'jsx'",
":",
"{",
"await",
"handleScriptExtension",
"(",
"req",
",",
"res",
",",
"fileExtension",
")",
";",
"return",
";",
"}",
"case",
"'wast'",
":",
"{",
"await",
"handleWASTExtension",
"(",
"req",
",",
"res",
",",
"fileExtension",
")",
";",
"return",
";",
"}",
"case",
"'wasm'",
":",
"{",
"await",
"handleWASMExtension",
"(",
"req",
",",
"res",
",",
"fileExtension",
")",
";",
"return",
";",
"}",
"default",
":",
"{",
"await",
"handleGenericFile",
"(",
"req",
",",
"res",
",",
"fileExtension",
")",
";",
"return",
";",
"}",
"}",
"}",
"catch",
"(",
"error",
")",
"{",
"console",
".",
"log",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}"
] |
end side-effects
|
[
"end",
"side",
"-",
"effects"
] |
7eb8cd2dbb8c869b99c3f057ee7769665c06c681
|
https://github.com/lastmjs/zwitterion/blob/7eb8cd2dbb8c869b99c3f057ee7769665c06c681/main.js#L180-L230
|
19,599
|
mapbox/vtshaver
|
lib/styleToFilters.js
|
styleToFilters
|
function styleToFilters(style) {
var layers = {};
// Store layers and filters used in style
if (style && style.layers) {
for (var i = 0; i < style.layers.length; i++) {
var layerName = style.layers[i]['source-layer'];
if (layerName) {
// if the layer already exists in our filters, update it
if (layers[layerName]) {
// Update zoom levels
var styleMin = style.layers[i].minzoom || 0;
var styleMax = style.layers[i].maxzoom || 22;
if (styleMin < layers[layerName].minzoom) layers[layerName].minzoom = styleMin;
if (styleMax > layers[layerName].maxzoom) layers[layerName].maxzoom = styleMax;
// Modify filter
if (layers[layerName].filters === true || !style.layers[i].filter) {
layers[layerName].filters = true;
} else {
layers[layerName].filters.push(style.layers[i].filter);
}
} else {
// otherwise create the layer & filter array, with min/max zoom
layers[layerName] = {};
layers[layerName].filters = style.layers[i].filter ? ['any', style.layers[i].filter] : true;
layers[layerName].minzoom = style.layers[i].minzoom || 0;
layers[layerName].maxzoom = style.layers[i].maxzoom || 22;
}
// Collect the used properties
// 1. from paint, layout, and filter
layers[layerName].properties = layers[layerName].properties || [];
['paint', 'layout'].forEach(item => {
let itemObject = style.layers[i][item];
itemObject && getPropertyFromLayoutAndPainter(itemObject, layers[layerName].properties);
});
// 2. from filter
if (style.layers[i].filter) {
getPropertyFromFilter(style.layers[i].filter, layers[layerName].properties);
}
}
}
}
// remove duplicate propertys and fix choose all the propertys in layers[i].properties
Object.keys(layers).forEach(layerId => {
let properties = layers[layerId].properties;
if (properties.indexOf(true) !== -1) {
layers[layerId].properties = true;
} else {
let unique = {};
properties.forEach(function(i) {
if (!unique[i]) {
unique[i] = true;
}
});
layers[layerId].properties = Object.keys(unique);
}
});
return layers;
}
|
javascript
|
function styleToFilters(style) {
var layers = {};
// Store layers and filters used in style
if (style && style.layers) {
for (var i = 0; i < style.layers.length; i++) {
var layerName = style.layers[i]['source-layer'];
if (layerName) {
// if the layer already exists in our filters, update it
if (layers[layerName]) {
// Update zoom levels
var styleMin = style.layers[i].minzoom || 0;
var styleMax = style.layers[i].maxzoom || 22;
if (styleMin < layers[layerName].minzoom) layers[layerName].minzoom = styleMin;
if (styleMax > layers[layerName].maxzoom) layers[layerName].maxzoom = styleMax;
// Modify filter
if (layers[layerName].filters === true || !style.layers[i].filter) {
layers[layerName].filters = true;
} else {
layers[layerName].filters.push(style.layers[i].filter);
}
} else {
// otherwise create the layer & filter array, with min/max zoom
layers[layerName] = {};
layers[layerName].filters = style.layers[i].filter ? ['any', style.layers[i].filter] : true;
layers[layerName].minzoom = style.layers[i].minzoom || 0;
layers[layerName].maxzoom = style.layers[i].maxzoom || 22;
}
// Collect the used properties
// 1. from paint, layout, and filter
layers[layerName].properties = layers[layerName].properties || [];
['paint', 'layout'].forEach(item => {
let itemObject = style.layers[i][item];
itemObject && getPropertyFromLayoutAndPainter(itemObject, layers[layerName].properties);
});
// 2. from filter
if (style.layers[i].filter) {
getPropertyFromFilter(style.layers[i].filter, layers[layerName].properties);
}
}
}
}
// remove duplicate propertys and fix choose all the propertys in layers[i].properties
Object.keys(layers).forEach(layerId => {
let properties = layers[layerId].properties;
if (properties.indexOf(true) !== -1) {
layers[layerId].properties = true;
} else {
let unique = {};
properties.forEach(function(i) {
if (!unique[i]) {
unique[i] = true;
}
});
layers[layerId].properties = Object.keys(unique);
}
});
return layers;
}
|
[
"function",
"styleToFilters",
"(",
"style",
")",
"{",
"var",
"layers",
"=",
"{",
"}",
";",
"// Store layers and filters used in style",
"if",
"(",
"style",
"&&",
"style",
".",
"layers",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"style",
".",
"layers",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"layerName",
"=",
"style",
".",
"layers",
"[",
"i",
"]",
"[",
"'source-layer'",
"]",
";",
"if",
"(",
"layerName",
")",
"{",
"// if the layer already exists in our filters, update it",
"if",
"(",
"layers",
"[",
"layerName",
"]",
")",
"{",
"// Update zoom levels",
"var",
"styleMin",
"=",
"style",
".",
"layers",
"[",
"i",
"]",
".",
"minzoom",
"||",
"0",
";",
"var",
"styleMax",
"=",
"style",
".",
"layers",
"[",
"i",
"]",
".",
"maxzoom",
"||",
"22",
";",
"if",
"(",
"styleMin",
"<",
"layers",
"[",
"layerName",
"]",
".",
"minzoom",
")",
"layers",
"[",
"layerName",
"]",
".",
"minzoom",
"=",
"styleMin",
";",
"if",
"(",
"styleMax",
">",
"layers",
"[",
"layerName",
"]",
".",
"maxzoom",
")",
"layers",
"[",
"layerName",
"]",
".",
"maxzoom",
"=",
"styleMax",
";",
"// Modify filter",
"if",
"(",
"layers",
"[",
"layerName",
"]",
".",
"filters",
"===",
"true",
"||",
"!",
"style",
".",
"layers",
"[",
"i",
"]",
".",
"filter",
")",
"{",
"layers",
"[",
"layerName",
"]",
".",
"filters",
"=",
"true",
";",
"}",
"else",
"{",
"layers",
"[",
"layerName",
"]",
".",
"filters",
".",
"push",
"(",
"style",
".",
"layers",
"[",
"i",
"]",
".",
"filter",
")",
";",
"}",
"}",
"else",
"{",
"// otherwise create the layer & filter array, with min/max zoom",
"layers",
"[",
"layerName",
"]",
"=",
"{",
"}",
";",
"layers",
"[",
"layerName",
"]",
".",
"filters",
"=",
"style",
".",
"layers",
"[",
"i",
"]",
".",
"filter",
"?",
"[",
"'any'",
",",
"style",
".",
"layers",
"[",
"i",
"]",
".",
"filter",
"]",
":",
"true",
";",
"layers",
"[",
"layerName",
"]",
".",
"minzoom",
"=",
"style",
".",
"layers",
"[",
"i",
"]",
".",
"minzoom",
"||",
"0",
";",
"layers",
"[",
"layerName",
"]",
".",
"maxzoom",
"=",
"style",
".",
"layers",
"[",
"i",
"]",
".",
"maxzoom",
"||",
"22",
";",
"}",
"// Collect the used properties ",
"// 1. from paint, layout, and filter",
"layers",
"[",
"layerName",
"]",
".",
"properties",
"=",
"layers",
"[",
"layerName",
"]",
".",
"properties",
"||",
"[",
"]",
";",
"[",
"'paint'",
",",
"'layout'",
"]",
".",
"forEach",
"(",
"item",
"=>",
"{",
"let",
"itemObject",
"=",
"style",
".",
"layers",
"[",
"i",
"]",
"[",
"item",
"]",
";",
"itemObject",
"&&",
"getPropertyFromLayoutAndPainter",
"(",
"itemObject",
",",
"layers",
"[",
"layerName",
"]",
".",
"properties",
")",
";",
"}",
")",
";",
"// 2. from filter",
"if",
"(",
"style",
".",
"layers",
"[",
"i",
"]",
".",
"filter",
")",
"{",
"getPropertyFromFilter",
"(",
"style",
".",
"layers",
"[",
"i",
"]",
".",
"filter",
",",
"layers",
"[",
"layerName",
"]",
".",
"properties",
")",
";",
"}",
"}",
"}",
"}",
"// remove duplicate propertys and fix choose all the propertys in layers[i].properties",
"Object",
".",
"keys",
"(",
"layers",
")",
".",
"forEach",
"(",
"layerId",
"=>",
"{",
"let",
"properties",
"=",
"layers",
"[",
"layerId",
"]",
".",
"properties",
";",
"if",
"(",
"properties",
".",
"indexOf",
"(",
"true",
")",
"!==",
"-",
"1",
")",
"{",
"layers",
"[",
"layerId",
"]",
".",
"properties",
"=",
"true",
";",
"}",
"else",
"{",
"let",
"unique",
"=",
"{",
"}",
";",
"properties",
".",
"forEach",
"(",
"function",
"(",
"i",
")",
"{",
"if",
"(",
"!",
"unique",
"[",
"i",
"]",
")",
"{",
"unique",
"[",
"i",
"]",
"=",
"true",
";",
"}",
"}",
")",
";",
"layers",
"[",
"layerId",
"]",
".",
"properties",
"=",
"Object",
".",
"keys",
"(",
"unique",
")",
";",
"}",
"}",
")",
";",
"return",
"layers",
";",
"}"
] |
Takes optimized filter object from shaver.styleToFilters and returns c++ filters for shave.
@function styleToFilters
@param {Object} style - Mapbox GL Style JSON
@example
var shaver = require('@mapbox/vtshaver');
var style = require('/path/to/style.json');
var filters = shaver.styleToFilters(style);
console.log(filters);
// {
// "poi_label": ["!=","maki","cafe"],
// "road": ["==","class","path"],
// "water": true,
// ...
// }
|
[
"Takes",
"optimized",
"filter",
"object",
"from",
"shaver",
".",
"styleToFilters",
"and",
"returns",
"c",
"++",
"filters",
"for",
"shave",
"."
] |
2052929612c3eb376a5d470a30415ee4c2940698
|
https://github.com/mapbox/vtshaver/blob/2052929612c3eb376a5d470a30415ee4c2940698/lib/styleToFilters.js#L21-L80
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.