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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
14,000
|
MariaDB/mariadb-connector-nodejs
|
lib/connection.js
|
function(authFailHandler) {
_timeout = null;
const handshake = _receiveQueue.peekFront();
authFailHandler(
Errors.createError(
'Connection timeout',
true,
info,
'08S01',
Errors.ER_CONNECTION_TIMEOUT,
handshake ? handshake.stack : null
)
);
}
|
javascript
|
function(authFailHandler) {
_timeout = null;
const handshake = _receiveQueue.peekFront();
authFailHandler(
Errors.createError(
'Connection timeout',
true,
info,
'08S01',
Errors.ER_CONNECTION_TIMEOUT,
handshake ? handshake.stack : null
)
);
}
|
[
"function",
"(",
"authFailHandler",
")",
"{",
"_timeout",
"=",
"null",
";",
"const",
"handshake",
"=",
"_receiveQueue",
".",
"peekFront",
"(",
")",
";",
"authFailHandler",
"(",
"Errors",
".",
"createError",
"(",
"'Connection timeout'",
",",
"true",
",",
"info",
",",
"'08S01'",
",",
"Errors",
".",
"ER_CONNECTION_TIMEOUT",
",",
"handshake",
"?",
"handshake",
".",
"stack",
":",
"null",
")",
")",
";",
"}"
] |
Handle connection timeout.
@private
|
[
"Handle",
"connection",
"timeout",
"."
] |
a596445fcfb5c39a6861b65cff3b6cd83a84a359
|
https://github.com/MariaDB/mariadb-connector-nodejs/blob/a596445fcfb5c39a6861b65cff3b6cd83a84a359/lib/connection.js#L1014-L1027
|
|
14,001
|
MariaDB/mariadb-connector-nodejs
|
lib/connection.js
|
function() {
const err = Errors.createError(
'socket timeout',
true,
info,
'08S01',
Errors.ER_SOCKET_TIMEOUT
);
const packetMsgs = info.getLastPackets();
if (packetMsgs !== '') {
err.message = err.message + '\nlast received packets:\n' + packetMsgs;
}
_fatalError(err, true);
}
|
javascript
|
function() {
const err = Errors.createError(
'socket timeout',
true,
info,
'08S01',
Errors.ER_SOCKET_TIMEOUT
);
const packetMsgs = info.getLastPackets();
if (packetMsgs !== '') {
err.message = err.message + '\nlast received packets:\n' + packetMsgs;
}
_fatalError(err, true);
}
|
[
"function",
"(",
")",
"{",
"const",
"err",
"=",
"Errors",
".",
"createError",
"(",
"'socket timeout'",
",",
"true",
",",
"info",
",",
"'08S01'",
",",
"Errors",
".",
"ER_SOCKET_TIMEOUT",
")",
";",
"const",
"packetMsgs",
"=",
"info",
".",
"getLastPackets",
"(",
")",
";",
"if",
"(",
"packetMsgs",
"!==",
"''",
")",
"{",
"err",
".",
"message",
"=",
"err",
".",
"message",
"+",
"'\\nlast received packets:\\n'",
"+",
"packetMsgs",
";",
"}",
"_fatalError",
"(",
"err",
",",
"true",
")",
";",
"}"
] |
Handle socket timeout.
@private
|
[
"Handle",
"socket",
"timeout",
"."
] |
a596445fcfb5c39a6861b65cff3b6cd83a84a359
|
https://github.com/MariaDB/mariadb-connector-nodejs/blob/a596445fcfb5c39a6861b65cff3b6cd83a84a359/lib/connection.js#L1034-L1047
|
|
14,002
|
MariaDB/mariadb-connector-nodejs
|
lib/connection.js
|
function(authFailHandler, err) {
if (_status === Status.CLOSING || _status === Status.CLOSED) return;
_socket.writeBuf = () => {};
_socket.flush = () => {};
//socket has been ended without error
if (!err) {
err = Errors.createError(
'socket has unexpectedly been closed',
true,
info,
'08S01',
Errors.ER_SOCKET_UNEXPECTED_CLOSE
);
} else {
err.fatal = true;
this.sqlState = 'HY000';
}
const packetMsgs = info.getLastPackets();
if (packetMsgs !== '') {
err.message += '\nlast received packets:\n' + packetMsgs;
}
switch (_status) {
case Status.CONNECTING:
case Status.AUTHENTICATING:
const currentCmd = _receiveQueue.peekFront();
if (currentCmd && currentCmd.stack && err) {
err.stack +=
'\n From event:\n' +
currentCmd.stack.substring(currentCmd.stack.indexOf('\n') + 1);
}
authFailHandler(err);
break;
default:
_fatalError(err, false);
}
}
|
javascript
|
function(authFailHandler, err) {
if (_status === Status.CLOSING || _status === Status.CLOSED) return;
_socket.writeBuf = () => {};
_socket.flush = () => {};
//socket has been ended without error
if (!err) {
err = Errors.createError(
'socket has unexpectedly been closed',
true,
info,
'08S01',
Errors.ER_SOCKET_UNEXPECTED_CLOSE
);
} else {
err.fatal = true;
this.sqlState = 'HY000';
}
const packetMsgs = info.getLastPackets();
if (packetMsgs !== '') {
err.message += '\nlast received packets:\n' + packetMsgs;
}
switch (_status) {
case Status.CONNECTING:
case Status.AUTHENTICATING:
const currentCmd = _receiveQueue.peekFront();
if (currentCmd && currentCmd.stack && err) {
err.stack +=
'\n From event:\n' +
currentCmd.stack.substring(currentCmd.stack.indexOf('\n') + 1);
}
authFailHandler(err);
break;
default:
_fatalError(err, false);
}
}
|
[
"function",
"(",
"authFailHandler",
",",
"err",
")",
"{",
"if",
"(",
"_status",
"===",
"Status",
".",
"CLOSING",
"||",
"_status",
"===",
"Status",
".",
"CLOSED",
")",
"return",
";",
"_socket",
".",
"writeBuf",
"=",
"(",
")",
"=>",
"{",
"}",
";",
"_socket",
".",
"flush",
"=",
"(",
")",
"=>",
"{",
"}",
";",
"//socket has been ended without error",
"if",
"(",
"!",
"err",
")",
"{",
"err",
"=",
"Errors",
".",
"createError",
"(",
"'socket has unexpectedly been closed'",
",",
"true",
",",
"info",
",",
"'08S01'",
",",
"Errors",
".",
"ER_SOCKET_UNEXPECTED_CLOSE",
")",
";",
"}",
"else",
"{",
"err",
".",
"fatal",
"=",
"true",
";",
"this",
".",
"sqlState",
"=",
"'HY000'",
";",
"}",
"const",
"packetMsgs",
"=",
"info",
".",
"getLastPackets",
"(",
")",
";",
"if",
"(",
"packetMsgs",
"!==",
"''",
")",
"{",
"err",
".",
"message",
"+=",
"'\\nlast received packets:\\n'",
"+",
"packetMsgs",
";",
"}",
"switch",
"(",
"_status",
")",
"{",
"case",
"Status",
".",
"CONNECTING",
":",
"case",
"Status",
".",
"AUTHENTICATING",
":",
"const",
"currentCmd",
"=",
"_receiveQueue",
".",
"peekFront",
"(",
")",
";",
"if",
"(",
"currentCmd",
"&&",
"currentCmd",
".",
"stack",
"&&",
"err",
")",
"{",
"err",
".",
"stack",
"+=",
"'\\n From event:\\n'",
"+",
"currentCmd",
".",
"stack",
".",
"substring",
"(",
"currentCmd",
".",
"stack",
".",
"indexOf",
"(",
"'\\n'",
")",
"+",
"1",
")",
";",
"}",
"authFailHandler",
"(",
"err",
")",
";",
"break",
";",
"default",
":",
"_fatalError",
"(",
"err",
",",
"false",
")",
";",
"}",
"}"
] |
Handle socket error.
@param authFailHandler authentication handler
@param err socket error
@private
|
[
"Handle",
"socket",
"error",
"."
] |
a596445fcfb5c39a6861b65cff3b6cd83a84a359
|
https://github.com/MariaDB/mariadb-connector-nodejs/blob/a596445fcfb5c39a6861b65cff3b6cd83a84a359/lib/connection.js#L1128-L1168
|
|
14,003
|
MariaDB/mariadb-connector-nodejs
|
lib/filtered-pool-cluster.js
|
FilteredPoolCluster
|
function FilteredPoolCluster(poolCluster, patternArg, selectorArg) {
const cluster = poolCluster;
const pattern = patternArg;
const selector = selectorArg;
/**
* Get a connection according to previously indicated pattern and selector.
*
* @return {Promise}
*/
this.getConnection = () => {
return cluster.getConnection(pattern, selector);
};
/**
* Execute a query on one connection from available pools matching pattern
* in cluster.
*
* @param sql sql command
* @param value parameter value of sql command (not mandatory)
* @return {Promise}
*/
this.query = function(sql, value) {
return cluster
.getConnection(pattern, selector)
.then(conn => {
return conn
.query(sql, value)
.then(res => {
conn.end();
return res;
})
.catch(err => {
conn.end();
return Promise.reject(err);
});
})
.catch(err => {
return Promise.reject(err);
});
};
/**
* Execute a batch on one connection from available pools matching pattern
* in cluster.
*
* @param sql sql command
* @param value parameter value of sql command
* @return {Promise}
*/
this.batch = function(sql, value) {
return cluster
.getConnection(pattern, selector)
.then(conn => {
return conn
.batch(sql, value)
.then(res => {
conn.end();
return res;
})
.catch(err => {
conn.end();
return Promise.reject(err);
});
})
.catch(err => {
return Promise.reject(err);
});
};
}
|
javascript
|
function FilteredPoolCluster(poolCluster, patternArg, selectorArg) {
const cluster = poolCluster;
const pattern = patternArg;
const selector = selectorArg;
/**
* Get a connection according to previously indicated pattern and selector.
*
* @return {Promise}
*/
this.getConnection = () => {
return cluster.getConnection(pattern, selector);
};
/**
* Execute a query on one connection from available pools matching pattern
* in cluster.
*
* @param sql sql command
* @param value parameter value of sql command (not mandatory)
* @return {Promise}
*/
this.query = function(sql, value) {
return cluster
.getConnection(pattern, selector)
.then(conn => {
return conn
.query(sql, value)
.then(res => {
conn.end();
return res;
})
.catch(err => {
conn.end();
return Promise.reject(err);
});
})
.catch(err => {
return Promise.reject(err);
});
};
/**
* Execute a batch on one connection from available pools matching pattern
* in cluster.
*
* @param sql sql command
* @param value parameter value of sql command
* @return {Promise}
*/
this.batch = function(sql, value) {
return cluster
.getConnection(pattern, selector)
.then(conn => {
return conn
.batch(sql, value)
.then(res => {
conn.end();
return res;
})
.catch(err => {
conn.end();
return Promise.reject(err);
});
})
.catch(err => {
return Promise.reject(err);
});
};
}
|
[
"function",
"FilteredPoolCluster",
"(",
"poolCluster",
",",
"patternArg",
",",
"selectorArg",
")",
"{",
"const",
"cluster",
"=",
"poolCluster",
";",
"const",
"pattern",
"=",
"patternArg",
";",
"const",
"selector",
"=",
"selectorArg",
";",
"/**\n * Get a connection according to previously indicated pattern and selector.\n *\n * @return {Promise}\n */",
"this",
".",
"getConnection",
"=",
"(",
")",
"=>",
"{",
"return",
"cluster",
".",
"getConnection",
"(",
"pattern",
",",
"selector",
")",
";",
"}",
";",
"/**\n * Execute a query on one connection from available pools matching pattern\n * in cluster.\n *\n * @param sql sql command\n * @param value parameter value of sql command (not mandatory)\n * @return {Promise}\n */",
"this",
".",
"query",
"=",
"function",
"(",
"sql",
",",
"value",
")",
"{",
"return",
"cluster",
".",
"getConnection",
"(",
"pattern",
",",
"selector",
")",
".",
"then",
"(",
"conn",
"=>",
"{",
"return",
"conn",
".",
"query",
"(",
"sql",
",",
"value",
")",
".",
"then",
"(",
"res",
"=>",
"{",
"conn",
".",
"end",
"(",
")",
";",
"return",
"res",
";",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"conn",
".",
"end",
"(",
")",
";",
"return",
"Promise",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"return",
"Promise",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
";",
"/**\n * Execute a batch on one connection from available pools matching pattern\n * in cluster.\n *\n * @param sql sql command\n * @param value parameter value of sql command\n * @return {Promise}\n */",
"this",
".",
"batch",
"=",
"function",
"(",
"sql",
",",
"value",
")",
"{",
"return",
"cluster",
".",
"getConnection",
"(",
"pattern",
",",
"selector",
")",
".",
"then",
"(",
"conn",
"=>",
"{",
"return",
"conn",
".",
"batch",
"(",
"sql",
",",
"value",
")",
".",
"then",
"(",
"res",
"=>",
"{",
"conn",
".",
"end",
"(",
")",
";",
"return",
"res",
";",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"conn",
".",
"end",
"(",
")",
";",
"return",
"Promise",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"return",
"Promise",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] |
Similar to pool cluster with pre-set pattern and selector.
Additional method query
@param poolCluster cluster
@param patternArg pre-set pattern
@param selectorArg pre-set selector
@constructor
|
[
"Similar",
"to",
"pool",
"cluster",
"with",
"pre",
"-",
"set",
"pattern",
"and",
"selector",
".",
"Additional",
"method",
"query"
] |
a596445fcfb5c39a6861b65cff3b6cd83a84a359
|
https://github.com/MariaDB/mariadb-connector-nodejs/blob/a596445fcfb5c39a6861b65cff3b6cd83a84a359/lib/filtered-pool-cluster.js#L10-L79
|
14,004
|
MariaDB/mariadb-connector-nodejs
|
lib/pool-promise.js
|
function(pool) {
const conn = new Connection(options.connOptions);
return conn
.connect()
.then(() => {
if (pool.closed) {
conn
.end()
.then(() => {})
.catch(() => {});
return Promise.reject(
Errors.createError(
'Cannot create new connection to pool, pool closed',
true,
null,
'08S01',
Errors.ER_ADD_CONNECTION_CLOSED_POOL,
null
)
);
}
conn.releaseWithoutError = () => {
conn.release().catch(() => {});
};
conn.forceEnd = conn.end;
conn.release = () => {
if (pool.closed) {
pool._discardConnection(conn);
return Promise.resolve();
}
if (options.noControlAfterUse) {
pool._releaseConnection(conn);
return Promise.resolve();
}
//if server permit it, reset the connection, or rollback only if not
let revertFunction = conn.rollback;
if (
options.resetAfterUse &&
((conn.info.isMariaDB() && conn.info.hasMinVersion(10, 2, 4)) ||
(!conn.info.isMariaDB() && conn.info.hasMinVersion(5, 7, 3)))
) {
revertFunction = conn.reset;
}
return revertFunction()
.then(() => {
pool._releaseConnection(conn);
return Promise.resolve();
})
.catch(err => {
//uncertain connection state.
// discard it
pool._discardConnection(conn);
return Promise.resolve();
});
};
conn.end = conn.release;
return Promise.resolve(conn);
})
.catch(err => {
return Promise.reject(err);
});
}
|
javascript
|
function(pool) {
const conn = new Connection(options.connOptions);
return conn
.connect()
.then(() => {
if (pool.closed) {
conn
.end()
.then(() => {})
.catch(() => {});
return Promise.reject(
Errors.createError(
'Cannot create new connection to pool, pool closed',
true,
null,
'08S01',
Errors.ER_ADD_CONNECTION_CLOSED_POOL,
null
)
);
}
conn.releaseWithoutError = () => {
conn.release().catch(() => {});
};
conn.forceEnd = conn.end;
conn.release = () => {
if (pool.closed) {
pool._discardConnection(conn);
return Promise.resolve();
}
if (options.noControlAfterUse) {
pool._releaseConnection(conn);
return Promise.resolve();
}
//if server permit it, reset the connection, or rollback only if not
let revertFunction = conn.rollback;
if (
options.resetAfterUse &&
((conn.info.isMariaDB() && conn.info.hasMinVersion(10, 2, 4)) ||
(!conn.info.isMariaDB() && conn.info.hasMinVersion(5, 7, 3)))
) {
revertFunction = conn.reset;
}
return revertFunction()
.then(() => {
pool._releaseConnection(conn);
return Promise.resolve();
})
.catch(err => {
//uncertain connection state.
// discard it
pool._discardConnection(conn);
return Promise.resolve();
});
};
conn.end = conn.release;
return Promise.resolve(conn);
})
.catch(err => {
return Promise.reject(err);
});
}
|
[
"function",
"(",
"pool",
")",
"{",
"const",
"conn",
"=",
"new",
"Connection",
"(",
"options",
".",
"connOptions",
")",
";",
"return",
"conn",
".",
"connect",
"(",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"pool",
".",
"closed",
")",
"{",
"conn",
".",
"end",
"(",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"}",
")",
".",
"catch",
"(",
"(",
")",
"=>",
"{",
"}",
")",
";",
"return",
"Promise",
".",
"reject",
"(",
"Errors",
".",
"createError",
"(",
"'Cannot create new connection to pool, pool closed'",
",",
"true",
",",
"null",
",",
"'08S01'",
",",
"Errors",
".",
"ER_ADD_CONNECTION_CLOSED_POOL",
",",
"null",
")",
")",
";",
"}",
"conn",
".",
"releaseWithoutError",
"=",
"(",
")",
"=>",
"{",
"conn",
".",
"release",
"(",
")",
".",
"catch",
"(",
"(",
")",
"=>",
"{",
"}",
")",
";",
"}",
";",
"conn",
".",
"forceEnd",
"=",
"conn",
".",
"end",
";",
"conn",
".",
"release",
"=",
"(",
")",
"=>",
"{",
"if",
"(",
"pool",
".",
"closed",
")",
"{",
"pool",
".",
"_discardConnection",
"(",
"conn",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
"if",
"(",
"options",
".",
"noControlAfterUse",
")",
"{",
"pool",
".",
"_releaseConnection",
"(",
"conn",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
"//if server permit it, reset the connection, or rollback only if not",
"let",
"revertFunction",
"=",
"conn",
".",
"rollback",
";",
"if",
"(",
"options",
".",
"resetAfterUse",
"&&",
"(",
"(",
"conn",
".",
"info",
".",
"isMariaDB",
"(",
")",
"&&",
"conn",
".",
"info",
".",
"hasMinVersion",
"(",
"10",
",",
"2",
",",
"4",
")",
")",
"||",
"(",
"!",
"conn",
".",
"info",
".",
"isMariaDB",
"(",
")",
"&&",
"conn",
".",
"info",
".",
"hasMinVersion",
"(",
"5",
",",
"7",
",",
"3",
")",
")",
")",
")",
"{",
"revertFunction",
"=",
"conn",
".",
"reset",
";",
"}",
"return",
"revertFunction",
"(",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"pool",
".",
"_releaseConnection",
"(",
"conn",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"//uncertain connection state.",
"// discard it",
"pool",
".",
"_discardConnection",
"(",
"conn",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
";",
"conn",
".",
"end",
"=",
"conn",
".",
"release",
";",
"return",
"Promise",
".",
"resolve",
"(",
"conn",
")",
";",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"return",
"Promise",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] |
Add connection to pool.
|
[
"Add",
"connection",
"to",
"pool",
"."
] |
a596445fcfb5c39a6861b65cff3b6cd83a84a359
|
https://github.com/MariaDB/mariadb-connector-nodejs/blob/a596445fcfb5c39a6861b65cff3b6cd83a84a359/lib/pool-promise.js#L27-L92
|
|
14,005
|
revolunet/angular-carousel
|
lib/angular-mobile.js
|
checkAllowableRegions
|
function checkAllowableRegions(touchCoordinates, x, y) {
for (var i = 0; i < touchCoordinates.length; i += 2) {
if (hit(touchCoordinates[i], touchCoordinates[i+1], x, y)) {
touchCoordinates.splice(i, i + 2);
return true; // allowable region
}
}
return false; // No allowable region; bust it.
}
|
javascript
|
function checkAllowableRegions(touchCoordinates, x, y) {
for (var i = 0; i < touchCoordinates.length; i += 2) {
if (hit(touchCoordinates[i], touchCoordinates[i+1], x, y)) {
touchCoordinates.splice(i, i + 2);
return true; // allowable region
}
}
return false; // No allowable region; bust it.
}
|
[
"function",
"checkAllowableRegions",
"(",
"touchCoordinates",
",",
"x",
",",
"y",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"touchCoordinates",
".",
"length",
";",
"i",
"+=",
"2",
")",
"{",
"if",
"(",
"hit",
"(",
"touchCoordinates",
"[",
"i",
"]",
",",
"touchCoordinates",
"[",
"i",
"+",
"1",
"]",
",",
"x",
",",
"y",
")",
")",
"{",
"touchCoordinates",
".",
"splice",
"(",
"i",
",",
"i",
"+",
"2",
")",
";",
"return",
"true",
";",
"// allowable region",
"}",
"}",
"return",
"false",
";",
"// No allowable region; bust it.",
"}"
] |
Checks a list of allowable regions against a click location. Returns true if the click should be allowed. Splices out the allowable region from the list after it has been used.
|
[
"Checks",
"a",
"list",
"of",
"allowable",
"regions",
"against",
"a",
"click",
"location",
".",
"Returns",
"true",
"if",
"the",
"click",
"should",
"be",
"allowed",
".",
"Splices",
"out",
"the",
"allowable",
"region",
"from",
"the",
"list",
"after",
"it",
"has",
"been",
"used",
"."
] |
adfecc8f5d4f8832dbfb21e311f195c044f8f6eb
|
https://github.com/revolunet/angular-carousel/blob/adfecc8f5d4f8832dbfb21e311f195c044f8f6eb/lib/angular-mobile.js#L203-L211
|
14,006
|
revolunet/angular-carousel
|
lib/angular-mobile.js
|
preventGhostClick
|
function preventGhostClick(x, y) {
if (!touchCoordinates) {
$rootElement[0].addEventListener('click', onClick, true);
$rootElement[0].addEventListener('touchstart', onTouchStart, true);
touchCoordinates = [];
}
lastPreventedTime = Date.now();
checkAllowableRegions(touchCoordinates, x, y);
}
|
javascript
|
function preventGhostClick(x, y) {
if (!touchCoordinates) {
$rootElement[0].addEventListener('click', onClick, true);
$rootElement[0].addEventListener('touchstart', onTouchStart, true);
touchCoordinates = [];
}
lastPreventedTime = Date.now();
checkAllowableRegions(touchCoordinates, x, y);
}
|
[
"function",
"preventGhostClick",
"(",
"x",
",",
"y",
")",
"{",
"if",
"(",
"!",
"touchCoordinates",
")",
"{",
"$rootElement",
"[",
"0",
"]",
".",
"addEventListener",
"(",
"'click'",
",",
"onClick",
",",
"true",
")",
";",
"$rootElement",
"[",
"0",
"]",
".",
"addEventListener",
"(",
"'touchstart'",
",",
"onTouchStart",
",",
"true",
")",
";",
"touchCoordinates",
"=",
"[",
"]",
";",
"}",
"lastPreventedTime",
"=",
"Date",
".",
"now",
"(",
")",
";",
"checkAllowableRegions",
"(",
"touchCoordinates",
",",
"x",
",",
"y",
")",
";",
"}"
] |
On the first call, attaches some event handlers. Then whenever it gets called, it creates a zone around the touchstart where clicks will get busted.
|
[
"On",
"the",
"first",
"call",
"attaches",
"some",
"event",
"handlers",
".",
"Then",
"whenever",
"it",
"gets",
"called",
"it",
"creates",
"a",
"zone",
"around",
"the",
"touchstart",
"where",
"clicks",
"will",
"get",
"busted",
"."
] |
adfecc8f5d4f8832dbfb21e311f195c044f8f6eb
|
https://github.com/revolunet/angular-carousel/blob/adfecc8f5d4f8832dbfb21e311f195c044f8f6eb/lib/angular-mobile.js#L264-L274
|
14,007
|
revolunet/angular-carousel
|
dist/angular-carousel.js
|
Tweenable
|
function Tweenable (opt_initialState, opt_config) {
this._currentState = opt_initialState || {};
this._configured = false;
this._scheduleFunction = DEFAULT_SCHEDULE_FUNCTION;
// To prevent unnecessary calls to setConfig do not set default configuration here.
// Only set default configuration immediately before tweening if none has been set.
if (typeof opt_config !== 'undefined') {
this.setConfig(opt_config);
}
}
|
javascript
|
function Tweenable (opt_initialState, opt_config) {
this._currentState = opt_initialState || {};
this._configured = false;
this._scheduleFunction = DEFAULT_SCHEDULE_FUNCTION;
// To prevent unnecessary calls to setConfig do not set default configuration here.
// Only set default configuration immediately before tweening if none has been set.
if (typeof opt_config !== 'undefined') {
this.setConfig(opt_config);
}
}
|
[
"function",
"Tweenable",
"(",
"opt_initialState",
",",
"opt_config",
")",
"{",
"this",
".",
"_currentState",
"=",
"opt_initialState",
"||",
"{",
"}",
";",
"this",
".",
"_configured",
"=",
"false",
";",
"this",
".",
"_scheduleFunction",
"=",
"DEFAULT_SCHEDULE_FUNCTION",
";",
"// To prevent unnecessary calls to setConfig do not set default configuration here.",
"// Only set default configuration immediately before tweening if none has been set.",
"if",
"(",
"typeof",
"opt_config",
"!==",
"'undefined'",
")",
"{",
"this",
".",
"setConfig",
"(",
"opt_config",
")",
";",
"}",
"}"
] |
Tweenable constructor.
@param {Object=} opt_initialState The values that the initial tween should start at if a "from" object is not provided to Tweenable#tween.
@param {Object=} opt_config See Tweenable.prototype.setConfig()
@constructor
|
[
"Tweenable",
"constructor",
"."
] |
adfecc8f5d4f8832dbfb21e311f195c044f8f6eb
|
https://github.com/revolunet/angular-carousel/blob/adfecc8f5d4f8832dbfb21e311f195c044f8f6eb/dist/angular-carousel.js#L934-L944
|
14,008
|
facundoolano/aso
|
lib/calc.js
|
aggregate
|
function aggregate (weights, values) {
const max = 10 * R.sum(weights);
const min = 1 * R.sum(weights);
const sum = R.sum(R.zipWith(R.multiply, weights, values));
return score(min, max, sum);
}
|
javascript
|
function aggregate (weights, values) {
const max = 10 * R.sum(weights);
const min = 1 * R.sum(weights);
const sum = R.sum(R.zipWith(R.multiply, weights, values));
return score(min, max, sum);
}
|
[
"function",
"aggregate",
"(",
"weights",
",",
"values",
")",
"{",
"const",
"max",
"=",
"10",
"*",
"R",
".",
"sum",
"(",
"weights",
")",
";",
"const",
"min",
"=",
"1",
"*",
"R",
".",
"sum",
"(",
"weights",
")",
";",
"const",
"sum",
"=",
"R",
".",
"sum",
"(",
"R",
".",
"zipWith",
"(",
"R",
".",
"multiply",
",",
"weights",
",",
"values",
")",
")",
";",
"return",
"score",
"(",
"min",
",",
"max",
",",
"sum",
")",
";",
"}"
] |
weighted aggregate score
|
[
"weighted",
"aggregate",
"score"
] |
cdd7466c3855a0c789c65c847675e0f902bab92e
|
https://github.com/facundoolano/aso/blob/cdd7466c3855a0c789c65c847675e0f902bab92e/lib/calc.js#L34-L39
|
14,009
|
ember-cli/eslint-plugin-ember
|
lib/utils/utils.js
|
findNodes
|
function findNodes(body, nodeName) {
let nodesArray = [];
if (body) {
nodesArray = body.filter(node => node.type === nodeName);
}
return nodesArray;
}
|
javascript
|
function findNodes(body, nodeName) {
let nodesArray = [];
if (body) {
nodesArray = body.filter(node => node.type === nodeName);
}
return nodesArray;
}
|
[
"function",
"findNodes",
"(",
"body",
",",
"nodeName",
")",
"{",
"let",
"nodesArray",
"=",
"[",
"]",
";",
"if",
"(",
"body",
")",
"{",
"nodesArray",
"=",
"body",
".",
"filter",
"(",
"node",
"=>",
"node",
".",
"type",
"===",
"nodeName",
")",
";",
"}",
"return",
"nodesArray",
";",
"}"
] |
Find nodes of given name
@param {Node[]} body Array of nodes
@param {String} nodeName
@return {Node[]}
|
[
"Find",
"nodes",
"of",
"given",
"name"
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/utils/utils.js#L44-L52
|
14,010
|
ember-cli/eslint-plugin-ember
|
lib/utils/utils.js
|
isGlobalCallExpression
|
function isGlobalCallExpression(node, destructuredName, aliases) {
const isDestructured = node && node.callee && node.callee.name === destructuredName;
const isGlobalCall = node.callee && aliases.indexOf(node.callee.name) > -1;
return !isDestructured && isGlobalCall;
}
|
javascript
|
function isGlobalCallExpression(node, destructuredName, aliases) {
const isDestructured = node && node.callee && node.callee.name === destructuredName;
const isGlobalCall = node.callee && aliases.indexOf(node.callee.name) > -1;
return !isDestructured && isGlobalCall;
}
|
[
"function",
"isGlobalCallExpression",
"(",
"node",
",",
"destructuredName",
",",
"aliases",
")",
"{",
"const",
"isDestructured",
"=",
"node",
"&&",
"node",
".",
"callee",
"&&",
"node",
".",
"callee",
".",
"name",
"===",
"destructuredName",
";",
"const",
"isGlobalCall",
"=",
"node",
".",
"callee",
"&&",
"aliases",
".",
"indexOf",
"(",
"node",
".",
"callee",
".",
"name",
")",
">",
"-",
"1",
";",
"return",
"!",
"isDestructured",
"&&",
"isGlobalCall",
";",
"}"
] |
Check if given call is a global call
This function checks whether given CallExpression node contains global
function call (name is provided in the aliases array). It also gives option to check against
already destructrued name and checking aliases.
@param {CallExpression} node The node to check.
@param {String} destructuredName The desctructured name.
@param {String[]} aliases array of aliases of the global function.
@return {Boolean} Whether function is a global call
|
[
"Check",
"if",
"given",
"call",
"is",
"a",
"global",
"call"
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/utils/utils.js#L265-L270
|
14,011
|
ember-cli/eslint-plugin-ember
|
lib/utils/utils.js
|
getSize
|
function getSize(node) {
return (node.loc.end.line - node.loc.start.line) + 1;
}
|
javascript
|
function getSize(node) {
return (node.loc.end.line - node.loc.start.line) + 1;
}
|
[
"function",
"getSize",
"(",
"node",
")",
"{",
"return",
"(",
"node",
".",
"loc",
".",
"end",
".",
"line",
"-",
"node",
".",
"loc",
".",
"start",
".",
"line",
")",
"+",
"1",
";",
"}"
] |
Get size of expression in lines
@param {Object} node The node to check.
@return {Integer} Number of lines
|
[
"Get",
"size",
"of",
"expression",
"in",
"lines"
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/utils/utils.js#L286-L288
|
14,012
|
ember-cli/eslint-plugin-ember
|
lib/utils/utils.js
|
parseCallee
|
function parseCallee(node) {
const parsedCallee = [];
let callee;
if (isCallExpression(node) || isNewExpression(node)) {
callee = node.callee;
while (isMemberExpression(callee)) {
if (isIdentifier(callee.property)) {
parsedCallee.push(callee.property.name);
}
callee = callee.object;
}
if (isIdentifier(callee)) {
parsedCallee.push(callee.name);
}
}
return parsedCallee.reverse();
}
|
javascript
|
function parseCallee(node) {
const parsedCallee = [];
let callee;
if (isCallExpression(node) || isNewExpression(node)) {
callee = node.callee;
while (isMemberExpression(callee)) {
if (isIdentifier(callee.property)) {
parsedCallee.push(callee.property.name);
}
callee = callee.object;
}
if (isIdentifier(callee)) {
parsedCallee.push(callee.name);
}
}
return parsedCallee.reverse();
}
|
[
"function",
"parseCallee",
"(",
"node",
")",
"{",
"const",
"parsedCallee",
"=",
"[",
"]",
";",
"let",
"callee",
";",
"if",
"(",
"isCallExpression",
"(",
"node",
")",
"||",
"isNewExpression",
"(",
"node",
")",
")",
"{",
"callee",
"=",
"node",
".",
"callee",
";",
"while",
"(",
"isMemberExpression",
"(",
"callee",
")",
")",
"{",
"if",
"(",
"isIdentifier",
"(",
"callee",
".",
"property",
")",
")",
"{",
"parsedCallee",
".",
"push",
"(",
"callee",
".",
"property",
".",
"name",
")",
";",
"}",
"callee",
"=",
"callee",
".",
"object",
";",
"}",
"if",
"(",
"isIdentifier",
"(",
"callee",
")",
")",
"{",
"parsedCallee",
".",
"push",
"(",
"callee",
".",
"name",
")",
";",
"}",
"}",
"return",
"parsedCallee",
".",
"reverse",
"(",
")",
";",
"}"
] |
Parse CallExpression or NewExpression to get array of properties and object name
@param {Object} node The node to parse
@return {String[]} eg. ['Ember', 'computed', 'alias']
|
[
"Parse",
"CallExpression",
"or",
"NewExpression",
"to",
"get",
"array",
"of",
"properties",
"and",
"object",
"name"
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/utils/utils.js#L296-L316
|
14,013
|
ember-cli/eslint-plugin-ember
|
lib/utils/utils.js
|
parseArgs
|
function parseArgs(node) {
let parsedArgs = [];
if (isCallExpression(node)) {
parsedArgs = node.arguments
.filter(argument => isLiteral(argument) && argument.value)
.map(argument => argument.value);
}
return parsedArgs;
}
|
javascript
|
function parseArgs(node) {
let parsedArgs = [];
if (isCallExpression(node)) {
parsedArgs = node.arguments
.filter(argument => isLiteral(argument) && argument.value)
.map(argument => argument.value);
}
return parsedArgs;
}
|
[
"function",
"parseArgs",
"(",
"node",
")",
"{",
"let",
"parsedArgs",
"=",
"[",
"]",
";",
"if",
"(",
"isCallExpression",
"(",
"node",
")",
")",
"{",
"parsedArgs",
"=",
"node",
".",
"arguments",
".",
"filter",
"(",
"argument",
"=>",
"isLiteral",
"(",
"argument",
")",
"&&",
"argument",
".",
"value",
")",
".",
"map",
"(",
"argument",
"=>",
"argument",
".",
"value",
")",
";",
"}",
"return",
"parsedArgs",
";",
"}"
] |
Parse CallExpression to get array of arguments
@param {Object} node Node to parse
@return {String[]} Literal function's arguments
|
[
"Parse",
"CallExpression",
"to",
"get",
"array",
"of",
"arguments"
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/utils/utils.js#L324-L334
|
14,014
|
ember-cli/eslint-plugin-ember
|
lib/utils/utils.js
|
findUnorderedProperty
|
function findUnorderedProperty(arr) {
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i].order > arr[i + 1].order) {
return arr[i];
}
}
return null;
}
|
javascript
|
function findUnorderedProperty(arr) {
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i].order > arr[i + 1].order) {
return arr[i];
}
}
return null;
}
|
[
"function",
"findUnorderedProperty",
"(",
"arr",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
"-",
"1",
";",
"i",
"++",
")",
"{",
"if",
"(",
"arr",
"[",
"i",
"]",
".",
"order",
">",
"arr",
"[",
"i",
"+",
"1",
"]",
".",
"order",
")",
"{",
"return",
"arr",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
Find property that is in wrong order
@param {Object[]} arr Properties with their order value
@return {Object} Unordered property or null
|
[
"Find",
"property",
"that",
"is",
"in",
"wrong",
"order"
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/utils/utils.js#L342-L350
|
14,015
|
ember-cli/eslint-plugin-ember
|
lib/utils/utils.js
|
getPropertyValue
|
function getPropertyValue(node, path) {
const parts = typeof path === 'string' ? path.split('.') : path;
if (parts.length === 1) {
return node[path];
}
const property = node[parts[0]];
if (property && parts.length > 1) {
parts.shift();
return getPropertyValue(property, parts);
}
return property;
}
|
javascript
|
function getPropertyValue(node, path) {
const parts = typeof path === 'string' ? path.split('.') : path;
if (parts.length === 1) {
return node[path];
}
const property = node[parts[0]];
if (property && parts.length > 1) {
parts.shift();
return getPropertyValue(property, parts);
}
return property;
}
|
[
"function",
"getPropertyValue",
"(",
"node",
",",
"path",
")",
"{",
"const",
"parts",
"=",
"typeof",
"path",
"===",
"'string'",
"?",
"path",
".",
"split",
"(",
"'.'",
")",
":",
"path",
";",
"if",
"(",
"parts",
".",
"length",
"===",
"1",
")",
"{",
"return",
"node",
"[",
"path",
"]",
";",
"}",
"const",
"property",
"=",
"node",
"[",
"parts",
"[",
"0",
"]",
"]",
";",
"if",
"(",
"property",
"&&",
"parts",
".",
"length",
">",
"1",
")",
"{",
"parts",
".",
"shift",
"(",
")",
";",
"return",
"getPropertyValue",
"(",
"property",
",",
"parts",
")",
";",
"}",
"return",
"property",
";",
"}"
] |
Gets a property's value either by property path.
@example
getPropertyValue('name');
getPropertyValue('parent.key.name');
@param {Object} node
@param {String} path
@returns
|
[
"Gets",
"a",
"property",
"s",
"value",
"either",
"by",
"property",
"path",
"."
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/utils/utils.js#L363-L378
|
14,016
|
ember-cli/eslint-plugin-ember
|
lib/utils/utils.js
|
collectObjectPatternBindings
|
function collectObjectPatternBindings(node, initialObjToBinding) {
if (!isObjectPattern(node.id)) return [];
const identifiers = Object.keys(initialObjToBinding);
const objBindingName = node.init.name;
const bindingIndex = identifiers.indexOf(objBindingName);
if (bindingIndex === -1) return [];
const binding = identifiers[bindingIndex];
return node.id.properties
.filter(props => initialObjToBinding[binding].indexOf(props.key.name) > -1)
.map(props => props.value.name);
}
|
javascript
|
function collectObjectPatternBindings(node, initialObjToBinding) {
if (!isObjectPattern(node.id)) return [];
const identifiers = Object.keys(initialObjToBinding);
const objBindingName = node.init.name;
const bindingIndex = identifiers.indexOf(objBindingName);
if (bindingIndex === -1) return [];
const binding = identifiers[bindingIndex];
return node.id.properties
.filter(props => initialObjToBinding[binding].indexOf(props.key.name) > -1)
.map(props => props.value.name);
}
|
[
"function",
"collectObjectPatternBindings",
"(",
"node",
",",
"initialObjToBinding",
")",
"{",
"if",
"(",
"!",
"isObjectPattern",
"(",
"node",
".",
"id",
")",
")",
"return",
"[",
"]",
";",
"const",
"identifiers",
"=",
"Object",
".",
"keys",
"(",
"initialObjToBinding",
")",
";",
"const",
"objBindingName",
"=",
"node",
".",
"init",
".",
"name",
";",
"const",
"bindingIndex",
"=",
"identifiers",
".",
"indexOf",
"(",
"objBindingName",
")",
";",
"if",
"(",
"bindingIndex",
"===",
"-",
"1",
")",
"return",
"[",
"]",
";",
"const",
"binding",
"=",
"identifiers",
"[",
"bindingIndex",
"]",
";",
"return",
"node",
".",
"id",
".",
"properties",
".",
"filter",
"(",
"props",
"=>",
"initialObjToBinding",
"[",
"binding",
"]",
".",
"indexOf",
"(",
"props",
".",
"key",
".",
"name",
")",
">",
"-",
"1",
")",
".",
"map",
"(",
"props",
"=>",
"props",
".",
"value",
".",
"name",
")",
";",
"}"
] |
Find deconstructed bindings based on the initialObjToBinding hash.
Extracts the names of destructured properties, even if they are aliased.
`initialObjToBinding` should should have variable names as keys and bindings array as values.
Given `const { $: foo } = Ember` it will return `['foo']`.
@param {VariableDeclarator} node node to parse
@param {Object} initialObjToBinding relevant bindings
@return {String[]} list of object pattern bindings
|
[
"Find",
"deconstructed",
"bindings",
"based",
"on",
"the",
"initialObjToBinding",
"hash",
"."
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/utils/utils.js#L391-L404
|
14,017
|
ember-cli/eslint-plugin-ember
|
lib/utils/utils.js
|
isEmptyMethod
|
function isEmptyMethod(node) {
return node.value.body
&& node.value.body.body
&& node.value.body.body.length <= 0;
}
|
javascript
|
function isEmptyMethod(node) {
return node.value.body
&& node.value.body.body
&& node.value.body.body.length <= 0;
}
|
[
"function",
"isEmptyMethod",
"(",
"node",
")",
"{",
"return",
"node",
".",
"value",
".",
"body",
"&&",
"node",
".",
"value",
".",
"body",
".",
"body",
"&&",
"node",
".",
"value",
".",
"body",
".",
"body",
".",
"length",
"<=",
"0",
";",
"}"
] |
Check whether or not a node is a empty method.
@param {Object} node The node to check.
@returns {boolean} Whether or not the node is an empty method.
|
[
"Check",
"whether",
"or",
"not",
"a",
"node",
"is",
"a",
"empty",
"method",
"."
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/utils/utils.js#L412-L416
|
14,018
|
ember-cli/eslint-plugin-ember
|
lib/utils/utils.js
|
getParent
|
function getParent(node, predicate) {
let currentNode = node;
while (currentNode) {
if (predicate(currentNode)) {
return currentNode;
}
currentNode = currentNode.parent;
}
return null;
}
|
javascript
|
function getParent(node, predicate) {
let currentNode = node;
while (currentNode) {
if (predicate(currentNode)) {
return currentNode;
}
currentNode = currentNode.parent;
}
return null;
}
|
[
"function",
"getParent",
"(",
"node",
",",
"predicate",
")",
"{",
"let",
"currentNode",
"=",
"node",
";",
"while",
"(",
"currentNode",
")",
"{",
"if",
"(",
"predicate",
"(",
"currentNode",
")",
")",
"{",
"return",
"currentNode",
";",
"}",
"currentNode",
"=",
"currentNode",
".",
"parent",
";",
"}",
"return",
"null",
";",
"}"
] |
Travels up the ancestors of a given node, if the predicate function returns
truthy for a given node or ancestor, return that node, otherwise return null
@name getParent
@param {Object} node The child node to start at
@param {Function} predicate Function that should return a boolean for a given value
@returns {Object|null} The first node that matches predicate, otherwise null
|
[
"Travels",
"up",
"the",
"ancestors",
"of",
"a",
"given",
"node",
"if",
"the",
"predicate",
"function",
"returns",
"truthy",
"for",
"a",
"given",
"node",
"or",
"ancestor",
"return",
"that",
"node",
"otherwise",
"return",
"null"
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/utils/utils.js#L427-L438
|
14,019
|
ember-cli/eslint-plugin-ember
|
lib/utils/ember.js
|
getEmberImportAliasName
|
function getEmberImportAliasName(importDeclaration) {
if (!importDeclaration.source) return null;
if (importDeclaration.source.value !== 'ember') return null;
return importDeclaration.specifiers[0].local.name;
}
|
javascript
|
function getEmberImportAliasName(importDeclaration) {
if (!importDeclaration.source) return null;
if (importDeclaration.source.value !== 'ember') return null;
return importDeclaration.specifiers[0].local.name;
}
|
[
"function",
"getEmberImportAliasName",
"(",
"importDeclaration",
")",
"{",
"if",
"(",
"!",
"importDeclaration",
".",
"source",
")",
"return",
"null",
";",
"if",
"(",
"importDeclaration",
".",
"source",
".",
"value",
"!==",
"'ember'",
")",
"return",
"null",
";",
"return",
"importDeclaration",
".",
"specifiers",
"[",
"0",
"]",
".",
"local",
".",
"name",
";",
"}"
] |
Get alias name of default ember import.
@param {ImportDeclaration} importDeclaration node to parse
@return {String} import name
|
[
"Get",
"alias",
"name",
"of",
"default",
"ember",
"import",
"."
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/utils/ember.js#L317-L321
|
14,020
|
ember-cli/eslint-plugin-ember
|
lib/utils/ember.js
|
hasDuplicateDependentKeys
|
function hasDuplicateDependentKeys(callExp) {
if (!isComputedProp(callExp)) return false;
const dependentKeys = parseDependentKeys(callExp);
const uniqueKeys = dependentKeys
.filter((val, index, self) => self.indexOf(val) === index);
return uniqueKeys.length !== dependentKeys.length;
}
|
javascript
|
function hasDuplicateDependentKeys(callExp) {
if (!isComputedProp(callExp)) return false;
const dependentKeys = parseDependentKeys(callExp);
const uniqueKeys = dependentKeys
.filter((val, index, self) => self.indexOf(val) === index);
return uniqueKeys.length !== dependentKeys.length;
}
|
[
"function",
"hasDuplicateDependentKeys",
"(",
"callExp",
")",
"{",
"if",
"(",
"!",
"isComputedProp",
"(",
"callExp",
")",
")",
"return",
"false",
";",
"const",
"dependentKeys",
"=",
"parseDependentKeys",
"(",
"callExp",
")",
";",
"const",
"uniqueKeys",
"=",
"dependentKeys",
".",
"filter",
"(",
"(",
"val",
",",
"index",
",",
"self",
")",
"=>",
"self",
".",
"indexOf",
"(",
"val",
")",
"===",
"index",
")",
";",
"return",
"uniqueKeys",
".",
"length",
"!==",
"dependentKeys",
".",
"length",
";",
"}"
] |
Checks whether a computed property has duplicate dependent keys.
@param {CallExpression} callExp Given call expression
@return {Boolean} Flag whether dependent keys present.
|
[
"Checks",
"whether",
"a",
"computed",
"property",
"has",
"duplicate",
"dependent",
"keys",
"."
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/utils/ember.js#L368-L376
|
14,021
|
ember-cli/eslint-plugin-ember
|
lib/utils/ember.js
|
parseDependentKeys
|
function parseDependentKeys(callExp) {
// Check whether we have a MemberExpression, eg. computed(...).volatile()
const isMemberExpCallExp = !callExp.arguments.length &&
utils.isMemberExpression(callExp.callee) &&
utils.isCallExpression(callExp.callee.object);
const args = isMemberExpCallExp ? callExp.callee.object.arguments : callExp.arguments;
const dependentKeys = args
.filter(arg => utils.isLiteral(arg))
.map(literal => literal.value);
return unwrapBraceExpressions(dependentKeys);
}
|
javascript
|
function parseDependentKeys(callExp) {
// Check whether we have a MemberExpression, eg. computed(...).volatile()
const isMemberExpCallExp = !callExp.arguments.length &&
utils.isMemberExpression(callExp.callee) &&
utils.isCallExpression(callExp.callee.object);
const args = isMemberExpCallExp ? callExp.callee.object.arguments : callExp.arguments;
const dependentKeys = args
.filter(arg => utils.isLiteral(arg))
.map(literal => literal.value);
return unwrapBraceExpressions(dependentKeys);
}
|
[
"function",
"parseDependentKeys",
"(",
"callExp",
")",
"{",
"// Check whether we have a MemberExpression, eg. computed(...).volatile()",
"const",
"isMemberExpCallExp",
"=",
"!",
"callExp",
".",
"arguments",
".",
"length",
"&&",
"utils",
".",
"isMemberExpression",
"(",
"callExp",
".",
"callee",
")",
"&&",
"utils",
".",
"isCallExpression",
"(",
"callExp",
".",
"callee",
".",
"object",
")",
";",
"const",
"args",
"=",
"isMemberExpCallExp",
"?",
"callExp",
".",
"callee",
".",
"object",
".",
"arguments",
":",
"callExp",
".",
"arguments",
";",
"const",
"dependentKeys",
"=",
"args",
".",
"filter",
"(",
"arg",
"=>",
"utils",
".",
"isLiteral",
"(",
"arg",
")",
")",
".",
"map",
"(",
"literal",
"=>",
"literal",
".",
"value",
")",
";",
"return",
"unwrapBraceExpressions",
"(",
"dependentKeys",
")",
";",
"}"
] |
Parses dependent keys from call expression and returns them in an array.
It also unwraps the expressions, so that `model.{foo,bar}` becomes `model.foo, model.bar`.
@param {CallExpression} callExp CallExpression to examine
@return {String[]} Array of unwrapped dependent keys
|
[
"Parses",
"dependent",
"keys",
"from",
"call",
"expression",
"and",
"returns",
"them",
"in",
"an",
"array",
"."
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/utils/ember.js#L386-L399
|
14,022
|
ember-cli/eslint-plugin-ember
|
lib/utils/ember.js
|
unwrapBraceExpressions
|
function unwrapBraceExpressions(dependentKeys) {
const braceExpressionRegexp = /{.+}/g;
const unwrappedExpressions = dependentKeys.map((key) => {
if (typeof key !== 'string' || !braceExpressionRegexp.test(key)) return key;
const braceExpansionPart = key.match(braceExpressionRegexp)[0];
const prefix = key.replace(braceExpansionPart, '');
const properties = braceExpansionPart
.replace('{', '')
.replace('}', '')
.split(',');
return properties.map(property => `${prefix}${property}`);
});
return unwrappedExpressions
.reduce((acc, cur) => acc.concat(cur), []);
}
|
javascript
|
function unwrapBraceExpressions(dependentKeys) {
const braceExpressionRegexp = /{.+}/g;
const unwrappedExpressions = dependentKeys.map((key) => {
if (typeof key !== 'string' || !braceExpressionRegexp.test(key)) return key;
const braceExpansionPart = key.match(braceExpressionRegexp)[0];
const prefix = key.replace(braceExpansionPart, '');
const properties = braceExpansionPart
.replace('{', '')
.replace('}', '')
.split(',');
return properties.map(property => `${prefix}${property}`);
});
return unwrappedExpressions
.reduce((acc, cur) => acc.concat(cur), []);
}
|
[
"function",
"unwrapBraceExpressions",
"(",
"dependentKeys",
")",
"{",
"const",
"braceExpressionRegexp",
"=",
"/",
"{.+}",
"/",
"g",
";",
"const",
"unwrappedExpressions",
"=",
"dependentKeys",
".",
"map",
"(",
"(",
"key",
")",
"=>",
"{",
"if",
"(",
"typeof",
"key",
"!==",
"'string'",
"||",
"!",
"braceExpressionRegexp",
".",
"test",
"(",
"key",
")",
")",
"return",
"key",
";",
"const",
"braceExpansionPart",
"=",
"key",
".",
"match",
"(",
"braceExpressionRegexp",
")",
"[",
"0",
"]",
";",
"const",
"prefix",
"=",
"key",
".",
"replace",
"(",
"braceExpansionPart",
",",
"''",
")",
";",
"const",
"properties",
"=",
"braceExpansionPart",
".",
"replace",
"(",
"'{'",
",",
"''",
")",
".",
"replace",
"(",
"'}'",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
";",
"return",
"properties",
".",
"map",
"(",
"property",
"=>",
"`",
"${",
"prefix",
"}",
"${",
"property",
"}",
"`",
")",
";",
"}",
")",
";",
"return",
"unwrappedExpressions",
".",
"reduce",
"(",
"(",
"acc",
",",
"cur",
")",
"=>",
"acc",
".",
"concat",
"(",
"cur",
")",
",",
"[",
"]",
")",
";",
"}"
] |
Unwraps brace expressions.
@param {String[]} dependentKeys array of strings containing unprocessed dependent keys.
@return {String[]} Array of unwrapped dependent keys
|
[
"Unwraps",
"brace",
"expressions",
"."
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/utils/ember.js#L407-L425
|
14,023
|
ember-cli/eslint-plugin-ember
|
lib/rules/require-super-in-init.js
|
findStmtNodes
|
function findStmtNodes(nodeBody) {
const nodes = [];
const fnExpressions = utils.findNodes(nodeBody, 'ExpressionStatement');
const returnStatement = utils.findNodes(nodeBody, 'ReturnStatement');
if (fnExpressions.length !== 0) {
fnExpressions.forEach((item) => {
nodes.push(item);
});
}
if (returnStatement.length !== 0) {
returnStatement.forEach((item) => {
nodes.push(item);
});
}
return nodes;
}
|
javascript
|
function findStmtNodes(nodeBody) {
const nodes = [];
const fnExpressions = utils.findNodes(nodeBody, 'ExpressionStatement');
const returnStatement = utils.findNodes(nodeBody, 'ReturnStatement');
if (fnExpressions.length !== 0) {
fnExpressions.forEach((item) => {
nodes.push(item);
});
}
if (returnStatement.length !== 0) {
returnStatement.forEach((item) => {
nodes.push(item);
});
}
return nodes;
}
|
[
"function",
"findStmtNodes",
"(",
"nodeBody",
")",
"{",
"const",
"nodes",
"=",
"[",
"]",
";",
"const",
"fnExpressions",
"=",
"utils",
".",
"findNodes",
"(",
"nodeBody",
",",
"'ExpressionStatement'",
")",
";",
"const",
"returnStatement",
"=",
"utils",
".",
"findNodes",
"(",
"nodeBody",
",",
"'ReturnStatement'",
")",
";",
"if",
"(",
"fnExpressions",
".",
"length",
"!==",
"0",
")",
"{",
"fnExpressions",
".",
"forEach",
"(",
"(",
"item",
")",
"=>",
"{",
"nodes",
".",
"push",
"(",
"item",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"returnStatement",
".",
"length",
"!==",
"0",
")",
"{",
"returnStatement",
".",
"forEach",
"(",
"(",
"item",
")",
"=>",
"{",
"nodes",
".",
"push",
"(",
"item",
")",
";",
"}",
")",
";",
"}",
"return",
"nodes",
";",
"}"
] |
Locates nodes with either an ExpressionStatement or ReturnStatement
given name.
@param {Node[]} nodeBody Array of nodes.
@returns {Node[]} Array of nodes with given names.
|
[
"Locates",
"nodes",
"with",
"either",
"an",
"ExpressionStatement",
"or",
"ReturnStatement",
"given",
"name",
"."
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/rules/require-super-in-init.js#L12-L30
|
14,024
|
ember-cli/eslint-plugin-ember
|
lib/rules/require-super-in-init.js
|
checkForSuper
|
function checkForSuper(nodes) {
if (nodes.length === 0) return false;
return nodes.some((n) => {
if (utils.isCallExpression(n.expression)) {
const fnCallee = n.expression.callee;
return utils.isMemberExpression(fnCallee) &&
utils.isThisExpression(fnCallee.object) &&
utils.isIdentifier(fnCallee.property) &&
fnCallee.property.name === '_super';
} else if (utils.isReturnStatement(n)) {
if (!n.argument || !utils.isCallExpression(n.argument)) return false;
const fnCallee = n.argument.callee;
return fnCallee.property.name === '_super';
}
return false;
});
}
|
javascript
|
function checkForSuper(nodes) {
if (nodes.length === 0) return false;
return nodes.some((n) => {
if (utils.isCallExpression(n.expression)) {
const fnCallee = n.expression.callee;
return utils.isMemberExpression(fnCallee) &&
utils.isThisExpression(fnCallee.object) &&
utils.isIdentifier(fnCallee.property) &&
fnCallee.property.name === '_super';
} else if (utils.isReturnStatement(n)) {
if (!n.argument || !utils.isCallExpression(n.argument)) return false;
const fnCallee = n.argument.callee;
return fnCallee.property.name === '_super';
}
return false;
});
}
|
[
"function",
"checkForSuper",
"(",
"nodes",
")",
"{",
"if",
"(",
"nodes",
".",
"length",
"===",
"0",
")",
"return",
"false",
";",
"return",
"nodes",
".",
"some",
"(",
"(",
"n",
")",
"=>",
"{",
"if",
"(",
"utils",
".",
"isCallExpression",
"(",
"n",
".",
"expression",
")",
")",
"{",
"const",
"fnCallee",
"=",
"n",
".",
"expression",
".",
"callee",
";",
"return",
"utils",
".",
"isMemberExpression",
"(",
"fnCallee",
")",
"&&",
"utils",
".",
"isThisExpression",
"(",
"fnCallee",
".",
"object",
")",
"&&",
"utils",
".",
"isIdentifier",
"(",
"fnCallee",
".",
"property",
")",
"&&",
"fnCallee",
".",
"property",
".",
"name",
"===",
"'_super'",
";",
"}",
"else",
"if",
"(",
"utils",
".",
"isReturnStatement",
"(",
"n",
")",
")",
"{",
"if",
"(",
"!",
"n",
".",
"argument",
"||",
"!",
"utils",
".",
"isCallExpression",
"(",
"n",
".",
"argument",
")",
")",
"return",
"false",
";",
"const",
"fnCallee",
"=",
"n",
".",
"argument",
".",
"callee",
";",
"return",
"fnCallee",
".",
"property",
".",
"name",
"===",
"'_super'",
";",
"}",
"return",
"false",
";",
"}",
")",
";",
"}"
] |
Checks whether a node has the '_super' property.
@param {Node[]} nodes An array of nodes.
@returns {Boolean}
|
[
"Checks",
"whether",
"a",
"node",
"has",
"the",
"_super",
"property",
"."
] |
cce30db8d4c8fd0f27fa26411bfdc57864015231
|
https://github.com/ember-cli/eslint-plugin-ember/blob/cce30db8d4c8fd0f27fa26411bfdc57864015231/lib/rules/require-super-in-init.js#L37-L56
|
14,025
|
wojtkowiak/meteor-desktop
|
plugins/watcher/watcher.js
|
saveNewVersion
|
function saveNewVersion(version, versionFile) {
fs.writeFileSync(versionFile, JSON.stringify({
version
}, null, 2), 'UTF-8');
}
|
javascript
|
function saveNewVersion(version, versionFile) {
fs.writeFileSync(versionFile, JSON.stringify({
version
}, null, 2), 'UTF-8');
}
|
[
"function",
"saveNewVersion",
"(",
"version",
",",
"versionFile",
")",
"{",
"fs",
".",
"writeFileSync",
"(",
"versionFile",
",",
"JSON",
".",
"stringify",
"(",
"{",
"version",
"}",
",",
"null",
",",
"2",
")",
",",
"'UTF-8'",
")",
";",
"}"
] |
Saves version hash to the version file.
@param {string} version
@param {string} versionFile
|
[
"Saves",
"version",
"hash",
"to",
"the",
"version",
"file",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/plugins/watcher/watcher.js#L78-L82
|
14,026
|
wojtkowiak/meteor-desktop
|
plugins/watcher/watcher.js
|
getSettings
|
function getSettings(desktopPath) {
let settings = {};
try {
settings = JSON.parse(
fs.readFileSync(path.join(desktopPath, 'settings.json'), 'UTF-8')
);
} catch (e) {
return {};
}
return settings;
}
|
javascript
|
function getSettings(desktopPath) {
let settings = {};
try {
settings = JSON.parse(
fs.readFileSync(path.join(desktopPath, 'settings.json'), 'UTF-8')
);
} catch (e) {
return {};
}
return settings;
}
|
[
"function",
"getSettings",
"(",
"desktopPath",
")",
"{",
"let",
"settings",
"=",
"{",
"}",
";",
"try",
"{",
"settings",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"desktopPath",
",",
"'settings.json'",
")",
",",
"'UTF-8'",
")",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"{",
"}",
";",
"}",
"return",
"settings",
";",
"}"
] |
Tries to read a settings.json file from desktop dir.
@param {string} desktopPath - Path to the desktop dir.
@returns {Object}
|
[
"Tries",
"to",
"read",
"a",
"settings",
".",
"json",
"file",
"from",
"desktop",
"dir",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/plugins/watcher/watcher.js#L90-L100
|
14,027
|
wojtkowiak/meteor-desktop
|
plugins/watcher/watcher.js
|
getFileList
|
function getFileList(dir, sort = true) {
return new Promise((resolve, reject) => {
readdir(dir, (error, files) => {
if (error) {
reject(error);
return;
}
let resultantFilesList;
if (sort) {
const stripLength = (dir.substr(0, 2) === './') ? dir.length - 1 : dir.length + 1;
let pathsUnified = files.map((pth => pth.substr(stripLength).replace(/[\\/]/gm, '-')));
const temporaryIndex = {};
files.forEach((file, i) => {
temporaryIndex[pathsUnified[i]] = file;
});
pathsUnified = pathsUnified.sort();
const filesSorted = [];
pathsUnified.forEach((key) => {
filesSorted.push(temporaryIndex[key]);
});
resultantFilesList = filesSorted;
} else {
resultantFilesList = files;
}
resolve(resultantFilesList);
});
});
}
|
javascript
|
function getFileList(dir, sort = true) {
return new Promise((resolve, reject) => {
readdir(dir, (error, files) => {
if (error) {
reject(error);
return;
}
let resultantFilesList;
if (sort) {
const stripLength = (dir.substr(0, 2) === './') ? dir.length - 1 : dir.length + 1;
let pathsUnified = files.map((pth => pth.substr(stripLength).replace(/[\\/]/gm, '-')));
const temporaryIndex = {};
files.forEach((file, i) => {
temporaryIndex[pathsUnified[i]] = file;
});
pathsUnified = pathsUnified.sort();
const filesSorted = [];
pathsUnified.forEach((key) => {
filesSorted.push(temporaryIndex[key]);
});
resultantFilesList = filesSorted;
} else {
resultantFilesList = files;
}
resolve(resultantFilesList);
});
});
}
|
[
"function",
"getFileList",
"(",
"dir",
",",
"sort",
"=",
"true",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"readdir",
"(",
"dir",
",",
"(",
"error",
",",
"files",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"reject",
"(",
"error",
")",
";",
"return",
";",
"}",
"let",
"resultantFilesList",
";",
"if",
"(",
"sort",
")",
"{",
"const",
"stripLength",
"=",
"(",
"dir",
".",
"substr",
"(",
"0",
",",
"2",
")",
"===",
"'./'",
")",
"?",
"dir",
".",
"length",
"-",
"1",
":",
"dir",
".",
"length",
"+",
"1",
";",
"let",
"pathsUnified",
"=",
"files",
".",
"map",
"(",
"(",
"pth",
"=>",
"pth",
".",
"substr",
"(",
"stripLength",
")",
".",
"replace",
"(",
"/",
"[\\\\/]",
"/",
"gm",
",",
"'-'",
")",
")",
")",
";",
"const",
"temporaryIndex",
"=",
"{",
"}",
";",
"files",
".",
"forEach",
"(",
"(",
"file",
",",
"i",
")",
"=>",
"{",
"temporaryIndex",
"[",
"pathsUnified",
"[",
"i",
"]",
"]",
"=",
"file",
";",
"}",
")",
";",
"pathsUnified",
"=",
"pathsUnified",
".",
"sort",
"(",
")",
";",
"const",
"filesSorted",
"=",
"[",
"]",
";",
"pathsUnified",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"{",
"filesSorted",
".",
"push",
"(",
"temporaryIndex",
"[",
"key",
"]",
")",
";",
"}",
")",
";",
"resultantFilesList",
"=",
"filesSorted",
";",
"}",
"else",
"{",
"resultantFilesList",
"=",
"files",
";",
"}",
"resolve",
"(",
"resultantFilesList",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Returns a file list from a directory.
@param {string} dir - dir path
@returns {Promise<Array>}
|
[
"Returns",
"a",
"file",
"list",
"from",
"a",
"directory",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/plugins/watcher/watcher.js#L107-L136
|
14,028
|
wojtkowiak/meteor-desktop
|
plugins/watcher/watcher.js
|
readAndHashFiles
|
function readAndHashFiles(files) {
const fileHashes = {};
const fileContents = {};
const promises = [];
function readSingleFile(file) {
return new Promise((resolve, reject) => {
fs.readFile(file, (err, data) => {
if (err) {
console.log(err);
reject(err);
return;
}
const hash = crypto.createHash('sha1');
hash.update(data);
const bufferHash = hash.digest();
fileHashes[file] = bufferHash.toString('hex');
if (file.endsWith('.js') && !file.endsWith('.test.js')) {
fileContents[file] = data.toString('utf8');
}
resolve();
});
});
}
files.forEach((file) => {
promises.push(readSingleFile(file));
});
return new Promise((resolve, reject) => {
Promise.all(promises)
.then(() => {
resolve({ files, fileContents, fileHashes });
})
.catch(reject);
});
}
|
javascript
|
function readAndHashFiles(files) {
const fileHashes = {};
const fileContents = {};
const promises = [];
function readSingleFile(file) {
return new Promise((resolve, reject) => {
fs.readFile(file, (err, data) => {
if (err) {
console.log(err);
reject(err);
return;
}
const hash = crypto.createHash('sha1');
hash.update(data);
const bufferHash = hash.digest();
fileHashes[file] = bufferHash.toString('hex');
if (file.endsWith('.js') && !file.endsWith('.test.js')) {
fileContents[file] = data.toString('utf8');
}
resolve();
});
});
}
files.forEach((file) => {
promises.push(readSingleFile(file));
});
return new Promise((resolve, reject) => {
Promise.all(promises)
.then(() => {
resolve({ files, fileContents, fileHashes });
})
.catch(reject);
});
}
|
[
"function",
"readAndHashFiles",
"(",
"files",
")",
"{",
"const",
"fileHashes",
"=",
"{",
"}",
";",
"const",
"fileContents",
"=",
"{",
"}",
";",
"const",
"promises",
"=",
"[",
"]",
";",
"function",
"readSingleFile",
"(",
"file",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"readFile",
"(",
"file",
",",
"(",
"err",
",",
"data",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"err",
")",
";",
"reject",
"(",
"err",
")",
";",
"return",
";",
"}",
"const",
"hash",
"=",
"crypto",
".",
"createHash",
"(",
"'sha1'",
")",
";",
"hash",
".",
"update",
"(",
"data",
")",
";",
"const",
"bufferHash",
"=",
"hash",
".",
"digest",
"(",
")",
";",
"fileHashes",
"[",
"file",
"]",
"=",
"bufferHash",
".",
"toString",
"(",
"'hex'",
")",
";",
"if",
"(",
"file",
".",
"endsWith",
"(",
"'.js'",
")",
"&&",
"!",
"file",
".",
"endsWith",
"(",
"'.test.js'",
")",
")",
"{",
"fileContents",
"[",
"file",
"]",
"=",
"data",
".",
"toString",
"(",
"'utf8'",
")",
";",
"}",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"files",
".",
"forEach",
"(",
"(",
"file",
")",
"=>",
"{",
"promises",
".",
"push",
"(",
"readSingleFile",
"(",
"file",
")",
")",
";",
"}",
")",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"Promise",
".",
"all",
"(",
"promises",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"resolve",
"(",
"{",
"files",
",",
"fileContents",
",",
"fileHashes",
"}",
")",
";",
"}",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
";",
"}"
] |
Reads files from disk and computes hashes for them.
@param {Array} files - array with file paths
@returns {Promise<any>}
|
[
"Reads",
"files",
"from",
"disk",
"and",
"computes",
"hashes",
"for",
"them",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/plugins/watcher/watcher.js#L143-L179
|
14,029
|
wojtkowiak/meteor-desktop
|
plugins/watcher/watcher.js
|
readFilesAndComputeDesktopHash
|
function readFilesAndComputeDesktopHash(dir) {
const desktopHash = crypto.createHash('sha1');
return new Promise((resolve, reject) => {
getFileList(dir)
.catch(reject)
.then(readAndHashFiles)
.catch(reject)
.then((result) => {
const hash = result.files.reduce(
(tmpHash, file) => {
tmpHash += result.fileHashes[file];
return tmpHash;
}, ''
);
desktopHash.update(hash);
result.hash = desktopHash.digest('hex');
resolve(result);
});
});
}
|
javascript
|
function readFilesAndComputeDesktopHash(dir) {
const desktopHash = crypto.createHash('sha1');
return new Promise((resolve, reject) => {
getFileList(dir)
.catch(reject)
.then(readAndHashFiles)
.catch(reject)
.then((result) => {
const hash = result.files.reduce(
(tmpHash, file) => {
tmpHash += result.fileHashes[file];
return tmpHash;
}, ''
);
desktopHash.update(hash);
result.hash = desktopHash.digest('hex');
resolve(result);
});
});
}
|
[
"function",
"readFilesAndComputeDesktopHash",
"(",
"dir",
")",
"{",
"const",
"desktopHash",
"=",
"crypto",
".",
"createHash",
"(",
"'sha1'",
")",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"getFileList",
"(",
"dir",
")",
".",
"catch",
"(",
"reject",
")",
".",
"then",
"(",
"readAndHashFiles",
")",
".",
"catch",
"(",
"reject",
")",
".",
"then",
"(",
"(",
"result",
")",
"=>",
"{",
"const",
"hash",
"=",
"result",
".",
"files",
".",
"reduce",
"(",
"(",
"tmpHash",
",",
"file",
")",
"=>",
"{",
"tmpHash",
"+=",
"result",
".",
"fileHashes",
"[",
"file",
"]",
";",
"return",
"tmpHash",
";",
"}",
",",
"''",
")",
";",
"desktopHash",
".",
"update",
"(",
"hash",
")",
";",
"result",
".",
"hash",
"=",
"desktopHash",
".",
"digest",
"(",
"'hex'",
")",
";",
"resolve",
"(",
"result",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Reads files from .desktop and computes a version hash.
@param {string} dir - path
@returns {Promise<Object>}
|
[
"Reads",
"files",
"from",
".",
"desktop",
"and",
"computes",
"a",
"version",
"hash",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/plugins/watcher/watcher.js#L187-L207
|
14,030
|
wojtkowiak/meteor-desktop
|
lib/electronBuilder.js
|
removeDir
|
function removeDir(dirPath, delay = 0) {
return new Promise((resolve, reject) => {
setTimeout(() => {
rimraf(dirPath, {
maxBusyTries: 100
}, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
}, delay);
});
}
|
javascript
|
function removeDir(dirPath, delay = 0) {
return new Promise((resolve, reject) => {
setTimeout(() => {
rimraf(dirPath, {
maxBusyTries: 100
}, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
}, delay);
});
}
|
[
"function",
"removeDir",
"(",
"dirPath",
",",
"delay",
"=",
"0",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"rimraf",
"(",
"dirPath",
",",
"{",
"maxBusyTries",
":",
"100",
"}",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
"else",
"{",
"resolve",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"delay",
")",
";",
"}",
")",
";",
"}"
] |
Promisfied rimraf.
@param {string} dirPath - path to the dir to be deleted
@param {number} delay - delay the task by ms
@returns {Promise<any>}
|
[
"Promisfied",
"rimraf",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/lib/electronBuilder.js#L18-L32
|
14,031
|
wojtkowiak/meteor-desktop
|
skeleton/modules/autoupdate/assetManifest.js
|
ManifestEntry
|
function ManifestEntry(manifestEntry) {
assignIn(this, {
filePath: manifestEntry.path,
urlPath: manifestEntry.url,
fileType: manifestEntry.type,
size: manifestEntry.size,
cacheable: manifestEntry.cacheable,
hash: manifestEntry.hash || null,
sourceMapFilePath: manifestEntry.sourceMap || null,
sourceMapUrlPath: manifestEntry.sourceMapUrl || null
});
}
|
javascript
|
function ManifestEntry(manifestEntry) {
assignIn(this, {
filePath: manifestEntry.path,
urlPath: manifestEntry.url,
fileType: manifestEntry.type,
size: manifestEntry.size,
cacheable: manifestEntry.cacheable,
hash: manifestEntry.hash || null,
sourceMapFilePath: manifestEntry.sourceMap || null,
sourceMapUrlPath: manifestEntry.sourceMapUrl || null
});
}
|
[
"function",
"ManifestEntry",
"(",
"manifestEntry",
")",
"{",
"assignIn",
"(",
"this",
",",
"{",
"filePath",
":",
"manifestEntry",
".",
"path",
",",
"urlPath",
":",
"manifestEntry",
".",
"url",
",",
"fileType",
":",
"manifestEntry",
".",
"type",
",",
"size",
":",
"manifestEntry",
".",
"size",
",",
"cacheable",
":",
"manifestEntry",
".",
"cacheable",
",",
"hash",
":",
"manifestEntry",
".",
"hash",
"||",
"null",
",",
"sourceMapFilePath",
":",
"manifestEntry",
".",
"sourceMap",
"||",
"null",
",",
"sourceMapUrlPath",
":",
"manifestEntry",
".",
"sourceMapUrl",
"||",
"null",
"}",
")",
";",
"}"
] |
Represents single file in the manifest.
@param {object} manifestEntry
@param {string} manifestEntry.path
@param {string} manifestEntry.url
@param {string} manifestEntry.type
@param {number} manifestEntry.size
@param {bool} manifestEntry.cacheable
@param {string} manifestEntry.hash
@param {string} manifestEntry.sourceMap
@param {string} manifestEntry.sourceMapUrl
@property {string} filePath
@property {string} urlPath
@property {string} fileType
@property {number} size
@property {bool} cacheable
@property {string} hash
@property {string} sourceMapFilePath
@property {string} sourceMapUrlPath
@constructor
|
[
"Represents",
"single",
"file",
"in",
"the",
"manifest",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/skeleton/modules/autoupdate/assetManifest.js#L57-L68
|
14,032
|
wojtkowiak/meteor-desktop
|
skeleton/modules/localServer.js
|
createStreamProtocolResponse
|
function createStreamProtocolResponse(filePath, res, beforeFinalize) {
if (!fs.existsSync(filePath)) {
return;
}
// Setting file size.
const stat = fs.statSync(filePath);
res.setHeader('Content-Length', stat.size);
// Setting last modified date.
const modified = stat.mtime.toUTCString();
res.setHeader('Last-Modified', modified);
// Determining mime type.
const type = mime.getType(filePath);
if (type) {
const charset = mime.getExtension(type);
res.setHeader('Content-Type', type + (charset ? `; charset=${charset}` : ''));
} else {
res.setHeader('Content-Type', 'application/octet-stream');
}
res.setHeader('Connection', 'close');
res.setStream(fs.createReadStream(filePath));
res.setStatusCode(200);
beforeFinalize();
res.finalize();
}
|
javascript
|
function createStreamProtocolResponse(filePath, res, beforeFinalize) {
if (!fs.existsSync(filePath)) {
return;
}
// Setting file size.
const stat = fs.statSync(filePath);
res.setHeader('Content-Length', stat.size);
// Setting last modified date.
const modified = stat.mtime.toUTCString();
res.setHeader('Last-Modified', modified);
// Determining mime type.
const type = mime.getType(filePath);
if (type) {
const charset = mime.getExtension(type);
res.setHeader('Content-Type', type + (charset ? `; charset=${charset}` : ''));
} else {
res.setHeader('Content-Type', 'application/octet-stream');
}
res.setHeader('Connection', 'close');
res.setStream(fs.createReadStream(filePath));
res.setStatusCode(200);
beforeFinalize();
res.finalize();
}
|
[
"function",
"createStreamProtocolResponse",
"(",
"filePath",
",",
"res",
",",
"beforeFinalize",
")",
"{",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"filePath",
")",
")",
"{",
"return",
";",
"}",
"// Setting file size.",
"const",
"stat",
"=",
"fs",
".",
"statSync",
"(",
"filePath",
")",
";",
"res",
".",
"setHeader",
"(",
"'Content-Length'",
",",
"stat",
".",
"size",
")",
";",
"// Setting last modified date.",
"const",
"modified",
"=",
"stat",
".",
"mtime",
".",
"toUTCString",
"(",
")",
";",
"res",
".",
"setHeader",
"(",
"'Last-Modified'",
",",
"modified",
")",
";",
"// Determining mime type.",
"const",
"type",
"=",
"mime",
".",
"getType",
"(",
"filePath",
")",
";",
"if",
"(",
"type",
")",
"{",
"const",
"charset",
"=",
"mime",
".",
"getExtension",
"(",
"type",
")",
";",
"res",
".",
"setHeader",
"(",
"'Content-Type'",
",",
"type",
"+",
"(",
"charset",
"?",
"`",
"${",
"charset",
"}",
"`",
":",
"''",
")",
")",
";",
"}",
"else",
"{",
"res",
".",
"setHeader",
"(",
"'Content-Type'",
",",
"'application/octet-stream'",
")",
";",
"}",
"res",
".",
"setHeader",
"(",
"'Connection'",
",",
"'close'",
")",
";",
"res",
".",
"setStream",
"(",
"fs",
".",
"createReadStream",
"(",
"filePath",
")",
")",
";",
"res",
".",
"setStatusCode",
"(",
"200",
")",
";",
"beforeFinalize",
"(",
")",
";",
"res",
".",
"finalize",
"(",
")",
";",
"}"
] |
Creates stream protocol response for a given file acting like it would come
from a real HTTP server.
@param {string} filePath - path to the file being sent
@param {StreamProtocolResponse} res - the response object
@param {Function} beforeFinalize - function to be run before finalizing the response object
|
[
"Creates",
"stream",
"protocol",
"response",
"for",
"a",
"given",
"file",
"acting",
"like",
"it",
"would",
"come",
"from",
"a",
"real",
"HTTP",
"server",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/skeleton/modules/localServer.js#L55-L83
|
14,033
|
wojtkowiak/meteor-desktop
|
skeleton/modules/localServer.js
|
respondWithCode
|
function respondWithCode(res, code, message) {
/* eslint-disable */
res._headers = {};
res._headerNames = {};
res.statusCode = code;
/* eslint-enable */
res.setHeader('Content-Type', 'text/plain; charset=UTF-8');
res.setHeader('Content-Length', Buffer.byteLength(message));
res.setHeader('X-Content-Type-Options', 'nosniff');
res.end(message);
}
|
javascript
|
function respondWithCode(res, code, message) {
/* eslint-disable */
res._headers = {};
res._headerNames = {};
res.statusCode = code;
/* eslint-enable */
res.setHeader('Content-Type', 'text/plain; charset=UTF-8');
res.setHeader('Content-Length', Buffer.byteLength(message));
res.setHeader('X-Content-Type-Options', 'nosniff');
res.end(message);
}
|
[
"function",
"respondWithCode",
"(",
"res",
",",
"code",
",",
"message",
")",
"{",
"/* eslint-disable */",
"res",
".",
"_headers",
"=",
"{",
"}",
";",
"res",
".",
"_headerNames",
"=",
"{",
"}",
";",
"res",
".",
"statusCode",
"=",
"code",
";",
"/* eslint-enable */",
"res",
".",
"setHeader",
"(",
"'Content-Type'",
",",
"'text/plain; charset=UTF-8'",
")",
";",
"res",
".",
"setHeader",
"(",
"'Content-Length'",
",",
"Buffer",
".",
"byteLength",
"(",
"message",
")",
")",
";",
"res",
".",
"setHeader",
"(",
"'X-Content-Type-Options'",
",",
"'nosniff'",
")",
";",
"res",
".",
"end",
"(",
"message",
")",
";",
"}"
] |
Responds with HTTP status code and a message.
@param {Object} res - response object
@param {number} code - http response code
@param {string} message - message
|
[
"Responds",
"with",
"HTTP",
"status",
"code",
"and",
"a",
"message",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/skeleton/modules/localServer.js#L209-L219
|
14,034
|
wojtkowiak/meteor-desktop
|
skeleton/modules/localServer.js
|
AssetHandler
|
function AssetHandler(req, res, next, local = false) {
const parsedUrl = url.parse(req.url);
// Check if we have an asset for that url defined.
/** @type {Asset} */
const asset = self.assetBundle.assetForUrlPath(parsedUrl.pathname);
if (!asset) return next();
const processors = () => (
addSourceMapHeader(asset, res),
addETagHeader(asset, res),
addCacheHeader(asset, res, req.url)
);
if (local) {
return createStreamProtocolResponse(asset.getFile(), res, processors);
}
return send(
req,
encodeURIComponent(asset.getFile()),
{ etag: false, cacheControl: false }
)
.on('file', processors)
.pipe(res);
}
|
javascript
|
function AssetHandler(req, res, next, local = false) {
const parsedUrl = url.parse(req.url);
// Check if we have an asset for that url defined.
/** @type {Asset} */
const asset = self.assetBundle.assetForUrlPath(parsedUrl.pathname);
if (!asset) return next();
const processors = () => (
addSourceMapHeader(asset, res),
addETagHeader(asset, res),
addCacheHeader(asset, res, req.url)
);
if (local) {
return createStreamProtocolResponse(asset.getFile(), res, processors);
}
return send(
req,
encodeURIComponent(asset.getFile()),
{ etag: false, cacheControl: false }
)
.on('file', processors)
.pipe(res);
}
|
[
"function",
"AssetHandler",
"(",
"req",
",",
"res",
",",
"next",
",",
"local",
"=",
"false",
")",
"{",
"const",
"parsedUrl",
"=",
"url",
".",
"parse",
"(",
"req",
".",
"url",
")",
";",
"// Check if we have an asset for that url defined.",
"/** @type {Asset} */",
"const",
"asset",
"=",
"self",
".",
"assetBundle",
".",
"assetForUrlPath",
"(",
"parsedUrl",
".",
"pathname",
")",
";",
"if",
"(",
"!",
"asset",
")",
"return",
"next",
"(",
")",
";",
"const",
"processors",
"=",
"(",
")",
"=>",
"(",
"addSourceMapHeader",
"(",
"asset",
",",
"res",
")",
",",
"addETagHeader",
"(",
"asset",
",",
"res",
")",
",",
"addCacheHeader",
"(",
"asset",
",",
"res",
",",
"req",
".",
"url",
")",
")",
";",
"if",
"(",
"local",
")",
"{",
"return",
"createStreamProtocolResponse",
"(",
"asset",
".",
"getFile",
"(",
")",
",",
"res",
",",
"processors",
")",
";",
"}",
"return",
"send",
"(",
"req",
",",
"encodeURIComponent",
"(",
"asset",
".",
"getFile",
"(",
")",
")",
",",
"{",
"etag",
":",
"false",
",",
"cacheControl",
":",
"false",
"}",
")",
".",
"on",
"(",
"'file'",
",",
"processors",
")",
".",
"pipe",
"(",
"res",
")",
";",
"}"
] |
Provides assets defined in the manifest.
@param {Object} req - request object
@param {Object} res - response object
@param {Function} next - called on handler miss
@param {boolean} local - local mode
|
[
"Provides",
"assets",
"defined",
"in",
"the",
"manifest",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/skeleton/modules/localServer.js#L268-L292
|
14,035
|
wojtkowiak/meteor-desktop
|
skeleton/modules/localServer.js
|
WwwHandler
|
function WwwHandler(req, res, next, local = false) {
const parsedUrl = url.parse(req.url);
if (parsedUrl.pathname !== '/cordova.js') {
return next();
}
const parentAssetBundle = self.assetBundle.getParentAssetBundle();
// We need to obtain a path for the initial asset bundle which usually is the parent
// asset bundle, but if there were not HCPs yet, the main asset bundle is the
// initial one.
const initialAssetBundlePath =
parentAssetBundle ?
parentAssetBundle.getDirectoryUri() : self.assetBundle.getDirectoryUri();
const filePath = path.join(initialAssetBundlePath, parsedUrl.pathname);
if (fs.existsSync(filePath)) {
return local ?
createStreamProtocolResponse(filePath, res, () => {
}) :
send(req, encodeURIComponent(filePath)).pipe(res);
}
return next();
}
|
javascript
|
function WwwHandler(req, res, next, local = false) {
const parsedUrl = url.parse(req.url);
if (parsedUrl.pathname !== '/cordova.js') {
return next();
}
const parentAssetBundle = self.assetBundle.getParentAssetBundle();
// We need to obtain a path for the initial asset bundle which usually is the parent
// asset bundle, but if there were not HCPs yet, the main asset bundle is the
// initial one.
const initialAssetBundlePath =
parentAssetBundle ?
parentAssetBundle.getDirectoryUri() : self.assetBundle.getDirectoryUri();
const filePath = path.join(initialAssetBundlePath, parsedUrl.pathname);
if (fs.existsSync(filePath)) {
return local ?
createStreamProtocolResponse(filePath, res, () => {
}) :
send(req, encodeURIComponent(filePath)).pipe(res);
}
return next();
}
|
[
"function",
"WwwHandler",
"(",
"req",
",",
"res",
",",
"next",
",",
"local",
"=",
"false",
")",
"{",
"const",
"parsedUrl",
"=",
"url",
".",
"parse",
"(",
"req",
".",
"url",
")",
";",
"if",
"(",
"parsedUrl",
".",
"pathname",
"!==",
"'/cordova.js'",
")",
"{",
"return",
"next",
"(",
")",
";",
"}",
"const",
"parentAssetBundle",
"=",
"self",
".",
"assetBundle",
".",
"getParentAssetBundle",
"(",
")",
";",
"// We need to obtain a path for the initial asset bundle which usually is the parent",
"// asset bundle, but if there were not HCPs yet, the main asset bundle is the",
"// initial one.",
"const",
"initialAssetBundlePath",
"=",
"parentAssetBundle",
"?",
"parentAssetBundle",
".",
"getDirectoryUri",
"(",
")",
":",
"self",
".",
"assetBundle",
".",
"getDirectoryUri",
"(",
")",
";",
"const",
"filePath",
"=",
"path",
".",
"join",
"(",
"initialAssetBundlePath",
",",
"parsedUrl",
".",
"pathname",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"filePath",
")",
")",
"{",
"return",
"local",
"?",
"createStreamProtocolResponse",
"(",
"filePath",
",",
"res",
",",
"(",
")",
"=>",
"{",
"}",
")",
":",
"send",
"(",
"req",
",",
"encodeURIComponent",
"(",
"filePath",
")",
")",
".",
"pipe",
"(",
"res",
")",
";",
"}",
"return",
"next",
"(",
")",
";",
"}"
] |
Right now this is only used to serve cordova.js and it might seems like an overkill but
it will be used later for serving desktop specific files bundled into meteor bundle.
@param {Object} req - request object
@param {Object} res - response object
@param {Function} next - called on handler miss
@param {boolean} local - local mode
|
[
"Right",
"now",
"this",
"is",
"only",
"used",
"to",
"serve",
"cordova",
".",
"js",
"and",
"it",
"might",
"seems",
"like",
"an",
"overkill",
"but",
"it",
"will",
"be",
"used",
"later",
"for",
"serving",
"desktop",
"specific",
"files",
"bundled",
"into",
"meteor",
"bundle",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/skeleton/modules/localServer.js#L303-L326
|
14,036
|
wojtkowiak/meteor-desktop
|
skeleton/modules/localServer.js
|
FilesystemHandler
|
function FilesystemHandler(req, res, next, urlAlias, localPath, local = false) {
const parsedUrl = url.parse(req.url);
if (!parsedUrl.pathname.startsWith(urlAlias)) {
return next();
}
const bareUrl = parsedUrl.pathname.substr(urlAlias.length);
let filePath;
if (localPath) {
filePath = path.join(localPath, decodeURIComponent(bareUrl));
if (filePath.toLowerCase().lastIndexOf(localPath.toLowerCase(), 0) !== 0) {
return respondWithCode(res, 400, 'Wrong path.');
}
} else {
filePath = decodeURIComponent(bareUrl);
}
if (fs.existsSync(filePath)) {
return local ?
createStreamProtocolResponse(filePath, res, () => {
}) :
send(req, encodeURIComponent(filePath)).pipe(res);
}
return local ? res.setStatusCode(404) : respondWithCode(res, 404, 'File does not exist.');
}
|
javascript
|
function FilesystemHandler(req, res, next, urlAlias, localPath, local = false) {
const parsedUrl = url.parse(req.url);
if (!parsedUrl.pathname.startsWith(urlAlias)) {
return next();
}
const bareUrl = parsedUrl.pathname.substr(urlAlias.length);
let filePath;
if (localPath) {
filePath = path.join(localPath, decodeURIComponent(bareUrl));
if (filePath.toLowerCase().lastIndexOf(localPath.toLowerCase(), 0) !== 0) {
return respondWithCode(res, 400, 'Wrong path.');
}
} else {
filePath = decodeURIComponent(bareUrl);
}
if (fs.existsSync(filePath)) {
return local ?
createStreamProtocolResponse(filePath, res, () => {
}) :
send(req, encodeURIComponent(filePath)).pipe(res);
}
return local ? res.setStatusCode(404) : respondWithCode(res, 404, 'File does not exist.');
}
|
[
"function",
"FilesystemHandler",
"(",
"req",
",",
"res",
",",
"next",
",",
"urlAlias",
",",
"localPath",
",",
"local",
"=",
"false",
")",
"{",
"const",
"parsedUrl",
"=",
"url",
".",
"parse",
"(",
"req",
".",
"url",
")",
";",
"if",
"(",
"!",
"parsedUrl",
".",
"pathname",
".",
"startsWith",
"(",
"urlAlias",
")",
")",
"{",
"return",
"next",
"(",
")",
";",
"}",
"const",
"bareUrl",
"=",
"parsedUrl",
".",
"pathname",
".",
"substr",
"(",
"urlAlias",
".",
"length",
")",
";",
"let",
"filePath",
";",
"if",
"(",
"localPath",
")",
"{",
"filePath",
"=",
"path",
".",
"join",
"(",
"localPath",
",",
"decodeURIComponent",
"(",
"bareUrl",
")",
")",
";",
"if",
"(",
"filePath",
".",
"toLowerCase",
"(",
")",
".",
"lastIndexOf",
"(",
"localPath",
".",
"toLowerCase",
"(",
")",
",",
"0",
")",
"!==",
"0",
")",
"{",
"return",
"respondWithCode",
"(",
"res",
",",
"400",
",",
"'Wrong path.'",
")",
";",
"}",
"}",
"else",
"{",
"filePath",
"=",
"decodeURIComponent",
"(",
"bareUrl",
")",
";",
"}",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"filePath",
")",
")",
"{",
"return",
"local",
"?",
"createStreamProtocolResponse",
"(",
"filePath",
",",
"res",
",",
"(",
")",
"=>",
"{",
"}",
")",
":",
"send",
"(",
"req",
",",
"encodeURIComponent",
"(",
"filePath",
")",
")",
".",
"pipe",
"(",
"res",
")",
";",
"}",
"return",
"local",
"?",
"res",
".",
"setStatusCode",
"(",
"404",
")",
":",
"respondWithCode",
"(",
"res",
",",
"404",
",",
"'File does not exist.'",
")",
";",
"}"
] |
Provides files from the filesystem on a specified url alias.
@param {Object} req - request object
@param {Object} res - response object
@param {Function} next - called on handler miss
@param {string} urlAlias - url alias on which to serve the files
@param {string=} localPath - serve files only from this path
@param {boolean} local - local mode
|
[
"Provides",
"files",
"from",
"the",
"filesystem",
"on",
"a",
"specified",
"url",
"alias",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/skeleton/modules/localServer.js#L338-L363
|
14,037
|
wojtkowiak/meteor-desktop
|
skeleton/modules/localServer.js
|
LocalFilesystemHandler
|
function LocalFilesystemHandler(req, res, next, local = false) {
if (!self.settings.localFilesystem) {
return next();
}
return FilesystemHandler(req, res, next, self.localFilesystemUrl, undefined, local);
}
|
javascript
|
function LocalFilesystemHandler(req, res, next, local = false) {
if (!self.settings.localFilesystem) {
return next();
}
return FilesystemHandler(req, res, next, self.localFilesystemUrl, undefined, local);
}
|
[
"function",
"LocalFilesystemHandler",
"(",
"req",
",",
"res",
",",
"next",
",",
"local",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"self",
".",
"settings",
".",
"localFilesystem",
")",
"{",
"return",
"next",
"(",
")",
";",
"}",
"return",
"FilesystemHandler",
"(",
"req",
",",
"res",
",",
"next",
",",
"self",
".",
"localFilesystemUrl",
",",
"undefined",
",",
"local",
")",
";",
"}"
] |
Serves files from the entire filesystem if enabled in settings.
@param {Object} req - request object
@param {Object} res - response object
@param {Function} next - called on handler miss
@param {boolean} local - local mode
|
[
"Serves",
"files",
"from",
"the",
"entire",
"filesystem",
"if",
"enabled",
"in",
"settings",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/skeleton/modules/localServer.js#L374-L379
|
14,038
|
wojtkowiak/meteor-desktop
|
skeleton/modules/localServer.js
|
DesktopAssetsHandler
|
function DesktopAssetsHandler(req, res, next, local = false) {
return FilesystemHandler(req, res, next, self.desktopAssetsUrl, path.join(desktopPath, 'assets'), local);
}
|
javascript
|
function DesktopAssetsHandler(req, res, next, local = false) {
return FilesystemHandler(req, res, next, self.desktopAssetsUrl, path.join(desktopPath, 'assets'), local);
}
|
[
"function",
"DesktopAssetsHandler",
"(",
"req",
",",
"res",
",",
"next",
",",
"local",
"=",
"false",
")",
"{",
"return",
"FilesystemHandler",
"(",
"req",
",",
"res",
",",
"next",
",",
"self",
".",
"desktopAssetsUrl",
",",
"path",
".",
"join",
"(",
"desktopPath",
",",
"'assets'",
")",
",",
"local",
")",
";",
"}"
] |
Serves files from the assets directory.
@param {Object} req - request object
@param {Object} res - response object
@param {Function} next - called on handler miss
@param {boolean} local - local mode
|
[
"Serves",
"files",
"from",
"the",
"assets",
"directory",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/skeleton/modules/localServer.js#L389-L391
|
14,039
|
wojtkowiak/meteor-desktop
|
skeleton/modules/localServer.js
|
IndexHandler
|
function IndexHandler(req, res, next, local = false) {
const parsedUrl = url.parse(req.url);
if (!parsedUrl.pathname.startsWith(self.localFilesystemUrl) &&
parsedUrl.pathname !== '/favicon.ico'
) {
/** @type {Asset} */
const indexFile = self.assetBundle.getIndexFile();
if (local) {
createStreamProtocolResponse(indexFile.getFile(), res, () => {
});
} else {
send(req, encodeURIComponent(indexFile.getFile())).pipe(res);
}
} else {
next();
}
}
|
javascript
|
function IndexHandler(req, res, next, local = false) {
const parsedUrl = url.parse(req.url);
if (!parsedUrl.pathname.startsWith(self.localFilesystemUrl) &&
parsedUrl.pathname !== '/favicon.ico'
) {
/** @type {Asset} */
const indexFile = self.assetBundle.getIndexFile();
if (local) {
createStreamProtocolResponse(indexFile.getFile(), res, () => {
});
} else {
send(req, encodeURIComponent(indexFile.getFile())).pipe(res);
}
} else {
next();
}
}
|
[
"function",
"IndexHandler",
"(",
"req",
",",
"res",
",",
"next",
",",
"local",
"=",
"false",
")",
"{",
"const",
"parsedUrl",
"=",
"url",
".",
"parse",
"(",
"req",
".",
"url",
")",
";",
"if",
"(",
"!",
"parsedUrl",
".",
"pathname",
".",
"startsWith",
"(",
"self",
".",
"localFilesystemUrl",
")",
"&&",
"parsedUrl",
".",
"pathname",
"!==",
"'/favicon.ico'",
")",
"{",
"/** @type {Asset} */",
"const",
"indexFile",
"=",
"self",
".",
"assetBundle",
".",
"getIndexFile",
"(",
")",
";",
"if",
"(",
"local",
")",
"{",
"createStreamProtocolResponse",
"(",
"indexFile",
".",
"getFile",
"(",
")",
",",
"res",
",",
"(",
")",
"=>",
"{",
"}",
")",
";",
"}",
"else",
"{",
"send",
"(",
"req",
",",
"encodeURIComponent",
"(",
"indexFile",
".",
"getFile",
"(",
")",
")",
")",
".",
"pipe",
"(",
"res",
")",
";",
"}",
"}",
"else",
"{",
"next",
"(",
")",
";",
"}",
"}"
] |
Serves index.html as the last resort.
@param {Object} req - request object
@param {Object} res - response object
@param {Function} next - called on handler miss
@param {boolean} local - local mode
|
[
"Serves",
"index",
".",
"html",
"as",
"the",
"last",
"resort",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/skeleton/modules/localServer.js#L401-L417
|
14,040
|
wojtkowiak/meteor-desktop
|
skeleton/modules/autoupdate/assetBundle.js
|
Asset
|
function Asset(filePath, urlPath, fileType, cacheable, hash, sourceMapUrlPath, size, bundle) {
this.filePath = filePath;
this.urlPath = urlPath;
this.fileType = fileType;
this.cacheable = cacheable;
this.hash = hash;
this.entrySize = size;
this.sourceMapUrlPath = sourceMapUrlPath;
this.bundle = bundle;
this.getFile = function getFile() {
return path.join(this.bundle.directoryUri, filePath);
};
}
|
javascript
|
function Asset(filePath, urlPath, fileType, cacheable, hash, sourceMapUrlPath, size, bundle) {
this.filePath = filePath;
this.urlPath = urlPath;
this.fileType = fileType;
this.cacheable = cacheable;
this.hash = hash;
this.entrySize = size;
this.sourceMapUrlPath = sourceMapUrlPath;
this.bundle = bundle;
this.getFile = function getFile() {
return path.join(this.bundle.directoryUri, filePath);
};
}
|
[
"function",
"Asset",
"(",
"filePath",
",",
"urlPath",
",",
"fileType",
",",
"cacheable",
",",
"hash",
",",
"sourceMapUrlPath",
",",
"size",
",",
"bundle",
")",
"{",
"this",
".",
"filePath",
"=",
"filePath",
";",
"this",
".",
"urlPath",
"=",
"urlPath",
";",
"this",
".",
"fileType",
"=",
"fileType",
";",
"this",
".",
"cacheable",
"=",
"cacheable",
";",
"this",
".",
"hash",
"=",
"hash",
";",
"this",
".",
"entrySize",
"=",
"size",
";",
"this",
".",
"sourceMapUrlPath",
"=",
"sourceMapUrlPath",
";",
"this",
".",
"bundle",
"=",
"bundle",
";",
"this",
".",
"getFile",
"=",
"function",
"getFile",
"(",
")",
"{",
"return",
"path",
".",
"join",
"(",
"this",
".",
"bundle",
".",
"directoryUri",
",",
"filePath",
")",
";",
"}",
";",
"}"
] |
Represent single asset in the bundle.
@property {string} filePath
@property {string} urlPath
@property {string} fileType
@property {number} size
@property {bool} cacheable
@property {string} hash
@property {string} sourceMapFilePath
@property {string} sourceMapUrlPath
@property {AssetBundle} bundle
@constructor
|
[
"Represent",
"single",
"asset",
"in",
"the",
"bundle",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/skeleton/modules/autoupdate/assetBundle.js#L52-L65
|
14,041
|
wojtkowiak/meteor-desktop
|
lib/desktop.js
|
isEmptySync
|
function isEmptySync(searchPath) {
let stat;
try {
stat = fs.statSync(searchPath);
} catch (e) {
return true;
}
if (stat.isDirectory()) {
const items = fs.readdirSync(searchPath);
return !items || !items.length;
}
return false;
}
|
javascript
|
function isEmptySync(searchPath) {
let stat;
try {
stat = fs.statSync(searchPath);
} catch (e) {
return true;
}
if (stat.isDirectory()) {
const items = fs.readdirSync(searchPath);
return !items || !items.length;
}
return false;
}
|
[
"function",
"isEmptySync",
"(",
"searchPath",
")",
"{",
"let",
"stat",
";",
"try",
"{",
"stat",
"=",
"fs",
".",
"statSync",
"(",
"searchPath",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"const",
"items",
"=",
"fs",
".",
"readdirSync",
"(",
"searchPath",
")",
";",
"return",
"!",
"items",
"||",
"!",
"items",
".",
"length",
";",
"}",
"return",
"false",
";",
"}"
] |
Checks if the path is empty.
@param {string} searchPath
@returns {boolean}
|
[
"Checks",
"if",
"the",
"path",
"is",
"empty",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/lib/desktop.js#L16-L28
|
14,042
|
wojtkowiak/meteor-desktop
|
skeleton/modules/autoupdate/utils.js
|
rimrafWithRetries
|
function rimrafWithRetries(...args) {
let retries = 0;
return new Promise((resolve, reject) => {
function rm(...rmArgs) {
try {
rimraf.sync(...rmArgs);
resolve();
} catch (e) {
retries += 1;
if (retries < 5) {
setTimeout(() => {
rm(...rmArgs);
}, 100);
} else {
reject(e);
}
}
}
rm(...args);
});
}
|
javascript
|
function rimrafWithRetries(...args) {
let retries = 0;
return new Promise((resolve, reject) => {
function rm(...rmArgs) {
try {
rimraf.sync(...rmArgs);
resolve();
} catch (e) {
retries += 1;
if (retries < 5) {
setTimeout(() => {
rm(...rmArgs);
}, 100);
} else {
reject(e);
}
}
}
rm(...args);
});
}
|
[
"function",
"rimrafWithRetries",
"(",
"...",
"args",
")",
"{",
"let",
"retries",
"=",
"0",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"function",
"rm",
"(",
"...",
"rmArgs",
")",
"{",
"try",
"{",
"rimraf",
".",
"sync",
"(",
"...",
"rmArgs",
")",
";",
"resolve",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"retries",
"+=",
"1",
";",
"if",
"(",
"retries",
"<",
"5",
")",
"{",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"rm",
"(",
"...",
"rmArgs",
")",
";",
"}",
",",
"100",
")",
";",
"}",
"else",
"{",
"reject",
"(",
"e",
")",
";",
"}",
"}",
"}",
"rm",
"(",
"...",
"args",
")",
";",
"}",
")",
";",
"}"
] |
Simple wrapper for rimraf with additional retries in case of failure.
It is useful when something is concurrently reading the dir you want to remove.
|
[
"Simple",
"wrapper",
"for",
"rimraf",
"with",
"additional",
"retries",
"in",
"case",
"of",
"failure",
".",
"It",
"is",
"useful",
"when",
"something",
"is",
"concurrently",
"reading",
"the",
"dir",
"you",
"want",
"to",
"remove",
"."
] |
3e4f21be1b7ca3cfbf9093b413037e679e502d81
|
https://github.com/wojtkowiak/meteor-desktop/blob/3e4f21be1b7ca3cfbf9093b413037e679e502d81/skeleton/modules/autoupdate/utils.js#L7-L27
|
14,043
|
englercj/resource-loader
|
src/Resource.js
|
setExtMap
|
function setExtMap(map, extname, val) {
if (extname && extname.indexOf('.') === 0) {
extname = extname.substring(1);
}
if (!extname) {
return;
}
map[extname] = val;
}
|
javascript
|
function setExtMap(map, extname, val) {
if (extname && extname.indexOf('.') === 0) {
extname = extname.substring(1);
}
if (!extname) {
return;
}
map[extname] = val;
}
|
[
"function",
"setExtMap",
"(",
"map",
",",
"extname",
",",
"val",
")",
"{",
"if",
"(",
"extname",
"&&",
"extname",
".",
"indexOf",
"(",
"'.'",
")",
"===",
"0",
")",
"{",
"extname",
"=",
"extname",
".",
"substring",
"(",
"1",
")",
";",
"}",
"if",
"(",
"!",
"extname",
")",
"{",
"return",
";",
"}",
"map",
"[",
"extname",
"]",
"=",
"val",
";",
"}"
] |
Quick helper to set a value on one of the extension maps. Ensures there is no
dot at the start of the extension.
@ignore
@param {object} map - The map to set on.
@param {string} extname - The extension (or key) to set.
@param {number} val - The value to set.
|
[
"Quick",
"helper",
"to",
"set",
"a",
"value",
"on",
"one",
"of",
"the",
"extension",
"maps",
".",
"Ensures",
"there",
"is",
"no",
"dot",
"at",
"the",
"start",
"of",
"the",
"extension",
"."
] |
3a2a8d7a524bc467cb4198f72ef725dbcc54f2cd
|
https://github.com/englercj/resource-loader/blob/3a2a8d7a524bc467cb4198f72ef725dbcc54f2cd/src/Resource.js#L1155-L1165
|
14,044
|
leancloud/javascript-sdk
|
src/op.js
|
function(json) {
var decoder = AV.Op._opDecoderMap[json.__op];
if (decoder) {
return decoder(json);
} else {
return undefined;
}
}
|
javascript
|
function(json) {
var decoder = AV.Op._opDecoderMap[json.__op];
if (decoder) {
return decoder(json);
} else {
return undefined;
}
}
|
[
"function",
"(",
"json",
")",
"{",
"var",
"decoder",
"=",
"AV",
".",
"Op",
".",
"_opDecoderMap",
"[",
"json",
".",
"__op",
"]",
";",
"if",
"(",
"decoder",
")",
"{",
"return",
"decoder",
"(",
"json",
")",
";",
"}",
"else",
"{",
"return",
"undefined",
";",
"}",
"}"
] |
Converts a json object into an instance of a subclass of AV.Op.
@private
|
[
"Converts",
"a",
"json",
"object",
"into",
"an",
"instance",
"of",
"a",
"subclass",
"of",
"AV",
".",
"Op",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/op.js#L51-L58
|
|
14,045
|
leancloud/javascript-sdk
|
src/status.js
|
function(options) {
if (!this.id)
return Promise.reject(new Error('The status id is not exists.'));
var request = AVRequest('statuses', null, this.id, 'DELETE', options);
return request;
}
|
javascript
|
function(options) {
if (!this.id)
return Promise.reject(new Error('The status id is not exists.'));
var request = AVRequest('statuses', null, this.id, 'DELETE', options);
return request;
}
|
[
"function",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"this",
".",
"id",
")",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'The status id is not exists.'",
")",
")",
";",
"var",
"request",
"=",
"AVRequest",
"(",
"'statuses'",
",",
"null",
",",
"this",
".",
"id",
",",
"'DELETE'",
",",
"options",
")",
";",
"return",
"request",
";",
"}"
] |
Destroy this status,then it will not be avaiable in other user's inboxes.
@param {AuthOptions} options
@return {Promise} A promise that is fulfilled when the destroy
completes.
|
[
"Destroy",
"this",
"status",
"then",
"it",
"will",
"not",
"be",
"avaiable",
"in",
"other",
"user",
"s",
"inboxes",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/status.js#L66-L71
|
|
14,046
|
leancloud/javascript-sdk
|
src/status.js
|
function(options = {}) {
if (!getSessionToken(options) && !AV.User.current()) {
throw new Error('Please signin an user.');
}
if (!this.query) {
return AV.Status.sendStatusToFollowers(this, options);
}
return getUserPointer(options)
.then(currUser => {
var query = this.query.toJSON();
query.className = this.query.className;
var data = {};
data.query = query;
this.data = this.data || {};
this.data.source = this.data.source || currUser;
data.data = this._getDataJSON();
data.inboxType = this.inboxType || 'default';
return AVRequest('statuses', null, null, 'POST', data, options);
})
.then(response => {
this.id = response.objectId;
this.createdAt = AV._parseDate(response.createdAt);
return this;
});
}
|
javascript
|
function(options = {}) {
if (!getSessionToken(options) && !AV.User.current()) {
throw new Error('Please signin an user.');
}
if (!this.query) {
return AV.Status.sendStatusToFollowers(this, options);
}
return getUserPointer(options)
.then(currUser => {
var query = this.query.toJSON();
query.className = this.query.className;
var data = {};
data.query = query;
this.data = this.data || {};
this.data.source = this.data.source || currUser;
data.data = this._getDataJSON();
data.inboxType = this.inboxType || 'default';
return AVRequest('statuses', null, null, 'POST', data, options);
})
.then(response => {
this.id = response.objectId;
this.createdAt = AV._parseDate(response.createdAt);
return this;
});
}
|
[
"function",
"(",
"options",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"!",
"getSessionToken",
"(",
"options",
")",
"&&",
"!",
"AV",
".",
"User",
".",
"current",
"(",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Please signin an user.'",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"query",
")",
"{",
"return",
"AV",
".",
"Status",
".",
"sendStatusToFollowers",
"(",
"this",
",",
"options",
")",
";",
"}",
"return",
"getUserPointer",
"(",
"options",
")",
".",
"then",
"(",
"currUser",
"=>",
"{",
"var",
"query",
"=",
"this",
".",
"query",
".",
"toJSON",
"(",
")",
";",
"query",
".",
"className",
"=",
"this",
".",
"query",
".",
"className",
";",
"var",
"data",
"=",
"{",
"}",
";",
"data",
".",
"query",
"=",
"query",
";",
"this",
".",
"data",
"=",
"this",
".",
"data",
"||",
"{",
"}",
";",
"this",
".",
"data",
".",
"source",
"=",
"this",
".",
"data",
".",
"source",
"||",
"currUser",
";",
"data",
".",
"data",
"=",
"this",
".",
"_getDataJSON",
"(",
")",
";",
"data",
".",
"inboxType",
"=",
"this",
".",
"inboxType",
"||",
"'default'",
";",
"return",
"AVRequest",
"(",
"'statuses'",
",",
"null",
",",
"null",
",",
"'POST'",
",",
"data",
",",
"options",
")",
";",
"}",
")",
".",
"then",
"(",
"response",
"=>",
"{",
"this",
".",
"id",
"=",
"response",
".",
"objectId",
";",
"this",
".",
"createdAt",
"=",
"AV",
".",
"_parseDate",
"(",
"response",
".",
"createdAt",
")",
";",
"return",
"this",
";",
"}",
")",
";",
"}"
] |
Send a status by a AV.Query object.
@since 0.3.0
@param {AuthOptions} options
@return {Promise} A promise that is fulfilled when the send
completes.
@example
// send a status to male users
var status = new AVStatus('image url', 'a message');
status.query = new AV.Query('_User');
status.query.equalTo('gender', 'male');
status.send().then(function(){
//send status successfully.
}, function(err){
//an error threw.
console.dir(err);
});
|
[
"Send",
"a",
"status",
"by",
"a",
"AV",
".",
"Query",
"object",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/status.js#L102-L128
|
|
14,047
|
leancloud/javascript-sdk
|
src/query.js
|
function(objectId, options) {
if (!objectId) {
var errorObject = new AVError(
AVError.OBJECT_NOT_FOUND,
'Object not found.'
);
throw errorObject;
}
var obj = this._newObject();
obj.id = objectId;
var queryJSON = this.toJSON();
var fetchOptions = {};
if (queryJSON.keys) fetchOptions.keys = queryJSON.keys;
if (queryJSON.include) fetchOptions.include = queryJSON.include;
if (queryJSON.includeACL)
fetchOptions.includeACL = queryJSON.includeACL;
return _request(
'classes',
this.className,
objectId,
'GET',
transformFetchOptions(fetchOptions),
options
).then(response => {
if (_.isEmpty(response))
throw new AVError(AVError.OBJECT_NOT_FOUND, 'Object not found.');
obj._finishFetch(obj.parse(response), true);
return obj;
});
}
|
javascript
|
function(objectId, options) {
if (!objectId) {
var errorObject = new AVError(
AVError.OBJECT_NOT_FOUND,
'Object not found.'
);
throw errorObject;
}
var obj = this._newObject();
obj.id = objectId;
var queryJSON = this.toJSON();
var fetchOptions = {};
if (queryJSON.keys) fetchOptions.keys = queryJSON.keys;
if (queryJSON.include) fetchOptions.include = queryJSON.include;
if (queryJSON.includeACL)
fetchOptions.includeACL = queryJSON.includeACL;
return _request(
'classes',
this.className,
objectId,
'GET',
transformFetchOptions(fetchOptions),
options
).then(response => {
if (_.isEmpty(response))
throw new AVError(AVError.OBJECT_NOT_FOUND, 'Object not found.');
obj._finishFetch(obj.parse(response), true);
return obj;
});
}
|
[
"function",
"(",
"objectId",
",",
"options",
")",
"{",
"if",
"(",
"!",
"objectId",
")",
"{",
"var",
"errorObject",
"=",
"new",
"AVError",
"(",
"AVError",
".",
"OBJECT_NOT_FOUND",
",",
"'Object not found.'",
")",
";",
"throw",
"errorObject",
";",
"}",
"var",
"obj",
"=",
"this",
".",
"_newObject",
"(",
")",
";",
"obj",
".",
"id",
"=",
"objectId",
";",
"var",
"queryJSON",
"=",
"this",
".",
"toJSON",
"(",
")",
";",
"var",
"fetchOptions",
"=",
"{",
"}",
";",
"if",
"(",
"queryJSON",
".",
"keys",
")",
"fetchOptions",
".",
"keys",
"=",
"queryJSON",
".",
"keys",
";",
"if",
"(",
"queryJSON",
".",
"include",
")",
"fetchOptions",
".",
"include",
"=",
"queryJSON",
".",
"include",
";",
"if",
"(",
"queryJSON",
".",
"includeACL",
")",
"fetchOptions",
".",
"includeACL",
"=",
"queryJSON",
".",
"includeACL",
";",
"return",
"_request",
"(",
"'classes'",
",",
"this",
".",
"className",
",",
"objectId",
",",
"'GET'",
",",
"transformFetchOptions",
"(",
"fetchOptions",
")",
",",
"options",
")",
".",
"then",
"(",
"response",
"=>",
"{",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"response",
")",
")",
"throw",
"new",
"AVError",
"(",
"AVError",
".",
"OBJECT_NOT_FOUND",
",",
"'Object not found.'",
")",
";",
"obj",
".",
"_finishFetch",
"(",
"obj",
".",
"parse",
"(",
"response",
")",
",",
"true",
")",
";",
"return",
"obj",
";",
"}",
")",
";",
"}"
] |
Constructs an AV.Object whose id is already known by fetching data from
the server.
@param {String} objectId The id of the object to be fetched.
@param {AuthOptions} options
@return {Promise.<AV.Object>}
|
[
"Constructs",
"an",
"AV",
".",
"Object",
"whose",
"id",
"is",
"already",
"known",
"by",
"fetching",
"data",
"from",
"the",
"server",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/query.js#L185-L218
|
|
14,048
|
leancloud/javascript-sdk
|
src/query.js
|
function() {
var params = {
where: this._where,
};
if (this._include.length > 0) {
params.include = this._include.join(',');
}
if (this._select.length > 0) {
params.keys = this._select.join(',');
}
if (this._includeACL !== undefined) {
params.returnACL = this._includeACL;
}
if (this._limit >= 0) {
params.limit = this._limit;
}
if (this._skip > 0) {
params.skip = this._skip;
}
if (this._order !== undefined) {
params.order = this._order;
}
AV._objectEach(this._extraOptions, function(v, k) {
params[k] = v;
});
return params;
}
|
javascript
|
function() {
var params = {
where: this._where,
};
if (this._include.length > 0) {
params.include = this._include.join(',');
}
if (this._select.length > 0) {
params.keys = this._select.join(',');
}
if (this._includeACL !== undefined) {
params.returnACL = this._includeACL;
}
if (this._limit >= 0) {
params.limit = this._limit;
}
if (this._skip > 0) {
params.skip = this._skip;
}
if (this._order !== undefined) {
params.order = this._order;
}
AV._objectEach(this._extraOptions, function(v, k) {
params[k] = v;
});
return params;
}
|
[
"function",
"(",
")",
"{",
"var",
"params",
"=",
"{",
"where",
":",
"this",
".",
"_where",
",",
"}",
";",
"if",
"(",
"this",
".",
"_include",
".",
"length",
">",
"0",
")",
"{",
"params",
".",
"include",
"=",
"this",
".",
"_include",
".",
"join",
"(",
"','",
")",
";",
"}",
"if",
"(",
"this",
".",
"_select",
".",
"length",
">",
"0",
")",
"{",
"params",
".",
"keys",
"=",
"this",
".",
"_select",
".",
"join",
"(",
"','",
")",
";",
"}",
"if",
"(",
"this",
".",
"_includeACL",
"!==",
"undefined",
")",
"{",
"params",
".",
"returnACL",
"=",
"this",
".",
"_includeACL",
";",
"}",
"if",
"(",
"this",
".",
"_limit",
">=",
"0",
")",
"{",
"params",
".",
"limit",
"=",
"this",
".",
"_limit",
";",
"}",
"if",
"(",
"this",
".",
"_skip",
">",
"0",
")",
"{",
"params",
".",
"skip",
"=",
"this",
".",
"_skip",
";",
"}",
"if",
"(",
"this",
".",
"_order",
"!==",
"undefined",
")",
"{",
"params",
".",
"order",
"=",
"this",
".",
"_order",
";",
"}",
"AV",
".",
"_objectEach",
"(",
"this",
".",
"_extraOptions",
",",
"function",
"(",
"v",
",",
"k",
")",
"{",
"params",
"[",
"k",
"]",
"=",
"v",
";",
"}",
")",
";",
"return",
"params",
";",
"}"
] |
Returns a JSON representation of this query.
@return {Object}
|
[
"Returns",
"a",
"JSON",
"representation",
"of",
"this",
"query",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/query.js#L224-L253
|
|
14,049
|
leancloud/javascript-sdk
|
src/query.js
|
function(options) {
var self = this;
return self.find(options).then(function(objects) {
return AV.Object.destroyAll(objects, options);
});
}
|
javascript
|
function(options) {
var self = this;
return self.find(options).then(function(objects) {
return AV.Object.destroyAll(objects, options);
});
}
|
[
"function",
"(",
"options",
")",
"{",
"var",
"self",
"=",
"this",
";",
"return",
"self",
".",
"find",
"(",
"options",
")",
".",
"then",
"(",
"function",
"(",
"objects",
")",
"{",
"return",
"AV",
".",
"Object",
".",
"destroyAll",
"(",
"objects",
",",
"options",
")",
";",
"}",
")",
";",
"}"
] |
Delete objects retrieved by this query.
@param {AuthOptions} options
@return {Promise} A promise that is fulfilled when the save
completes.
|
[
"Delete",
"objects",
"retrieved",
"by",
"this",
"query",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/query.js#L421-L426
|
|
14,050
|
leancloud/javascript-sdk
|
src/query.js
|
function(options) {
var params = this.toJSON();
params.limit = 0;
params.count = 1;
var request = this._createRequest(params, options);
return request.then(function(response) {
return response.count;
});
}
|
javascript
|
function(options) {
var params = this.toJSON();
params.limit = 0;
params.count = 1;
var request = this._createRequest(params, options);
return request.then(function(response) {
return response.count;
});
}
|
[
"function",
"(",
"options",
")",
"{",
"var",
"params",
"=",
"this",
".",
"toJSON",
"(",
")",
";",
"params",
".",
"limit",
"=",
"0",
";",
"params",
".",
"count",
"=",
"1",
";",
"var",
"request",
"=",
"this",
".",
"_createRequest",
"(",
"params",
",",
"options",
")",
";",
"return",
"request",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"return",
"response",
".",
"count",
";",
"}",
")",
";",
"}"
] |
Counts the number of objects that match this query.
@param {AuthOptions} options
@return {Promise} A promise that is resolved with the count when
the query completes.
|
[
"Counts",
"the",
"number",
"of",
"objects",
"that",
"match",
"this",
"query",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/query.js#L435-L444
|
|
14,051
|
leancloud/javascript-sdk
|
src/query.js
|
function(options) {
var self = this;
var params = this.toJSON();
params.limit = 1;
var request = this._createRequest(params, options);
return request.then(function(response) {
return _.map(response.results, function(json) {
var obj = self._newObject();
if (obj._finishFetch) {
obj._finishFetch(self._processResult(json), true);
}
return obj;
})[0];
});
}
|
javascript
|
function(options) {
var self = this;
var params = this.toJSON();
params.limit = 1;
var request = this._createRequest(params, options);
return request.then(function(response) {
return _.map(response.results, function(json) {
var obj = self._newObject();
if (obj._finishFetch) {
obj._finishFetch(self._processResult(json), true);
}
return obj;
})[0];
});
}
|
[
"function",
"(",
"options",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"params",
"=",
"this",
".",
"toJSON",
"(",
")",
";",
"params",
".",
"limit",
"=",
"1",
";",
"var",
"request",
"=",
"this",
".",
"_createRequest",
"(",
"params",
",",
"options",
")",
";",
"return",
"request",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"return",
"_",
".",
"map",
"(",
"response",
".",
"results",
",",
"function",
"(",
"json",
")",
"{",
"var",
"obj",
"=",
"self",
".",
"_newObject",
"(",
")",
";",
"if",
"(",
"obj",
".",
"_finishFetch",
")",
"{",
"obj",
".",
"_finishFetch",
"(",
"self",
".",
"_processResult",
"(",
"json",
")",
",",
"true",
")",
";",
"}",
"return",
"obj",
";",
"}",
")",
"[",
"0",
"]",
";",
"}",
")",
";",
"}"
] |
Retrieves at most one AV.Object that satisfies this query.
@param {AuthOptions} options
@return {Promise} A promise that is resolved with the object when
the query completes.
|
[
"Retrieves",
"at",
"most",
"one",
"AV",
".",
"Object",
"that",
"satisfies",
"this",
"query",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/query.js#L453-L469
|
|
14,052
|
leancloud/javascript-sdk
|
src/query.js
|
function(key, regex, modifiers) {
this._addCondition(key, '$regex', regex);
if (!modifiers) {
modifiers = '';
}
// Javascript regex options support mig as inline options but store them
// as properties of the object. We support mi & should migrate them to
// modifiers
if (regex.ignoreCase) {
modifiers += 'i';
}
if (regex.multiline) {
modifiers += 'm';
}
if (modifiers && modifiers.length) {
this._addCondition(key, '$options', modifiers);
}
return this;
}
|
javascript
|
function(key, regex, modifiers) {
this._addCondition(key, '$regex', regex);
if (!modifiers) {
modifiers = '';
}
// Javascript regex options support mig as inline options but store them
// as properties of the object. We support mi & should migrate them to
// modifiers
if (regex.ignoreCase) {
modifiers += 'i';
}
if (regex.multiline) {
modifiers += 'm';
}
if (modifiers && modifiers.length) {
this._addCondition(key, '$options', modifiers);
}
return this;
}
|
[
"function",
"(",
"key",
",",
"regex",
",",
"modifiers",
")",
"{",
"this",
".",
"_addCondition",
"(",
"key",
",",
"'$regex'",
",",
"regex",
")",
";",
"if",
"(",
"!",
"modifiers",
")",
"{",
"modifiers",
"=",
"''",
";",
"}",
"// Javascript regex options support mig as inline options but store them",
"// as properties of the object. We support mi & should migrate them to",
"// modifiers",
"if",
"(",
"regex",
".",
"ignoreCase",
")",
"{",
"modifiers",
"+=",
"'i'",
";",
"}",
"if",
"(",
"regex",
".",
"multiline",
")",
"{",
"modifiers",
"+=",
"'m'",
";",
"}",
"if",
"(",
"modifiers",
"&&",
"modifiers",
".",
"length",
")",
"{",
"this",
".",
"_addCondition",
"(",
"key",
",",
"'$options'",
",",
"modifiers",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Add a regular expression constraint for finding string values that match
the provided regular expression.
This may be slow for large datasets.
@param {String} key The key that the string to match is stored in.
@param {RegExp} regex The regular expression pattern to match.
@return {AV.Query} Returns the query, so you can chain this call.
|
[
"Add",
"a",
"regular",
"expression",
"constraint",
"for",
"finding",
"string",
"values",
"that",
"match",
"the",
"provided",
"regular",
"expression",
".",
"This",
"may",
"be",
"slow",
"for",
"large",
"datasets",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/query.js#L663-L682
|
|
14,053
|
leancloud/javascript-sdk
|
src/query.js
|
function(key, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
this._addCondition(key, '$inQuery', queryJSON);
return this;
}
|
javascript
|
function(key, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
this._addCondition(key, '$inQuery', queryJSON);
return this;
}
|
[
"function",
"(",
"key",
",",
"query",
")",
"{",
"var",
"queryJSON",
"=",
"query",
".",
"toJSON",
"(",
")",
";",
"queryJSON",
".",
"className",
"=",
"query",
".",
"className",
";",
"this",
".",
"_addCondition",
"(",
"key",
",",
"'$inQuery'",
",",
"queryJSON",
")",
";",
"return",
"this",
";",
"}"
] |
Add a constraint that requires that a key's value matches a AV.Query
constraint.
@param {String} key The key that the contains the object to match the
query.
@param {AV.Query} query The query that should match.
@return {AV.Query} Returns the query, so you can chain this call.
|
[
"Add",
"a",
"constraint",
"that",
"requires",
"that",
"a",
"key",
"s",
"value",
"matches",
"a",
"AV",
".",
"Query",
"constraint",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/query.js#L692-L697
|
|
14,054
|
leancloud/javascript-sdk
|
src/query.js
|
function(queries) {
var queryJSON = _.map(queries, function(q) {
return q.toJSON().where;
});
this._where.$and = queryJSON;
return this;
}
|
javascript
|
function(queries) {
var queryJSON = _.map(queries, function(q) {
return q.toJSON().where;
});
this._where.$and = queryJSON;
return this;
}
|
[
"function",
"(",
"queries",
")",
"{",
"var",
"queryJSON",
"=",
"_",
".",
"map",
"(",
"queries",
",",
"function",
"(",
"q",
")",
"{",
"return",
"q",
".",
"toJSON",
"(",
")",
".",
"where",
";",
"}",
")",
";",
"this",
".",
"_where",
".",
"$and",
"=",
"queryJSON",
";",
"return",
"this",
";",
"}"
] |
Add constraint that both of the passed in queries matches.
@param {Array} queries
@return {AV.Query} Returns the query, so you can chain this call.
@private
|
[
"Add",
"constraint",
"that",
"both",
"of",
"the",
"passed",
"in",
"queries",
"matches",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/query.js#L772-L779
|
|
14,055
|
leancloud/javascript-sdk
|
src/query.js
|
function(keys) {
requires(keys, 'undefined is not a valid key');
_(arguments).forEach(keys => {
this._include = this._include.concat(ensureArray(keys));
});
return this;
}
|
javascript
|
function(keys) {
requires(keys, 'undefined is not a valid key');
_(arguments).forEach(keys => {
this._include = this._include.concat(ensureArray(keys));
});
return this;
}
|
[
"function",
"(",
"keys",
")",
"{",
"requires",
"(",
"keys",
",",
"'undefined is not a valid key'",
")",
";",
"_",
"(",
"arguments",
")",
".",
"forEach",
"(",
"keys",
"=>",
"{",
"this",
".",
"_include",
"=",
"this",
".",
"_include",
".",
"concat",
"(",
"ensureArray",
"(",
"keys",
")",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] |
Include nested AV.Objects for the provided key. You can use dot
notation to specify which fields in the included object are also fetch.
@param {String[]} keys The name of the key to include.
@return {AV.Query} Returns the query, so you can chain this call.
|
[
"Include",
"nested",
"AV",
".",
"Objects",
"for",
"the",
"provided",
"key",
".",
"You",
"can",
"use",
"dot",
"notation",
"to",
"specify",
"which",
"fields",
"in",
"the",
"included",
"object",
"are",
"also",
"fetch",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/query.js#L966-L972
|
|
14,056
|
leancloud/javascript-sdk
|
src/query.js
|
function(keys) {
requires(keys, 'undefined is not a valid key');
_(arguments).forEach(keys => {
this._select = this._select.concat(ensureArray(keys));
});
return this;
}
|
javascript
|
function(keys) {
requires(keys, 'undefined is not a valid key');
_(arguments).forEach(keys => {
this._select = this._select.concat(ensureArray(keys));
});
return this;
}
|
[
"function",
"(",
"keys",
")",
"{",
"requires",
"(",
"keys",
",",
"'undefined is not a valid key'",
")",
";",
"_",
"(",
"arguments",
")",
".",
"forEach",
"(",
"keys",
"=>",
"{",
"this",
".",
"_select",
"=",
"this",
".",
"_select",
".",
"concat",
"(",
"ensureArray",
"(",
"keys",
")",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] |
Restrict the fields of the returned AV.Objects to include only the
provided keys. If this is called multiple times, then all of the keys
specified in each of the calls will be included.
@param {String[]} keys The names of the keys to include.
@return {AV.Query} Returns the query, so you can chain this call.
|
[
"Restrict",
"the",
"fields",
"of",
"the",
"returned",
"AV",
".",
"Objects",
"to",
"include",
"only",
"the",
"provided",
"keys",
".",
"If",
"this",
"is",
"called",
"multiple",
"times",
"then",
"all",
"of",
"the",
"keys",
"specified",
"in",
"each",
"of",
"the",
"calls",
"will",
"be",
"included",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/query.js#L991-L997
|
|
14,057
|
leancloud/javascript-sdk
|
src/search.js
|
function() {
var self = this;
var request = this._createRequest();
return request.then(function(response) {
//update sid for next querying.
if (response.sid) {
self._oldSid = self._sid;
self._sid = response.sid;
} else {
self._sid = null;
self._hitEnd = true;
}
self._hits = response.hits || 0;
return _.map(response.results, function(json) {
if (json.className) {
response.className = json.className;
}
var obj = self._newObject(response);
obj.appURL = json['_app_url'];
obj._finishFetch(self._processResult(json), true);
return obj;
});
});
}
|
javascript
|
function() {
var self = this;
var request = this._createRequest();
return request.then(function(response) {
//update sid for next querying.
if (response.sid) {
self._oldSid = self._sid;
self._sid = response.sid;
} else {
self._sid = null;
self._hitEnd = true;
}
self._hits = response.hits || 0;
return _.map(response.results, function(json) {
if (json.className) {
response.className = json.className;
}
var obj = self._newObject(response);
obj.appURL = json['_app_url'];
obj._finishFetch(self._processResult(json), true);
return obj;
});
});
}
|
[
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"request",
"=",
"this",
".",
"_createRequest",
"(",
")",
";",
"return",
"request",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"//update sid for next querying.",
"if",
"(",
"response",
".",
"sid",
")",
"{",
"self",
".",
"_oldSid",
"=",
"self",
".",
"_sid",
";",
"self",
".",
"_sid",
"=",
"response",
".",
"sid",
";",
"}",
"else",
"{",
"self",
".",
"_sid",
"=",
"null",
";",
"self",
".",
"_hitEnd",
"=",
"true",
";",
"}",
"self",
".",
"_hits",
"=",
"response",
".",
"hits",
"||",
"0",
";",
"return",
"_",
".",
"map",
"(",
"response",
".",
"results",
",",
"function",
"(",
"json",
")",
"{",
"if",
"(",
"json",
".",
"className",
")",
"{",
"response",
".",
"className",
"=",
"json",
".",
"className",
";",
"}",
"var",
"obj",
"=",
"self",
".",
"_newObject",
"(",
"response",
")",
";",
"obj",
".",
"appURL",
"=",
"json",
"[",
"'_app_url'",
"]",
";",
"obj",
".",
"_finishFetch",
"(",
"self",
".",
"_processResult",
"(",
"json",
")",
",",
"true",
")",
";",
"return",
"obj",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Retrieves a list of AVObjects that satisfy this query.
Either options.success or options.error is called when the find
completes.
@see AV.Query#find
@return {Promise} A promise that is resolved with the results when
the query completes.
|
[
"Retrieves",
"a",
"list",
"of",
"AVObjects",
"that",
"satisfy",
"this",
"query",
".",
"Either",
"options",
".",
"success",
"or",
"options",
".",
"error",
"is",
"called",
"when",
"the",
"find",
"completes",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/search.js#L232-L258
|
|
14,058
|
leancloud/javascript-sdk
|
src/event.js
|
function(events, callback, context) {
var calls, event, node, tail, list;
if (!callback) {
return this;
}
events = events.split(eventSplitter);
calls = this._callbacks || (this._callbacks = {});
// Create an immutable callback list, allowing traversal during
// modification. The tail is an empty object that will always be used
// as the next node.
event = events.shift();
while (event) {
list = calls[event];
node = list ? list.tail : {};
node.next = tail = {};
node.context = context;
node.callback = callback;
calls[event] = { tail: tail, next: list ? list.next : node };
event = events.shift();
}
return this;
}
|
javascript
|
function(events, callback, context) {
var calls, event, node, tail, list;
if (!callback) {
return this;
}
events = events.split(eventSplitter);
calls = this._callbacks || (this._callbacks = {});
// Create an immutable callback list, allowing traversal during
// modification. The tail is an empty object that will always be used
// as the next node.
event = events.shift();
while (event) {
list = calls[event];
node = list ? list.tail : {};
node.next = tail = {};
node.context = context;
node.callback = callback;
calls[event] = { tail: tail, next: list ? list.next : node };
event = events.shift();
}
return this;
}
|
[
"function",
"(",
"events",
",",
"callback",
",",
"context",
")",
"{",
"var",
"calls",
",",
"event",
",",
"node",
",",
"tail",
",",
"list",
";",
"if",
"(",
"!",
"callback",
")",
"{",
"return",
"this",
";",
"}",
"events",
"=",
"events",
".",
"split",
"(",
"eventSplitter",
")",
";",
"calls",
"=",
"this",
".",
"_callbacks",
"||",
"(",
"this",
".",
"_callbacks",
"=",
"{",
"}",
")",
";",
"// Create an immutable callback list, allowing traversal during",
"// modification. The tail is an empty object that will always be used",
"// as the next node.",
"event",
"=",
"events",
".",
"shift",
"(",
")",
";",
"while",
"(",
"event",
")",
"{",
"list",
"=",
"calls",
"[",
"event",
"]",
";",
"node",
"=",
"list",
"?",
"list",
".",
"tail",
":",
"{",
"}",
";",
"node",
".",
"next",
"=",
"tail",
"=",
"{",
"}",
";",
"node",
".",
"context",
"=",
"context",
";",
"node",
".",
"callback",
"=",
"callback",
";",
"calls",
"[",
"event",
"]",
"=",
"{",
"tail",
":",
"tail",
",",
"next",
":",
"list",
"?",
"list",
".",
"next",
":",
"node",
"}",
";",
"event",
"=",
"events",
".",
"shift",
"(",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Bind one or more space separated events, `events`, to a `callback`
function. Passing `"all"` will bind the callback to all events fired.
|
[
"Bind",
"one",
"or",
"more",
"space",
"separated",
"events",
"events",
"to",
"a",
"callback",
"function",
".",
"Passing",
"all",
"will",
"bind",
"the",
"callback",
"to",
"all",
"events",
"fired",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/event.js#L32-L55
|
|
14,059
|
leancloud/javascript-sdk
|
src/object.js
|
getValue
|
function getValue(object, prop) {
if (!(object && object[prop])) {
return null;
}
return _.isFunction(object[prop]) ? object[prop]() : object[prop];
}
|
javascript
|
function getValue(object, prop) {
if (!(object && object[prop])) {
return null;
}
return _.isFunction(object[prop]) ? object[prop]() : object[prop];
}
|
[
"function",
"getValue",
"(",
"object",
",",
"prop",
")",
"{",
"if",
"(",
"!",
"(",
"object",
"&&",
"object",
"[",
"prop",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"_",
".",
"isFunction",
"(",
"object",
"[",
"prop",
"]",
")",
"?",
"object",
"[",
"prop",
"]",
"(",
")",
":",
"object",
"[",
"prop",
"]",
";",
"}"
] |
Helper function to get a value from a Backbone object as a property or as a function.
|
[
"Helper",
"function",
"to",
"get",
"a",
"value",
"from",
"a",
"Backbone",
"object",
"as",
"a",
"property",
"or",
"as",
"a",
"function",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/object.js#L40-L45
|
14,060
|
leancloud/javascript-sdk
|
src/object.js
|
function(serverData) {
// Grab a copy of any object referenced by this object. These instances
// may have already been fetched, and we don't want to lose their data.
// Note that doing it like this means we will unify separate copies of the
// same object, but that's a risk we have to take.
var fetchedObjects = {};
AV._traverse(this.attributes, function(object) {
if (object instanceof AV.Object && object.id && object._hasData) {
fetchedObjects[object.id] = object;
}
});
var savedChanges = _.first(this._opSetQueue);
this._opSetQueue = _.rest(this._opSetQueue);
this._applyOpSet(savedChanges, this._serverData);
this._mergeMagicFields(serverData);
var self = this;
AV._objectEach(serverData, function(value, key) {
self._serverData[key] = AV._decode(value, key);
// Look for any objects that might have become unfetched and fix them
// by replacing their values with the previously observed values.
var fetched = AV._traverse(self._serverData[key], function(object) {
if (object instanceof AV.Object && fetchedObjects[object.id]) {
return fetchedObjects[object.id];
}
});
if (fetched) {
self._serverData[key] = fetched;
}
});
this._rebuildAllEstimatedData();
const opSetQueue = this._opSetQueue.map(_.clone);
this._refreshCache();
this._opSetQueue = opSetQueue;
this._saving = this._saving - 1;
}
|
javascript
|
function(serverData) {
// Grab a copy of any object referenced by this object. These instances
// may have already been fetched, and we don't want to lose their data.
// Note that doing it like this means we will unify separate copies of the
// same object, but that's a risk we have to take.
var fetchedObjects = {};
AV._traverse(this.attributes, function(object) {
if (object instanceof AV.Object && object.id && object._hasData) {
fetchedObjects[object.id] = object;
}
});
var savedChanges = _.first(this._opSetQueue);
this._opSetQueue = _.rest(this._opSetQueue);
this._applyOpSet(savedChanges, this._serverData);
this._mergeMagicFields(serverData);
var self = this;
AV._objectEach(serverData, function(value, key) {
self._serverData[key] = AV._decode(value, key);
// Look for any objects that might have become unfetched and fix them
// by replacing their values with the previously observed values.
var fetched = AV._traverse(self._serverData[key], function(object) {
if (object instanceof AV.Object && fetchedObjects[object.id]) {
return fetchedObjects[object.id];
}
});
if (fetched) {
self._serverData[key] = fetched;
}
});
this._rebuildAllEstimatedData();
const opSetQueue = this._opSetQueue.map(_.clone);
this._refreshCache();
this._opSetQueue = opSetQueue;
this._saving = this._saving - 1;
}
|
[
"function",
"(",
"serverData",
")",
"{",
"// Grab a copy of any object referenced by this object. These instances",
"// may have already been fetched, and we don't want to lose their data.",
"// Note that doing it like this means we will unify separate copies of the",
"// same object, but that's a risk we have to take.",
"var",
"fetchedObjects",
"=",
"{",
"}",
";",
"AV",
".",
"_traverse",
"(",
"this",
".",
"attributes",
",",
"function",
"(",
"object",
")",
"{",
"if",
"(",
"object",
"instanceof",
"AV",
".",
"Object",
"&&",
"object",
".",
"id",
"&&",
"object",
".",
"_hasData",
")",
"{",
"fetchedObjects",
"[",
"object",
".",
"id",
"]",
"=",
"object",
";",
"}",
"}",
")",
";",
"var",
"savedChanges",
"=",
"_",
".",
"first",
"(",
"this",
".",
"_opSetQueue",
")",
";",
"this",
".",
"_opSetQueue",
"=",
"_",
".",
"rest",
"(",
"this",
".",
"_opSetQueue",
")",
";",
"this",
".",
"_applyOpSet",
"(",
"savedChanges",
",",
"this",
".",
"_serverData",
")",
";",
"this",
".",
"_mergeMagicFields",
"(",
"serverData",
")",
";",
"var",
"self",
"=",
"this",
";",
"AV",
".",
"_objectEach",
"(",
"serverData",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"self",
".",
"_serverData",
"[",
"key",
"]",
"=",
"AV",
".",
"_decode",
"(",
"value",
",",
"key",
")",
";",
"// Look for any objects that might have become unfetched and fix them",
"// by replacing their values with the previously observed values.",
"var",
"fetched",
"=",
"AV",
".",
"_traverse",
"(",
"self",
".",
"_serverData",
"[",
"key",
"]",
",",
"function",
"(",
"object",
")",
"{",
"if",
"(",
"object",
"instanceof",
"AV",
".",
"Object",
"&&",
"fetchedObjects",
"[",
"object",
".",
"id",
"]",
")",
"{",
"return",
"fetchedObjects",
"[",
"object",
".",
"id",
"]",
";",
"}",
"}",
")",
";",
"if",
"(",
"fetched",
")",
"{",
"self",
".",
"_serverData",
"[",
"key",
"]",
"=",
"fetched",
";",
"}",
"}",
")",
";",
"this",
".",
"_rebuildAllEstimatedData",
"(",
")",
";",
"const",
"opSetQueue",
"=",
"this",
".",
"_opSetQueue",
".",
"map",
"(",
"_",
".",
"clone",
")",
";",
"this",
".",
"_refreshCache",
"(",
")",
";",
"this",
".",
"_opSetQueue",
"=",
"opSetQueue",
";",
"this",
".",
"_saving",
"=",
"this",
".",
"_saving",
"-",
"1",
";",
"}"
] |
Called when a save completes successfully. This merges the changes that
were saved into the known server data, and overrides it with any data
sent directly from the server.
@private
|
[
"Called",
"when",
"a",
"save",
"completes",
"successfully",
".",
"This",
"merges",
"the",
"changes",
"that",
"were",
"saved",
"into",
"the",
"known",
"server",
"data",
"and",
"overrides",
"it",
"with",
"any",
"data",
"sent",
"directly",
"from",
"the",
"server",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/object.js#L486-L522
|
|
14,061
|
leancloud/javascript-sdk
|
src/object.js
|
function(serverData, hasData) {
// Clear out any changes the user might have made previously.
this._opSetQueue = [{}];
// Bring in all the new server data.
this._mergeMagicFields(serverData);
var self = this;
AV._objectEach(serverData, function(value, key) {
self._serverData[key] = AV._decode(value, key);
});
// Refresh the attributes.
this._rebuildAllEstimatedData();
// Clear out the cache of mutable containers.
this._refreshCache();
this._opSetQueue = [{}];
this._hasData = hasData;
}
|
javascript
|
function(serverData, hasData) {
// Clear out any changes the user might have made previously.
this._opSetQueue = [{}];
// Bring in all the new server data.
this._mergeMagicFields(serverData);
var self = this;
AV._objectEach(serverData, function(value, key) {
self._serverData[key] = AV._decode(value, key);
});
// Refresh the attributes.
this._rebuildAllEstimatedData();
// Clear out the cache of mutable containers.
this._refreshCache();
this._opSetQueue = [{}];
this._hasData = hasData;
}
|
[
"function",
"(",
"serverData",
",",
"hasData",
")",
"{",
"// Clear out any changes the user might have made previously.",
"this",
".",
"_opSetQueue",
"=",
"[",
"{",
"}",
"]",
";",
"// Bring in all the new server data.",
"this",
".",
"_mergeMagicFields",
"(",
"serverData",
")",
";",
"var",
"self",
"=",
"this",
";",
"AV",
".",
"_objectEach",
"(",
"serverData",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"self",
".",
"_serverData",
"[",
"key",
"]",
"=",
"AV",
".",
"_decode",
"(",
"value",
",",
"key",
")",
";",
"}",
")",
";",
"// Refresh the attributes.",
"this",
".",
"_rebuildAllEstimatedData",
"(",
")",
";",
"// Clear out the cache of mutable containers.",
"this",
".",
"_refreshCache",
"(",
")",
";",
"this",
".",
"_opSetQueue",
"=",
"[",
"{",
"}",
"]",
";",
"this",
".",
"_hasData",
"=",
"hasData",
";",
"}"
] |
Called when a fetch or login is complete to set the known server data to
the given object.
@private
|
[
"Called",
"when",
"a",
"fetch",
"or",
"login",
"is",
"complete",
"to",
"set",
"the",
"known",
"server",
"data",
"to",
"the",
"given",
"object",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/object.js#L529-L548
|
|
14,062
|
leancloud/javascript-sdk
|
src/object.js
|
function(opSet, target) {
var self = this;
AV._objectEach(opSet, function(change, key) {
const [value, actualTarget, actualKey] = findValue(target, key);
setValue(target, key, change._estimate(value, self, key));
if (actualTarget && actualTarget[actualKey] === AV.Op._UNSET) {
delete actualTarget[actualKey];
}
});
}
|
javascript
|
function(opSet, target) {
var self = this;
AV._objectEach(opSet, function(change, key) {
const [value, actualTarget, actualKey] = findValue(target, key);
setValue(target, key, change._estimate(value, self, key));
if (actualTarget && actualTarget[actualKey] === AV.Op._UNSET) {
delete actualTarget[actualKey];
}
});
}
|
[
"function",
"(",
"opSet",
",",
"target",
")",
"{",
"var",
"self",
"=",
"this",
";",
"AV",
".",
"_objectEach",
"(",
"opSet",
",",
"function",
"(",
"change",
",",
"key",
")",
"{",
"const",
"[",
"value",
",",
"actualTarget",
",",
"actualKey",
"]",
"=",
"findValue",
"(",
"target",
",",
"key",
")",
";",
"setValue",
"(",
"target",
",",
"key",
",",
"change",
".",
"_estimate",
"(",
"value",
",",
"self",
",",
"key",
")",
")",
";",
"if",
"(",
"actualTarget",
"&&",
"actualTarget",
"[",
"actualKey",
"]",
"===",
"AV",
".",
"Op",
".",
"_UNSET",
")",
"{",
"delete",
"actualTarget",
"[",
"actualKey",
"]",
";",
"}",
"}",
")",
";",
"}"
] |
Applies the set of AV.Op in opSet to the object target.
@private
|
[
"Applies",
"the",
"set",
"of",
"AV",
".",
"Op",
"in",
"opSet",
"to",
"the",
"object",
"target",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/object.js#L554-L563
|
|
14,063
|
leancloud/javascript-sdk
|
src/object.js
|
function(value, attr) {
if (!self._pending[attr] && !self._silent[attr]) {
delete self.changed[attr];
}
}
|
javascript
|
function(value, attr) {
if (!self._pending[attr] && !self._silent[attr]) {
delete self.changed[attr];
}
}
|
[
"function",
"(",
"value",
",",
"attr",
")",
"{",
"if",
"(",
"!",
"self",
".",
"_pending",
"[",
"attr",
"]",
"&&",
"!",
"self",
".",
"_silent",
"[",
"attr",
"]",
")",
"{",
"delete",
"self",
".",
"changed",
"[",
"attr",
"]",
";",
"}",
"}"
] |
This is to get around lint not letting us make a function in a loop.
|
[
"This",
"is",
"to",
"get",
"around",
"lint",
"not",
"letting",
"us",
"make",
"a",
"function",
"in",
"a",
"loop",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/object.js#L1203-L1207
|
|
14,064
|
leancloud/javascript-sdk
|
src/user.js
|
function(attrs) {
if (attrs.sessionToken) {
this._sessionToken = attrs.sessionToken;
delete attrs.sessionToken;
}
return AV.User.__super__._mergeMagicFields.call(this, attrs);
}
|
javascript
|
function(attrs) {
if (attrs.sessionToken) {
this._sessionToken = attrs.sessionToken;
delete attrs.sessionToken;
}
return AV.User.__super__._mergeMagicFields.call(this, attrs);
}
|
[
"function",
"(",
"attrs",
")",
"{",
"if",
"(",
"attrs",
".",
"sessionToken",
")",
"{",
"this",
".",
"_sessionToken",
"=",
"attrs",
".",
"sessionToken",
";",
"delete",
"attrs",
".",
"sessionToken",
";",
"}",
"return",
"AV",
".",
"User",
".",
"__super__",
".",
"_mergeMagicFields",
".",
"call",
"(",
"this",
",",
"attrs",
")",
";",
"}"
] |
Instance Methods
Internal method to handle special fields in a _User response.
@private
|
[
"Instance",
"Methods",
"Internal",
"method",
"to",
"handle",
"special",
"fields",
"in",
"a",
"_User",
"response",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/user.js#L79-L85
|
|
14,065
|
leancloud/javascript-sdk
|
src/user.js
|
function(provider) {
var authType;
if (_.isString(provider)) {
authType = provider;
} else {
authType = provider.getAuthType();
}
var authData = this.get('authData') || {};
return !!authData[authType];
}
|
javascript
|
function(provider) {
var authType;
if (_.isString(provider)) {
authType = provider;
} else {
authType = provider.getAuthType();
}
var authData = this.get('authData') || {};
return !!authData[authType];
}
|
[
"function",
"(",
"provider",
")",
"{",
"var",
"authType",
";",
"if",
"(",
"_",
".",
"isString",
"(",
"provider",
")",
")",
"{",
"authType",
"=",
"provider",
";",
"}",
"else",
"{",
"authType",
"=",
"provider",
".",
"getAuthType",
"(",
")",
";",
"}",
"var",
"authData",
"=",
"this",
".",
"get",
"(",
"'authData'",
")",
"||",
"{",
"}",
";",
"return",
"!",
"!",
"authData",
"[",
"authType",
"]",
";",
"}"
] |
Checks whether a user is linked to a service.
@private
|
[
"Checks",
"whether",
"a",
"user",
"is",
"linked",
"to",
"a",
"service",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/user.js#L336-L345
|
|
14,066
|
leancloud/javascript-sdk
|
src/user.js
|
function(options, authOptions) {
if (!this.id) {
throw new Error('Please signin.');
}
let user;
let attributes;
if (options.user) {
user = options.user;
attributes = options.attributes;
} else {
user = options;
}
var userObjectId = _.isString(user) ? user : user.id;
if (!userObjectId) {
throw new Error('Invalid target user.');
}
var route = 'users/' + this.id + '/friendship/' + userObjectId;
var request = AVRequest(
route,
null,
null,
'POST',
AV._encode(attributes),
authOptions
);
return request;
}
|
javascript
|
function(options, authOptions) {
if (!this.id) {
throw new Error('Please signin.');
}
let user;
let attributes;
if (options.user) {
user = options.user;
attributes = options.attributes;
} else {
user = options;
}
var userObjectId = _.isString(user) ? user : user.id;
if (!userObjectId) {
throw new Error('Invalid target user.');
}
var route = 'users/' + this.id + '/friendship/' + userObjectId;
var request = AVRequest(
route,
null,
null,
'POST',
AV._encode(attributes),
authOptions
);
return request;
}
|
[
"function",
"(",
"options",
",",
"authOptions",
")",
"{",
"if",
"(",
"!",
"this",
".",
"id",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Please signin.'",
")",
";",
"}",
"let",
"user",
";",
"let",
"attributes",
";",
"if",
"(",
"options",
".",
"user",
")",
"{",
"user",
"=",
"options",
".",
"user",
";",
"attributes",
"=",
"options",
".",
"attributes",
";",
"}",
"else",
"{",
"user",
"=",
"options",
";",
"}",
"var",
"userObjectId",
"=",
"_",
".",
"isString",
"(",
"user",
")",
"?",
"user",
":",
"user",
".",
"id",
";",
"if",
"(",
"!",
"userObjectId",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid target user.'",
")",
";",
"}",
"var",
"route",
"=",
"'users/'",
"+",
"this",
".",
"id",
"+",
"'/friendship/'",
"+",
"userObjectId",
";",
"var",
"request",
"=",
"AVRequest",
"(",
"route",
",",
"null",
",",
"null",
",",
"'POST'",
",",
"AV",
".",
"_encode",
"(",
"attributes",
")",
",",
"authOptions",
")",
";",
"return",
"request",
";",
"}"
] |
Follow a user
@since 0.3.0
@param {Object | AV.User | String} options if an AV.User or string is given, it will be used as the target user.
@param {AV.User | String} options.user The target user or user's objectId to follow.
@param {Object} [options.attributes] key-value attributes dictionary to be used as
conditions of followerQuery/followeeQuery.
@param {AuthOptions} [authOptions]
|
[
"Follow",
"a",
"user"
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/user.js#L605-L631
|
|
14,067
|
leancloud/javascript-sdk
|
src/user.js
|
function(oldPassword, newPassword, options) {
var route = 'users/' + this.id + '/updatePassword';
var params = {
old_password: oldPassword,
new_password: newPassword,
};
var request = AVRequest(route, null, null, 'PUT', params, options);
return request;
}
|
javascript
|
function(oldPassword, newPassword, options) {
var route = 'users/' + this.id + '/updatePassword';
var params = {
old_password: oldPassword,
new_password: newPassword,
};
var request = AVRequest(route, null, null, 'PUT', params, options);
return request;
}
|
[
"function",
"(",
"oldPassword",
",",
"newPassword",
",",
"options",
")",
"{",
"var",
"route",
"=",
"'users/'",
"+",
"this",
".",
"id",
"+",
"'/updatePassword'",
";",
"var",
"params",
"=",
"{",
"old_password",
":",
"oldPassword",
",",
"new_password",
":",
"newPassword",
",",
"}",
";",
"var",
"request",
"=",
"AVRequest",
"(",
"route",
",",
"null",
",",
"null",
",",
"'PUT'",
",",
"params",
",",
"options",
")",
";",
"return",
"request",
";",
"}"
] |
Update user's new password safely based on old password.
@param {String} oldPassword the old password.
@param {String} newPassword the new password.
@param {AuthOptions} options
|
[
"Update",
"user",
"s",
"new",
"password",
"safely",
"based",
"on",
"old",
"password",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/user.js#L696-L704
|
|
14,068
|
leancloud/javascript-sdk
|
src/user.js
|
function(userObjectId) {
if (!userObjectId || !_.isString(userObjectId)) {
throw new Error('Invalid user object id.');
}
var query = new AV.FriendShipQuery('_Follower');
query._friendshipTag = 'follower';
query.equalTo(
'user',
AV.Object.createWithoutData('_User', userObjectId)
);
return query;
}
|
javascript
|
function(userObjectId) {
if (!userObjectId || !_.isString(userObjectId)) {
throw new Error('Invalid user object id.');
}
var query = new AV.FriendShipQuery('_Follower');
query._friendshipTag = 'follower';
query.equalTo(
'user',
AV.Object.createWithoutData('_User', userObjectId)
);
return query;
}
|
[
"function",
"(",
"userObjectId",
")",
"{",
"if",
"(",
"!",
"userObjectId",
"||",
"!",
"_",
".",
"isString",
"(",
"userObjectId",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid user object id.'",
")",
";",
"}",
"var",
"query",
"=",
"new",
"AV",
".",
"FriendShipQuery",
"(",
"'_Follower'",
")",
";",
"query",
".",
"_friendshipTag",
"=",
"'follower'",
";",
"query",
".",
"equalTo",
"(",
"'user'",
",",
"AV",
".",
"Object",
".",
"createWithoutData",
"(",
"'_User'",
",",
"userObjectId",
")",
")",
";",
"return",
"query",
";",
"}"
] |
Create a follower query for special user to query the user's followers.
@param {String} userObjectId The user object id.
@return {AV.FriendShipQuery}
@since 0.3.0
|
[
"Create",
"a",
"follower",
"query",
"for",
"special",
"user",
"to",
"query",
"the",
"user",
"s",
"followers",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/user.js#L1210-L1221
|
|
14,069
|
leancloud/javascript-sdk
|
src/user.js
|
function(email) {
var json = { email: email };
var request = AVRequest(
'requestPasswordReset',
null,
null,
'POST',
json
);
return request;
}
|
javascript
|
function(email) {
var json = { email: email };
var request = AVRequest(
'requestPasswordReset',
null,
null,
'POST',
json
);
return request;
}
|
[
"function",
"(",
"email",
")",
"{",
"var",
"json",
"=",
"{",
"email",
":",
"email",
"}",
";",
"var",
"request",
"=",
"AVRequest",
"(",
"'requestPasswordReset'",
",",
"null",
",",
"null",
",",
"'POST'",
",",
"json",
")",
";",
"return",
"request",
";",
"}"
] |
Requests a password reset email to be sent to the specified email address
associated with the user account. This email allows the user to securely
reset their password on the AV site.
@param {String} email The email address associated with the user that
forgot their password.
@return {Promise}
|
[
"Requests",
"a",
"password",
"reset",
"email",
"to",
"be",
"sent",
"to",
"the",
"specified",
"email",
"address",
"associated",
"with",
"the",
"user",
"account",
".",
"This",
"email",
"allows",
"the",
"user",
"to",
"securely",
"reset",
"their",
"password",
"on",
"the",
"AV",
"site",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/user.js#L1251-L1261
|
|
14,070
|
leancloud/javascript-sdk
|
src/user.js
|
function(code, password) {
var json = { password: password };
var request = AVRequest(
'resetPasswordBySmsCode',
null,
code,
'PUT',
json
);
return request;
}
|
javascript
|
function(code, password) {
var json = { password: password };
var request = AVRequest(
'resetPasswordBySmsCode',
null,
code,
'PUT',
json
);
return request;
}
|
[
"function",
"(",
"code",
",",
"password",
")",
"{",
"var",
"json",
"=",
"{",
"password",
":",
"password",
"}",
";",
"var",
"request",
"=",
"AVRequest",
"(",
"'resetPasswordBySmsCode'",
",",
"null",
",",
"code",
",",
"'PUT'",
",",
"json",
")",
";",
"return",
"request",
";",
"}"
] |
Makes a call to reset user's account password by sms code and new password.
The sms code is sent by AV.User.requestPasswordResetBySmsCode.
@param {String} code The sms code sent by AV.User.Cloud.requestSmsCode
@param {String} password The new password.
@return {Promise} A promise that will be resolved with the result
of the function.
|
[
"Makes",
"a",
"call",
"to",
"reset",
"user",
"s",
"account",
"password",
"by",
"sms",
"code",
"and",
"new",
"password",
".",
"The",
"sms",
"code",
"is",
"sent",
"by",
"AV",
".",
"User",
".",
"requestPasswordResetBySmsCode",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/user.js#L1344-L1354
|
|
14,071
|
leancloud/javascript-sdk
|
src/user.js
|
function(mobilePhoneNumber, options = {}) {
const data = {
mobilePhoneNumber,
};
if (options.validateToken) {
data.validate_token = options.validateToken;
}
var request = AVRequest(
'requestLoginSmsCode',
null,
null,
'POST',
data,
options
);
return request;
}
|
javascript
|
function(mobilePhoneNumber, options = {}) {
const data = {
mobilePhoneNumber,
};
if (options.validateToken) {
data.validate_token = options.validateToken;
}
var request = AVRequest(
'requestLoginSmsCode',
null,
null,
'POST',
data,
options
);
return request;
}
|
[
"function",
"(",
"mobilePhoneNumber",
",",
"options",
"=",
"{",
"}",
")",
"{",
"const",
"data",
"=",
"{",
"mobilePhoneNumber",
",",
"}",
";",
"if",
"(",
"options",
".",
"validateToken",
")",
"{",
"data",
".",
"validate_token",
"=",
"options",
".",
"validateToken",
";",
"}",
"var",
"request",
"=",
"AVRequest",
"(",
"'requestLoginSmsCode'",
",",
"null",
",",
"null",
",",
"'POST'",
",",
"data",
",",
"options",
")",
";",
"return",
"request",
";",
"}"
] |
Requests a logIn sms code to be sent to the specified mobile phone
number associated with the user account. This sms code allows the user to
login by AV.User.logInWithMobilePhoneSmsCode function.
@param {String} mobilePhoneNumber The mobile phone number associated with the
user that want to login by AV.User.logInWithMobilePhoneSmsCode
@param {AuthOptions} [options] AuthOptions plus:
@param {String} [options.validateToken] a validate token returned by {@link AV.Cloud.verifyCaptcha}
@return {Promise}
|
[
"Requests",
"a",
"logIn",
"sms",
"code",
"to",
"be",
"sent",
"to",
"the",
"specified",
"mobile",
"phone",
"number",
"associated",
"with",
"the",
"user",
"account",
".",
"This",
"sms",
"code",
"allows",
"the",
"user",
"to",
"login",
"by",
"AV",
".",
"User",
".",
"logInWithMobilePhoneSmsCode",
"function",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/user.js#L1379-L1395
|
|
14,072
|
leancloud/javascript-sdk
|
src/user.js
|
function() {
if (AV._config.disableCurrentUser) {
console.warn(
'AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'
);
return Promise.resolve(null);
}
if (AV.User._currentUser) {
return Promise.resolve(AV.User._currentUser);
}
if (AV.User._currentUserMatchesDisk) {
return Promise.resolve(AV.User._currentUser);
}
return AV.localStorage
.getItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY))
.then(function(userData) {
if (!userData) {
return null;
}
// Load the user from local storage.
AV.User._currentUserMatchesDisk = true;
AV.User._currentUser = AV.Object._create('_User');
AV.User._currentUser._isCurrentUser = true;
var json = JSON.parse(userData);
AV.User._currentUser.id = json._id;
delete json._id;
AV.User._currentUser._sessionToken = json._sessionToken;
delete json._sessionToken;
AV.User._currentUser._finishFetch(json);
//AV.User._currentUser.set(json);
AV.User._currentUser._synchronizeAllAuthData();
AV.User._currentUser._refreshCache();
AV.User._currentUser._opSetQueue = [{}];
return AV.User._currentUser;
});
}
|
javascript
|
function() {
if (AV._config.disableCurrentUser) {
console.warn(
'AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'
);
return Promise.resolve(null);
}
if (AV.User._currentUser) {
return Promise.resolve(AV.User._currentUser);
}
if (AV.User._currentUserMatchesDisk) {
return Promise.resolve(AV.User._currentUser);
}
return AV.localStorage
.getItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY))
.then(function(userData) {
if (!userData) {
return null;
}
// Load the user from local storage.
AV.User._currentUserMatchesDisk = true;
AV.User._currentUser = AV.Object._create('_User');
AV.User._currentUser._isCurrentUser = true;
var json = JSON.parse(userData);
AV.User._currentUser.id = json._id;
delete json._id;
AV.User._currentUser._sessionToken = json._sessionToken;
delete json._sessionToken;
AV.User._currentUser._finishFetch(json);
//AV.User._currentUser.set(json);
AV.User._currentUser._synchronizeAllAuthData();
AV.User._currentUser._refreshCache();
AV.User._currentUser._opSetQueue = [{}];
return AV.User._currentUser;
});
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"AV",
".",
"_config",
".",
"disableCurrentUser",
")",
"{",
"console",
".",
"warn",
"(",
"'AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
"null",
")",
";",
"}",
"if",
"(",
"AV",
".",
"User",
".",
"_currentUser",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"AV",
".",
"User",
".",
"_currentUser",
")",
";",
"}",
"if",
"(",
"AV",
".",
"User",
".",
"_currentUserMatchesDisk",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"AV",
".",
"User",
".",
"_currentUser",
")",
";",
"}",
"return",
"AV",
".",
"localStorage",
".",
"getItemAsync",
"(",
"AV",
".",
"_getAVPath",
"(",
"AV",
".",
"User",
".",
"_CURRENT_USER_KEY",
")",
")",
".",
"then",
"(",
"function",
"(",
"userData",
")",
"{",
"if",
"(",
"!",
"userData",
")",
"{",
"return",
"null",
";",
"}",
"// Load the user from local storage.",
"AV",
".",
"User",
".",
"_currentUserMatchesDisk",
"=",
"true",
";",
"AV",
".",
"User",
".",
"_currentUser",
"=",
"AV",
".",
"Object",
".",
"_create",
"(",
"'_User'",
")",
";",
"AV",
".",
"User",
".",
"_currentUser",
".",
"_isCurrentUser",
"=",
"true",
";",
"var",
"json",
"=",
"JSON",
".",
"parse",
"(",
"userData",
")",
";",
"AV",
".",
"User",
".",
"_currentUser",
".",
"id",
"=",
"json",
".",
"_id",
";",
"delete",
"json",
".",
"_id",
";",
"AV",
".",
"User",
".",
"_currentUser",
".",
"_sessionToken",
"=",
"json",
".",
"_sessionToken",
";",
"delete",
"json",
".",
"_sessionToken",
";",
"AV",
".",
"User",
".",
"_currentUser",
".",
"_finishFetch",
"(",
"json",
")",
";",
"//AV.User._currentUser.set(json);",
"AV",
".",
"User",
".",
"_currentUser",
".",
"_synchronizeAllAuthData",
"(",
")",
";",
"AV",
".",
"User",
".",
"_currentUser",
".",
"_refreshCache",
"(",
")",
";",
"AV",
".",
"User",
".",
"_currentUser",
".",
"_opSetQueue",
"=",
"[",
"{",
"}",
"]",
";",
"return",
"AV",
".",
"User",
".",
"_currentUser",
";",
"}",
")",
";",
"}"
] |
Retrieves the currently logged in AVUser with a valid session,
either from memory or localStorage, if necessary.
@return {Promise.<AV.User>} resolved with the currently logged in AV.User.
|
[
"Retrieves",
"the",
"currently",
"logged",
"in",
"AVUser",
"with",
"a",
"valid",
"session",
"either",
"from",
"memory",
"or",
"localStorage",
"if",
"necessary",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/user.js#L1402-L1444
|
|
14,073
|
leancloud/javascript-sdk
|
src/geopoint.js
|
function() {
AV.GeoPoint._validate(this.latitude, this.longitude);
return {
__type: 'GeoPoint',
latitude: this.latitude,
longitude: this.longitude,
};
}
|
javascript
|
function() {
AV.GeoPoint._validate(this.latitude, this.longitude);
return {
__type: 'GeoPoint',
latitude: this.latitude,
longitude: this.longitude,
};
}
|
[
"function",
"(",
")",
"{",
"AV",
".",
"GeoPoint",
".",
"_validate",
"(",
"this",
".",
"latitude",
",",
"this",
".",
"longitude",
")",
";",
"return",
"{",
"__type",
":",
"'GeoPoint'",
",",
"latitude",
":",
"this",
".",
"latitude",
",",
"longitude",
":",
"this",
".",
"longitude",
",",
"}",
";",
"}"
] |
Returns a JSON representation of the GeoPoint, suitable for AV.
@return {Object}
|
[
"Returns",
"a",
"JSON",
"representation",
"of",
"the",
"GeoPoint",
"suitable",
"for",
"AV",
"."
] |
f44017dc64e36ac126cf64d6cfd0ee1489e31a22
|
https://github.com/leancloud/javascript-sdk/blob/f44017dc64e36ac126cf64d6cfd0ee1489e31a22/src/geopoint.js#L121-L128
|
|
14,074
|
wellcaffeinated/PhysicsJS
|
src/math/gjk.js
|
getNextSearchDir
|
function getNextSearchDir( ptA, ptB, dir ){
var ABdotB = ptB.normSq() - ptB.dot( ptA )
,ABdotA = ptB.dot( ptA ) - ptA.normSq()
;
// if the origin is farther than either of these points
// get the direction from one of those points to the origin
if ( ABdotB < 0 ){
return dir.clone( ptB ).negate();
} else if ( ABdotA > 0 ){
return dir.clone( ptA ).negate();
// otherwise, use the perpendicular direction from the simplex
} else {
// dir = AB = B - A
dir.clone( ptB ).vsub( ptA );
// if (left handed coordinate system)
// A cross AB < 0 then get perpendicular counterclockwise
return dir.perp( (ptA.cross( dir ) > 0) );
}
}
|
javascript
|
function getNextSearchDir( ptA, ptB, dir ){
var ABdotB = ptB.normSq() - ptB.dot( ptA )
,ABdotA = ptB.dot( ptA ) - ptA.normSq()
;
// if the origin is farther than either of these points
// get the direction from one of those points to the origin
if ( ABdotB < 0 ){
return dir.clone( ptB ).negate();
} else if ( ABdotA > 0 ){
return dir.clone( ptA ).negate();
// otherwise, use the perpendicular direction from the simplex
} else {
// dir = AB = B - A
dir.clone( ptB ).vsub( ptA );
// if (left handed coordinate system)
// A cross AB < 0 then get perpendicular counterclockwise
return dir.perp( (ptA.cross( dir ) > 0) );
}
}
|
[
"function",
"getNextSearchDir",
"(",
"ptA",
",",
"ptB",
",",
"dir",
")",
"{",
"var",
"ABdotB",
"=",
"ptB",
".",
"normSq",
"(",
")",
"-",
"ptB",
".",
"dot",
"(",
"ptA",
")",
",",
"ABdotA",
"=",
"ptB",
".",
"dot",
"(",
"ptA",
")",
"-",
"ptA",
".",
"normSq",
"(",
")",
";",
"// if the origin is farther than either of these points",
"// get the direction from one of those points to the origin",
"if",
"(",
"ABdotB",
"<",
"0",
")",
"{",
"return",
"dir",
".",
"clone",
"(",
"ptB",
")",
".",
"negate",
"(",
")",
";",
"}",
"else",
"if",
"(",
"ABdotA",
">",
"0",
")",
"{",
"return",
"dir",
".",
"clone",
"(",
"ptA",
")",
".",
"negate",
"(",
")",
";",
"// otherwise, use the perpendicular direction from the simplex",
"}",
"else",
"{",
"// dir = AB = B - A",
"dir",
".",
"clone",
"(",
"ptB",
")",
".",
"vsub",
"(",
"ptA",
")",
";",
"// if (left handed coordinate system)",
"// A cross AB < 0 then get perpendicular counterclockwise",
"return",
"dir",
".",
"perp",
"(",
"(",
"ptA",
".",
"cross",
"(",
"dir",
")",
">",
"0",
")",
")",
";",
"}",
"}"
] |
get the next search direction from two simplex points
|
[
"get",
"the",
"next",
"search",
"direction",
"from",
"two",
"simplex",
"points"
] |
b9eca1634b6db222571e7e820a09404513fe2e46
|
https://github.com/wellcaffeinated/PhysicsJS/blob/b9eca1634b6db222571e7e820a09404513fe2e46/src/math/gjk.js#L9-L34
|
14,075
|
wellcaffeinated/PhysicsJS
|
src/math/transform.js
|
Transform
|
function Transform( vect, angle, origin ) {
if (!(this instanceof Transform)){
return new Transform( vect, angle );
}
this.v = new Physics.vector();
this.o = new Physics.vector(); // origin of rotation
if ( vect instanceof Transform ){
this.clone( vect );
return;
}
if (vect){
this.setTranslation( vect );
}
this.setRotation( angle || 0, origin );
}
|
javascript
|
function Transform( vect, angle, origin ) {
if (!(this instanceof Transform)){
return new Transform( vect, angle );
}
this.v = new Physics.vector();
this.o = new Physics.vector(); // origin of rotation
if ( vect instanceof Transform ){
this.clone( vect );
return;
}
if (vect){
this.setTranslation( vect );
}
this.setRotation( angle || 0, origin );
}
|
[
"function",
"Transform",
"(",
"vect",
",",
"angle",
",",
"origin",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Transform",
")",
")",
"{",
"return",
"new",
"Transform",
"(",
"vect",
",",
"angle",
")",
";",
"}",
"this",
".",
"v",
"=",
"new",
"Physics",
".",
"vector",
"(",
")",
";",
"this",
".",
"o",
"=",
"new",
"Physics",
".",
"vector",
"(",
")",
";",
"// origin of rotation",
"if",
"(",
"vect",
"instanceof",
"Transform",
")",
"{",
"this",
".",
"clone",
"(",
"vect",
")",
";",
"return",
";",
"}",
"if",
"(",
"vect",
")",
"{",
"this",
".",
"setTranslation",
"(",
"vect",
")",
";",
"}",
"this",
".",
"setRotation",
"(",
"angle",
"||",
"0",
",",
"origin",
")",
";",
"}"
] |
class Physics.transform
Vector Transformations class for rotating and translating vectors
new Physics.transform( [vect, angle, origin] )
new Physics.transform( transform )
- vect (Vectorish): Translation vector
- transform (Physics.transform): Transform to copy
- angle (Number): Angle (radians) to use for rotation
- origin (Vectorish): Origin of the rotation
Transform Constructor / Factory
|
[
"class",
"Physics",
".",
"transform"
] |
b9eca1634b6db222571e7e820a09404513fe2e46
|
https://github.com/wellcaffeinated/PhysicsJS/blob/b9eca1634b6db222571e7e820a09404513fe2e46/src/math/transform.js#L19-L39
|
14,076
|
wellcaffeinated/PhysicsJS
|
gruntfile.js
|
wrapDefine
|
function wrapDefine( src, path ){
path = path.replace('src/', '');
var deps = ['physicsjs'];
var l = path.split('/').length;
var pfx = l > 0 ? (new Array( l )).join('../') : './';
src.replace(/@requires\s([\w-_\/]+(\.js)?)/g, function( match, dep ){
var i = dep.indexOf('.js');
if ( i > -1 ){
// must be a 3rd party dep
dep = dep.substr( 0, i );
deps.push( dep );
} else {
// just get the dependency
deps.push( pfx + dep );
}
// no effect
return match;
});
var data = {
src: src.replace(/\n/g, '\n '),
path: path,
deps: deps
};
return grunt.template.process(config.banner, config) +
grunt.template.process(config.extensionWrapper, {data: data});
}
|
javascript
|
function wrapDefine( src, path ){
path = path.replace('src/', '');
var deps = ['physicsjs'];
var l = path.split('/').length;
var pfx = l > 0 ? (new Array( l )).join('../') : './';
src.replace(/@requires\s([\w-_\/]+(\.js)?)/g, function( match, dep ){
var i = dep.indexOf('.js');
if ( i > -1 ){
// must be a 3rd party dep
dep = dep.substr( 0, i );
deps.push( dep );
} else {
// just get the dependency
deps.push( pfx + dep );
}
// no effect
return match;
});
var data = {
src: src.replace(/\n/g, '\n '),
path: path,
deps: deps
};
return grunt.template.process(config.banner, config) +
grunt.template.process(config.extensionWrapper, {data: data});
}
|
[
"function",
"wrapDefine",
"(",
"src",
",",
"path",
")",
"{",
"path",
"=",
"path",
".",
"replace",
"(",
"'src/'",
",",
"''",
")",
";",
"var",
"deps",
"=",
"[",
"'physicsjs'",
"]",
";",
"var",
"l",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
".",
"length",
";",
"var",
"pfx",
"=",
"l",
">",
"0",
"?",
"(",
"new",
"Array",
"(",
"l",
")",
")",
".",
"join",
"(",
"'../'",
")",
":",
"'./'",
";",
"src",
".",
"replace",
"(",
"/",
"@requires\\s([\\w-_\\/]+(\\.js)?)",
"/",
"g",
",",
"function",
"(",
"match",
",",
"dep",
")",
"{",
"var",
"i",
"=",
"dep",
".",
"indexOf",
"(",
"'.js'",
")",
";",
"if",
"(",
"i",
">",
"-",
"1",
")",
"{",
"// must be a 3rd party dep",
"dep",
"=",
"dep",
".",
"substr",
"(",
"0",
",",
"i",
")",
";",
"deps",
".",
"push",
"(",
"dep",
")",
";",
"}",
"else",
"{",
"// just get the dependency",
"deps",
".",
"push",
"(",
"pfx",
"+",
"dep",
")",
";",
"}",
"// no effect",
"return",
"match",
";",
"}",
")",
";",
"var",
"data",
"=",
"{",
"src",
":",
"src",
".",
"replace",
"(",
"/",
"\\n",
"/",
"g",
",",
"'\\n '",
")",
",",
"path",
":",
"path",
",",
"deps",
":",
"deps",
"}",
";",
"return",
"grunt",
".",
"template",
".",
"process",
"(",
"config",
".",
"banner",
",",
"config",
")",
"+",
"grunt",
".",
"template",
".",
"process",
"(",
"config",
".",
"extensionWrapper",
",",
"{",
"data",
":",
"data",
"}",
")",
";",
"}"
] |
search for pragmas to figure out dependencies and add a umd declaration
|
[
"search",
"for",
"pragmas",
"to",
"figure",
"out",
"dependencies",
"and",
"add",
"a",
"umd",
"declaration"
] |
b9eca1634b6db222571e7e820a09404513fe2e46
|
https://github.com/wellcaffeinated/PhysicsJS/blob/b9eca1634b6db222571e7e820a09404513fe2e46/gruntfile.js#L133-L164
|
14,077
|
chadxz/imap-simple
|
lib/errors.js
|
ConnectionTimeoutError
|
function ConnectionTimeoutError(timeout) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.message = 'connection timed out';
if (timeout) {
this.message += '. timeout = ' + timeout + ' ms';
}
this.name = 'ConnectionTimeoutError';
}
|
javascript
|
function ConnectionTimeoutError(timeout) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.message = 'connection timed out';
if (timeout) {
this.message += '. timeout = ' + timeout + ' ms';
}
this.name = 'ConnectionTimeoutError';
}
|
[
"function",
"ConnectionTimeoutError",
"(",
"timeout",
")",
"{",
"Error",
".",
"call",
"(",
"this",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"this",
".",
"constructor",
")",
";",
"this",
".",
"message",
"=",
"'connection timed out'",
";",
"if",
"(",
"timeout",
")",
"{",
"this",
".",
"message",
"+=",
"'. timeout = '",
"+",
"timeout",
"+",
"' ms'",
";",
"}",
"this",
".",
"name",
"=",
"'ConnectionTimeoutError'",
";",
"}"
] |
Error thrown when a connection attempt has timed out
@param {number} timeout timeout in milliseconds that the connection waited before timing out
@constructor
|
[
"Error",
"thrown",
"when",
"a",
"connection",
"attempt",
"has",
"timed",
"out"
] |
a0c73265123d15000109b04fe6de54a73ef948d5
|
https://github.com/chadxz/imap-simple/blob/a0c73265123d15000109b04fe6de54a73ef948d5/lib/errors.js#L10-L20
|
14,078
|
chadxz/imap-simple
|
lib/imapSimple.js
|
ImapSimple
|
function ImapSimple(imap) {
var self = this;
self.imap = imap;
// flag to determine whether we should suppress ECONNRESET from bubbling up to listener
self.ending = false;
// pass most node-imap `Connection` events through 1:1
['alert', 'mail', 'expunge', 'uidvalidity', 'update', 'close', 'end'].forEach(function (event) {
self.imap.on(event, self.emit.bind(self, event));
});
// special handling for `error` event
self.imap.on('error', function (err) {
// if .end() has been called and an 'ECONNRESET' error is received, don't bubble
if (err && self.ending && (err.code.toUpperCase() === 'ECONNRESET')) {
return;
}
self.emit('error', err);
});
}
|
javascript
|
function ImapSimple(imap) {
var self = this;
self.imap = imap;
// flag to determine whether we should suppress ECONNRESET from bubbling up to listener
self.ending = false;
// pass most node-imap `Connection` events through 1:1
['alert', 'mail', 'expunge', 'uidvalidity', 'update', 'close', 'end'].forEach(function (event) {
self.imap.on(event, self.emit.bind(self, event));
});
// special handling for `error` event
self.imap.on('error', function (err) {
// if .end() has been called and an 'ECONNRESET' error is received, don't bubble
if (err && self.ending && (err.code.toUpperCase() === 'ECONNRESET')) {
return;
}
self.emit('error', err);
});
}
|
[
"function",
"ImapSimple",
"(",
"imap",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"imap",
"=",
"imap",
";",
"// flag to determine whether we should suppress ECONNRESET from bubbling up to listener",
"self",
".",
"ending",
"=",
"false",
";",
"// pass most node-imap `Connection` events through 1:1",
"[",
"'alert'",
",",
"'mail'",
",",
"'expunge'",
",",
"'uidvalidity'",
",",
"'update'",
",",
"'close'",
",",
"'end'",
"]",
".",
"forEach",
"(",
"function",
"(",
"event",
")",
"{",
"self",
".",
"imap",
".",
"on",
"(",
"event",
",",
"self",
".",
"emit",
".",
"bind",
"(",
"self",
",",
"event",
")",
")",
";",
"}",
")",
";",
"// special handling for `error` event",
"self",
".",
"imap",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"// if .end() has been called and an 'ECONNRESET' error is received, don't bubble",
"if",
"(",
"err",
"&&",
"self",
".",
"ending",
"&&",
"(",
"err",
".",
"code",
".",
"toUpperCase",
"(",
")",
"===",
"'ECONNRESET'",
")",
")",
"{",
"return",
";",
"}",
"self",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
";",
"}",
")",
";",
"}"
] |
Constructs an instance of ImapSimple
@param {object} imap a constructed node-imap connection
@constructor
@class ImapSimple
|
[
"Constructs",
"an",
"instance",
"of",
"ImapSimple"
] |
a0c73265123d15000109b04fe6de54a73ef948d5
|
https://github.com/chadxz/imap-simple/blob/a0c73265123d15000109b04fe6de54a73ef948d5/lib/imapSimple.js#L20-L41
|
14,079
|
chadxz/imap-simple
|
lib/imapSimple.js
|
connect
|
function connect(options, callback) {
options = options || {};
options.imap = options.imap || {};
// support old connectTimeout config option. Remove in v2.0.0
if (options.hasOwnProperty('connectTimeout')) {
console.warn('[imap-simple] connect: options.connectTimeout is deprecated. ' +
'Please use options.imap.authTimeout instead.');
options.imap.authTimeout = options.connectTimeout;
}
// set default authTimeout
options.imap.authTimeout = options.imap.hasOwnProperty('authTimeout') ? options.imap.authTimeout : 2000;
if (callback) {
return nodeify(connect(options), callback);
}
return new Promise(function (resolve, reject) {
var imap = new Imap(options.imap);
function imapOnReady() {
imap.removeListener('error', imapOnError);
imap.removeListener('close', imapOnClose);
imap.removeListener('end', imapOnEnd);
resolve(new ImapSimple(imap));
}
function imapOnError(err) {
if (err.source === 'timeout-auth') {
err = new errors.ConnectionTimeoutError(options.imap.authTimeout);
}
imap.removeListener('ready', imapOnReady);
imap.removeListener('close', imapOnClose);
imap.removeListener('end', imapOnEnd);
reject(err);
}
function imapOnEnd() {
imap.removeListener('ready', imapOnReady);
imap.removeListener('error', imapOnError);
imap.removeListener('close', imapOnClose);
reject(new Error('Connection ended unexpectedly'));
}
function imapOnClose() {
imap.removeListener('ready', imapOnReady);
imap.removeListener('error', imapOnError);
imap.removeListener('end', imapOnEnd);
reject(new Error('Connection closed unexpectedly'));
}
imap.once('ready', imapOnReady);
imap.once('error', imapOnError);
imap.once('close', imapOnClose);
imap.once('end', imapOnEnd);
if (options.hasOwnProperty('onmail')) {
imap.on('mail', options.onmail);
}
if (options.hasOwnProperty('onexpunge')) {
imap.on('expunge', options.onexpunge);
}
if (options.hasOwnProperty('onupdate')) {
imap.on('update', options.onupdate);
}
imap.connect();
});
}
|
javascript
|
function connect(options, callback) {
options = options || {};
options.imap = options.imap || {};
// support old connectTimeout config option. Remove in v2.0.0
if (options.hasOwnProperty('connectTimeout')) {
console.warn('[imap-simple] connect: options.connectTimeout is deprecated. ' +
'Please use options.imap.authTimeout instead.');
options.imap.authTimeout = options.connectTimeout;
}
// set default authTimeout
options.imap.authTimeout = options.imap.hasOwnProperty('authTimeout') ? options.imap.authTimeout : 2000;
if (callback) {
return nodeify(connect(options), callback);
}
return new Promise(function (resolve, reject) {
var imap = new Imap(options.imap);
function imapOnReady() {
imap.removeListener('error', imapOnError);
imap.removeListener('close', imapOnClose);
imap.removeListener('end', imapOnEnd);
resolve(new ImapSimple(imap));
}
function imapOnError(err) {
if (err.source === 'timeout-auth') {
err = new errors.ConnectionTimeoutError(options.imap.authTimeout);
}
imap.removeListener('ready', imapOnReady);
imap.removeListener('close', imapOnClose);
imap.removeListener('end', imapOnEnd);
reject(err);
}
function imapOnEnd() {
imap.removeListener('ready', imapOnReady);
imap.removeListener('error', imapOnError);
imap.removeListener('close', imapOnClose);
reject(new Error('Connection ended unexpectedly'));
}
function imapOnClose() {
imap.removeListener('ready', imapOnReady);
imap.removeListener('error', imapOnError);
imap.removeListener('end', imapOnEnd);
reject(new Error('Connection closed unexpectedly'));
}
imap.once('ready', imapOnReady);
imap.once('error', imapOnError);
imap.once('close', imapOnClose);
imap.once('end', imapOnEnd);
if (options.hasOwnProperty('onmail')) {
imap.on('mail', options.onmail);
}
if (options.hasOwnProperty('onexpunge')) {
imap.on('expunge', options.onexpunge);
}
if (options.hasOwnProperty('onupdate')) {
imap.on('update', options.onupdate);
}
imap.connect();
});
}
|
[
"function",
"connect",
"(",
"options",
",",
"callback",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"imap",
"=",
"options",
".",
"imap",
"||",
"{",
"}",
";",
"// support old connectTimeout config option. Remove in v2.0.0",
"if",
"(",
"options",
".",
"hasOwnProperty",
"(",
"'connectTimeout'",
")",
")",
"{",
"console",
".",
"warn",
"(",
"'[imap-simple] connect: options.connectTimeout is deprecated. '",
"+",
"'Please use options.imap.authTimeout instead.'",
")",
";",
"options",
".",
"imap",
".",
"authTimeout",
"=",
"options",
".",
"connectTimeout",
";",
"}",
"// set default authTimeout",
"options",
".",
"imap",
".",
"authTimeout",
"=",
"options",
".",
"imap",
".",
"hasOwnProperty",
"(",
"'authTimeout'",
")",
"?",
"options",
".",
"imap",
".",
"authTimeout",
":",
"2000",
";",
"if",
"(",
"callback",
")",
"{",
"return",
"nodeify",
"(",
"connect",
"(",
"options",
")",
",",
"callback",
")",
";",
"}",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"imap",
"=",
"new",
"Imap",
"(",
"options",
".",
"imap",
")",
";",
"function",
"imapOnReady",
"(",
")",
"{",
"imap",
".",
"removeListener",
"(",
"'error'",
",",
"imapOnError",
")",
";",
"imap",
".",
"removeListener",
"(",
"'close'",
",",
"imapOnClose",
")",
";",
"imap",
".",
"removeListener",
"(",
"'end'",
",",
"imapOnEnd",
")",
";",
"resolve",
"(",
"new",
"ImapSimple",
"(",
"imap",
")",
")",
";",
"}",
"function",
"imapOnError",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"source",
"===",
"'timeout-auth'",
")",
"{",
"err",
"=",
"new",
"errors",
".",
"ConnectionTimeoutError",
"(",
"options",
".",
"imap",
".",
"authTimeout",
")",
";",
"}",
"imap",
".",
"removeListener",
"(",
"'ready'",
",",
"imapOnReady",
")",
";",
"imap",
".",
"removeListener",
"(",
"'close'",
",",
"imapOnClose",
")",
";",
"imap",
".",
"removeListener",
"(",
"'end'",
",",
"imapOnEnd",
")",
";",
"reject",
"(",
"err",
")",
";",
"}",
"function",
"imapOnEnd",
"(",
")",
"{",
"imap",
".",
"removeListener",
"(",
"'ready'",
",",
"imapOnReady",
")",
";",
"imap",
".",
"removeListener",
"(",
"'error'",
",",
"imapOnError",
")",
";",
"imap",
".",
"removeListener",
"(",
"'close'",
",",
"imapOnClose",
")",
";",
"reject",
"(",
"new",
"Error",
"(",
"'Connection ended unexpectedly'",
")",
")",
";",
"}",
"function",
"imapOnClose",
"(",
")",
"{",
"imap",
".",
"removeListener",
"(",
"'ready'",
",",
"imapOnReady",
")",
";",
"imap",
".",
"removeListener",
"(",
"'error'",
",",
"imapOnError",
")",
";",
"imap",
".",
"removeListener",
"(",
"'end'",
",",
"imapOnEnd",
")",
";",
"reject",
"(",
"new",
"Error",
"(",
"'Connection closed unexpectedly'",
")",
")",
";",
"}",
"imap",
".",
"once",
"(",
"'ready'",
",",
"imapOnReady",
")",
";",
"imap",
".",
"once",
"(",
"'error'",
",",
"imapOnError",
")",
";",
"imap",
".",
"once",
"(",
"'close'",
",",
"imapOnClose",
")",
";",
"imap",
".",
"once",
"(",
"'end'",
",",
"imapOnEnd",
")",
";",
"if",
"(",
"options",
".",
"hasOwnProperty",
"(",
"'onmail'",
")",
")",
"{",
"imap",
".",
"on",
"(",
"'mail'",
",",
"options",
".",
"onmail",
")",
";",
"}",
"if",
"(",
"options",
".",
"hasOwnProperty",
"(",
"'onexpunge'",
")",
")",
"{",
"imap",
".",
"on",
"(",
"'expunge'",
",",
"options",
".",
"onexpunge",
")",
";",
"}",
"if",
"(",
"options",
".",
"hasOwnProperty",
"(",
"'onupdate'",
")",
")",
"{",
"imap",
".",
"on",
"(",
"'update'",
",",
"options",
".",
"onupdate",
")",
";",
"}",
"imap",
".",
"connect",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Connect to an Imap server, returning an ImapSimple instance, which is a wrapper over node-imap to
simplify it's api for common use cases.
@param {object} options
@param {object} options.imap Options to pass to node-imap constructor 1:1
@param {function} [callback] Optional callback, receiving signature (err, connection)
@returns {undefined|Promise} Returns a promise when no callback is specified, resolving to `connection`
|
[
"Connect",
"to",
"an",
"Imap",
"server",
"returning",
"an",
"ImapSimple",
"instance",
"which",
"is",
"a",
"wrapper",
"over",
"node",
"-",
"imap",
"to",
"simplify",
"it",
"s",
"api",
"for",
"common",
"use",
"cases",
"."
] |
a0c73265123d15000109b04fe6de54a73ef948d5
|
https://github.com/chadxz/imap-simple/blob/a0c73265123d15000109b04fe6de54a73ef948d5/lib/imapSimple.js#L548-L620
|
14,080
|
chadxz/imap-simple
|
lib/imapSimple.js
|
getParts
|
function getParts(struct, parts) {
parts = parts || [];
for (var i = 0; i < struct.length; i++) {
if (Array.isArray(struct[i])) {
getParts(struct[i], parts);
} else if (struct[i].partID) {
parts.push(struct[i]);
}
}
return parts;
}
|
javascript
|
function getParts(struct, parts) {
parts = parts || [];
for (var i = 0; i < struct.length; i++) {
if (Array.isArray(struct[i])) {
getParts(struct[i], parts);
} else if (struct[i].partID) {
parts.push(struct[i]);
}
}
return parts;
}
|
[
"function",
"getParts",
"(",
"struct",
",",
"parts",
")",
"{",
"parts",
"=",
"parts",
"||",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"struct",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"struct",
"[",
"i",
"]",
")",
")",
"{",
"getParts",
"(",
"struct",
"[",
"i",
"]",
",",
"parts",
")",
";",
"}",
"else",
"if",
"(",
"struct",
"[",
"i",
"]",
".",
"partID",
")",
"{",
"parts",
".",
"push",
"(",
"struct",
"[",
"i",
"]",
")",
";",
"}",
"}",
"return",
"parts",
";",
"}"
] |
Given the `message.attributes.struct`, retrieve a flattened array of `parts` objects that describe the structure of
the different parts of the message's body. Useful for getting a simple list to iterate for the purposes of,
for example, finding all attachments.
Code taken from http://stackoverflow.com/questions/25247207/how-to-read-and-save-attachments-using-node-imap
@param {Array} struct The `message.attributes.struct` value from the message you wish to retrieve parts for.
@param {Array} [parts] The list of parts to push to.
@returns {Array} a flattened array of `parts` objects that describe the structure of the different parts of the
message's body
|
[
"Given",
"the",
"message",
".",
"attributes",
".",
"struct",
"retrieve",
"a",
"flattened",
"array",
"of",
"parts",
"objects",
"that",
"describe",
"the",
"structure",
"of",
"the",
"different",
"parts",
"of",
"the",
"message",
"s",
"body",
".",
"Useful",
"for",
"getting",
"a",
"simple",
"list",
"to",
"iterate",
"for",
"the",
"purposes",
"of",
"for",
"example",
"finding",
"all",
"attachments",
"."
] |
a0c73265123d15000109b04fe6de54a73ef948d5
|
https://github.com/chadxz/imap-simple/blob/a0c73265123d15000109b04fe6de54a73ef948d5/lib/imapSimple.js#L634-L644
|
14,081
|
blinksocks/blinksocks
|
bin/init.js
|
random
|
function random(array, len) {
const size = array.length;
const randomIndexes = crypto.randomBytes(len).toJSON().data;
return randomIndexes.map((char) => array[char % size]).join('');
}
|
javascript
|
function random(array, len) {
const size = array.length;
const randomIndexes = crypto.randomBytes(len).toJSON().data;
return randomIndexes.map((char) => array[char % size]).join('');
}
|
[
"function",
"random",
"(",
"array",
",",
"len",
")",
"{",
"const",
"size",
"=",
"array",
".",
"length",
";",
"const",
"randomIndexes",
"=",
"crypto",
".",
"randomBytes",
"(",
"len",
")",
".",
"toJSON",
"(",
")",
".",
"data",
";",
"return",
"randomIndexes",
".",
"map",
"(",
"(",
"char",
")",
"=>",
"array",
"[",
"char",
"%",
"size",
"]",
")",
".",
"join",
"(",
"''",
")",
";",
"}"
] |
return a fixed length random string from array
@param array
@param len
@returns {string}
|
[
"return",
"a",
"fixed",
"length",
"random",
"string",
"from",
"array"
] |
88b2b6c0041ef8df4912f9ff0a9cbbec7a2784d0
|
https://github.com/blinksocks/blinksocks/blob/88b2b6c0041ef8df4912f9ff0a9cbbec7a2784d0/bin/init.js#L10-L14
|
14,082
|
blinksocks/blinksocks
|
src/core/acl.js
|
ruleIsMatch
|
function ruleIsMatch(host, port) {
const { host: rHost, port: rPort } = this;
const slashIndex = rHost.indexOf('/');
let isHostMatch = false;
if (slashIndex !== -1 && net.isIP(host)) {
isHostMatch = ip.cidrSubnet(rHost).contains(host);
} else {
isHostMatch = (rHost === host);
}
if (rHost === '*' || isHostMatch) {
if (rPort === '*' || port === rPort) {
return true;
}
}
return false;
}
|
javascript
|
function ruleIsMatch(host, port) {
const { host: rHost, port: rPort } = this;
const slashIndex = rHost.indexOf('/');
let isHostMatch = false;
if (slashIndex !== -1 && net.isIP(host)) {
isHostMatch = ip.cidrSubnet(rHost).contains(host);
} else {
isHostMatch = (rHost === host);
}
if (rHost === '*' || isHostMatch) {
if (rPort === '*' || port === rPort) {
return true;
}
}
return false;
}
|
[
"function",
"ruleIsMatch",
"(",
"host",
",",
"port",
")",
"{",
"const",
"{",
"host",
":",
"rHost",
",",
"port",
":",
"rPort",
"}",
"=",
"this",
";",
"const",
"slashIndex",
"=",
"rHost",
".",
"indexOf",
"(",
"'/'",
")",
";",
"let",
"isHostMatch",
"=",
"false",
";",
"if",
"(",
"slashIndex",
"!==",
"-",
"1",
"&&",
"net",
".",
"isIP",
"(",
"host",
")",
")",
"{",
"isHostMatch",
"=",
"ip",
".",
"cidrSubnet",
"(",
"rHost",
")",
".",
"contains",
"(",
"host",
")",
";",
"}",
"else",
"{",
"isHostMatch",
"=",
"(",
"rHost",
"===",
"host",
")",
";",
"}",
"if",
"(",
"rHost",
"===",
"'*'",
"||",
"isHostMatch",
")",
"{",
"if",
"(",
"rPort",
"===",
"'*'",
"||",
"port",
"===",
"rPort",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
rule's methods
|
[
"rule",
"s",
"methods"
] |
88b2b6c0041ef8df4912f9ff0a9cbbec7a2784d0
|
https://github.com/blinksocks/blinksocks/blob/88b2b6c0041ef8df4912f9ff0a9cbbec7a2784d0/src/core/acl.js#L17-L34
|
14,083
|
blinksocks/blinksocks
|
src/proxies/socks.js
|
getHostType
|
function getHostType(host) {
if (net.isIPv4(host)) {
return ATYP_V4;
}
if (net.isIPv6(host)) {
return ATYP_V6;
}
return ATYP_DOMAIN;
}
|
javascript
|
function getHostType(host) {
if (net.isIPv4(host)) {
return ATYP_V4;
}
if (net.isIPv6(host)) {
return ATYP_V6;
}
return ATYP_DOMAIN;
}
|
[
"function",
"getHostType",
"(",
"host",
")",
"{",
"if",
"(",
"net",
".",
"isIPv4",
"(",
"host",
")",
")",
"{",
"return",
"ATYP_V4",
";",
"}",
"if",
"(",
"net",
".",
"isIPv6",
"(",
"host",
")",
")",
"{",
"return",
"ATYP_V6",
";",
"}",
"return",
"ATYP_DOMAIN",
";",
"}"
] |
const REPLY_ADDRESS_TYPE_NOT_SUPPORTED = 0x08; const REPLY_UNASSIGNED = 0xff;
|
[
"const",
"REPLY_ADDRESS_TYPE_NOT_SUPPORTED",
"=",
"0x08",
";",
"const",
"REPLY_UNASSIGNED",
"=",
"0xff",
";"
] |
88b2b6c0041ef8df4912f9ff0a9cbbec7a2784d0
|
https://github.com/blinksocks/blinksocks/blob/88b2b6c0041ef8df4912f9ff0a9cbbec7a2784d0/src/proxies/socks.js#L98-L106
|
14,084
|
blinksocks/blinksocks
|
bin/bootstrap.js
|
obtainConfig
|
function obtainConfig(file) {
let json;
try {
const jsonFile = fs.readFileSync(file);
json = JSON.parse(jsonFile);
} catch (err) {
throw Error(`fail to load/parse your '${file}': ${err.message}`);
}
return json;
}
|
javascript
|
function obtainConfig(file) {
let json;
try {
const jsonFile = fs.readFileSync(file);
json = JSON.parse(jsonFile);
} catch (err) {
throw Error(`fail to load/parse your '${file}': ${err.message}`);
}
return json;
}
|
[
"function",
"obtainConfig",
"(",
"file",
")",
"{",
"let",
"json",
";",
"try",
"{",
"const",
"jsonFile",
"=",
"fs",
".",
"readFileSync",
"(",
"file",
")",
";",
"json",
"=",
"JSON",
".",
"parse",
"(",
"jsonFile",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"throw",
"Error",
"(",
"`",
"${",
"file",
"}",
"${",
"err",
".",
"message",
"}",
"`",
")",
";",
"}",
"return",
"json",
";",
"}"
] |
get raw config object from json
@param file
@returns {object}
|
[
"get",
"raw",
"config",
"object",
"from",
"json"
] |
88b2b6c0041ef8df4912f9ff0a9cbbec7a2784d0
|
https://github.com/blinksocks/blinksocks/blob/88b2b6c0041ef8df4912f9ff0a9cbbec7a2784d0/bin/bootstrap.js#L8-L17
|
14,085
|
blinksocks/blinksocks
|
src/presets/obfs-tls1.2-ticket.js
|
ApplicationData
|
function ApplicationData(buffer) {
const len = numberToBuffer(buffer.length);
return Buffer.concat([stb('170303'), len, buffer]);
}
|
javascript
|
function ApplicationData(buffer) {
const len = numberToBuffer(buffer.length);
return Buffer.concat([stb('170303'), len, buffer]);
}
|
[
"function",
"ApplicationData",
"(",
"buffer",
")",
"{",
"const",
"len",
"=",
"numberToBuffer",
"(",
"buffer",
".",
"length",
")",
";",
"return",
"Buffer",
".",
"concat",
"(",
"[",
"stb",
"(",
"'170303'",
")",
",",
"len",
",",
"buffer",
"]",
")",
";",
"}"
] |
wrap buffer to Application Data
@param buffer
@returns {Buffer}
@constructor
|
[
"wrap",
"buffer",
"to",
"Application",
"Data"
] |
88b2b6c0041ef8df4912f9ff0a9cbbec7a2784d0
|
https://github.com/blinksocks/blinksocks/blob/88b2b6c0041ef8df4912f9ff0a9cbbec7a2784d0/src/presets/obfs-tls1.2-ticket.js#L41-L44
|
14,086
|
bartve/disconnect
|
lib/client.js
|
function() {
var err = null, status = parseInt(res.statusCode, 10);
if (status > 399) { // Unsuccessful HTTP status? Then pass an error to the callback
var match = data.match(/^\{"message": "(.+)"\}/i);
err = new error.DiscogsError(status, ((match && match[1]) ? match[1] : null));
}
callback(err, data, rateLimit);
}
|
javascript
|
function() {
var err = null, status = parseInt(res.statusCode, 10);
if (status > 399) { // Unsuccessful HTTP status? Then pass an error to the callback
var match = data.match(/^\{"message": "(.+)"\}/i);
err = new error.DiscogsError(status, ((match && match[1]) ? match[1] : null));
}
callback(err, data, rateLimit);
}
|
[
"function",
"(",
")",
"{",
"var",
"err",
"=",
"null",
",",
"status",
"=",
"parseInt",
"(",
"res",
".",
"statusCode",
",",
"10",
")",
";",
"if",
"(",
"status",
">",
"399",
")",
"{",
"// Unsuccessful HTTP status? Then pass an error to the callback",
"var",
"match",
"=",
"data",
".",
"match",
"(",
"/",
"^\\{\"message\": \"(.+)\"\\}",
"/",
"i",
")",
";",
"err",
"=",
"new",
"error",
".",
"DiscogsError",
"(",
"status",
",",
"(",
"(",
"match",
"&&",
"match",
"[",
"1",
"]",
")",
"?",
"match",
"[",
"1",
"]",
":",
"null",
")",
")",
";",
"}",
"callback",
"(",
"err",
",",
"data",
",",
"rateLimit",
")",
";",
"}"
] |
Pass the data to the callback and pass an error on unsuccessful HTTP status
|
[
"Pass",
"the",
"data",
"to",
"the",
"callback",
"and",
"pass",
"an",
"error",
"on",
"unsuccessful",
"HTTP",
"status"
] |
a3fa52cffefa07b3f3d2863284228843176a7336
|
https://github.com/bartve/disconnect/blob/a3fa52cffefa07b3f3d2863284228843176a7336/lib/client.js#L208-L215
|
|
14,087
|
bartve/disconnect
|
lib/error.js
|
DiscogsError
|
function DiscogsError(statusCode, message){
Error.captureStackTrace(this, this.constructor);
this.statusCode = statusCode||404;
this.message = message||'Unknown error.';
}
|
javascript
|
function DiscogsError(statusCode, message){
Error.captureStackTrace(this, this.constructor);
this.statusCode = statusCode||404;
this.message = message||'Unknown error.';
}
|
[
"function",
"DiscogsError",
"(",
"statusCode",
",",
"message",
")",
"{",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"this",
".",
"constructor",
")",
";",
"this",
".",
"statusCode",
"=",
"statusCode",
"||",
"404",
";",
"this",
".",
"message",
"=",
"message",
"||",
"'Unknown error.'",
";",
"}"
] |
Discogs generic error
@param {number} [statusCode] - A HTTP status code
@param {string} [message] - The error message
@returns {DiscogsError}
|
[
"Discogs",
"generic",
"error"
] |
a3fa52cffefa07b3f3d2863284228843176a7336
|
https://github.com/bartve/disconnect/blob/a3fa52cffefa07b3f3d2863284228843176a7336/lib/error.js#L12-L16
|
14,088
|
bbc/bigscreen-player
|
script/playbackstrategy/msestrategy.js
|
calculateSourceAnchor
|
function calculateSourceAnchor (source, startTime) {
if (startTime === undefined || isNaN(startTime)) {
return source;
}
if (windowType === WindowTypes.STATIC) {
return startTime === 0 ? source : source + '#t=' + parseInt(startTime);
}
if (windowType === WindowTypes.SLIDING) {
return startTime === 0 ? source : source + '#r=' + parseInt(startTime);
}
if (windowType === WindowTypes.GROWING) {
var windowStartTimeSeconds = (timeData.windowStartTime / 1000);
var srcWithTimeAnchor = source + '#t=';
startTime = parseInt(startTime);
return startTime === 0 ? srcWithTimeAnchor + (windowStartTimeSeconds + 1) : srcWithTimeAnchor + (windowStartTimeSeconds + startTime);
}
}
|
javascript
|
function calculateSourceAnchor (source, startTime) {
if (startTime === undefined || isNaN(startTime)) {
return source;
}
if (windowType === WindowTypes.STATIC) {
return startTime === 0 ? source : source + '#t=' + parseInt(startTime);
}
if (windowType === WindowTypes.SLIDING) {
return startTime === 0 ? source : source + '#r=' + parseInt(startTime);
}
if (windowType === WindowTypes.GROWING) {
var windowStartTimeSeconds = (timeData.windowStartTime / 1000);
var srcWithTimeAnchor = source + '#t=';
startTime = parseInt(startTime);
return startTime === 0 ? srcWithTimeAnchor + (windowStartTimeSeconds + 1) : srcWithTimeAnchor + (windowStartTimeSeconds + startTime);
}
}
|
[
"function",
"calculateSourceAnchor",
"(",
"source",
",",
"startTime",
")",
"{",
"if",
"(",
"startTime",
"===",
"undefined",
"||",
"isNaN",
"(",
"startTime",
")",
")",
"{",
"return",
"source",
";",
"}",
"if",
"(",
"windowType",
"===",
"WindowTypes",
".",
"STATIC",
")",
"{",
"return",
"startTime",
"===",
"0",
"?",
"source",
":",
"source",
"+",
"'#t='",
"+",
"parseInt",
"(",
"startTime",
")",
";",
"}",
"if",
"(",
"windowType",
"===",
"WindowTypes",
".",
"SLIDING",
")",
"{",
"return",
"startTime",
"===",
"0",
"?",
"source",
":",
"source",
"+",
"'#r='",
"+",
"parseInt",
"(",
"startTime",
")",
";",
"}",
"if",
"(",
"windowType",
"===",
"WindowTypes",
".",
"GROWING",
")",
"{",
"var",
"windowStartTimeSeconds",
"=",
"(",
"timeData",
".",
"windowStartTime",
"/",
"1000",
")",
";",
"var",
"srcWithTimeAnchor",
"=",
"source",
"+",
"'#t='",
";",
"startTime",
"=",
"parseInt",
"(",
"startTime",
")",
";",
"return",
"startTime",
"===",
"0",
"?",
"srcWithTimeAnchor",
"+",
"(",
"windowStartTimeSeconds",
"+",
"1",
")",
":",
"srcWithTimeAnchor",
"+",
"(",
"windowStartTimeSeconds",
"+",
"startTime",
")",
";",
"}",
"}"
] |
Calculates a source url with anchor tags for playback within dashjs
Anchor tags applied to the MPD source for playback:
#r - relative to the start of the first period defined in the DASH manifest
#t - time since the beginning of the first period defined in the DASH manifest
@param {String} source
@param {Number} startTime
|
[
"Calculates",
"a",
"source",
"url",
"with",
"anchor",
"tags",
"for",
"playback",
"within",
"dashjs"
] |
2ea81b43cdae1c1cf3540b5e35b224ad7bb734b5
|
https://github.com/bbc/bigscreen-player/blob/2ea81b43cdae1c1cf3540b5e35b224ad7bb734b5/script/playbackstrategy/msestrategy.js#L228-L248
|
14,089
|
bbc/bigscreen-player
|
docs/example-app/script/index.js
|
toggleControls
|
function toggleControls () {
controlsElement.style.display = controlsElement.style.display == "none" ? "block" : "none";
if (controlsElement.style.display === "block") {
playButton.focus();
}
}
|
javascript
|
function toggleControls () {
controlsElement.style.display = controlsElement.style.display == "none" ? "block" : "none";
if (controlsElement.style.display === "block") {
playButton.focus();
}
}
|
[
"function",
"toggleControls",
"(",
")",
"{",
"controlsElement",
".",
"style",
".",
"display",
"=",
"controlsElement",
".",
"style",
".",
"display",
"==",
"\"none\"",
"?",
"\"block\"",
":",
"\"none\"",
";",
"if",
"(",
"controlsElement",
".",
"style",
".",
"display",
"===",
"\"block\"",
")",
"{",
"playButton",
".",
"focus",
"(",
")",
";",
"}",
"}"
] |
Toggle on screen playback controls
|
[
"Toggle",
"on",
"screen",
"playback",
"controls"
] |
2ea81b43cdae1c1cf3540b5e35b224ad7bb734b5
|
https://github.com/bbc/bigscreen-player/blob/2ea81b43cdae1c1cf3540b5e35b224ad7bb734b5/docs/example-app/script/index.js#L26-L31
|
14,090
|
bbc/bigscreen-player
|
docs/example-app/script/index.js
|
startControlsTimeOut
|
function startControlsTimeOut () {
clearTimeout(controlsTimeout);
if (controlsElement.style.display === "block") {
controlsTimeout = setTimeout(function () {
toggleControls();
}, 5000);
} else {
toggleControls();
}
}
|
javascript
|
function startControlsTimeOut () {
clearTimeout(controlsTimeout);
if (controlsElement.style.display === "block") {
controlsTimeout = setTimeout(function () {
toggleControls();
}, 5000);
} else {
toggleControls();
}
}
|
[
"function",
"startControlsTimeOut",
"(",
")",
"{",
"clearTimeout",
"(",
"controlsTimeout",
")",
";",
"if",
"(",
"controlsElement",
".",
"style",
".",
"display",
"===",
"\"block\"",
")",
"{",
"controlsTimeout",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"toggleControls",
"(",
")",
";",
"}",
",",
"5000",
")",
";",
"}",
"else",
"{",
"toggleControls",
"(",
")",
";",
"}",
"}"
] |
Timeout feature for controls
|
[
"Timeout",
"feature",
"for",
"controls"
] |
2ea81b43cdae1c1cf3540b5e35b224ad7bb734b5
|
https://github.com/bbc/bigscreen-player/blob/2ea81b43cdae1c1cf3540b5e35b224ad7bb734b5/docs/example-app/script/index.js#L34-L45
|
14,091
|
bbc/bigscreen-player
|
docs/example-app/script/index.js
|
setupControls
|
function setupControls () {
window.addEventListener('keydown', function () {
startControlsTimeOut();
});
playButton.addEventListener('click', function () {
bigscreenPlayer.play();
startControlsTimeOut();
});
pauseButton.addEventListener('click', function () {
bigscreenPlayer.pause();
startControlsTimeOut();
});
seekForwardButton.addEventListener('click', function () {
bigscreenPlayer.setCurrentTime(bigscreenPlayer.getCurrentTime() + 10);
startControlsTimeOut();
});
seekBackButton.addEventListener('click', function () {
bigscreenPlayer.setCurrentTime(bigscreenPlayer.getCurrentTime() - 10);
startControlsTimeOut();
});
seekToEndButton.addEventListener('click', function () {
bigscreenPlayer.setCurrentTime(bigscreenPlayer.getDuration() - 10);
startControlsTimeOut();
});
debugToolButton.addEventListener('click', function () {
DebugTool.toggleVisibility();
startControlsTimeOut();
});
bigscreenPlayer.registerForTimeUpdates(function (event) {
});
bigscreenPlayer.registerForStateChanges(function (event) {
var state = 'EMPTY';
switch (event.state) {
case 0: state = 'STOPPED'; break;
case 1: state = 'PAUSED'; break;
case 2: state = 'PLAYING'; break;
case 4: state = 'WAITING'; break;
case 5: state = 'ENDED'; break;
case 6: state = 'FATAL_ERROR'; break;
}
if (state === 'WAITING') {
playbackElement.appendChild(playbackSpinner);
} else {
playbackElement.removeChild(playbackSpinner);
}
});
}
|
javascript
|
function setupControls () {
window.addEventListener('keydown', function () {
startControlsTimeOut();
});
playButton.addEventListener('click', function () {
bigscreenPlayer.play();
startControlsTimeOut();
});
pauseButton.addEventListener('click', function () {
bigscreenPlayer.pause();
startControlsTimeOut();
});
seekForwardButton.addEventListener('click', function () {
bigscreenPlayer.setCurrentTime(bigscreenPlayer.getCurrentTime() + 10);
startControlsTimeOut();
});
seekBackButton.addEventListener('click', function () {
bigscreenPlayer.setCurrentTime(bigscreenPlayer.getCurrentTime() - 10);
startControlsTimeOut();
});
seekToEndButton.addEventListener('click', function () {
bigscreenPlayer.setCurrentTime(bigscreenPlayer.getDuration() - 10);
startControlsTimeOut();
});
debugToolButton.addEventListener('click', function () {
DebugTool.toggleVisibility();
startControlsTimeOut();
});
bigscreenPlayer.registerForTimeUpdates(function (event) {
});
bigscreenPlayer.registerForStateChanges(function (event) {
var state = 'EMPTY';
switch (event.state) {
case 0: state = 'STOPPED'; break;
case 1: state = 'PAUSED'; break;
case 2: state = 'PLAYING'; break;
case 4: state = 'WAITING'; break;
case 5: state = 'ENDED'; break;
case 6: state = 'FATAL_ERROR'; break;
}
if (state === 'WAITING') {
playbackElement.appendChild(playbackSpinner);
} else {
playbackElement.removeChild(playbackSpinner);
}
});
}
|
[
"function",
"setupControls",
"(",
")",
"{",
"window",
".",
"addEventListener",
"(",
"'keydown'",
",",
"function",
"(",
")",
"{",
"startControlsTimeOut",
"(",
")",
";",
"}",
")",
";",
"playButton",
".",
"addEventListener",
"(",
"'click'",
",",
"function",
"(",
")",
"{",
"bigscreenPlayer",
".",
"play",
"(",
")",
";",
"startControlsTimeOut",
"(",
")",
";",
"}",
")",
";",
"pauseButton",
".",
"addEventListener",
"(",
"'click'",
",",
"function",
"(",
")",
"{",
"bigscreenPlayer",
".",
"pause",
"(",
")",
";",
"startControlsTimeOut",
"(",
")",
";",
"}",
")",
";",
"seekForwardButton",
".",
"addEventListener",
"(",
"'click'",
",",
"function",
"(",
")",
"{",
"bigscreenPlayer",
".",
"setCurrentTime",
"(",
"bigscreenPlayer",
".",
"getCurrentTime",
"(",
")",
"+",
"10",
")",
";",
"startControlsTimeOut",
"(",
")",
";",
"}",
")",
";",
"seekBackButton",
".",
"addEventListener",
"(",
"'click'",
",",
"function",
"(",
")",
"{",
"bigscreenPlayer",
".",
"setCurrentTime",
"(",
"bigscreenPlayer",
".",
"getCurrentTime",
"(",
")",
"-",
"10",
")",
";",
"startControlsTimeOut",
"(",
")",
";",
"}",
")",
";",
"seekToEndButton",
".",
"addEventListener",
"(",
"'click'",
",",
"function",
"(",
")",
"{",
"bigscreenPlayer",
".",
"setCurrentTime",
"(",
"bigscreenPlayer",
".",
"getDuration",
"(",
")",
"-",
"10",
")",
";",
"startControlsTimeOut",
"(",
")",
";",
"}",
")",
";",
"debugToolButton",
".",
"addEventListener",
"(",
"'click'",
",",
"function",
"(",
")",
"{",
"DebugTool",
".",
"toggleVisibility",
"(",
")",
";",
"startControlsTimeOut",
"(",
")",
";",
"}",
")",
";",
"bigscreenPlayer",
".",
"registerForTimeUpdates",
"(",
"function",
"(",
"event",
")",
"{",
"}",
")",
";",
"bigscreenPlayer",
".",
"registerForStateChanges",
"(",
"function",
"(",
"event",
")",
"{",
"var",
"state",
"=",
"'EMPTY'",
";",
"switch",
"(",
"event",
".",
"state",
")",
"{",
"case",
"0",
":",
"state",
"=",
"'STOPPED'",
";",
"break",
";",
"case",
"1",
":",
"state",
"=",
"'PAUSED'",
";",
"break",
";",
"case",
"2",
":",
"state",
"=",
"'PLAYING'",
";",
"break",
";",
"case",
"4",
":",
"state",
"=",
"'WAITING'",
";",
"break",
";",
"case",
"5",
":",
"state",
"=",
"'ENDED'",
";",
"break",
";",
"case",
"6",
":",
"state",
"=",
"'FATAL_ERROR'",
";",
"break",
";",
"}",
"if",
"(",
"state",
"===",
"'WAITING'",
")",
"{",
"playbackElement",
".",
"appendChild",
"(",
"playbackSpinner",
")",
";",
"}",
"else",
"{",
"playbackElement",
".",
"removeChild",
"(",
"playbackSpinner",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Create event listeners
|
[
"Create",
"event",
"listeners"
] |
2ea81b43cdae1c1cf3540b5e35b224ad7bb734b5
|
https://github.com/bbc/bigscreen-player/blob/2ea81b43cdae1c1cf3540b5e35b224ad7bb734b5/docs/example-app/script/index.js#L48-L103
|
14,092
|
bbc/bigscreen-player
|
script/playbackstrategy/modifiers/html5.js
|
isNearToCurrentTime
|
function isNearToCurrentTime (seconds) {
var currentTime = getCurrentTime();
var targetTime = getClampedTime(seconds);
return Math.abs(currentTime - targetTime) <= CURRENT_TIME_TOLERANCE;
}
|
javascript
|
function isNearToCurrentTime (seconds) {
var currentTime = getCurrentTime();
var targetTime = getClampedTime(seconds);
return Math.abs(currentTime - targetTime) <= CURRENT_TIME_TOLERANCE;
}
|
[
"function",
"isNearToCurrentTime",
"(",
"seconds",
")",
"{",
"var",
"currentTime",
"=",
"getCurrentTime",
"(",
")",
";",
"var",
"targetTime",
"=",
"getClampedTime",
"(",
"seconds",
")",
";",
"return",
"Math",
".",
"abs",
"(",
"currentTime",
"-",
"targetTime",
")",
"<=",
"CURRENT_TIME_TOLERANCE",
";",
"}"
] |
Check whether a time value is near to the current media play time.
@param {Number} seconds The time value to test, in seconds from the start of the media
@protected
|
[
"Check",
"whether",
"a",
"time",
"value",
"is",
"near",
"to",
"the",
"current",
"media",
"play",
"time",
"."
] |
2ea81b43cdae1c1cf3540b5e35b224ad7bb734b5
|
https://github.com/bbc/bigscreen-player/blob/2ea81b43cdae1c1cf3540b5e35b224ad7bb734b5/script/playbackstrategy/modifiers/html5.js#L475-L479
|
14,093
|
bbc/bigscreen-player
|
script/playbackstrategy/modifiers/html5.js
|
getClampedTime
|
function getClampedTime (seconds) {
var range = getSeekableRange();
var offsetFromEnd = getClampOffsetFromConfig();
var nearToEnd = Math.max(range.end - offsetFromEnd, range.start);
if (seconds < range.start) {
return range.start;
} else if (seconds > nearToEnd) {
return nearToEnd;
} else {
return seconds;
}
}
|
javascript
|
function getClampedTime (seconds) {
var range = getSeekableRange();
var offsetFromEnd = getClampOffsetFromConfig();
var nearToEnd = Math.max(range.end - offsetFromEnd, range.start);
if (seconds < range.start) {
return range.start;
} else if (seconds > nearToEnd) {
return nearToEnd;
} else {
return seconds;
}
}
|
[
"function",
"getClampedTime",
"(",
"seconds",
")",
"{",
"var",
"range",
"=",
"getSeekableRange",
"(",
")",
";",
"var",
"offsetFromEnd",
"=",
"getClampOffsetFromConfig",
"(",
")",
";",
"var",
"nearToEnd",
"=",
"Math",
".",
"max",
"(",
"range",
".",
"end",
"-",
"offsetFromEnd",
",",
"range",
".",
"start",
")",
";",
"if",
"(",
"seconds",
"<",
"range",
".",
"start",
")",
"{",
"return",
"range",
".",
"start",
";",
"}",
"else",
"if",
"(",
"seconds",
">",
"nearToEnd",
")",
"{",
"return",
"nearToEnd",
";",
"}",
"else",
"{",
"return",
"seconds",
";",
"}",
"}"
] |
Clamp a time value so it does not exceed the current range.
Clamps to near the end instead of the end itself to allow for devices that cannot seek to the very end of the media.
@param {Number} seconds The time value to clamp in seconds from the start of the media
@protected
|
[
"Clamp",
"a",
"time",
"value",
"so",
"it",
"does",
"not",
"exceed",
"the",
"current",
"range",
".",
"Clamps",
"to",
"near",
"the",
"end",
"instead",
"of",
"the",
"end",
"itself",
"to",
"allow",
"for",
"devices",
"that",
"cannot",
"seek",
"to",
"the",
"very",
"end",
"of",
"the",
"media",
"."
] |
2ea81b43cdae1c1cf3540b5e35b224ad7bb734b5
|
https://github.com/bbc/bigscreen-player/blob/2ea81b43cdae1c1cf3540b5e35b224ad7bb734b5/script/playbackstrategy/modifiers/html5.js#L487-L498
|
14,094
|
supermedium/aframe-environment-component
|
index.js
|
function (skyType, sunHeight) {
var fogColor;
if (skyType == 'color' || skyType == 'none'){
fogColor = new THREE.Color(this.data.skyColor);
}
else if (skyType == 'gradient'){
fogColor = new THREE.Color(this.data.horizonColor);
}
else if (skyType == 'atmosphere')
{
var fogRatios = [ 1, 0.5, 0.22, 0.1, 0.05, 0];
var fogColors = ['#C0CDCF', '#81ADC5', '#525e62', '#2a2d2d', '#141616', '#000'];
if (sunHeight <= 0) return '#000';
sunHeight = Math.min(1, sunHeight);
for (var i = 0; i < fogRatios.length; i++){
if (sunHeight > fogRatios[i]){
var c1 = new THREE.Color(fogColors[i - 1]);
var c2 = new THREE.Color(fogColors[i]);
var a = (sunHeight - fogRatios[i]) / (fogRatios[i - 1] - fogRatios[i]);
c2.lerp(c1, a);
fogColor = c2;
break;
}
}
}
// dim down the color
fogColor.multiplyScalar(0.9);
// mix it a bit with ground color
fogColor.lerp(new THREE.Color(this.data.groundColor), 0.3);
return '#' + fogColor.getHexString();
}
|
javascript
|
function (skyType, sunHeight) {
var fogColor;
if (skyType == 'color' || skyType == 'none'){
fogColor = new THREE.Color(this.data.skyColor);
}
else if (skyType == 'gradient'){
fogColor = new THREE.Color(this.data.horizonColor);
}
else if (skyType == 'atmosphere')
{
var fogRatios = [ 1, 0.5, 0.22, 0.1, 0.05, 0];
var fogColors = ['#C0CDCF', '#81ADC5', '#525e62', '#2a2d2d', '#141616', '#000'];
if (sunHeight <= 0) return '#000';
sunHeight = Math.min(1, sunHeight);
for (var i = 0; i < fogRatios.length; i++){
if (sunHeight > fogRatios[i]){
var c1 = new THREE.Color(fogColors[i - 1]);
var c2 = new THREE.Color(fogColors[i]);
var a = (sunHeight - fogRatios[i]) / (fogRatios[i - 1] - fogRatios[i]);
c2.lerp(c1, a);
fogColor = c2;
break;
}
}
}
// dim down the color
fogColor.multiplyScalar(0.9);
// mix it a bit with ground color
fogColor.lerp(new THREE.Color(this.data.groundColor), 0.3);
return '#' + fogColor.getHexString();
}
|
[
"function",
"(",
"skyType",
",",
"sunHeight",
")",
"{",
"var",
"fogColor",
";",
"if",
"(",
"skyType",
"==",
"'color'",
"||",
"skyType",
"==",
"'none'",
")",
"{",
"fogColor",
"=",
"new",
"THREE",
".",
"Color",
"(",
"this",
".",
"data",
".",
"skyColor",
")",
";",
"}",
"else",
"if",
"(",
"skyType",
"==",
"'gradient'",
")",
"{",
"fogColor",
"=",
"new",
"THREE",
".",
"Color",
"(",
"this",
".",
"data",
".",
"horizonColor",
")",
";",
"}",
"else",
"if",
"(",
"skyType",
"==",
"'atmosphere'",
")",
"{",
"var",
"fogRatios",
"=",
"[",
"1",
",",
"0.5",
",",
"0.22",
",",
"0.1",
",",
"0.05",
",",
"0",
"]",
";",
"var",
"fogColors",
"=",
"[",
"'#C0CDCF'",
",",
"'#81ADC5'",
",",
"'#525e62'",
",",
"'#2a2d2d'",
",",
"'#141616'",
",",
"'#000'",
"]",
";",
"if",
"(",
"sunHeight",
"<=",
"0",
")",
"return",
"'#000'",
";",
"sunHeight",
"=",
"Math",
".",
"min",
"(",
"1",
",",
"sunHeight",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"fogRatios",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"sunHeight",
">",
"fogRatios",
"[",
"i",
"]",
")",
"{",
"var",
"c1",
"=",
"new",
"THREE",
".",
"Color",
"(",
"fogColors",
"[",
"i",
"-",
"1",
"]",
")",
";",
"var",
"c2",
"=",
"new",
"THREE",
".",
"Color",
"(",
"fogColors",
"[",
"i",
"]",
")",
";",
"var",
"a",
"=",
"(",
"sunHeight",
"-",
"fogRatios",
"[",
"i",
"]",
")",
"/",
"(",
"fogRatios",
"[",
"i",
"-",
"1",
"]",
"-",
"fogRatios",
"[",
"i",
"]",
")",
";",
"c2",
".",
"lerp",
"(",
"c1",
",",
"a",
")",
";",
"fogColor",
"=",
"c2",
";",
"break",
";",
"}",
"}",
"}",
"// dim down the color",
"fogColor",
".",
"multiplyScalar",
"(",
"0.9",
")",
";",
"// mix it a bit with ground color",
"fogColor",
".",
"lerp",
"(",
"new",
"THREE",
".",
"Color",
"(",
"this",
".",
"data",
".",
"groundColor",
")",
",",
"0.3",
")",
";",
"return",
"'#'",
"+",
"fogColor",
".",
"getHexString",
"(",
")",
";",
"}"
] |
returns a fog color from a specific sky type and sun height
|
[
"returns",
"a",
"fog",
"color",
"from",
"a",
"specific",
"sky",
"type",
"and",
"sun",
"height"
] |
4054f003ff4781b4ee6c4b3ae5071fd691831ccf
|
https://github.com/supermedium/aframe-environment-component/blob/4054f003ff4781b4ee6c4b3ae5071fd691831ccf/index.js#L205-L240
|
|
14,095
|
supermedium/aframe-environment-component
|
index.js
|
function () {
var str = '{';
for (var i in this.schema){
if (i == 'preset') continue;
str += i + ': ';
var type = this.schema[i].type;
if (type == 'vec3') {
str += '{ x: ' + this.data[i].x + ', y: ' + this.data[i].y + ', z: ' + this.data[i].z + '}';
}
else if (type == 'string' || type == 'color') {
str += '"' + this.data[i] + '"';
}
else {
str += this.data[i];
}
str += ', ';
}
str += '}';
console.log(str);
}
|
javascript
|
function () {
var str = '{';
for (var i in this.schema){
if (i == 'preset') continue;
str += i + ': ';
var type = this.schema[i].type;
if (type == 'vec3') {
str += '{ x: ' + this.data[i].x + ', y: ' + this.data[i].y + ', z: ' + this.data[i].z + '}';
}
else if (type == 'string' || type == 'color') {
str += '"' + this.data[i] + '"';
}
else {
str += this.data[i];
}
str += ', ';
}
str += '}';
console.log(str);
}
|
[
"function",
"(",
")",
"{",
"var",
"str",
"=",
"'{'",
";",
"for",
"(",
"var",
"i",
"in",
"this",
".",
"schema",
")",
"{",
"if",
"(",
"i",
"==",
"'preset'",
")",
"continue",
";",
"str",
"+=",
"i",
"+",
"': '",
";",
"var",
"type",
"=",
"this",
".",
"schema",
"[",
"i",
"]",
".",
"type",
";",
"if",
"(",
"type",
"==",
"'vec3'",
")",
"{",
"str",
"+=",
"'{ x: '",
"+",
"this",
".",
"data",
"[",
"i",
"]",
".",
"x",
"+",
"', y: '",
"+",
"this",
".",
"data",
"[",
"i",
"]",
".",
"y",
"+",
"', z: '",
"+",
"this",
".",
"data",
"[",
"i",
"]",
".",
"z",
"+",
"'}'",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"'string'",
"||",
"type",
"==",
"'color'",
")",
"{",
"str",
"+=",
"'\"'",
"+",
"this",
".",
"data",
"[",
"i",
"]",
"+",
"'\"'",
";",
"}",
"else",
"{",
"str",
"+=",
"this",
".",
"data",
"[",
"i",
"]",
";",
"}",
"str",
"+=",
"', '",
";",
"}",
"str",
"+=",
"'}'",
";",
"console",
".",
"log",
"(",
"str",
")",
";",
"}"
] |
logs current parameters to console, for saving to a preset
|
[
"logs",
"current",
"parameters",
"to",
"console",
"for",
"saving",
"to",
"a",
"preset"
] |
4054f003ff4781b4ee6c4b3ae5071fd691831ccf
|
https://github.com/supermedium/aframe-environment-component/blob/4054f003ff4781b4ee6c4b3ae5071fd691831ccf/index.js#L385-L404
|
|
14,096
|
supermedium/aframe-environment-component
|
index.js
|
function () {
// trim number to 3 decimals
function dec3 (v) {
return Math.floor(v * 1000) / 1000;
}
var params = [];
var usingPreset = this.data.preset != 'none' ? this.presets[this.data.preset] : false;
if (usingPreset) {
params.push('preset: ' + this.data.preset);
}
for (var i in this.schema) {
if (i == 'preset' || (usingPreset && usingPreset[i] === undefined)) {
continue;
}
var def = usingPreset ? usingPreset[i] : this.schema[i].default;
var data = this.data[i];
var type = this.schema[i].type;
if (type == 'vec3') {
var coords = def;
if (typeof(def) == 'string') {
def = def.split(' ');
coords = {x: def[0], y: def[1], z: def[2]};
}
if (dec3(coords.x) != dec3(data.x) || dec3(coords.y) != dec3(data.y) || dec3(coords.z) != dec3(data.z)) {
params.push(i + ': ' + dec3(data.x) + ' ' + dec3(data.y) + ' ' + dec3(data.z));
}
}
else {
if (def != data) {
if (this.schema[i].type == 'number') {
data = dec3(data);
}
params.push(i + ': ' + data);
}
}
}
console.log('%c' + params.join('; '), 'color: #f48;font-weight:bold');
}
|
javascript
|
function () {
// trim number to 3 decimals
function dec3 (v) {
return Math.floor(v * 1000) / 1000;
}
var params = [];
var usingPreset = this.data.preset != 'none' ? this.presets[this.data.preset] : false;
if (usingPreset) {
params.push('preset: ' + this.data.preset);
}
for (var i in this.schema) {
if (i == 'preset' || (usingPreset && usingPreset[i] === undefined)) {
continue;
}
var def = usingPreset ? usingPreset[i] : this.schema[i].default;
var data = this.data[i];
var type = this.schema[i].type;
if (type == 'vec3') {
var coords = def;
if (typeof(def) == 'string') {
def = def.split(' ');
coords = {x: def[0], y: def[1], z: def[2]};
}
if (dec3(coords.x) != dec3(data.x) || dec3(coords.y) != dec3(data.y) || dec3(coords.z) != dec3(data.z)) {
params.push(i + ': ' + dec3(data.x) + ' ' + dec3(data.y) + ' ' + dec3(data.z));
}
}
else {
if (def != data) {
if (this.schema[i].type == 'number') {
data = dec3(data);
}
params.push(i + ': ' + data);
}
}
}
console.log('%c' + params.join('; '), 'color: #f48;font-weight:bold');
}
|
[
"function",
"(",
")",
"{",
"// trim number to 3 decimals",
"function",
"dec3",
"(",
"v",
")",
"{",
"return",
"Math",
".",
"floor",
"(",
"v",
"*",
"1000",
")",
"/",
"1000",
";",
"}",
"var",
"params",
"=",
"[",
"]",
";",
"var",
"usingPreset",
"=",
"this",
".",
"data",
".",
"preset",
"!=",
"'none'",
"?",
"this",
".",
"presets",
"[",
"this",
".",
"data",
".",
"preset",
"]",
":",
"false",
";",
"if",
"(",
"usingPreset",
")",
"{",
"params",
".",
"push",
"(",
"'preset: '",
"+",
"this",
".",
"data",
".",
"preset",
")",
";",
"}",
"for",
"(",
"var",
"i",
"in",
"this",
".",
"schema",
")",
"{",
"if",
"(",
"i",
"==",
"'preset'",
"||",
"(",
"usingPreset",
"&&",
"usingPreset",
"[",
"i",
"]",
"===",
"undefined",
")",
")",
"{",
"continue",
";",
"}",
"var",
"def",
"=",
"usingPreset",
"?",
"usingPreset",
"[",
"i",
"]",
":",
"this",
".",
"schema",
"[",
"i",
"]",
".",
"default",
";",
"var",
"data",
"=",
"this",
".",
"data",
"[",
"i",
"]",
";",
"var",
"type",
"=",
"this",
".",
"schema",
"[",
"i",
"]",
".",
"type",
";",
"if",
"(",
"type",
"==",
"'vec3'",
")",
"{",
"var",
"coords",
"=",
"def",
";",
"if",
"(",
"typeof",
"(",
"def",
")",
"==",
"'string'",
")",
"{",
"def",
"=",
"def",
".",
"split",
"(",
"' '",
")",
";",
"coords",
"=",
"{",
"x",
":",
"def",
"[",
"0",
"]",
",",
"y",
":",
"def",
"[",
"1",
"]",
",",
"z",
":",
"def",
"[",
"2",
"]",
"}",
";",
"}",
"if",
"(",
"dec3",
"(",
"coords",
".",
"x",
")",
"!=",
"dec3",
"(",
"data",
".",
"x",
")",
"||",
"dec3",
"(",
"coords",
".",
"y",
")",
"!=",
"dec3",
"(",
"data",
".",
"y",
")",
"||",
"dec3",
"(",
"coords",
".",
"z",
")",
"!=",
"dec3",
"(",
"data",
".",
"z",
")",
")",
"{",
"params",
".",
"push",
"(",
"i",
"+",
"': '",
"+",
"dec3",
"(",
"data",
".",
"x",
")",
"+",
"' '",
"+",
"dec3",
"(",
"data",
".",
"y",
")",
"+",
"' '",
"+",
"dec3",
"(",
"data",
".",
"z",
")",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"def",
"!=",
"data",
")",
"{",
"if",
"(",
"this",
".",
"schema",
"[",
"i",
"]",
".",
"type",
"==",
"'number'",
")",
"{",
"data",
"=",
"dec3",
"(",
"data",
")",
";",
"}",
"params",
".",
"push",
"(",
"i",
"+",
"': '",
"+",
"data",
")",
";",
"}",
"}",
"}",
"console",
".",
"log",
"(",
"'%c'",
"+",
"params",
".",
"join",
"(",
"'; '",
")",
",",
"'color: #f48;font-weight:bold'",
")",
";",
"}"
] |
dumps current component settings to console.
|
[
"dumps",
"current",
"component",
"settings",
"to",
"console",
"."
] |
4054f003ff4781b4ee6c4b3ae5071fd691831ccf
|
https://github.com/supermedium/aframe-environment-component/blob/4054f003ff4781b4ee6c4b3ae5071fd691831ccf/index.js#L407-L448
|
|
14,097
|
supermedium/aframe-environment-component
|
index.js
|
function (ctx, size, texMeters) {
if (this.data.grid == 'none') return;
// one grid feature each 2 meters
var num = Math.floor(texMeters / 2);
var step = size / (texMeters / 2); // 2 meters == <step> pixels
var i, j, ii;
ctx.fillStyle = this.data.gridColor;
switch (this.data.grid) {
case '1x1':
case '2x2': {
if (this.data.grid == '1x1') {
num = num * 2;
step = size / texMeters;
}
for (i = 0; i < num; i++) {
ii = Math.floor(i * step);
ctx.fillRect(0, ii, size, 1);
ctx.fillRect(ii, 0, 1, size);
}
break;
}
case 'crosses': {
var l = Math.floor(step / 20);
for (i = 0; i < num + 1; i++) {
ii = Math.floor(i * step);
for (j = 0; j < num + 1; j++) {
var jj = Math.floor(-l + j * step);
ctx.fillRect(jj, ii, l * 2, 1);
ctx.fillRect(ii, jj, 1, l * 2);
}
}
break;
}
case 'dots': {
for (i = 0; i < num + 1; i++) {
for (j = 0; j < num + 1; j++) {
ctx.beginPath(); ctx.arc(Math.floor(j * step), Math.floor(i * step), 4, 0, Math.PI * 2); ctx.fill();
}
}
break;
}
case 'xlines': {
for (i = 0; i < num; i++) {
ctx.fillRect(Math.floor(i * step), 0, 1, size);
}
break;
}
case 'ylines': {
for (i = 0; i < num; i++) {
ctx.fillRect(0, Math.floor(i * step), size, 1);
}
break;
}
}
}
|
javascript
|
function (ctx, size, texMeters) {
if (this.data.grid == 'none') return;
// one grid feature each 2 meters
var num = Math.floor(texMeters / 2);
var step = size / (texMeters / 2); // 2 meters == <step> pixels
var i, j, ii;
ctx.fillStyle = this.data.gridColor;
switch (this.data.grid) {
case '1x1':
case '2x2': {
if (this.data.grid == '1x1') {
num = num * 2;
step = size / texMeters;
}
for (i = 0; i < num; i++) {
ii = Math.floor(i * step);
ctx.fillRect(0, ii, size, 1);
ctx.fillRect(ii, 0, 1, size);
}
break;
}
case 'crosses': {
var l = Math.floor(step / 20);
for (i = 0; i < num + 1; i++) {
ii = Math.floor(i * step);
for (j = 0; j < num + 1; j++) {
var jj = Math.floor(-l + j * step);
ctx.fillRect(jj, ii, l * 2, 1);
ctx.fillRect(ii, jj, 1, l * 2);
}
}
break;
}
case 'dots': {
for (i = 0; i < num + 1; i++) {
for (j = 0; j < num + 1; j++) {
ctx.beginPath(); ctx.arc(Math.floor(j * step), Math.floor(i * step), 4, 0, Math.PI * 2); ctx.fill();
}
}
break;
}
case 'xlines': {
for (i = 0; i < num; i++) {
ctx.fillRect(Math.floor(i * step), 0, 1, size);
}
break;
}
case 'ylines': {
for (i = 0; i < num; i++) {
ctx.fillRect(0, Math.floor(i * step), size, 1);
}
break;
}
}
}
|
[
"function",
"(",
"ctx",
",",
"size",
",",
"texMeters",
")",
"{",
"if",
"(",
"this",
".",
"data",
".",
"grid",
"==",
"'none'",
")",
"return",
";",
"// one grid feature each 2 meters",
"var",
"num",
"=",
"Math",
".",
"floor",
"(",
"texMeters",
"/",
"2",
")",
";",
"var",
"step",
"=",
"size",
"/",
"(",
"texMeters",
"/",
"2",
")",
";",
"// 2 meters == <step> pixels",
"var",
"i",
",",
"j",
",",
"ii",
";",
"ctx",
".",
"fillStyle",
"=",
"this",
".",
"data",
".",
"gridColor",
";",
"switch",
"(",
"this",
".",
"data",
".",
"grid",
")",
"{",
"case",
"'1x1'",
":",
"case",
"'2x2'",
":",
"{",
"if",
"(",
"this",
".",
"data",
".",
"grid",
"==",
"'1x1'",
")",
"{",
"num",
"=",
"num",
"*",
"2",
";",
"step",
"=",
"size",
"/",
"texMeters",
";",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"num",
";",
"i",
"++",
")",
"{",
"ii",
"=",
"Math",
".",
"floor",
"(",
"i",
"*",
"step",
")",
";",
"ctx",
".",
"fillRect",
"(",
"0",
",",
"ii",
",",
"size",
",",
"1",
")",
";",
"ctx",
".",
"fillRect",
"(",
"ii",
",",
"0",
",",
"1",
",",
"size",
")",
";",
"}",
"break",
";",
"}",
"case",
"'crosses'",
":",
"{",
"var",
"l",
"=",
"Math",
".",
"floor",
"(",
"step",
"/",
"20",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"num",
"+",
"1",
";",
"i",
"++",
")",
"{",
"ii",
"=",
"Math",
".",
"floor",
"(",
"i",
"*",
"step",
")",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"num",
"+",
"1",
";",
"j",
"++",
")",
"{",
"var",
"jj",
"=",
"Math",
".",
"floor",
"(",
"-",
"l",
"+",
"j",
"*",
"step",
")",
";",
"ctx",
".",
"fillRect",
"(",
"jj",
",",
"ii",
",",
"l",
"*",
"2",
",",
"1",
")",
";",
"ctx",
".",
"fillRect",
"(",
"ii",
",",
"jj",
",",
"1",
",",
"l",
"*",
"2",
")",
";",
"}",
"}",
"break",
";",
"}",
"case",
"'dots'",
":",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"num",
"+",
"1",
";",
"i",
"++",
")",
"{",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"num",
"+",
"1",
";",
"j",
"++",
")",
"{",
"ctx",
".",
"beginPath",
"(",
")",
";",
"ctx",
".",
"arc",
"(",
"Math",
".",
"floor",
"(",
"j",
"*",
"step",
")",
",",
"Math",
".",
"floor",
"(",
"i",
"*",
"step",
")",
",",
"4",
",",
"0",
",",
"Math",
".",
"PI",
"*",
"2",
")",
";",
"ctx",
".",
"fill",
"(",
")",
";",
"}",
"}",
"break",
";",
"}",
"case",
"'xlines'",
":",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"num",
";",
"i",
"++",
")",
"{",
"ctx",
".",
"fillRect",
"(",
"Math",
".",
"floor",
"(",
"i",
"*",
"step",
")",
",",
"0",
",",
"1",
",",
"size",
")",
";",
"}",
"break",
";",
"}",
"case",
"'ylines'",
":",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"num",
";",
"i",
"++",
")",
"{",
"ctx",
".",
"fillRect",
"(",
"0",
",",
"Math",
".",
"floor",
"(",
"i",
"*",
"step",
")",
",",
"size",
",",
"1",
")",
";",
"}",
"break",
";",
"}",
"}",
"}"
] |
draw grid to a canvas context
|
[
"draw",
"grid",
"to",
"a",
"canvas",
"context"
] |
4054f003ff4781b4ee6c4b3ae5071fd691831ccf
|
https://github.com/supermedium/aframe-environment-component/blob/4054f003ff4781b4ee6c4b3ae5071fd691831ccf/index.js#L608-L667
|
|
14,098
|
supermedium/aframe-environment-component
|
index.js
|
function() {
var numStars = 2000;
var geometry = new THREE.BufferGeometry();
var positions = new Float32Array( numStars * 3 );
var radius = this.STAGE_SIZE - 1;
var v = new THREE.Vector3();
for (var i = 0; i < positions.length; i += 3) {
v.set(this.random(i + 23) - 0.5, this.random(i + 24), this.random(i + 25) - 0.5);
v.normalize();
v.multiplyScalar(radius);
positions[i ] = v.x;
positions[i+1] = v.y;
positions[i+2] = v.z;
}
geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setDrawRange(0, 0); // don't draw any yet
var material = new THREE.PointsMaterial({size: 0.01, color: 0xCCCCCC, fog: false});
this.stars.setObject3D('mesh', new THREE.Points(geometry, material));
}
|
javascript
|
function() {
var numStars = 2000;
var geometry = new THREE.BufferGeometry();
var positions = new Float32Array( numStars * 3 );
var radius = this.STAGE_SIZE - 1;
var v = new THREE.Vector3();
for (var i = 0; i < positions.length; i += 3) {
v.set(this.random(i + 23) - 0.5, this.random(i + 24), this.random(i + 25) - 0.5);
v.normalize();
v.multiplyScalar(radius);
positions[i ] = v.x;
positions[i+1] = v.y;
positions[i+2] = v.z;
}
geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setDrawRange(0, 0); // don't draw any yet
var material = new THREE.PointsMaterial({size: 0.01, color: 0xCCCCCC, fog: false});
this.stars.setObject3D('mesh', new THREE.Points(geometry, material));
}
|
[
"function",
"(",
")",
"{",
"var",
"numStars",
"=",
"2000",
";",
"var",
"geometry",
"=",
"new",
"THREE",
".",
"BufferGeometry",
"(",
")",
";",
"var",
"positions",
"=",
"new",
"Float32Array",
"(",
"numStars",
"*",
"3",
")",
";",
"var",
"radius",
"=",
"this",
".",
"STAGE_SIZE",
"-",
"1",
";",
"var",
"v",
"=",
"new",
"THREE",
".",
"Vector3",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"positions",
".",
"length",
";",
"i",
"+=",
"3",
")",
"{",
"v",
".",
"set",
"(",
"this",
".",
"random",
"(",
"i",
"+",
"23",
")",
"-",
"0.5",
",",
"this",
".",
"random",
"(",
"i",
"+",
"24",
")",
",",
"this",
".",
"random",
"(",
"i",
"+",
"25",
")",
"-",
"0.5",
")",
";",
"v",
".",
"normalize",
"(",
")",
";",
"v",
".",
"multiplyScalar",
"(",
"radius",
")",
";",
"positions",
"[",
"i",
"]",
"=",
"v",
".",
"x",
";",
"positions",
"[",
"i",
"+",
"1",
"]",
"=",
"v",
".",
"y",
";",
"positions",
"[",
"i",
"+",
"2",
"]",
"=",
"v",
".",
"z",
";",
"}",
"geometry",
".",
"addAttribute",
"(",
"'position'",
",",
"new",
"THREE",
".",
"BufferAttribute",
"(",
"positions",
",",
"3",
")",
")",
";",
"geometry",
".",
"setDrawRange",
"(",
"0",
",",
"0",
")",
";",
"// don't draw any yet",
"var",
"material",
"=",
"new",
"THREE",
".",
"PointsMaterial",
"(",
"{",
"size",
":",
"0.01",
",",
"color",
":",
"0xCCCCCC",
",",
"fog",
":",
"false",
"}",
")",
";",
"this",
".",
"stars",
".",
"setObject3D",
"(",
"'mesh'",
",",
"new",
"THREE",
".",
"Points",
"(",
"geometry",
",",
"material",
")",
")",
";",
"}"
] |
initializes the BufferGeometry for the stars
|
[
"initializes",
"the",
"BufferGeometry",
"for",
"the",
"stars"
] |
4054f003ff4781b4ee6c4b3ae5071fd691831ccf
|
https://github.com/supermedium/aframe-environment-component/blob/4054f003ff4781b4ee6c4b3ae5071fd691831ccf/index.js#L959-L977
|
|
14,099
|
datproject/dat-node
|
index.js
|
checkIfExists
|
function checkIfExists () {
// Create after we check for pre-sleep .dat stuff
var createAfterValid = (createIfMissing && !errorIfExists)
var missingError = new Error('Dat storage does not exist.')
missingError.name = 'MissingError'
var existsError = new Error('Dat storage already exists.')
existsError.name = 'ExistsError'
var oldError = new Error('Dat folder contains incompatible metadata. Please remove your metadata (rm -rf .dat).')
oldError.name = 'IncompatibleError'
fs.readdir(path.join(opts.dir, '.dat'), function (err, files) {
// TODO: omg please make this less confusing.
var noDat = !!(err || !files.length)
hasDat = !noDat
var validSleep = (files && files.length && files.indexOf('metadata.key') > -1)
var badDat = !(noDat || validSleep)
if ((noDat || validSleep) && createAfterValid) return create()
else if (badDat) return cb(oldError)
if (err && !createIfMissing) return cb(missingError)
else if (!err && errorIfExists) return cb(existsError)
return create()
})
}
|
javascript
|
function checkIfExists () {
// Create after we check for pre-sleep .dat stuff
var createAfterValid = (createIfMissing && !errorIfExists)
var missingError = new Error('Dat storage does not exist.')
missingError.name = 'MissingError'
var existsError = new Error('Dat storage already exists.')
existsError.name = 'ExistsError'
var oldError = new Error('Dat folder contains incompatible metadata. Please remove your metadata (rm -rf .dat).')
oldError.name = 'IncompatibleError'
fs.readdir(path.join(opts.dir, '.dat'), function (err, files) {
// TODO: omg please make this less confusing.
var noDat = !!(err || !files.length)
hasDat = !noDat
var validSleep = (files && files.length && files.indexOf('metadata.key') > -1)
var badDat = !(noDat || validSleep)
if ((noDat || validSleep) && createAfterValid) return create()
else if (badDat) return cb(oldError)
if (err && !createIfMissing) return cb(missingError)
else if (!err && errorIfExists) return cb(existsError)
return create()
})
}
|
[
"function",
"checkIfExists",
"(",
")",
"{",
"// Create after we check for pre-sleep .dat stuff",
"var",
"createAfterValid",
"=",
"(",
"createIfMissing",
"&&",
"!",
"errorIfExists",
")",
"var",
"missingError",
"=",
"new",
"Error",
"(",
"'Dat storage does not exist.'",
")",
"missingError",
".",
"name",
"=",
"'MissingError'",
"var",
"existsError",
"=",
"new",
"Error",
"(",
"'Dat storage already exists.'",
")",
"existsError",
".",
"name",
"=",
"'ExistsError'",
"var",
"oldError",
"=",
"new",
"Error",
"(",
"'Dat folder contains incompatible metadata. Please remove your metadata (rm -rf .dat).'",
")",
"oldError",
".",
"name",
"=",
"'IncompatibleError'",
"fs",
".",
"readdir",
"(",
"path",
".",
"join",
"(",
"opts",
".",
"dir",
",",
"'.dat'",
")",
",",
"function",
"(",
"err",
",",
"files",
")",
"{",
"// TODO: omg please make this less confusing.",
"var",
"noDat",
"=",
"!",
"!",
"(",
"err",
"||",
"!",
"files",
".",
"length",
")",
"hasDat",
"=",
"!",
"noDat",
"var",
"validSleep",
"=",
"(",
"files",
"&&",
"files",
".",
"length",
"&&",
"files",
".",
"indexOf",
"(",
"'metadata.key'",
")",
">",
"-",
"1",
")",
"var",
"badDat",
"=",
"!",
"(",
"noDat",
"||",
"validSleep",
")",
"if",
"(",
"(",
"noDat",
"||",
"validSleep",
")",
"&&",
"createAfterValid",
")",
"return",
"create",
"(",
")",
"else",
"if",
"(",
"badDat",
")",
"return",
"cb",
"(",
"oldError",
")",
"if",
"(",
"err",
"&&",
"!",
"createIfMissing",
")",
"return",
"cb",
"(",
"missingError",
")",
"else",
"if",
"(",
"!",
"err",
"&&",
"errorIfExists",
")",
"return",
"cb",
"(",
"existsError",
")",
"return",
"create",
"(",
")",
"}",
")",
"}"
] |
Check if archive storage folder exists.
@private
|
[
"Check",
"if",
"archive",
"storage",
"folder",
"exists",
"."
] |
c5f377309ead92cbef57f726795e2d85e0720b24
|
https://github.com/datproject/dat-node/blob/c5f377309ead92cbef57f726795e2d85e0720b24/index.js#L52-L78
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.