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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
15,000
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/driver.js
|
callMethod
|
function callMethod(name, params) {
return (methodCache.has(name) || typeof params === 'undefined')
? asyncCall(name, params)
: cacheCall(name, params);
}
|
javascript
|
function callMethod(name, params) {
return (methodCache.has(name) || typeof params === 'undefined')
? asyncCall(name, params)
: cacheCall(name, params);
}
|
[
"function",
"callMethod",
"(",
"name",
",",
"params",
")",
"{",
"return",
"(",
"methodCache",
".",
"has",
"(",
"name",
")",
"||",
"typeof",
"params",
"===",
"'undefined'",
")",
"?",
"asyncCall",
"(",
"name",
",",
"params",
")",
":",
"cacheCall",
"(",
"name",
",",
"params",
")",
";",
"}"
] |
Call a method as async via Asteroid, or through cache if one is created.
If the method doesn't have or need parameters, it can't use them for caching
so it will always call asynchronously.
@param name The Rocket.Chat server method to call
@param params Single or array of parameters of the method to call
|
[
"Call",
"a",
"method",
"as",
"async",
"via",
"Asteroid",
"or",
"through",
"cache",
"if",
"one",
"is",
"created",
".",
"If",
"the",
"method",
"doesn",
"t",
"have",
"or",
"need",
"parameters",
"it",
"can",
"t",
"use",
"them",
"for",
"caching",
"so",
"it",
"will",
"always",
"call",
"asynchronously",
"."
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/driver.js#L172-L176
|
15,001
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/driver.js
|
cacheCall
|
function cacheCall(method, key) {
return methodCache.call(method, key)
.catch((err) => {
log_1.logger.error(`[${method}] Error:`, err);
throw err; // throw after log to stop async chain
})
.then((result) => {
(result)
? log_1.logger.debug(`[${method}] Success: ${JSON.stringify(result)}`)
: log_1.logger.debug(`[${method}] Success`);
return result;
});
}
|
javascript
|
function cacheCall(method, key) {
return methodCache.call(method, key)
.catch((err) => {
log_1.logger.error(`[${method}] Error:`, err);
throw err; // throw after log to stop async chain
})
.then((result) => {
(result)
? log_1.logger.debug(`[${method}] Success: ${JSON.stringify(result)}`)
: log_1.logger.debug(`[${method}] Success`);
return result;
});
}
|
[
"function",
"cacheCall",
"(",
"method",
",",
"key",
")",
"{",
"return",
"methodCache",
".",
"call",
"(",
"method",
",",
"key",
")",
".",
"catch",
"(",
"(",
"err",
")",
"=>",
"{",
"log_1",
".",
"logger",
".",
"error",
"(",
"`",
"${",
"method",
"}",
"`",
",",
"err",
")",
";",
"throw",
"err",
";",
"// throw after log to stop async chain",
"}",
")",
".",
"then",
"(",
"(",
"result",
")",
"=>",
"{",
"(",
"result",
")",
"?",
"log_1",
".",
"logger",
".",
"debug",
"(",
"`",
"${",
"method",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"result",
")",
"}",
"`",
")",
":",
"log_1",
".",
"logger",
".",
"debug",
"(",
"`",
"${",
"method",
"}",
"`",
")",
";",
"return",
"result",
";",
"}",
")",
";",
"}"
] |
Wraps Asteroid method calls, passed through method cache if cache is valid.
@param method The Rocket.Chat server method, to call through Asteroid
@param key Single string parameters only, required to use as cache key
|
[
"Wraps",
"Asteroid",
"method",
"calls",
"passed",
"through",
"method",
"cache",
"if",
"cache",
"is",
"valid",
"."
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/driver.js#L183-L195
|
15,002
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/driver.js
|
logout
|
function logout() {
return exports.asteroid.logout()
.catch((err) => {
log_1.logger.error('[Logout] Error:', err);
throw err; // throw after log to stop async chain
});
}
|
javascript
|
function logout() {
return exports.asteroid.logout()
.catch((err) => {
log_1.logger.error('[Logout] Error:', err);
throw err; // throw after log to stop async chain
});
}
|
[
"function",
"logout",
"(",
")",
"{",
"return",
"exports",
".",
"asteroid",
".",
"logout",
"(",
")",
".",
"catch",
"(",
"(",
"err",
")",
"=>",
"{",
"log_1",
".",
"logger",
".",
"error",
"(",
"'[Logout] Error:'",
",",
"err",
")",
";",
"throw",
"err",
";",
"// throw after log to stop async chain",
"}",
")",
";",
"}"
] |
Logout of Rocket.Chat via Asteroid
|
[
"Logout",
"of",
"Rocket",
".",
"Chat",
"via",
"Asteroid"
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/driver.js#L229-L235
|
15,003
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/driver.js
|
unsubscribe
|
function unsubscribe(subscription) {
const index = exports.subscriptions.indexOf(subscription);
if (index === -1)
return;
subscription.stop();
// asteroid.unsubscribe(subscription.id) // v2
exports.subscriptions.splice(index, 1); // remove from collection
log_1.logger.info(`[${subscription.id}] Unsubscribed`);
}
|
javascript
|
function unsubscribe(subscription) {
const index = exports.subscriptions.indexOf(subscription);
if (index === -1)
return;
subscription.stop();
// asteroid.unsubscribe(subscription.id) // v2
exports.subscriptions.splice(index, 1); // remove from collection
log_1.logger.info(`[${subscription.id}] Unsubscribed`);
}
|
[
"function",
"unsubscribe",
"(",
"subscription",
")",
"{",
"const",
"index",
"=",
"exports",
".",
"subscriptions",
".",
"indexOf",
"(",
"subscription",
")",
";",
"if",
"(",
"index",
"===",
"-",
"1",
")",
"return",
";",
"subscription",
".",
"stop",
"(",
")",
";",
"// asteroid.unsubscribe(subscription.id) // v2",
"exports",
".",
"subscriptions",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"// remove from collection",
"log_1",
".",
"logger",
".",
"info",
"(",
"`",
"${",
"subscription",
".",
"id",
"}",
"`",
")",
";",
"}"
] |
Unsubscribe from Meteor subscription
|
[
"Unsubscribe",
"from",
"Meteor",
"subscription"
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/driver.js#L256-L264
|
15,004
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/driver.js
|
subscribeToMessages
|
function subscribeToMessages() {
return subscribe(_messageCollectionName, _messageStreamName)
.then((subscription) => {
exports.messages = exports.asteroid.getCollection(_messageCollectionName);
return subscription;
});
}
|
javascript
|
function subscribeToMessages() {
return subscribe(_messageCollectionName, _messageStreamName)
.then((subscription) => {
exports.messages = exports.asteroid.getCollection(_messageCollectionName);
return subscription;
});
}
|
[
"function",
"subscribeToMessages",
"(",
")",
"{",
"return",
"subscribe",
"(",
"_messageCollectionName",
",",
"_messageStreamName",
")",
".",
"then",
"(",
"(",
"subscription",
")",
"=>",
"{",
"exports",
".",
"messages",
"=",
"exports",
".",
"asteroid",
".",
"getCollection",
"(",
"_messageCollectionName",
")",
";",
"return",
"subscription",
";",
"}",
")",
";",
"}"
] |
Begin subscription to room events for user.
Older adapters used an option for this method but it was always the default.
|
[
"Begin",
"subscription",
"to",
"room",
"events",
"for",
"user",
".",
"Older",
"adapters",
"used",
"an",
"option",
"for",
"this",
"method",
"but",
"it",
"was",
"always",
"the",
"default",
"."
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/driver.js#L275-L281
|
15,005
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/driver.js
|
respondToMessages
|
function respondToMessages(callback, options = {}) {
const config = Object.assign({}, settings, options);
// return value, may be replaced by async ops
let promise = Promise.resolve();
// Join configured rooms if they haven't been already, unless listening to all
// public rooms, in which case it doesn't matter
if (!config.allPublic &&
exports.joinedIds.length === 0 &&
config.rooms &&
config.rooms.length > 0) {
promise = joinRooms(config.rooms)
.catch((err) => {
log_1.logger.error(`[joinRooms] Failed to join configured rooms (${config.rooms.join(', ')}): ${err.message}`);
});
}
exports.lastReadTime = new Date(); // init before any message read
reactToMessages((err, message, meta) => __awaiter(this, void 0, void 0, function* () {
if (err) {
log_1.logger.error(`[received] Unable to receive: ${err.message}`);
callback(err); // bubble errors back to adapter
}
// Ignore bot's own messages
if (message.u._id === exports.userId)
return;
// Ignore DMs unless configured not to
const isDM = meta.roomType === 'd';
if (isDM && !config.dm)
return;
// Ignore Livechat unless configured not to
const isLC = meta.roomType === 'l';
if (isLC && !config.livechat)
return;
// Ignore messages in un-joined public rooms unless configured not to
if (!config.allPublic && !isDM && !meta.roomParticipant)
return;
// Set current time for comparison to incoming
let currentReadTime = new Date(message.ts.$date);
// Ignore edited messages if configured to
if (!config.edited && message.editedAt)
return;
// Set read time as time of edit, if message is edited
if (message.editedAt)
currentReadTime = new Date(message.editedAt.$date);
// Ignore messages in stream that aren't new
if (currentReadTime <= exports.lastReadTime)
return;
// At this point, message has passed checks and can be responded to
log_1.logger.info(`[received] Message ${message._id} from ${message.u.username}`);
exports.lastReadTime = currentReadTime;
// Processing completed, call callback to respond to message
callback(null, message, meta);
}));
return promise;
}
|
javascript
|
function respondToMessages(callback, options = {}) {
const config = Object.assign({}, settings, options);
// return value, may be replaced by async ops
let promise = Promise.resolve();
// Join configured rooms if they haven't been already, unless listening to all
// public rooms, in which case it doesn't matter
if (!config.allPublic &&
exports.joinedIds.length === 0 &&
config.rooms &&
config.rooms.length > 0) {
promise = joinRooms(config.rooms)
.catch((err) => {
log_1.logger.error(`[joinRooms] Failed to join configured rooms (${config.rooms.join(', ')}): ${err.message}`);
});
}
exports.lastReadTime = new Date(); // init before any message read
reactToMessages((err, message, meta) => __awaiter(this, void 0, void 0, function* () {
if (err) {
log_1.logger.error(`[received] Unable to receive: ${err.message}`);
callback(err); // bubble errors back to adapter
}
// Ignore bot's own messages
if (message.u._id === exports.userId)
return;
// Ignore DMs unless configured not to
const isDM = meta.roomType === 'd';
if (isDM && !config.dm)
return;
// Ignore Livechat unless configured not to
const isLC = meta.roomType === 'l';
if (isLC && !config.livechat)
return;
// Ignore messages in un-joined public rooms unless configured not to
if (!config.allPublic && !isDM && !meta.roomParticipant)
return;
// Set current time for comparison to incoming
let currentReadTime = new Date(message.ts.$date);
// Ignore edited messages if configured to
if (!config.edited && message.editedAt)
return;
// Set read time as time of edit, if message is edited
if (message.editedAt)
currentReadTime = new Date(message.editedAt.$date);
// Ignore messages in stream that aren't new
if (currentReadTime <= exports.lastReadTime)
return;
// At this point, message has passed checks and can be responded to
log_1.logger.info(`[received] Message ${message._id} from ${message.u.username}`);
exports.lastReadTime = currentReadTime;
// Processing completed, call callback to respond to message
callback(null, message, meta);
}));
return promise;
}
|
[
"function",
"respondToMessages",
"(",
"callback",
",",
"options",
"=",
"{",
"}",
")",
"{",
"const",
"config",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"settings",
",",
"options",
")",
";",
"// return value, may be replaced by async ops",
"let",
"promise",
"=",
"Promise",
".",
"resolve",
"(",
")",
";",
"// Join configured rooms if they haven't been already, unless listening to all",
"// public rooms, in which case it doesn't matter",
"if",
"(",
"!",
"config",
".",
"allPublic",
"&&",
"exports",
".",
"joinedIds",
".",
"length",
"===",
"0",
"&&",
"config",
".",
"rooms",
"&&",
"config",
".",
"rooms",
".",
"length",
">",
"0",
")",
"{",
"promise",
"=",
"joinRooms",
"(",
"config",
".",
"rooms",
")",
".",
"catch",
"(",
"(",
"err",
")",
"=>",
"{",
"log_1",
".",
"logger",
".",
"error",
"(",
"`",
"${",
"config",
".",
"rooms",
".",
"join",
"(",
"', '",
")",
"}",
"${",
"err",
".",
"message",
"}",
"`",
")",
";",
"}",
")",
";",
"}",
"exports",
".",
"lastReadTime",
"=",
"new",
"Date",
"(",
")",
";",
"// init before any message read",
"reactToMessages",
"(",
"(",
"err",
",",
"message",
",",
"meta",
")",
"=>",
"__awaiter",
"(",
"this",
",",
"void",
"0",
",",
"void",
"0",
",",
"function",
"*",
"(",
")",
"{",
"if",
"(",
"err",
")",
"{",
"log_1",
".",
"logger",
".",
"error",
"(",
"`",
"${",
"err",
".",
"message",
"}",
"`",
")",
";",
"callback",
"(",
"err",
")",
";",
"// bubble errors back to adapter",
"}",
"// Ignore bot's own messages",
"if",
"(",
"message",
".",
"u",
".",
"_id",
"===",
"exports",
".",
"userId",
")",
"return",
";",
"// Ignore DMs unless configured not to",
"const",
"isDM",
"=",
"meta",
".",
"roomType",
"===",
"'d'",
";",
"if",
"(",
"isDM",
"&&",
"!",
"config",
".",
"dm",
")",
"return",
";",
"// Ignore Livechat unless configured not to",
"const",
"isLC",
"=",
"meta",
".",
"roomType",
"===",
"'l'",
";",
"if",
"(",
"isLC",
"&&",
"!",
"config",
".",
"livechat",
")",
"return",
";",
"// Ignore messages in un-joined public rooms unless configured not to",
"if",
"(",
"!",
"config",
".",
"allPublic",
"&&",
"!",
"isDM",
"&&",
"!",
"meta",
".",
"roomParticipant",
")",
"return",
";",
"// Set current time for comparison to incoming",
"let",
"currentReadTime",
"=",
"new",
"Date",
"(",
"message",
".",
"ts",
".",
"$date",
")",
";",
"// Ignore edited messages if configured to",
"if",
"(",
"!",
"config",
".",
"edited",
"&&",
"message",
".",
"editedAt",
")",
"return",
";",
"// Set read time as time of edit, if message is edited",
"if",
"(",
"message",
".",
"editedAt",
")",
"currentReadTime",
"=",
"new",
"Date",
"(",
"message",
".",
"editedAt",
".",
"$date",
")",
";",
"// Ignore messages in stream that aren't new",
"if",
"(",
"currentReadTime",
"<=",
"exports",
".",
"lastReadTime",
")",
"return",
";",
"// At this point, message has passed checks and can be responded to",
"log_1",
".",
"logger",
".",
"info",
"(",
"`",
"${",
"message",
".",
"_id",
"}",
"${",
"message",
".",
"u",
".",
"username",
"}",
"`",
")",
";",
"exports",
".",
"lastReadTime",
"=",
"currentReadTime",
";",
"// Processing completed, call callback to respond to message",
"callback",
"(",
"null",
",",
"message",
",",
"meta",
")",
";",
"}",
")",
")",
";",
"return",
"promise",
";",
"}"
] |
Proxy for `reactToMessages` with some filtering of messages based on config.
@param callback Function called after filters run on subscription events.
- Uses error-first callback pattern
- Second argument is the changed item
- Third argument is additional attributes, such as `roomType`
@param options Sets filters for different event/message types.
|
[
"Proxy",
"for",
"reactToMessages",
"with",
"some",
"filtering",
"of",
"messages",
"based",
"on",
"config",
"."
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/driver.js#L335-L388
|
15,006
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/driver.js
|
leaveRoom
|
function leaveRoom(room) {
return __awaiter(this, void 0, void 0, function* () {
let roomId = yield getRoomId(room);
let joinedIndex = exports.joinedIds.indexOf(room);
if (joinedIndex === -1) {
log_1.logger.error(`[leaveRoom] failed because bot has not joined ${room}`);
}
else {
yield asyncCall('leaveRoom', roomId);
delete exports.joinedIds[joinedIndex];
}
});
}
|
javascript
|
function leaveRoom(room) {
return __awaiter(this, void 0, void 0, function* () {
let roomId = yield getRoomId(room);
let joinedIndex = exports.joinedIds.indexOf(room);
if (joinedIndex === -1) {
log_1.logger.error(`[leaveRoom] failed because bot has not joined ${room}`);
}
else {
yield asyncCall('leaveRoom', roomId);
delete exports.joinedIds[joinedIndex];
}
});
}
|
[
"function",
"leaveRoom",
"(",
"room",
")",
"{",
"return",
"__awaiter",
"(",
"this",
",",
"void",
"0",
",",
"void",
"0",
",",
"function",
"*",
"(",
")",
"{",
"let",
"roomId",
"=",
"yield",
"getRoomId",
"(",
"room",
")",
";",
"let",
"joinedIndex",
"=",
"exports",
".",
"joinedIds",
".",
"indexOf",
"(",
"room",
")",
";",
"if",
"(",
"joinedIndex",
"===",
"-",
"1",
")",
"{",
"log_1",
".",
"logger",
".",
"error",
"(",
"`",
"${",
"room",
"}",
"`",
")",
";",
"}",
"else",
"{",
"yield",
"asyncCall",
"(",
"'leaveRoom'",
",",
"roomId",
")",
";",
"delete",
"exports",
".",
"joinedIds",
"[",
"joinedIndex",
"]",
";",
"}",
"}",
")",
";",
"}"
] |
Exit a room the bot has joined
|
[
"Exit",
"a",
"room",
"the",
"bot",
"has",
"joined"
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/driver.js#L428-L440
|
15,007
|
RocketChat/Rocket.Chat.js.SDK
|
dist/lib/driver.js
|
prepareMessage
|
function prepareMessage(content, roomId) {
const message = new message_1.Message(content, exports.integrationId);
if (roomId)
message.setRoomId(roomId);
return message;
}
|
javascript
|
function prepareMessage(content, roomId) {
const message = new message_1.Message(content, exports.integrationId);
if (roomId)
message.setRoomId(roomId);
return message;
}
|
[
"function",
"prepareMessage",
"(",
"content",
",",
"roomId",
")",
"{",
"const",
"message",
"=",
"new",
"message_1",
".",
"Message",
"(",
"content",
",",
"exports",
".",
"integrationId",
")",
";",
"if",
"(",
"roomId",
")",
"message",
".",
"setRoomId",
"(",
"roomId",
")",
";",
"return",
"message",
";",
"}"
] |
Structure message content, optionally addressing to room ID.
Accepts message text string or a structured message object.
|
[
"Structure",
"message",
"content",
"optionally",
"addressing",
"to",
"room",
"ID",
".",
"Accepts",
"message",
"text",
"string",
"or",
"a",
"structured",
"message",
"object",
"."
] |
3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6
|
https://github.com/RocketChat/Rocket.Chat.js.SDK/blob/3ebfbff3d6354b3e6dcb9f579c36d6433484a5f6/dist/lib/driver.js#L451-L456
|
15,008
|
MeisterTR/ioBroker.landroid-s
|
lib/utils.js
|
getControllerDir
|
function getControllerDir(isInstall) {
var fs = require('fs');
// Find the js-controller location
var controllerDir = __dirname.replace(/\\/g, '/');
controllerDir = controllerDir.split('/');
if (controllerDir[controllerDir.length - 3] === 'adapter') {
controllerDir.splice(controllerDir.length - 3, 3);
controllerDir = controllerDir.join('/');
} else if (controllerDir[controllerDir.length - 3] === 'node_modules') {
controllerDir.splice(controllerDir.length - 3, 3);
controllerDir = controllerDir.join('/');
if (fs.existsSync(controllerDir + '/node_modules/' + appName + '.js-controller')) {
controllerDir += '/node_modules/' + appName + '.js-controller';
} else if (fs.existsSync(controllerDir + '/node_modules/' + appName.toLowerCase() + '.js-controller')) {
controllerDir += '/node_modules/' + appName.toLowerCase() + '.js-controller';
} else if (!fs.existsSync(controllerDir + '/controller.js')) {
if (!isInstall) {
console.log('Cannot find js-controller');
process.exit(10);
} else {
process.exit();
}
}
} else if (fs.existsSync(__dirname + '/../../node_modules/' + appName.toLowerCase() + '.js-controller')) {
controllerDir.splice(controllerDir.length - 2, 2);
return controllerDir.join('/') + '/node_modules/' + appName.toLowerCase() + '.js-controller';
} else {
if (!isInstall) {
console.log('Cannot find js-controller');
process.exit(10);
} else {
process.exit();
}
}
return controllerDir;
}
|
javascript
|
function getControllerDir(isInstall) {
var fs = require('fs');
// Find the js-controller location
var controllerDir = __dirname.replace(/\\/g, '/');
controllerDir = controllerDir.split('/');
if (controllerDir[controllerDir.length - 3] === 'adapter') {
controllerDir.splice(controllerDir.length - 3, 3);
controllerDir = controllerDir.join('/');
} else if (controllerDir[controllerDir.length - 3] === 'node_modules') {
controllerDir.splice(controllerDir.length - 3, 3);
controllerDir = controllerDir.join('/');
if (fs.existsSync(controllerDir + '/node_modules/' + appName + '.js-controller')) {
controllerDir += '/node_modules/' + appName + '.js-controller';
} else if (fs.existsSync(controllerDir + '/node_modules/' + appName.toLowerCase() + '.js-controller')) {
controllerDir += '/node_modules/' + appName.toLowerCase() + '.js-controller';
} else if (!fs.existsSync(controllerDir + '/controller.js')) {
if (!isInstall) {
console.log('Cannot find js-controller');
process.exit(10);
} else {
process.exit();
}
}
} else if (fs.existsSync(__dirname + '/../../node_modules/' + appName.toLowerCase() + '.js-controller')) {
controllerDir.splice(controllerDir.length - 2, 2);
return controllerDir.join('/') + '/node_modules/' + appName.toLowerCase() + '.js-controller';
} else {
if (!isInstall) {
console.log('Cannot find js-controller');
process.exit(10);
} else {
process.exit();
}
}
return controllerDir;
}
|
[
"function",
"getControllerDir",
"(",
"isInstall",
")",
"{",
"var",
"fs",
"=",
"require",
"(",
"'fs'",
")",
";",
"// Find the js-controller location\r",
"var",
"controllerDir",
"=",
"__dirname",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'/'",
")",
";",
"controllerDir",
"=",
"controllerDir",
".",
"split",
"(",
"'/'",
")",
";",
"if",
"(",
"controllerDir",
"[",
"controllerDir",
".",
"length",
"-",
"3",
"]",
"===",
"'adapter'",
")",
"{",
"controllerDir",
".",
"splice",
"(",
"controllerDir",
".",
"length",
"-",
"3",
",",
"3",
")",
";",
"controllerDir",
"=",
"controllerDir",
".",
"join",
"(",
"'/'",
")",
";",
"}",
"else",
"if",
"(",
"controllerDir",
"[",
"controllerDir",
".",
"length",
"-",
"3",
"]",
"===",
"'node_modules'",
")",
"{",
"controllerDir",
".",
"splice",
"(",
"controllerDir",
".",
"length",
"-",
"3",
",",
"3",
")",
";",
"controllerDir",
"=",
"controllerDir",
".",
"join",
"(",
"'/'",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"controllerDir",
"+",
"'/node_modules/'",
"+",
"appName",
"+",
"'.js-controller'",
")",
")",
"{",
"controllerDir",
"+=",
"'/node_modules/'",
"+",
"appName",
"+",
"'.js-controller'",
";",
"}",
"else",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"controllerDir",
"+",
"'/node_modules/'",
"+",
"appName",
".",
"toLowerCase",
"(",
")",
"+",
"'.js-controller'",
")",
")",
"{",
"controllerDir",
"+=",
"'/node_modules/'",
"+",
"appName",
".",
"toLowerCase",
"(",
")",
"+",
"'.js-controller'",
";",
"}",
"else",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"controllerDir",
"+",
"'/controller.js'",
")",
")",
"{",
"if",
"(",
"!",
"isInstall",
")",
"{",
"console",
".",
"log",
"(",
"'Cannot find js-controller'",
")",
";",
"process",
".",
"exit",
"(",
"10",
")",
";",
"}",
"else",
"{",
"process",
".",
"exit",
"(",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"__dirname",
"+",
"'/../../node_modules/'",
"+",
"appName",
".",
"toLowerCase",
"(",
")",
"+",
"'.js-controller'",
")",
")",
"{",
"controllerDir",
".",
"splice",
"(",
"controllerDir",
".",
"length",
"-",
"2",
",",
"2",
")",
";",
"return",
"controllerDir",
".",
"join",
"(",
"'/'",
")",
"+",
"'/node_modules/'",
"+",
"appName",
".",
"toLowerCase",
"(",
")",
"+",
"'.js-controller'",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"isInstall",
")",
"{",
"console",
".",
"log",
"(",
"'Cannot find js-controller'",
")",
";",
"process",
".",
"exit",
"(",
"10",
")",
";",
"}",
"else",
"{",
"process",
".",
"exit",
"(",
")",
";",
"}",
"}",
"return",
"controllerDir",
";",
"}"
] |
Get js-controller directory to load libs
|
[
"Get",
"js",
"-",
"controller",
"directory",
"to",
"load",
"libs"
] |
51494d79f0dca674783af2d4284288181ea99683
|
https://github.com/MeisterTR/ioBroker.landroid-s/blob/51494d79f0dca674783af2d4284288181ea99683/lib/utils.js#L10-L45
|
15,009
|
MeisterTR/ioBroker.landroid-s
|
lib/utils.js
|
getConfig
|
function getConfig() {
var fs = require('fs');
if (fs.existsSync(controllerDir + '/conf/' + appName + '.json')) {
return JSON.parse(fs.readFileSync(controllerDir + '/conf/' + appName + '.json'));
} else if (fs.existsSync(controllerDir + '/conf/' + appName.toLowerCase() + '.json')) {
return JSON.parse(fs.readFileSync(controllerDir + '/conf/' + appName.toLowerCase() + '.json'));
} else {
throw new Error('Cannot find ' + controllerDir + '/conf/' + appName + '.json');
}
}
|
javascript
|
function getConfig() {
var fs = require('fs');
if (fs.existsSync(controllerDir + '/conf/' + appName + '.json')) {
return JSON.parse(fs.readFileSync(controllerDir + '/conf/' + appName + '.json'));
} else if (fs.existsSync(controllerDir + '/conf/' + appName.toLowerCase() + '.json')) {
return JSON.parse(fs.readFileSync(controllerDir + '/conf/' + appName.toLowerCase() + '.json'));
} else {
throw new Error('Cannot find ' + controllerDir + '/conf/' + appName + '.json');
}
}
|
[
"function",
"getConfig",
"(",
")",
"{",
"var",
"fs",
"=",
"require",
"(",
"'fs'",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"controllerDir",
"+",
"'/conf/'",
"+",
"appName",
"+",
"'.json'",
")",
")",
"{",
"return",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"controllerDir",
"+",
"'/conf/'",
"+",
"appName",
"+",
"'.json'",
")",
")",
";",
"}",
"else",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"controllerDir",
"+",
"'/conf/'",
"+",
"appName",
".",
"toLowerCase",
"(",
")",
"+",
"'.json'",
")",
")",
"{",
"return",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"controllerDir",
"+",
"'/conf/'",
"+",
"appName",
".",
"toLowerCase",
"(",
")",
"+",
"'.json'",
")",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Cannot find '",
"+",
"controllerDir",
"+",
"'/conf/'",
"+",
"appName",
"+",
"'.json'",
")",
";",
"}",
"}"
] |
Read controller configuration file
|
[
"Read",
"controller",
"configuration",
"file"
] |
51494d79f0dca674783af2d4284288181ea99683
|
https://github.com/MeisterTR/ioBroker.landroid-s/blob/51494d79f0dca674783af2d4284288181ea99683/lib/utils.js#L48-L57
|
15,010
|
heigeo/leaflet.wms
|
lib/leaflet.js
|
function (remove) {
if (!L.DomEvent) { return; }
this._targets = {};
this._targets[L.stamp(this._container)] = this;
var onOff = remove ? 'off' : 'on';
// @event click: MouseEvent
// Fired when the user clicks (or taps) the map.
// @event dblclick: MouseEvent
// Fired when the user double-clicks (or double-taps) the map.
// @event mousedown: MouseEvent
// Fired when the user pushes the mouse button on the map.
// @event mouseup: MouseEvent
// Fired when the user releases the mouse button on the map.
// @event mouseover: MouseEvent
// Fired when the mouse enters the map.
// @event mouseout: MouseEvent
// Fired when the mouse leaves the map.
// @event mousemove: MouseEvent
// Fired while the mouse moves over the map.
// @event contextmenu: MouseEvent
// Fired when the user pushes the right mouse button on the map, prevents
// default browser context menu from showing if there are listeners on
// this event. Also fired on mobile when the user holds a single touch
// for a second (also called long press).
// @event keypress: Event
// Fired when the user presses a key from the keyboard while the map is focused.
L.DomEvent[onOff](this._container, 'click dblclick mousedown mouseup ' +
'mouseover mouseout mousemove contextmenu keypress', this._handleDOMEvent, this);
if (this.options.trackResize) {
L.DomEvent[onOff](window, 'resize', this._onResize, this);
}
if (L.Browser.any3d && this.options.transform3DLimit) {
this[onOff]('moveend', this._onMoveEnd);
}
}
|
javascript
|
function (remove) {
if (!L.DomEvent) { return; }
this._targets = {};
this._targets[L.stamp(this._container)] = this;
var onOff = remove ? 'off' : 'on';
// @event click: MouseEvent
// Fired when the user clicks (or taps) the map.
// @event dblclick: MouseEvent
// Fired when the user double-clicks (or double-taps) the map.
// @event mousedown: MouseEvent
// Fired when the user pushes the mouse button on the map.
// @event mouseup: MouseEvent
// Fired when the user releases the mouse button on the map.
// @event mouseover: MouseEvent
// Fired when the mouse enters the map.
// @event mouseout: MouseEvent
// Fired when the mouse leaves the map.
// @event mousemove: MouseEvent
// Fired while the mouse moves over the map.
// @event contextmenu: MouseEvent
// Fired when the user pushes the right mouse button on the map, prevents
// default browser context menu from showing if there are listeners on
// this event. Also fired on mobile when the user holds a single touch
// for a second (also called long press).
// @event keypress: Event
// Fired when the user presses a key from the keyboard while the map is focused.
L.DomEvent[onOff](this._container, 'click dblclick mousedown mouseup ' +
'mouseover mouseout mousemove contextmenu keypress', this._handleDOMEvent, this);
if (this.options.trackResize) {
L.DomEvent[onOff](window, 'resize', this._onResize, this);
}
if (L.Browser.any3d && this.options.transform3DLimit) {
this[onOff]('moveend', this._onMoveEnd);
}
}
|
[
"function",
"(",
"remove",
")",
"{",
"if",
"(",
"!",
"L",
".",
"DomEvent",
")",
"{",
"return",
";",
"}",
"this",
".",
"_targets",
"=",
"{",
"}",
";",
"this",
".",
"_targets",
"[",
"L",
".",
"stamp",
"(",
"this",
".",
"_container",
")",
"]",
"=",
"this",
";",
"var",
"onOff",
"=",
"remove",
"?",
"'off'",
":",
"'on'",
";",
"// @event click: MouseEvent\r",
"// Fired when the user clicks (or taps) the map.\r",
"// @event dblclick: MouseEvent\r",
"// Fired when the user double-clicks (or double-taps) the map.\r",
"// @event mousedown: MouseEvent\r",
"// Fired when the user pushes the mouse button on the map.\r",
"// @event mouseup: MouseEvent\r",
"// Fired when the user releases the mouse button on the map.\r",
"// @event mouseover: MouseEvent\r",
"// Fired when the mouse enters the map.\r",
"// @event mouseout: MouseEvent\r",
"// Fired when the mouse leaves the map.\r",
"// @event mousemove: MouseEvent\r",
"// Fired while the mouse moves over the map.\r",
"// @event contextmenu: MouseEvent\r",
"// Fired when the user pushes the right mouse button on the map, prevents\r",
"// default browser context menu from showing if there are listeners on\r",
"// this event. Also fired on mobile when the user holds a single touch\r",
"// for a second (also called long press).\r",
"// @event keypress: Event\r",
"// Fired when the user presses a key from the keyboard while the map is focused.\r",
"L",
".",
"DomEvent",
"[",
"onOff",
"]",
"(",
"this",
".",
"_container",
",",
"'click dblclick mousedown mouseup '",
"+",
"'mouseover mouseout mousemove contextmenu keypress'",
",",
"this",
".",
"_handleDOMEvent",
",",
"this",
")",
";",
"if",
"(",
"this",
".",
"options",
".",
"trackResize",
")",
"{",
"L",
".",
"DomEvent",
"[",
"onOff",
"]",
"(",
"window",
",",
"'resize'",
",",
"this",
".",
"_onResize",
",",
"this",
")",
";",
"}",
"if",
"(",
"L",
".",
"Browser",
".",
"any3d",
"&&",
"this",
".",
"options",
".",
"transform3DLimit",
")",
"{",
"this",
"[",
"onOff",
"]",
"(",
"'moveend'",
",",
"this",
".",
"_onMoveEnd",
")",
";",
"}",
"}"
] |
DOM event handling @section Interaction events
|
[
"DOM",
"event",
"handling"
] |
1f3542158b1743a681b375e3853cd147af742d91
|
https://github.com/heigeo/leaflet.wms/blob/1f3542158b1743a681b375e3853cd147af742d91/lib/leaflet.js#L3185-L3224
|
|
15,011
|
heigeo/leaflet.wms
|
lib/leaflet.js
|
function (center, zoom, bounds) {
if (!bounds) { return center; }
var centerPoint = this.project(center, zoom),
viewHalf = this.getSize().divideBy(2),
viewBounds = new L.Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
offset = this._getBoundsOffset(viewBounds, bounds, zoom);
// If offset is less than a pixel, ignore.
// This prevents unstable projections from getting into
// an infinite loop of tiny offsets.
if (offset.round().equals([0, 0])) {
return center;
}
return this.unproject(centerPoint.add(offset), zoom);
}
|
javascript
|
function (center, zoom, bounds) {
if (!bounds) { return center; }
var centerPoint = this.project(center, zoom),
viewHalf = this.getSize().divideBy(2),
viewBounds = new L.Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
offset = this._getBoundsOffset(viewBounds, bounds, zoom);
// If offset is less than a pixel, ignore.
// This prevents unstable projections from getting into
// an infinite loop of tiny offsets.
if (offset.round().equals([0, 0])) {
return center;
}
return this.unproject(centerPoint.add(offset), zoom);
}
|
[
"function",
"(",
"center",
",",
"zoom",
",",
"bounds",
")",
"{",
"if",
"(",
"!",
"bounds",
")",
"{",
"return",
"center",
";",
"}",
"var",
"centerPoint",
"=",
"this",
".",
"project",
"(",
"center",
",",
"zoom",
")",
",",
"viewHalf",
"=",
"this",
".",
"getSize",
"(",
")",
".",
"divideBy",
"(",
"2",
")",
",",
"viewBounds",
"=",
"new",
"L",
".",
"Bounds",
"(",
"centerPoint",
".",
"subtract",
"(",
"viewHalf",
")",
",",
"centerPoint",
".",
"add",
"(",
"viewHalf",
")",
")",
",",
"offset",
"=",
"this",
".",
"_getBoundsOffset",
"(",
"viewBounds",
",",
"bounds",
",",
"zoom",
")",
";",
"// If offset is less than a pixel, ignore.\r",
"// This prevents unstable projections from getting into\r",
"// an infinite loop of tiny offsets.\r",
"if",
"(",
"offset",
".",
"round",
"(",
")",
".",
"equals",
"(",
"[",
"0",
",",
"0",
"]",
")",
")",
"{",
"return",
"center",
";",
"}",
"return",
"this",
".",
"unproject",
"(",
"centerPoint",
".",
"add",
"(",
"offset",
")",
",",
"zoom",
")",
";",
"}"
] |
adjust center for view to get inside bounds
|
[
"adjust",
"center",
"for",
"view",
"to",
"get",
"inside",
"bounds"
] |
1f3542158b1743a681b375e3853cd147af742d91
|
https://github.com/heigeo/leaflet.wms/blob/1f3542158b1743a681b375e3853cd147af742d91/lib/leaflet.js#L3397-L3414
|
|
15,012
|
heigeo/leaflet.wms
|
lib/leaflet.js
|
function (center) {
var map = this._map;
if (!map) { return; }
var zoom = map.getZoom();
if (center === undefined) { center = map.getCenter(); }
if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
var pixelBounds = this._getTiledPixelBounds(center),
tileRange = this._pxBoundsToTileRange(pixelBounds),
tileCenter = tileRange.getCenter(),
queue = [],
margin = this.options.keepBuffer,
noPruneRange = new L.Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
tileRange.getTopRight().add([margin, -margin]));
for (var key in this._tiles) {
var c = this._tiles[key].coords;
if (c.z !== this._tileZoom || !noPruneRange.contains(L.point(c.x, c.y))) {
this._tiles[key].current = false;
}
}
// _update just loads more tiles. If the tile zoom level differs too much
// from the map's, let _setView reset levels and prune old tiles.
if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
// create a queue of coordinates to load tiles from
for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
var coords = new L.Point(i, j);
coords.z = this._tileZoom;
if (!this._isValidTile(coords)) { continue; }
var tile = this._tiles[this._tileCoordsToKey(coords)];
if (tile) {
tile.current = true;
} else {
queue.push(coords);
}
}
}
// sort tile queue to load tiles in order of their distance to center
queue.sort(function (a, b) {
return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
});
if (queue.length !== 0) {
// if its the first batch of tiles to load
if (!this._loading) {
this._loading = true;
// @event loading: Event
// Fired when the grid layer starts loading tiles.
this.fire('loading');
}
// create DOM fragment to append tiles in one batch
var fragment = document.createDocumentFragment();
for (i = 0; i < queue.length; i++) {
this._addTile(queue[i], fragment);
}
this._level.el.appendChild(fragment);
}
}
|
javascript
|
function (center) {
var map = this._map;
if (!map) { return; }
var zoom = map.getZoom();
if (center === undefined) { center = map.getCenter(); }
if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
var pixelBounds = this._getTiledPixelBounds(center),
tileRange = this._pxBoundsToTileRange(pixelBounds),
tileCenter = tileRange.getCenter(),
queue = [],
margin = this.options.keepBuffer,
noPruneRange = new L.Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
tileRange.getTopRight().add([margin, -margin]));
for (var key in this._tiles) {
var c = this._tiles[key].coords;
if (c.z !== this._tileZoom || !noPruneRange.contains(L.point(c.x, c.y))) {
this._tiles[key].current = false;
}
}
// _update just loads more tiles. If the tile zoom level differs too much
// from the map's, let _setView reset levels and prune old tiles.
if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
// create a queue of coordinates to load tiles from
for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
var coords = new L.Point(i, j);
coords.z = this._tileZoom;
if (!this._isValidTile(coords)) { continue; }
var tile = this._tiles[this._tileCoordsToKey(coords)];
if (tile) {
tile.current = true;
} else {
queue.push(coords);
}
}
}
// sort tile queue to load tiles in order of their distance to center
queue.sort(function (a, b) {
return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
});
if (queue.length !== 0) {
// if its the first batch of tiles to load
if (!this._loading) {
this._loading = true;
// @event loading: Event
// Fired when the grid layer starts loading tiles.
this.fire('loading');
}
// create DOM fragment to append tiles in one batch
var fragment = document.createDocumentFragment();
for (i = 0; i < queue.length; i++) {
this._addTile(queue[i], fragment);
}
this._level.el.appendChild(fragment);
}
}
|
[
"function",
"(",
"center",
")",
"{",
"var",
"map",
"=",
"this",
".",
"_map",
";",
"if",
"(",
"!",
"map",
")",
"{",
"return",
";",
"}",
"var",
"zoom",
"=",
"map",
".",
"getZoom",
"(",
")",
";",
"if",
"(",
"center",
"===",
"undefined",
")",
"{",
"center",
"=",
"map",
".",
"getCenter",
"(",
")",
";",
"}",
"if",
"(",
"this",
".",
"_tileZoom",
"===",
"undefined",
")",
"{",
"return",
";",
"}",
"// if out of minzoom/maxzoom",
"var",
"pixelBounds",
"=",
"this",
".",
"_getTiledPixelBounds",
"(",
"center",
")",
",",
"tileRange",
"=",
"this",
".",
"_pxBoundsToTileRange",
"(",
"pixelBounds",
")",
",",
"tileCenter",
"=",
"tileRange",
".",
"getCenter",
"(",
")",
",",
"queue",
"=",
"[",
"]",
",",
"margin",
"=",
"this",
".",
"options",
".",
"keepBuffer",
",",
"noPruneRange",
"=",
"new",
"L",
".",
"Bounds",
"(",
"tileRange",
".",
"getBottomLeft",
"(",
")",
".",
"subtract",
"(",
"[",
"margin",
",",
"-",
"margin",
"]",
")",
",",
"tileRange",
".",
"getTopRight",
"(",
")",
".",
"add",
"(",
"[",
"margin",
",",
"-",
"margin",
"]",
")",
")",
";",
"for",
"(",
"var",
"key",
"in",
"this",
".",
"_tiles",
")",
"{",
"var",
"c",
"=",
"this",
".",
"_tiles",
"[",
"key",
"]",
".",
"coords",
";",
"if",
"(",
"c",
".",
"z",
"!==",
"this",
".",
"_tileZoom",
"||",
"!",
"noPruneRange",
".",
"contains",
"(",
"L",
".",
"point",
"(",
"c",
".",
"x",
",",
"c",
".",
"y",
")",
")",
")",
"{",
"this",
".",
"_tiles",
"[",
"key",
"]",
".",
"current",
"=",
"false",
";",
"}",
"}",
"// _update just loads more tiles. If the tile zoom level differs too much",
"// from the map's, let _setView reset levels and prune old tiles.",
"if",
"(",
"Math",
".",
"abs",
"(",
"zoom",
"-",
"this",
".",
"_tileZoom",
")",
">",
"1",
")",
"{",
"this",
".",
"_setView",
"(",
"center",
",",
"zoom",
")",
";",
"return",
";",
"}",
"// create a queue of coordinates to load tiles from",
"for",
"(",
"var",
"j",
"=",
"tileRange",
".",
"min",
".",
"y",
";",
"j",
"<=",
"tileRange",
".",
"max",
".",
"y",
";",
"j",
"++",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"tileRange",
".",
"min",
".",
"x",
";",
"i",
"<=",
"tileRange",
".",
"max",
".",
"x",
";",
"i",
"++",
")",
"{",
"var",
"coords",
"=",
"new",
"L",
".",
"Point",
"(",
"i",
",",
"j",
")",
";",
"coords",
".",
"z",
"=",
"this",
".",
"_tileZoom",
";",
"if",
"(",
"!",
"this",
".",
"_isValidTile",
"(",
"coords",
")",
")",
"{",
"continue",
";",
"}",
"var",
"tile",
"=",
"this",
".",
"_tiles",
"[",
"this",
".",
"_tileCoordsToKey",
"(",
"coords",
")",
"]",
";",
"if",
"(",
"tile",
")",
"{",
"tile",
".",
"current",
"=",
"true",
";",
"}",
"else",
"{",
"queue",
".",
"push",
"(",
"coords",
")",
";",
"}",
"}",
"}",
"// sort tile queue to load tiles in order of their distance to center",
"queue",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
".",
"distanceTo",
"(",
"tileCenter",
")",
"-",
"b",
".",
"distanceTo",
"(",
"tileCenter",
")",
";",
"}",
")",
";",
"if",
"(",
"queue",
".",
"length",
"!==",
"0",
")",
"{",
"// if its the first batch of tiles to load",
"if",
"(",
"!",
"this",
".",
"_loading",
")",
"{",
"this",
".",
"_loading",
"=",
"true",
";",
"// @event loading: Event",
"// Fired when the grid layer starts loading tiles.",
"this",
".",
"fire",
"(",
"'loading'",
")",
";",
"}",
"// create DOM fragment to append tiles in one batch",
"var",
"fragment",
"=",
"document",
".",
"createDocumentFragment",
"(",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"queue",
".",
"length",
";",
"i",
"++",
")",
"{",
"this",
".",
"_addTile",
"(",
"queue",
"[",
"i",
"]",
",",
"fragment",
")",
";",
"}",
"this",
".",
"_level",
".",
"el",
".",
"appendChild",
"(",
"fragment",
")",
";",
"}",
"}"
] |
Private method to load tiles in the grid's active zoom level according to map bounds
|
[
"Private",
"method",
"to",
"load",
"tiles",
"in",
"the",
"grid",
"s",
"active",
"zoom",
"level",
"according",
"to",
"map",
"bounds"
] |
1f3542158b1743a681b375e3853cd147af742d91
|
https://github.com/heigeo/leaflet.wms/blob/1f3542158b1743a681b375e3853cd147af742d91/lib/leaflet.js#L4388-L4455
|
|
15,013
|
heigeo/leaflet.wms
|
lib/leaflet.js
|
function (coords) {
var map = this._map,
tileSize = this.getTileSize(),
nwPoint = coords.scaleBy(tileSize),
sePoint = nwPoint.add(tileSize),
nw = map.wrapLatLng(map.unproject(nwPoint, coords.z)),
se = map.wrapLatLng(map.unproject(sePoint, coords.z));
return new L.LatLngBounds(nw, se);
}
|
javascript
|
function (coords) {
var map = this._map,
tileSize = this.getTileSize(),
nwPoint = coords.scaleBy(tileSize),
sePoint = nwPoint.add(tileSize),
nw = map.wrapLatLng(map.unproject(nwPoint, coords.z)),
se = map.wrapLatLng(map.unproject(sePoint, coords.z));
return new L.LatLngBounds(nw, se);
}
|
[
"function",
"(",
"coords",
")",
"{",
"var",
"map",
"=",
"this",
".",
"_map",
",",
"tileSize",
"=",
"this",
".",
"getTileSize",
"(",
")",
",",
"nwPoint",
"=",
"coords",
".",
"scaleBy",
"(",
"tileSize",
")",
",",
"sePoint",
"=",
"nwPoint",
".",
"add",
"(",
"tileSize",
")",
",",
"nw",
"=",
"map",
".",
"wrapLatLng",
"(",
"map",
".",
"unproject",
"(",
"nwPoint",
",",
"coords",
".",
"z",
")",
")",
",",
"se",
"=",
"map",
".",
"wrapLatLng",
"(",
"map",
".",
"unproject",
"(",
"sePoint",
",",
"coords",
".",
"z",
")",
")",
";",
"return",
"new",
"L",
".",
"LatLngBounds",
"(",
"nw",
",",
"se",
")",
";",
"}"
] |
converts tile coordinates to its geographical bounds
|
[
"converts",
"tile",
"coordinates",
"to",
"its",
"geographical",
"bounds"
] |
1f3542158b1743a681b375e3853cd147af742d91
|
https://github.com/heigeo/leaflet.wms/blob/1f3542158b1743a681b375e3853cd147af742d91/lib/leaflet.js#L4479-L4491
|
|
15,014
|
heigeo/leaflet.wms
|
lib/leaflet.js
|
function (key) {
var k = key.split(':'),
coords = new L.Point(+k[0], +k[1]);
coords.z = +k[2];
return coords;
}
|
javascript
|
function (key) {
var k = key.split(':'),
coords = new L.Point(+k[0], +k[1]);
coords.z = +k[2];
return coords;
}
|
[
"function",
"(",
"key",
")",
"{",
"var",
"k",
"=",
"key",
".",
"split",
"(",
"':'",
")",
",",
"coords",
"=",
"new",
"L",
".",
"Point",
"(",
"+",
"k",
"[",
"0",
"]",
",",
"+",
"k",
"[",
"1",
"]",
")",
";",
"coords",
".",
"z",
"=",
"+",
"k",
"[",
"2",
"]",
";",
"return",
"coords",
";",
"}"
] |
converts tile cache key to coordinates
|
[
"converts",
"tile",
"cache",
"key",
"to",
"coordinates"
] |
1f3542158b1743a681b375e3853cd147af742d91
|
https://github.com/heigeo/leaflet.wms/blob/1f3542158b1743a681b375e3853cd147af742d91/lib/leaflet.js#L4499-L4504
|
|
15,015
|
heigeo/leaflet.wms
|
lib/leaflet.js
|
function (latlngs) {
var result = [],
flat = L.Polyline._flat(latlngs);
for (var i = 0, len = latlngs.length; i < len; i++) {
if (flat) {
result[i] = L.latLng(latlngs[i]);
this._bounds.extend(result[i]);
} else {
result[i] = this._convertLatLngs(latlngs[i]);
}
}
return result;
}
|
javascript
|
function (latlngs) {
var result = [],
flat = L.Polyline._flat(latlngs);
for (var i = 0, len = latlngs.length; i < len; i++) {
if (flat) {
result[i] = L.latLng(latlngs[i]);
this._bounds.extend(result[i]);
} else {
result[i] = this._convertLatLngs(latlngs[i]);
}
}
return result;
}
|
[
"function",
"(",
"latlngs",
")",
"{",
"var",
"result",
"=",
"[",
"]",
",",
"flat",
"=",
"L",
".",
"Polyline",
".",
"_flat",
"(",
"latlngs",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"latlngs",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"flat",
")",
"{",
"result",
"[",
"i",
"]",
"=",
"L",
".",
"latLng",
"(",
"latlngs",
"[",
"i",
"]",
")",
";",
"this",
".",
"_bounds",
".",
"extend",
"(",
"result",
"[",
"i",
"]",
")",
";",
"}",
"else",
"{",
"result",
"[",
"i",
"]",
"=",
"this",
".",
"_convertLatLngs",
"(",
"latlngs",
"[",
"i",
"]",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
|
[
"recursively",
"convert",
"latlngs",
"input",
"into",
"actual",
"LatLng",
"instances",
";",
"calculate",
"bounds",
"along",
"the",
"way"
] |
1f3542158b1743a681b375e3853cd147af742d91
|
https://github.com/heigeo/leaflet.wms/blob/1f3542158b1743a681b375e3853cd147af742d91/lib/leaflet.js#L7924-L7938
|
|
15,016
|
heigeo/leaflet.wms
|
lib/leaflet.js
|
function (latlngs, result, projectedBounds) {
var flat = latlngs[0] instanceof L.LatLng,
len = latlngs.length,
i, ring;
if (flat) {
ring = [];
for (i = 0; i < len; i++) {
ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
projectedBounds.extend(ring[i]);
}
result.push(ring);
} else {
for (i = 0; i < len; i++) {
this._projectLatlngs(latlngs[i], result, projectedBounds);
}
}
}
|
javascript
|
function (latlngs, result, projectedBounds) {
var flat = latlngs[0] instanceof L.LatLng,
len = latlngs.length,
i, ring;
if (flat) {
ring = [];
for (i = 0; i < len; i++) {
ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
projectedBounds.extend(ring[i]);
}
result.push(ring);
} else {
for (i = 0; i < len; i++) {
this._projectLatlngs(latlngs[i], result, projectedBounds);
}
}
}
|
[
"function",
"(",
"latlngs",
",",
"result",
",",
"projectedBounds",
")",
"{",
"var",
"flat",
"=",
"latlngs",
"[",
"0",
"]",
"instanceof",
"L",
".",
"LatLng",
",",
"len",
"=",
"latlngs",
".",
"length",
",",
"i",
",",
"ring",
";",
"if",
"(",
"flat",
")",
"{",
"ring",
"=",
"[",
"]",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"ring",
"[",
"i",
"]",
"=",
"this",
".",
"_map",
".",
"latLngToLayerPoint",
"(",
"latlngs",
"[",
"i",
"]",
")",
";",
"projectedBounds",
".",
"extend",
"(",
"ring",
"[",
"i",
"]",
")",
";",
"}",
"result",
".",
"push",
"(",
"ring",
")",
";",
"}",
"else",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"this",
".",
"_projectLatlngs",
"(",
"latlngs",
"[",
"i",
"]",
",",
"result",
",",
"projectedBounds",
")",
";",
"}",
"}",
"}"
] |
recursively turns latlngs into a set of rings with projected coordinates
|
[
"recursively",
"turns",
"latlngs",
"into",
"a",
"set",
"of",
"rings",
"with",
"projected",
"coordinates"
] |
1f3542158b1743a681b375e3853cd147af742d91
|
https://github.com/heigeo/leaflet.wms/blob/1f3542158b1743a681b375e3853cd147af742d91/lib/leaflet.js#L7956-L7973
|
|
15,017
|
heigeo/leaflet.wms
|
lib/leaflet.js
|
function () {
var bounds = this._renderer._bounds;
this._parts = [];
if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
return;
}
if (this.options.noClip) {
this._parts = this._rings;
return;
}
var parts = this._parts,
i, j, k, len, len2, segment, points;
for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
points = this._rings[i];
for (j = 0, len2 = points.length; j < len2 - 1; j++) {
segment = L.LineUtil.clipSegment(points[j], points[j + 1], bounds, j, true);
if (!segment) { continue; }
parts[k] = parts[k] || [];
parts[k].push(segment[0]);
// if segment goes out of screen, or it's the last one, it's the end of the line part
if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
parts[k].push(segment[1]);
k++;
}
}
}
}
|
javascript
|
function () {
var bounds = this._renderer._bounds;
this._parts = [];
if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
return;
}
if (this.options.noClip) {
this._parts = this._rings;
return;
}
var parts = this._parts,
i, j, k, len, len2, segment, points;
for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
points = this._rings[i];
for (j = 0, len2 = points.length; j < len2 - 1; j++) {
segment = L.LineUtil.clipSegment(points[j], points[j + 1], bounds, j, true);
if (!segment) { continue; }
parts[k] = parts[k] || [];
parts[k].push(segment[0]);
// if segment goes out of screen, or it's the last one, it's the end of the line part
if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
parts[k].push(segment[1]);
k++;
}
}
}
}
|
[
"function",
"(",
")",
"{",
"var",
"bounds",
"=",
"this",
".",
"_renderer",
".",
"_bounds",
";",
"this",
".",
"_parts",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"this",
".",
"_pxBounds",
"||",
"!",
"this",
".",
"_pxBounds",
".",
"intersects",
"(",
"bounds",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"this",
".",
"options",
".",
"noClip",
")",
"{",
"this",
".",
"_parts",
"=",
"this",
".",
"_rings",
";",
"return",
";",
"}",
"var",
"parts",
"=",
"this",
".",
"_parts",
",",
"i",
",",
"j",
",",
"k",
",",
"len",
",",
"len2",
",",
"segment",
",",
"points",
";",
"for",
"(",
"i",
"=",
"0",
",",
"k",
"=",
"0",
",",
"len",
"=",
"this",
".",
"_rings",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"points",
"=",
"this",
".",
"_rings",
"[",
"i",
"]",
";",
"for",
"(",
"j",
"=",
"0",
",",
"len2",
"=",
"points",
".",
"length",
";",
"j",
"<",
"len2",
"-",
"1",
";",
"j",
"++",
")",
"{",
"segment",
"=",
"L",
".",
"LineUtil",
".",
"clipSegment",
"(",
"points",
"[",
"j",
"]",
",",
"points",
"[",
"j",
"+",
"1",
"]",
",",
"bounds",
",",
"j",
",",
"true",
")",
";",
"if",
"(",
"!",
"segment",
")",
"{",
"continue",
";",
"}",
"parts",
"[",
"k",
"]",
"=",
"parts",
"[",
"k",
"]",
"||",
"[",
"]",
";",
"parts",
"[",
"k",
"]",
".",
"push",
"(",
"segment",
"[",
"0",
"]",
")",
";",
"// if segment goes out of screen, or it's the last one, it's the end of the line part",
"if",
"(",
"(",
"segment",
"[",
"1",
"]",
"!==",
"points",
"[",
"j",
"+",
"1",
"]",
")",
"||",
"(",
"j",
"===",
"len2",
"-",
"2",
")",
")",
"{",
"parts",
"[",
"k",
"]",
".",
"push",
"(",
"segment",
"[",
"1",
"]",
")",
";",
"k",
"++",
";",
"}",
"}",
"}",
"}"
] |
clip polyline by renderer bounds so that we have less to render for performance
|
[
"clip",
"polyline",
"by",
"renderer",
"bounds",
"so",
"that",
"we",
"have",
"less",
"to",
"render",
"for",
"performance"
] |
1f3542158b1743a681b375e3853cd147af742d91
|
https://github.com/heigeo/leaflet.wms/blob/1f3542158b1743a681b375e3853cd147af742d91/lib/leaflet.js#L7976-L8010
|
|
15,018
|
heigeo/leaflet.wms
|
lib/leaflet.js
|
function () {
var parts = this._parts,
tolerance = this.options.smoothFactor;
for (var i = 0, len = parts.length; i < len; i++) {
parts[i] = L.LineUtil.simplify(parts[i], tolerance);
}
}
|
javascript
|
function () {
var parts = this._parts,
tolerance = this.options.smoothFactor;
for (var i = 0, len = parts.length; i < len; i++) {
parts[i] = L.LineUtil.simplify(parts[i], tolerance);
}
}
|
[
"function",
"(",
")",
"{",
"var",
"parts",
"=",
"this",
".",
"_parts",
",",
"tolerance",
"=",
"this",
".",
"options",
".",
"smoothFactor",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"parts",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"parts",
"[",
"i",
"]",
"=",
"L",
".",
"LineUtil",
".",
"simplify",
"(",
"parts",
"[",
"i",
"]",
",",
"tolerance",
")",
";",
"}",
"}"
] |
simplify each clipped part of the polyline for performance
|
[
"simplify",
"each",
"clipped",
"part",
"of",
"the",
"polyline",
"for",
"performance"
] |
1f3542158b1743a681b375e3853cd147af742d91
|
https://github.com/heigeo/leaflet.wms/blob/1f3542158b1743a681b375e3853cd147af742d91/lib/leaflet.js#L8013-L8020
|
|
15,019
|
heigeo/leaflet.wms
|
lib/leaflet.js
|
function (layer) {
var path = layer._path = L.SVG.create('path');
// @namespace Path
// @option className: String = null
// Custom class name set on an element. Only for SVG renderer.
if (layer.options.className) {
L.DomUtil.addClass(path, layer.options.className);
}
if (layer.options.interactive) {
L.DomUtil.addClass(path, 'leaflet-interactive');
}
this._updateStyle(layer);
}
|
javascript
|
function (layer) {
var path = layer._path = L.SVG.create('path');
// @namespace Path
// @option className: String = null
// Custom class name set on an element. Only for SVG renderer.
if (layer.options.className) {
L.DomUtil.addClass(path, layer.options.className);
}
if (layer.options.interactive) {
L.DomUtil.addClass(path, 'leaflet-interactive');
}
this._updateStyle(layer);
}
|
[
"function",
"(",
"layer",
")",
"{",
"var",
"path",
"=",
"layer",
".",
"_path",
"=",
"L",
".",
"SVG",
".",
"create",
"(",
"'path'",
")",
";",
"// @namespace Path",
"// @option className: String = null",
"// Custom class name set on an element. Only for SVG renderer.",
"if",
"(",
"layer",
".",
"options",
".",
"className",
")",
"{",
"L",
".",
"DomUtil",
".",
"addClass",
"(",
"path",
",",
"layer",
".",
"options",
".",
"className",
")",
";",
"}",
"if",
"(",
"layer",
".",
"options",
".",
"interactive",
")",
"{",
"L",
".",
"DomUtil",
".",
"addClass",
"(",
"path",
",",
"'leaflet-interactive'",
")",
";",
"}",
"this",
".",
"_updateStyle",
"(",
"layer",
")",
";",
"}"
] |
methods below are called by vector layers implementations
|
[
"methods",
"below",
"are",
"called",
"by",
"vector",
"layers",
"implementations"
] |
1f3542158b1743a681b375e3853cd147af742d91
|
https://github.com/heigeo/leaflet.wms/blob/1f3542158b1743a681b375e3853cd147af742d91/lib/leaflet.js#L8605-L8620
|
|
15,020
|
heigeo/leaflet.wms
|
lib/leaflet.js
|
function (e, handler) {
var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),
elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
// are they closer together than 500ms yet more than 100ms?
// Android typically triggers them ~300ms apart while multiple listeners
// on the same event should be triggered far faster;
// or check if click is simulated on the element, and if it is, reject any non-simulated events
if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
L.DomEvent.stop(e);
return;
}
L.DomEvent._lastClick = timeStamp;
handler(e);
}
|
javascript
|
function (e, handler) {
var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),
elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
// are they closer together than 500ms yet more than 100ms?
// Android typically triggers them ~300ms apart while multiple listeners
// on the same event should be triggered far faster;
// or check if click is simulated on the element, and if it is, reject any non-simulated events
if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
L.DomEvent.stop(e);
return;
}
L.DomEvent._lastClick = timeStamp;
handler(e);
}
|
[
"function",
"(",
"e",
",",
"handler",
")",
"{",
"var",
"timeStamp",
"=",
"(",
"e",
".",
"timeStamp",
"||",
"(",
"e",
".",
"originalEvent",
"&&",
"e",
".",
"originalEvent",
".",
"timeStamp",
")",
")",
",",
"elapsed",
"=",
"L",
".",
"DomEvent",
".",
"_lastClick",
"&&",
"(",
"timeStamp",
"-",
"L",
".",
"DomEvent",
".",
"_lastClick",
")",
";",
"// are they closer together than 500ms yet more than 100ms?\r",
"// Android typically triggers them ~300ms apart while multiple listeners\r",
"// on the same event should be triggered far faster;\r",
"// or check if click is simulated on the element, and if it is, reject any non-simulated events\r",
"if",
"(",
"(",
"elapsed",
"&&",
"elapsed",
">",
"100",
"&&",
"elapsed",
"<",
"500",
")",
"||",
"(",
"e",
".",
"target",
".",
"_simulatedClick",
"&&",
"!",
"e",
".",
"_simulated",
")",
")",
"{",
"L",
".",
"DomEvent",
".",
"stop",
"(",
"e",
")",
";",
"return",
";",
"}",
"L",
".",
"DomEvent",
".",
"_lastClick",
"=",
"timeStamp",
";",
"handler",
"(",
"e",
")",
";",
"}"
] |
this is a horrible workaround for a bug in Android where a single touch triggers two click events
|
[
"this",
"is",
"a",
"horrible",
"workaround",
"for",
"a",
"bug",
"in",
"Android",
"where",
"a",
"single",
"touch",
"triggers",
"two",
"click",
"events"
] |
1f3542158b1743a681b375e3853cd147af742d91
|
https://github.com/heigeo/leaflet.wms/blob/1f3542158b1743a681b375e3853cd147af742d91/lib/leaflet.js#L9960-L9976
|
|
15,021
|
keen/explorer
|
lib/js/app/utils/ExplorerUtils.js
|
function(config) {
config.client
.query(config.query.analysis_type, _.omit(config.query, 'analysis_type'))
.then(function(res, err){
if (err) {
config.error(err);
}
else {
config.success(res);
}
if (config.complete) config.complete(err, res);
})
.catch(config.error);
}
|
javascript
|
function(config) {
config.client
.query(config.query.analysis_type, _.omit(config.query, 'analysis_type'))
.then(function(res, err){
if (err) {
config.error(err);
}
else {
config.success(res);
}
if (config.complete) config.complete(err, res);
})
.catch(config.error);
}
|
[
"function",
"(",
"config",
")",
"{",
"config",
".",
"client",
".",
"query",
"(",
"config",
".",
"query",
".",
"analysis_type",
",",
"_",
".",
"omit",
"(",
"config",
".",
"query",
",",
"'analysis_type'",
")",
")",
".",
"then",
"(",
"function",
"(",
"res",
",",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"config",
".",
"error",
"(",
"err",
")",
";",
"}",
"else",
"{",
"config",
".",
"success",
"(",
"res",
")",
";",
"}",
"if",
"(",
"config",
".",
"complete",
")",
"config",
".",
"complete",
"(",
"err",
",",
"res",
")",
";",
"}",
")",
".",
"catch",
"(",
"config",
".",
"error",
")",
";",
"}"
] |
Execures a Keen.js query with the provided client and query params, calling the
callbacks after execution.
@param {Object} config The runQuery configuration
Expected structure:
{
client: {The Keen.js client},
query: {The object with the query parameters},
success: {Success callback function},
error: {Error callback function},
complete: {Complete callback function}
}
@return {undefined}
|
[
"Execures",
"a",
"Keen",
".",
"js",
"query",
"with",
"the",
"provided",
"client",
"and",
"query",
"params",
"calling",
"the",
"callbacks",
"after",
"execution",
"."
] |
910765df704dfd38ef053a15a18a1e5fa3b6289e
|
https://github.com/keen/explorer/blob/910765df704dfd38ef053a15a18a1e5fa3b6289e/lib/js/app/utils/ExplorerUtils.js#L185-L198
|
|
15,022
|
keen/explorer
|
lib/js/app/stores/ExplorerStore.js
|
_getDefaultFilterCoercionType
|
function _getDefaultFilterCoercionType(explorer, filter) {
var propertyType = ProjectUtils.getPropertyType(
ProjectStore.getProject(),
explorer.query.event_collection,
filter.property_name);
var targetCoercionType = FormatUtils.coercionTypeForPropertyType(propertyType);
return targetCoercionType;
}
|
javascript
|
function _getDefaultFilterCoercionType(explorer, filter) {
var propertyType = ProjectUtils.getPropertyType(
ProjectStore.getProject(),
explorer.query.event_collection,
filter.property_name);
var targetCoercionType = FormatUtils.coercionTypeForPropertyType(propertyType);
return targetCoercionType;
}
|
[
"function",
"_getDefaultFilterCoercionType",
"(",
"explorer",
",",
"filter",
")",
"{",
"var",
"propertyType",
"=",
"ProjectUtils",
".",
"getPropertyType",
"(",
"ProjectStore",
".",
"getProject",
"(",
")",
",",
"explorer",
".",
"query",
".",
"event_collection",
",",
"filter",
".",
"property_name",
")",
";",
"var",
"targetCoercionType",
"=",
"FormatUtils",
".",
"coercionTypeForPropertyType",
"(",
"propertyType",
")",
";",
"return",
"targetCoercionType",
";",
"}"
] |
Get the default coercion type for this filter based off the filter's property_name's set type
in the project schema.
@param {Object} explorer The explorer model that the filter belongs to
@param {Object} filter The filter
@return {String} The default coercion type
|
[
"Get",
"the",
"default",
"coercion",
"type",
"for",
"this",
"filter",
"based",
"off",
"the",
"filter",
"s",
"property_name",
"s",
"set",
"type",
"in",
"the",
"project",
"schema",
"."
] |
910765df704dfd38ef053a15a18a1e5fa3b6289e
|
https://github.com/keen/explorer/blob/910765df704dfd38ef053a15a18a1e5fa3b6289e/lib/js/app/stores/ExplorerStore.js#L121-L128
|
15,023
|
keen/explorer
|
lib/js/app/stores/ExplorerStore.js
|
_prepareUpdates
|
function _prepareUpdates(explorer, updates) {
// TODO: We're assigning the response object directly onto the model so we
// don't have to loop through the (sometimes) massive response object.
function customizer(objValue, srcValue, key) {
if (_.isArray(objValue)) {
return srcValue;
} else if (key === 'time' && _.isPlainObject(objValue)) {
return srcValue;
}
}
var newModel = _.mergeWith({}, explorer, _.omit(updates, 'response'), customizer);
if (updates.response) newModel.response = updates.response;
// Check if the event collection has changed. Clear the property names if so.
if (updates.query && updates.query.event_collection && updates.query.event_collection !== explorer.query.event_collection) {
newModel.query.property_names = [];
}
if(newModel.query.analysis_type === 'funnel' && explorer.query.analysis_type !== 'funnel') {
newModel = _migrateToFunnel(explorer, newModel);
} else if(newModel.query.analysis_type !== 'funnel' && explorer.query.analysis_type === 'funnel') {
newModel = _migrateFromFunnel(explorer, newModel);
}
newModel = _removeInvalidFields(newModel);
return newModel;
}
|
javascript
|
function _prepareUpdates(explorer, updates) {
// TODO: We're assigning the response object directly onto the model so we
// don't have to loop through the (sometimes) massive response object.
function customizer(objValue, srcValue, key) {
if (_.isArray(objValue)) {
return srcValue;
} else if (key === 'time' && _.isPlainObject(objValue)) {
return srcValue;
}
}
var newModel = _.mergeWith({}, explorer, _.omit(updates, 'response'), customizer);
if (updates.response) newModel.response = updates.response;
// Check if the event collection has changed. Clear the property names if so.
if (updates.query && updates.query.event_collection && updates.query.event_collection !== explorer.query.event_collection) {
newModel.query.property_names = [];
}
if(newModel.query.analysis_type === 'funnel' && explorer.query.analysis_type !== 'funnel') {
newModel = _migrateToFunnel(explorer, newModel);
} else if(newModel.query.analysis_type !== 'funnel' && explorer.query.analysis_type === 'funnel') {
newModel = _migrateFromFunnel(explorer, newModel);
}
newModel = _removeInvalidFields(newModel);
return newModel;
}
|
[
"function",
"_prepareUpdates",
"(",
"explorer",
",",
"updates",
")",
"{",
"// TODO: We're assigning the response object directly onto the model so we",
"// don't have to loop through the (sometimes) massive response object.",
"function",
"customizer",
"(",
"objValue",
",",
"srcValue",
",",
"key",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"objValue",
")",
")",
"{",
"return",
"srcValue",
";",
"}",
"else",
"if",
"(",
"key",
"===",
"'time'",
"&&",
"_",
".",
"isPlainObject",
"(",
"objValue",
")",
")",
"{",
"return",
"srcValue",
";",
"}",
"}",
"var",
"newModel",
"=",
"_",
".",
"mergeWith",
"(",
"{",
"}",
",",
"explorer",
",",
"_",
".",
"omit",
"(",
"updates",
",",
"'response'",
")",
",",
"customizer",
")",
";",
"if",
"(",
"updates",
".",
"response",
")",
"newModel",
".",
"response",
"=",
"updates",
".",
"response",
";",
"// Check if the event collection has changed. Clear the property names if so.",
"if",
"(",
"updates",
".",
"query",
"&&",
"updates",
".",
"query",
".",
"event_collection",
"&&",
"updates",
".",
"query",
".",
"event_collection",
"!==",
"explorer",
".",
"query",
".",
"event_collection",
")",
"{",
"newModel",
".",
"query",
".",
"property_names",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"newModel",
".",
"query",
".",
"analysis_type",
"===",
"'funnel'",
"&&",
"explorer",
".",
"query",
".",
"analysis_type",
"!==",
"'funnel'",
")",
"{",
"newModel",
"=",
"_migrateToFunnel",
"(",
"explorer",
",",
"newModel",
")",
";",
"}",
"else",
"if",
"(",
"newModel",
".",
"query",
".",
"analysis_type",
"!==",
"'funnel'",
"&&",
"explorer",
".",
"query",
".",
"analysis_type",
"===",
"'funnel'",
")",
"{",
"newModel",
"=",
"_migrateFromFunnel",
"(",
"explorer",
",",
"newModel",
")",
";",
"}",
"newModel",
"=",
"_removeInvalidFields",
"(",
"newModel",
")",
";",
"return",
"newModel",
";",
"}"
] |
Runs through the changeset and moves data around if necessary
@param {Object} explorer The explorer model that is being updated
@param {Object} updates The updated explorer model
@return {Object} The new set of updates
|
[
"Runs",
"through",
"the",
"changeset",
"and",
"moves",
"data",
"around",
"if",
"necessary"
] |
910765df704dfd38ef053a15a18a1e5fa3b6289e
|
https://github.com/keen/explorer/blob/910765df704dfd38ef053a15a18a1e5fa3b6289e/lib/js/app/stores/ExplorerStore.js#L136-L162
|
15,024
|
keen/explorer
|
lib/js/app/stores/ExplorerStore.js
|
_migrateToFunnel
|
function _migrateToFunnel(explorer, newModel) {
var firstStep = _defaultStep();
firstStep.active = true;
_.each(SHARED_FUNNEL_STEP_PROPERTIES, function (key) {
if(!_.isUndefined(explorer.query[key]) && !_.isNull(explorer.query[key])) {
firstStep[key] = explorer.query[key]
}
newModel.query[key] = (key === 'filters') ? [] : null;
});
if(!_.isUndefined(explorer.query.target_property) && !_.isNull(explorer.query.target_property)) {
firstStep.actor_property = explorer.query.target_property;
explorer.query.target_property = null;
}
newModel.query.steps = [firstStep];
return newModel;
}
|
javascript
|
function _migrateToFunnel(explorer, newModel) {
var firstStep = _defaultStep();
firstStep.active = true;
_.each(SHARED_FUNNEL_STEP_PROPERTIES, function (key) {
if(!_.isUndefined(explorer.query[key]) && !_.isNull(explorer.query[key])) {
firstStep[key] = explorer.query[key]
}
newModel.query[key] = (key === 'filters') ? [] : null;
});
if(!_.isUndefined(explorer.query.target_property) && !_.isNull(explorer.query.target_property)) {
firstStep.actor_property = explorer.query.target_property;
explorer.query.target_property = null;
}
newModel.query.steps = [firstStep];
return newModel;
}
|
[
"function",
"_migrateToFunnel",
"(",
"explorer",
",",
"newModel",
")",
"{",
"var",
"firstStep",
"=",
"_defaultStep",
"(",
")",
";",
"firstStep",
".",
"active",
"=",
"true",
";",
"_",
".",
"each",
"(",
"SHARED_FUNNEL_STEP_PROPERTIES",
",",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isUndefined",
"(",
"explorer",
".",
"query",
"[",
"key",
"]",
")",
"&&",
"!",
"_",
".",
"isNull",
"(",
"explorer",
".",
"query",
"[",
"key",
"]",
")",
")",
"{",
"firstStep",
"[",
"key",
"]",
"=",
"explorer",
".",
"query",
"[",
"key",
"]",
"}",
"newModel",
".",
"query",
"[",
"key",
"]",
"=",
"(",
"key",
"===",
"'filters'",
")",
"?",
"[",
"]",
":",
"null",
";",
"}",
")",
";",
"if",
"(",
"!",
"_",
".",
"isUndefined",
"(",
"explorer",
".",
"query",
".",
"target_property",
")",
"&&",
"!",
"_",
".",
"isNull",
"(",
"explorer",
".",
"query",
".",
"target_property",
")",
")",
"{",
"firstStep",
".",
"actor_property",
"=",
"explorer",
".",
"query",
".",
"target_property",
";",
"explorer",
".",
"query",
".",
"target_property",
"=",
"null",
";",
"}",
"newModel",
".",
"query",
".",
"steps",
"=",
"[",
"firstStep",
"]",
";",
"return",
"newModel",
";",
"}"
] |
If the query got changed to a funnel, move the step-specific parameters to a steps object.
@param {Object} explorer The explorer model that is being updated
@param {Object} newModel The updated explorer model
@return {Object} The new set of updates
|
[
"If",
"the",
"query",
"got",
"changed",
"to",
"a",
"funnel",
"move",
"the",
"step",
"-",
"specific",
"parameters",
"to",
"a",
"steps",
"object",
"."
] |
910765df704dfd38ef053a15a18a1e5fa3b6289e
|
https://github.com/keen/explorer/blob/910765df704dfd38ef053a15a18a1e5fa3b6289e/lib/js/app/stores/ExplorerStore.js#L170-L190
|
15,025
|
keen/explorer
|
lib/js/app/stores/ExplorerStore.js
|
_migrateFromFunnel
|
function _migrateFromFunnel(explorer, newModel) {
if (explorer.query.steps.length < 1) return newModel;
var activeStep = _.find(explorer.query.steps, { active: true }) || explorer.query.steps[0];
_.each(SHARED_FUNNEL_STEP_PROPERTIES, function (key) {
if (!_.isUndefined(activeStep[key])) {
newModel.query[key] = activeStep[key];
}
});
if (!_.isNull(activeStep.actor_property) && ExplorerUtils.shouldHaveTarget(newModel)) {
newModel.query.target_property = activeStep.actor_property;
}
newModel.query.steps = [];
return newModel;
}
|
javascript
|
function _migrateFromFunnel(explorer, newModel) {
if (explorer.query.steps.length < 1) return newModel;
var activeStep = _.find(explorer.query.steps, { active: true }) || explorer.query.steps[0];
_.each(SHARED_FUNNEL_STEP_PROPERTIES, function (key) {
if (!_.isUndefined(activeStep[key])) {
newModel.query[key] = activeStep[key];
}
});
if (!_.isNull(activeStep.actor_property) && ExplorerUtils.shouldHaveTarget(newModel)) {
newModel.query.target_property = activeStep.actor_property;
}
newModel.query.steps = [];
return newModel;
}
|
[
"function",
"_migrateFromFunnel",
"(",
"explorer",
",",
"newModel",
")",
"{",
"if",
"(",
"explorer",
".",
"query",
".",
"steps",
".",
"length",
"<",
"1",
")",
"return",
"newModel",
";",
"var",
"activeStep",
"=",
"_",
".",
"find",
"(",
"explorer",
".",
"query",
".",
"steps",
",",
"{",
"active",
":",
"true",
"}",
")",
"||",
"explorer",
".",
"query",
".",
"steps",
"[",
"0",
"]",
";",
"_",
".",
"each",
"(",
"SHARED_FUNNEL_STEP_PROPERTIES",
",",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isUndefined",
"(",
"activeStep",
"[",
"key",
"]",
")",
")",
"{",
"newModel",
".",
"query",
"[",
"key",
"]",
"=",
"activeStep",
"[",
"key",
"]",
";",
"}",
"}",
")",
";",
"if",
"(",
"!",
"_",
".",
"isNull",
"(",
"activeStep",
".",
"actor_property",
")",
"&&",
"ExplorerUtils",
".",
"shouldHaveTarget",
"(",
"newModel",
")",
")",
"{",
"newModel",
".",
"query",
".",
"target_property",
"=",
"activeStep",
".",
"actor_property",
";",
"}",
"newModel",
".",
"query",
".",
"steps",
"=",
"[",
"]",
";",
"return",
"newModel",
";",
"}"
] |
If the query got changed from a funnel, move the applicable parameters out to the root query
@param {Object} explorer The explorer model that is being updated
@param {Object} newModel The updated explorer model
@return {Object} The new set of updates
|
[
"If",
"the",
"query",
"got",
"changed",
"from",
"a",
"funnel",
"move",
"the",
"applicable",
"parameters",
"out",
"to",
"the",
"root",
"query"
] |
910765df704dfd38ef053a15a18a1e5fa3b6289e
|
https://github.com/keen/explorer/blob/910765df704dfd38ef053a15a18a1e5fa3b6289e/lib/js/app/stores/ExplorerStore.js#L198-L215
|
15,026
|
keen/explorer
|
lib/js/app/stores/ExplorerStore.js
|
_removeInvalidFields
|
function _removeInvalidFields(newModel) {
if (!ExplorerUtils.isEmailExtraction(newModel)) {
newModel.query.latest = null;
newModel.query.email = null;
}
if (newModel.query.analysis_type === 'extraction') {
newModel.query.group_by = null;
newModel.query.order_by = null;
newModel.query.limit = null;
newModel.query.interval = null;
}
if (newModel.query.analysis_type !== 'extraction') {
newModel.query.latest = null;
}
if (newModel.query.analysis_type !== 'percentile') {
newModel.query.percentile = null;
}
if (_.includes(['count', 'extraction', 'funnel'], newModel.query.analysis_type)) {
newModel.query.target_property = null;
}
if (newModel.query.analysis_type !== 'funnel') {
newModel.query.steps = [];
}
if(newModel.query.analysis_type === 'funnel') {
newModel.query.filters = [];
newModel.query.time = null;
newModel.query.timezone = null;
newModel.query.group_by = null;
newModel.query.order_by = null;
newModel.query.limit = null;
newModel.query.timeframe = null;
newModel.query.interval = null;
}
return newModel;
}
|
javascript
|
function _removeInvalidFields(newModel) {
if (!ExplorerUtils.isEmailExtraction(newModel)) {
newModel.query.latest = null;
newModel.query.email = null;
}
if (newModel.query.analysis_type === 'extraction') {
newModel.query.group_by = null;
newModel.query.order_by = null;
newModel.query.limit = null;
newModel.query.interval = null;
}
if (newModel.query.analysis_type !== 'extraction') {
newModel.query.latest = null;
}
if (newModel.query.analysis_type !== 'percentile') {
newModel.query.percentile = null;
}
if (_.includes(['count', 'extraction', 'funnel'], newModel.query.analysis_type)) {
newModel.query.target_property = null;
}
if (newModel.query.analysis_type !== 'funnel') {
newModel.query.steps = [];
}
if(newModel.query.analysis_type === 'funnel') {
newModel.query.filters = [];
newModel.query.time = null;
newModel.query.timezone = null;
newModel.query.group_by = null;
newModel.query.order_by = null;
newModel.query.limit = null;
newModel.query.timeframe = null;
newModel.query.interval = null;
}
return newModel;
}
|
[
"function",
"_removeInvalidFields",
"(",
"newModel",
")",
"{",
"if",
"(",
"!",
"ExplorerUtils",
".",
"isEmailExtraction",
"(",
"newModel",
")",
")",
"{",
"newModel",
".",
"query",
".",
"latest",
"=",
"null",
";",
"newModel",
".",
"query",
".",
"email",
"=",
"null",
";",
"}",
"if",
"(",
"newModel",
".",
"query",
".",
"analysis_type",
"===",
"'extraction'",
")",
"{",
"newModel",
".",
"query",
".",
"group_by",
"=",
"null",
";",
"newModel",
".",
"query",
".",
"order_by",
"=",
"null",
";",
"newModel",
".",
"query",
".",
"limit",
"=",
"null",
";",
"newModel",
".",
"query",
".",
"interval",
"=",
"null",
";",
"}",
"if",
"(",
"newModel",
".",
"query",
".",
"analysis_type",
"!==",
"'extraction'",
")",
"{",
"newModel",
".",
"query",
".",
"latest",
"=",
"null",
";",
"}",
"if",
"(",
"newModel",
".",
"query",
".",
"analysis_type",
"!==",
"'percentile'",
")",
"{",
"newModel",
".",
"query",
".",
"percentile",
"=",
"null",
";",
"}",
"if",
"(",
"_",
".",
"includes",
"(",
"[",
"'count'",
",",
"'extraction'",
",",
"'funnel'",
"]",
",",
"newModel",
".",
"query",
".",
"analysis_type",
")",
")",
"{",
"newModel",
".",
"query",
".",
"target_property",
"=",
"null",
";",
"}",
"if",
"(",
"newModel",
".",
"query",
".",
"analysis_type",
"!==",
"'funnel'",
")",
"{",
"newModel",
".",
"query",
".",
"steps",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"newModel",
".",
"query",
".",
"analysis_type",
"===",
"'funnel'",
")",
"{",
"newModel",
".",
"query",
".",
"filters",
"=",
"[",
"]",
";",
"newModel",
".",
"query",
".",
"time",
"=",
"null",
";",
"newModel",
".",
"query",
".",
"timezone",
"=",
"null",
";",
"newModel",
".",
"query",
".",
"group_by",
"=",
"null",
";",
"newModel",
".",
"query",
".",
"order_by",
"=",
"null",
";",
"newModel",
".",
"query",
".",
"limit",
"=",
"null",
";",
"newModel",
".",
"query",
".",
"timeframe",
"=",
"null",
";",
"newModel",
".",
"query",
".",
"interval",
"=",
"null",
";",
"}",
"return",
"newModel",
";",
"}"
] |
Removes fields from the query that aren't valid given the new analysis type.
@param {Object} newModel The updated explorer model
@return {Object} The new set of updates
|
[
"Removes",
"fields",
"from",
"the",
"query",
"that",
"aren",
"t",
"valid",
"given",
"the",
"new",
"analysis",
"type",
"."
] |
910765df704dfd38ef053a15a18a1e5fa3b6289e
|
https://github.com/keen/explorer/blob/910765df704dfd38ef053a15a18a1e5fa3b6289e/lib/js/app/stores/ExplorerStore.js#L222-L256
|
15,027
|
keen/explorer
|
lib/js/app/stores/ExplorerStore.js
|
_prepareFilterUpdates
|
function _prepareFilterUpdates(explorer, filter, updates) {
if (updates.property_name && updates.property_name !== filter.property_name) {
if (filter.operator === 'exists') {
updates.coercion_type = 'Boolean';
} else {
// No need to update the operator - we allow any operator for any property type right now.
updates.coercion_type = _getDefaultFilterCoercionType(explorer, _.merge({}, filter, updates));
}
}
else if (updates.operator && updates.operator !== filter.operator) {
var newOp = updates.operator;
if (newOp === 'in') updates.coercion_type = 'List';
if (newOp === 'exists') updates.coercion_type = 'Boolean';
if (newOp === 'within') updates.coercion_type = 'Geo';
// If it's not any of these operators, we still need to make sure that the current coercion_type is available
// as an option for this new operator.
var coercionOptions = _.find(ProjectUtils.getConstant('FILTER_OPERATORS'), { value: updates.operator }).canBeCoeredTo;
var coercion_type = updates.coercion_type || filter.coercion_type;
if (!_.includes(coercionOptions, coercion_type)) {
updates.coercion_type = coercionOptions[0];
}
}
if (updates.coercion_type === 'Geo' && filter.coercion_type !== 'Geo') {
updates.property_value = _defaultGeoFilter();
}
updates.property_value = FilterUtils.getCoercedValue(_.merge({}, filter, updates));
return updates;
}
|
javascript
|
function _prepareFilterUpdates(explorer, filter, updates) {
if (updates.property_name && updates.property_name !== filter.property_name) {
if (filter.operator === 'exists') {
updates.coercion_type = 'Boolean';
} else {
// No need to update the operator - we allow any operator for any property type right now.
updates.coercion_type = _getDefaultFilterCoercionType(explorer, _.merge({}, filter, updates));
}
}
else if (updates.operator && updates.operator !== filter.operator) {
var newOp = updates.operator;
if (newOp === 'in') updates.coercion_type = 'List';
if (newOp === 'exists') updates.coercion_type = 'Boolean';
if (newOp === 'within') updates.coercion_type = 'Geo';
// If it's not any of these operators, we still need to make sure that the current coercion_type is available
// as an option for this new operator.
var coercionOptions = _.find(ProjectUtils.getConstant('FILTER_OPERATORS'), { value: updates.operator }).canBeCoeredTo;
var coercion_type = updates.coercion_type || filter.coercion_type;
if (!_.includes(coercionOptions, coercion_type)) {
updates.coercion_type = coercionOptions[0];
}
}
if (updates.coercion_type === 'Geo' && filter.coercion_type !== 'Geo') {
updates.property_value = _defaultGeoFilter();
}
updates.property_value = FilterUtils.getCoercedValue(_.merge({}, filter, updates));
return updates;
}
|
[
"function",
"_prepareFilterUpdates",
"(",
"explorer",
",",
"filter",
",",
"updates",
")",
"{",
"if",
"(",
"updates",
".",
"property_name",
"&&",
"updates",
".",
"property_name",
"!==",
"filter",
".",
"property_name",
")",
"{",
"if",
"(",
"filter",
".",
"operator",
"===",
"'exists'",
")",
"{",
"updates",
".",
"coercion_type",
"=",
"'Boolean'",
";",
"}",
"else",
"{",
"// No need to update the operator - we allow any operator for any property type right now.",
"updates",
".",
"coercion_type",
"=",
"_getDefaultFilterCoercionType",
"(",
"explorer",
",",
"_",
".",
"merge",
"(",
"{",
"}",
",",
"filter",
",",
"updates",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"updates",
".",
"operator",
"&&",
"updates",
".",
"operator",
"!==",
"filter",
".",
"operator",
")",
"{",
"var",
"newOp",
"=",
"updates",
".",
"operator",
";",
"if",
"(",
"newOp",
"===",
"'in'",
")",
"updates",
".",
"coercion_type",
"=",
"'List'",
";",
"if",
"(",
"newOp",
"===",
"'exists'",
")",
"updates",
".",
"coercion_type",
"=",
"'Boolean'",
";",
"if",
"(",
"newOp",
"===",
"'within'",
")",
"updates",
".",
"coercion_type",
"=",
"'Geo'",
";",
"// If it's not any of these operators, we still need to make sure that the current coercion_type is available",
"// as an option for this new operator.",
"var",
"coercionOptions",
"=",
"_",
".",
"find",
"(",
"ProjectUtils",
".",
"getConstant",
"(",
"'FILTER_OPERATORS'",
")",
",",
"{",
"value",
":",
"updates",
".",
"operator",
"}",
")",
".",
"canBeCoeredTo",
";",
"var",
"coercion_type",
"=",
"updates",
".",
"coercion_type",
"||",
"filter",
".",
"coercion_type",
";",
"if",
"(",
"!",
"_",
".",
"includes",
"(",
"coercionOptions",
",",
"coercion_type",
")",
")",
"{",
"updates",
".",
"coercion_type",
"=",
"coercionOptions",
"[",
"0",
"]",
";",
"}",
"}",
"if",
"(",
"updates",
".",
"coercion_type",
"===",
"'Geo'",
"&&",
"filter",
".",
"coercion_type",
"!==",
"'Geo'",
")",
"{",
"updates",
".",
"property_value",
"=",
"_defaultGeoFilter",
"(",
")",
";",
"}",
"updates",
".",
"property_value",
"=",
"FilterUtils",
".",
"getCoercedValue",
"(",
"_",
".",
"merge",
"(",
"{",
"}",
",",
"filter",
",",
"updates",
")",
")",
";",
"return",
"updates",
";",
"}"
] |
Looks at updates about to be made to a filter and performs a series of operations to
change the filter values depending on the coercion_type, operator and type of property_value.
@param {Object} explorer The explorer model that owns the filter to be updated
@param {Object} filter The filter to be updated
@param {Object} updates The updates to be made to the filter
@return {Object} The updated version of the filter after the changes have been made to it.
|
[
"Looks",
"at",
"updates",
"about",
"to",
"be",
"made",
"to",
"a",
"filter",
"and",
"performs",
"a",
"series",
"of",
"operations",
"to",
"change",
"the",
"filter",
"values",
"depending",
"on",
"the",
"coercion_type",
"operator",
"and",
"type",
"of",
"property_value",
"."
] |
910765df704dfd38ef053a15a18a1e5fa3b6289e
|
https://github.com/keen/explorer/blob/910765df704dfd38ef053a15a18a1e5fa3b6289e/lib/js/app/stores/ExplorerStore.js#L266-L297
|
15,028
|
ember-fastboot/ember-cli-fastboot
|
lib/build-utilities/migrate-initializers.js
|
_migrateAddonInitializers
|
function _migrateAddonInitializers(project) {
project.addons.forEach(addon => {
const currentAddonPath = addon.root;
_checkBrowserInitializers(currentAddonPath);
_moveFastBootInitializers(project, currentAddonPath);
});
}
|
javascript
|
function _migrateAddonInitializers(project) {
project.addons.forEach(addon => {
const currentAddonPath = addon.root;
_checkBrowserInitializers(currentAddonPath);
_moveFastBootInitializers(project, currentAddonPath);
});
}
|
[
"function",
"_migrateAddonInitializers",
"(",
"project",
")",
"{",
"project",
".",
"addons",
".",
"forEach",
"(",
"addon",
"=>",
"{",
"const",
"currentAddonPath",
"=",
"addon",
".",
"root",
";",
"_checkBrowserInitializers",
"(",
"currentAddonPath",
")",
";",
"_moveFastBootInitializers",
"(",
"project",
",",
"currentAddonPath",
")",
";",
"}",
")",
";",
"}"
] |
Function that migrates the fastboot initializers for all addons.
@param {Object} project
|
[
"Function",
"that",
"migrates",
"the",
"fastboot",
"initializers",
"for",
"all",
"addons",
"."
] |
9a8856b08ffbd32443a69b3de1077a53a0a931e3
|
https://github.com/ember-fastboot/ember-cli-fastboot/blob/9a8856b08ffbd32443a69b3de1077a53a0a931e3/lib/build-utilities/migrate-initializers.js#L91-L98
|
15,029
|
ember-fastboot/ember-cli-fastboot
|
lib/build-utilities/migrate-initializers.js
|
_migrateHostAppInitializers
|
function _migrateHostAppInitializers(project) {
const hostAppPath = path.join(project.root);
_checkBrowserInitializers(hostAppPath);
_moveFastBootInitializers(project, hostAppPath);
}
|
javascript
|
function _migrateHostAppInitializers(project) {
const hostAppPath = path.join(project.root);
_checkBrowserInitializers(hostAppPath);
_moveFastBootInitializers(project, hostAppPath);
}
|
[
"function",
"_migrateHostAppInitializers",
"(",
"project",
")",
"{",
"const",
"hostAppPath",
"=",
"path",
".",
"join",
"(",
"project",
".",
"root",
")",
";",
"_checkBrowserInitializers",
"(",
"hostAppPath",
")",
";",
"_moveFastBootInitializers",
"(",
"project",
",",
"hostAppPath",
")",
";",
"}"
] |
Function to migrate fastboot initializers for host app.
@param {Object} project
|
[
"Function",
"to",
"migrate",
"fastboot",
"initializers",
"for",
"host",
"app",
"."
] |
9a8856b08ffbd32443a69b3de1077a53a0a931e3
|
https://github.com/ember-fastboot/ember-cli-fastboot/blob/9a8856b08ffbd32443a69b3de1077a53a0a931e3/lib/build-utilities/migrate-initializers.js#L105-L110
|
15,030
|
angular-wizard/angular-wizard
|
dist/angular-wizard.js
|
function() {
var editMode = $scope.editMode;
if (angular.isUndefined(editMode) || (editMode === null)) return;
//Set completed for all steps to the value of editMode
angular.forEach($scope.steps, function (step) {
step.completed = editMode;
});
//If editMode is false, set ONLY ENABLED steps with index lower then completedIndex to completed
if (!editMode) {
var completedStepsIndex = $scope.currentStepNumber() - 1;
angular.forEach($scope.getEnabledSteps(), function(step, stepIndex) {
if(stepIndex < completedStepsIndex) {
step.completed = true;
}
});
}
}
|
javascript
|
function() {
var editMode = $scope.editMode;
if (angular.isUndefined(editMode) || (editMode === null)) return;
//Set completed for all steps to the value of editMode
angular.forEach($scope.steps, function (step) {
step.completed = editMode;
});
//If editMode is false, set ONLY ENABLED steps with index lower then completedIndex to completed
if (!editMode) {
var completedStepsIndex = $scope.currentStepNumber() - 1;
angular.forEach($scope.getEnabledSteps(), function(step, stepIndex) {
if(stepIndex < completedStepsIndex) {
step.completed = true;
}
});
}
}
|
[
"function",
"(",
")",
"{",
"var",
"editMode",
"=",
"$scope",
".",
"editMode",
";",
"if",
"(",
"angular",
".",
"isUndefined",
"(",
"editMode",
")",
"||",
"(",
"editMode",
"===",
"null",
")",
")",
"return",
";",
"//Set completed for all steps to the value of editMode",
"angular",
".",
"forEach",
"(",
"$scope",
".",
"steps",
",",
"function",
"(",
"step",
")",
"{",
"step",
".",
"completed",
"=",
"editMode",
";",
"}",
")",
";",
"//If editMode is false, set ONLY ENABLED steps with index lower then completedIndex to completed",
"if",
"(",
"!",
"editMode",
")",
"{",
"var",
"completedStepsIndex",
"=",
"$scope",
".",
"currentStepNumber",
"(",
")",
"-",
"1",
";",
"angular",
".",
"forEach",
"(",
"$scope",
".",
"getEnabledSteps",
"(",
")",
",",
"function",
"(",
"step",
",",
"stepIndex",
")",
"{",
"if",
"(",
"stepIndex",
"<",
"completedStepsIndex",
")",
"{",
"step",
".",
"completed",
"=",
"true",
";",
"}",
"}",
")",
";",
"}",
"}"
] |
update completed state for each step based on the editMode and current step number
|
[
"update",
"completed",
"state",
"for",
"each",
"step",
"based",
"on",
"the",
"editMode",
"and",
"current",
"step",
"number"
] |
9823e1f67d1fc60c88125f41dfc3fc5ab62e505c
|
https://github.com/angular-wizard/angular-wizard/blob/9823e1f67d1fc60c88125f41dfc3fc5ab62e505c/dist/angular-wizard.js#L126-L144
|
|
15,031
|
angular-wizard/angular-wizard
|
dist/angular-wizard.js
|
unselectAll
|
function unselectAll() {
//traverse steps array and set each "selected" property to false
angular.forEach($scope.getEnabledSteps(), function (step) {
step.selected = false;
});
//set selectedStep variable to null
$scope.selectedStep = null;
}
|
javascript
|
function unselectAll() {
//traverse steps array and set each "selected" property to false
angular.forEach($scope.getEnabledSteps(), function (step) {
step.selected = false;
});
//set selectedStep variable to null
$scope.selectedStep = null;
}
|
[
"function",
"unselectAll",
"(",
")",
"{",
"//traverse steps array and set each \"selected\" property to false",
"angular",
".",
"forEach",
"(",
"$scope",
".",
"getEnabledSteps",
"(",
")",
",",
"function",
"(",
"step",
")",
"{",
"step",
".",
"selected",
"=",
"false",
";",
"}",
")",
";",
"//set selectedStep variable to null",
"$scope",
".",
"selectedStep",
"=",
"null",
";",
"}"
] |
unSelect All Steps
|
[
"unSelect",
"All",
"Steps"
] |
9823e1f67d1fc60c88125f41dfc3fc5ab62e505c
|
https://github.com/angular-wizard/angular-wizard/blob/9823e1f67d1fc60c88125f41dfc3fc5ab62e505c/dist/angular-wizard.js#L314-L321
|
15,032
|
IHCantabria/Leaflet.CanvasLayer.Field
|
src/layer/L.CanvasLayer.ScalarField.js
|
function() {
const bounds = this._pixelBounds();
const pixelSize = (bounds.max.x - bounds.min.x) / this._field.nCols;
var stride = Math.max(
1,
Math.floor(1.2 * this.options.vectorSize / pixelSize)
);
const ctx = this._getDrawingContext();
ctx.strokeStyle = this.options.color;
var currentBounds = this._map.getBounds();
for (var y = 0; y < this._field.height; y = y + stride) {
for (var x = 0; x < this._field.width; x = x + stride) {
let [lon, lat] = this._field._lonLatAtIndexes(x, y);
let v = this._field.valueAt(lon, lat);
let center = L.latLng(lat, lon);
if (v !== null && currentBounds.contains(center)) {
let cell = new Cell(
center,
v,
this.cellXSize,
this.cellYSize
);
this._drawArrow(cell, ctx);
}
}
}
}
|
javascript
|
function() {
const bounds = this._pixelBounds();
const pixelSize = (bounds.max.x - bounds.min.x) / this._field.nCols;
var stride = Math.max(
1,
Math.floor(1.2 * this.options.vectorSize / pixelSize)
);
const ctx = this._getDrawingContext();
ctx.strokeStyle = this.options.color;
var currentBounds = this._map.getBounds();
for (var y = 0; y < this._field.height; y = y + stride) {
for (var x = 0; x < this._field.width; x = x + stride) {
let [lon, lat] = this._field._lonLatAtIndexes(x, y);
let v = this._field.valueAt(lon, lat);
let center = L.latLng(lat, lon);
if (v !== null && currentBounds.contains(center)) {
let cell = new Cell(
center,
v,
this.cellXSize,
this.cellYSize
);
this._drawArrow(cell, ctx);
}
}
}
}
|
[
"function",
"(",
")",
"{",
"const",
"bounds",
"=",
"this",
".",
"_pixelBounds",
"(",
")",
";",
"const",
"pixelSize",
"=",
"(",
"bounds",
".",
"max",
".",
"x",
"-",
"bounds",
".",
"min",
".",
"x",
")",
"/",
"this",
".",
"_field",
".",
"nCols",
";",
"var",
"stride",
"=",
"Math",
".",
"max",
"(",
"1",
",",
"Math",
".",
"floor",
"(",
"1.2",
"*",
"this",
".",
"options",
".",
"vectorSize",
"/",
"pixelSize",
")",
")",
";",
"const",
"ctx",
"=",
"this",
".",
"_getDrawingContext",
"(",
")",
";",
"ctx",
".",
"strokeStyle",
"=",
"this",
".",
"options",
".",
"color",
";",
"var",
"currentBounds",
"=",
"this",
".",
"_map",
".",
"getBounds",
"(",
")",
";",
"for",
"(",
"var",
"y",
"=",
"0",
";",
"y",
"<",
"this",
".",
"_field",
".",
"height",
";",
"y",
"=",
"y",
"+",
"stride",
")",
"{",
"for",
"(",
"var",
"x",
"=",
"0",
";",
"x",
"<",
"this",
".",
"_field",
".",
"width",
";",
"x",
"=",
"x",
"+",
"stride",
")",
"{",
"let",
"[",
"lon",
",",
"lat",
"]",
"=",
"this",
".",
"_field",
".",
"_lonLatAtIndexes",
"(",
"x",
",",
"y",
")",
";",
"let",
"v",
"=",
"this",
".",
"_field",
".",
"valueAt",
"(",
"lon",
",",
"lat",
")",
";",
"let",
"center",
"=",
"L",
".",
"latLng",
"(",
"lat",
",",
"lon",
")",
";",
"if",
"(",
"v",
"!==",
"null",
"&&",
"currentBounds",
".",
"contains",
"(",
"center",
")",
")",
"{",
"let",
"cell",
"=",
"new",
"Cell",
"(",
"center",
",",
"v",
",",
"this",
".",
"cellXSize",
",",
"this",
".",
"cellYSize",
")",
";",
"this",
".",
"_drawArrow",
"(",
"cell",
",",
"ctx",
")",
";",
"}",
"}",
"}",
"}"
] |
Draws the field as a set of arrows. Direction from 0 to 360 is assumed.
|
[
"Draws",
"the",
"field",
"as",
"a",
"set",
"of",
"arrows",
".",
"Direction",
"from",
"0",
"to",
"360",
"is",
"assumed",
"."
] |
7c861b246d619ba6e04d8c8486a9bf7f57be7a09
|
https://github.com/IHCantabria/Leaflet.CanvasLayer.Field/blob/7c861b246d619ba6e04d8c8486a9bf7f57be7a09/src/layer/L.CanvasLayer.ScalarField.js#L120-L150
|
|
15,033
|
IHCantabria/Leaflet.CanvasLayer.Field
|
src/layer/L.CanvasLayer.VectorFieldAnim.js
|
_drawParticles
|
function _drawParticles() {
// Previous paths...
let prev = ctx.globalCompositeOperation;
ctx.globalCompositeOperation = 'destination-in';
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
//ctx.globalCompositeOperation = 'source-over';
ctx.globalCompositeOperation = prev;
// fading paths...
ctx.fillStyle = `rgba(0, 0, 0, ${self.options.fade})`;
ctx.lineWidth = self.options.width;
ctx.strokeStyle = self.options.color;
// New paths
paths.forEach(function(par) {
self._drawParticle(viewInfo, ctx, par);
});
}
|
javascript
|
function _drawParticles() {
// Previous paths...
let prev = ctx.globalCompositeOperation;
ctx.globalCompositeOperation = 'destination-in';
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
//ctx.globalCompositeOperation = 'source-over';
ctx.globalCompositeOperation = prev;
// fading paths...
ctx.fillStyle = `rgba(0, 0, 0, ${self.options.fade})`;
ctx.lineWidth = self.options.width;
ctx.strokeStyle = self.options.color;
// New paths
paths.forEach(function(par) {
self._drawParticle(viewInfo, ctx, par);
});
}
|
[
"function",
"_drawParticles",
"(",
")",
"{",
"// Previous paths...",
"let",
"prev",
"=",
"ctx",
".",
"globalCompositeOperation",
";",
"ctx",
".",
"globalCompositeOperation",
"=",
"'destination-in'",
";",
"ctx",
".",
"fillRect",
"(",
"0",
",",
"0",
",",
"ctx",
".",
"canvas",
".",
"width",
",",
"ctx",
".",
"canvas",
".",
"height",
")",
";",
"//ctx.globalCompositeOperation = 'source-over';",
"ctx",
".",
"globalCompositeOperation",
"=",
"prev",
";",
"// fading paths...",
"ctx",
".",
"fillStyle",
"=",
"`",
"${",
"self",
".",
"options",
".",
"fade",
"}",
"`",
";",
"ctx",
".",
"lineWidth",
"=",
"self",
".",
"options",
".",
"width",
";",
"ctx",
".",
"strokeStyle",
"=",
"self",
".",
"options",
".",
"color",
";",
"// New paths",
"paths",
".",
"forEach",
"(",
"function",
"(",
"par",
")",
"{",
"self",
".",
"_drawParticle",
"(",
"viewInfo",
",",
"ctx",
",",
"par",
")",
";",
"}",
")",
";",
"}"
] |
Draws the paths on each step
|
[
"Draws",
"the",
"paths",
"on",
"each",
"step"
] |
7c861b246d619ba6e04d8c8486a9bf7f57be7a09
|
https://github.com/IHCantabria/Leaflet.CanvasLayer.Field/blob/7c861b246d619ba6e04d8c8486a9bf7f57be7a09/src/layer/L.CanvasLayer.VectorFieldAnim.js#L94-L111
|
15,034
|
senchalabs/cssbeautify
|
assets/thirdparty/codemirror.js
|
updateLines
|
function updateLines(from, to, newText, selFrom, selTo) {
if (suppressEdits) return;
var old = [];
doc.iter(from.line, to.line + 1, function(line) {
old.push(newHL(line.text, line.markedSpans));
});
if (history) {
history.addChange(from.line, newText.length, old);
while (history.done.length > options.undoDepth) history.done.shift();
}
var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText);
updateLinesNoUndo(from, to, lines, selFrom, selTo);
}
|
javascript
|
function updateLines(from, to, newText, selFrom, selTo) {
if (suppressEdits) return;
var old = [];
doc.iter(from.line, to.line + 1, function(line) {
old.push(newHL(line.text, line.markedSpans));
});
if (history) {
history.addChange(from.line, newText.length, old);
while (history.done.length > options.undoDepth) history.done.shift();
}
var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText);
updateLinesNoUndo(from, to, lines, selFrom, selTo);
}
|
[
"function",
"updateLines",
"(",
"from",
",",
"to",
",",
"newText",
",",
"selFrom",
",",
"selTo",
")",
"{",
"if",
"(",
"suppressEdits",
")",
"return",
";",
"var",
"old",
"=",
"[",
"]",
";",
"doc",
".",
"iter",
"(",
"from",
".",
"line",
",",
"to",
".",
"line",
"+",
"1",
",",
"function",
"(",
"line",
")",
"{",
"old",
".",
"push",
"(",
"newHL",
"(",
"line",
".",
"text",
",",
"line",
".",
"markedSpans",
")",
")",
";",
"}",
")",
";",
"if",
"(",
"history",
")",
"{",
"history",
".",
"addChange",
"(",
"from",
".",
"line",
",",
"newText",
".",
"length",
",",
"old",
")",
";",
"while",
"(",
"history",
".",
"done",
".",
"length",
">",
"options",
".",
"undoDepth",
")",
"history",
".",
"done",
".",
"shift",
"(",
")",
";",
"}",
"var",
"lines",
"=",
"updateMarkedSpans",
"(",
"hlSpans",
"(",
"old",
"[",
"0",
"]",
")",
",",
"hlSpans",
"(",
"lst",
"(",
"old",
")",
")",
",",
"from",
".",
"ch",
",",
"to",
".",
"ch",
",",
"newText",
")",
";",
"updateLinesNoUndo",
"(",
"from",
",",
"to",
",",
"lines",
",",
"selFrom",
",",
"selTo",
")",
";",
"}"
] |
Replace the range from from to to by the strings in newText. Afterwards, set the selection to selFrom, selTo.
|
[
"Replace",
"the",
"range",
"from",
"from",
"to",
"to",
"by",
"the",
"strings",
"in",
"newText",
".",
"Afterwards",
"set",
"the",
"selection",
"to",
"selFrom",
"selTo",
"."
] |
4a1f5d8aff8886c6790655acbccd9b478f8fee32
|
https://github.com/senchalabs/cssbeautify/blob/4a1f5d8aff8886c6790655acbccd9b478f8fee32/assets/thirdparty/codemirror.js#L717-L729
|
15,035
|
senchalabs/cssbeautify
|
assets/thirdparty/codemirror.js
|
setSelection
|
function setSelection(from, to, oldFrom, oldTo) {
goalColumn = null;
if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;}
if (posEq(sel.from, from) && posEq(sel.to, to)) return;
if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
// Skip over hidden lines.
if (from.line != oldFrom) {
var from1 = skipHidden(from, oldFrom, sel.from.ch);
// If there is no non-hidden line left, force visibility on current line
if (!from1) setLineHidden(from.line, false);
else from = from1;
}
if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch);
if (posEq(from, to)) sel.inverted = false;
else if (posEq(from, sel.to)) sel.inverted = false;
else if (posEq(to, sel.from)) sel.inverted = true;
if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) {
var head = sel.inverted ? from : to;
if (head.line != sel.from.line && sel.from.line < doc.size) {
var oldLine = getLine(sel.from.line);
if (/^\s+$/.test(oldLine.text))
setTimeout(operation(function() {
if (oldLine.parent && /^\s+$/.test(oldLine.text)) {
var no = lineNo(oldLine);
replaceRange("", {line: no, ch: 0}, {line: no, ch: oldLine.text.length});
}
}, 10));
}
}
sel.from = from; sel.to = to;
selectionChanged = true;
}
|
javascript
|
function setSelection(from, to, oldFrom, oldTo) {
goalColumn = null;
if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;}
if (posEq(sel.from, from) && posEq(sel.to, to)) return;
if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
// Skip over hidden lines.
if (from.line != oldFrom) {
var from1 = skipHidden(from, oldFrom, sel.from.ch);
// If there is no non-hidden line left, force visibility on current line
if (!from1) setLineHidden(from.line, false);
else from = from1;
}
if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch);
if (posEq(from, to)) sel.inverted = false;
else if (posEq(from, sel.to)) sel.inverted = false;
else if (posEq(to, sel.from)) sel.inverted = true;
if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) {
var head = sel.inverted ? from : to;
if (head.line != sel.from.line && sel.from.line < doc.size) {
var oldLine = getLine(sel.from.line);
if (/^\s+$/.test(oldLine.text))
setTimeout(operation(function() {
if (oldLine.parent && /^\s+$/.test(oldLine.text)) {
var no = lineNo(oldLine);
replaceRange("", {line: no, ch: 0}, {line: no, ch: oldLine.text.length});
}
}, 10));
}
}
sel.from = from; sel.to = to;
selectionChanged = true;
}
|
[
"function",
"setSelection",
"(",
"from",
",",
"to",
",",
"oldFrom",
",",
"oldTo",
")",
"{",
"goalColumn",
"=",
"null",
";",
"if",
"(",
"oldFrom",
"==",
"null",
")",
"{",
"oldFrom",
"=",
"sel",
".",
"from",
".",
"line",
";",
"oldTo",
"=",
"sel",
".",
"to",
".",
"line",
";",
"}",
"if",
"(",
"posEq",
"(",
"sel",
".",
"from",
",",
"from",
")",
"&&",
"posEq",
"(",
"sel",
".",
"to",
",",
"to",
")",
")",
"return",
";",
"if",
"(",
"posLess",
"(",
"to",
",",
"from",
")",
")",
"{",
"var",
"tmp",
"=",
"to",
";",
"to",
"=",
"from",
";",
"from",
"=",
"tmp",
";",
"}",
"// Skip over hidden lines.",
"if",
"(",
"from",
".",
"line",
"!=",
"oldFrom",
")",
"{",
"var",
"from1",
"=",
"skipHidden",
"(",
"from",
",",
"oldFrom",
",",
"sel",
".",
"from",
".",
"ch",
")",
";",
"// If there is no non-hidden line left, force visibility on current line",
"if",
"(",
"!",
"from1",
")",
"setLineHidden",
"(",
"from",
".",
"line",
",",
"false",
")",
";",
"else",
"from",
"=",
"from1",
";",
"}",
"if",
"(",
"to",
".",
"line",
"!=",
"oldTo",
")",
"to",
"=",
"skipHidden",
"(",
"to",
",",
"oldTo",
",",
"sel",
".",
"to",
".",
"ch",
")",
";",
"if",
"(",
"posEq",
"(",
"from",
",",
"to",
")",
")",
"sel",
".",
"inverted",
"=",
"false",
";",
"else",
"if",
"(",
"posEq",
"(",
"from",
",",
"sel",
".",
"to",
")",
")",
"sel",
".",
"inverted",
"=",
"false",
";",
"else",
"if",
"(",
"posEq",
"(",
"to",
",",
"sel",
".",
"from",
")",
")",
"sel",
".",
"inverted",
"=",
"true",
";",
"if",
"(",
"options",
".",
"autoClearEmptyLines",
"&&",
"posEq",
"(",
"sel",
".",
"from",
",",
"sel",
".",
"to",
")",
")",
"{",
"var",
"head",
"=",
"sel",
".",
"inverted",
"?",
"from",
":",
"to",
";",
"if",
"(",
"head",
".",
"line",
"!=",
"sel",
".",
"from",
".",
"line",
"&&",
"sel",
".",
"from",
".",
"line",
"<",
"doc",
".",
"size",
")",
"{",
"var",
"oldLine",
"=",
"getLine",
"(",
"sel",
".",
"from",
".",
"line",
")",
";",
"if",
"(",
"/",
"^\\s+$",
"/",
".",
"test",
"(",
"oldLine",
".",
"text",
")",
")",
"setTimeout",
"(",
"operation",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"oldLine",
".",
"parent",
"&&",
"/",
"^\\s+$",
"/",
".",
"test",
"(",
"oldLine",
".",
"text",
")",
")",
"{",
"var",
"no",
"=",
"lineNo",
"(",
"oldLine",
")",
";",
"replaceRange",
"(",
"\"\"",
",",
"{",
"line",
":",
"no",
",",
"ch",
":",
"0",
"}",
",",
"{",
"line",
":",
"no",
",",
"ch",
":",
"oldLine",
".",
"text",
".",
"length",
"}",
")",
";",
"}",
"}",
",",
"10",
")",
")",
";",
"}",
"}",
"sel",
".",
"from",
"=",
"from",
";",
"sel",
".",
"to",
"=",
"to",
";",
"selectionChanged",
"=",
"true",
";",
"}"
] |
Update the selection. Last two args are only used by updateLines, since they have to be expressed in the line numbers before the update.
|
[
"Update",
"the",
"selection",
".",
"Last",
"two",
"args",
"are",
"only",
"used",
"by",
"updateLines",
"since",
"they",
"have",
"to",
"be",
"expressed",
"in",
"the",
"line",
"numbers",
"before",
"the",
"update",
"."
] |
4a1f5d8aff8886c6790655acbccd9b478f8fee32
|
https://github.com/senchalabs/cssbeautify/blob/4a1f5d8aff8886c6790655acbccd9b478f8fee32/assets/thirdparty/codemirror.js#L1288-L1323
|
15,036
|
senchalabs/cssbeautify
|
assets/thirdparty/codemirror.js
|
restartBlink
|
function restartBlink() {
clearInterval(blinker);
var on = true;
cursor.style.visibility = "";
blinker = setInterval(function() {
cursor.style.visibility = (on = !on) ? "" : "hidden";
}, options.cursorBlinkRate);
}
|
javascript
|
function restartBlink() {
clearInterval(blinker);
var on = true;
cursor.style.visibility = "";
blinker = setInterval(function() {
cursor.style.visibility = (on = !on) ? "" : "hidden";
}, options.cursorBlinkRate);
}
|
[
"function",
"restartBlink",
"(",
")",
"{",
"clearInterval",
"(",
"blinker",
")",
";",
"var",
"on",
"=",
"true",
";",
"cursor",
".",
"style",
".",
"visibility",
"=",
"\"\"",
";",
"blinker",
"=",
"setInterval",
"(",
"function",
"(",
")",
"{",
"cursor",
".",
"style",
".",
"visibility",
"=",
"(",
"on",
"=",
"!",
"on",
")",
"?",
"\"\"",
":",
"\"hidden\"",
";",
"}",
",",
"options",
".",
"cursorBlinkRate",
")",
";",
"}"
] |
Cursor-blinking
|
[
"Cursor",
"-",
"blinking"
] |
4a1f5d8aff8886c6790655acbccd9b478f8fee32
|
https://github.com/senchalabs/cssbeautify/blob/4a1f5d8aff8886c6790655acbccd9b478f8fee32/assets/thirdparty/codemirror.js#L1812-L1819
|
15,037
|
senchalabs/cssbeautify
|
assets/thirdparty/codemirror.js
|
connect
|
function connect(node, type, handler, disconnect) {
if (typeof node.addEventListener == "function") {
node.addEventListener(type, handler, false);
if (disconnect) return function() {node.removeEventListener(type, handler, false);};
} else {
var wrapHandler = function(event) {handler(event || window.event);};
node.attachEvent("on" + type, wrapHandler);
if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);};
}
}
|
javascript
|
function connect(node, type, handler, disconnect) {
if (typeof node.addEventListener == "function") {
node.addEventListener(type, handler, false);
if (disconnect) return function() {node.removeEventListener(type, handler, false);};
} else {
var wrapHandler = function(event) {handler(event || window.event);};
node.attachEvent("on" + type, wrapHandler);
if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);};
}
}
|
[
"function",
"connect",
"(",
"node",
",",
"type",
",",
"handler",
",",
"disconnect",
")",
"{",
"if",
"(",
"typeof",
"node",
".",
"addEventListener",
"==",
"\"function\"",
")",
"{",
"node",
".",
"addEventListener",
"(",
"type",
",",
"handler",
",",
"false",
")",
";",
"if",
"(",
"disconnect",
")",
"return",
"function",
"(",
")",
"{",
"node",
".",
"removeEventListener",
"(",
"type",
",",
"handler",
",",
"false",
")",
";",
"}",
";",
"}",
"else",
"{",
"var",
"wrapHandler",
"=",
"function",
"(",
"event",
")",
"{",
"handler",
"(",
"event",
"||",
"window",
".",
"event",
")",
";",
"}",
";",
"node",
".",
"attachEvent",
"(",
"\"on\"",
"+",
"type",
",",
"wrapHandler",
")",
";",
"if",
"(",
"disconnect",
")",
"return",
"function",
"(",
")",
"{",
"node",
".",
"detachEvent",
"(",
"\"on\"",
"+",
"type",
",",
"wrapHandler",
")",
";",
"}",
";",
"}",
"}"
] |
Event handler registration. If disconnect is true, it'll return a function that unregisters the handler.
|
[
"Event",
"handler",
"registration",
".",
"If",
"disconnect",
"is",
"true",
"it",
"ll",
"return",
"a",
"function",
"that",
"unregisters",
"the",
"handler",
"."
] |
4a1f5d8aff8886c6790655acbccd9b478f8fee32
|
https://github.com/senchalabs/cssbeautify/blob/4a1f5d8aff8886c6790655acbccd9b478f8fee32/assets/thirdparty/codemirror.js#L2942-L2951
|
15,038
|
ember-cli/ember-fetch
|
fastboot/instance-initializers/setup-fetch.js
|
patchFetchForRelativeURLs
|
function patchFetchForRelativeURLs(instance) {
const fastboot = instance.lookup('service:fastboot');
const request = fastboot.get('request');
// Prember is not sending protocol
const protocol = request.protocol === 'undefined:' ? 'http:' : request.protocol;
// host is cp
setupFastboot(protocol, request.get('host'));
}
|
javascript
|
function patchFetchForRelativeURLs(instance) {
const fastboot = instance.lookup('service:fastboot');
const request = fastboot.get('request');
// Prember is not sending protocol
const protocol = request.protocol === 'undefined:' ? 'http:' : request.protocol;
// host is cp
setupFastboot(protocol, request.get('host'));
}
|
[
"function",
"patchFetchForRelativeURLs",
"(",
"instance",
")",
"{",
"const",
"fastboot",
"=",
"instance",
".",
"lookup",
"(",
"'service:fastboot'",
")",
";",
"const",
"request",
"=",
"fastboot",
".",
"get",
"(",
"'request'",
")",
";",
"// Prember is not sending protocol",
"const",
"protocol",
"=",
"request",
".",
"protocol",
"===",
"'undefined:'",
"?",
"'http:'",
":",
"request",
".",
"protocol",
";",
"// host is cp",
"setupFastboot",
"(",
"protocol",
",",
"request",
".",
"get",
"(",
"'host'",
")",
")",
";",
"}"
] |
To allow relative URLs for Fastboot mode, we need the per request information
from the fastboot service. Then we set the protocol and host to fetch module.
|
[
"To",
"allow",
"relative",
"URLs",
"for",
"Fastboot",
"mode",
"we",
"need",
"the",
"per",
"request",
"information",
"from",
"the",
"fastboot",
"service",
".",
"Then",
"we",
"set",
"the",
"protocol",
"and",
"host",
"to",
"fetch",
"module",
"."
] |
5e3dee2d1fcd41f113b392a33d97d19691805f61
|
https://github.com/ember-cli/ember-fetch/blob/5e3dee2d1fcd41f113b392a33d97d19691805f61/fastboot/instance-initializers/setup-fetch.js#L7-L14
|
15,039
|
SAP/node-hdb
|
lib/protocol/Connection.js
|
ondata
|
function ondata(chunk) {
packet.push(chunk);
if (packet.isReady()) {
if (self._state.sessionId !== packet.header.sessionId) {
self._state.sessionId = packet.header.sessionId;
self._state.packetCount = -1;
}
var buffer = packet.getData();
packet.clear();
var cb = self._state.receive;
self._state.receive = undefined;
self._state.messageType = undefined;
self.receive(buffer, cb);
}
}
|
javascript
|
function ondata(chunk) {
packet.push(chunk);
if (packet.isReady()) {
if (self._state.sessionId !== packet.header.sessionId) {
self._state.sessionId = packet.header.sessionId;
self._state.packetCount = -1;
}
var buffer = packet.getData();
packet.clear();
var cb = self._state.receive;
self._state.receive = undefined;
self._state.messageType = undefined;
self.receive(buffer, cb);
}
}
|
[
"function",
"ondata",
"(",
"chunk",
")",
"{",
"packet",
".",
"push",
"(",
"chunk",
")",
";",
"if",
"(",
"packet",
".",
"isReady",
"(",
")",
")",
"{",
"if",
"(",
"self",
".",
"_state",
".",
"sessionId",
"!==",
"packet",
".",
"header",
".",
"sessionId",
")",
"{",
"self",
".",
"_state",
".",
"sessionId",
"=",
"packet",
".",
"header",
".",
"sessionId",
";",
"self",
".",
"_state",
".",
"packetCount",
"=",
"-",
"1",
";",
"}",
"var",
"buffer",
"=",
"packet",
".",
"getData",
"(",
")",
";",
"packet",
".",
"clear",
"(",
")",
";",
"var",
"cb",
"=",
"self",
".",
"_state",
".",
"receive",
";",
"self",
".",
"_state",
".",
"receive",
"=",
"undefined",
";",
"self",
".",
"_state",
".",
"messageType",
"=",
"undefined",
";",
"self",
".",
"receive",
"(",
"buffer",
",",
"cb",
")",
";",
"}",
"}"
] |
register listerners on socket
|
[
"register",
"listerners",
"on",
"socket"
] |
807fe50e02e5a8bc6a146f250369436634f6d57f
|
https://github.com/SAP/node-hdb/blob/807fe50e02e5a8bc6a146f250369436634f6d57f/lib/protocol/Connection.js#L211-L225
|
15,040
|
wikimedia/parsoid
|
lib/wt2html/DOMPostProcessor.js
|
appendToHead
|
function appendToHead(document, tagName, attrs) {
var elt = document.createElement(tagName);
DOMDataUtils.addAttributes(elt, attrs || Object.create(null));
document.head.appendChild(elt);
}
|
javascript
|
function appendToHead(document, tagName, attrs) {
var elt = document.createElement(tagName);
DOMDataUtils.addAttributes(elt, attrs || Object.create(null));
document.head.appendChild(elt);
}
|
[
"function",
"appendToHead",
"(",
"document",
",",
"tagName",
",",
"attrs",
")",
"{",
"var",
"elt",
"=",
"document",
".",
"createElement",
"(",
"tagName",
")",
";",
"DOMDataUtils",
".",
"addAttributes",
"(",
"elt",
",",
"attrs",
"||",
"Object",
".",
"create",
"(",
"null",
")",
")",
";",
"document",
".",
"head",
".",
"appendChild",
"(",
"elt",
")",
";",
"}"
] |
Create an element in the document.head with the given attrs.
|
[
"Create",
"an",
"element",
"in",
"the",
"document",
".",
"head",
"with",
"the",
"given",
"attrs",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/wt2html/DOMPostProcessor.js#L437-L441
|
15,041
|
wikimedia/parsoid
|
lib/utils/DOMPostOrder.js
|
DOMPostOrder
|
function DOMPostOrder(root, visitFunc) {
let node = root;
while (true) {
// Find leftmost (grand)child, and visit that first.
while (node.firstChild) {
node = node.firstChild;
}
visitFunc(node);
while (true) {
if (node === root) {
return; // Visiting the root is the last thing we do.
}
/* Look for right sibling to continue traversal. */
if (node.nextSibling) {
node = node.nextSibling;
/* Loop back and visit its leftmost (grand)child first. */
break;
}
/* Visit parent only after we've run out of right siblings. */
node = node.parentNode;
visitFunc(node);
}
}
}
|
javascript
|
function DOMPostOrder(root, visitFunc) {
let node = root;
while (true) {
// Find leftmost (grand)child, and visit that first.
while (node.firstChild) {
node = node.firstChild;
}
visitFunc(node);
while (true) {
if (node === root) {
return; // Visiting the root is the last thing we do.
}
/* Look for right sibling to continue traversal. */
if (node.nextSibling) {
node = node.nextSibling;
/* Loop back and visit its leftmost (grand)child first. */
break;
}
/* Visit parent only after we've run out of right siblings. */
node = node.parentNode;
visitFunc(node);
}
}
}
|
[
"function",
"DOMPostOrder",
"(",
"root",
",",
"visitFunc",
")",
"{",
"let",
"node",
"=",
"root",
";",
"while",
"(",
"true",
")",
"{",
"// Find leftmost (grand)child, and visit that first.",
"while",
"(",
"node",
".",
"firstChild",
")",
"{",
"node",
"=",
"node",
".",
"firstChild",
";",
"}",
"visitFunc",
"(",
"node",
")",
";",
"while",
"(",
"true",
")",
"{",
"if",
"(",
"node",
"===",
"root",
")",
"{",
"return",
";",
"// Visiting the root is the last thing we do.",
"}",
"/* Look for right sibling to continue traversal. */",
"if",
"(",
"node",
".",
"nextSibling",
")",
"{",
"node",
"=",
"node",
".",
"nextSibling",
";",
"/* Loop back and visit its leftmost (grand)child first. */",
"break",
";",
"}",
"/* Visit parent only after we've run out of right siblings. */",
"node",
"=",
"node",
".",
"parentNode",
";",
"visitFunc",
"(",
"node",
")",
";",
"}",
"}",
"}"
] |
Non-recursive post-order traversal of a DOM tree.
@param {Node} root
@param {Function} visitFunc Called in post-order on each node.
|
[
"Non",
"-",
"recursive",
"post",
"-",
"order",
"traversal",
"of",
"a",
"DOM",
"tree",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/utils/DOMPostOrder.js#L13-L36
|
15,042
|
wikimedia/parsoid
|
lib/wt2html/tt/ParserFunctions.js
|
buildAsyncOutputBufferCB
|
function buildAsyncOutputBufferCB(cb) {
function AsyncOutputBufferCB(cb2) {
this.accum = [];
this.targetCB = cb2;
}
AsyncOutputBufferCB.prototype.processAsyncOutput = function(res) {
// * Ignore switch-to-async mode calls since
// we are actually collapsing async calls.
// * Accumulate async call results in an array
// till we get the signal that we are all done
// * Once we are done, pass everything to the target cb.
if (res.async !== true) {
// There are 3 kinds of callbacks:
// 1. cb({tokens: .. })
// 2. cb({}) ==> toks can be undefined
// 3. cb(foo) -- which means in some cases foo can
// be one of the two cases above, or it can also be a simple string.
//
// Version 1. is the general case.
// Versions 2. and 3. are optimized scenarios to eliminate
// additional processing of tokens.
//
// In the C++ version, this is handled more cleanly.
var toks = res.tokens;
if (!toks && res.constructor === String) {
toks = res;
}
if (toks) {
if (Array.isArray(toks)) {
for (var i = 0, l = toks.length; i < l; i++) {
this.accum.push(toks[i]);
}
// this.accum = this.accum.concat(toks);
} else {
this.accum.push(toks);
}
}
if (!res.async) {
// we are done!
this.targetCB(this.accum);
}
}
};
var r = new AsyncOutputBufferCB(cb);
return r.processAsyncOutput.bind(r);
}
|
javascript
|
function buildAsyncOutputBufferCB(cb) {
function AsyncOutputBufferCB(cb2) {
this.accum = [];
this.targetCB = cb2;
}
AsyncOutputBufferCB.prototype.processAsyncOutput = function(res) {
// * Ignore switch-to-async mode calls since
// we are actually collapsing async calls.
// * Accumulate async call results in an array
// till we get the signal that we are all done
// * Once we are done, pass everything to the target cb.
if (res.async !== true) {
// There are 3 kinds of callbacks:
// 1. cb({tokens: .. })
// 2. cb({}) ==> toks can be undefined
// 3. cb(foo) -- which means in some cases foo can
// be one of the two cases above, or it can also be a simple string.
//
// Version 1. is the general case.
// Versions 2. and 3. are optimized scenarios to eliminate
// additional processing of tokens.
//
// In the C++ version, this is handled more cleanly.
var toks = res.tokens;
if (!toks && res.constructor === String) {
toks = res;
}
if (toks) {
if (Array.isArray(toks)) {
for (var i = 0, l = toks.length; i < l; i++) {
this.accum.push(toks[i]);
}
// this.accum = this.accum.concat(toks);
} else {
this.accum.push(toks);
}
}
if (!res.async) {
// we are done!
this.targetCB(this.accum);
}
}
};
var r = new AsyncOutputBufferCB(cb);
return r.processAsyncOutput.bind(r);
}
|
[
"function",
"buildAsyncOutputBufferCB",
"(",
"cb",
")",
"{",
"function",
"AsyncOutputBufferCB",
"(",
"cb2",
")",
"{",
"this",
".",
"accum",
"=",
"[",
"]",
";",
"this",
".",
"targetCB",
"=",
"cb2",
";",
"}",
"AsyncOutputBufferCB",
".",
"prototype",
".",
"processAsyncOutput",
"=",
"function",
"(",
"res",
")",
"{",
"// * Ignore switch-to-async mode calls since",
"// we are actually collapsing async calls.",
"// * Accumulate async call results in an array",
"// till we get the signal that we are all done",
"// * Once we are done, pass everything to the target cb.",
"if",
"(",
"res",
".",
"async",
"!==",
"true",
")",
"{",
"// There are 3 kinds of callbacks:",
"// 1. cb({tokens: .. })",
"// 2. cb({}) ==> toks can be undefined",
"// 3. cb(foo) -- which means in some cases foo can",
"// be one of the two cases above, or it can also be a simple string.",
"//",
"// Version 1. is the general case.",
"// Versions 2. and 3. are optimized scenarios to eliminate",
"// additional processing of tokens.",
"//",
"// In the C++ version, this is handled more cleanly.",
"var",
"toks",
"=",
"res",
".",
"tokens",
";",
"if",
"(",
"!",
"toks",
"&&",
"res",
".",
"constructor",
"===",
"String",
")",
"{",
"toks",
"=",
"res",
";",
"}",
"if",
"(",
"toks",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"toks",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"toks",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"this",
".",
"accum",
".",
"push",
"(",
"toks",
"[",
"i",
"]",
")",
";",
"}",
"// this.accum = this.accum.concat(toks);",
"}",
"else",
"{",
"this",
".",
"accum",
".",
"push",
"(",
"toks",
")",
";",
"}",
"}",
"if",
"(",
"!",
"res",
".",
"async",
")",
"{",
"// we are done!",
"this",
".",
"targetCB",
"(",
"this",
".",
"accum",
")",
";",
"}",
"}",
"}",
";",
"var",
"r",
"=",
"new",
"AsyncOutputBufferCB",
"(",
"cb",
")",
";",
"return",
"r",
".",
"processAsyncOutput",
".",
"bind",
"(",
"r",
")",
";",
"}"
] |
'cb' can only be called once after "everything" is done. But, we need something that can be used in async context where it is called repeatedly till we are done. Primarily needed in the context of async.map calls that requires a 1-shot callback. Use with caution! If the async stream that we are accumulating into the buffer is a firehose of tokens, the buffer will become huge.
|
[
"cb",
"can",
"only",
"be",
"called",
"once",
"after",
"everything",
"is",
"done",
".",
"But",
"we",
"need",
"something",
"that",
"can",
"be",
"used",
"in",
"async",
"context",
"where",
"it",
"is",
"called",
"repeatedly",
"till",
"we",
"are",
"done",
".",
"Primarily",
"needed",
"in",
"the",
"context",
"of",
"async",
".",
"map",
"calls",
"that",
"requires",
"a",
"1",
"-",
"shot",
"callback",
".",
"Use",
"with",
"caution!",
"If",
"the",
"async",
"stream",
"that",
"we",
"are",
"accumulating",
"into",
"the",
"buffer",
"is",
"a",
"firehose",
"of",
"tokens",
"the",
"buffer",
"will",
"become",
"huge",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/wt2html/tt/ParserFunctions.js#L49-L98
|
15,043
|
wikimedia/parsoid
|
lib/api/routes.js
|
function(res, text, httpStatus) {
processLogger.log('fatal/request', text);
apiUtils.errorResponse(res, text, httpStatus || 404);
}
|
javascript
|
function(res, text, httpStatus) {
processLogger.log('fatal/request', text);
apiUtils.errorResponse(res, text, httpStatus || 404);
}
|
[
"function",
"(",
"res",
",",
"text",
",",
"httpStatus",
")",
"{",
"processLogger",
".",
"log",
"(",
"'fatal/request'",
",",
"text",
")",
";",
"apiUtils",
".",
"errorResponse",
"(",
"res",
",",
"text",
",",
"httpStatus",
"||",
"404",
")",
";",
"}"
] |
This helper is only to be used in middleware, before an environment is setup. The logger doesn't emit the expected location info. You probably want `apiUtils.fatalRequest` instead.
|
[
"This",
"helper",
"is",
"only",
"to",
"be",
"used",
"in",
"middleware",
"before",
"an",
"environment",
"is",
"setup",
".",
"The",
"logger",
"doesn",
"t",
"emit",
"the",
"expected",
"location",
"info",
".",
"You",
"probably",
"want",
"apiUtils",
".",
"fatalRequest",
"instead",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/api/routes.js#L37-L40
|
|
15,044
|
wikimedia/parsoid
|
lib/api/apiUtils.js
|
function(doc, pb) {
// Effectively, skip applying data-parsoid. Note that if we were to
// support a pb2html downgrade, we'd need to apply the full thing,
// but that would create complications where ids would be left behind.
// See the comment in around `DOMDataUtils.applyPageBundle`
DOMDataUtils.applyPageBundle(doc, { parsoid: { ids: {} }, mw: pb.mw });
// Now, modify the pagebundle to the expected form. This is important
// since, at least in the serialization path, the original pb will be
// applied to the modified content and its presence could cause lost
// deletions.
pb.mw = { ids: {} };
}
|
javascript
|
function(doc, pb) {
// Effectively, skip applying data-parsoid. Note that if we were to
// support a pb2html downgrade, we'd need to apply the full thing,
// but that would create complications where ids would be left behind.
// See the comment in around `DOMDataUtils.applyPageBundle`
DOMDataUtils.applyPageBundle(doc, { parsoid: { ids: {} }, mw: pb.mw });
// Now, modify the pagebundle to the expected form. This is important
// since, at least in the serialization path, the original pb will be
// applied to the modified content and its presence could cause lost
// deletions.
pb.mw = { ids: {} };
}
|
[
"function",
"(",
"doc",
",",
"pb",
")",
"{",
"// Effectively, skip applying data-parsoid. Note that if we were to",
"// support a pb2html downgrade, we'd need to apply the full thing,",
"// but that would create complications where ids would be left behind.",
"// See the comment in around `DOMDataUtils.applyPageBundle`",
"DOMDataUtils",
".",
"applyPageBundle",
"(",
"doc",
",",
"{",
"parsoid",
":",
"{",
"ids",
":",
"{",
"}",
"}",
",",
"mw",
":",
"pb",
".",
"mw",
"}",
")",
";",
"// Now, modify the pagebundle to the expected form. This is important",
"// since, at least in the serialization path, the original pb will be",
"// applied to the modified content and its presence could cause lost",
"// deletions.",
"pb",
".",
"mw",
"=",
"{",
"ids",
":",
"{",
"}",
"}",
";",
"}"
] |
Downgrade content from 999.x to 2.x.
@param {Document} doc
@param {Object} pb
|
[
"Downgrade",
"content",
"from",
"999",
".",
"x",
"to",
"2",
".",
"x",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/api/apiUtils.js#L490-L501
|
|
15,045
|
wikimedia/parsoid
|
lib/wt2html/tt/Sanitizer.js
|
function(codepoint) {
// U+000C is valid in HTML5 but not allowed in XML.
// U+000D is valid in XML but not allowed in HTML5.
// U+007F - U+009F are disallowed in HTML5 (control characters).
return codepoint === 0x09
|| codepoint === 0x0a
|| (codepoint >= 0x20 && codepoint <= 0x7e)
|| (codepoint >= 0xa0 && codepoint <= 0xd7ff)
|| (codepoint >= 0xe000 && codepoint <= 0xfffd)
|| (codepoint >= 0x10000 && codepoint <= 0x10ffff);
}
|
javascript
|
function(codepoint) {
// U+000C is valid in HTML5 but not allowed in XML.
// U+000D is valid in XML but not allowed in HTML5.
// U+007F - U+009F are disallowed in HTML5 (control characters).
return codepoint === 0x09
|| codepoint === 0x0a
|| (codepoint >= 0x20 && codepoint <= 0x7e)
|| (codepoint >= 0xa0 && codepoint <= 0xd7ff)
|| (codepoint >= 0xe000 && codepoint <= 0xfffd)
|| (codepoint >= 0x10000 && codepoint <= 0x10ffff);
}
|
[
"function",
"(",
"codepoint",
")",
"{",
"// U+000C is valid in HTML5 but not allowed in XML.",
"// U+000D is valid in XML but not allowed in HTML5.",
"// U+007F - U+009F are disallowed in HTML5 (control characters).",
"return",
"codepoint",
"===",
"0x09",
"||",
"codepoint",
"===",
"0x0a",
"||",
"(",
"codepoint",
">=",
"0x20",
"&&",
"codepoint",
"<=",
"0x7e",
")",
"||",
"(",
"codepoint",
">=",
"0xa0",
"&&",
"codepoint",
"<=",
"0xd7ff",
")",
"||",
"(",
"codepoint",
">=",
"0xe000",
"&&",
"codepoint",
"<=",
"0xfffd",
")",
"||",
"(",
"codepoint",
">=",
"0x10000",
"&&",
"codepoint",
"<=",
"0x10ffff",
")",
";",
"}"
] |
Returns true if a given Unicode codepoint is a valid character in
both HTML5 and XML.
|
[
"Returns",
"true",
"if",
"a",
"given",
"Unicode",
"codepoint",
"is",
"a",
"valid",
"character",
"in",
"both",
"HTML5",
"and",
"XML",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/wt2html/tt/Sanitizer.js#L28-L38
|
|
15,046
|
wikimedia/parsoid
|
lib/mw/Batcher.js
|
Batcher
|
function Batcher(env) {
this.env = env;
this.itemCallbacks = {};
this.currentBatch = [];
this.pendingBatches = [];
this.resultCache = {};
this.numOutstanding = 0;
this.forwardProgressTimer = null;
this.maxBatchSize = env.conf.parsoid.batchSize;
this.targetConcurrency = env.conf.parsoid.batchConcurrency;
// Max latency before we give up on a batch response and terminate the req.
this.maxResponseLatency = env.conf.parsoid.timeouts.mwApi.batch *
(1 + env.conf.parsoid.retries.mwApi.all) + 5 * 1000;
}
|
javascript
|
function Batcher(env) {
this.env = env;
this.itemCallbacks = {};
this.currentBatch = [];
this.pendingBatches = [];
this.resultCache = {};
this.numOutstanding = 0;
this.forwardProgressTimer = null;
this.maxBatchSize = env.conf.parsoid.batchSize;
this.targetConcurrency = env.conf.parsoid.batchConcurrency;
// Max latency before we give up on a batch response and terminate the req.
this.maxResponseLatency = env.conf.parsoid.timeouts.mwApi.batch *
(1 + env.conf.parsoid.retries.mwApi.all) + 5 * 1000;
}
|
[
"function",
"Batcher",
"(",
"env",
")",
"{",
"this",
".",
"env",
"=",
"env",
";",
"this",
".",
"itemCallbacks",
"=",
"{",
"}",
";",
"this",
".",
"currentBatch",
"=",
"[",
"]",
";",
"this",
".",
"pendingBatches",
"=",
"[",
"]",
";",
"this",
".",
"resultCache",
"=",
"{",
"}",
";",
"this",
".",
"numOutstanding",
"=",
"0",
";",
"this",
".",
"forwardProgressTimer",
"=",
"null",
";",
"this",
".",
"maxBatchSize",
"=",
"env",
".",
"conf",
".",
"parsoid",
".",
"batchSize",
";",
"this",
".",
"targetConcurrency",
"=",
"env",
".",
"conf",
".",
"parsoid",
".",
"batchConcurrency",
";",
"// Max latency before we give up on a batch response and terminate the req.",
"this",
".",
"maxResponseLatency",
"=",
"env",
".",
"conf",
".",
"parsoid",
".",
"timeouts",
".",
"mwApi",
".",
"batch",
"*",
"(",
"1",
"+",
"env",
".",
"conf",
".",
"parsoid",
".",
"retries",
".",
"mwApi",
".",
"all",
")",
"+",
"5",
"*",
"1000",
";",
"}"
] |
This class combines requests into batches for dispatch to the
ParsoidBatchAPI extension, and calls the item callbacks when the batch
result is returned. It handles scheduling and concurrency of batch requests.
It also has a legacy mode which sends requests to the MW core API.
@class
@param {MWParserEnvironment} env
|
[
"This",
"class",
"combines",
"requests",
"into",
"batches",
"for",
"dispatch",
"to",
"the",
"ParsoidBatchAPI",
"extension",
"and",
"calls",
"the",
"item",
"callbacks",
"when",
"the",
"batch",
"result",
"is",
"returned",
".",
"It",
"handles",
"scheduling",
"and",
"concurrency",
"of",
"batch",
"requests",
".",
"It",
"also",
"has",
"a",
"legacy",
"mode",
"which",
"sends",
"requests",
"to",
"the",
"MW",
"core",
"API",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/mw/Batcher.js#L20-L33
|
15,047
|
wikimedia/parsoid
|
bin/inspectTokenizer.js
|
function(node) {
if (node.code) {
// remove trailing whitespace for single-line predicates
var code = node.code.replace(/[ \t]+$/, '');
// wrap with a function, to prevent spurious errors caused
// by redeclarations or multiple returns in a block.
rulesSource += tab + '(function() {\n' + code + '\n' +
tab + '})();\n';
}
}
|
javascript
|
function(node) {
if (node.code) {
// remove trailing whitespace for single-line predicates
var code = node.code.replace(/[ \t]+$/, '');
// wrap with a function, to prevent spurious errors caused
// by redeclarations or multiple returns in a block.
rulesSource += tab + '(function() {\n' + code + '\n' +
tab + '})();\n';
}
}
|
[
"function",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"code",
")",
"{",
"// remove trailing whitespace for single-line predicates",
"var",
"code",
"=",
"node",
".",
"code",
".",
"replace",
"(",
"/",
"[ \\t]+$",
"/",
",",
"''",
")",
";",
"// wrap with a function, to prevent spurious errors caused",
"// by redeclarations or multiple returns in a block.",
"rulesSource",
"+=",
"tab",
"+",
"'(function() {\\n'",
"+",
"code",
"+",
"'\\n'",
"+",
"tab",
"+",
"'})();\\n'",
";",
"}",
"}"
] |
Collect all the code blocks in the AST.
|
[
"Collect",
"all",
"the",
"code",
"blocks",
"in",
"the",
"AST",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/bin/inspectTokenizer.js#L101-L110
|
|
15,048
|
wikimedia/parsoid
|
lib/wt2html/parser.js
|
function(options) {
if (!options) { options = {}; }
Object.keys(options).forEach(function(k) {
console.assert(supportedOptions.has(k), 'Invalid cacheKey option: ' + k);
});
// default: not an include context
if (options.isInclude === undefined) {
options.isInclude = false;
}
// default: wrap templates
if (options.expandTemplates === undefined) {
options.expandTemplates = true;
}
return options;
}
|
javascript
|
function(options) {
if (!options) { options = {}; }
Object.keys(options).forEach(function(k) {
console.assert(supportedOptions.has(k), 'Invalid cacheKey option: ' + k);
});
// default: not an include context
if (options.isInclude === undefined) {
options.isInclude = false;
}
// default: wrap templates
if (options.expandTemplates === undefined) {
options.expandTemplates = true;
}
return options;
}
|
[
"function",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"options",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"Object",
".",
"keys",
"(",
"options",
")",
".",
"forEach",
"(",
"function",
"(",
"k",
")",
"{",
"console",
".",
"assert",
"(",
"supportedOptions",
".",
"has",
"(",
"k",
")",
",",
"'Invalid cacheKey option: '",
"+",
"k",
")",
";",
"}",
")",
";",
"// default: not an include context",
"if",
"(",
"options",
".",
"isInclude",
"===",
"undefined",
")",
"{",
"options",
".",
"isInclude",
"=",
"false",
";",
"}",
"// default: wrap templates",
"if",
"(",
"options",
".",
"expandTemplates",
"===",
"undefined",
")",
"{",
"options",
".",
"expandTemplates",
"=",
"true",
";",
"}",
"return",
"options",
";",
"}"
] |
Default options processing
|
[
"Default",
"options",
"processing"
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/wt2html/parser.js#L213-L231
|
|
15,049
|
wikimedia/parsoid
|
lib/html2wt/WikitextEscapeHandlers.js
|
startsOnANewLine
|
function startsOnANewLine(node) {
var name = node.nodeName.toUpperCase();
return Consts.BlockScopeOpenTags.has(name) &&
!WTUtils.isLiteralHTMLNode(node) &&
name !== "BLOCKQUOTE";
}
|
javascript
|
function startsOnANewLine(node) {
var name = node.nodeName.toUpperCase();
return Consts.BlockScopeOpenTags.has(name) &&
!WTUtils.isLiteralHTMLNode(node) &&
name !== "BLOCKQUOTE";
}
|
[
"function",
"startsOnANewLine",
"(",
"node",
")",
"{",
"var",
"name",
"=",
"node",
".",
"nodeName",
".",
"toUpperCase",
"(",
")",
";",
"return",
"Consts",
".",
"BlockScopeOpenTags",
".",
"has",
"(",
"name",
")",
"&&",
"!",
"WTUtils",
".",
"isLiteralHTMLNode",
"(",
"node",
")",
"&&",
"name",
"!==",
"\"BLOCKQUOTE\"",
";",
"}"
] |
ignore the cases where the serializer adds newlines not present in the dom
|
[
"ignore",
"the",
"cases",
"where",
"the",
"serializer",
"adds",
"newlines",
"not",
"present",
"in",
"the",
"dom"
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/html2wt/WikitextEscapeHandlers.js#L18-L23
|
15,050
|
wikimedia/parsoid
|
lib/html2wt/WikitextEscapeHandlers.js
|
hasBlocksOnLine
|
function hasBlocksOnLine(node, first) {
// special case for firstNode:
// we're at sol so ignore possible \n at first char
if (first) {
if (node.textContent.substring(1).match(/\n/)) {
return false;
}
node = node.nextSibling;
}
while (node) {
if (DOMUtils.isElt(node)) {
if (DOMUtils.isBlockNode(node)) {
return !startsOnANewLine(node);
}
if (node.hasChildNodes()) {
if (hasBlocksOnLine(node.firstChild, false)) {
return true;
}
}
} else {
if (node.textContent.match(/\n/)) {
return false;
}
}
node = node.nextSibling;
}
return false;
}
|
javascript
|
function hasBlocksOnLine(node, first) {
// special case for firstNode:
// we're at sol so ignore possible \n at first char
if (first) {
if (node.textContent.substring(1).match(/\n/)) {
return false;
}
node = node.nextSibling;
}
while (node) {
if (DOMUtils.isElt(node)) {
if (DOMUtils.isBlockNode(node)) {
return !startsOnANewLine(node);
}
if (node.hasChildNodes()) {
if (hasBlocksOnLine(node.firstChild, false)) {
return true;
}
}
} else {
if (node.textContent.match(/\n/)) {
return false;
}
}
node = node.nextSibling;
}
return false;
}
|
[
"function",
"hasBlocksOnLine",
"(",
"node",
",",
"first",
")",
"{",
"// special case for firstNode:",
"// we're at sol so ignore possible \\n at first char",
"if",
"(",
"first",
")",
"{",
"if",
"(",
"node",
".",
"textContent",
".",
"substring",
"(",
"1",
")",
".",
"match",
"(",
"/",
"\\n",
"/",
")",
")",
"{",
"return",
"false",
";",
"}",
"node",
"=",
"node",
".",
"nextSibling",
";",
"}",
"while",
"(",
"node",
")",
"{",
"if",
"(",
"DOMUtils",
".",
"isElt",
"(",
"node",
")",
")",
"{",
"if",
"(",
"DOMUtils",
".",
"isBlockNode",
"(",
"node",
")",
")",
"{",
"return",
"!",
"startsOnANewLine",
"(",
"node",
")",
";",
"}",
"if",
"(",
"node",
".",
"hasChildNodes",
"(",
")",
")",
"{",
"if",
"(",
"hasBlocksOnLine",
"(",
"node",
".",
"firstChild",
",",
"false",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"node",
".",
"textContent",
".",
"match",
"(",
"/",
"\\n",
"/",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"node",
"=",
"node",
".",
"nextSibling",
";",
"}",
"return",
"false",
";",
"}"
] |
look ahead on current line for block content
|
[
"look",
"ahead",
"on",
"current",
"line",
"for",
"block",
"content"
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/html2wt/WikitextEscapeHandlers.js#L26-L55
|
15,051
|
wikimedia/parsoid
|
lib/logger/Logger.js
|
logTypeToString
|
function logTypeToString(logType) {
var logTypeString;
if (logType instanceof RegExp) {
logTypeString = logType.source;
} else if (typeof (logType) === 'string') {
logTypeString = '^' + JSUtils.escapeRegExp(logType) + '$';
} else {
throw new Error('logType is neither a regular expression nor a string.');
}
return logTypeString;
}
|
javascript
|
function logTypeToString(logType) {
var logTypeString;
if (logType instanceof RegExp) {
logTypeString = logType.source;
} else if (typeof (logType) === 'string') {
logTypeString = '^' + JSUtils.escapeRegExp(logType) + '$';
} else {
throw new Error('logType is neither a regular expression nor a string.');
}
return logTypeString;
}
|
[
"function",
"logTypeToString",
"(",
"logType",
")",
"{",
"var",
"logTypeString",
";",
"if",
"(",
"logType",
"instanceof",
"RegExp",
")",
"{",
"logTypeString",
"=",
"logType",
".",
"source",
";",
"}",
"else",
"if",
"(",
"typeof",
"(",
"logType",
")",
"===",
"'string'",
")",
"{",
"logTypeString",
"=",
"'^'",
"+",
"JSUtils",
".",
"escapeRegExp",
"(",
"logType",
")",
"+",
"'$'",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'logType is neither a regular expression nor a string.'",
")",
";",
"}",
"return",
"logTypeString",
";",
"}"
] |
Convert logType into a source string for a regExp that we can
subsequently use to test logTypes passed in from Logger.log.
@param {RegExp} logType
@return {string}
@private
|
[
"Convert",
"logType",
"into",
"a",
"source",
"string",
"for",
"a",
"regExp",
"that",
"we",
"can",
"subsequently",
"use",
"to",
"test",
"logTypes",
"passed",
"in",
"from",
"Logger",
".",
"log",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/logger/Logger.js#L123-L133
|
15,052
|
wikimedia/parsoid
|
lib/config/MWParserEnvironment.js
|
function(parsoidConfig, options) {
options = options || {};
// page information
this.page = new Page();
Object.assign(this, options);
// Record time spent in various passes
this.timeProfile = {};
this.ioProfile = {};
this.mwProfile = {};
this.timeCategories = {};
this.counts = {};
// execution state
this.setCaches({});
// Configuration
this.conf = {
parsoid: parsoidConfig,
wiki: null,
};
// FIXME: This is temporary and will be replaced after the call to
// `switchToConfig`. However, it may somehow be used in the
// `ConfigRequest` along the way. Perhaps worth seeing if that can be
// eliminated so `WikiConfig` can't be instantiated without a `resultConf`.
console.assert(parsoidConfig.mwApiMap.has(options.prefix));
this.conf.wiki = new WikiConfig(parsoidConfig, null, options.prefix);
this.configureLogging();
// FIXME: Continuing with the line above, we can't initialize a specific
// page until we have the correct wiki config, since things like
// namespace aliases may not be same as the baseconfig, which has an
// effect on what are considered valid titles. At present, the only
// consequence should be that failed config requests would all be
// attributed to the mainpage, which doesn't seem so bad.
this.initializeForPageName(this.conf.wiki.mainpage);
this.pipelineFactory = new ParserPipelineFactory(this);
// Outstanding page requests (for templates etc)
this.requestQueue = {};
this.batcher = new Batcher(this);
this.setResourceLimits();
// Fragments have had `storeDataAttribs` called on them
this.fragmentMap = new Map();
this.fid = 1;
}
|
javascript
|
function(parsoidConfig, options) {
options = options || {};
// page information
this.page = new Page();
Object.assign(this, options);
// Record time spent in various passes
this.timeProfile = {};
this.ioProfile = {};
this.mwProfile = {};
this.timeCategories = {};
this.counts = {};
// execution state
this.setCaches({});
// Configuration
this.conf = {
parsoid: parsoidConfig,
wiki: null,
};
// FIXME: This is temporary and will be replaced after the call to
// `switchToConfig`. However, it may somehow be used in the
// `ConfigRequest` along the way. Perhaps worth seeing if that can be
// eliminated so `WikiConfig` can't be instantiated without a `resultConf`.
console.assert(parsoidConfig.mwApiMap.has(options.prefix));
this.conf.wiki = new WikiConfig(parsoidConfig, null, options.prefix);
this.configureLogging();
// FIXME: Continuing with the line above, we can't initialize a specific
// page until we have the correct wiki config, since things like
// namespace aliases may not be same as the baseconfig, which has an
// effect on what are considered valid titles. At present, the only
// consequence should be that failed config requests would all be
// attributed to the mainpage, which doesn't seem so bad.
this.initializeForPageName(this.conf.wiki.mainpage);
this.pipelineFactory = new ParserPipelineFactory(this);
// Outstanding page requests (for templates etc)
this.requestQueue = {};
this.batcher = new Batcher(this);
this.setResourceLimits();
// Fragments have had `storeDataAttribs` called on them
this.fragmentMap = new Map();
this.fid = 1;
}
|
[
"function",
"(",
"parsoidConfig",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"// page information",
"this",
".",
"page",
"=",
"new",
"Page",
"(",
")",
";",
"Object",
".",
"assign",
"(",
"this",
",",
"options",
")",
";",
"// Record time spent in various passes",
"this",
".",
"timeProfile",
"=",
"{",
"}",
";",
"this",
".",
"ioProfile",
"=",
"{",
"}",
";",
"this",
".",
"mwProfile",
"=",
"{",
"}",
";",
"this",
".",
"timeCategories",
"=",
"{",
"}",
";",
"this",
".",
"counts",
"=",
"{",
"}",
";",
"// execution state",
"this",
".",
"setCaches",
"(",
"{",
"}",
")",
";",
"// Configuration",
"this",
".",
"conf",
"=",
"{",
"parsoid",
":",
"parsoidConfig",
",",
"wiki",
":",
"null",
",",
"}",
";",
"// FIXME: This is temporary and will be replaced after the call to",
"// `switchToConfig`. However, it may somehow be used in the",
"// `ConfigRequest` along the way. Perhaps worth seeing if that can be",
"// eliminated so `WikiConfig` can't be instantiated without a `resultConf`.",
"console",
".",
"assert",
"(",
"parsoidConfig",
".",
"mwApiMap",
".",
"has",
"(",
"options",
".",
"prefix",
")",
")",
";",
"this",
".",
"conf",
".",
"wiki",
"=",
"new",
"WikiConfig",
"(",
"parsoidConfig",
",",
"null",
",",
"options",
".",
"prefix",
")",
";",
"this",
".",
"configureLogging",
"(",
")",
";",
"// FIXME: Continuing with the line above, we can't initialize a specific",
"// page until we have the correct wiki config, since things like",
"// namespace aliases may not be same as the baseconfig, which has an",
"// effect on what are considered valid titles. At present, the only",
"// consequence should be that failed config requests would all be",
"// attributed to the mainpage, which doesn't seem so bad.",
"this",
".",
"initializeForPageName",
"(",
"this",
".",
"conf",
".",
"wiki",
".",
"mainpage",
")",
";",
"this",
".",
"pipelineFactory",
"=",
"new",
"ParserPipelineFactory",
"(",
"this",
")",
";",
"// Outstanding page requests (for templates etc)",
"this",
".",
"requestQueue",
"=",
"{",
"}",
";",
"this",
".",
"batcher",
"=",
"new",
"Batcher",
"(",
"this",
")",
";",
"this",
".",
"setResourceLimits",
"(",
")",
";",
"// Fragments have had `storeDataAttribs` called on them",
"this",
".",
"fragmentMap",
"=",
"new",
"Map",
"(",
")",
";",
"this",
".",
"fid",
"=",
"1",
";",
"}"
] |
Holds configuration data that isn't modified at runtime, debugging objects,
a page object that represents the page we're parsing, and more.
The title of the page is held in `this.page.name` and is stored
as a "true" url-decoded title, ie without any url-encoding which
might be necessary if the title were referenced in wikitext.
Should probably be constructed with {@link .getParserEnv}.
@class
@param {ParsoidConfig} parsoidConfig
@param {Object} [options]
|
[
"Holds",
"configuration",
"data",
"that",
"isn",
"t",
"modified",
"at",
"runtime",
"debugging",
"objects",
"a",
"page",
"object",
"that",
"represents",
"the",
"page",
"we",
"re",
"parsing",
"and",
"more",
".",
"The",
"title",
"of",
"the",
"page",
"is",
"held",
"in",
"this",
".",
"page",
".",
"name",
"and",
"is",
"stored",
"as",
"a",
"true",
"url",
"-",
"decoded",
"title",
"ie",
"without",
"any",
"url",
"-",
"encoding",
"which",
"might",
"be",
"necessary",
"if",
"the",
"title",
"were",
"referenced",
"in",
"wikitext",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/config/MWParserEnvironment.js#L137-L190
|
|
15,053
|
wikimedia/parsoid
|
lib/mw/ApiRequest.js
|
TemplateRequest
|
function TemplateRequest(env, title, oldid, opts) {
ApiRequest.call(this, env, title);
// IMPORTANT: Set queueKey to the 'title'
// since TemplateHandler uses it for recording listeners
this.queueKey = title;
this.reqType = "Template Fetch";
opts = opts || {}; // optional extra arguments
var apiargs = {
format: 'json',
// XXX: should use formatversion=2
action: 'query',
prop: 'info|revisions',
rawcontinue: 1,
// all revision properties which parsoid is interested in.
rvprop: 'content|ids|timestamp|size|sha1|contentmodel',
rvslots: 'main',
};
if (oldid) {
this.oldid = oldid;
apiargs.revids = oldid;
} else {
apiargs.titles = title;
}
this.requestOptions = {
method: 'GET',
followRedirect: true,
uri: env.conf.wiki.apiURI,
qs: apiargs,
timeout: env.conf.parsoid.timeouts.mwApi.srcFetch,
};
this.request(this.requestOptions);
}
|
javascript
|
function TemplateRequest(env, title, oldid, opts) {
ApiRequest.call(this, env, title);
// IMPORTANT: Set queueKey to the 'title'
// since TemplateHandler uses it for recording listeners
this.queueKey = title;
this.reqType = "Template Fetch";
opts = opts || {}; // optional extra arguments
var apiargs = {
format: 'json',
// XXX: should use formatversion=2
action: 'query',
prop: 'info|revisions',
rawcontinue: 1,
// all revision properties which parsoid is interested in.
rvprop: 'content|ids|timestamp|size|sha1|contentmodel',
rvslots: 'main',
};
if (oldid) {
this.oldid = oldid;
apiargs.revids = oldid;
} else {
apiargs.titles = title;
}
this.requestOptions = {
method: 'GET',
followRedirect: true,
uri: env.conf.wiki.apiURI,
qs: apiargs,
timeout: env.conf.parsoid.timeouts.mwApi.srcFetch,
};
this.request(this.requestOptions);
}
|
[
"function",
"TemplateRequest",
"(",
"env",
",",
"title",
",",
"oldid",
",",
"opts",
")",
"{",
"ApiRequest",
".",
"call",
"(",
"this",
",",
"env",
",",
"title",
")",
";",
"// IMPORTANT: Set queueKey to the 'title'",
"// since TemplateHandler uses it for recording listeners",
"this",
".",
"queueKey",
"=",
"title",
";",
"this",
".",
"reqType",
"=",
"\"Template Fetch\"",
";",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"// optional extra arguments",
"var",
"apiargs",
"=",
"{",
"format",
":",
"'json'",
",",
"// XXX: should use formatversion=2",
"action",
":",
"'query'",
",",
"prop",
":",
"'info|revisions'",
",",
"rawcontinue",
":",
"1",
",",
"// all revision properties which parsoid is interested in.",
"rvprop",
":",
"'content|ids|timestamp|size|sha1|contentmodel'",
",",
"rvslots",
":",
"'main'",
",",
"}",
";",
"if",
"(",
"oldid",
")",
"{",
"this",
".",
"oldid",
"=",
"oldid",
";",
"apiargs",
".",
"revids",
"=",
"oldid",
";",
"}",
"else",
"{",
"apiargs",
".",
"titles",
"=",
"title",
";",
"}",
"this",
".",
"requestOptions",
"=",
"{",
"method",
":",
"'GET'",
",",
"followRedirect",
":",
"true",
",",
"uri",
":",
"env",
".",
"conf",
".",
"wiki",
".",
"apiURI",
",",
"qs",
":",
"apiargs",
",",
"timeout",
":",
"env",
".",
"conf",
".",
"parsoid",
".",
"timeouts",
".",
"mwApi",
".",
"srcFetch",
",",
"}",
";",
"this",
".",
"request",
"(",
"this",
".",
"requestOptions",
")",
";",
"}"
] |
Template fetch request helper class.
@class
@extends ~ApiRequest
@param {MWParserEnvironment} env
@param {string} title The template (or really, page) we should fetch from the wiki.
@param {string} oldid The revision ID you want to get, defaults to "latest revision".
|
[
"Template",
"fetch",
"request",
"helper",
"class",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/mw/ApiRequest.js#L502-L537
|
15,054
|
wikimedia/parsoid
|
lib/mw/ApiRequest.js
|
PreprocessorRequest
|
function PreprocessorRequest(env, title, text, queueKey) {
ApiRequest.call(this, env, title);
this.queueKey = queueKey;
this.text = text;
this.reqType = "Template Expansion";
var apiargs = {
format: 'json',
formatversion: 2,
action: 'expandtemplates',
prop: 'wikitext|categories|properties|modules|jsconfigvars',
text: text,
};
// the empty string is an invalid title
// default value is: API
if (title) {
apiargs.title = title;
}
if (env.page.meta.revision.revid) {
apiargs.revid = env.page.meta.revision.revid;
}
this.requestOptions = {
// Use POST since we are passing a bit of source, and GET has a very
// limited length. You'll be greeted by "HTTP Error 414 Request URI
// too long" otherwise ;)
method: 'POST',
form: apiargs, // The API arguments
followRedirect: true,
uri: env.conf.wiki.apiURI,
timeout: env.conf.parsoid.timeouts.mwApi.preprocessor,
};
this.request(this.requestOptions);
}
|
javascript
|
function PreprocessorRequest(env, title, text, queueKey) {
ApiRequest.call(this, env, title);
this.queueKey = queueKey;
this.text = text;
this.reqType = "Template Expansion";
var apiargs = {
format: 'json',
formatversion: 2,
action: 'expandtemplates',
prop: 'wikitext|categories|properties|modules|jsconfigvars',
text: text,
};
// the empty string is an invalid title
// default value is: API
if (title) {
apiargs.title = title;
}
if (env.page.meta.revision.revid) {
apiargs.revid = env.page.meta.revision.revid;
}
this.requestOptions = {
// Use POST since we are passing a bit of source, and GET has a very
// limited length. You'll be greeted by "HTTP Error 414 Request URI
// too long" otherwise ;)
method: 'POST',
form: apiargs, // The API arguments
followRedirect: true,
uri: env.conf.wiki.apiURI,
timeout: env.conf.parsoid.timeouts.mwApi.preprocessor,
};
this.request(this.requestOptions);
}
|
[
"function",
"PreprocessorRequest",
"(",
"env",
",",
"title",
",",
"text",
",",
"queueKey",
")",
"{",
"ApiRequest",
".",
"call",
"(",
"this",
",",
"env",
",",
"title",
")",
";",
"this",
".",
"queueKey",
"=",
"queueKey",
";",
"this",
".",
"text",
"=",
"text",
";",
"this",
".",
"reqType",
"=",
"\"Template Expansion\"",
";",
"var",
"apiargs",
"=",
"{",
"format",
":",
"'json'",
",",
"formatversion",
":",
"2",
",",
"action",
":",
"'expandtemplates'",
",",
"prop",
":",
"'wikitext|categories|properties|modules|jsconfigvars'",
",",
"text",
":",
"text",
",",
"}",
";",
"// the empty string is an invalid title",
"// default value is: API",
"if",
"(",
"title",
")",
"{",
"apiargs",
".",
"title",
"=",
"title",
";",
"}",
"if",
"(",
"env",
".",
"page",
".",
"meta",
".",
"revision",
".",
"revid",
")",
"{",
"apiargs",
".",
"revid",
"=",
"env",
".",
"page",
".",
"meta",
".",
"revision",
".",
"revid",
";",
"}",
"this",
".",
"requestOptions",
"=",
"{",
"// Use POST since we are passing a bit of source, and GET has a very",
"// limited length. You'll be greeted by \"HTTP Error 414 Request URI",
"// too long\" otherwise ;)",
"method",
":",
"'POST'",
",",
"form",
":",
"apiargs",
",",
"// The API arguments",
"followRedirect",
":",
"true",
",",
"uri",
":",
"env",
".",
"conf",
".",
"wiki",
".",
"apiURI",
",",
"timeout",
":",
"env",
".",
"conf",
".",
"parsoid",
".",
"timeouts",
".",
"mwApi",
".",
"preprocessor",
",",
"}",
";",
"this",
".",
"request",
"(",
"this",
".",
"requestOptions",
")",
";",
"}"
] |
Passes the source of a single preprocessor construct including its
parameters to action=expandtemplates.
@class
@extends ~ApiRequest
@param {MWParserEnvironment} env
@param {string} title The title of the page to use as the context.
@param {string} text
@param {string} queueKey The queue key.
|
[
"Passes",
"the",
"source",
"of",
"a",
"single",
"preprocessor",
"construct",
"including",
"its",
"parameters",
"to",
"action",
"=",
"expandtemplates",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/mw/ApiRequest.js#L639-L675
|
15,055
|
wikimedia/parsoid
|
lib/mw/ApiRequest.js
|
PHPParseRequest
|
function PHPParseRequest(env, title, text, onlypst, queueKey) {
ApiRequest.call(this, env, title);
this.text = text;
this.queueKey = queueKey || text;
this.reqType = "Extension Parse";
var apiargs = {
format: 'json',
formatversion: 2,
action: 'parse',
text: text,
disablelimitreport: 'true',
contentmodel: 'wikitext',
prop: 'text|modules|jsconfigvars|categories',
wrapoutputclass: '',
};
if (onlypst) {
apiargs.onlypst = 'true';
}
// Pass the page title to the API
if (title) {
apiargs.title = title;
}
if (env.page.meta.revision.revid) {
apiargs.revid = env.page.meta.revision.revid;
}
this.requestOptions = {
// Use POST since we are passing a bit of source, and GET has a very
// limited length. You'll be greeted by "HTTP Error 414 Request URI
// too long" otherwise ;)
method: 'POST',
form: apiargs, // The API arguments
followRedirect: true,
uri: env.conf.wiki.apiURI,
timeout: env.conf.parsoid.timeouts.mwApi.extParse,
};
this.request(this.requestOptions);
}
|
javascript
|
function PHPParseRequest(env, title, text, onlypst, queueKey) {
ApiRequest.call(this, env, title);
this.text = text;
this.queueKey = queueKey || text;
this.reqType = "Extension Parse";
var apiargs = {
format: 'json',
formatversion: 2,
action: 'parse',
text: text,
disablelimitreport: 'true',
contentmodel: 'wikitext',
prop: 'text|modules|jsconfigvars|categories',
wrapoutputclass: '',
};
if (onlypst) {
apiargs.onlypst = 'true';
}
// Pass the page title to the API
if (title) {
apiargs.title = title;
}
if (env.page.meta.revision.revid) {
apiargs.revid = env.page.meta.revision.revid;
}
this.requestOptions = {
// Use POST since we are passing a bit of source, and GET has a very
// limited length. You'll be greeted by "HTTP Error 414 Request URI
// too long" otherwise ;)
method: 'POST',
form: apiargs, // The API arguments
followRedirect: true,
uri: env.conf.wiki.apiURI,
timeout: env.conf.parsoid.timeouts.mwApi.extParse,
};
this.request(this.requestOptions);
}
|
[
"function",
"PHPParseRequest",
"(",
"env",
",",
"title",
",",
"text",
",",
"onlypst",
",",
"queueKey",
")",
"{",
"ApiRequest",
".",
"call",
"(",
"this",
",",
"env",
",",
"title",
")",
";",
"this",
".",
"text",
"=",
"text",
";",
"this",
".",
"queueKey",
"=",
"queueKey",
"||",
"text",
";",
"this",
".",
"reqType",
"=",
"\"Extension Parse\"",
";",
"var",
"apiargs",
"=",
"{",
"format",
":",
"'json'",
",",
"formatversion",
":",
"2",
",",
"action",
":",
"'parse'",
",",
"text",
":",
"text",
",",
"disablelimitreport",
":",
"'true'",
",",
"contentmodel",
":",
"'wikitext'",
",",
"prop",
":",
"'text|modules|jsconfigvars|categories'",
",",
"wrapoutputclass",
":",
"''",
",",
"}",
";",
"if",
"(",
"onlypst",
")",
"{",
"apiargs",
".",
"onlypst",
"=",
"'true'",
";",
"}",
"// Pass the page title to the API",
"if",
"(",
"title",
")",
"{",
"apiargs",
".",
"title",
"=",
"title",
";",
"}",
"if",
"(",
"env",
".",
"page",
".",
"meta",
".",
"revision",
".",
"revid",
")",
"{",
"apiargs",
".",
"revid",
"=",
"env",
".",
"page",
".",
"meta",
".",
"revision",
".",
"revid",
";",
"}",
"this",
".",
"requestOptions",
"=",
"{",
"// Use POST since we are passing a bit of source, and GET has a very",
"// limited length. You'll be greeted by \"HTTP Error 414 Request URI",
"// too long\" otherwise ;)",
"method",
":",
"'POST'",
",",
"form",
":",
"apiargs",
",",
"// The API arguments",
"followRedirect",
":",
"true",
",",
"uri",
":",
"env",
".",
"conf",
".",
"wiki",
".",
"apiURI",
",",
"timeout",
":",
"env",
".",
"conf",
".",
"parsoid",
".",
"timeouts",
".",
"mwApi",
".",
"extParse",
",",
"}",
";",
"this",
".",
"request",
"(",
"this",
".",
"requestOptions",
")",
";",
"}"
] |
Gets the PHP parser to parse content for us.
Used for handling extension content right now.
And, probably magic words later on.
@class
@extends ~ApiRequest
@param {MWParserEnvironment} env
@param {string} title The title of the page to use as context.
@param {string} text
@param {boolean} [onlypst] Pass onlypst to PHP parser.
@param {string} [queueKey] The queue key.
|
[
"Gets",
"the",
"PHP",
"parser",
"to",
"parse",
"content",
"for",
"us",
".",
"Used",
"for",
"handling",
"extension",
"content",
"right",
"now",
".",
"And",
"probably",
"magic",
"words",
"later",
"on",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/mw/ApiRequest.js#L706-L747
|
15,056
|
wikimedia/parsoid
|
lib/mw/ApiRequest.js
|
BatchRequest
|
function BatchRequest(env, batchParams, key) {
ApiRequest.call(this, env);
this.queueKey = key;
this.batchParams = batchParams;
this.reqType = 'Batch request';
this.batchText = JSON.stringify(batchParams);
var apiargs = {
format: 'json',
formatversion: 2,
action: 'parsoid-batch',
batch: this.batchText,
};
this.requestOptions = {
method: 'POST',
followRedirect: true,
uri: env.conf.wiki.apiURI,
timeout: env.conf.parsoid.timeouts.mwApi.batch,
};
// Use multipart form encoding to get more efficient transfer if the gain
// will be larger than the typical overhead.
if (encodeURIComponent(apiargs.batch).length - apiargs.batch.length > 600) {
this.requestOptions.formData = apiargs;
} else {
this.requestOptions.form = apiargs;
}
this.request(this.requestOptions);
}
|
javascript
|
function BatchRequest(env, batchParams, key) {
ApiRequest.call(this, env);
this.queueKey = key;
this.batchParams = batchParams;
this.reqType = 'Batch request';
this.batchText = JSON.stringify(batchParams);
var apiargs = {
format: 'json',
formatversion: 2,
action: 'parsoid-batch',
batch: this.batchText,
};
this.requestOptions = {
method: 'POST',
followRedirect: true,
uri: env.conf.wiki.apiURI,
timeout: env.conf.parsoid.timeouts.mwApi.batch,
};
// Use multipart form encoding to get more efficient transfer if the gain
// will be larger than the typical overhead.
if (encodeURIComponent(apiargs.batch).length - apiargs.batch.length > 600) {
this.requestOptions.formData = apiargs;
} else {
this.requestOptions.form = apiargs;
}
this.request(this.requestOptions);
}
|
[
"function",
"BatchRequest",
"(",
"env",
",",
"batchParams",
",",
"key",
")",
"{",
"ApiRequest",
".",
"call",
"(",
"this",
",",
"env",
")",
";",
"this",
".",
"queueKey",
"=",
"key",
";",
"this",
".",
"batchParams",
"=",
"batchParams",
";",
"this",
".",
"reqType",
"=",
"'Batch request'",
";",
"this",
".",
"batchText",
"=",
"JSON",
".",
"stringify",
"(",
"batchParams",
")",
";",
"var",
"apiargs",
"=",
"{",
"format",
":",
"'json'",
",",
"formatversion",
":",
"2",
",",
"action",
":",
"'parsoid-batch'",
",",
"batch",
":",
"this",
".",
"batchText",
",",
"}",
";",
"this",
".",
"requestOptions",
"=",
"{",
"method",
":",
"'POST'",
",",
"followRedirect",
":",
"true",
",",
"uri",
":",
"env",
".",
"conf",
".",
"wiki",
".",
"apiURI",
",",
"timeout",
":",
"env",
".",
"conf",
".",
"parsoid",
".",
"timeouts",
".",
"mwApi",
".",
"batch",
",",
"}",
";",
"// Use multipart form encoding to get more efficient transfer if the gain",
"// will be larger than the typical overhead.",
"if",
"(",
"encodeURIComponent",
"(",
"apiargs",
".",
"batch",
")",
".",
"length",
"-",
"apiargs",
".",
"batch",
".",
"length",
">",
"600",
")",
"{",
"this",
".",
"requestOptions",
".",
"formData",
"=",
"apiargs",
";",
"}",
"else",
"{",
"this",
".",
"requestOptions",
".",
"form",
"=",
"apiargs",
";",
"}",
"this",
".",
"request",
"(",
"this",
".",
"requestOptions",
")",
";",
"}"
] |
Do a mixed-action batch request using the ParsoidBatchAPI extension.
@class
@extends ~ApiRequest
@param {MWParserEnvironment} env
@param {Array} batchParams An array of objects.
@param {string} key The queue key.
|
[
"Do",
"a",
"mixed",
"-",
"action",
"batch",
"request",
"using",
"the",
"ParsoidBatchAPI",
"extension",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/mw/ApiRequest.js#L776-L806
|
15,057
|
wikimedia/parsoid
|
lib/mw/ApiRequest.js
|
function(env) {
ApiRequest.call(this, env, null);
this.queueKey = env.conf.wiki.apiURI;
this.reqType = "Config Request";
var metas = [ 'siteinfo' ];
var siprops = [
'namespaces',
'namespacealiases',
'magicwords',
'functionhooks',
'extensiontags',
'general',
'interwikimap',
'languages',
'languagevariants', // T153341
'protocols',
'specialpagealiases',
'defaultoptions',
'variables',
];
var apiargs = {
format: 'json',
// XXX: should use formatversion=2
action: 'query',
meta: metas.join('|'),
siprop: siprops.join('|'),
rawcontinue: 1,
};
this.requestOptions = {
method: 'GET',
followRedirect: true,
uri: env.conf.wiki.apiURI,
qs: apiargs,
timeout: env.conf.parsoid.timeouts.mwApi.configInfo,
};
this.request(this.requestOptions);
}
|
javascript
|
function(env) {
ApiRequest.call(this, env, null);
this.queueKey = env.conf.wiki.apiURI;
this.reqType = "Config Request";
var metas = [ 'siteinfo' ];
var siprops = [
'namespaces',
'namespacealiases',
'magicwords',
'functionhooks',
'extensiontags',
'general',
'interwikimap',
'languages',
'languagevariants', // T153341
'protocols',
'specialpagealiases',
'defaultoptions',
'variables',
];
var apiargs = {
format: 'json',
// XXX: should use formatversion=2
action: 'query',
meta: metas.join('|'),
siprop: siprops.join('|'),
rawcontinue: 1,
};
this.requestOptions = {
method: 'GET',
followRedirect: true,
uri: env.conf.wiki.apiURI,
qs: apiargs,
timeout: env.conf.parsoid.timeouts.mwApi.configInfo,
};
this.request(this.requestOptions);
}
|
[
"function",
"(",
"env",
")",
"{",
"ApiRequest",
".",
"call",
"(",
"this",
",",
"env",
",",
"null",
")",
";",
"this",
".",
"queueKey",
"=",
"env",
".",
"conf",
".",
"wiki",
".",
"apiURI",
";",
"this",
".",
"reqType",
"=",
"\"Config Request\"",
";",
"var",
"metas",
"=",
"[",
"'siteinfo'",
"]",
";",
"var",
"siprops",
"=",
"[",
"'namespaces'",
",",
"'namespacealiases'",
",",
"'magicwords'",
",",
"'functionhooks'",
",",
"'extensiontags'",
",",
"'general'",
",",
"'interwikimap'",
",",
"'languages'",
",",
"'languagevariants'",
",",
"// T153341",
"'protocols'",
",",
"'specialpagealiases'",
",",
"'defaultoptions'",
",",
"'variables'",
",",
"]",
";",
"var",
"apiargs",
"=",
"{",
"format",
":",
"'json'",
",",
"// XXX: should use formatversion=2",
"action",
":",
"'query'",
",",
"meta",
":",
"metas",
".",
"join",
"(",
"'|'",
")",
",",
"siprop",
":",
"siprops",
".",
"join",
"(",
"'|'",
")",
",",
"rawcontinue",
":",
"1",
",",
"}",
";",
"this",
".",
"requestOptions",
"=",
"{",
"method",
":",
"'GET'",
",",
"followRedirect",
":",
"true",
",",
"uri",
":",
"env",
".",
"conf",
".",
"wiki",
".",
"apiURI",
",",
"qs",
":",
"apiargs",
",",
"timeout",
":",
"env",
".",
"conf",
".",
"parsoid",
".",
"timeouts",
".",
"mwApi",
".",
"configInfo",
",",
"}",
";",
"this",
".",
"request",
"(",
"this",
".",
"requestOptions",
")",
";",
"}"
] |
A request for the wiki's configuration variables.
@class
@extends ~ApiRequest
@param {MWParserEnvironment} env
|
[
"A",
"request",
"for",
"the",
"wiki",
"s",
"configuration",
"variables",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/mw/ApiRequest.js#L867-L906
|
|
15,058
|
wikimedia/parsoid
|
lib/mw/ApiRequest.js
|
ImageInfoRequest
|
function ImageInfoRequest(env, filename, dims, key) {
ApiRequest.call(this, env, null);
this.env = env;
this.queueKey = key;
this.reqType = "Image Info Request";
var conf = env.conf.wiki;
var filenames = [ filename ];
var imgnsid = conf.canonicalNamespaces.image;
var imgns = conf.namespaceNames[imgnsid];
var props = [
'mediatype',
'mime',
'size',
'url',
'badfile',
];
// If the videoinfo prop is available, as determined by our feature
// detection when initializing the wiki config, use that to fetch the
// derivates for videos. videoinfo is just a wrapper for imageinfo,
// so all our media requests should go there, and the response can be
// disambiguated by the returned mediatype.
var prop, prefix;
if (conf.useVideoInfo) {
prop = 'videoinfo';
prefix = 'vi';
props.push('derivatives', 'timedtext');
} else {
prop = 'imageinfo';
prefix = 'ii';
}
this.ns = imgns;
for (var ix = 0; ix < filenames.length; ix++) {
filenames[ix] = imgns + ':' + filenames[ix];
}
var apiArgs = {
action: 'query',
format: 'json',
formatversion: 2,
prop: prop,
titles: filenames.join('|'),
rawcontinue: 1,
};
apiArgs[prefix + 'prop'] = props.join('|');
apiArgs[prefix + 'badfilecontexttitle'] = env.page.name;
if (dims) {
if (dims.width !== undefined && dims.width !== null) {
console.assert(typeof (dims.width) === 'number');
apiArgs[prefix + 'urlwidth'] = dims.width;
if (dims.page !== undefined) {
// NOTE: This format is specific to PDFs. Not sure how to
// support this generally, though it seems common enough /
// shared with other file types.
apiArgs[prefix + 'urlparam'] = `page${dims.page}-${dims.width}px`;
}
}
if (dims.height !== undefined && dims.height !== null) {
console.assert(typeof (dims.height) === 'number');
apiArgs[prefix + 'urlheight'] = dims.height;
}
if (dims.seek !== undefined) {
apiArgs[prefix + 'urlparam'] = `seek=${dims.seek}`;
}
}
this.requestOptions = {
method: 'GET',
followRedirect: true,
uri: env.conf.wiki.apiURI,
qs: apiArgs,
timeout: env.conf.parsoid.timeouts.mwApi.imgInfo,
};
this.request(this.requestOptions);
}
|
javascript
|
function ImageInfoRequest(env, filename, dims, key) {
ApiRequest.call(this, env, null);
this.env = env;
this.queueKey = key;
this.reqType = "Image Info Request";
var conf = env.conf.wiki;
var filenames = [ filename ];
var imgnsid = conf.canonicalNamespaces.image;
var imgns = conf.namespaceNames[imgnsid];
var props = [
'mediatype',
'mime',
'size',
'url',
'badfile',
];
// If the videoinfo prop is available, as determined by our feature
// detection when initializing the wiki config, use that to fetch the
// derivates for videos. videoinfo is just a wrapper for imageinfo,
// so all our media requests should go there, and the response can be
// disambiguated by the returned mediatype.
var prop, prefix;
if (conf.useVideoInfo) {
prop = 'videoinfo';
prefix = 'vi';
props.push('derivatives', 'timedtext');
} else {
prop = 'imageinfo';
prefix = 'ii';
}
this.ns = imgns;
for (var ix = 0; ix < filenames.length; ix++) {
filenames[ix] = imgns + ':' + filenames[ix];
}
var apiArgs = {
action: 'query',
format: 'json',
formatversion: 2,
prop: prop,
titles: filenames.join('|'),
rawcontinue: 1,
};
apiArgs[prefix + 'prop'] = props.join('|');
apiArgs[prefix + 'badfilecontexttitle'] = env.page.name;
if (dims) {
if (dims.width !== undefined && dims.width !== null) {
console.assert(typeof (dims.width) === 'number');
apiArgs[prefix + 'urlwidth'] = dims.width;
if (dims.page !== undefined) {
// NOTE: This format is specific to PDFs. Not sure how to
// support this generally, though it seems common enough /
// shared with other file types.
apiArgs[prefix + 'urlparam'] = `page${dims.page}-${dims.width}px`;
}
}
if (dims.height !== undefined && dims.height !== null) {
console.assert(typeof (dims.height) === 'number');
apiArgs[prefix + 'urlheight'] = dims.height;
}
if (dims.seek !== undefined) {
apiArgs[prefix + 'urlparam'] = `seek=${dims.seek}`;
}
}
this.requestOptions = {
method: 'GET',
followRedirect: true,
uri: env.conf.wiki.apiURI,
qs: apiArgs,
timeout: env.conf.parsoid.timeouts.mwApi.imgInfo,
};
this.request(this.requestOptions);
}
|
[
"function",
"ImageInfoRequest",
"(",
"env",
",",
"filename",
",",
"dims",
",",
"key",
")",
"{",
"ApiRequest",
".",
"call",
"(",
"this",
",",
"env",
",",
"null",
")",
";",
"this",
".",
"env",
"=",
"env",
";",
"this",
".",
"queueKey",
"=",
"key",
";",
"this",
".",
"reqType",
"=",
"\"Image Info Request\"",
";",
"var",
"conf",
"=",
"env",
".",
"conf",
".",
"wiki",
";",
"var",
"filenames",
"=",
"[",
"filename",
"]",
";",
"var",
"imgnsid",
"=",
"conf",
".",
"canonicalNamespaces",
".",
"image",
";",
"var",
"imgns",
"=",
"conf",
".",
"namespaceNames",
"[",
"imgnsid",
"]",
";",
"var",
"props",
"=",
"[",
"'mediatype'",
",",
"'mime'",
",",
"'size'",
",",
"'url'",
",",
"'badfile'",
",",
"]",
";",
"// If the videoinfo prop is available, as determined by our feature",
"// detection when initializing the wiki config, use that to fetch the",
"// derivates for videos. videoinfo is just a wrapper for imageinfo,",
"// so all our media requests should go there, and the response can be",
"// disambiguated by the returned mediatype.",
"var",
"prop",
",",
"prefix",
";",
"if",
"(",
"conf",
".",
"useVideoInfo",
")",
"{",
"prop",
"=",
"'videoinfo'",
";",
"prefix",
"=",
"'vi'",
";",
"props",
".",
"push",
"(",
"'derivatives'",
",",
"'timedtext'",
")",
";",
"}",
"else",
"{",
"prop",
"=",
"'imageinfo'",
";",
"prefix",
"=",
"'ii'",
";",
"}",
"this",
".",
"ns",
"=",
"imgns",
";",
"for",
"(",
"var",
"ix",
"=",
"0",
";",
"ix",
"<",
"filenames",
".",
"length",
";",
"ix",
"++",
")",
"{",
"filenames",
"[",
"ix",
"]",
"=",
"imgns",
"+",
"':'",
"+",
"filenames",
"[",
"ix",
"]",
";",
"}",
"var",
"apiArgs",
"=",
"{",
"action",
":",
"'query'",
",",
"format",
":",
"'json'",
",",
"formatversion",
":",
"2",
",",
"prop",
":",
"prop",
",",
"titles",
":",
"filenames",
".",
"join",
"(",
"'|'",
")",
",",
"rawcontinue",
":",
"1",
",",
"}",
";",
"apiArgs",
"[",
"prefix",
"+",
"'prop'",
"]",
"=",
"props",
".",
"join",
"(",
"'|'",
")",
";",
"apiArgs",
"[",
"prefix",
"+",
"'badfilecontexttitle'",
"]",
"=",
"env",
".",
"page",
".",
"name",
";",
"if",
"(",
"dims",
")",
"{",
"if",
"(",
"dims",
".",
"width",
"!==",
"undefined",
"&&",
"dims",
".",
"width",
"!==",
"null",
")",
"{",
"console",
".",
"assert",
"(",
"typeof",
"(",
"dims",
".",
"width",
")",
"===",
"'number'",
")",
";",
"apiArgs",
"[",
"prefix",
"+",
"'urlwidth'",
"]",
"=",
"dims",
".",
"width",
";",
"if",
"(",
"dims",
".",
"page",
"!==",
"undefined",
")",
"{",
"// NOTE: This format is specific to PDFs. Not sure how to",
"// support this generally, though it seems common enough /",
"// shared with other file types.",
"apiArgs",
"[",
"prefix",
"+",
"'urlparam'",
"]",
"=",
"`",
"${",
"dims",
".",
"page",
"}",
"${",
"dims",
".",
"width",
"}",
"`",
";",
"}",
"}",
"if",
"(",
"dims",
".",
"height",
"!==",
"undefined",
"&&",
"dims",
".",
"height",
"!==",
"null",
")",
"{",
"console",
".",
"assert",
"(",
"typeof",
"(",
"dims",
".",
"height",
")",
"===",
"'number'",
")",
";",
"apiArgs",
"[",
"prefix",
"+",
"'urlheight'",
"]",
"=",
"dims",
".",
"height",
";",
"}",
"if",
"(",
"dims",
".",
"seek",
"!==",
"undefined",
")",
"{",
"apiArgs",
"[",
"prefix",
"+",
"'urlparam'",
"]",
"=",
"`",
"${",
"dims",
".",
"seek",
"}",
"`",
";",
"}",
"}",
"this",
".",
"requestOptions",
"=",
"{",
"method",
":",
"'GET'",
",",
"followRedirect",
":",
"true",
",",
"uri",
":",
"env",
".",
"conf",
".",
"wiki",
".",
"apiURI",
",",
"qs",
":",
"apiArgs",
",",
"timeout",
":",
"env",
".",
"conf",
".",
"parsoid",
".",
"timeouts",
".",
"mwApi",
".",
"imgInfo",
",",
"}",
";",
"this",
".",
"request",
"(",
"this",
".",
"requestOptions",
")",
";",
"}"
] |
Fetch information about an image.
@class
@extends ~ApiRequest
@param {MWParserEnvironment} env
@param {string} filename
@param {Object} [dims]
@param {number} [dims.width]
@param {number} [dims.height]
|
[
"Fetch",
"information",
"about",
"an",
"image",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/mw/ApiRequest.js#L947-L1027
|
15,059
|
wikimedia/parsoid
|
lib/mw/ApiRequest.js
|
TemplateDataRequest
|
function TemplateDataRequest(env, template, queueKey) {
ApiRequest.call(this, env, null);
this.env = env;
this.text = template;
this.queueKey = queueKey;
this.reqType = "TemplateData Request";
var apiargs = {
format: 'json',
// XXX: should use formatversion=2
action: 'templatedata',
includeMissingTitles: '1',
titles: template,
};
this.requestOptions = {
// Use GET so this request can be cached in Varnish
method: 'GET',
qs: apiargs,
followRedirect: true,
uri: env.conf.wiki.apiURI,
timeout: env.conf.parsoid.timeouts.mwApi.templateData,
};
this.request(this.requestOptions);
}
|
javascript
|
function TemplateDataRequest(env, template, queueKey) {
ApiRequest.call(this, env, null);
this.env = env;
this.text = template;
this.queueKey = queueKey;
this.reqType = "TemplateData Request";
var apiargs = {
format: 'json',
// XXX: should use formatversion=2
action: 'templatedata',
includeMissingTitles: '1',
titles: template,
};
this.requestOptions = {
// Use GET so this request can be cached in Varnish
method: 'GET',
qs: apiargs,
followRedirect: true,
uri: env.conf.wiki.apiURI,
timeout: env.conf.parsoid.timeouts.mwApi.templateData,
};
this.request(this.requestOptions);
}
|
[
"function",
"TemplateDataRequest",
"(",
"env",
",",
"template",
",",
"queueKey",
")",
"{",
"ApiRequest",
".",
"call",
"(",
"this",
",",
"env",
",",
"null",
")",
";",
"this",
".",
"env",
"=",
"env",
";",
"this",
".",
"text",
"=",
"template",
";",
"this",
".",
"queueKey",
"=",
"queueKey",
";",
"this",
".",
"reqType",
"=",
"\"TemplateData Request\"",
";",
"var",
"apiargs",
"=",
"{",
"format",
":",
"'json'",
",",
"// XXX: should use formatversion=2",
"action",
":",
"'templatedata'",
",",
"includeMissingTitles",
":",
"'1'",
",",
"titles",
":",
"template",
",",
"}",
";",
"this",
".",
"requestOptions",
"=",
"{",
"// Use GET so this request can be cached in Varnish",
"method",
":",
"'GET'",
",",
"qs",
":",
"apiargs",
",",
"followRedirect",
":",
"true",
",",
"uri",
":",
"env",
".",
"conf",
".",
"wiki",
".",
"apiURI",
",",
"timeout",
":",
"env",
".",
"conf",
".",
"parsoid",
".",
"timeouts",
".",
"mwApi",
".",
"templateData",
",",
"}",
";",
"this",
".",
"request",
"(",
"this",
".",
"requestOptions",
")",
";",
"}"
] |
Fetch TemplateData info for a template.
This is used by the html -> wt serialization path.
@class
@extends ~ApiRequest
@param {MWParserEnvironment} env
@param {string} template
@param {string} [queueKey] The queue key.
|
[
"Fetch",
"TemplateData",
"info",
"for",
"a",
"template",
".",
"This",
"is",
"used",
"by",
"the",
"html",
"-",
">",
"wt",
"serialization",
"path",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/mw/ApiRequest.js#L1098-L1123
|
15,060
|
wikimedia/parsoid
|
lib/mw/ApiRequest.js
|
LintRequest
|
function LintRequest(env, data, queueKey) {
ApiRequest.call(this, env, null);
this.queueKey = queueKey || data;
this.reqType = 'Lint Request';
var apiargs = {
data: data,
page: env.page.name,
revision: env.page.meta.revision.revid,
action: 'record-lint',
format: 'json',
formatversion: 2,
};
this.requestOptions = {
method: 'POST',
form: apiargs,
followRedirect: true,
uri: env.conf.wiki.apiURI,
timeout: env.conf.parsoid.timeouts.mwApi.lint,
};
this.request(this.requestOptions);
}
|
javascript
|
function LintRequest(env, data, queueKey) {
ApiRequest.call(this, env, null);
this.queueKey = queueKey || data;
this.reqType = 'Lint Request';
var apiargs = {
data: data,
page: env.page.name,
revision: env.page.meta.revision.revid,
action: 'record-lint',
format: 'json',
formatversion: 2,
};
this.requestOptions = {
method: 'POST',
form: apiargs,
followRedirect: true,
uri: env.conf.wiki.apiURI,
timeout: env.conf.parsoid.timeouts.mwApi.lint,
};
this.request(this.requestOptions);
}
|
[
"function",
"LintRequest",
"(",
"env",
",",
"data",
",",
"queueKey",
")",
"{",
"ApiRequest",
".",
"call",
"(",
"this",
",",
"env",
",",
"null",
")",
";",
"this",
".",
"queueKey",
"=",
"queueKey",
"||",
"data",
";",
"this",
".",
"reqType",
"=",
"'Lint Request'",
";",
"var",
"apiargs",
"=",
"{",
"data",
":",
"data",
",",
"page",
":",
"env",
".",
"page",
".",
"name",
",",
"revision",
":",
"env",
".",
"page",
".",
"meta",
".",
"revision",
".",
"revid",
",",
"action",
":",
"'record-lint'",
",",
"format",
":",
"'json'",
",",
"formatversion",
":",
"2",
",",
"}",
";",
"this",
".",
"requestOptions",
"=",
"{",
"method",
":",
"'POST'",
",",
"form",
":",
"apiargs",
",",
"followRedirect",
":",
"true",
",",
"uri",
":",
"env",
".",
"conf",
".",
"wiki",
".",
"apiURI",
",",
"timeout",
":",
"env",
".",
"conf",
".",
"parsoid",
".",
"timeouts",
".",
"mwApi",
".",
"lint",
",",
"}",
";",
"this",
".",
"request",
"(",
"this",
".",
"requestOptions",
")",
";",
"}"
] |
Record lint information.
@class
@extends ~ApiRequest
@param {MWParserEnvironment} env
@param {string} data
@param {string} [queueKey] The queue key.
|
[
"Record",
"lint",
"information",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/mw/ApiRequest.js#L1152-L1175
|
15,061
|
wikimedia/parsoid
|
lib/mw/ApiRequest.js
|
ParamInfoRequest
|
function ParamInfoRequest(env, queueKey) {
ApiRequest.call(this, env, null);
this.reqType = 'ParamInfo Request';
var apiargs = {
format: 'json',
// XXX: should use formatversion=2
action: 'paraminfo',
modules: 'query',
rawcontinue: 1,
};
this.queueKey = queueKey || JSON.stringify(apiargs);
this.requestOptions = {
method: 'GET',
followRedirect: true,
uri: env.conf.wiki.apiURI,
qs: apiargs,
timeout: env.conf.parsoid.timeouts.mwApi.paramInfo,
};
this.request(this.requestOptions);
}
|
javascript
|
function ParamInfoRequest(env, queueKey) {
ApiRequest.call(this, env, null);
this.reqType = 'ParamInfo Request';
var apiargs = {
format: 'json',
// XXX: should use formatversion=2
action: 'paraminfo',
modules: 'query',
rawcontinue: 1,
};
this.queueKey = queueKey || JSON.stringify(apiargs);
this.requestOptions = {
method: 'GET',
followRedirect: true,
uri: env.conf.wiki.apiURI,
qs: apiargs,
timeout: env.conf.parsoid.timeouts.mwApi.paramInfo,
};
this.request(this.requestOptions);
}
|
[
"function",
"ParamInfoRequest",
"(",
"env",
",",
"queueKey",
")",
"{",
"ApiRequest",
".",
"call",
"(",
"this",
",",
"env",
",",
"null",
")",
";",
"this",
".",
"reqType",
"=",
"'ParamInfo Request'",
";",
"var",
"apiargs",
"=",
"{",
"format",
":",
"'json'",
",",
"// XXX: should use formatversion=2",
"action",
":",
"'paraminfo'",
",",
"modules",
":",
"'query'",
",",
"rawcontinue",
":",
"1",
",",
"}",
";",
"this",
".",
"queueKey",
"=",
"queueKey",
"||",
"JSON",
".",
"stringify",
"(",
"apiargs",
")",
";",
"this",
".",
"requestOptions",
"=",
"{",
"method",
":",
"'GET'",
",",
"followRedirect",
":",
"true",
",",
"uri",
":",
"env",
".",
"conf",
".",
"wiki",
".",
"apiURI",
",",
"qs",
":",
"apiargs",
",",
"timeout",
":",
"env",
".",
"conf",
".",
"parsoid",
".",
"timeouts",
".",
"mwApi",
".",
"paramInfo",
",",
"}",
";",
"this",
".",
"request",
"(",
"this",
".",
"requestOptions",
")",
";",
"}"
] |
Obtain information about MediaWiki API modules.
@class
@extends ~ApiRequest
@param {MWParserEnvironment} env
@param {string} [queueKey] The queue key.
|
[
"Obtain",
"information",
"about",
"MediaWiki",
"API",
"modules",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/mw/ApiRequest.js#L1194-L1217
|
15,062
|
wikimedia/parsoid
|
lib/html2wt/separators.js
|
getSepNlConstraints
|
function getSepNlConstraints(state, nodeA, aCons, nodeB, bCons) {
const env = state.env;
const nlConstraints = {
min: aCons.min,
max: aCons.max,
force: aCons.force || bCons.force,
};
// now figure out if this conflicts with the nlConstraints so far
if (bCons.min !== undefined) {
if (nlConstraints.max !== undefined && nlConstraints.max < bCons.min) {
// Conflict, warn and let nodeB win.
env.log("info/html2wt", "Incompatible constraints 1:", nodeA.nodeName,
nodeB.nodeName, loggableConstraints(nlConstraints));
nlConstraints.min = bCons.min;
nlConstraints.max = bCons.min;
} else {
nlConstraints.min = Math.max(nlConstraints.min || 0, bCons.min);
}
}
if (bCons.max !== undefined) {
if (nlConstraints.min !== undefined && nlConstraints.min > bCons.max) {
// Conflict, warn and let nodeB win.
env.log("info/html2wt", "Incompatible constraints 2:", nodeA.nodeName,
nodeB.nodeName, loggableConstraints(nlConstraints));
nlConstraints.min = bCons.max;
nlConstraints.max = bCons.max;
} else if (nlConstraints.max !== undefined) {
nlConstraints.max = Math.min(nlConstraints.max, bCons.max);
} else {
nlConstraints.max = bCons.max;
}
}
if (nlConstraints.max === undefined) {
// Anything more than two lines will trigger paragraphs, so default to
// two if nothing is specified.
nlConstraints.max = 2;
}
return nlConstraints;
}
|
javascript
|
function getSepNlConstraints(state, nodeA, aCons, nodeB, bCons) {
const env = state.env;
const nlConstraints = {
min: aCons.min,
max: aCons.max,
force: aCons.force || bCons.force,
};
// now figure out if this conflicts with the nlConstraints so far
if (bCons.min !== undefined) {
if (nlConstraints.max !== undefined && nlConstraints.max < bCons.min) {
// Conflict, warn and let nodeB win.
env.log("info/html2wt", "Incompatible constraints 1:", nodeA.nodeName,
nodeB.nodeName, loggableConstraints(nlConstraints));
nlConstraints.min = bCons.min;
nlConstraints.max = bCons.min;
} else {
nlConstraints.min = Math.max(nlConstraints.min || 0, bCons.min);
}
}
if (bCons.max !== undefined) {
if (nlConstraints.min !== undefined && nlConstraints.min > bCons.max) {
// Conflict, warn and let nodeB win.
env.log("info/html2wt", "Incompatible constraints 2:", nodeA.nodeName,
nodeB.nodeName, loggableConstraints(nlConstraints));
nlConstraints.min = bCons.max;
nlConstraints.max = bCons.max;
} else if (nlConstraints.max !== undefined) {
nlConstraints.max = Math.min(nlConstraints.max, bCons.max);
} else {
nlConstraints.max = bCons.max;
}
}
if (nlConstraints.max === undefined) {
// Anything more than two lines will trigger paragraphs, so default to
// two if nothing is specified.
nlConstraints.max = 2;
}
return nlConstraints;
}
|
[
"function",
"getSepNlConstraints",
"(",
"state",
",",
"nodeA",
",",
"aCons",
",",
"nodeB",
",",
"bCons",
")",
"{",
"const",
"env",
"=",
"state",
".",
"env",
";",
"const",
"nlConstraints",
"=",
"{",
"min",
":",
"aCons",
".",
"min",
",",
"max",
":",
"aCons",
".",
"max",
",",
"force",
":",
"aCons",
".",
"force",
"||",
"bCons",
".",
"force",
",",
"}",
";",
"// now figure out if this conflicts with the nlConstraints so far",
"if",
"(",
"bCons",
".",
"min",
"!==",
"undefined",
")",
"{",
"if",
"(",
"nlConstraints",
".",
"max",
"!==",
"undefined",
"&&",
"nlConstraints",
".",
"max",
"<",
"bCons",
".",
"min",
")",
"{",
"// Conflict, warn and let nodeB win.",
"env",
".",
"log",
"(",
"\"info/html2wt\"",
",",
"\"Incompatible constraints 1:\"",
",",
"nodeA",
".",
"nodeName",
",",
"nodeB",
".",
"nodeName",
",",
"loggableConstraints",
"(",
"nlConstraints",
")",
")",
";",
"nlConstraints",
".",
"min",
"=",
"bCons",
".",
"min",
";",
"nlConstraints",
".",
"max",
"=",
"bCons",
".",
"min",
";",
"}",
"else",
"{",
"nlConstraints",
".",
"min",
"=",
"Math",
".",
"max",
"(",
"nlConstraints",
".",
"min",
"||",
"0",
",",
"bCons",
".",
"min",
")",
";",
"}",
"}",
"if",
"(",
"bCons",
".",
"max",
"!==",
"undefined",
")",
"{",
"if",
"(",
"nlConstraints",
".",
"min",
"!==",
"undefined",
"&&",
"nlConstraints",
".",
"min",
">",
"bCons",
".",
"max",
")",
"{",
"// Conflict, warn and let nodeB win.",
"env",
".",
"log",
"(",
"\"info/html2wt\"",
",",
"\"Incompatible constraints 2:\"",
",",
"nodeA",
".",
"nodeName",
",",
"nodeB",
".",
"nodeName",
",",
"loggableConstraints",
"(",
"nlConstraints",
")",
")",
";",
"nlConstraints",
".",
"min",
"=",
"bCons",
".",
"max",
";",
"nlConstraints",
".",
"max",
"=",
"bCons",
".",
"max",
";",
"}",
"else",
"if",
"(",
"nlConstraints",
".",
"max",
"!==",
"undefined",
")",
"{",
"nlConstraints",
".",
"max",
"=",
"Math",
".",
"min",
"(",
"nlConstraints",
".",
"max",
",",
"bCons",
".",
"max",
")",
";",
"}",
"else",
"{",
"nlConstraints",
".",
"max",
"=",
"bCons",
".",
"max",
";",
"}",
"}",
"if",
"(",
"nlConstraints",
".",
"max",
"===",
"undefined",
")",
"{",
"// Anything more than two lines will trigger paragraphs, so default to",
"// two if nothing is specified.",
"nlConstraints",
".",
"max",
"=",
"2",
";",
"}",
"return",
"nlConstraints",
";",
"}"
] |
Helper for updateSeparatorConstraints.
Collects, checks and integrates separator newline requirements to a simple
min, max structure.
@param {SerializerState} state
@param {Node} nodeA
@param {Object} aCons
@param {Node} nodeB
@param {Object} bCons
@return {Object}
@return {Object} [return.a]
@return {Object} [return.b]
@private
|
[
"Helper",
"for",
"updateSeparatorConstraints",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/html2wt/separators.js#L91-L134
|
15,063
|
wikimedia/parsoid
|
lib/html2wt/separators.js
|
mergeConstraints
|
function mergeConstraints(env, oldConstraints, newConstraints) {
const res = {
min: Math.max(oldConstraints.min || 0, newConstraints.min || 0),
max: Math.min(
oldConstraints.max !== undefined ? oldConstraints.max : 2,
newConstraints.max !== undefined ? newConstraints.max : 2
),
force: oldConstraints.force || newConstraints.force,
};
if (res.min > res.max) {
// If oldConstraints.force is set, older constraints win
if (!oldConstraints.force) {
// let newConstraints win, but complain
if (newConstraints.max !== undefined && newConstraints.max > res.min) {
res.max = newConstraints.max;
} else if (newConstraints.min && newConstraints.min < res.min) {
res.min = newConstraints.min;
}
}
res.max = res.min;
env.log("info/html2wt", 'Incompatible constraints (merge):', res,
loggableConstraints(oldConstraints), loggableConstraints(newConstraints));
}
return res;
}
|
javascript
|
function mergeConstraints(env, oldConstraints, newConstraints) {
const res = {
min: Math.max(oldConstraints.min || 0, newConstraints.min || 0),
max: Math.min(
oldConstraints.max !== undefined ? oldConstraints.max : 2,
newConstraints.max !== undefined ? newConstraints.max : 2
),
force: oldConstraints.force || newConstraints.force,
};
if (res.min > res.max) {
// If oldConstraints.force is set, older constraints win
if (!oldConstraints.force) {
// let newConstraints win, but complain
if (newConstraints.max !== undefined && newConstraints.max > res.min) {
res.max = newConstraints.max;
} else if (newConstraints.min && newConstraints.min < res.min) {
res.min = newConstraints.min;
}
}
res.max = res.min;
env.log("info/html2wt", 'Incompatible constraints (merge):', res,
loggableConstraints(oldConstraints), loggableConstraints(newConstraints));
}
return res;
}
|
[
"function",
"mergeConstraints",
"(",
"env",
",",
"oldConstraints",
",",
"newConstraints",
")",
"{",
"const",
"res",
"=",
"{",
"min",
":",
"Math",
".",
"max",
"(",
"oldConstraints",
".",
"min",
"||",
"0",
",",
"newConstraints",
".",
"min",
"||",
"0",
")",
",",
"max",
":",
"Math",
".",
"min",
"(",
"oldConstraints",
".",
"max",
"!==",
"undefined",
"?",
"oldConstraints",
".",
"max",
":",
"2",
",",
"newConstraints",
".",
"max",
"!==",
"undefined",
"?",
"newConstraints",
".",
"max",
":",
"2",
")",
",",
"force",
":",
"oldConstraints",
".",
"force",
"||",
"newConstraints",
".",
"force",
",",
"}",
";",
"if",
"(",
"res",
".",
"min",
">",
"res",
".",
"max",
")",
"{",
"// If oldConstraints.force is set, older constraints win",
"if",
"(",
"!",
"oldConstraints",
".",
"force",
")",
"{",
"// let newConstraints win, but complain",
"if",
"(",
"newConstraints",
".",
"max",
"!==",
"undefined",
"&&",
"newConstraints",
".",
"max",
">",
"res",
".",
"min",
")",
"{",
"res",
".",
"max",
"=",
"newConstraints",
".",
"max",
";",
"}",
"else",
"if",
"(",
"newConstraints",
".",
"min",
"&&",
"newConstraints",
".",
"min",
"<",
"res",
".",
"min",
")",
"{",
"res",
".",
"min",
"=",
"newConstraints",
".",
"min",
";",
"}",
"}",
"res",
".",
"max",
"=",
"res",
".",
"min",
";",
"env",
".",
"log",
"(",
"\"info/html2wt\"",
",",
"'Incompatible constraints (merge):'",
",",
"res",
",",
"loggableConstraints",
"(",
"oldConstraints",
")",
",",
"loggableConstraints",
"(",
"newConstraints",
")",
")",
";",
"}",
"return",
"res",
";",
"}"
] |
Merge two constraints.
@private
|
[
"Merge",
"two",
"constraints",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/html2wt/separators.js#L251-L277
|
15,064
|
wikimedia/parsoid
|
lib/html2wt/separators.js
|
function(state, nodeA, sepHandlerA, nodeB, sepHandlerB) {
let sepType, nlConstraints, aCons, bCons;
if (nodeA.nextSibling === nodeB) {
// sibling separator
sepType = "sibling";
aCons = sepHandlerA.after(nodeA, nodeB, state);
bCons = sepHandlerB.before(nodeB, nodeA, state);
nlConstraints = getSepNlConstraints(state, nodeA, aCons, nodeB, bCons);
} else if (nodeB.parentNode === nodeA) {
// parent-child separator, nodeA parent of nodeB
sepType = "parent-child";
aCons = sepHandlerA.firstChild(nodeA, nodeB, state);
bCons = sepHandlerB.before(nodeB, nodeA, state);
nlConstraints = getSepNlConstraints(state, nodeA, aCons, nodeB, bCons);
} else if (nodeA.parentNode === nodeB) {
// parent-child separator, nodeB parent of nodeA
sepType = "child-parent";
aCons = sepHandlerA.after(nodeA, nodeB, state);
bCons = sepHandlerB.lastChild(nodeB, nodeA, state);
nlConstraints = getSepNlConstraints(state, nodeA, aCons, nodeB, bCons);
} else {
// sibling separator
sepType = "sibling";
aCons = sepHandlerA.after(nodeA, nodeB, state);
bCons = sepHandlerB.before(nodeB, nodeA, state);
nlConstraints = getSepNlConstraints(state, nodeA, aCons, nodeB, bCons);
}
if (nodeA.nodeName === undefined) {
console.trace();
}
if (state.sep.constraints) {
// Merge the constraints
state.sep.constraints = mergeConstraints(
state.env,
state.sep.constraints,
nlConstraints
);
} else {
state.sep.constraints = nlConstraints;
}
state.env.log('debug/wts/sep', function() {
return 'constraint' +
' | ' + sepType +
' | <' + nodeA.nodeName + ',' + nodeB.nodeName + '>' +
' | ' + JSON.stringify(state.sep.constraints) +
' | ' + debugOut(nodeA) +
' | ' + debugOut(nodeB);
});
state.sep.constraints.constraintInfo = {
onSOL: state.onSOL,
// force SOL state when separator is built/emitted
forceSOL: sepHandlerB.forceSOL,
sepType: sepType,
nodeA: nodeA,
nodeB: nodeB,
};
}
|
javascript
|
function(state, nodeA, sepHandlerA, nodeB, sepHandlerB) {
let sepType, nlConstraints, aCons, bCons;
if (nodeA.nextSibling === nodeB) {
// sibling separator
sepType = "sibling";
aCons = sepHandlerA.after(nodeA, nodeB, state);
bCons = sepHandlerB.before(nodeB, nodeA, state);
nlConstraints = getSepNlConstraints(state, nodeA, aCons, nodeB, bCons);
} else if (nodeB.parentNode === nodeA) {
// parent-child separator, nodeA parent of nodeB
sepType = "parent-child";
aCons = sepHandlerA.firstChild(nodeA, nodeB, state);
bCons = sepHandlerB.before(nodeB, nodeA, state);
nlConstraints = getSepNlConstraints(state, nodeA, aCons, nodeB, bCons);
} else if (nodeA.parentNode === nodeB) {
// parent-child separator, nodeB parent of nodeA
sepType = "child-parent";
aCons = sepHandlerA.after(nodeA, nodeB, state);
bCons = sepHandlerB.lastChild(nodeB, nodeA, state);
nlConstraints = getSepNlConstraints(state, nodeA, aCons, nodeB, bCons);
} else {
// sibling separator
sepType = "sibling";
aCons = sepHandlerA.after(nodeA, nodeB, state);
bCons = sepHandlerB.before(nodeB, nodeA, state);
nlConstraints = getSepNlConstraints(state, nodeA, aCons, nodeB, bCons);
}
if (nodeA.nodeName === undefined) {
console.trace();
}
if (state.sep.constraints) {
// Merge the constraints
state.sep.constraints = mergeConstraints(
state.env,
state.sep.constraints,
nlConstraints
);
} else {
state.sep.constraints = nlConstraints;
}
state.env.log('debug/wts/sep', function() {
return 'constraint' +
' | ' + sepType +
' | <' + nodeA.nodeName + ',' + nodeB.nodeName + '>' +
' | ' + JSON.stringify(state.sep.constraints) +
' | ' + debugOut(nodeA) +
' | ' + debugOut(nodeB);
});
state.sep.constraints.constraintInfo = {
onSOL: state.onSOL,
// force SOL state when separator is built/emitted
forceSOL: sepHandlerB.forceSOL,
sepType: sepType,
nodeA: nodeA,
nodeB: nodeB,
};
}
|
[
"function",
"(",
"state",
",",
"nodeA",
",",
"sepHandlerA",
",",
"nodeB",
",",
"sepHandlerB",
")",
"{",
"let",
"sepType",
",",
"nlConstraints",
",",
"aCons",
",",
"bCons",
";",
"if",
"(",
"nodeA",
".",
"nextSibling",
"===",
"nodeB",
")",
"{",
"// sibling separator",
"sepType",
"=",
"\"sibling\"",
";",
"aCons",
"=",
"sepHandlerA",
".",
"after",
"(",
"nodeA",
",",
"nodeB",
",",
"state",
")",
";",
"bCons",
"=",
"sepHandlerB",
".",
"before",
"(",
"nodeB",
",",
"nodeA",
",",
"state",
")",
";",
"nlConstraints",
"=",
"getSepNlConstraints",
"(",
"state",
",",
"nodeA",
",",
"aCons",
",",
"nodeB",
",",
"bCons",
")",
";",
"}",
"else",
"if",
"(",
"nodeB",
".",
"parentNode",
"===",
"nodeA",
")",
"{",
"// parent-child separator, nodeA parent of nodeB",
"sepType",
"=",
"\"parent-child\"",
";",
"aCons",
"=",
"sepHandlerA",
".",
"firstChild",
"(",
"nodeA",
",",
"nodeB",
",",
"state",
")",
";",
"bCons",
"=",
"sepHandlerB",
".",
"before",
"(",
"nodeB",
",",
"nodeA",
",",
"state",
")",
";",
"nlConstraints",
"=",
"getSepNlConstraints",
"(",
"state",
",",
"nodeA",
",",
"aCons",
",",
"nodeB",
",",
"bCons",
")",
";",
"}",
"else",
"if",
"(",
"nodeA",
".",
"parentNode",
"===",
"nodeB",
")",
"{",
"// parent-child separator, nodeB parent of nodeA",
"sepType",
"=",
"\"child-parent\"",
";",
"aCons",
"=",
"sepHandlerA",
".",
"after",
"(",
"nodeA",
",",
"nodeB",
",",
"state",
")",
";",
"bCons",
"=",
"sepHandlerB",
".",
"lastChild",
"(",
"nodeB",
",",
"nodeA",
",",
"state",
")",
";",
"nlConstraints",
"=",
"getSepNlConstraints",
"(",
"state",
",",
"nodeA",
",",
"aCons",
",",
"nodeB",
",",
"bCons",
")",
";",
"}",
"else",
"{",
"// sibling separator",
"sepType",
"=",
"\"sibling\"",
";",
"aCons",
"=",
"sepHandlerA",
".",
"after",
"(",
"nodeA",
",",
"nodeB",
",",
"state",
")",
";",
"bCons",
"=",
"sepHandlerB",
".",
"before",
"(",
"nodeB",
",",
"nodeA",
",",
"state",
")",
";",
"nlConstraints",
"=",
"getSepNlConstraints",
"(",
"state",
",",
"nodeA",
",",
"aCons",
",",
"nodeB",
",",
"bCons",
")",
";",
"}",
"if",
"(",
"nodeA",
".",
"nodeName",
"===",
"undefined",
")",
"{",
"console",
".",
"trace",
"(",
")",
";",
"}",
"if",
"(",
"state",
".",
"sep",
".",
"constraints",
")",
"{",
"// Merge the constraints",
"state",
".",
"sep",
".",
"constraints",
"=",
"mergeConstraints",
"(",
"state",
".",
"env",
",",
"state",
".",
"sep",
".",
"constraints",
",",
"nlConstraints",
")",
";",
"}",
"else",
"{",
"state",
".",
"sep",
".",
"constraints",
"=",
"nlConstraints",
";",
"}",
"state",
".",
"env",
".",
"log",
"(",
"'debug/wts/sep'",
",",
"function",
"(",
")",
"{",
"return",
"'constraint'",
"+",
"' | '",
"+",
"sepType",
"+",
"' | <'",
"+",
"nodeA",
".",
"nodeName",
"+",
"','",
"+",
"nodeB",
".",
"nodeName",
"+",
"'>'",
"+",
"' | '",
"+",
"JSON",
".",
"stringify",
"(",
"state",
".",
"sep",
".",
"constraints",
")",
"+",
"' | '",
"+",
"debugOut",
"(",
"nodeA",
")",
"+",
"' | '",
"+",
"debugOut",
"(",
"nodeB",
")",
";",
"}",
")",
";",
"state",
".",
"sep",
".",
"constraints",
".",
"constraintInfo",
"=",
"{",
"onSOL",
":",
"state",
".",
"onSOL",
",",
"// force SOL state when separator is built/emitted",
"forceSOL",
":",
"sepHandlerB",
".",
"forceSOL",
",",
"sepType",
":",
"sepType",
",",
"nodeA",
":",
"nodeA",
",",
"nodeB",
":",
"nodeB",
",",
"}",
";",
"}"
] |
Figure out separator constraints and merge them with existing constraints
in state so that they can be emitted when the next content emits source.
@param {Node} nodeA
@param {DOMHandler} sepHandlerA
@param {Node} nodeB
@param {DOMHandler} sepHandlerB
|
[
"Figure",
"out",
"separator",
"constraints",
"and",
"merge",
"them",
"with",
"existing",
"constraints",
"in",
"state",
"so",
"that",
"they",
"can",
"be",
"emitted",
"when",
"the",
"next",
"content",
"emits",
"source",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/html2wt/separators.js#L291-L352
|
|
15,065
|
wikimedia/parsoid
|
lib/html2wt/separators.js
|
function(node) {
var dp = DOMDataUtils.getDataParsoid(node);
var dsr = Util.clone(dp.dsr);
if (dp.autoInsertedStart) { dsr[2] = null; }
if (dp.autoInsertedEnd) { dsr[3] = null; }
return dsr;
}
|
javascript
|
function(node) {
var dp = DOMDataUtils.getDataParsoid(node);
var dsr = Util.clone(dp.dsr);
if (dp.autoInsertedStart) { dsr[2] = null; }
if (dp.autoInsertedEnd) { dsr[3] = null; }
return dsr;
}
|
[
"function",
"(",
"node",
")",
"{",
"var",
"dp",
"=",
"DOMDataUtils",
".",
"getDataParsoid",
"(",
"node",
")",
";",
"var",
"dsr",
"=",
"Util",
".",
"clone",
"(",
"dp",
".",
"dsr",
")",
";",
"if",
"(",
"dp",
".",
"autoInsertedStart",
")",
"{",
"dsr",
"[",
"2",
"]",
"=",
"null",
";",
"}",
"if",
"(",
"dp",
".",
"autoInsertedEnd",
")",
"{",
"dsr",
"[",
"3",
"]",
"=",
"null",
";",
"}",
"return",
"dsr",
";",
"}"
] |
Serializing auto inserted content should invalidate the original separator
|
[
"Serializing",
"auto",
"inserted",
"content",
"should",
"invalidate",
"the",
"original",
"separator"
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/html2wt/separators.js#L490-L496
|
|
15,066
|
wikimedia/parsoid
|
lib/utils/Diff.js
|
function(diff) {
var ret = [];
diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier
// Formats a given set of lines for printing as context lines in a patch
function contextLines(lines) {
return lines.map(function(entry) { return ' ' + entry; });
}
var oldRangeStart = 0;
var newRangeStart = 0;
var curRange = [];
var oldLine = 1;
var newLine = 1;
for (var i = 0; i < diff.length; i++) {
var current = diff[i];
var lines = current.lines || current.value.replace(/\n$/, '').split('\n');
current.lines = lines;
if (current.added || current.removed) {
// If we have previous context, start with that
if (!oldRangeStart) {
var prev = diff[i - 1];
oldRangeStart = oldLine;
newRangeStart = newLine;
if (prev) {
curRange = contextLines(prev.lines.slice(-4));
oldRangeStart -= curRange.length;
newRangeStart -= curRange.length;
}
}
// Output our changes
curRange.push.apply(curRange, lines.map(function(entry) {
return (current.added ? '+' : '-') + entry;
}));
// Track the updated file position
if (current.added) {
newLine += lines.length;
} else {
oldLine += lines.length;
}
} else {
// Identical context lines. Track line changes
if (oldRangeStart) {
// Close out any changes that have been output (or join overlapping)
if (lines.length <= 8 && i < diff.length - 2) {
// Overlapping
curRange.push.apply(curRange, contextLines(lines));
} else {
// end the range and output
var contextSize = Math.min(lines.length, 4);
ret.push(
'@@ -' + oldRangeStart + ',' + (oldLine - oldRangeStart + contextSize)
+ ' +' + newRangeStart + ',' + (newLine - newRangeStart + contextSize)
+ ' @@');
ret.push.apply(ret, curRange);
ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
oldRangeStart = 0;
newRangeStart = 0;
curRange = [];
}
}
oldLine += lines.length;
newLine += lines.length;
}
}
return ret.join('\n') + '\n';
}
|
javascript
|
function(diff) {
var ret = [];
diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier
// Formats a given set of lines for printing as context lines in a patch
function contextLines(lines) {
return lines.map(function(entry) { return ' ' + entry; });
}
var oldRangeStart = 0;
var newRangeStart = 0;
var curRange = [];
var oldLine = 1;
var newLine = 1;
for (var i = 0; i < diff.length; i++) {
var current = diff[i];
var lines = current.lines || current.value.replace(/\n$/, '').split('\n');
current.lines = lines;
if (current.added || current.removed) {
// If we have previous context, start with that
if (!oldRangeStart) {
var prev = diff[i - 1];
oldRangeStart = oldLine;
newRangeStart = newLine;
if (prev) {
curRange = contextLines(prev.lines.slice(-4));
oldRangeStart -= curRange.length;
newRangeStart -= curRange.length;
}
}
// Output our changes
curRange.push.apply(curRange, lines.map(function(entry) {
return (current.added ? '+' : '-') + entry;
}));
// Track the updated file position
if (current.added) {
newLine += lines.length;
} else {
oldLine += lines.length;
}
} else {
// Identical context lines. Track line changes
if (oldRangeStart) {
// Close out any changes that have been output (or join overlapping)
if (lines.length <= 8 && i < diff.length - 2) {
// Overlapping
curRange.push.apply(curRange, contextLines(lines));
} else {
// end the range and output
var contextSize = Math.min(lines.length, 4);
ret.push(
'@@ -' + oldRangeStart + ',' + (oldLine - oldRangeStart + contextSize)
+ ' +' + newRangeStart + ',' + (newLine - newRangeStart + contextSize)
+ ' @@');
ret.push.apply(ret, curRange);
ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
oldRangeStart = 0;
newRangeStart = 0;
curRange = [];
}
}
oldLine += lines.length;
newLine += lines.length;
}
}
return ret.join('\n') + '\n';
}
|
[
"function",
"(",
"diff",
")",
"{",
"var",
"ret",
"=",
"[",
"]",
";",
"diff",
".",
"push",
"(",
"{",
"value",
":",
"''",
",",
"lines",
":",
"[",
"]",
"}",
")",
";",
"// Append an empty value to make cleanup easier",
"// Formats a given set of lines for printing as context lines in a patch",
"function",
"contextLines",
"(",
"lines",
")",
"{",
"return",
"lines",
".",
"map",
"(",
"function",
"(",
"entry",
")",
"{",
"return",
"' '",
"+",
"entry",
";",
"}",
")",
";",
"}",
"var",
"oldRangeStart",
"=",
"0",
";",
"var",
"newRangeStart",
"=",
"0",
";",
"var",
"curRange",
"=",
"[",
"]",
";",
"var",
"oldLine",
"=",
"1",
";",
"var",
"newLine",
"=",
"1",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"diff",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"current",
"=",
"diff",
"[",
"i",
"]",
";",
"var",
"lines",
"=",
"current",
".",
"lines",
"||",
"current",
".",
"value",
".",
"replace",
"(",
"/",
"\\n$",
"/",
",",
"''",
")",
".",
"split",
"(",
"'\\n'",
")",
";",
"current",
".",
"lines",
"=",
"lines",
";",
"if",
"(",
"current",
".",
"added",
"||",
"current",
".",
"removed",
")",
"{",
"// If we have previous context, start with that",
"if",
"(",
"!",
"oldRangeStart",
")",
"{",
"var",
"prev",
"=",
"diff",
"[",
"i",
"-",
"1",
"]",
";",
"oldRangeStart",
"=",
"oldLine",
";",
"newRangeStart",
"=",
"newLine",
";",
"if",
"(",
"prev",
")",
"{",
"curRange",
"=",
"contextLines",
"(",
"prev",
".",
"lines",
".",
"slice",
"(",
"-",
"4",
")",
")",
";",
"oldRangeStart",
"-=",
"curRange",
".",
"length",
";",
"newRangeStart",
"-=",
"curRange",
".",
"length",
";",
"}",
"}",
"// Output our changes",
"curRange",
".",
"push",
".",
"apply",
"(",
"curRange",
",",
"lines",
".",
"map",
"(",
"function",
"(",
"entry",
")",
"{",
"return",
"(",
"current",
".",
"added",
"?",
"'+'",
":",
"'-'",
")",
"+",
"entry",
";",
"}",
")",
")",
";",
"// Track the updated file position",
"if",
"(",
"current",
".",
"added",
")",
"{",
"newLine",
"+=",
"lines",
".",
"length",
";",
"}",
"else",
"{",
"oldLine",
"+=",
"lines",
".",
"length",
";",
"}",
"}",
"else",
"{",
"// Identical context lines. Track line changes",
"if",
"(",
"oldRangeStart",
")",
"{",
"// Close out any changes that have been output (or join overlapping)",
"if",
"(",
"lines",
".",
"length",
"<=",
"8",
"&&",
"i",
"<",
"diff",
".",
"length",
"-",
"2",
")",
"{",
"// Overlapping",
"curRange",
".",
"push",
".",
"apply",
"(",
"curRange",
",",
"contextLines",
"(",
"lines",
")",
")",
";",
"}",
"else",
"{",
"// end the range and output",
"var",
"contextSize",
"=",
"Math",
".",
"min",
"(",
"lines",
".",
"length",
",",
"4",
")",
";",
"ret",
".",
"push",
"(",
"'@@ -'",
"+",
"oldRangeStart",
"+",
"','",
"+",
"(",
"oldLine",
"-",
"oldRangeStart",
"+",
"contextSize",
")",
"+",
"' +'",
"+",
"newRangeStart",
"+",
"','",
"+",
"(",
"newLine",
"-",
"newRangeStart",
"+",
"contextSize",
")",
"+",
"' @@'",
")",
";",
"ret",
".",
"push",
".",
"apply",
"(",
"ret",
",",
"curRange",
")",
";",
"ret",
".",
"push",
".",
"apply",
"(",
"ret",
",",
"contextLines",
"(",
"lines",
".",
"slice",
"(",
"0",
",",
"contextSize",
")",
")",
")",
";",
"oldRangeStart",
"=",
"0",
";",
"newRangeStart",
"=",
"0",
";",
"curRange",
"=",
"[",
"]",
";",
"}",
"}",
"oldLine",
"+=",
"lines",
".",
"length",
";",
"newLine",
"+=",
"lines",
".",
"length",
";",
"}",
"}",
"return",
"ret",
".",
"join",
"(",
"'\\n'",
")",
"+",
"'\\n'",
";",
"}"
] |
This is essentially lifted from jsDiff@1.4.0, but using our diff and
without the header and no newline warning.
@private
|
[
"This",
"is",
"essentially",
"lifted",
"from",
"jsDiff"
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/utils/Diff.js#L211-L285
|
|
15,067
|
wikimedia/parsoid
|
lib/utils/Diff.js
|
function(value) {
var ret = [];
var linesAndNewlines = value.split(/(\n|\r\n)/);
// Ignore the final empty token that occurs if the string ends with a new line
if (!linesAndNewlines[linesAndNewlines.length - 1]) {
linesAndNewlines.pop();
}
// Merge the content and line separators into single tokens
for (var i = 0; i < linesAndNewlines.length; i++) {
var line = linesAndNewlines[i];
if (i % 2) {
ret[ret.length - 1] += line;
} else {
ret.push(line);
}
}
return ret;
}
|
javascript
|
function(value) {
var ret = [];
var linesAndNewlines = value.split(/(\n|\r\n)/);
// Ignore the final empty token that occurs if the string ends with a new line
if (!linesAndNewlines[linesAndNewlines.length - 1]) {
linesAndNewlines.pop();
}
// Merge the content and line separators into single tokens
for (var i = 0; i < linesAndNewlines.length; i++) {
var line = linesAndNewlines[i];
if (i % 2) {
ret[ret.length - 1] += line;
} else {
ret.push(line);
}
}
return ret;
}
|
[
"function",
"(",
"value",
")",
"{",
"var",
"ret",
"=",
"[",
"]",
";",
"var",
"linesAndNewlines",
"=",
"value",
".",
"split",
"(",
"/",
"(\\n|\\r\\n)",
"/",
")",
";",
"// Ignore the final empty token that occurs if the string ends with a new line",
"if",
"(",
"!",
"linesAndNewlines",
"[",
"linesAndNewlines",
".",
"length",
"-",
"1",
"]",
")",
"{",
"linesAndNewlines",
".",
"pop",
"(",
")",
";",
"}",
"// Merge the content and line separators into single tokens",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"linesAndNewlines",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"line",
"=",
"linesAndNewlines",
"[",
"i",
"]",
";",
"if",
"(",
"i",
"%",
"2",
")",
"{",
"ret",
"[",
"ret",
".",
"length",
"-",
"1",
"]",
"+=",
"line",
";",
"}",
"else",
"{",
"ret",
".",
"push",
"(",
"line",
")",
";",
"}",
"}",
"return",
"ret",
";",
"}"
] |
Essentially lifted from jsDiff@1.4.0's PatchDiff.tokenize
|
[
"Essentially",
"lifted",
"from",
"jsDiff"
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/utils/Diff.js#L290-L307
|
|
15,068
|
wikimedia/parsoid
|
lib/html2wt/DOMNormalizer.js
|
mergable
|
function mergable(a, b) {
return a.nodeName === b.nodeName && similar(a, b);
}
|
javascript
|
function mergable(a, b) {
return a.nodeName === b.nodeName && similar(a, b);
}
|
[
"function",
"mergable",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
".",
"nodeName",
"===",
"b",
".",
"nodeName",
"&&",
"similar",
"(",
"a",
",",
"b",
")",
";",
"}"
] |
Can a and b be merged into a single node?
|
[
"Can",
"a",
"and",
"b",
"be",
"merged",
"into",
"a",
"single",
"node?"
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/html2wt/DOMNormalizer.js#L53-L55
|
15,069
|
wikimedia/parsoid
|
lib/html2wt/DOMNormalizer.js
|
swappable
|
function swappable(a, b) {
return DOMUtils.numNonDeletedChildNodes(a) === 1 &&
similar(a, DOMUtils.firstNonDeletedChild(a)) &&
mergable(DOMUtils.firstNonDeletedChild(a), b);
}
|
javascript
|
function swappable(a, b) {
return DOMUtils.numNonDeletedChildNodes(a) === 1 &&
similar(a, DOMUtils.firstNonDeletedChild(a)) &&
mergable(DOMUtils.firstNonDeletedChild(a), b);
}
|
[
"function",
"swappable",
"(",
"a",
",",
"b",
")",
"{",
"return",
"DOMUtils",
".",
"numNonDeletedChildNodes",
"(",
"a",
")",
"===",
"1",
"&&",
"similar",
"(",
"a",
",",
"DOMUtils",
".",
"firstNonDeletedChild",
"(",
"a",
")",
")",
"&&",
"mergable",
"(",
"DOMUtils",
".",
"firstNonDeletedChild",
"(",
"a",
")",
",",
"b",
")",
";",
"}"
] |
Can a and b be combined into a single node
if we swap a and a.firstChild?
For example: A='<b><i>x</i></b>' b='<i>y</i>' => '<i><b>x</b>y</i>'.
|
[
"Can",
"a",
"and",
"b",
"be",
"combined",
"into",
"a",
"single",
"node",
"if",
"we",
"swap",
"a",
"and",
"a",
".",
"firstChild?"
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/lib/html2wt/DOMNormalizer.js#L63-L67
|
15,070
|
wikimedia/parsoid
|
tools/ScriptUtils.js
|
function(parsoidOptions, cliOpts) {
[
'fetchConfig',
'fetchTemplates',
'fetchImageInfo',
'expandExtensions',
'rtTestMode',
'addHTMLTemplateParameters',
].forEach(function(c) {
if (cliOpts[c] !== undefined) {
parsoidOptions[c] = ScriptUtils.booleanOption(cliOpts[c]);
}
});
if (cliOpts.usePHPPreProcessor !== undefined) {
parsoidOptions.usePHPPreProcessor = parsoidOptions.fetchTemplates &&
ScriptUtils.booleanOption(cliOpts.usePHPPreProcessor);
}
if (cliOpts.maxDepth !== undefined) {
parsoidOptions.maxDepth = typeof (cliOpts.maxdepth) === 'number' ?
cliOpts.maxdepth : parsoidOptions.maxDepth;
}
if (cliOpts.apiURL) {
if (!Array.isArray(parsoidOptions.mwApis)) {
parsoidOptions.mwApis = [];
}
parsoidOptions.mwApis.push({ prefix: 'customwiki', uri: cliOpts.apiURL });
}
if (cliOpts.addHTMLTemplateParameters !== undefined) {
parsoidOptions.addHTMLTemplateParameters =
ScriptUtils.booleanOption(cliOpts.addHTMLTemplateParameters);
}
if (cliOpts.lint) {
parsoidOptions.linting = true;
if (!parsoidOptions.linter) {
parsoidOptions.linter = {};
}
parsoidOptions.linter.sendAPI = false;
}
if (cliOpts.useBatchAPI !== null) {
parsoidOptions.useBatchAPI = ScriptUtils.booleanOption(cliOpts.useBatchAPI);
}
if (cliOpts.phpConfigFile) {
parsoidOptions.phpConfigFile = cliOpts.phpConfigFile;
}
return parsoidOptions;
}
|
javascript
|
function(parsoidOptions, cliOpts) {
[
'fetchConfig',
'fetchTemplates',
'fetchImageInfo',
'expandExtensions',
'rtTestMode',
'addHTMLTemplateParameters',
].forEach(function(c) {
if (cliOpts[c] !== undefined) {
parsoidOptions[c] = ScriptUtils.booleanOption(cliOpts[c]);
}
});
if (cliOpts.usePHPPreProcessor !== undefined) {
parsoidOptions.usePHPPreProcessor = parsoidOptions.fetchTemplates &&
ScriptUtils.booleanOption(cliOpts.usePHPPreProcessor);
}
if (cliOpts.maxDepth !== undefined) {
parsoidOptions.maxDepth = typeof (cliOpts.maxdepth) === 'number' ?
cliOpts.maxdepth : parsoidOptions.maxDepth;
}
if (cliOpts.apiURL) {
if (!Array.isArray(parsoidOptions.mwApis)) {
parsoidOptions.mwApis = [];
}
parsoidOptions.mwApis.push({ prefix: 'customwiki', uri: cliOpts.apiURL });
}
if (cliOpts.addHTMLTemplateParameters !== undefined) {
parsoidOptions.addHTMLTemplateParameters =
ScriptUtils.booleanOption(cliOpts.addHTMLTemplateParameters);
}
if (cliOpts.lint) {
parsoidOptions.linting = true;
if (!parsoidOptions.linter) {
parsoidOptions.linter = {};
}
parsoidOptions.linter.sendAPI = false;
}
if (cliOpts.useBatchAPI !== null) {
parsoidOptions.useBatchAPI = ScriptUtils.booleanOption(cliOpts.useBatchAPI);
}
if (cliOpts.phpConfigFile) {
parsoidOptions.phpConfigFile = cliOpts.phpConfigFile;
}
return parsoidOptions;
}
|
[
"function",
"(",
"parsoidOptions",
",",
"cliOpts",
")",
"{",
"[",
"'fetchConfig'",
",",
"'fetchTemplates'",
",",
"'fetchImageInfo'",
",",
"'expandExtensions'",
",",
"'rtTestMode'",
",",
"'addHTMLTemplateParameters'",
",",
"]",
".",
"forEach",
"(",
"function",
"(",
"c",
")",
"{",
"if",
"(",
"cliOpts",
"[",
"c",
"]",
"!==",
"undefined",
")",
"{",
"parsoidOptions",
"[",
"c",
"]",
"=",
"ScriptUtils",
".",
"booleanOption",
"(",
"cliOpts",
"[",
"c",
"]",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"cliOpts",
".",
"usePHPPreProcessor",
"!==",
"undefined",
")",
"{",
"parsoidOptions",
".",
"usePHPPreProcessor",
"=",
"parsoidOptions",
".",
"fetchTemplates",
"&&",
"ScriptUtils",
".",
"booleanOption",
"(",
"cliOpts",
".",
"usePHPPreProcessor",
")",
";",
"}",
"if",
"(",
"cliOpts",
".",
"maxDepth",
"!==",
"undefined",
")",
"{",
"parsoidOptions",
".",
"maxDepth",
"=",
"typeof",
"(",
"cliOpts",
".",
"maxdepth",
")",
"===",
"'number'",
"?",
"cliOpts",
".",
"maxdepth",
":",
"parsoidOptions",
".",
"maxDepth",
";",
"}",
"if",
"(",
"cliOpts",
".",
"apiURL",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"parsoidOptions",
".",
"mwApis",
")",
")",
"{",
"parsoidOptions",
".",
"mwApis",
"=",
"[",
"]",
";",
"}",
"parsoidOptions",
".",
"mwApis",
".",
"push",
"(",
"{",
"prefix",
":",
"'customwiki'",
",",
"uri",
":",
"cliOpts",
".",
"apiURL",
"}",
")",
";",
"}",
"if",
"(",
"cliOpts",
".",
"addHTMLTemplateParameters",
"!==",
"undefined",
")",
"{",
"parsoidOptions",
".",
"addHTMLTemplateParameters",
"=",
"ScriptUtils",
".",
"booleanOption",
"(",
"cliOpts",
".",
"addHTMLTemplateParameters",
")",
";",
"}",
"if",
"(",
"cliOpts",
".",
"lint",
")",
"{",
"parsoidOptions",
".",
"linting",
"=",
"true",
";",
"if",
"(",
"!",
"parsoidOptions",
".",
"linter",
")",
"{",
"parsoidOptions",
".",
"linter",
"=",
"{",
"}",
";",
"}",
"parsoidOptions",
".",
"linter",
".",
"sendAPI",
"=",
"false",
";",
"}",
"if",
"(",
"cliOpts",
".",
"useBatchAPI",
"!==",
"null",
")",
"{",
"parsoidOptions",
".",
"useBatchAPI",
"=",
"ScriptUtils",
".",
"booleanOption",
"(",
"cliOpts",
".",
"useBatchAPI",
")",
";",
"}",
"if",
"(",
"cliOpts",
".",
"phpConfigFile",
")",
"{",
"parsoidOptions",
".",
"phpConfigFile",
"=",
"cliOpts",
".",
"phpConfigFile",
";",
"}",
"return",
"parsoidOptions",
";",
"}"
] |
Sets templating and processing flags on an object,
based on an options object.
@param {Object} parsoidOptions Object to be assigned to the ParsoidConfig.
@param {Object} cliOpts The options object to use for setting the debug flags.
@return {Object} The modified object.
|
[
"Sets",
"templating",
"and",
"processing",
"flags",
"on",
"an",
"object",
"based",
"on",
"an",
"options",
"object",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/tools/ScriptUtils.js#L270-L316
|
|
15,071
|
wikimedia/parsoid
|
tools/ScriptUtils.js
|
function(options) {
var colors = require('colors');
if (options.color === 'auto') {
if (!process.stdout.isTTY) {
colors.mode = 'none';
}
} else if (!ScriptUtils.booleanOption(options.color)) {
colors.mode = 'none';
}
}
|
javascript
|
function(options) {
var colors = require('colors');
if (options.color === 'auto') {
if (!process.stdout.isTTY) {
colors.mode = 'none';
}
} else if (!ScriptUtils.booleanOption(options.color)) {
colors.mode = 'none';
}
}
|
[
"function",
"(",
"options",
")",
"{",
"var",
"colors",
"=",
"require",
"(",
"'colors'",
")",
";",
"if",
"(",
"options",
".",
"color",
"===",
"'auto'",
")",
"{",
"if",
"(",
"!",
"process",
".",
"stdout",
".",
"isTTY",
")",
"{",
"colors",
".",
"mode",
"=",
"'none'",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"ScriptUtils",
".",
"booleanOption",
"(",
"options",
".",
"color",
")",
")",
"{",
"colors",
".",
"mode",
"=",
"'none'",
";",
"}",
"}"
] |
Set the color flags, based on an options object.
@param {Object} options
The options object to use for setting the mode of the 'color' package.
@param {string|boolean} options.color
Whether to use color. Passing 'auto' will enable color only if
stdout is a TTY device.
|
[
"Set",
"the",
"color",
"flags",
"based",
"on",
"an",
"options",
"object",
"."
] |
641ded74d8f736c2a18259d509525f96e83cd570
|
https://github.com/wikimedia/parsoid/blob/641ded74d8f736c2a18259d509525f96e83cd570/tools/ScriptUtils.js#L345-L354
|
|
15,072
|
mapbox/geojson-merge
|
index.js
|
merge
|
function merge (inputs) {
var output = {
type: 'FeatureCollection',
features: []
};
for (var i = 0; i < inputs.length; i++) {
var normalized = normalize(inputs[i]);
for (var j = 0; j < normalized.features.length; j++) {
output.features.push(normalized.features[j]);
}
}
return output;
}
|
javascript
|
function merge (inputs) {
var output = {
type: 'FeatureCollection',
features: []
};
for (var i = 0; i < inputs.length; i++) {
var normalized = normalize(inputs[i]);
for (var j = 0; j < normalized.features.length; j++) {
output.features.push(normalized.features[j]);
}
}
return output;
}
|
[
"function",
"merge",
"(",
"inputs",
")",
"{",
"var",
"output",
"=",
"{",
"type",
":",
"'FeatureCollection'",
",",
"features",
":",
"[",
"]",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"inputs",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"normalized",
"=",
"normalize",
"(",
"inputs",
"[",
"i",
"]",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"normalized",
".",
"features",
".",
"length",
";",
"j",
"++",
")",
"{",
"output",
".",
"features",
".",
"push",
"(",
"normalized",
".",
"features",
"[",
"j",
"]",
")",
";",
"}",
"}",
"return",
"output",
";",
"}"
] |
Merge a series of GeoJSON objects into one FeatureCollection containing all
features in all files. The objects can be any valid GeoJSON root object,
including FeatureCollection, Feature, and Geometry types.
@param {Array<Object>} inputs a list of GeoJSON objects of any type
@return {Object} a geojson FeatureCollection.
@example
var geojsonMerge = require('@mapbox/geojson-merge');
var mergedGeoJSON = geojsonMerge.merge([
{ type: 'Point', coordinates: [0, 1] },
{ type: 'Feature', geometry: { type: 'Point', coordinates: [0, 1] }, properties: {} }
]);
console.log(JSON.stringify(mergedGeoJSON));
|
[
"Merge",
"a",
"series",
"of",
"GeoJSON",
"objects",
"into",
"one",
"FeatureCollection",
"containing",
"all",
"features",
"in",
"all",
"files",
".",
"The",
"objects",
"can",
"be",
"any",
"valid",
"GeoJSON",
"root",
"object",
"including",
"FeatureCollection",
"Feature",
"and",
"Geometry",
"types",
"."
] |
a4e8ed3cb2e8ce61a59cb5c160f4a3506937dd7d
|
https://github.com/mapbox/geojson-merge/blob/a4e8ed3cb2e8ce61a59cb5c160f4a3506937dd7d/index.js#L22-L34
|
15,073
|
mapbox/geojson-merge
|
index.js
|
mergeFeatureCollectionStream
|
function mergeFeatureCollectionStream (inputs) {
var out = geojsonStream.stringify();
inputs.forEach(function(file) {
fs.createReadStream(file)
.pipe(geojsonStream.parse())
.pipe(out);
});
return out;
}
|
javascript
|
function mergeFeatureCollectionStream (inputs) {
var out = geojsonStream.stringify();
inputs.forEach(function(file) {
fs.createReadStream(file)
.pipe(geojsonStream.parse())
.pipe(out);
});
return out;
}
|
[
"function",
"mergeFeatureCollectionStream",
"(",
"inputs",
")",
"{",
"var",
"out",
"=",
"geojsonStream",
".",
"stringify",
"(",
")",
";",
"inputs",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"fs",
".",
"createReadStream",
"(",
"file",
")",
".",
"pipe",
"(",
"geojsonStream",
".",
"parse",
"(",
")",
")",
".",
"pipe",
"(",
"out",
")",
";",
"}",
")",
";",
"return",
"out",
";",
"}"
] |
Merge GeoJSON files containing GeoJSON FeatureCollections
into a single stream of a FeatureCollection as a JSON string.
This is more limited than merge - it only supports FeatureCollections
as input - but more performant, since it can operate on GeoJSON files
larger than what you can keep in memory at one time.
@param {Array<string>} inputs a list of filenames of GeoJSON files
@returns {Stream} output: a stringified JSON of a FeatureCollection.
@example
var geojsonMerge = require('@mapbox/geojson-merge');
var mergedStream = geojsonMerge.mergeFeatureCollectionStream([
'features.geojson',
'otherFeatures.geojson'])
mergedStream.pipe(process.stdout);
|
[
"Merge",
"GeoJSON",
"files",
"containing",
"GeoJSON",
"FeatureCollections",
"into",
"a",
"single",
"stream",
"of",
"a",
"FeatureCollection",
"as",
"a",
"JSON",
"string",
"."
] |
a4e8ed3cb2e8ce61a59cb5c160f4a3506937dd7d
|
https://github.com/mapbox/geojson-merge/blob/a4e8ed3cb2e8ce61a59cb5c160f4a3506937dd7d/index.js#L54-L62
|
15,074
|
midwayjs/pandora
|
packages/pandora/3rd/fork.js
|
onerror
|
function onerror(err) {
if (!err) {
return;
}
debug('[%s] [cfork:master:%s] master uncaughtException: %s', Date(), process.pid, err.stack);
debug(err);
debug('(total %d disconnect, %d unexpected exit)', disconnectCount, unexpectedCount);
}
|
javascript
|
function onerror(err) {
if (!err) {
return;
}
debug('[%s] [cfork:master:%s] master uncaughtException: %s', Date(), process.pid, err.stack);
debug(err);
debug('(total %d disconnect, %d unexpected exit)', disconnectCount, unexpectedCount);
}
|
[
"function",
"onerror",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"return",
";",
"}",
"debug",
"(",
"'[%s] [cfork:master:%s] master uncaughtException: %s'",
",",
"Date",
"(",
")",
",",
"process",
".",
"pid",
",",
"err",
".",
"stack",
")",
";",
"debug",
"(",
"err",
")",
";",
"debug",
"(",
"'(total %d disconnect, %d unexpected exit)'",
",",
"disconnectCount",
",",
"unexpectedCount",
")",
";",
"}"
] |
uncaughtException default handler
|
[
"uncaughtException",
"default",
"handler"
] |
7310db12af93ef353b4d2014f7b5d276b81aaeec
|
https://github.com/midwayjs/pandora/blob/7310db12af93ef353b4d2014f7b5d276b81aaeec/packages/pandora/3rd/fork.js#L213-L220
|
15,075
|
midwayjs/pandora
|
packages/pandora/3rd/fork.js
|
onUnexpected
|
function onUnexpected(worker, code, signal) {
var exitCode = worker.process.exitCode;
var err = new Error(util.format('worker:%s died unexpected (code: %s, signal: %s, exitedAfterDisconnect: %s, state: %s)',
worker.process.pid, exitCode, signal, worker.exitedAfterDisconnect, worker.state));
err.name = 'WorkerDiedUnexpectedError';
debug('[%s] [cfork:master:%s] (total %d disconnect, %d unexpected exit) %s',
Date(), process.pid, disconnectCount, unexpectedCount, err.stack);
}
|
javascript
|
function onUnexpected(worker, code, signal) {
var exitCode = worker.process.exitCode;
var err = new Error(util.format('worker:%s died unexpected (code: %s, signal: %s, exitedAfterDisconnect: %s, state: %s)',
worker.process.pid, exitCode, signal, worker.exitedAfterDisconnect, worker.state));
err.name = 'WorkerDiedUnexpectedError';
debug('[%s] [cfork:master:%s] (total %d disconnect, %d unexpected exit) %s',
Date(), process.pid, disconnectCount, unexpectedCount, err.stack);
}
|
[
"function",
"onUnexpected",
"(",
"worker",
",",
"code",
",",
"signal",
")",
"{",
"var",
"exitCode",
"=",
"worker",
".",
"process",
".",
"exitCode",
";",
"var",
"err",
"=",
"new",
"Error",
"(",
"util",
".",
"format",
"(",
"'worker:%s died unexpected (code: %s, signal: %s, exitedAfterDisconnect: %s, state: %s)'",
",",
"worker",
".",
"process",
".",
"pid",
",",
"exitCode",
",",
"signal",
",",
"worker",
".",
"exitedAfterDisconnect",
",",
"worker",
".",
"state",
")",
")",
";",
"err",
".",
"name",
"=",
"'WorkerDiedUnexpectedError'",
";",
"debug",
"(",
"'[%s] [cfork:master:%s] (total %d disconnect, %d unexpected exit) %s'",
",",
"Date",
"(",
")",
",",
"process",
".",
"pid",
",",
"disconnectCount",
",",
"unexpectedCount",
",",
"err",
".",
"stack",
")",
";",
"}"
] |
unexpectedExit default handler
|
[
"unexpectedExit",
"default",
"handler"
] |
7310db12af93ef353b4d2014f7b5d276b81aaeec
|
https://github.com/midwayjs/pandora/blob/7310db12af93ef353b4d2014f7b5d276b81aaeec/packages/pandora/3rd/fork.js#L226-L234
|
15,076
|
midwayjs/pandora
|
packages/pandora/3rd/fork.js
|
normalizeSlaveConfig
|
function normalizeSlaveConfig(opt) {
// exec path
if (typeof opt === 'string') {
opt = { exec: opt };
}
if (!opt.exec) {
return null;
} else {
return opt;
}
}
|
javascript
|
function normalizeSlaveConfig(opt) {
// exec path
if (typeof opt === 'string') {
opt = { exec: opt };
}
if (!opt.exec) {
return null;
} else {
return opt;
}
}
|
[
"function",
"normalizeSlaveConfig",
"(",
"opt",
")",
"{",
"// exec path",
"if",
"(",
"typeof",
"opt",
"===",
"'string'",
")",
"{",
"opt",
"=",
"{",
"exec",
":",
"opt",
"}",
";",
"}",
"if",
"(",
"!",
"opt",
".",
"exec",
")",
"{",
"return",
"null",
";",
"}",
"else",
"{",
"return",
"opt",
";",
"}",
"}"
] |
normalize slave config
|
[
"normalize",
"slave",
"config"
] |
7310db12af93ef353b4d2014f7b5d276b81aaeec
|
https://github.com/midwayjs/pandora/blob/7310db12af93ef353b4d2014f7b5d276b81aaeec/packages/pandora/3rd/fork.js#L248-L258
|
15,077
|
midwayjs/pandora
|
packages/pandora/3rd/fork.js
|
forkWorker
|
function forkWorker(settings, env) {
if (settings) {
cluster.settings = settings;
cluster.setupMaster();
}
return cluster.fork(env);
}
|
javascript
|
function forkWorker(settings, env) {
if (settings) {
cluster.settings = settings;
cluster.setupMaster();
}
return cluster.fork(env);
}
|
[
"function",
"forkWorker",
"(",
"settings",
",",
"env",
")",
"{",
"if",
"(",
"settings",
")",
"{",
"cluster",
".",
"settings",
"=",
"settings",
";",
"cluster",
".",
"setupMaster",
"(",
")",
";",
"}",
"return",
"cluster",
".",
"fork",
"(",
"env",
")",
";",
"}"
] |
fork worker with certain settings
|
[
"fork",
"worker",
"with",
"certain",
"settings"
] |
7310db12af93ef353b4d2014f7b5d276b81aaeec
|
https://github.com/midwayjs/pandora/blob/7310db12af93ef353b4d2014f7b5d276b81aaeec/packages/pandora/3rd/fork.js#L263-L269
|
15,078
|
jamesssooi/Croppr.js
|
src/polyfills.js
|
MouseEvent
|
function MouseEvent(eventType, params) {
params = params || { bubbles: false, cancelable: false };
var mouseEvent = document.createEvent('MouseEvent');
mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
return mouseEvent;
}
|
javascript
|
function MouseEvent(eventType, params) {
params = params || { bubbles: false, cancelable: false };
var mouseEvent = document.createEvent('MouseEvent');
mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
return mouseEvent;
}
|
[
"function",
"MouseEvent",
"(",
"eventType",
",",
"params",
")",
"{",
"params",
"=",
"params",
"||",
"{",
"bubbles",
":",
"false",
",",
"cancelable",
":",
"false",
"}",
";",
"var",
"mouseEvent",
"=",
"document",
".",
"createEvent",
"(",
"'MouseEvent'",
")",
";",
"mouseEvent",
".",
"initMouseEvent",
"(",
"eventType",
",",
"params",
".",
"bubbles",
",",
"params",
".",
"cancelable",
",",
"window",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"false",
",",
"false",
",",
"false",
",",
"false",
",",
"0",
",",
"null",
")",
";",
"return",
"mouseEvent",
";",
"}"
] |
Polyfills DOM4 CustomEvent
|
[
"Polyfills",
"DOM4",
"CustomEvent"
] |
df27b32e8c7cd14d1fa8a63de74e74035aecc06e
|
https://github.com/jamesssooi/Croppr.js/blob/df27b32e8c7cd14d1fa8a63de74e74035aecc06e/src/polyfills.js#L58-L64
|
15,079
|
jamesssooi/Croppr.js
|
src/touch.js
|
simulateMouseEvent
|
function simulateMouseEvent(e) {
e.preventDefault();
const touch = e.changedTouches[0];
const eventMap = {
'touchstart': 'mousedown',
'touchmove': 'mousemove',
'touchend': 'mouseup'
}
touch.target.dispatchEvent(new MouseEvent(eventMap[e.type], {
bubbles: true,
cancelable: true,
view: window,
clientX: touch.clientX,
clientY: touch.clientY,
screenX: touch.screenX,
screenY: touch.screenY,
}));
}
|
javascript
|
function simulateMouseEvent(e) {
e.preventDefault();
const touch = e.changedTouches[0];
const eventMap = {
'touchstart': 'mousedown',
'touchmove': 'mousemove',
'touchend': 'mouseup'
}
touch.target.dispatchEvent(new MouseEvent(eventMap[e.type], {
bubbles: true,
cancelable: true,
view: window,
clientX: touch.clientX,
clientY: touch.clientY,
screenX: touch.screenX,
screenY: touch.screenY,
}));
}
|
[
"function",
"simulateMouseEvent",
"(",
"e",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"const",
"touch",
"=",
"e",
".",
"changedTouches",
"[",
"0",
"]",
";",
"const",
"eventMap",
"=",
"{",
"'touchstart'",
":",
"'mousedown'",
",",
"'touchmove'",
":",
"'mousemove'",
",",
"'touchend'",
":",
"'mouseup'",
"}",
"touch",
".",
"target",
".",
"dispatchEvent",
"(",
"new",
"MouseEvent",
"(",
"eventMap",
"[",
"e",
".",
"type",
"]",
",",
"{",
"bubbles",
":",
"true",
",",
"cancelable",
":",
"true",
",",
"view",
":",
"window",
",",
"clientX",
":",
"touch",
".",
"clientX",
",",
"clientY",
":",
"touch",
".",
"clientY",
",",
"screenX",
":",
"touch",
".",
"screenX",
",",
"screenY",
":",
"touch",
".",
"screenY",
",",
"}",
")",
")",
";",
"}"
] |
Translates a touch event to a mouse event.
@param {Event} e
|
[
"Translates",
"a",
"touch",
"event",
"to",
"a",
"mouse",
"event",
"."
] |
df27b32e8c7cd14d1fa8a63de74e74035aecc06e
|
https://github.com/jamesssooi/Croppr.js/blob/df27b32e8c7cd14d1fa8a63de74e74035aecc06e/src/touch.js#L21-L39
|
15,080
|
jleyba/js-dossier
|
src/js/app.js
|
onCardHeaderClick
|
function onCardHeaderClick(e) {
if (/** @type {!Element} */(e.target).nodeName == 'A') {
return;
}
/** @type {?Node} */
const node = /** @type {!Element} */(e.currentTarget).parentNode;
if (node && node.nodeType === NodeType.ELEMENT) {
const card = /** @type {!Element} */(node);
if (card.classList && card.classList.contains('property')) {
card.classList.toggle('open');
}
}
}
|
javascript
|
function onCardHeaderClick(e) {
if (/** @type {!Element} */(e.target).nodeName == 'A') {
return;
}
/** @type {?Node} */
const node = /** @type {!Element} */(e.currentTarget).parentNode;
if (node && node.nodeType === NodeType.ELEMENT) {
const card = /** @type {!Element} */(node);
if (card.classList && card.classList.contains('property')) {
card.classList.toggle('open');
}
}
}
|
[
"function",
"onCardHeaderClick",
"(",
"e",
")",
"{",
"if",
"(",
"/** @type {!Element} */",
"(",
"e",
".",
"target",
")",
".",
"nodeName",
"==",
"'A'",
")",
"{",
"return",
";",
"}",
"/** @type {?Node} */",
"const",
"node",
"=",
"/** @type {!Element} */",
"(",
"e",
".",
"currentTarget",
")",
".",
"parentNode",
";",
"if",
"(",
"node",
"&&",
"node",
".",
"nodeType",
"===",
"NodeType",
".",
"ELEMENT",
")",
"{",
"const",
"card",
"=",
"/** @type {!Element} */",
"(",
"node",
")",
";",
"if",
"(",
"card",
".",
"classList",
"&&",
"card",
".",
"classList",
".",
"contains",
"(",
"'property'",
")",
")",
"{",
"card",
".",
"classList",
".",
"toggle",
"(",
"'open'",
")",
";",
"}",
"}",
"}"
] |
Responds to click events on a property card.
@param {!Event} e The click event.
|
[
"Responds",
"to",
"click",
"events",
"on",
"a",
"property",
"card",
"."
] |
c58032be37d8c138312c9f2ee77a867c8d9a944c
|
https://github.com/jleyba/js-dossier/blob/c58032be37d8c138312c9f2ee77a867c8d9a944c/src/js/app.js#L44-L57
|
15,081
|
Falconerd/discord-bot-github
|
src/main.js
|
parseMessage
|
function parseMessage(message) {
const parts = message.content.split(' ');
const command = parts[1];
const args = parts.slice(2);
if (typeof Commands[command] === 'function') {
// @TODO We could check the command validity here
return { command, args };
} else {
return null;
}
}
|
javascript
|
function parseMessage(message) {
const parts = message.content.split(' ');
const command = parts[1];
const args = parts.slice(2);
if (typeof Commands[command] === 'function') {
// @TODO We could check the command validity here
return { command, args };
} else {
return null;
}
}
|
[
"function",
"parseMessage",
"(",
"message",
")",
"{",
"const",
"parts",
"=",
"message",
".",
"content",
".",
"split",
"(",
"' '",
")",
";",
"const",
"command",
"=",
"parts",
"[",
"1",
"]",
";",
"const",
"args",
"=",
"parts",
".",
"slice",
"(",
"2",
")",
";",
"if",
"(",
"typeof",
"Commands",
"[",
"command",
"]",
"===",
"'function'",
")",
"{",
"// @TODO We could check the command validity here",
"return",
"{",
"command",
",",
"args",
"}",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] |
Take in the content of a message and return a command
@param {Message} message The Discord.Message object
@return {Object} An object continaing a command name and arguments
|
[
"Take",
"in",
"the",
"content",
"of",
"a",
"message",
"and",
"return",
"a",
"command"
] |
44ecf5b2e1cc69190df4863c67a66989d412cf7d
|
https://github.com/Falconerd/discord-bot-github/blob/44ecf5b2e1cc69190df4863c67a66989d412cf7d/src/main.js#L87-L98
|
15,082
|
postmanlabs/postman-collection
|
npm/publish-wiki.js
|
function (next) {
console.log(chalk.yellow.bold('Publishing wiki...'));
// create a location to clone repository
// @todo - maybe do this outside in an os-level temp folder to avoid recursive .git
mkdir('-p', WIKI_GIT_PATH);
rm('-rf', WIKI_GIT_PATH);
// @todo: Consider navigating to WIKI_GIT_PATH, setting up a new git repo there, point the remote
// to WIKI_GIT_URL,
// @todo: and push
exec(`git clone ${WIKI_URL} ${WIKI_GIT_PATH} --quiet`, next);
}
|
javascript
|
function (next) {
console.log(chalk.yellow.bold('Publishing wiki...'));
// create a location to clone repository
// @todo - maybe do this outside in an os-level temp folder to avoid recursive .git
mkdir('-p', WIKI_GIT_PATH);
rm('-rf', WIKI_GIT_PATH);
// @todo: Consider navigating to WIKI_GIT_PATH, setting up a new git repo there, point the remote
// to WIKI_GIT_URL,
// @todo: and push
exec(`git clone ${WIKI_URL} ${WIKI_GIT_PATH} --quiet`, next);
}
|
[
"function",
"(",
"next",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"yellow",
".",
"bold",
"(",
"'Publishing wiki...'",
")",
")",
";",
"// create a location to clone repository",
"// @todo - maybe do this outside in an os-level temp folder to avoid recursive .git",
"mkdir",
"(",
"'-p'",
",",
"WIKI_GIT_PATH",
")",
";",
"rm",
"(",
"'-rf'",
",",
"WIKI_GIT_PATH",
")",
";",
"// @todo: Consider navigating to WIKI_GIT_PATH, setting up a new git repo there, point the remote",
"// to WIKI_GIT_URL,",
"// @todo: and push",
"exec",
"(",
"`",
"${",
"WIKI_URL",
"}",
"${",
"WIKI_GIT_PATH",
"}",
"`",
",",
"next",
")",
";",
"}"
] |
prepare a separate wiki output folder
|
[
"prepare",
"a",
"separate",
"wiki",
"output",
"folder"
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/npm/publish-wiki.js#L21-L33
|
|
15,083
|
postmanlabs/postman-collection
|
npm/publish-wiki.js
|
function (next) {
var source = fs.readFileSync(path.join('out', 'wiki', 'REFERENCE.md')).toString(),
home,
sidebar;
// extract sidebar from source
sidebar = source.replace(/<a name="Collection"><\/a>[\s\S]+/g, '');
// remove sidebar data from home
home = source.substr(sidebar.length);
// add timestamp to sidebar
sidebar += '\n\n ' + (new Date()).toUTCString();
async.each([{
path: path.join('.tmp', 'github-wiki', '_Sidebar.md'),
data: sidebar
}, {
path: path.join('.tmp', 'github-wiki', 'Home.md'),
data: home
}], function (opts, next) {
fs.writeFile(opts.path, opts.data, next);
}, next);
}
|
javascript
|
function (next) {
var source = fs.readFileSync(path.join('out', 'wiki', 'REFERENCE.md')).toString(),
home,
sidebar;
// extract sidebar from source
sidebar = source.replace(/<a name="Collection"><\/a>[\s\S]+/g, '');
// remove sidebar data from home
home = source.substr(sidebar.length);
// add timestamp to sidebar
sidebar += '\n\n ' + (new Date()).toUTCString();
async.each([{
path: path.join('.tmp', 'github-wiki', '_Sidebar.md'),
data: sidebar
}, {
path: path.join('.tmp', 'github-wiki', 'Home.md'),
data: home
}], function (opts, next) {
fs.writeFile(opts.path, opts.data, next);
}, next);
}
|
[
"function",
"(",
"next",
")",
"{",
"var",
"source",
"=",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"'out'",
",",
"'wiki'",
",",
"'REFERENCE.md'",
")",
")",
".",
"toString",
"(",
")",
",",
"home",
",",
"sidebar",
";",
"// extract sidebar from source",
"sidebar",
"=",
"source",
".",
"replace",
"(",
"/",
"<a name=\"Collection\"><\\/a>[\\s\\S]+",
"/",
"g",
",",
"''",
")",
";",
"// remove sidebar data from home",
"home",
"=",
"source",
".",
"substr",
"(",
"sidebar",
".",
"length",
")",
";",
"// add timestamp to sidebar",
"sidebar",
"+=",
"'\\n\\n '",
"+",
"(",
"new",
"Date",
"(",
")",
")",
".",
"toUTCString",
"(",
")",
";",
"async",
".",
"each",
"(",
"[",
"{",
"path",
":",
"path",
".",
"join",
"(",
"'.tmp'",
",",
"'github-wiki'",
",",
"'_Sidebar.md'",
")",
",",
"data",
":",
"sidebar",
"}",
",",
"{",
"path",
":",
"path",
".",
"join",
"(",
"'.tmp'",
",",
"'github-wiki'",
",",
"'Home.md'",
")",
",",
"data",
":",
"home",
"}",
"]",
",",
"function",
"(",
"opts",
",",
"next",
")",
"{",
"fs",
".",
"writeFile",
"(",
"opts",
".",
"path",
",",
"opts",
".",
"data",
",",
"next",
")",
";",
"}",
",",
"next",
")",
";",
"}"
] |
update contents of repository
|
[
"update",
"contents",
"of",
"repository"
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/npm/publish-wiki.js#L36-L59
|
|
15,084
|
postmanlabs/postman-collection
|
npm/publish-wiki.js
|
function (next) {
// silence terminal output to prevent leaking sensitive information
config.silent = true;
pushd(WIKI_GIT_PATH);
exec('git add --all');
exec('git commit -m "[auto] ' + WIKI_VERSION + '"');
exec('git push origin master', function (code) {
popd();
next(code);
});
}
|
javascript
|
function (next) {
// silence terminal output to prevent leaking sensitive information
config.silent = true;
pushd(WIKI_GIT_PATH);
exec('git add --all');
exec('git commit -m "[auto] ' + WIKI_VERSION + '"');
exec('git push origin master', function (code) {
popd();
next(code);
});
}
|
[
"function",
"(",
"next",
")",
"{",
"// silence terminal output to prevent leaking sensitive information",
"config",
".",
"silent",
"=",
"true",
";",
"pushd",
"(",
"WIKI_GIT_PATH",
")",
";",
"exec",
"(",
"'git add --all'",
")",
";",
"exec",
"(",
"'git commit -m \"[auto] '",
"+",
"WIKI_VERSION",
"+",
"'\"'",
")",
";",
"exec",
"(",
"'git push origin master'",
",",
"function",
"(",
"code",
")",
"{",
"popd",
"(",
")",
";",
"next",
"(",
"code",
")",
";",
"}",
")",
";",
"}"
] |
publish the wiki where it should go
|
[
"publish",
"the",
"wiki",
"where",
"it",
"should",
"go"
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/npm/publish-wiki.js#L62-L73
|
|
15,085
|
postmanlabs/postman-collection
|
lib/collection/variable-list.js
|
function (obj, overrides, mutate) {
var resolutionQueue = [], // we use this to store the queue of variable hierarchy
// this is an intermediate object to stimulate a property (makes the do-while loop easier)
variableSource = {
variables: this,
__parent: this.__parent
};
do { // iterate and accumulate as long as you find `.variables` in parent tree
variableSource.variables && resolutionQueue.push(variableSource.variables);
variableSource = variableSource.__parent;
} while (variableSource);
variableSource = null; // cautious cleanup
return Property.replaceSubstitutionsIn(obj, _.union(resolutionQueue, overrides), mutate);
}
|
javascript
|
function (obj, overrides, mutate) {
var resolutionQueue = [], // we use this to store the queue of variable hierarchy
// this is an intermediate object to stimulate a property (makes the do-while loop easier)
variableSource = {
variables: this,
__parent: this.__parent
};
do { // iterate and accumulate as long as you find `.variables` in parent tree
variableSource.variables && resolutionQueue.push(variableSource.variables);
variableSource = variableSource.__parent;
} while (variableSource);
variableSource = null; // cautious cleanup
return Property.replaceSubstitutionsIn(obj, _.union(resolutionQueue, overrides), mutate);
}
|
[
"function",
"(",
"obj",
",",
"overrides",
",",
"mutate",
")",
"{",
"var",
"resolutionQueue",
"=",
"[",
"]",
",",
"// we use this to store the queue of variable hierarchy",
"// this is an intermediate object to stimulate a property (makes the do-while loop easier)",
"variableSource",
"=",
"{",
"variables",
":",
"this",
",",
"__parent",
":",
"this",
".",
"__parent",
"}",
";",
"do",
"{",
"// iterate and accumulate as long as you find `.variables` in parent tree",
"variableSource",
".",
"variables",
"&&",
"resolutionQueue",
".",
"push",
"(",
"variableSource",
".",
"variables",
")",
";",
"variableSource",
"=",
"variableSource",
".",
"__parent",
";",
"}",
"while",
"(",
"variableSource",
")",
";",
"variableSource",
"=",
"null",
";",
"// cautious cleanup",
"return",
"Property",
".",
"replaceSubstitutionsIn",
"(",
"obj",
",",
"_",
".",
"union",
"(",
"resolutionQueue",
",",
"overrides",
")",
",",
"mutate",
")",
";",
"}"
] |
Recursively replace strings in an object with instances of variables. Note that it clones the original object. If
the `mutate` param is set to true, then it replaces the same object instead of creating a new one.
@param {Array|Object} obj
@param {?Array<Object>=} [overrides] - additional objects to lookup for variable values
@param {Boolean=} [mutate=false]
@returns {Array|Object}
|
[
"Recursively",
"replace",
"strings",
"in",
"an",
"object",
"with",
"instances",
"of",
"variables",
".",
"Note",
"that",
"it",
"clones",
"the",
"original",
"object",
".",
"If",
"the",
"mutate",
"param",
"is",
"set",
"to",
"true",
"then",
"it",
"replaces",
"the",
"same",
"object",
"instead",
"of",
"creating",
"a",
"new",
"one",
"."
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/collection/variable-list.js#L43-L60
|
|
15,086
|
postmanlabs/postman-collection
|
lib/collection/variable-list.js
|
function (obj, track, prune) {
var list = this,
ops = track && {
created: [],
updated: [],
deleted: []
},
indexer = list._postman_listIndexKey,
tmp;
if (!_.isObject(obj)) { return ops; }
// ensure that all properties in the object is updated in this list
_.forOwn(obj, function (value, key) {
// we need to create new variable if exists or update existing
if (list.has(key)) {
list.one(key).set(value);
ops && ops.updated.push(key);
}
else {
tmp = { value: value };
tmp[indexer] = key;
list.add(tmp);
tmp = null;
ops && ops.created.push(key);
}
});
// now remove any variable that is not in source object
// @note - using direct `this.reference` list of keys here so that we can mutate the list while iterating
// on it
if (prune !== false) {
_.forEach(list.reference, function (value, key) {
if (obj.hasOwnProperty(key)) { return; } // de not delete if source obj has this variable
list.remove(key); // use PropertyList functions to remove so that the .members array is cleared too
ops && ops.deleted.push(key);
});
}
return ops;
}
|
javascript
|
function (obj, track, prune) {
var list = this,
ops = track && {
created: [],
updated: [],
deleted: []
},
indexer = list._postman_listIndexKey,
tmp;
if (!_.isObject(obj)) { return ops; }
// ensure that all properties in the object is updated in this list
_.forOwn(obj, function (value, key) {
// we need to create new variable if exists or update existing
if (list.has(key)) {
list.one(key).set(value);
ops && ops.updated.push(key);
}
else {
tmp = { value: value };
tmp[indexer] = key;
list.add(tmp);
tmp = null;
ops && ops.created.push(key);
}
});
// now remove any variable that is not in source object
// @note - using direct `this.reference` list of keys here so that we can mutate the list while iterating
// on it
if (prune !== false) {
_.forEach(list.reference, function (value, key) {
if (obj.hasOwnProperty(key)) { return; } // de not delete if source obj has this variable
list.remove(key); // use PropertyList functions to remove so that the .members array is cleared too
ops && ops.deleted.push(key);
});
}
return ops;
}
|
[
"function",
"(",
"obj",
",",
"track",
",",
"prune",
")",
"{",
"var",
"list",
"=",
"this",
",",
"ops",
"=",
"track",
"&&",
"{",
"created",
":",
"[",
"]",
",",
"updated",
":",
"[",
"]",
",",
"deleted",
":",
"[",
"]",
"}",
",",
"indexer",
"=",
"list",
".",
"_postman_listIndexKey",
",",
"tmp",
";",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"obj",
")",
")",
"{",
"return",
"ops",
";",
"}",
"// ensure that all properties in the object is updated in this list",
"_",
".",
"forOwn",
"(",
"obj",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"// we need to create new variable if exists or update existing",
"if",
"(",
"list",
".",
"has",
"(",
"key",
")",
")",
"{",
"list",
".",
"one",
"(",
"key",
")",
".",
"set",
"(",
"value",
")",
";",
"ops",
"&&",
"ops",
".",
"updated",
".",
"push",
"(",
"key",
")",
";",
"}",
"else",
"{",
"tmp",
"=",
"{",
"value",
":",
"value",
"}",
";",
"tmp",
"[",
"indexer",
"]",
"=",
"key",
";",
"list",
".",
"add",
"(",
"tmp",
")",
";",
"tmp",
"=",
"null",
";",
"ops",
"&&",
"ops",
".",
"created",
".",
"push",
"(",
"key",
")",
";",
"}",
"}",
")",
";",
"// now remove any variable that is not in source object",
"// @note - using direct `this.reference` list of keys here so that we can mutate the list while iterating",
"// on it",
"if",
"(",
"prune",
"!==",
"false",
")",
"{",
"_",
".",
"forEach",
"(",
"list",
".",
"reference",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"if",
"(",
"obj",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"return",
";",
"}",
"// de not delete if source obj has this variable",
"list",
".",
"remove",
"(",
"key",
")",
";",
"// use PropertyList functions to remove so that the .members array is cleared too",
"ops",
"&&",
"ops",
".",
"deleted",
".",
"push",
"(",
"key",
")",
";",
"}",
")",
";",
"}",
"return",
"ops",
";",
"}"
] |
Using this function, one can sync the values of this variable list from a reference object.
@param {Object} obj
@param {Boolean=} track
@param {Boolean} [prune=true]
@returns {Object}
|
[
"Using",
"this",
"function",
"one",
"can",
"sync",
"the",
"values",
"of",
"this",
"variable",
"list",
"from",
"a",
"reference",
"object",
"."
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/collection/variable-list.js#L71-L111
|
|
15,087
|
postmanlabs/postman-collection
|
lib/collection/variable-list.js
|
function (obj) {
var list = this;
// in case user did not provide an object to mutate, create a new one
!_.isObject(obj) && (obj = {});
// delete extra variables from object that are not present in list
_.forEach(obj, function (value, key) {
!_.has(list.reference, key) && (delete obj[key]);
});
// we first sync all variables in this list to the object
list.each(function (variable) {
obj[variable.key] = variable.valueOf();
});
return obj;
}
|
javascript
|
function (obj) {
var list = this;
// in case user did not provide an object to mutate, create a new one
!_.isObject(obj) && (obj = {});
// delete extra variables from object that are not present in list
_.forEach(obj, function (value, key) {
!_.has(list.reference, key) && (delete obj[key]);
});
// we first sync all variables in this list to the object
list.each(function (variable) {
obj[variable.key] = variable.valueOf();
});
return obj;
}
|
[
"function",
"(",
"obj",
")",
"{",
"var",
"list",
"=",
"this",
";",
"// in case user did not provide an object to mutate, create a new one",
"!",
"_",
".",
"isObject",
"(",
"obj",
")",
"&&",
"(",
"obj",
"=",
"{",
"}",
")",
";",
"// delete extra variables from object that are not present in list",
"_",
".",
"forEach",
"(",
"obj",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"!",
"_",
".",
"has",
"(",
"list",
".",
"reference",
",",
"key",
")",
"&&",
"(",
"delete",
"obj",
"[",
"key",
"]",
")",
";",
"}",
")",
";",
"// we first sync all variables in this list to the object",
"list",
".",
"each",
"(",
"function",
"(",
"variable",
")",
"{",
"obj",
"[",
"variable",
".",
"key",
"]",
"=",
"variable",
".",
"valueOf",
"(",
")",
";",
"}",
")",
";",
"return",
"obj",
";",
"}"
] |
Transfer all variables from this list to an object
@param {Object=} [obj]
@returns {Object}
|
[
"Transfer",
"all",
"variables",
"from",
"this",
"list",
"to",
"an",
"object"
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/collection/variable-list.js#L119-L136
|
|
15,088
|
postmanlabs/postman-collection
|
lib/collection/variable-list.js
|
function (obj) {
return Boolean(obj) && ((obj instanceof VariableList) ||
_.inSuperChain(obj.constructor, '_postman_propertyName', VariableList._postman_propertyName));
}
|
javascript
|
function (obj) {
return Boolean(obj) && ((obj instanceof VariableList) ||
_.inSuperChain(obj.constructor, '_postman_propertyName', VariableList._postman_propertyName));
}
|
[
"function",
"(",
"obj",
")",
"{",
"return",
"Boolean",
"(",
"obj",
")",
"&&",
"(",
"(",
"obj",
"instanceof",
"VariableList",
")",
"||",
"_",
".",
"inSuperChain",
"(",
"obj",
".",
"constructor",
",",
"'_postman_propertyName'",
",",
"VariableList",
".",
"_postman_propertyName",
")",
")",
";",
"}"
] |
Checks whether an object is a VariableList
@param {*} obj
@returns {Boolean}
|
[
"Checks",
"whether",
"an",
"object",
"is",
"a",
"VariableList"
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/collection/variable-list.js#L187-L190
|
|
15,089
|
postmanlabs/postman-collection
|
lib/collection/certificate-list.js
|
function (url) {
// url must be either string or an instance of url.
if (!_.isString(url) && !Url.isUrl(url)) {
return;
}
// find a certificate that can be applied to the url
return this.find(function (certificate) {
return certificate.canApplyTo(url);
});
}
|
javascript
|
function (url) {
// url must be either string or an instance of url.
if (!_.isString(url) && !Url.isUrl(url)) {
return;
}
// find a certificate that can be applied to the url
return this.find(function (certificate) {
return certificate.canApplyTo(url);
});
}
|
[
"function",
"(",
"url",
")",
"{",
"// url must be either string or an instance of url.",
"if",
"(",
"!",
"_",
".",
"isString",
"(",
"url",
")",
"&&",
"!",
"Url",
".",
"isUrl",
"(",
"url",
")",
")",
"{",
"return",
";",
"}",
"// find a certificate that can be applied to the url",
"return",
"this",
".",
"find",
"(",
"function",
"(",
"certificate",
")",
"{",
"return",
"certificate",
".",
"canApplyTo",
"(",
"url",
")",
";",
"}",
")",
";",
"}"
] |
Matches the given url against the member certificates' allowed matches
and returns the certificate that can be used for the url.
@param {String} url The url to find the certificate for
@return {Certificate~definition=} The matched certificate
|
[
"Matches",
"the",
"given",
"url",
"against",
"the",
"member",
"certificates",
"allowed",
"matches",
"and",
"returns",
"the",
"certificate",
"that",
"can",
"be",
"used",
"for",
"the",
"url",
"."
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/collection/certificate-list.js#L47-L57
|
|
15,090
|
postmanlabs/postman-collection
|
lib/collection/certificate-list.js
|
function (obj) {
return Boolean(obj) && ((obj instanceof CertificateList) ||
_.inSuperChain(obj.constructor, '_postman_propertyName', CertificateList._postman_propertyName));
}
|
javascript
|
function (obj) {
return Boolean(obj) && ((obj instanceof CertificateList) ||
_.inSuperChain(obj.constructor, '_postman_propertyName', CertificateList._postman_propertyName));
}
|
[
"function",
"(",
"obj",
")",
"{",
"return",
"Boolean",
"(",
"obj",
")",
"&&",
"(",
"(",
"obj",
"instanceof",
"CertificateList",
")",
"||",
"_",
".",
"inSuperChain",
"(",
"obj",
".",
"constructor",
",",
"'_postman_propertyName'",
",",
"CertificateList",
".",
"_postman_propertyName",
")",
")",
";",
"}"
] |
Checks if the given object is a CertificateList
@param {*} obj
@returns {Boolean}
|
[
"Checks",
"if",
"the",
"given",
"object",
"is",
"a",
"CertificateList"
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/collection/certificate-list.js#L75-L78
|
|
15,091
|
postmanlabs/postman-collection
|
lib/collection/mutation-tracker.js
|
function (mutation) {
// bail out for empty or unsupported mutations
if (!(mutation && isPrimitiveMutation(mutation))) {
return;
}
// if autoCompact is set, we need to compact while adding
if (this.autoCompact) {
this.addAndCompact(mutation);
return;
}
// otherwise just push to the stream of mutations
this.stream.push(mutation);
}
|
javascript
|
function (mutation) {
// bail out for empty or unsupported mutations
if (!(mutation && isPrimitiveMutation(mutation))) {
return;
}
// if autoCompact is set, we need to compact while adding
if (this.autoCompact) {
this.addAndCompact(mutation);
return;
}
// otherwise just push to the stream of mutations
this.stream.push(mutation);
}
|
[
"function",
"(",
"mutation",
")",
"{",
"// bail out for empty or unsupported mutations",
"if",
"(",
"!",
"(",
"mutation",
"&&",
"isPrimitiveMutation",
"(",
"mutation",
")",
")",
")",
"{",
"return",
";",
"}",
"// if autoCompact is set, we need to compact while adding",
"if",
"(",
"this",
".",
"autoCompact",
")",
"{",
"this",
".",
"addAndCompact",
"(",
"mutation",
")",
";",
"return",
";",
"}",
"// otherwise just push to the stream of mutations",
"this",
".",
"stream",
".",
"push",
"(",
"mutation",
")",
";",
"}"
] |
Records a new mutation.
@private
@param {MutationTracker~mutation} mutation
|
[
"Records",
"a",
"new",
"mutation",
"."
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/collection/mutation-tracker.js#L112-L126
|
|
15,092
|
postmanlabs/postman-collection
|
lib/collection/mutation-tracker.js
|
function (mutation) {
// for `set` and `unset` mutations the key to compact with is the `keyPath`
var key = mutation[0];
// convert `keyPath` to a string
key = Array.isArray(key) ? key.join('.') : key;
this.compacted[key] = mutation;
}
|
javascript
|
function (mutation) {
// for `set` and `unset` mutations the key to compact with is the `keyPath`
var key = mutation[0];
// convert `keyPath` to a string
key = Array.isArray(key) ? key.join('.') : key;
this.compacted[key] = mutation;
}
|
[
"function",
"(",
"mutation",
")",
"{",
"// for `set` and `unset` mutations the key to compact with is the `keyPath`",
"var",
"key",
"=",
"mutation",
"[",
"0",
"]",
";",
"// convert `keyPath` to a string",
"key",
"=",
"Array",
".",
"isArray",
"(",
"key",
")",
"?",
"key",
".",
"join",
"(",
"'.'",
")",
":",
"key",
";",
"this",
".",
"compacted",
"[",
"key",
"]",
"=",
"mutation",
";",
"}"
] |
Records a mutation compacting existing mutations for the same key path.
@private
@param {MutationTracker~mutation} mutation
|
[
"Records",
"a",
"mutation",
"compacting",
"existing",
"mutations",
"for",
"the",
"same",
"key",
"path",
"."
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/collection/mutation-tracker.js#L134-L142
|
|
15,093
|
postmanlabs/postman-collection
|
lib/collection/mutation-tracker.js
|
function (instruction) {
// @todo: use argument spread here once we drop support for node v4
var payload = Array.prototype.slice.call(arguments, 1);
// invalid call
if (!(instruction && payload)) {
return;
}
// unknown instruction
if (!(instruction === PRIMITIVE_MUTATIONS.SET || instruction === PRIMITIVE_MUTATIONS.UNSET)) {
return;
}
// for primitive mutations the arguments form the mutation object
// if there is more complex mutation, we have to use a processor to create a mutation for the instruction
this.addMutation(payload);
}
|
javascript
|
function (instruction) {
// @todo: use argument spread here once we drop support for node v4
var payload = Array.prototype.slice.call(arguments, 1);
// invalid call
if (!(instruction && payload)) {
return;
}
// unknown instruction
if (!(instruction === PRIMITIVE_MUTATIONS.SET || instruction === PRIMITIVE_MUTATIONS.UNSET)) {
return;
}
// for primitive mutations the arguments form the mutation object
// if there is more complex mutation, we have to use a processor to create a mutation for the instruction
this.addMutation(payload);
}
|
[
"function",
"(",
"instruction",
")",
"{",
"// @todo: use argument spread here once we drop support for node v4",
"var",
"payload",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"// invalid call",
"if",
"(",
"!",
"(",
"instruction",
"&&",
"payload",
")",
")",
"{",
"return",
";",
"}",
"// unknown instruction",
"if",
"(",
"!",
"(",
"instruction",
"===",
"PRIMITIVE_MUTATIONS",
".",
"SET",
"||",
"instruction",
"===",
"PRIMITIVE_MUTATIONS",
".",
"UNSET",
")",
")",
"{",
"return",
";",
"}",
"// for primitive mutations the arguments form the mutation object",
"// if there is more complex mutation, we have to use a processor to create a mutation for the instruction",
"this",
".",
"addMutation",
"(",
"payload",
")",
";",
"}"
] |
Track a mutation.
@param {String} instruction the type of mutation
|
[
"Track",
"a",
"mutation",
"."
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/collection/mutation-tracker.js#L149-L166
|
|
15,094
|
postmanlabs/postman-collection
|
lib/collection/mutation-tracker.js
|
function (target) {
if (!(target && target.applyMutation)) {
return;
}
var applyIndividualMutation = function applyIndividualMutation (mutation) {
applyMutation(target, mutation);
};
// mutations move from `stream` to `compacted`, so we apply the compacted mutations first
// to ensure FIFO of mutations
// apply the compacted mutations first
_.forEach(this.compacted, applyIndividualMutation);
// apply the mutations in the stream
_.forEach(this.stream, applyIndividualMutation);
}
|
javascript
|
function (target) {
if (!(target && target.applyMutation)) {
return;
}
var applyIndividualMutation = function applyIndividualMutation (mutation) {
applyMutation(target, mutation);
};
// mutations move from `stream` to `compacted`, so we apply the compacted mutations first
// to ensure FIFO of mutations
// apply the compacted mutations first
_.forEach(this.compacted, applyIndividualMutation);
// apply the mutations in the stream
_.forEach(this.stream, applyIndividualMutation);
}
|
[
"function",
"(",
"target",
")",
"{",
"if",
"(",
"!",
"(",
"target",
"&&",
"target",
".",
"applyMutation",
")",
")",
"{",
"return",
";",
"}",
"var",
"applyIndividualMutation",
"=",
"function",
"applyIndividualMutation",
"(",
"mutation",
")",
"{",
"applyMutation",
"(",
"target",
",",
"mutation",
")",
";",
"}",
";",
"// mutations move from `stream` to `compacted`, so we apply the compacted mutations first",
"// to ensure FIFO of mutations",
"// apply the compacted mutations first",
"_",
".",
"forEach",
"(",
"this",
".",
"compacted",
",",
"applyIndividualMutation",
")",
";",
"// apply the mutations in the stream",
"_",
".",
"forEach",
"(",
"this",
".",
"stream",
",",
"applyIndividualMutation",
")",
";",
"}"
] |
Applies all the recorded mutations on a target object.
@param {*} target Target to apply mutations. Must implement `applyMutation`.
|
[
"Applies",
"all",
"the",
"recorded",
"mutations",
"on",
"a",
"target",
"object",
"."
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/collection/mutation-tracker.js#L200-L217
|
|
15,095
|
postmanlabs/postman-collection
|
lib/url-pattern/url-match-pattern.js
|
function (options) {
_.has(options, 'pattern') && (_.isString(options.pattern) && !_.isEmpty(options.pattern)) &&
(this.pattern = options.pattern);
// create a match pattern and store it on cache
this._matchPatternObject = this.createMatchPattern();
}
|
javascript
|
function (options) {
_.has(options, 'pattern') && (_.isString(options.pattern) && !_.isEmpty(options.pattern)) &&
(this.pattern = options.pattern);
// create a match pattern and store it on cache
this._matchPatternObject = this.createMatchPattern();
}
|
[
"function",
"(",
"options",
")",
"{",
"_",
".",
"has",
"(",
"options",
",",
"'pattern'",
")",
"&&",
"(",
"_",
".",
"isString",
"(",
"options",
".",
"pattern",
")",
"&&",
"!",
"_",
".",
"isEmpty",
"(",
"options",
".",
"pattern",
")",
")",
"&&",
"(",
"this",
".",
"pattern",
"=",
"options",
".",
"pattern",
")",
";",
"// create a match pattern and store it on cache",
"this",
".",
"_matchPatternObject",
"=",
"this",
".",
"createMatchPattern",
"(",
")",
";",
"}"
] |
Assigns the given properties to the UrlMatchPattern.
@param {{ pattern: (string) }} options
|
[
"Assigns",
"the",
"given",
"properties",
"to",
"the",
"UrlMatchPattern",
"."
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/url-pattern/url-match-pattern.js#L75-L81
|
|
15,096
|
postmanlabs/postman-collection
|
lib/url-pattern/url-match-pattern.js
|
function () {
var matchPattern = this.pattern,
// Check the match pattern of sanity and split it into protocol, host and path
match = matchPattern.match(regexes.patternSplit);
if (!match) {
// This ensures it is a invalid match pattern
return;
}
return {
protocols: _.uniq(match[1].split(PROTOCOL_DELIMITER)),
host: match[5],
port: match[6] && match[6].substr(1), // remove leading `:`
path: this.globPatternToRegexp(match[7])
};
}
|
javascript
|
function () {
var matchPattern = this.pattern,
// Check the match pattern of sanity and split it into protocol, host and path
match = matchPattern.match(regexes.patternSplit);
if (!match) {
// This ensures it is a invalid match pattern
return;
}
return {
protocols: _.uniq(match[1].split(PROTOCOL_DELIMITER)),
host: match[5],
port: match[6] && match[6].substr(1), // remove leading `:`
path: this.globPatternToRegexp(match[7])
};
}
|
[
"function",
"(",
")",
"{",
"var",
"matchPattern",
"=",
"this",
".",
"pattern",
",",
"// Check the match pattern of sanity and split it into protocol, host and path",
"match",
"=",
"matchPattern",
".",
"match",
"(",
"regexes",
".",
"patternSplit",
")",
";",
"if",
"(",
"!",
"match",
")",
"{",
"// This ensures it is a invalid match pattern",
"return",
";",
"}",
"return",
"{",
"protocols",
":",
"_",
".",
"uniq",
"(",
"match",
"[",
"1",
"]",
".",
"split",
"(",
"PROTOCOL_DELIMITER",
")",
")",
",",
"host",
":",
"match",
"[",
"5",
"]",
",",
"port",
":",
"match",
"[",
"6",
"]",
"&&",
"match",
"[",
"6",
"]",
".",
"substr",
"(",
"1",
")",
",",
"// remove leading `:`",
"path",
":",
"this",
".",
"globPatternToRegexp",
"(",
"match",
"[",
"7",
"]",
")",
"}",
";",
"}"
] |
Used to generate the match regex object from the match string we have.
@private
@returns {*} Match regex object
|
[
"Used",
"to",
"generate",
"the",
"match",
"regex",
"object",
"from",
"the",
"match",
"string",
"we",
"have",
"."
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/url-pattern/url-match-pattern.js#L89-L105
|
|
15,097
|
postmanlabs/postman-collection
|
lib/url-pattern/url-match-pattern.js
|
function (pattern) {
// Escape everything except ? and *.
pattern = pattern.replace(regexes.escapeMatcher, regexes.escapeMatchReplacement);
pattern = pattern.replace(regexes.questionmarkMatcher, regexes.questionmarkReplacment);
pattern = pattern.replace(regexes.starMatcher, regexes.starReplacement);
return new RegExp(PREFIX_DELIMITER + pattern + POSTFIX_DELIMITER);
}
|
javascript
|
function (pattern) {
// Escape everything except ? and *.
pattern = pattern.replace(regexes.escapeMatcher, regexes.escapeMatchReplacement);
pattern = pattern.replace(regexes.questionmarkMatcher, regexes.questionmarkReplacment);
pattern = pattern.replace(regexes.starMatcher, regexes.starReplacement);
return new RegExp(PREFIX_DELIMITER + pattern + POSTFIX_DELIMITER);
}
|
[
"function",
"(",
"pattern",
")",
"{",
"// Escape everything except ? and *.",
"pattern",
"=",
"pattern",
".",
"replace",
"(",
"regexes",
".",
"escapeMatcher",
",",
"regexes",
".",
"escapeMatchReplacement",
")",
";",
"pattern",
"=",
"pattern",
".",
"replace",
"(",
"regexes",
".",
"questionmarkMatcher",
",",
"regexes",
".",
"questionmarkReplacment",
")",
";",
"pattern",
"=",
"pattern",
".",
"replace",
"(",
"regexes",
".",
"starMatcher",
",",
"regexes",
".",
"starReplacement",
")",
";",
"return",
"new",
"RegExp",
"(",
"PREFIX_DELIMITER",
"+",
"pattern",
"+",
"POSTFIX_DELIMITER",
")",
";",
"}"
] |
Converts a given glob pattern into a regular expression.
@private
@param {String} pattern Glob pattern string
@return {RegExp=}
|
[
"Converts",
"a",
"given",
"glob",
"pattern",
"into",
"a",
"regular",
"expression",
"."
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/url-pattern/url-match-pattern.js#L114-L120
|
|
15,098
|
postmanlabs/postman-collection
|
lib/url-pattern/url-match-pattern.js
|
function (protocol) {
var matchRegexObject = this._matchPatternObject;
return _.includes(ALLOWED_PROTOCOLS, protocol) &&
(_.includes(matchRegexObject.protocols, MATCH_ALL) || _.includes(matchRegexObject.protocols, protocol));
}
|
javascript
|
function (protocol) {
var matchRegexObject = this._matchPatternObject;
return _.includes(ALLOWED_PROTOCOLS, protocol) &&
(_.includes(matchRegexObject.protocols, MATCH_ALL) || _.includes(matchRegexObject.protocols, protocol));
}
|
[
"function",
"(",
"protocol",
")",
"{",
"var",
"matchRegexObject",
"=",
"this",
".",
"_matchPatternObject",
";",
"return",
"_",
".",
"includes",
"(",
"ALLOWED_PROTOCOLS",
",",
"protocol",
")",
"&&",
"(",
"_",
".",
"includes",
"(",
"matchRegexObject",
".",
"protocols",
",",
"MATCH_ALL",
")",
"||",
"_",
".",
"includes",
"(",
"matchRegexObject",
".",
"protocols",
",",
"protocol",
")",
")",
";",
"}"
] |
Tests if the given protocol string, is allowed by the pattern.
@param {String=} protocol The protocol to be checked if the pattern allows.
@return {Boolean=}
|
[
"Tests",
"if",
"the",
"given",
"protocol",
"string",
"is",
"allowed",
"by",
"the",
"pattern",
"."
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/url-pattern/url-match-pattern.js#L128-L133
|
|
15,099
|
postmanlabs/postman-collection
|
lib/url-pattern/url-match-pattern.js
|
function (host) {
/*
* For Host match, we are considering the port with the host, hence we are using getRemote() instead of getHost()
* We need to address three cases for the host urlStr
* 1. * It matches all the host + protocol, hence we are not having any parsing logic for it.
* 2. *.foo.bar.com Here the prefix could be anything but it should end with foo.bar.com
* 3. foo.bar.com This is the absolute matching needs to done.
*/
var matchRegexObject = this._matchPatternObject;
return (
this.matchAnyHost(matchRegexObject) ||
this.matchAbsoluteHostPattern(matchRegexObject, host) ||
this.matchSuffixHostPattern(matchRegexObject, host)
);
}
|
javascript
|
function (host) {
/*
* For Host match, we are considering the port with the host, hence we are using getRemote() instead of getHost()
* We need to address three cases for the host urlStr
* 1. * It matches all the host + protocol, hence we are not having any parsing logic for it.
* 2. *.foo.bar.com Here the prefix could be anything but it should end with foo.bar.com
* 3. foo.bar.com This is the absolute matching needs to done.
*/
var matchRegexObject = this._matchPatternObject;
return (
this.matchAnyHost(matchRegexObject) ||
this.matchAbsoluteHostPattern(matchRegexObject, host) ||
this.matchSuffixHostPattern(matchRegexObject, host)
);
}
|
[
"function",
"(",
"host",
")",
"{",
"/*\n * For Host match, we are considering the port with the host, hence we are using getRemote() instead of getHost()\n * We need to address three cases for the host urlStr\n * 1. * It matches all the host + protocol, hence we are not having any parsing logic for it.\n * 2. *.foo.bar.com Here the prefix could be anything but it should end with foo.bar.com\n * 3. foo.bar.com This is the absolute matching needs to done.\n */",
"var",
"matchRegexObject",
"=",
"this",
".",
"_matchPatternObject",
";",
"return",
"(",
"this",
".",
"matchAnyHost",
"(",
"matchRegexObject",
")",
"||",
"this",
".",
"matchAbsoluteHostPattern",
"(",
"matchRegexObject",
",",
"host",
")",
"||",
"this",
".",
"matchSuffixHostPattern",
"(",
"matchRegexObject",
",",
"host",
")",
")",
";",
"}"
] |
Tests if the given host string, is allowed by the pattern.
@param {String=} host The host to be checked if the pattern allows.
@return {Boolean=}
|
[
"Tests",
"if",
"the",
"given",
"host",
"string",
"is",
"allowed",
"by",
"the",
"pattern",
"."
] |
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
|
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/url-pattern/url-match-pattern.js#L150-L164
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.