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
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
2,700 | firebase/firebase-js-sdk | scripts/docgen/generate-docs.js | fixAllLinks | function fixAllLinks(htmlFiles) {
const writePromises = [];
htmlFiles.forEach(file => {
// Update links in each html file to match flattened file structure.
writePromises.push(fixLinks(`${docPath}/${file}.html`));
});
return Promise.all(writePromises);
} | javascript | function fixAllLinks(htmlFiles) {
const writePromises = [];
htmlFiles.forEach(file => {
// Update links in each html file to match flattened file structure.
writePromises.push(fixLinks(`${docPath}/${file}.html`));
});
return Promise.all(writePromises);
} | [
"function",
"fixAllLinks",
"(",
"htmlFiles",
")",
"{",
"const",
"writePromises",
"=",
"[",
"]",
";",
"htmlFiles",
".",
"forEach",
"(",
"file",
"=>",
"{",
"// Update links in each html file to match flattened file structure.",
"writePromises",
".",
"push",
"(",
"fixLinks",
"(",
"`",
"${",
"docPath",
"}",
"${",
"file",
"}",
"`",
")",
")",
";",
"}",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"writePromises",
")",
";",
"}"
] | Fix all links in generated files to other generated files to point to top
level of generated docs dir.
@param {Array} htmlFiles List of html files found in generated dir. | [
"Fix",
"all",
"links",
"in",
"generated",
"files",
"to",
"other",
"generated",
"files",
"to",
"point",
"to",
"top",
"level",
"of",
"generated",
"docs",
"dir",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/scripts/docgen/generate-docs.js#L237-L244 |
2,701 | firebase/firebase-js-sdk | scripts/docgen/generate-docs.js | generateNodeSource | async function generateNodeSource() {
const sourceText = await fs.readFile(sourceFile, 'utf8');
// Parse index.d.ts. A dummy filename is required but it doesn't create a
// file.
let typescriptSourceFile = typescript.createSourceFile(
'temp.d.ts',
sourceText,
typescript.ScriptTarget.ES2015,
/*setParentNodes */ false
);
/**
* Typescript transformer function. Removes nodes tagged with @webonly.
*/
const removeWebOnlyNodes = context => rootNode => {
function visit(node) {
if (
node.jsDoc &&
node.jsDoc.some(
item =>
item.tags &&
item.tags.some(tag => tag.tagName.escapedText === 'webonly')
)
) {
return null;
}
return typescript.visitEachChild(node, visit, context);
}
return typescript.visitNode(rootNode, visit);
};
// Use above transformer on source AST to remove nodes tagged with @webonly.
const result = typescript.transform(typescriptSourceFile, [
removeWebOnlyNodes
]);
// Convert transformed AST to text and write to file.
const printer = typescript.createPrinter();
return fs.writeFile(
tempNodeSourcePath,
printer.printFile(result.transformed[0])
);
} | javascript | async function generateNodeSource() {
const sourceText = await fs.readFile(sourceFile, 'utf8');
// Parse index.d.ts. A dummy filename is required but it doesn't create a
// file.
let typescriptSourceFile = typescript.createSourceFile(
'temp.d.ts',
sourceText,
typescript.ScriptTarget.ES2015,
/*setParentNodes */ false
);
/**
* Typescript transformer function. Removes nodes tagged with @webonly.
*/
const removeWebOnlyNodes = context => rootNode => {
function visit(node) {
if (
node.jsDoc &&
node.jsDoc.some(
item =>
item.tags &&
item.tags.some(tag => tag.tagName.escapedText === 'webonly')
)
) {
return null;
}
return typescript.visitEachChild(node, visit, context);
}
return typescript.visitNode(rootNode, visit);
};
// Use above transformer on source AST to remove nodes tagged with @webonly.
const result = typescript.transform(typescriptSourceFile, [
removeWebOnlyNodes
]);
// Convert transformed AST to text and write to file.
const printer = typescript.createPrinter();
return fs.writeFile(
tempNodeSourcePath,
printer.printFile(result.transformed[0])
);
} | [
"async",
"function",
"generateNodeSource",
"(",
")",
"{",
"const",
"sourceText",
"=",
"await",
"fs",
".",
"readFile",
"(",
"sourceFile",
",",
"'utf8'",
")",
";",
"// Parse index.d.ts. A dummy filename is required but it doesn't create a",
"// file.",
"let",
"typescriptSourceFile",
"=",
"typescript",
".",
"createSourceFile",
"(",
"'temp.d.ts'",
",",
"sourceText",
",",
"typescript",
".",
"ScriptTarget",
".",
"ES2015",
",",
"/*setParentNodes */",
"false",
")",
";",
"/**\n * Typescript transformer function. Removes nodes tagged with @webonly.\n */",
"const",
"removeWebOnlyNodes",
"=",
"context",
"=>",
"rootNode",
"=>",
"{",
"function",
"visit",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"jsDoc",
"&&",
"node",
".",
"jsDoc",
".",
"some",
"(",
"item",
"=>",
"item",
".",
"tags",
"&&",
"item",
".",
"tags",
".",
"some",
"(",
"tag",
"=>",
"tag",
".",
"tagName",
".",
"escapedText",
"===",
"'webonly'",
")",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"typescript",
".",
"visitEachChild",
"(",
"node",
",",
"visit",
",",
"context",
")",
";",
"}",
"return",
"typescript",
".",
"visitNode",
"(",
"rootNode",
",",
"visit",
")",
";",
"}",
";",
"// Use above transformer on source AST to remove nodes tagged with @webonly.",
"const",
"result",
"=",
"typescript",
".",
"transform",
"(",
"typescriptSourceFile",
",",
"[",
"removeWebOnlyNodes",
"]",
")",
";",
"// Convert transformed AST to text and write to file.",
"const",
"printer",
"=",
"typescript",
".",
"createPrinter",
"(",
")",
";",
"return",
"fs",
".",
"writeFile",
"(",
"tempNodeSourcePath",
",",
"printer",
".",
"printFile",
"(",
"result",
".",
"transformed",
"[",
"0",
"]",
")",
")",
";",
"}"
] | Generate an temporary abridged version of index.d.ts used to create
Node docs. | [
"Generate",
"an",
"temporary",
"abridged",
"version",
"of",
"index",
".",
"d",
".",
"ts",
"used",
"to",
"create",
"Node",
"docs",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/scripts/docgen/generate-docs.js#L250-L293 |
2,702 | firebase/firebase-js-sdk | packages/auth/src/cordovahandler.js | function() {
// Remove current resume listener.
if (onResume) {
doc.removeEventListener('resume', onResume, false);
}
// Remove visibility change listener.
if (onVisibilityChange) {
doc.removeEventListener('visibilitychange', onVisibilityChange, false);
}
// Cancel onClose promise if not already cancelled.
if (onClose) {
onClose.cancel();
}
// Remove Auth event callback.
if (authEventCallback) {
self.removeAuthEventListener(authEventCallback);
}
// Clear any pending redirect now that it is completed.
self.pendingRedirect_ = null;
} | javascript | function() {
// Remove current resume listener.
if (onResume) {
doc.removeEventListener('resume', onResume, false);
}
// Remove visibility change listener.
if (onVisibilityChange) {
doc.removeEventListener('visibilitychange', onVisibilityChange, false);
}
// Cancel onClose promise if not already cancelled.
if (onClose) {
onClose.cancel();
}
// Remove Auth event callback.
if (authEventCallback) {
self.removeAuthEventListener(authEventCallback);
}
// Clear any pending redirect now that it is completed.
self.pendingRedirect_ = null;
} | [
"function",
"(",
")",
"{",
"// Remove current resume listener.",
"if",
"(",
"onResume",
")",
"{",
"doc",
".",
"removeEventListener",
"(",
"'resume'",
",",
"onResume",
",",
"false",
")",
";",
"}",
"// Remove visibility change listener.",
"if",
"(",
"onVisibilityChange",
")",
"{",
"doc",
".",
"removeEventListener",
"(",
"'visibilitychange'",
",",
"onVisibilityChange",
",",
"false",
")",
";",
"}",
"// Cancel onClose promise if not already cancelled.",
"if",
"(",
"onClose",
")",
"{",
"onClose",
".",
"cancel",
"(",
")",
";",
"}",
"// Remove Auth event callback.",
"if",
"(",
"authEventCallback",
")",
"{",
"self",
".",
"removeAuthEventListener",
"(",
"authEventCallback",
")",
";",
"}",
"// Clear any pending redirect now that it is completed.",
"self",
".",
"pendingRedirect_",
"=",
"null",
";",
"}"
] | When the processRedirect promise completes, clean up any remaining temporary listeners and timers. | [
"When",
"the",
"processRedirect",
"promise",
"completes",
"clean",
"up",
"any",
"remaining",
"temporary",
"listeners",
"and",
"timers",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/src/cordovahandler.js#L359-L378 |
|
2,703 | firebase/firebase-js-sdk | packages/auth/src/cordovahandler.js | function(eventData) {
initialResolve = true;
// Cancel no event timer.
if (noEventTimer) {
noEventTimer.cancel();
}
// Incoming link detected.
// Check for any stored partial event.
self.getPartialStoredEvent_().then(function(event) {
// Initialize to an unknown event.
var authEvent = noEvent;
// Confirm OAuth response included.
if (event && eventData && eventData['url']) {
// Construct complete event. Default to unknown event if none found.
authEvent = self.extractAuthEventFromUrl_(event, eventData['url']) ||
noEvent;
}
// Dispatch Auth event.
self.dispatchEvent_(authEvent);
});
} | javascript | function(eventData) {
initialResolve = true;
// Cancel no event timer.
if (noEventTimer) {
noEventTimer.cancel();
}
// Incoming link detected.
// Check for any stored partial event.
self.getPartialStoredEvent_().then(function(event) {
// Initialize to an unknown event.
var authEvent = noEvent;
// Confirm OAuth response included.
if (event && eventData && eventData['url']) {
// Construct complete event. Default to unknown event if none found.
authEvent = self.extractAuthEventFromUrl_(event, eventData['url']) ||
noEvent;
}
// Dispatch Auth event.
self.dispatchEvent_(authEvent);
});
} | [
"function",
"(",
"eventData",
")",
"{",
"initialResolve",
"=",
"true",
";",
"// Cancel no event timer.",
"if",
"(",
"noEventTimer",
")",
"{",
"noEventTimer",
".",
"cancel",
"(",
")",
";",
"}",
"// Incoming link detected.",
"// Check for any stored partial event.",
"self",
".",
"getPartialStoredEvent_",
"(",
")",
".",
"then",
"(",
"function",
"(",
"event",
")",
"{",
"// Initialize to an unknown event.",
"var",
"authEvent",
"=",
"noEvent",
";",
"// Confirm OAuth response included.",
"if",
"(",
"event",
"&&",
"eventData",
"&&",
"eventData",
"[",
"'url'",
"]",
")",
"{",
"// Construct complete event. Default to unknown event if none found.",
"authEvent",
"=",
"self",
".",
"extractAuthEventFromUrl_",
"(",
"event",
",",
"eventData",
"[",
"'url'",
"]",
")",
"||",
"noEvent",
";",
"}",
"// Dispatch Auth event.",
"self",
".",
"dispatchEvent_",
"(",
"authEvent",
")",
";",
"}",
")",
";",
"}"
] | No event name needed, subscribe to all incoming universal links. | [
"No",
"event",
"name",
"needed",
"subscribe",
"to",
"all",
"incoming",
"universal",
"links",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/src/cordovahandler.js#L753-L773 |
|
2,704 | firebase/firebase-js-sdk | packages/auth/src/authuser.js | function() {
// Get time until expiration minus the refresh offset.
var waitInterval =
self.stsTokenManager_.getExpirationTime() - goog.now() -
fireauth.TokenRefreshTime.OFFSET_DURATION;
// Set to zero if wait interval is negative.
return waitInterval > 0 ? waitInterval : 0;
} | javascript | function() {
// Get time until expiration minus the refresh offset.
var waitInterval =
self.stsTokenManager_.getExpirationTime() - goog.now() -
fireauth.TokenRefreshTime.OFFSET_DURATION;
// Set to zero if wait interval is negative.
return waitInterval > 0 ? waitInterval : 0;
} | [
"function",
"(",
")",
"{",
"// Get time until expiration minus the refresh offset.",
"var",
"waitInterval",
"=",
"self",
".",
"stsTokenManager_",
".",
"getExpirationTime",
"(",
")",
"-",
"goog",
".",
"now",
"(",
")",
"-",
"fireauth",
".",
"TokenRefreshTime",
".",
"OFFSET_DURATION",
";",
"// Set to zero if wait interval is negative.",
"return",
"waitInterval",
">",
"0",
"?",
"waitInterval",
":",
"0",
";",
"}"
] | Return next time to run with offset applied. | [
"Return",
"next",
"time",
"to",
"run",
"with",
"offset",
"applied",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/src/authuser.js#L474-L481 |
|
2,705 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | logAtLevel_ | function logAtLevel_(message, level) {
if (message != null) {
var messageDiv = $('<div></div>');
messageDiv.addClass(level);
if (typeof message === 'object') {
messageDiv.text(JSON.stringify(message, null, ' '));
} else {
messageDiv.text(message);
}
$('.logs').append(messageDiv);
}
console[level](message);
} | javascript | function logAtLevel_(message, level) {
if (message != null) {
var messageDiv = $('<div></div>');
messageDiv.addClass(level);
if (typeof message === 'object') {
messageDiv.text(JSON.stringify(message, null, ' '));
} else {
messageDiv.text(message);
}
$('.logs').append(messageDiv);
}
console[level](message);
} | [
"function",
"logAtLevel_",
"(",
"message",
",",
"level",
")",
"{",
"if",
"(",
"message",
"!=",
"null",
")",
"{",
"var",
"messageDiv",
"=",
"$",
"(",
"'<div></div>'",
")",
";",
"messageDiv",
".",
"addClass",
"(",
"level",
")",
";",
"if",
"(",
"typeof",
"message",
"===",
"'object'",
")",
"{",
"messageDiv",
".",
"text",
"(",
"JSON",
".",
"stringify",
"(",
"message",
",",
"null",
",",
"' '",
")",
")",
";",
"}",
"else",
"{",
"messageDiv",
".",
"text",
"(",
"message",
")",
";",
"}",
"$",
"(",
"'.logs'",
")",
".",
"append",
"(",
"messageDiv",
")",
";",
"}",
"console",
"[",
"level",
"]",
"(",
"message",
")",
";",
"}"
] | Logs the message in the console and on the log window in the app
using the level given.
@param {?Object} message Object or message to log.
@param {string} level The level of log (log, error, debug).
@private | [
"Logs",
"the",
"message",
"in",
"the",
"console",
"and",
"on",
"the",
"log",
"window",
"in",
"the",
"app",
"using",
"the",
"level",
"given",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L56-L68 |
2,706 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | alertMessage_ | function alertMessage_(message, cssClass) {
var alertBox = $('<div></div>')
.addClass(cssClass)
.css('display', 'none')
.text(message);
$('#alert-messages').prepend(alertBox);
alertBox.fadeIn({
complete: function() {
setTimeout(function() {
alertBox.slideUp();
}, 3000);
}
});
} | javascript | function alertMessage_(message, cssClass) {
var alertBox = $('<div></div>')
.addClass(cssClass)
.css('display', 'none')
.text(message);
$('#alert-messages').prepend(alertBox);
alertBox.fadeIn({
complete: function() {
setTimeout(function() {
alertBox.slideUp();
}, 3000);
}
});
} | [
"function",
"alertMessage_",
"(",
"message",
",",
"cssClass",
")",
"{",
"var",
"alertBox",
"=",
"$",
"(",
"'<div></div>'",
")",
".",
"addClass",
"(",
"cssClass",
")",
".",
"css",
"(",
"'display'",
",",
"'none'",
")",
".",
"text",
"(",
"message",
")",
";",
"$",
"(",
"'#alert-messages'",
")",
".",
"prepend",
"(",
"alertBox",
")",
";",
"alertBox",
".",
"fadeIn",
"(",
"{",
"complete",
":",
"function",
"(",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"alertBox",
".",
"slideUp",
"(",
")",
";",
"}",
",",
"3000",
")",
";",
"}",
"}",
")",
";",
"}"
] | Displays for a few seconds a box with a specific message and then fades
it out.
@param {string} message Small message to display.
@param {string} cssClass The class(s) to give the alert box.
@private | [
"Displays",
"for",
"a",
"few",
"seconds",
"a",
"box",
"with",
"a",
"specific",
"message",
"and",
"then",
"fades",
"it",
"out",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L94-L107 |
2,707 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | refreshUserData | function refreshUserData() {
if (activeUser()) {
var user = activeUser();
$('.profile').show();
$('body').addClass('user-info-displayed');
$('div.profile-email,span.profile-email').text(user.email || 'No Email');
$('div.profile-phone,span.profile-phone')
.text(user.phoneNumber || 'No Phone');
$('div.profile-uid,span.profile-uid').text(user.uid);
$('div.profile-name,span.profile-name').text(user.displayName || 'No Name');
$('input.profile-name').val(user.displayName);
$('input.photo-url').val(user.photoURL);
if (user.photoURL != null) {
var photoURL = user.photoURL;
// Append size to the photo URL for Google hosted images to avoid requesting
// the image with its original resolution (using more bandwidth than needed)
// when it is going to be presented in smaller size.
if ((photoURL.indexOf('googleusercontent.com') != -1) ||
(photoURL.indexOf('ggpht.com') != -1)) {
photoURL = photoURL + '?sz=' + $('img.profile-image').height();
}
$('img.profile-image').attr('src', photoURL).show();
} else {
$('img.profile-image').hide();
}
$('.profile-email-verified').toggle(user.emailVerified);
$('.profile-email-not-verified').toggle(!user.emailVerified);
$('.profile-anonymous').toggle(user.isAnonymous);
// Display/Hide providers icons.
$('.profile-providers').empty();
if (user['providerData'] && user['providerData'].length) {
var providersCount = user['providerData'].length;
for (var i = 0; i < providersCount; i++) {
addProviderIcon(user['providerData'][i]['providerId']);
}
}
// Change color.
if (user == auth.currentUser) {
$('#user-info').removeClass('last-user');
$('#user-info').addClass('current-user');
} else {
$('#user-info').removeClass('current-user');
$('#user-info').addClass('last-user');
}
} else {
$('.profile').slideUp();
$('body').removeClass('user-info-displayed');
$('input.profile-data').val('');
}
} | javascript | function refreshUserData() {
if (activeUser()) {
var user = activeUser();
$('.profile').show();
$('body').addClass('user-info-displayed');
$('div.profile-email,span.profile-email').text(user.email || 'No Email');
$('div.profile-phone,span.profile-phone')
.text(user.phoneNumber || 'No Phone');
$('div.profile-uid,span.profile-uid').text(user.uid);
$('div.profile-name,span.profile-name').text(user.displayName || 'No Name');
$('input.profile-name').val(user.displayName);
$('input.photo-url').val(user.photoURL);
if (user.photoURL != null) {
var photoURL = user.photoURL;
// Append size to the photo URL for Google hosted images to avoid requesting
// the image with its original resolution (using more bandwidth than needed)
// when it is going to be presented in smaller size.
if ((photoURL.indexOf('googleusercontent.com') != -1) ||
(photoURL.indexOf('ggpht.com') != -1)) {
photoURL = photoURL + '?sz=' + $('img.profile-image').height();
}
$('img.profile-image').attr('src', photoURL).show();
} else {
$('img.profile-image').hide();
}
$('.profile-email-verified').toggle(user.emailVerified);
$('.profile-email-not-verified').toggle(!user.emailVerified);
$('.profile-anonymous').toggle(user.isAnonymous);
// Display/Hide providers icons.
$('.profile-providers').empty();
if (user['providerData'] && user['providerData'].length) {
var providersCount = user['providerData'].length;
for (var i = 0; i < providersCount; i++) {
addProviderIcon(user['providerData'][i]['providerId']);
}
}
// Change color.
if (user == auth.currentUser) {
$('#user-info').removeClass('last-user');
$('#user-info').addClass('current-user');
} else {
$('#user-info').removeClass('current-user');
$('#user-info').addClass('last-user');
}
} else {
$('.profile').slideUp();
$('body').removeClass('user-info-displayed');
$('input.profile-data').val('');
}
} | [
"function",
"refreshUserData",
"(",
")",
"{",
"if",
"(",
"activeUser",
"(",
")",
")",
"{",
"var",
"user",
"=",
"activeUser",
"(",
")",
";",
"$",
"(",
"'.profile'",
")",
".",
"show",
"(",
")",
";",
"$",
"(",
"'body'",
")",
".",
"addClass",
"(",
"'user-info-displayed'",
")",
";",
"$",
"(",
"'div.profile-email,span.profile-email'",
")",
".",
"text",
"(",
"user",
".",
"email",
"||",
"'No Email'",
")",
";",
"$",
"(",
"'div.profile-phone,span.profile-phone'",
")",
".",
"text",
"(",
"user",
".",
"phoneNumber",
"||",
"'No Phone'",
")",
";",
"$",
"(",
"'div.profile-uid,span.profile-uid'",
")",
".",
"text",
"(",
"user",
".",
"uid",
")",
";",
"$",
"(",
"'div.profile-name,span.profile-name'",
")",
".",
"text",
"(",
"user",
".",
"displayName",
"||",
"'No Name'",
")",
";",
"$",
"(",
"'input.profile-name'",
")",
".",
"val",
"(",
"user",
".",
"displayName",
")",
";",
"$",
"(",
"'input.photo-url'",
")",
".",
"val",
"(",
"user",
".",
"photoURL",
")",
";",
"if",
"(",
"user",
".",
"photoURL",
"!=",
"null",
")",
"{",
"var",
"photoURL",
"=",
"user",
".",
"photoURL",
";",
"// Append size to the photo URL for Google hosted images to avoid requesting",
"// the image with its original resolution (using more bandwidth than needed)",
"// when it is going to be presented in smaller size.",
"if",
"(",
"(",
"photoURL",
".",
"indexOf",
"(",
"'googleusercontent.com'",
")",
"!=",
"-",
"1",
")",
"||",
"(",
"photoURL",
".",
"indexOf",
"(",
"'ggpht.com'",
")",
"!=",
"-",
"1",
")",
")",
"{",
"photoURL",
"=",
"photoURL",
"+",
"'?sz='",
"+",
"$",
"(",
"'img.profile-image'",
")",
".",
"height",
"(",
")",
";",
"}",
"$",
"(",
"'img.profile-image'",
")",
".",
"attr",
"(",
"'src'",
",",
"photoURL",
")",
".",
"show",
"(",
")",
";",
"}",
"else",
"{",
"$",
"(",
"'img.profile-image'",
")",
".",
"hide",
"(",
")",
";",
"}",
"$",
"(",
"'.profile-email-verified'",
")",
".",
"toggle",
"(",
"user",
".",
"emailVerified",
")",
";",
"$",
"(",
"'.profile-email-not-verified'",
")",
".",
"toggle",
"(",
"!",
"user",
".",
"emailVerified",
")",
";",
"$",
"(",
"'.profile-anonymous'",
")",
".",
"toggle",
"(",
"user",
".",
"isAnonymous",
")",
";",
"// Display/Hide providers icons.",
"$",
"(",
"'.profile-providers'",
")",
".",
"empty",
"(",
")",
";",
"if",
"(",
"user",
"[",
"'providerData'",
"]",
"&&",
"user",
"[",
"'providerData'",
"]",
".",
"length",
")",
"{",
"var",
"providersCount",
"=",
"user",
"[",
"'providerData'",
"]",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"providersCount",
";",
"i",
"++",
")",
"{",
"addProviderIcon",
"(",
"user",
"[",
"'providerData'",
"]",
"[",
"i",
"]",
"[",
"'providerId'",
"]",
")",
";",
"}",
"}",
"// Change color.",
"if",
"(",
"user",
"==",
"auth",
".",
"currentUser",
")",
"{",
"$",
"(",
"'#user-info'",
")",
".",
"removeClass",
"(",
"'last-user'",
")",
";",
"$",
"(",
"'#user-info'",
")",
".",
"addClass",
"(",
"'current-user'",
")",
";",
"}",
"else",
"{",
"$",
"(",
"'#user-info'",
")",
".",
"removeClass",
"(",
"'current-user'",
")",
";",
"$",
"(",
"'#user-info'",
")",
".",
"addClass",
"(",
"'last-user'",
")",
";",
"}",
"}",
"else",
"{",
"$",
"(",
"'.profile'",
")",
".",
"slideUp",
"(",
")",
";",
"$",
"(",
"'body'",
")",
".",
"removeClass",
"(",
"'user-info-displayed'",
")",
";",
"$",
"(",
"'input.profile-data'",
")",
".",
"val",
"(",
"''",
")",
";",
"}",
"}"
] | Refreshes the current user data in the UI, displaying a user info box if
a user is signed in, or removing it. | [
"Refreshes",
"the",
"current",
"user",
"data",
"in",
"the",
"UI",
"displaying",
"a",
"user",
"info",
"box",
"if",
"a",
"user",
"is",
"signed",
"in",
"or",
"removing",
"it",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L146-L195 |
2,708 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | addProviderIcon | function addProviderIcon(providerId) {
var pElt = $('<i>').addClass('fa ' + providersIcons[providerId])
.attr('title', providerId)
.data({
'toggle': 'tooltip',
'placement': 'bottom'
});
$('.profile-providers').append(pElt);
pElt.tooltip();
} | javascript | function addProviderIcon(providerId) {
var pElt = $('<i>').addClass('fa ' + providersIcons[providerId])
.attr('title', providerId)
.data({
'toggle': 'tooltip',
'placement': 'bottom'
});
$('.profile-providers').append(pElt);
pElt.tooltip();
} | [
"function",
"addProviderIcon",
"(",
"providerId",
")",
"{",
"var",
"pElt",
"=",
"$",
"(",
"'<i>'",
")",
".",
"addClass",
"(",
"'fa '",
"+",
"providersIcons",
"[",
"providerId",
"]",
")",
".",
"attr",
"(",
"'title'",
",",
"providerId",
")",
".",
"data",
"(",
"{",
"'toggle'",
":",
"'tooltip'",
",",
"'placement'",
":",
"'bottom'",
"}",
")",
";",
"$",
"(",
"'.profile-providers'",
")",
".",
"append",
"(",
"pElt",
")",
";",
"pElt",
".",
"tooltip",
"(",
")",
";",
"}"
] | Add a provider icon to the profile info.
@param {string} providerId The providerId of the provider. | [
"Add",
"a",
"provider",
"icon",
"to",
"the",
"profile",
"info",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L219-L228 |
2,709 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onSetLanguageCode | function onSetLanguageCode() {
var languageCode = $('#language-code').val() || null;
try {
auth.languageCode = languageCode;
alertSuccess('Language code changed to "' + languageCode + '".');
} catch (error) {
alertError('Error: ' + error.code);
}
} | javascript | function onSetLanguageCode() {
var languageCode = $('#language-code').val() || null;
try {
auth.languageCode = languageCode;
alertSuccess('Language code changed to "' + languageCode + '".');
} catch (error) {
alertError('Error: ' + error.code);
}
} | [
"function",
"onSetLanguageCode",
"(",
")",
"{",
"var",
"languageCode",
"=",
"$",
"(",
"'#language-code'",
")",
".",
"val",
"(",
")",
"||",
"null",
";",
"try",
"{",
"auth",
".",
"languageCode",
"=",
"languageCode",
";",
"alertSuccess",
"(",
"'Language code changed to \"'",
"+",
"languageCode",
"+",
"'\".'",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"alertError",
"(",
"'Error: '",
"+",
"error",
".",
"code",
")",
";",
"}",
"}"
] | Saves the new language code provided in the language code input field. | [
"Saves",
"the",
"new",
"language",
"code",
"provided",
"in",
"the",
"language",
"code",
"input",
"field",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L265-L273 |
2,710 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onSetPersistence | function onSetPersistence() {
var type = $('#persistence-type').val();
try {
auth.setPersistence(type).then(function() {
log('Persistence state change to "' + type + '".');
alertSuccess('Persistence state change to "' + type + '".');
}, function(error) {
alertError('Error: ' + error.code);
});
} catch (error) {
alertError('Error: ' + error.code);
}
} | javascript | function onSetPersistence() {
var type = $('#persistence-type').val();
try {
auth.setPersistence(type).then(function() {
log('Persistence state change to "' + type + '".');
alertSuccess('Persistence state change to "' + type + '".');
}, function(error) {
alertError('Error: ' + error.code);
});
} catch (error) {
alertError('Error: ' + error.code);
}
} | [
"function",
"onSetPersistence",
"(",
")",
"{",
"var",
"type",
"=",
"$",
"(",
"'#persistence-type'",
")",
".",
"val",
"(",
")",
";",
"try",
"{",
"auth",
".",
"setPersistence",
"(",
"type",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"log",
"(",
"'Persistence state change to \"'",
"+",
"type",
"+",
"'\".'",
")",
";",
"alertSuccess",
"(",
"'Persistence state change to \"'",
"+",
"type",
"+",
"'\".'",
")",
";",
"}",
",",
"function",
"(",
"error",
")",
"{",
"alertError",
"(",
"'Error: '",
"+",
"error",
".",
"code",
")",
";",
"}",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"alertError",
"(",
"'Error: '",
"+",
"error",
".",
"code",
")",
";",
"}",
"}"
] | Changes the Auth state persistence to the specified one. | [
"Changes",
"the",
"Auth",
"state",
"persistence",
"to",
"the",
"specified",
"one",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L289-L301 |
2,711 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onSignUp | function onSignUp() {
var email = $('#signup-email').val();
var password = $('#signup-password').val();
auth.createUserWithEmailAndPassword(email, password)
.then(onAuthUserCredentialSuccess, onAuthError);
} | javascript | function onSignUp() {
var email = $('#signup-email').val();
var password = $('#signup-password').val();
auth.createUserWithEmailAndPassword(email, password)
.then(onAuthUserCredentialSuccess, onAuthError);
} | [
"function",
"onSignUp",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#signup-email'",
")",
".",
"val",
"(",
")",
";",
"var",
"password",
"=",
"$",
"(",
"'#signup-password'",
")",
".",
"val",
"(",
")",
";",
"auth",
".",
"createUserWithEmailAndPassword",
"(",
"email",
",",
"password",
")",
".",
"then",
"(",
"onAuthUserCredentialSuccess",
",",
"onAuthError",
")",
";",
"}"
] | Signs up a new user with an email and a password. | [
"Signs",
"up",
"a",
"new",
"user",
"with",
"an",
"email",
"and",
"a",
"password",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L307-L312 |
2,712 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onSignInWithEmailAndPassword | function onSignInWithEmailAndPassword() {
var email = $('#signin-email').val();
var password = $('#signin-password').val();
auth.signInWithEmailAndPassword(email, password)
.then(onAuthUserCredentialSuccess, onAuthError);
} | javascript | function onSignInWithEmailAndPassword() {
var email = $('#signin-email').val();
var password = $('#signin-password').val();
auth.signInWithEmailAndPassword(email, password)
.then(onAuthUserCredentialSuccess, onAuthError);
} | [
"function",
"onSignInWithEmailAndPassword",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#signin-email'",
")",
".",
"val",
"(",
")",
";",
"var",
"password",
"=",
"$",
"(",
"'#signin-password'",
")",
".",
"val",
"(",
")",
";",
"auth",
".",
"signInWithEmailAndPassword",
"(",
"email",
",",
"password",
")",
".",
"then",
"(",
"onAuthUserCredentialSuccess",
",",
"onAuthError",
")",
";",
"}"
] | Signs in a user with an email and a password. | [
"Signs",
"in",
"a",
"user",
"with",
"an",
"email",
"and",
"a",
"password",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L318-L323 |
2,713 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onSignInWithEmailLink | function onSignInWithEmailLink() {
var email = $('#sign-in-with-email-link-email').val();
var link = $('#sign-in-with-email-link-link').val() || undefined;
if (auth.isSignInWithEmailLink(link)) {
auth.signInWithEmailLink(email, link).then(onAuthSuccess, onAuthError);
} else {
alertError('Sign in link is invalid');
}
} | javascript | function onSignInWithEmailLink() {
var email = $('#sign-in-with-email-link-email').val();
var link = $('#sign-in-with-email-link-link').val() || undefined;
if (auth.isSignInWithEmailLink(link)) {
auth.signInWithEmailLink(email, link).then(onAuthSuccess, onAuthError);
} else {
alertError('Sign in link is invalid');
}
} | [
"function",
"onSignInWithEmailLink",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#sign-in-with-email-link-email'",
")",
".",
"val",
"(",
")",
";",
"var",
"link",
"=",
"$",
"(",
"'#sign-in-with-email-link-link'",
")",
".",
"val",
"(",
")",
"||",
"undefined",
";",
"if",
"(",
"auth",
".",
"isSignInWithEmailLink",
"(",
"link",
")",
")",
"{",
"auth",
".",
"signInWithEmailLink",
"(",
"email",
",",
"link",
")",
".",
"then",
"(",
"onAuthSuccess",
",",
"onAuthError",
")",
";",
"}",
"else",
"{",
"alertError",
"(",
"'Sign in link is invalid'",
")",
";",
"}",
"}"
] | Signs in a user with an email link. | [
"Signs",
"in",
"a",
"user",
"with",
"an",
"email",
"link",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L329-L337 |
2,714 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onLinkWithEmailLink | function onLinkWithEmailLink() {
var email = $('#link-with-email-link-email').val();
var link = $('#link-with-email-link-link').val() || undefined;
var credential = firebase.auth.EmailAuthProvider
.credentialWithLink(email, link);
activeUser().linkWithCredential(credential)
.then(onAuthUserCredentialSuccess, onAuthError);
} | javascript | function onLinkWithEmailLink() {
var email = $('#link-with-email-link-email').val();
var link = $('#link-with-email-link-link').val() || undefined;
var credential = firebase.auth.EmailAuthProvider
.credentialWithLink(email, link);
activeUser().linkWithCredential(credential)
.then(onAuthUserCredentialSuccess, onAuthError);
} | [
"function",
"onLinkWithEmailLink",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#link-with-email-link-email'",
")",
".",
"val",
"(",
")",
";",
"var",
"link",
"=",
"$",
"(",
"'#link-with-email-link-link'",
")",
".",
"val",
"(",
")",
"||",
"undefined",
";",
"var",
"credential",
"=",
"firebase",
".",
"auth",
".",
"EmailAuthProvider",
".",
"credentialWithLink",
"(",
"email",
",",
"link",
")",
";",
"activeUser",
"(",
")",
".",
"linkWithCredential",
"(",
"credential",
")",
".",
"then",
"(",
"onAuthUserCredentialSuccess",
",",
"onAuthError",
")",
";",
"}"
] | Links a user with an email link. | [
"Links",
"a",
"user",
"with",
"an",
"email",
"link",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L342-L349 |
2,715 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onReauthenticateWithEmailLink | function onReauthenticateWithEmailLink() {
var email = $('#link-with-email-link-email').val();
var link = $('#link-with-email-link-link').val() || undefined;
var credential = firebase.auth.EmailAuthProvider
.credentialWithLink(email, link);
activeUser().reauthenticateWithCredential(credential)
.then(function(result) {
logAdditionalUserInfo(result);
refreshUserData();
alertSuccess('User reauthenticated!');
}, onAuthError);
} | javascript | function onReauthenticateWithEmailLink() {
var email = $('#link-with-email-link-email').val();
var link = $('#link-with-email-link-link').val() || undefined;
var credential = firebase.auth.EmailAuthProvider
.credentialWithLink(email, link);
activeUser().reauthenticateWithCredential(credential)
.then(function(result) {
logAdditionalUserInfo(result);
refreshUserData();
alertSuccess('User reauthenticated!');
}, onAuthError);
} | [
"function",
"onReauthenticateWithEmailLink",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#link-with-email-link-email'",
")",
".",
"val",
"(",
")",
";",
"var",
"link",
"=",
"$",
"(",
"'#link-with-email-link-link'",
")",
".",
"val",
"(",
")",
"||",
"undefined",
";",
"var",
"credential",
"=",
"firebase",
".",
"auth",
".",
"EmailAuthProvider",
".",
"credentialWithLink",
"(",
"email",
",",
"link",
")",
";",
"activeUser",
"(",
")",
".",
"reauthenticateWithCredential",
"(",
"credential",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"logAdditionalUserInfo",
"(",
"result",
")",
";",
"refreshUserData",
"(",
")",
";",
"alertSuccess",
"(",
"'User reauthenticated!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] | Re-authenticate a user with email link credential. | [
"Re",
"-",
"authenticate",
"a",
"user",
"with",
"email",
"link",
"credential",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L355-L366 |
2,716 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onSignInWithCustomToken | function onSignInWithCustomToken(event) {
// The token can be directly specified on the html element.
var token = $('#user-custom-token').val();
auth.signInWithCustomToken(token)
.then(onAuthUserCredentialSuccess, onAuthError);
} | javascript | function onSignInWithCustomToken(event) {
// The token can be directly specified on the html element.
var token = $('#user-custom-token').val();
auth.signInWithCustomToken(token)
.then(onAuthUserCredentialSuccess, onAuthError);
} | [
"function",
"onSignInWithCustomToken",
"(",
"event",
")",
"{",
"// The token can be directly specified on the html element.",
"var",
"token",
"=",
"$",
"(",
"'#user-custom-token'",
")",
".",
"val",
"(",
")",
";",
"auth",
".",
"signInWithCustomToken",
"(",
"token",
")",
".",
"then",
"(",
"onAuthUserCredentialSuccess",
",",
"onAuthError",
")",
";",
"}"
] | Signs in with a custom token.
@param {DOMEvent} event HTML DOM event returned by the listener. | [
"Signs",
"in",
"with",
"a",
"custom",
"token",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L373-L379 |
2,717 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onSignInWithGenericIdPCredential | function onSignInWithGenericIdPCredential() {
var providerId = $('#signin-generic-idp-provider-id').val();
var idToken = $('#signin-generic-idp-id-token').val();
var accessToken = $('#signin-generic-idp-access-token').val();
var provider = new firebase.auth.OAuthProvider(providerId);
auth.signInWithCredential(
provider.credential(idToken, accessToken))
.then(onAuthUserCredentialSuccess, onAuthError);
} | javascript | function onSignInWithGenericIdPCredential() {
var providerId = $('#signin-generic-idp-provider-id').val();
var idToken = $('#signin-generic-idp-id-token').val();
var accessToken = $('#signin-generic-idp-access-token').val();
var provider = new firebase.auth.OAuthProvider(providerId);
auth.signInWithCredential(
provider.credential(idToken, accessToken))
.then(onAuthUserCredentialSuccess, onAuthError);
} | [
"function",
"onSignInWithGenericIdPCredential",
"(",
")",
"{",
"var",
"providerId",
"=",
"$",
"(",
"'#signin-generic-idp-provider-id'",
")",
".",
"val",
"(",
")",
";",
"var",
"idToken",
"=",
"$",
"(",
"'#signin-generic-idp-id-token'",
")",
".",
"val",
"(",
")",
";",
"var",
"accessToken",
"=",
"$",
"(",
"'#signin-generic-idp-access-token'",
")",
".",
"val",
"(",
")",
";",
"var",
"provider",
"=",
"new",
"firebase",
".",
"auth",
".",
"OAuthProvider",
"(",
"providerId",
")",
";",
"auth",
".",
"signInWithCredential",
"(",
"provider",
".",
"credential",
"(",
"idToken",
",",
"accessToken",
")",
")",
".",
"then",
"(",
"onAuthUserCredentialSuccess",
",",
"onAuthError",
")",
";",
"}"
] | Signs in with a generic IdP credential. | [
"Signs",
"in",
"with",
"a",
"generic",
"IdP",
"credential",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L394-L402 |
2,718 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | makeApplicationVerifier | function makeApplicationVerifier(submitButtonId) {
var container = recaptchaSize === 'invisible' ?
submitButtonId :
'recaptcha-container';
applicationVerifier = new firebase.auth.RecaptchaVerifier(container,
{'size': recaptchaSize});
} | javascript | function makeApplicationVerifier(submitButtonId) {
var container = recaptchaSize === 'invisible' ?
submitButtonId :
'recaptcha-container';
applicationVerifier = new firebase.auth.RecaptchaVerifier(container,
{'size': recaptchaSize});
} | [
"function",
"makeApplicationVerifier",
"(",
"submitButtonId",
")",
"{",
"var",
"container",
"=",
"recaptchaSize",
"===",
"'invisible'",
"?",
"submitButtonId",
":",
"'recaptcha-container'",
";",
"applicationVerifier",
"=",
"new",
"firebase",
".",
"auth",
".",
"RecaptchaVerifier",
"(",
"container",
",",
"{",
"'size'",
":",
"recaptchaSize",
"}",
")",
";",
"}"
] | Initializes the ApplicationVerifier.
@param {string} submitButtonId The ID of the DOM element of the button to
which we attach the invisible reCAPTCHA. This is required even in visible
mode. | [
"Initializes",
"the",
"ApplicationVerifier",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L411-L417 |
2,719 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onSignInConfirmPhoneVerification | function onSignInConfirmPhoneVerification() {
var verificationId = $('#signin-phone-verification-id').val();
var verificationCode = $('#signin-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
signInOrLinkCredential(credential);
} | javascript | function onSignInConfirmPhoneVerification() {
var verificationId = $('#signin-phone-verification-id').val();
var verificationCode = $('#signin-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
signInOrLinkCredential(credential);
} | [
"function",
"onSignInConfirmPhoneVerification",
"(",
")",
"{",
"var",
"verificationId",
"=",
"$",
"(",
"'#signin-phone-verification-id'",
")",
".",
"val",
"(",
")",
";",
"var",
"verificationCode",
"=",
"$",
"(",
"'#signin-phone-verification-code'",
")",
".",
"val",
"(",
")",
";",
"var",
"credential",
"=",
"firebase",
".",
"auth",
".",
"PhoneAuthProvider",
".",
"credential",
"(",
"verificationId",
",",
"verificationCode",
")",
";",
"signInOrLinkCredential",
"(",
"credential",
")",
";",
"}"
] | Confirms a phone number verification for sign-in. | [
"Confirms",
"a",
"phone",
"number",
"verification",
"for",
"sign",
"-",
"in",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L457-L463 |
2,720 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onLinkReauthVerifyPhoneNumber | function onLinkReauthVerifyPhoneNumber() {
var phoneNumber = $('#link-reauth-phone-number').val();
var provider = new firebase.auth.PhoneAuthProvider(auth);
// Clear existing reCAPTCHA as an existing reCAPTCHA could be targeted for a
// sign-in operation.
clearApplicationVerifier();
// Initialize a reCAPTCHA application verifier.
makeApplicationVerifier('link-reauth-verify-phone-number');
provider.verifyPhoneNumber(phoneNumber, applicationVerifier)
.then(function(verificationId) {
clearApplicationVerifier();
$('#link-reauth-phone-verification-id').val(verificationId);
alertSuccess('Phone verification sent!');
}, function(error) {
clearApplicationVerifier();
onAuthError(error);
});
} | javascript | function onLinkReauthVerifyPhoneNumber() {
var phoneNumber = $('#link-reauth-phone-number').val();
var provider = new firebase.auth.PhoneAuthProvider(auth);
// Clear existing reCAPTCHA as an existing reCAPTCHA could be targeted for a
// sign-in operation.
clearApplicationVerifier();
// Initialize a reCAPTCHA application verifier.
makeApplicationVerifier('link-reauth-verify-phone-number');
provider.verifyPhoneNumber(phoneNumber, applicationVerifier)
.then(function(verificationId) {
clearApplicationVerifier();
$('#link-reauth-phone-verification-id').val(verificationId);
alertSuccess('Phone verification sent!');
}, function(error) {
clearApplicationVerifier();
onAuthError(error);
});
} | [
"function",
"onLinkReauthVerifyPhoneNumber",
"(",
")",
"{",
"var",
"phoneNumber",
"=",
"$",
"(",
"'#link-reauth-phone-number'",
")",
".",
"val",
"(",
")",
";",
"var",
"provider",
"=",
"new",
"firebase",
".",
"auth",
".",
"PhoneAuthProvider",
"(",
"auth",
")",
";",
"// Clear existing reCAPTCHA as an existing reCAPTCHA could be targeted for a",
"// sign-in operation.",
"clearApplicationVerifier",
"(",
")",
";",
"// Initialize a reCAPTCHA application verifier.",
"makeApplicationVerifier",
"(",
"'link-reauth-verify-phone-number'",
")",
";",
"provider",
".",
"verifyPhoneNumber",
"(",
"phoneNumber",
",",
"applicationVerifier",
")",
".",
"then",
"(",
"function",
"(",
"verificationId",
")",
"{",
"clearApplicationVerifier",
"(",
")",
";",
"$",
"(",
"'#link-reauth-phone-verification-id'",
")",
".",
"val",
"(",
"verificationId",
")",
";",
"alertSuccess",
"(",
"'Phone verification sent!'",
")",
";",
"}",
",",
"function",
"(",
"error",
")",
"{",
"clearApplicationVerifier",
"(",
")",
";",
"onAuthError",
"(",
"error",
")",
";",
"}",
")",
";",
"}"
] | Sends a phone number verification code for linking or reauth. | [
"Sends",
"a",
"phone",
"number",
"verification",
"code",
"for",
"linking",
"or",
"reauth",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L469-L486 |
2,721 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onUpdateConfirmPhoneVerification | function onUpdateConfirmPhoneVerification() {
if (!activeUser()) {
alertError('You need to sign in before linking an account.');
return;
}
var verificationId = $('#link-reauth-phone-verification-id').val();
var verificationCode = $('#link-reauth-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
activeUser().updatePhoneNumber(credential).then(function() {
refreshUserData();
alertSuccess('Phone number updated!');
}, onAuthError);
} | javascript | function onUpdateConfirmPhoneVerification() {
if (!activeUser()) {
alertError('You need to sign in before linking an account.');
return;
}
var verificationId = $('#link-reauth-phone-verification-id').val();
var verificationCode = $('#link-reauth-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
activeUser().updatePhoneNumber(credential).then(function() {
refreshUserData();
alertSuccess('Phone number updated!');
}, onAuthError);
} | [
"function",
"onUpdateConfirmPhoneVerification",
"(",
")",
"{",
"if",
"(",
"!",
"activeUser",
"(",
")",
")",
"{",
"alertError",
"(",
"'You need to sign in before linking an account.'",
")",
";",
"return",
";",
"}",
"var",
"verificationId",
"=",
"$",
"(",
"'#link-reauth-phone-verification-id'",
")",
".",
"val",
"(",
")",
";",
"var",
"verificationCode",
"=",
"$",
"(",
"'#link-reauth-phone-verification-code'",
")",
".",
"val",
"(",
")",
";",
"var",
"credential",
"=",
"firebase",
".",
"auth",
".",
"PhoneAuthProvider",
".",
"credential",
"(",
"verificationId",
",",
"verificationCode",
")",
";",
"activeUser",
"(",
")",
".",
"updatePhoneNumber",
"(",
"credential",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"refreshUserData",
"(",
")",
";",
"alertSuccess",
"(",
"'Phone number updated!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] | Updates the user's phone number. | [
"Updates",
"the",
"user",
"s",
"phone",
"number",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L492-L505 |
2,722 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onReauthConfirmPhoneVerification | function onReauthConfirmPhoneVerification() {
var verificationId = $('#link-reauth-phone-verification-id').val();
var verificationCode = $('#link-reauth-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
activeUser().reauthenticateWithCredential(credential)
.then(function(result) {
logAdditionalUserInfo(result);
refreshUserData();
alertSuccess('User reauthenticated!');
}, onAuthError);
} | javascript | function onReauthConfirmPhoneVerification() {
var verificationId = $('#link-reauth-phone-verification-id').val();
var verificationCode = $('#link-reauth-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
activeUser().reauthenticateWithCredential(credential)
.then(function(result) {
logAdditionalUserInfo(result);
refreshUserData();
alertSuccess('User reauthenticated!');
}, onAuthError);
} | [
"function",
"onReauthConfirmPhoneVerification",
"(",
")",
"{",
"var",
"verificationId",
"=",
"$",
"(",
"'#link-reauth-phone-verification-id'",
")",
".",
"val",
"(",
")",
";",
"var",
"verificationCode",
"=",
"$",
"(",
"'#link-reauth-phone-verification-code'",
")",
".",
"val",
"(",
")",
";",
"var",
"credential",
"=",
"firebase",
".",
"auth",
".",
"PhoneAuthProvider",
".",
"credential",
"(",
"verificationId",
",",
"verificationCode",
")",
";",
"activeUser",
"(",
")",
".",
"reauthenticateWithCredential",
"(",
"credential",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"logAdditionalUserInfo",
"(",
"result",
")",
";",
"refreshUserData",
"(",
")",
";",
"alertSuccess",
"(",
"'User reauthenticated!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] | Confirms a phone number verification for reauthentication. | [
"Confirms",
"a",
"phone",
"number",
"verification",
"for",
"reauthentication",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L523-L534 |
2,723 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | signInOrLinkCredential | function signInOrLinkCredential(credential) {
if (currentTab == '#user-section') {
if (!activeUser()) {
alertError('You need to sign in before linking an account.');
return;
}
activeUser().linkWithCredential(credential)
.then(function(result) {
logAdditionalUserInfo(result);
refreshUserData();
alertSuccess('Provider linked!');
}, onAuthError);
} else {
auth.signInWithCredential(credential)
.then(onAuthUserCredentialSuccess, onAuthError);
}
} | javascript | function signInOrLinkCredential(credential) {
if (currentTab == '#user-section') {
if (!activeUser()) {
alertError('You need to sign in before linking an account.');
return;
}
activeUser().linkWithCredential(credential)
.then(function(result) {
logAdditionalUserInfo(result);
refreshUserData();
alertSuccess('Provider linked!');
}, onAuthError);
} else {
auth.signInWithCredential(credential)
.then(onAuthUserCredentialSuccess, onAuthError);
}
} | [
"function",
"signInOrLinkCredential",
"(",
"credential",
")",
"{",
"if",
"(",
"currentTab",
"==",
"'#user-section'",
")",
"{",
"if",
"(",
"!",
"activeUser",
"(",
")",
")",
"{",
"alertError",
"(",
"'You need to sign in before linking an account.'",
")",
";",
"return",
";",
"}",
"activeUser",
"(",
")",
".",
"linkWithCredential",
"(",
"credential",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"logAdditionalUserInfo",
"(",
"result",
")",
";",
"refreshUserData",
"(",
")",
";",
"alertSuccess",
"(",
"'Provider linked!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}",
"else",
"{",
"auth",
".",
"signInWithCredential",
"(",
"credential",
")",
".",
"then",
"(",
"onAuthUserCredentialSuccess",
",",
"onAuthError",
")",
";",
"}",
"}"
] | Signs in or links a provider's credential, based on current tab opened.
@param {!firebase.auth.AuthCredential} credential The provider's credential. | [
"Signs",
"in",
"or",
"links",
"a",
"provider",
"s",
"credential",
"based",
"on",
"current",
"tab",
"opened",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L541-L557 |
2,724 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onChangeEmail | function onChangeEmail() {
var email = $('#changed-email').val();
activeUser().updateEmail(email).then(function() {
refreshUserData();
alertSuccess('Email changed!');
}, onAuthError);
} | javascript | function onChangeEmail() {
var email = $('#changed-email').val();
activeUser().updateEmail(email).then(function() {
refreshUserData();
alertSuccess('Email changed!');
}, onAuthError);
} | [
"function",
"onChangeEmail",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#changed-email'",
")",
".",
"val",
"(",
")",
";",
"activeUser",
"(",
")",
".",
"updateEmail",
"(",
"email",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"refreshUserData",
"(",
")",
";",
"alertSuccess",
"(",
"'Email changed!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] | Changes the user's email. | [
"Changes",
"the",
"user",
"s",
"email",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L601-L607 |
2,725 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onSendSignInLinkToEmail | function onSendSignInLinkToEmail() {
var email = $('#sign-in-with-email-link-email').val();
auth.sendSignInLinkToEmail(email, getActionCodeSettings()).then(function() {
alertSuccess('Email sent!');
}, onAuthError);
} | javascript | function onSendSignInLinkToEmail() {
var email = $('#sign-in-with-email-link-email').val();
auth.sendSignInLinkToEmail(email, getActionCodeSettings()).then(function() {
alertSuccess('Email sent!');
}, onAuthError);
} | [
"function",
"onSendSignInLinkToEmail",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#sign-in-with-email-link-email'",
")",
".",
"val",
"(",
")",
";",
"auth",
".",
"sendSignInLinkToEmail",
"(",
"email",
",",
"getActionCodeSettings",
"(",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"alertSuccess",
"(",
"'Email sent!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] | Sends sign in with email link to the user. | [
"Sends",
"sign",
"in",
"with",
"email",
"link",
"to",
"the",
"user",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L641-L646 |
2,726 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onSendSignInLinkToEmailCurrentUrl | function onSendSignInLinkToEmailCurrentUrl() {
var email = $('#sign-in-with-email-link-email').val();
var actionCodeSettings = {
'url': window.location.href,
'handleCodeInApp': true
};
auth.sendSignInLinkToEmail(email, actionCodeSettings).then(function() {
if ('localStorage' in window && window['localStorage'] !== null) {
window.localStorage.setItem(
'emailForSignIn',
// Save the email and the timestamp.
JSON.stringify({
email: email,
timestamp: new Date().getTime()
}));
}
alertSuccess('Email sent!');
}, onAuthError);
} | javascript | function onSendSignInLinkToEmailCurrentUrl() {
var email = $('#sign-in-with-email-link-email').val();
var actionCodeSettings = {
'url': window.location.href,
'handleCodeInApp': true
};
auth.sendSignInLinkToEmail(email, actionCodeSettings).then(function() {
if ('localStorage' in window && window['localStorage'] !== null) {
window.localStorage.setItem(
'emailForSignIn',
// Save the email and the timestamp.
JSON.stringify({
email: email,
timestamp: new Date().getTime()
}));
}
alertSuccess('Email sent!');
}, onAuthError);
} | [
"function",
"onSendSignInLinkToEmailCurrentUrl",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#sign-in-with-email-link-email'",
")",
".",
"val",
"(",
")",
";",
"var",
"actionCodeSettings",
"=",
"{",
"'url'",
":",
"window",
".",
"location",
".",
"href",
",",
"'handleCodeInApp'",
":",
"true",
"}",
";",
"auth",
".",
"sendSignInLinkToEmail",
"(",
"email",
",",
"actionCodeSettings",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"'localStorage'",
"in",
"window",
"&&",
"window",
"[",
"'localStorage'",
"]",
"!==",
"null",
")",
"{",
"window",
".",
"localStorage",
".",
"setItem",
"(",
"'emailForSignIn'",
",",
"// Save the email and the timestamp.",
"JSON",
".",
"stringify",
"(",
"{",
"email",
":",
"email",
",",
"timestamp",
":",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"}",
")",
")",
";",
"}",
"alertSuccess",
"(",
"'Email sent!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] | Sends sign in with email link to the user and pass in current url. | [
"Sends",
"sign",
"in",
"with",
"email",
"link",
"to",
"the",
"user",
"and",
"pass",
"in",
"current",
"url",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L651-L670 |
2,727 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onSendPasswordResetEmail | function onSendPasswordResetEmail() {
var email = $('#password-reset-email').val();
auth.sendPasswordResetEmail(email, getActionCodeSettings()).then(function() {
alertSuccess('Email sent!');
}, onAuthError);
} | javascript | function onSendPasswordResetEmail() {
var email = $('#password-reset-email').val();
auth.sendPasswordResetEmail(email, getActionCodeSettings()).then(function() {
alertSuccess('Email sent!');
}, onAuthError);
} | [
"function",
"onSendPasswordResetEmail",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#password-reset-email'",
")",
".",
"val",
"(",
")",
";",
"auth",
".",
"sendPasswordResetEmail",
"(",
"email",
",",
"getActionCodeSettings",
"(",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"alertSuccess",
"(",
"'Email sent!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] | Sends password reset email to the user. | [
"Sends",
"password",
"reset",
"email",
"to",
"the",
"user",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L687-L692 |
2,728 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onConfirmPasswordReset | function onConfirmPasswordReset() {
var code = $('#password-reset-code').val();
var password = $('#password-reset-password').val();
auth.confirmPasswordReset(code, password).then(function() {
alertSuccess('Password has been changed!');
}, onAuthError);
} | javascript | function onConfirmPasswordReset() {
var code = $('#password-reset-code').val();
var password = $('#password-reset-password').val();
auth.confirmPasswordReset(code, password).then(function() {
alertSuccess('Password has been changed!');
}, onAuthError);
} | [
"function",
"onConfirmPasswordReset",
"(",
")",
"{",
"var",
"code",
"=",
"$",
"(",
"'#password-reset-code'",
")",
".",
"val",
"(",
")",
";",
"var",
"password",
"=",
"$",
"(",
"'#password-reset-password'",
")",
".",
"val",
"(",
")",
";",
"auth",
".",
"confirmPasswordReset",
"(",
"code",
",",
"password",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"alertSuccess",
"(",
"'Password has been changed!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] | Confirms the password reset with the code and password supplied by the user. | [
"Confirms",
"the",
"password",
"reset",
"with",
"the",
"code",
"and",
"password",
"supplied",
"by",
"the",
"user",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L709-L715 |
2,729 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onFetchSignInMethodsForEmail | function onFetchSignInMethodsForEmail() {
var email = $('#fetch-sign-in-methods-email').val();
auth.fetchSignInMethodsForEmail(email).then(function(signInMethods) {
log('Sign in methods for ' + email + ' :');
log(signInMethods);
if (signInMethods.length == 0) {
alertSuccess('Sign In Methods for ' + email + ': N/A');
} else {
alertSuccess(
'Sign In Methods for ' + email +': ' + signInMethods.join(', '));
}
}, onAuthError);
} | javascript | function onFetchSignInMethodsForEmail() {
var email = $('#fetch-sign-in-methods-email').val();
auth.fetchSignInMethodsForEmail(email).then(function(signInMethods) {
log('Sign in methods for ' + email + ' :');
log(signInMethods);
if (signInMethods.length == 0) {
alertSuccess('Sign In Methods for ' + email + ': N/A');
} else {
alertSuccess(
'Sign In Methods for ' + email +': ' + signInMethods.join(', '));
}
}, onAuthError);
} | [
"function",
"onFetchSignInMethodsForEmail",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#fetch-sign-in-methods-email'",
")",
".",
"val",
"(",
")",
";",
"auth",
".",
"fetchSignInMethodsForEmail",
"(",
"email",
")",
".",
"then",
"(",
"function",
"(",
"signInMethods",
")",
"{",
"log",
"(",
"'Sign in methods for '",
"+",
"email",
"+",
"' :'",
")",
";",
"log",
"(",
"signInMethods",
")",
";",
"if",
"(",
"signInMethods",
".",
"length",
"==",
"0",
")",
"{",
"alertSuccess",
"(",
"'Sign In Methods for '",
"+",
"email",
"+",
"': N/A'",
")",
";",
"}",
"else",
"{",
"alertSuccess",
"(",
"'Sign In Methods for '",
"+",
"email",
"+",
"': '",
"+",
"signInMethods",
".",
"join",
"(",
"', '",
")",
")",
";",
"}",
"}",
",",
"onAuthError",
")",
";",
"}"
] | Gets the list of possible sign in methods for the given email address. | [
"Gets",
"the",
"list",
"of",
"possible",
"sign",
"in",
"methods",
"for",
"the",
"given",
"email",
"address",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L721-L733 |
2,730 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onLinkWithEmailAndPassword | function onLinkWithEmailAndPassword() {
var email = $('#link-email').val();
var password = $('#link-password').val();
activeUser().linkWithCredential(
firebase.auth.EmailAuthProvider.credential(email, password))
.then(onAuthUserCredentialSuccess, onAuthError);
} | javascript | function onLinkWithEmailAndPassword() {
var email = $('#link-email').val();
var password = $('#link-password').val();
activeUser().linkWithCredential(
firebase.auth.EmailAuthProvider.credential(email, password))
.then(onAuthUserCredentialSuccess, onAuthError);
} | [
"function",
"onLinkWithEmailAndPassword",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#link-email'",
")",
".",
"val",
"(",
")",
";",
"var",
"password",
"=",
"$",
"(",
"'#link-password'",
")",
".",
"val",
"(",
")",
";",
"activeUser",
"(",
")",
".",
"linkWithCredential",
"(",
"firebase",
".",
"auth",
".",
"EmailAuthProvider",
".",
"credential",
"(",
"email",
",",
"password",
")",
")",
".",
"then",
"(",
"onAuthUserCredentialSuccess",
",",
"onAuthError",
")",
";",
"}"
] | Links a signed in user with an email and password account. | [
"Links",
"a",
"signed",
"in",
"user",
"with",
"an",
"email",
"and",
"password",
"account",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L748-L754 |
2,731 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onLinkWithGenericIdPCredential | function onLinkWithGenericIdPCredential() {
var providerId = $('#link-generic-idp-provider-id').val();
var idToken = $('#link-generic-idp-id-token').val();
var accessToken = $('#link-generic-idp-access-token').val();
var provider = new firebase.auth.OAuthProvider(providerId);
activeUser().linkWithCredential(
provider.credential(idToken, accessToken))
.then(onAuthUserCredentialSuccess, onAuthError);
} | javascript | function onLinkWithGenericIdPCredential() {
var providerId = $('#link-generic-idp-provider-id').val();
var idToken = $('#link-generic-idp-id-token').val();
var accessToken = $('#link-generic-idp-access-token').val();
var provider = new firebase.auth.OAuthProvider(providerId);
activeUser().linkWithCredential(
provider.credential(idToken, accessToken))
.then(onAuthUserCredentialSuccess, onAuthError);
} | [
"function",
"onLinkWithGenericIdPCredential",
"(",
")",
"{",
"var",
"providerId",
"=",
"$",
"(",
"'#link-generic-idp-provider-id'",
")",
".",
"val",
"(",
")",
";",
"var",
"idToken",
"=",
"$",
"(",
"'#link-generic-idp-id-token'",
")",
".",
"val",
"(",
")",
";",
"var",
"accessToken",
"=",
"$",
"(",
"'#link-generic-idp-access-token'",
")",
".",
"val",
"(",
")",
";",
"var",
"provider",
"=",
"new",
"firebase",
".",
"auth",
".",
"OAuthProvider",
"(",
"providerId",
")",
";",
"activeUser",
"(",
")",
".",
"linkWithCredential",
"(",
"provider",
".",
"credential",
"(",
"idToken",
",",
"accessToken",
")",
")",
".",
"then",
"(",
"onAuthUserCredentialSuccess",
",",
"onAuthError",
")",
";",
"}"
] | Links with a generic IdP credential. | [
"Links",
"with",
"a",
"generic",
"IdP",
"credential",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L760-L768 |
2,732 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onUnlinkProvider | function onUnlinkProvider() {
var providerId = $('#unlinked-provider-id').val();
activeUser().unlink(providerId).then(function(user) {
alertSuccess('Provider unlinked from user.');
refreshUserData();
}, onAuthError);
} | javascript | function onUnlinkProvider() {
var providerId = $('#unlinked-provider-id').val();
activeUser().unlink(providerId).then(function(user) {
alertSuccess('Provider unlinked from user.');
refreshUserData();
}, onAuthError);
} | [
"function",
"onUnlinkProvider",
"(",
")",
"{",
"var",
"providerId",
"=",
"$",
"(",
"'#unlinked-provider-id'",
")",
".",
"val",
"(",
")",
";",
"activeUser",
"(",
")",
".",
"unlink",
"(",
"providerId",
")",
".",
"then",
"(",
"function",
"(",
"user",
")",
"{",
"alertSuccess",
"(",
"'Provider unlinked from user.'",
")",
";",
"refreshUserData",
"(",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] | Unlinks the specified provider. | [
"Unlinks",
"the",
"specified",
"provider",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L774-L780 |
2,733 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onApplyActionCode | function onApplyActionCode() {
var code = $('#email-verification-code').val();
auth.applyActionCode(code).then(function() {
alertSuccess('Email successfully verified!');
refreshUserData();
}, onAuthError);
} | javascript | function onApplyActionCode() {
var code = $('#email-verification-code').val();
auth.applyActionCode(code).then(function() {
alertSuccess('Email successfully verified!');
refreshUserData();
}, onAuthError);
} | [
"function",
"onApplyActionCode",
"(",
")",
"{",
"var",
"code",
"=",
"$",
"(",
"'#email-verification-code'",
")",
".",
"val",
"(",
")",
";",
"auth",
".",
"applyActionCode",
"(",
"code",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"alertSuccess",
"(",
"'Email successfully verified!'",
")",
";",
"refreshUserData",
"(",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] | Confirms the email verification code given. | [
"Confirms",
"the",
"email",
"verification",
"code",
"given",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L796-L802 |
2,734 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | getIdToken | function getIdToken(forceRefresh) {
if (activeUser() == null) {
alertError('No user logged in.');
return;
}
if (activeUser().getIdToken) {
activeUser().getIdToken(forceRefresh).then(alertSuccess, function() {
log("No token");
});
} else {
activeUser().getToken(forceRefresh).then(alertSuccess, function() {
log("No token");
});
}
} | javascript | function getIdToken(forceRefresh) {
if (activeUser() == null) {
alertError('No user logged in.');
return;
}
if (activeUser().getIdToken) {
activeUser().getIdToken(forceRefresh).then(alertSuccess, function() {
log("No token");
});
} else {
activeUser().getToken(forceRefresh).then(alertSuccess, function() {
log("No token");
});
}
} | [
"function",
"getIdToken",
"(",
"forceRefresh",
")",
"{",
"if",
"(",
"activeUser",
"(",
")",
"==",
"null",
")",
"{",
"alertError",
"(",
"'No user logged in.'",
")",
";",
"return",
";",
"}",
"if",
"(",
"activeUser",
"(",
")",
".",
"getIdToken",
")",
"{",
"activeUser",
"(",
")",
".",
"getIdToken",
"(",
"forceRefresh",
")",
".",
"then",
"(",
"alertSuccess",
",",
"function",
"(",
")",
"{",
"log",
"(",
"\"No token\"",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"activeUser",
"(",
")",
".",
"getToken",
"(",
"forceRefresh",
")",
".",
"then",
"(",
"alertSuccess",
",",
"function",
"(",
")",
"{",
"log",
"(",
"\"No token\"",
")",
";",
"}",
")",
";",
"}",
"}"
] | Gets or refreshes the ID token.
@param {boolean} forceRefresh Whether to force the refresh of the token
or not. | [
"Gets",
"or",
"refreshes",
"the",
"ID",
"token",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L810-L824 |
2,735 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | getIdTokenResult | function getIdTokenResult(forceRefresh) {
if (activeUser() == null) {
alertError('No user logged in.');
return;
}
activeUser().getIdTokenResult(forceRefresh).then(function(idTokenResult) {
alertSuccess(JSON.stringify(idTokenResult));
}, onAuthError);
} | javascript | function getIdTokenResult(forceRefresh) {
if (activeUser() == null) {
alertError('No user logged in.');
return;
}
activeUser().getIdTokenResult(forceRefresh).then(function(idTokenResult) {
alertSuccess(JSON.stringify(idTokenResult));
}, onAuthError);
} | [
"function",
"getIdTokenResult",
"(",
"forceRefresh",
")",
"{",
"if",
"(",
"activeUser",
"(",
")",
"==",
"null",
")",
"{",
"alertError",
"(",
"'No user logged in.'",
")",
";",
"return",
";",
"}",
"activeUser",
"(",
")",
".",
"getIdTokenResult",
"(",
"forceRefresh",
")",
".",
"then",
"(",
"function",
"(",
"idTokenResult",
")",
"{",
"alertSuccess",
"(",
"JSON",
".",
"stringify",
"(",
"idTokenResult",
")",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] | Gets or refreshes the ID token result.
@param {boolean} forceRefresh Whether to force the refresh of the token
or not | [
"Gets",
"or",
"refreshes",
"the",
"ID",
"token",
"result",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L832-L840 |
2,736 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onGetRedirectResult | function onGetRedirectResult() {
auth.getRedirectResult().then(function(response) {
log('Redirect results:');
if (response.credential) {
log('Credential:');
log(response.credential);
} else {
log('No credential');
}
if (response.user) {
log('User\'s id:');
log(response.user.uid);
} else {
log('No user');
}
logAdditionalUserInfo(response);
console.log(response);
}, onAuthError);
} | javascript | function onGetRedirectResult() {
auth.getRedirectResult().then(function(response) {
log('Redirect results:');
if (response.credential) {
log('Credential:');
log(response.credential);
} else {
log('No credential');
}
if (response.user) {
log('User\'s id:');
log(response.user.uid);
} else {
log('No user');
}
logAdditionalUserInfo(response);
console.log(response);
}, onAuthError);
} | [
"function",
"onGetRedirectResult",
"(",
")",
"{",
"auth",
".",
"getRedirectResult",
"(",
")",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"log",
"(",
"'Redirect results:'",
")",
";",
"if",
"(",
"response",
".",
"credential",
")",
"{",
"log",
"(",
"'Credential:'",
")",
";",
"log",
"(",
"response",
".",
"credential",
")",
";",
"}",
"else",
"{",
"log",
"(",
"'No credential'",
")",
";",
"}",
"if",
"(",
"response",
".",
"user",
")",
"{",
"log",
"(",
"'User\\'s id:'",
")",
";",
"log",
"(",
"response",
".",
"user",
".",
"uid",
")",
";",
"}",
"else",
"{",
"log",
"(",
"'No user'",
")",
";",
"}",
"logAdditionalUserInfo",
"(",
"response",
")",
";",
"console",
".",
"log",
"(",
"response",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] | Displays redirect result. | [
"Displays",
"redirect",
"result",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L1052-L1070 |
2,737 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | logAdditionalUserInfo | function logAdditionalUserInfo(response) {
if (response.additionalUserInfo) {
if (response.additionalUserInfo.username) {
log(response.additionalUserInfo['providerId'] + ' username: ' +
response.additionalUserInfo.username);
}
if (response.additionalUserInfo.profile) {
log(response.additionalUserInfo['providerId'] + ' profile information:');
log(JSON.stringify(response.additionalUserInfo.profile, null, 2));
}
if (typeof response.additionalUserInfo.isNewUser !== 'undefined') {
log(response.additionalUserInfo['providerId'] + ' isNewUser: ' +
response.additionalUserInfo.isNewUser);
}
}
} | javascript | function logAdditionalUserInfo(response) {
if (response.additionalUserInfo) {
if (response.additionalUserInfo.username) {
log(response.additionalUserInfo['providerId'] + ' username: ' +
response.additionalUserInfo.username);
}
if (response.additionalUserInfo.profile) {
log(response.additionalUserInfo['providerId'] + ' profile information:');
log(JSON.stringify(response.additionalUserInfo.profile, null, 2));
}
if (typeof response.additionalUserInfo.isNewUser !== 'undefined') {
log(response.additionalUserInfo['providerId'] + ' isNewUser: ' +
response.additionalUserInfo.isNewUser);
}
}
} | [
"function",
"logAdditionalUserInfo",
"(",
"response",
")",
"{",
"if",
"(",
"response",
".",
"additionalUserInfo",
")",
"{",
"if",
"(",
"response",
".",
"additionalUserInfo",
".",
"username",
")",
"{",
"log",
"(",
"response",
".",
"additionalUserInfo",
"[",
"'providerId'",
"]",
"+",
"' username: '",
"+",
"response",
".",
"additionalUserInfo",
".",
"username",
")",
";",
"}",
"if",
"(",
"response",
".",
"additionalUserInfo",
".",
"profile",
")",
"{",
"log",
"(",
"response",
".",
"additionalUserInfo",
"[",
"'providerId'",
"]",
"+",
"' profile information:'",
")",
";",
"log",
"(",
"JSON",
".",
"stringify",
"(",
"response",
".",
"additionalUserInfo",
".",
"profile",
",",
"null",
",",
"2",
")",
")",
";",
"}",
"if",
"(",
"typeof",
"response",
".",
"additionalUserInfo",
".",
"isNewUser",
"!==",
"'undefined'",
")",
"{",
"log",
"(",
"response",
".",
"additionalUserInfo",
"[",
"'providerId'",
"]",
"+",
"' isNewUser: '",
"+",
"response",
".",
"additionalUserInfo",
".",
"isNewUser",
")",
";",
"}",
"}",
"}"
] | Logs additional user info returned by a sign-in event, if available.
@param {!Object} response | [
"Logs",
"additional",
"user",
"info",
"returned",
"by",
"a",
"sign",
"-",
"in",
"event",
"if",
"available",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L1077-L1092 |
2,738 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | populateActionCodes | function populateActionCodes() {
var emailForSignIn = null;
var signInTime = 0;
if ('localStorage' in window && window['localStorage'] !== null) {
try {
// Try to parse as JSON first using new storage format.
var emailForSignInData =
JSON.parse(window.localStorage.getItem('emailForSignIn'));
emailForSignIn = emailForSignInData['email'] || null;
signInTime = emailForSignInData['timestamp'] || 0;
} catch (e) {
// JSON parsing failed. This means the email is stored in the old string
// format.
emailForSignIn = window.localStorage.getItem('emailForSignIn');
}
if (emailForSignIn) {
// Clear old codes. Old format codes should be cleared immediately.
if (new Date().getTime() - signInTime >= 1 * 24 * 3600 * 1000) {
// Remove email from storage.
window.localStorage.removeItem('emailForSignIn');
}
}
}
var actionCode = getParameterByName('oobCode');
if (actionCode != null) {
var mode = getParameterByName('mode');
if (mode == 'verifyEmail') {
$('#email-verification-code').val(actionCode);
} else if (mode == 'resetPassword') {
$('#password-reset-code').val(actionCode);
} else if (mode == 'signIn') {
if (emailForSignIn) {
$('#sign-in-with-email-link-email').val(emailForSignIn);
$('#sign-in-with-email-link-link').val(window.location.href);
onSignInWithEmailLink();
// Remove email from storage as the code is only usable once.
window.localStorage.removeItem('emailForSignIn');
}
} else {
$('#email-verification-code').val(actionCode);
$('#password-reset-code').val(actionCode);
}
}
} | javascript | function populateActionCodes() {
var emailForSignIn = null;
var signInTime = 0;
if ('localStorage' in window && window['localStorage'] !== null) {
try {
// Try to parse as JSON first using new storage format.
var emailForSignInData =
JSON.parse(window.localStorage.getItem('emailForSignIn'));
emailForSignIn = emailForSignInData['email'] || null;
signInTime = emailForSignInData['timestamp'] || 0;
} catch (e) {
// JSON parsing failed. This means the email is stored in the old string
// format.
emailForSignIn = window.localStorage.getItem('emailForSignIn');
}
if (emailForSignIn) {
// Clear old codes. Old format codes should be cleared immediately.
if (new Date().getTime() - signInTime >= 1 * 24 * 3600 * 1000) {
// Remove email from storage.
window.localStorage.removeItem('emailForSignIn');
}
}
}
var actionCode = getParameterByName('oobCode');
if (actionCode != null) {
var mode = getParameterByName('mode');
if (mode == 'verifyEmail') {
$('#email-verification-code').val(actionCode);
} else if (mode == 'resetPassword') {
$('#password-reset-code').val(actionCode);
} else if (mode == 'signIn') {
if (emailForSignIn) {
$('#sign-in-with-email-link-email').val(emailForSignIn);
$('#sign-in-with-email-link-link').val(window.location.href);
onSignInWithEmailLink();
// Remove email from storage as the code is only usable once.
window.localStorage.removeItem('emailForSignIn');
}
} else {
$('#email-verification-code').val(actionCode);
$('#password-reset-code').val(actionCode);
}
}
} | [
"function",
"populateActionCodes",
"(",
")",
"{",
"var",
"emailForSignIn",
"=",
"null",
";",
"var",
"signInTime",
"=",
"0",
";",
"if",
"(",
"'localStorage'",
"in",
"window",
"&&",
"window",
"[",
"'localStorage'",
"]",
"!==",
"null",
")",
"{",
"try",
"{",
"// Try to parse as JSON first using new storage format.",
"var",
"emailForSignInData",
"=",
"JSON",
".",
"parse",
"(",
"window",
".",
"localStorage",
".",
"getItem",
"(",
"'emailForSignIn'",
")",
")",
";",
"emailForSignIn",
"=",
"emailForSignInData",
"[",
"'email'",
"]",
"||",
"null",
";",
"signInTime",
"=",
"emailForSignInData",
"[",
"'timestamp'",
"]",
"||",
"0",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// JSON parsing failed. This means the email is stored in the old string",
"// format.",
"emailForSignIn",
"=",
"window",
".",
"localStorage",
".",
"getItem",
"(",
"'emailForSignIn'",
")",
";",
"}",
"if",
"(",
"emailForSignIn",
")",
"{",
"// Clear old codes. Old format codes should be cleared immediately.",
"if",
"(",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"-",
"signInTime",
">=",
"1",
"*",
"24",
"*",
"3600",
"*",
"1000",
")",
"{",
"// Remove email from storage.",
"window",
".",
"localStorage",
".",
"removeItem",
"(",
"'emailForSignIn'",
")",
";",
"}",
"}",
"}",
"var",
"actionCode",
"=",
"getParameterByName",
"(",
"'oobCode'",
")",
";",
"if",
"(",
"actionCode",
"!=",
"null",
")",
"{",
"var",
"mode",
"=",
"getParameterByName",
"(",
"'mode'",
")",
";",
"if",
"(",
"mode",
"==",
"'verifyEmail'",
")",
"{",
"$",
"(",
"'#email-verification-code'",
")",
".",
"val",
"(",
"actionCode",
")",
";",
"}",
"else",
"if",
"(",
"mode",
"==",
"'resetPassword'",
")",
"{",
"$",
"(",
"'#password-reset-code'",
")",
".",
"val",
"(",
"actionCode",
")",
";",
"}",
"else",
"if",
"(",
"mode",
"==",
"'signIn'",
")",
"{",
"if",
"(",
"emailForSignIn",
")",
"{",
"$",
"(",
"'#sign-in-with-email-link-email'",
")",
".",
"val",
"(",
"emailForSignIn",
")",
";",
"$",
"(",
"'#sign-in-with-email-link-link'",
")",
".",
"val",
"(",
"window",
".",
"location",
".",
"href",
")",
";",
"onSignInWithEmailLink",
"(",
")",
";",
"// Remove email from storage as the code is only usable once.",
"window",
".",
"localStorage",
".",
"removeItem",
"(",
"'emailForSignIn'",
")",
";",
"}",
"}",
"else",
"{",
"$",
"(",
"'#email-verification-code'",
")",
".",
"val",
"(",
"actionCode",
")",
";",
"$",
"(",
"'#password-reset-code'",
")",
".",
"val",
"(",
"actionCode",
")",
";",
"}",
"}",
"}"
] | Detects if an action code is passed in the URL, and populates accordingly
the input field for the confirm email verification process. | [
"Detects",
"if",
"an",
"action",
"code",
"is",
"passed",
"in",
"the",
"URL",
"and",
"populates",
"accordingly",
"the",
"input",
"field",
"for",
"the",
"confirm",
"email",
"verification",
"process",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L1128-L1171 |
2,739 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onCopyActiveUser | function onCopyActiveUser() {
tempAuth.updateCurrentUser(activeUser()).then(function() {
alertSuccess('Copied active user to temp Auth');
}, function(error) {
alertError('Error: ' + error.code);
});
} | javascript | function onCopyActiveUser() {
tempAuth.updateCurrentUser(activeUser()).then(function() {
alertSuccess('Copied active user to temp Auth');
}, function(error) {
alertError('Error: ' + error.code);
});
} | [
"function",
"onCopyActiveUser",
"(",
")",
"{",
"tempAuth",
".",
"updateCurrentUser",
"(",
"activeUser",
"(",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"alertSuccess",
"(",
"'Copied active user to temp Auth'",
")",
";",
"}",
",",
"function",
"(",
"error",
")",
"{",
"alertError",
"(",
"'Error: '",
"+",
"error",
".",
"code",
")",
";",
"}",
")",
";",
"}"
] | Copy current user of auth to tempAuth. | [
"Copy",
"current",
"user",
"of",
"auth",
"to",
"tempAuth",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L1279-L1285 |
2,740 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onCopyLastUser | function onCopyLastUser() {
// If last user is null, NULL_USER error will be thrown.
auth.updateCurrentUser(lastUser).then(function() {
alertSuccess('Copied last user to Auth');
}, function(error) {
alertError('Error: ' + error.code);
});
} | javascript | function onCopyLastUser() {
// If last user is null, NULL_USER error will be thrown.
auth.updateCurrentUser(lastUser).then(function() {
alertSuccess('Copied last user to Auth');
}, function(error) {
alertError('Error: ' + error.code);
});
} | [
"function",
"onCopyLastUser",
"(",
")",
"{",
"// If last user is null, NULL_USER error will be thrown.",
"auth",
".",
"updateCurrentUser",
"(",
"lastUser",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"alertSuccess",
"(",
"'Copied last user to Auth'",
")",
";",
"}",
",",
"function",
"(",
"error",
")",
"{",
"alertError",
"(",
"'Error: '",
"+",
"error",
".",
"code",
")",
";",
"}",
")",
";",
"}"
] | Copy last user to auth. | [
"Copy",
"last",
"user",
"to",
"auth",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L1289-L1296 |
2,741 | firebase/firebase-js-sdk | packages/auth/demo/public/script.js | onApplyAuthSettingsChange | function onApplyAuthSettingsChange() {
try {
auth.settings.appVerificationDisabledForTesting =
$("input[name=enable-app-verification]:checked").val() == 'No';
alertSuccess('Auth settings changed');
} catch (error) {
alertError('Error: ' + error.code);
}
} | javascript | function onApplyAuthSettingsChange() {
try {
auth.settings.appVerificationDisabledForTesting =
$("input[name=enable-app-verification]:checked").val() == 'No';
alertSuccess('Auth settings changed');
} catch (error) {
alertError('Error: ' + error.code);
}
} | [
"function",
"onApplyAuthSettingsChange",
"(",
")",
"{",
"try",
"{",
"auth",
".",
"settings",
".",
"appVerificationDisabledForTesting",
"=",
"$",
"(",
"\"input[name=enable-app-verification]:checked\"",
")",
".",
"val",
"(",
")",
"==",
"'No'",
";",
"alertSuccess",
"(",
"'Auth settings changed'",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"alertError",
"(",
"'Error: '",
"+",
"error",
".",
"code",
")",
";",
"}",
"}"
] | Applies selected auth settings change. | [
"Applies",
"selected",
"auth",
"settings",
"change",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L1300-L1308 |
2,742 | firebase/firebase-js-sdk | packages/auth/src/autheventmanager.js | function() {
if (!self.initialized_) {
self.initialized_ = true;
// Listen to Auth events on iframe.
self.oauthSignInHandler_.addAuthEventListener(self.authEventHandler_);
}
} | javascript | function() {
if (!self.initialized_) {
self.initialized_ = true;
// Listen to Auth events on iframe.
self.oauthSignInHandler_.addAuthEventListener(self.authEventHandler_);
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"self",
".",
"initialized_",
")",
"{",
"self",
".",
"initialized_",
"=",
"true",
";",
"// Listen to Auth events on iframe.",
"self",
".",
"oauthSignInHandler_",
".",
"addAuthEventListener",
"(",
"self",
".",
"authEventHandler_",
")",
";",
"}",
"}"
] | On initialization, add Auth event listener if not already added. | [
"On",
"initialization",
"add",
"Auth",
"event",
"listener",
"if",
"not",
"already",
"added",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/src/autheventmanager.js#L501-L507 |
|
2,743 | firebase/firebase-js-sdk | packages/auth/src/iframeclient/iframewrapper.js | function() {
// The developer may have tried to previously run gapi.load and failed.
// Run this to fix that.
fireauth.util.resetUnloadedGapiModules();
var loader = /** @type {function(string, !Object)} */ (
fireauth.util.getObjectRef('gapi.load'));
loader('gapi.iframes', {
'callback': resolve,
'ontimeout': function() {
// The above reset may be sufficient, but having this reset after
// failure ensures that if the developer calls gapi.load after the
// connection is re-established and before another attempt to embed
// the iframe, it would work and would not be broken because of our
// failed attempt.
// Timeout when gapi.iframes.Iframe not loaded.
fireauth.util.resetUnloadedGapiModules();
reject(new Error('Network Error'));
},
'timeout': fireauth.iframeclient.IframeWrapper.NETWORK_TIMEOUT_.get()
});
} | javascript | function() {
// The developer may have tried to previously run gapi.load and failed.
// Run this to fix that.
fireauth.util.resetUnloadedGapiModules();
var loader = /** @type {function(string, !Object)} */ (
fireauth.util.getObjectRef('gapi.load'));
loader('gapi.iframes', {
'callback': resolve,
'ontimeout': function() {
// The above reset may be sufficient, but having this reset after
// failure ensures that if the developer calls gapi.load after the
// connection is re-established and before another attempt to embed
// the iframe, it would work and would not be broken because of our
// failed attempt.
// Timeout when gapi.iframes.Iframe not loaded.
fireauth.util.resetUnloadedGapiModules();
reject(new Error('Network Error'));
},
'timeout': fireauth.iframeclient.IframeWrapper.NETWORK_TIMEOUT_.get()
});
} | [
"function",
"(",
")",
"{",
"// The developer may have tried to previously run gapi.load and failed.",
"// Run this to fix that.",
"fireauth",
".",
"util",
".",
"resetUnloadedGapiModules",
"(",
")",
";",
"var",
"loader",
"=",
"/** @type {function(string, !Object)} */",
"(",
"fireauth",
".",
"util",
".",
"getObjectRef",
"(",
"'gapi.load'",
")",
")",
";",
"loader",
"(",
"'gapi.iframes'",
",",
"{",
"'callback'",
":",
"resolve",
",",
"'ontimeout'",
":",
"function",
"(",
")",
"{",
"// The above reset may be sufficient, but having this reset after",
"// failure ensures that if the developer calls gapi.load after the",
"// connection is re-established and before another attempt to embed",
"// the iframe, it would work and would not be broken because of our",
"// failed attempt.",
"// Timeout when gapi.iframes.Iframe not loaded.",
"fireauth",
".",
"util",
".",
"resetUnloadedGapiModules",
"(",
")",
";",
"reject",
"(",
"new",
"Error",
"(",
"'Network Error'",
")",
")",
";",
"}",
",",
"'timeout'",
":",
"fireauth",
".",
"iframeclient",
".",
"IframeWrapper",
".",
"NETWORK_TIMEOUT_",
".",
"get",
"(",
")",
"}",
")",
";",
"}"
] | Function to run when gapi.load is ready. | [
"Function",
"to",
"run",
"when",
"gapi",
".",
"load",
"is",
"ready",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/src/iframeclient/iframewrapper.js#L252-L272 |
|
2,744 | firebase/firebase-js-sdk | packages/auth/gulpfile.js | createBuildTask | function createBuildTask(filename, prefix, suffix) {
return () =>
gulp
.src([
`${closureLibRoot}/closure/goog/**/*.js`,
`${closureLibRoot}/third_party/closure/goog/**/*.js`,
'src/**/*.js'
], { base: '.' })
.pipe(sourcemaps.init())
.pipe(
closureCompiler({
js_output_file: filename,
output_wrapper: `${prefix}%output%${suffix}`,
entry_point: 'fireauth.exports',
compilation_level: OPTIMIZATION_LEVEL,
externs: [
'externs/externs.js',
'externs/grecaptcha.js',
'externs/gapi.iframes.js',
path.resolve(
__dirname,
'../firebase/externs/firebase-app-externs.js'
),
path.resolve(
__dirname,
'../firebase/externs/firebase-error-externs.js'
),
path.resolve(
__dirname,
'../firebase/externs/firebase-app-internal-externs.js'
)
],
language_out: 'ES5',
only_closure_dependencies: true
})
)
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'));
} | javascript | function createBuildTask(filename, prefix, suffix) {
return () =>
gulp
.src([
`${closureLibRoot}/closure/goog/**/*.js`,
`${closureLibRoot}/third_party/closure/goog/**/*.js`,
'src/**/*.js'
], { base: '.' })
.pipe(sourcemaps.init())
.pipe(
closureCompiler({
js_output_file: filename,
output_wrapper: `${prefix}%output%${suffix}`,
entry_point: 'fireauth.exports',
compilation_level: OPTIMIZATION_LEVEL,
externs: [
'externs/externs.js',
'externs/grecaptcha.js',
'externs/gapi.iframes.js',
path.resolve(
__dirname,
'../firebase/externs/firebase-app-externs.js'
),
path.resolve(
__dirname,
'../firebase/externs/firebase-error-externs.js'
),
path.resolve(
__dirname,
'../firebase/externs/firebase-app-internal-externs.js'
)
],
language_out: 'ES5',
only_closure_dependencies: true
})
)
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'));
} | [
"function",
"createBuildTask",
"(",
"filename",
",",
"prefix",
",",
"suffix",
")",
"{",
"return",
"(",
")",
"=>",
"gulp",
".",
"src",
"(",
"[",
"`",
"${",
"closureLibRoot",
"}",
"`",
",",
"`",
"${",
"closureLibRoot",
"}",
"`",
",",
"'src/**/*.js'",
"]",
",",
"{",
"base",
":",
"'.'",
"}",
")",
".",
"pipe",
"(",
"sourcemaps",
".",
"init",
"(",
")",
")",
".",
"pipe",
"(",
"closureCompiler",
"(",
"{",
"js_output_file",
":",
"filename",
",",
"output_wrapper",
":",
"`",
"${",
"prefix",
"}",
"${",
"suffix",
"}",
"`",
",",
"entry_point",
":",
"'fireauth.exports'",
",",
"compilation_level",
":",
"OPTIMIZATION_LEVEL",
",",
"externs",
":",
"[",
"'externs/externs.js'",
",",
"'externs/grecaptcha.js'",
",",
"'externs/gapi.iframes.js'",
",",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"'../firebase/externs/firebase-app-externs.js'",
")",
",",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"'../firebase/externs/firebase-error-externs.js'",
")",
",",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"'../firebase/externs/firebase-app-internal-externs.js'",
")",
"]",
",",
"language_out",
":",
"'ES5'",
",",
"only_closure_dependencies",
":",
"true",
"}",
")",
")",
".",
"pipe",
"(",
"sourcemaps",
".",
"write",
"(",
"'.'",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"'dist'",
")",
")",
";",
"}"
] | Builds the core Firebase-auth JS.
@param {string} filename name of the generated file
@param {string} prefix prefix to the compiled code
@param {string} suffix suffix to the compiled code | [
"Builds",
"the",
"core",
"Firebase",
"-",
"auth",
"JS",
"."
] | 491598a499813dacc23724de5e237ec220cc560e | https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/gulpfile.js#L49-L87 |
2,745 | infinitered/ignite | src/cli/enforce-global.js | defaultVersionMatcher | function defaultVersionMatcher(raw) {
// sanity check
if (ramda.isNil(raw) || ramda.isEmpty(raw)) return null
try {
// look for something that looks like semver
var rx = /([0-9]+\.[0-9]+\.[0-9]+)/
var match = ramda.match(rx, raw)
if (match.length > 0) {
return match[0]
} else {
return null
}
} catch (err) {
// something tragic happened
return false
}
} | javascript | function defaultVersionMatcher(raw) {
// sanity check
if (ramda.isNil(raw) || ramda.isEmpty(raw)) return null
try {
// look for something that looks like semver
var rx = /([0-9]+\.[0-9]+\.[0-9]+)/
var match = ramda.match(rx, raw)
if (match.length > 0) {
return match[0]
} else {
return null
}
} catch (err) {
// something tragic happened
return false
}
} | [
"function",
"defaultVersionMatcher",
"(",
"raw",
")",
"{",
"// sanity check",
"if",
"(",
"ramda",
".",
"isNil",
"(",
"raw",
")",
"||",
"ramda",
".",
"isEmpty",
"(",
"raw",
")",
")",
"return",
"null",
"try",
"{",
"// look for something that looks like semver",
"var",
"rx",
"=",
"/",
"([0-9]+\\.[0-9]+\\.[0-9]+)",
"/",
"var",
"match",
"=",
"ramda",
".",
"match",
"(",
"rx",
",",
"raw",
")",
"if",
"(",
"match",
".",
"length",
">",
"0",
")",
"{",
"return",
"match",
"[",
"0",
"]",
"}",
"else",
"{",
"return",
"null",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"// something tragic happened",
"return",
"false",
"}",
"}"
] | Extracts the version number from a somewhere within a string.
This looks for things that look like semver (e.g. 0.0.0) and picks the first one.
@param {string} raw - The raw text which came from running the version command. | [
"Extracts",
"the",
"version",
"number",
"from",
"a",
"somewhere",
"within",
"a",
"string",
"."
] | dca91da22f9ad9bab1eb9f43565689d563bd111d | https://github.com/infinitered/ignite/blob/dca91da22f9ad9bab1eb9f43565689d563bd111d/src/cli/enforce-global.js#L15-L32 |
2,746 | infinitered/ignite | src/cli/enforce-global.js | enforce | function enforce(opts = {}) {
// opts to pass in
var optional = opts.optional || false
var range = opts.range
var whichExec = opts.which
var packageName = opts.packageName || opts.which
var versionCommand = opts.versionCommand
var installMessage = opts.installMessage
var versionMatcher = opts.versionMatcher || defaultVersionMatcher
/**
* Prints a friendly message that they don't meet the requirement.
*
* @param {string} installedVersion - current version if installed.
*/
function printNotMetMessage(installedVersion) {
console.log('Ignite CLI requires ' + packageName + ' ' + range + ' to be installed.')
if (installedVersion) {
console.log('')
console.log('You currently have ' + installedVersion + ' installed.')
}
console.log('')
console.log(installMessage)
}
/**
* Gets the version from the global dependency.
*
* @return {string} The version number or null.
*/
function getVersion() {
// parse the version number
try {
// find the executable
var resolvedPath = which.sync(whichExec)
// grab the raw output
var result = shell.exec(`"${resolvedPath}" ${versionCommand}`, { silent: true })
var rawOut = ramda.trim(result.stdout || '')
var rawErr = ramda.trim(result.stderr || '') // java -version does this... grr
// assign the "right" one to raw
var raw = rawOut
if (ramda.isEmpty(raw)) {
raw = rawErr
}
if (ramda.isEmpty(raw)) {
raw = null
}
// and run it by the version matcher
return versionMatcher(raw)
} catch (err) {
return null
}
}
// are we installed?
var isInstalled = Boolean(shell.which(whichExec))
if (!isInstalled) {
if (optional) {
return true
} else {
printNotMetMessage()
return false
}
}
// which version is installed?
try {
var installedVersion = getVersion()
var isMet = semver.satisfies(installedVersion, range)
// dependency has minimum met, we're good.
if (isMet) return true
} catch (err) {
// can't parse? just catch and we'll fallback to an error.
}
// o snap, time to upgrade
printNotMetMessage(installedVersion)
return false
} | javascript | function enforce(opts = {}) {
// opts to pass in
var optional = opts.optional || false
var range = opts.range
var whichExec = opts.which
var packageName = opts.packageName || opts.which
var versionCommand = opts.versionCommand
var installMessage = opts.installMessage
var versionMatcher = opts.versionMatcher || defaultVersionMatcher
/**
* Prints a friendly message that they don't meet the requirement.
*
* @param {string} installedVersion - current version if installed.
*/
function printNotMetMessage(installedVersion) {
console.log('Ignite CLI requires ' + packageName + ' ' + range + ' to be installed.')
if (installedVersion) {
console.log('')
console.log('You currently have ' + installedVersion + ' installed.')
}
console.log('')
console.log(installMessage)
}
/**
* Gets the version from the global dependency.
*
* @return {string} The version number or null.
*/
function getVersion() {
// parse the version number
try {
// find the executable
var resolvedPath = which.sync(whichExec)
// grab the raw output
var result = shell.exec(`"${resolvedPath}" ${versionCommand}`, { silent: true })
var rawOut = ramda.trim(result.stdout || '')
var rawErr = ramda.trim(result.stderr || '') // java -version does this... grr
// assign the "right" one to raw
var raw = rawOut
if (ramda.isEmpty(raw)) {
raw = rawErr
}
if (ramda.isEmpty(raw)) {
raw = null
}
// and run it by the version matcher
return versionMatcher(raw)
} catch (err) {
return null
}
}
// are we installed?
var isInstalled = Boolean(shell.which(whichExec))
if (!isInstalled) {
if (optional) {
return true
} else {
printNotMetMessage()
return false
}
}
// which version is installed?
try {
var installedVersion = getVersion()
var isMet = semver.satisfies(installedVersion, range)
// dependency has minimum met, we're good.
if (isMet) return true
} catch (err) {
// can't parse? just catch and we'll fallback to an error.
}
// o snap, time to upgrade
printNotMetMessage(installedVersion)
return false
} | [
"function",
"enforce",
"(",
"opts",
"=",
"{",
"}",
")",
"{",
"// opts to pass in",
"var",
"optional",
"=",
"opts",
".",
"optional",
"||",
"false",
"var",
"range",
"=",
"opts",
".",
"range",
"var",
"whichExec",
"=",
"opts",
".",
"which",
"var",
"packageName",
"=",
"opts",
".",
"packageName",
"||",
"opts",
".",
"which",
"var",
"versionCommand",
"=",
"opts",
".",
"versionCommand",
"var",
"installMessage",
"=",
"opts",
".",
"installMessage",
"var",
"versionMatcher",
"=",
"opts",
".",
"versionMatcher",
"||",
"defaultVersionMatcher",
"/**\n * Prints a friendly message that they don't meet the requirement.\n *\n * @param {string} installedVersion - current version if installed.\n */",
"function",
"printNotMetMessage",
"(",
"installedVersion",
")",
"{",
"console",
".",
"log",
"(",
"'Ignite CLI requires '",
"+",
"packageName",
"+",
"' '",
"+",
"range",
"+",
"' to be installed.'",
")",
"if",
"(",
"installedVersion",
")",
"{",
"console",
".",
"log",
"(",
"''",
")",
"console",
".",
"log",
"(",
"'You currently have '",
"+",
"installedVersion",
"+",
"' installed.'",
")",
"}",
"console",
".",
"log",
"(",
"''",
")",
"console",
".",
"log",
"(",
"installMessage",
")",
"}",
"/**\n * Gets the version from the global dependency.\n *\n * @return {string} The version number or null.\n */",
"function",
"getVersion",
"(",
")",
"{",
"// parse the version number",
"try",
"{",
"// find the executable",
"var",
"resolvedPath",
"=",
"which",
".",
"sync",
"(",
"whichExec",
")",
"// grab the raw output",
"var",
"result",
"=",
"shell",
".",
"exec",
"(",
"`",
"${",
"resolvedPath",
"}",
"${",
"versionCommand",
"}",
"`",
",",
"{",
"silent",
":",
"true",
"}",
")",
"var",
"rawOut",
"=",
"ramda",
".",
"trim",
"(",
"result",
".",
"stdout",
"||",
"''",
")",
"var",
"rawErr",
"=",
"ramda",
".",
"trim",
"(",
"result",
".",
"stderr",
"||",
"''",
")",
"// java -version does this... grr",
"// assign the \"right\" one to raw",
"var",
"raw",
"=",
"rawOut",
"if",
"(",
"ramda",
".",
"isEmpty",
"(",
"raw",
")",
")",
"{",
"raw",
"=",
"rawErr",
"}",
"if",
"(",
"ramda",
".",
"isEmpty",
"(",
"raw",
")",
")",
"{",
"raw",
"=",
"null",
"}",
"// and run it by the version matcher",
"return",
"versionMatcher",
"(",
"raw",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"null",
"}",
"}",
"// are we installed?",
"var",
"isInstalled",
"=",
"Boolean",
"(",
"shell",
".",
"which",
"(",
"whichExec",
")",
")",
"if",
"(",
"!",
"isInstalled",
")",
"{",
"if",
"(",
"optional",
")",
"{",
"return",
"true",
"}",
"else",
"{",
"printNotMetMessage",
"(",
")",
"return",
"false",
"}",
"}",
"// which version is installed?",
"try",
"{",
"var",
"installedVersion",
"=",
"getVersion",
"(",
")",
"var",
"isMet",
"=",
"semver",
".",
"satisfies",
"(",
"installedVersion",
",",
"range",
")",
"// dependency has minimum met, we're good.",
"if",
"(",
"isMet",
")",
"return",
"true",
"}",
"catch",
"(",
"err",
")",
"{",
"// can't parse? just catch and we'll fallback to an error.",
"}",
"// o snap, time to upgrade",
"printNotMetMessage",
"(",
"installedVersion",
")",
"return",
"false",
"}"
] | Verifies the dependency which is installed is compatible with ignite.
@param {any} opts The options to enforce.
@param {boolean} opts.optional Is this an optional dependency?
@param {string} opts.range The semver range to test against.
@param {string} opts.which The command to run `which` on.
@param {string} opts.packageName The npm package we're checking for.
@param {string} opts.versionCommand The command to run which returns text containing the version number.
@param {string} opts.installMessage What to print should we fail.
@param {function} opts.versionMatcher A way to override the method to discover the version number.
@return {boolean} `true` if we meet the requirements; otherwise `false`. | [
"Verifies",
"the",
"dependency",
"which",
"is",
"installed",
"is",
"compatible",
"with",
"ignite",
"."
] | dca91da22f9ad9bab1eb9f43565689d563bd111d | https://github.com/infinitered/ignite/blob/dca91da22f9ad9bab1eb9f43565689d563bd111d/src/cli/enforce-global.js#L47-L130 |
2,747 | infinitered/ignite | src/cli/enforce-global.js | printNotMetMessage | function printNotMetMessage(installedVersion) {
console.log('Ignite CLI requires ' + packageName + ' ' + range + ' to be installed.')
if (installedVersion) {
console.log('')
console.log('You currently have ' + installedVersion + ' installed.')
}
console.log('')
console.log(installMessage)
} | javascript | function printNotMetMessage(installedVersion) {
console.log('Ignite CLI requires ' + packageName + ' ' + range + ' to be installed.')
if (installedVersion) {
console.log('')
console.log('You currently have ' + installedVersion + ' installed.')
}
console.log('')
console.log(installMessage)
} | [
"function",
"printNotMetMessage",
"(",
"installedVersion",
")",
"{",
"console",
".",
"log",
"(",
"'Ignite CLI requires '",
"+",
"packageName",
"+",
"' '",
"+",
"range",
"+",
"' to be installed.'",
")",
"if",
"(",
"installedVersion",
")",
"{",
"console",
".",
"log",
"(",
"''",
")",
"console",
".",
"log",
"(",
"'You currently have '",
"+",
"installedVersion",
"+",
"' installed.'",
")",
"}",
"console",
".",
"log",
"(",
"''",
")",
"console",
".",
"log",
"(",
"installMessage",
")",
"}"
] | Prints a friendly message that they don't meet the requirement.
@param {string} installedVersion - current version if installed. | [
"Prints",
"a",
"friendly",
"message",
"that",
"they",
"don",
"t",
"meet",
"the",
"requirement",
"."
] | dca91da22f9ad9bab1eb9f43565689d563bd111d | https://github.com/infinitered/ignite/blob/dca91da22f9ad9bab1eb9f43565689d563bd111d/src/cli/enforce-global.js#L62-L70 |
2,748 | infinitered/ignite | src/cli/enforce-global.js | getVersion | function getVersion() {
// parse the version number
try {
// find the executable
var resolvedPath = which.sync(whichExec)
// grab the raw output
var result = shell.exec(`"${resolvedPath}" ${versionCommand}`, { silent: true })
var rawOut = ramda.trim(result.stdout || '')
var rawErr = ramda.trim(result.stderr || '') // java -version does this... grr
// assign the "right" one to raw
var raw = rawOut
if (ramda.isEmpty(raw)) {
raw = rawErr
}
if (ramda.isEmpty(raw)) {
raw = null
}
// and run it by the version matcher
return versionMatcher(raw)
} catch (err) {
return null
}
} | javascript | function getVersion() {
// parse the version number
try {
// find the executable
var resolvedPath = which.sync(whichExec)
// grab the raw output
var result = shell.exec(`"${resolvedPath}" ${versionCommand}`, { silent: true })
var rawOut = ramda.trim(result.stdout || '')
var rawErr = ramda.trim(result.stderr || '') // java -version does this... grr
// assign the "right" one to raw
var raw = rawOut
if (ramda.isEmpty(raw)) {
raw = rawErr
}
if (ramda.isEmpty(raw)) {
raw = null
}
// and run it by the version matcher
return versionMatcher(raw)
} catch (err) {
return null
}
} | [
"function",
"getVersion",
"(",
")",
"{",
"// parse the version number",
"try",
"{",
"// find the executable",
"var",
"resolvedPath",
"=",
"which",
".",
"sync",
"(",
"whichExec",
")",
"// grab the raw output",
"var",
"result",
"=",
"shell",
".",
"exec",
"(",
"`",
"${",
"resolvedPath",
"}",
"${",
"versionCommand",
"}",
"`",
",",
"{",
"silent",
":",
"true",
"}",
")",
"var",
"rawOut",
"=",
"ramda",
".",
"trim",
"(",
"result",
".",
"stdout",
"||",
"''",
")",
"var",
"rawErr",
"=",
"ramda",
".",
"trim",
"(",
"result",
".",
"stderr",
"||",
"''",
")",
"// java -version does this... grr",
"// assign the \"right\" one to raw",
"var",
"raw",
"=",
"rawOut",
"if",
"(",
"ramda",
".",
"isEmpty",
"(",
"raw",
")",
")",
"{",
"raw",
"=",
"rawErr",
"}",
"if",
"(",
"ramda",
".",
"isEmpty",
"(",
"raw",
")",
")",
"{",
"raw",
"=",
"null",
"}",
"// and run it by the version matcher",
"return",
"versionMatcher",
"(",
"raw",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"null",
"}",
"}"
] | Gets the version from the global dependency.
@return {string} The version number or null. | [
"Gets",
"the",
"version",
"from",
"the",
"global",
"dependency",
"."
] | dca91da22f9ad9bab1eb9f43565689d563bd111d | https://github.com/infinitered/ignite/blob/dca91da22f9ad9bab1eb9f43565689d563bd111d/src/cli/enforce-global.js#L77-L102 |
2,749 | scrumpy/tiptap | packages/tiptap-extensions/src/plugins/Suggestions.js | triggerCharacter | function triggerCharacter({
char = '@',
allowSpaces = false,
startOfLine = false,
}) {
return $position => {
// Matching expressions used for later
const escapedChar = `\\${char}`
const suffix = new RegExp(`\\s${escapedChar}$`)
const prefix = startOfLine ? '^' : ''
const regexp = allowSpaces
? new RegExp(`${prefix}${escapedChar}.*?(?=\\s${escapedChar}|$)`, 'gm')
: new RegExp(`${prefix}(?:^)?${escapedChar}[^\\s${escapedChar}]*`, 'gm')
// Lookup the boundaries of the current node
const textFrom = $position.before()
const textTo = $position.end()
const text = $position.doc.textBetween(textFrom, textTo, '\0', '\0')
let match = regexp.exec(text)
let position
while (match !== null) {
// JavaScript doesn't have lookbehinds; this hacks a check that first character is " "
// or the line beginning
const matchPrefix = match.input.slice(Math.max(0, match.index - 1), match.index)
if (/^[\s\0]?$/.test(matchPrefix)) {
// The absolute position of the match in the document
const from = match.index + $position.start()
let to = from + match[0].length
// Edge case handling; if spaces are allowed and we're directly in between
// two triggers
if (allowSpaces && suffix.test(text.slice(to - 1, to + 1))) {
match[0] += ' '
to += 1
}
// If the $position is located within the matched substring, return that range
if (from < $position.pos && to >= $position.pos) {
position = {
range: {
from,
to,
},
query: match[0].slice(char.length),
text: match[0],
}
}
}
match = regexp.exec(text)
}
return position
}
} | javascript | function triggerCharacter({
char = '@',
allowSpaces = false,
startOfLine = false,
}) {
return $position => {
// Matching expressions used for later
const escapedChar = `\\${char}`
const suffix = new RegExp(`\\s${escapedChar}$`)
const prefix = startOfLine ? '^' : ''
const regexp = allowSpaces
? new RegExp(`${prefix}${escapedChar}.*?(?=\\s${escapedChar}|$)`, 'gm')
: new RegExp(`${prefix}(?:^)?${escapedChar}[^\\s${escapedChar}]*`, 'gm')
// Lookup the boundaries of the current node
const textFrom = $position.before()
const textTo = $position.end()
const text = $position.doc.textBetween(textFrom, textTo, '\0', '\0')
let match = regexp.exec(text)
let position
while (match !== null) {
// JavaScript doesn't have lookbehinds; this hacks a check that first character is " "
// or the line beginning
const matchPrefix = match.input.slice(Math.max(0, match.index - 1), match.index)
if (/^[\s\0]?$/.test(matchPrefix)) {
// The absolute position of the match in the document
const from = match.index + $position.start()
let to = from + match[0].length
// Edge case handling; if spaces are allowed and we're directly in between
// two triggers
if (allowSpaces && suffix.test(text.slice(to - 1, to + 1))) {
match[0] += ' '
to += 1
}
// If the $position is located within the matched substring, return that range
if (from < $position.pos && to >= $position.pos) {
position = {
range: {
from,
to,
},
query: match[0].slice(char.length),
text: match[0],
}
}
}
match = regexp.exec(text)
}
return position
}
} | [
"function",
"triggerCharacter",
"(",
"{",
"char",
"=",
"'@'",
",",
"allowSpaces",
"=",
"false",
",",
"startOfLine",
"=",
"false",
",",
"}",
")",
"{",
"return",
"$position",
"=>",
"{",
"// Matching expressions used for later",
"const",
"escapedChar",
"=",
"`",
"\\\\",
"${",
"char",
"}",
"`",
"const",
"suffix",
"=",
"new",
"RegExp",
"(",
"`",
"\\\\",
"${",
"escapedChar",
"}",
"`",
")",
"const",
"prefix",
"=",
"startOfLine",
"?",
"'^'",
":",
"''",
"const",
"regexp",
"=",
"allowSpaces",
"?",
"new",
"RegExp",
"(",
"`",
"${",
"prefix",
"}",
"${",
"escapedChar",
"}",
"\\\\",
"${",
"escapedChar",
"}",
"`",
",",
"'gm'",
")",
":",
"new",
"RegExp",
"(",
"`",
"${",
"prefix",
"}",
"${",
"escapedChar",
"}",
"\\\\",
"${",
"escapedChar",
"}",
"`",
",",
"'gm'",
")",
"// Lookup the boundaries of the current node",
"const",
"textFrom",
"=",
"$position",
".",
"before",
"(",
")",
"const",
"textTo",
"=",
"$position",
".",
"end",
"(",
")",
"const",
"text",
"=",
"$position",
".",
"doc",
".",
"textBetween",
"(",
"textFrom",
",",
"textTo",
",",
"'\\0'",
",",
"'\\0'",
")",
"let",
"match",
"=",
"regexp",
".",
"exec",
"(",
"text",
")",
"let",
"position",
"while",
"(",
"match",
"!==",
"null",
")",
"{",
"// JavaScript doesn't have lookbehinds; this hacks a check that first character is \" \"",
"// or the line beginning",
"const",
"matchPrefix",
"=",
"match",
".",
"input",
".",
"slice",
"(",
"Math",
".",
"max",
"(",
"0",
",",
"match",
".",
"index",
"-",
"1",
")",
",",
"match",
".",
"index",
")",
"if",
"(",
"/",
"^[\\s\\0]?$",
"/",
".",
"test",
"(",
"matchPrefix",
")",
")",
"{",
"// The absolute position of the match in the document",
"const",
"from",
"=",
"match",
".",
"index",
"+",
"$position",
".",
"start",
"(",
")",
"let",
"to",
"=",
"from",
"+",
"match",
"[",
"0",
"]",
".",
"length",
"// Edge case handling; if spaces are allowed and we're directly in between",
"// two triggers",
"if",
"(",
"allowSpaces",
"&&",
"suffix",
".",
"test",
"(",
"text",
".",
"slice",
"(",
"to",
"-",
"1",
",",
"to",
"+",
"1",
")",
")",
")",
"{",
"match",
"[",
"0",
"]",
"+=",
"' '",
"to",
"+=",
"1",
"}",
"// If the $position is located within the matched substring, return that range",
"if",
"(",
"from",
"<",
"$position",
".",
"pos",
"&&",
"to",
">=",
"$position",
".",
"pos",
")",
"{",
"position",
"=",
"{",
"range",
":",
"{",
"from",
",",
"to",
",",
"}",
",",
"query",
":",
"match",
"[",
"0",
"]",
".",
"slice",
"(",
"char",
".",
"length",
")",
",",
"text",
":",
"match",
"[",
"0",
"]",
",",
"}",
"}",
"}",
"match",
"=",
"regexp",
".",
"exec",
"(",
"text",
")",
"}",
"return",
"position",
"}",
"}"
] | Create a matcher that matches when a specific character is typed. Useful for @mentions and #tags. | [
"Create",
"a",
"matcher",
"that",
"matches",
"when",
"a",
"specific",
"character",
"is",
"typed",
".",
"Useful",
"for"
] | f02461cc791f9efa0d87b6e811d27b7078eb9b86 | https://github.com/scrumpy/tiptap/blob/f02461cc791f9efa0d87b6e811d27b7078eb9b86/packages/tiptap-extensions/src/plugins/Suggestions.js#L6-L63 |
2,750 | GoogleChromeLabs/quicklink | demos/network-idle.js | networkIdleCallback | function networkIdleCallback(fn, options = {timeout: 0}) {
// Call the function immediately if required features are absent
if (
!('MessageChannel' in window) ||
!('serviceWorker' in navigator) ||
!navigator.serviceWorker.controller
) {
DOMContentLoad.then(() => fn({didTimeout: false}));
return;
}
const messageChannel = new MessageChannel();
navigator.serviceWorker.controller
.postMessage(
'NETWORK_IDLE_ENQUIRY',
[messageChannel.port2],
);
const timeoutId = setTimeout(() => {
const cbToPop = networkIdleCallback.__callbacks__
.find(cb => cb.id === timeoutId);
networkIdleCallback.__popCallback__(cbToPop, true);
}, options.timeout);
networkIdleCallback.__callbacks__.push({
id: timeoutId,
fn,
timeout: options.timeout,
});
messageChannel.port1.addEventListener('message', handleMessage);
messageChannel.port1.start();
} | javascript | function networkIdleCallback(fn, options = {timeout: 0}) {
// Call the function immediately if required features are absent
if (
!('MessageChannel' in window) ||
!('serviceWorker' in navigator) ||
!navigator.serviceWorker.controller
) {
DOMContentLoad.then(() => fn({didTimeout: false}));
return;
}
const messageChannel = new MessageChannel();
navigator.serviceWorker.controller
.postMessage(
'NETWORK_IDLE_ENQUIRY',
[messageChannel.port2],
);
const timeoutId = setTimeout(() => {
const cbToPop = networkIdleCallback.__callbacks__
.find(cb => cb.id === timeoutId);
networkIdleCallback.__popCallback__(cbToPop, true);
}, options.timeout);
networkIdleCallback.__callbacks__.push({
id: timeoutId,
fn,
timeout: options.timeout,
});
messageChannel.port1.addEventListener('message', handleMessage);
messageChannel.port1.start();
} | [
"function",
"networkIdleCallback",
"(",
"fn",
",",
"options",
"=",
"{",
"timeout",
":",
"0",
"}",
")",
"{",
"// Call the function immediately if required features are absent",
"if",
"(",
"!",
"(",
"'MessageChannel'",
"in",
"window",
")",
"||",
"!",
"(",
"'serviceWorker'",
"in",
"navigator",
")",
"||",
"!",
"navigator",
".",
"serviceWorker",
".",
"controller",
")",
"{",
"DOMContentLoad",
".",
"then",
"(",
"(",
")",
"=>",
"fn",
"(",
"{",
"didTimeout",
":",
"false",
"}",
")",
")",
";",
"return",
";",
"}",
"const",
"messageChannel",
"=",
"new",
"MessageChannel",
"(",
")",
";",
"navigator",
".",
"serviceWorker",
".",
"controller",
".",
"postMessage",
"(",
"'NETWORK_IDLE_ENQUIRY'",
",",
"[",
"messageChannel",
".",
"port2",
"]",
",",
")",
";",
"const",
"timeoutId",
"=",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"const",
"cbToPop",
"=",
"networkIdleCallback",
".",
"__callbacks__",
".",
"find",
"(",
"cb",
"=>",
"cb",
".",
"id",
"===",
"timeoutId",
")",
";",
"networkIdleCallback",
".",
"__popCallback__",
"(",
"cbToPop",
",",
"true",
")",
";",
"}",
",",
"options",
".",
"timeout",
")",
";",
"networkIdleCallback",
".",
"__callbacks__",
".",
"push",
"(",
"{",
"id",
":",
"timeoutId",
",",
"fn",
",",
"timeout",
":",
"options",
".",
"timeout",
",",
"}",
")",
";",
"messageChannel",
".",
"port1",
".",
"addEventListener",
"(",
"'message'",
",",
"handleMessage",
")",
";",
"messageChannel",
".",
"port1",
".",
"start",
"(",
")",
";",
"}"
] | networkIdleCallback works similar to requestIdleCallback,
detecting and notifying you when network activity goes idle
in your current tab.
@param {*} fn - A valid function
@param {*} options - An options object | [
"networkIdleCallback",
"works",
"similar",
"to",
"requestIdleCallback",
"detecting",
"and",
"notifying",
"you",
"when",
"network",
"activity",
"goes",
"idle",
"in",
"your",
"current",
"tab",
"."
] | f91f5c51964fc8e19ce136c52967f7ccd9179726 | https://github.com/GoogleChromeLabs/quicklink/blob/f91f5c51964fc8e19ce136c52967f7ccd9179726/demos/network-idle.js#L25-L58 |
2,751 | GoogleChromeLabs/quicklink | demos/network-idle.js | handleMessage | function handleMessage(event) {
if (!event.data) {
return;
}
switch (event.data) {
case 'NETWORK_IDLE_ENQUIRY_RESULT_IDLE':
case 'NETWORK_IDLE_CALLBACK':
networkIdleCallback.__callbacks__.forEach(callback => {
networkIdleCallback.__popCallback__(callback, false);
});
break;
}
} | javascript | function handleMessage(event) {
if (!event.data) {
return;
}
switch (event.data) {
case 'NETWORK_IDLE_ENQUIRY_RESULT_IDLE':
case 'NETWORK_IDLE_CALLBACK':
networkIdleCallback.__callbacks__.forEach(callback => {
networkIdleCallback.__popCallback__(callback, false);
});
break;
}
} | [
"function",
"handleMessage",
"(",
"event",
")",
"{",
"if",
"(",
"!",
"event",
".",
"data",
")",
"{",
"return",
";",
"}",
"switch",
"(",
"event",
".",
"data",
")",
"{",
"case",
"'NETWORK_IDLE_ENQUIRY_RESULT_IDLE'",
":",
"case",
"'NETWORK_IDLE_CALLBACK'",
":",
"networkIdleCallback",
".",
"__callbacks__",
".",
"forEach",
"(",
"callback",
"=>",
"{",
"networkIdleCallback",
".",
"__popCallback__",
"(",
"callback",
",",
"false",
")",
";",
"}",
")",
";",
"break",
";",
"}",
"}"
] | Handle message passing
@param {*} event - A valid event | [
"Handle",
"message",
"passing"
] | f91f5c51964fc8e19ce136c52967f7ccd9179726 | https://github.com/GoogleChromeLabs/quicklink/blob/f91f5c51964fc8e19ce136c52967f7ccd9179726/demos/network-idle.js#L93-L106 |
2,752 | badges/shields | frontend/lib/generate-image-markup.js | mapValues | function mapValues(obj, iteratee) {
const result = {}
for (const k in obj) {
result[k] = iteratee(obj[k])
}
return result
} | javascript | function mapValues(obj, iteratee) {
const result = {}
for (const k in obj) {
result[k] = iteratee(obj[k])
}
return result
} | [
"function",
"mapValues",
"(",
"obj",
",",
"iteratee",
")",
"{",
"const",
"result",
"=",
"{",
"}",
"for",
"(",
"const",
"k",
"in",
"obj",
")",
"{",
"result",
"[",
"k",
"]",
"=",
"iteratee",
"(",
"obj",
"[",
"k",
"]",
")",
"}",
"return",
"result",
"}"
] | lodash.mapvalues is huge! | [
"lodash",
".",
"mapvalues",
"is",
"huge!"
] | 283601423f3d1a19aae83bf62032d40683948636 | https://github.com/badges/shields/blob/283601423f3d1a19aae83bf62032d40683948636/frontend/lib/generate-image-markup.js#L46-L52 |
2,753 | badges/shields | gh-badges/lib/lru-cache.js | heuristic | function heuristic() {
if (this.type === typeEnum.unit) {
// Remove the excess.
return Math.max(0, this.cache.size - this.capacity)
} else if (this.type === typeEnum.heap) {
if (getHeapSize() >= this.capacity) {
console.log('LRU HEURISTIC heap:', getHeapSize())
// Remove half of them.
return this.cache.size >> 1
} else {
return 0
}
} else {
console.error(`Unknown heuristic '${this.type}' for LRU cache.`)
return 1
}
} | javascript | function heuristic() {
if (this.type === typeEnum.unit) {
// Remove the excess.
return Math.max(0, this.cache.size - this.capacity)
} else if (this.type === typeEnum.heap) {
if (getHeapSize() >= this.capacity) {
console.log('LRU HEURISTIC heap:', getHeapSize())
// Remove half of them.
return this.cache.size >> 1
} else {
return 0
}
} else {
console.error(`Unknown heuristic '${this.type}' for LRU cache.`)
return 1
}
} | [
"function",
"heuristic",
"(",
")",
"{",
"if",
"(",
"this",
".",
"type",
"===",
"typeEnum",
".",
"unit",
")",
"{",
"// Remove the excess.",
"return",
"Math",
".",
"max",
"(",
"0",
",",
"this",
".",
"cache",
".",
"size",
"-",
"this",
".",
"capacity",
")",
"}",
"else",
"if",
"(",
"this",
".",
"type",
"===",
"typeEnum",
".",
"heap",
")",
"{",
"if",
"(",
"getHeapSize",
"(",
")",
">=",
"this",
".",
"capacity",
")",
"{",
"console",
".",
"log",
"(",
"'LRU HEURISTIC heap:'",
",",
"getHeapSize",
"(",
")",
")",
"// Remove half of them.",
"return",
"this",
".",
"cache",
".",
"size",
">>",
"1",
"}",
"else",
"{",
"return",
"0",
"}",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"`",
"${",
"this",
".",
"type",
"}",
"`",
")",
"return",
"1",
"}",
"}"
] | Returns the number of elements to remove if we're past the limit. | [
"Returns",
"the",
"number",
"of",
"elements",
"to",
"remove",
"if",
"we",
"re",
"past",
"the",
"limit",
"."
] | 283601423f3d1a19aae83bf62032d40683948636 | https://github.com/badges/shields/blob/283601423f3d1a19aae83bf62032d40683948636/gh-badges/lib/lru-cache.js#L94-L110 |
2,754 | badges/shields | services/luarocks/luarocks-version-helpers.js | parseVersion | function parseVersion(versionString) {
versionString = versionString.toLowerCase().replace('-', '.')
const versionList = []
versionString.split('.').forEach(versionPart => {
const parsedPart = /(\d*)([a-z]*)(\d*)/.exec(versionPart)
if (parsedPart[1]) {
versionList.push(parseInt(parsedPart[1]))
}
if (parsedPart[2]) {
let weight
// calculate weight as a negative number
// 'rc' > 'pre' > 'beta' > 'alpha' > any other value
switch (parsedPart[2]) {
case 'alpha':
case 'beta':
case 'pre':
case 'rc':
weight = (parsedPart[2].charCodeAt(0) - 128) * 100
break
default:
weight = -10000
}
// add positive number, i.e. 'beta5' > 'beta2'
weight += parseInt(parsedPart[3]) || 0
versionList.push(weight)
}
})
return versionList
} | javascript | function parseVersion(versionString) {
versionString = versionString.toLowerCase().replace('-', '.')
const versionList = []
versionString.split('.').forEach(versionPart => {
const parsedPart = /(\d*)([a-z]*)(\d*)/.exec(versionPart)
if (parsedPart[1]) {
versionList.push(parseInt(parsedPart[1]))
}
if (parsedPart[2]) {
let weight
// calculate weight as a negative number
// 'rc' > 'pre' > 'beta' > 'alpha' > any other value
switch (parsedPart[2]) {
case 'alpha':
case 'beta':
case 'pre':
case 'rc':
weight = (parsedPart[2].charCodeAt(0) - 128) * 100
break
default:
weight = -10000
}
// add positive number, i.e. 'beta5' > 'beta2'
weight += parseInt(parsedPart[3]) || 0
versionList.push(weight)
}
})
return versionList
} | [
"function",
"parseVersion",
"(",
"versionString",
")",
"{",
"versionString",
"=",
"versionString",
".",
"toLowerCase",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"'.'",
")",
"const",
"versionList",
"=",
"[",
"]",
"versionString",
".",
"split",
"(",
"'.'",
")",
".",
"forEach",
"(",
"versionPart",
"=>",
"{",
"const",
"parsedPart",
"=",
"/",
"(\\d*)([a-z]*)(\\d*)",
"/",
".",
"exec",
"(",
"versionPart",
")",
"if",
"(",
"parsedPart",
"[",
"1",
"]",
")",
"{",
"versionList",
".",
"push",
"(",
"parseInt",
"(",
"parsedPart",
"[",
"1",
"]",
")",
")",
"}",
"if",
"(",
"parsedPart",
"[",
"2",
"]",
")",
"{",
"let",
"weight",
"// calculate weight as a negative number",
"// 'rc' > 'pre' > 'beta' > 'alpha' > any other value",
"switch",
"(",
"parsedPart",
"[",
"2",
"]",
")",
"{",
"case",
"'alpha'",
":",
"case",
"'beta'",
":",
"case",
"'pre'",
":",
"case",
"'rc'",
":",
"weight",
"=",
"(",
"parsedPart",
"[",
"2",
"]",
".",
"charCodeAt",
"(",
"0",
")",
"-",
"128",
")",
"*",
"100",
"break",
"default",
":",
"weight",
"=",
"-",
"10000",
"}",
"// add positive number, i.e. 'beta5' > 'beta2'",
"weight",
"+=",
"parseInt",
"(",
"parsedPart",
"[",
"3",
"]",
")",
"||",
"0",
"versionList",
".",
"push",
"(",
"weight",
")",
"}",
"}",
")",
"return",
"versionList",
"}"
] | Parse a dotted version string to an array of numbers 'rc', 'pre', 'beta', 'alpha' are converted to negative numbers | [
"Parse",
"a",
"dotted",
"version",
"string",
"to",
"an",
"array",
"of",
"numbers",
"rc",
"pre",
"beta",
"alpha",
"are",
"converted",
"to",
"negative",
"numbers"
] | 283601423f3d1a19aae83bf62032d40683948636 | https://github.com/badges/shields/blob/283601423f3d1a19aae83bf62032d40683948636/services/luarocks/luarocks-version-helpers.js#L31-L59 |
2,755 | badges/shields | services/pypi/pypi-helpers.js | sortDjangoVersions | function sortDjangoVersions(versions) {
return versions.sort((a, b) => {
if (
parseDjangoVersionString(a).major === parseDjangoVersionString(b).major
) {
return (
parseDjangoVersionString(a).minor - parseDjangoVersionString(b).minor
)
} else {
return (
parseDjangoVersionString(a).major - parseDjangoVersionString(b).major
)
}
})
} | javascript | function sortDjangoVersions(versions) {
return versions.sort((a, b) => {
if (
parseDjangoVersionString(a).major === parseDjangoVersionString(b).major
) {
return (
parseDjangoVersionString(a).minor - parseDjangoVersionString(b).minor
)
} else {
return (
parseDjangoVersionString(a).major - parseDjangoVersionString(b).major
)
}
})
} | [
"function",
"sortDjangoVersions",
"(",
"versions",
")",
"{",
"return",
"versions",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"if",
"(",
"parseDjangoVersionString",
"(",
"a",
")",
".",
"major",
"===",
"parseDjangoVersionString",
"(",
"b",
")",
".",
"major",
")",
"{",
"return",
"(",
"parseDjangoVersionString",
"(",
"a",
")",
".",
"minor",
"-",
"parseDjangoVersionString",
"(",
"b",
")",
".",
"minor",
")",
"}",
"else",
"{",
"return",
"(",
"parseDjangoVersionString",
"(",
"a",
")",
".",
"major",
"-",
"parseDjangoVersionString",
"(",
"b",
")",
".",
"major",
")",
"}",
"}",
")",
"}"
] | Sort an array of django versions low to high. | [
"Sort",
"an",
"array",
"of",
"django",
"versions",
"low",
"to",
"high",
"."
] | 283601423f3d1a19aae83bf62032d40683948636 | https://github.com/badges/shields/blob/283601423f3d1a19aae83bf62032d40683948636/services/pypi/pypi-helpers.js#L25-L39 |
2,756 | badges/shields | services/pypi/pypi-helpers.js | parseClassifiers | function parseClassifiers(parsedData, pattern) {
const results = []
for (let i = 0; i < parsedData.info.classifiers.length; i++) {
const matched = pattern.exec(parsedData.info.classifiers[i])
if (matched && matched[1]) {
results.push(matched[1].toLowerCase())
}
}
return results
} | javascript | function parseClassifiers(parsedData, pattern) {
const results = []
for (let i = 0; i < parsedData.info.classifiers.length; i++) {
const matched = pattern.exec(parsedData.info.classifiers[i])
if (matched && matched[1]) {
results.push(matched[1].toLowerCase())
}
}
return results
} | [
"function",
"parseClassifiers",
"(",
"parsedData",
",",
"pattern",
")",
"{",
"const",
"results",
"=",
"[",
"]",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"parsedData",
".",
"info",
".",
"classifiers",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"matched",
"=",
"pattern",
".",
"exec",
"(",
"parsedData",
".",
"info",
".",
"classifiers",
"[",
"i",
"]",
")",
"if",
"(",
"matched",
"&&",
"matched",
"[",
"1",
"]",
")",
"{",
"results",
".",
"push",
"(",
"matched",
"[",
"1",
"]",
".",
"toLowerCase",
"(",
")",
")",
"}",
"}",
"return",
"results",
"}"
] | Extract classifiers from a pypi json response based on a regex. | [
"Extract",
"classifiers",
"from",
"a",
"pypi",
"json",
"response",
"based",
"on",
"a",
"regex",
"."
] | 283601423f3d1a19aae83bf62032d40683948636 | https://github.com/badges/shields/blob/283601423f3d1a19aae83bf62032d40683948636/services/pypi/pypi-helpers.js#L42-L51 |
2,757 | elastic/elasticsearch-js | scripts/utils/generateDocs.js | fixLink | function fixLink (name, str) {
/* In 6.x some API start with `xpack.` when in master they do not. We
* can safely ignore that for link generation. */
name = name.replace(/^xpack\./, '')
const override = LINK_OVERRIDES[name]
if (override) return override
if (!str) return ''
/* Replace references to the guide with the attribute {ref} because
* the json files in the Elasticsearch repo are a bit of a mess. */
str = str.replace(/^.+guide\/en\/elasticsearch\/reference\/[^/]+\/([^./]*\.html(?:#.+)?)$/, '{ref}/$1')
str = str.replace(/frozen\.html/, 'freeze-index-api.html')
str = str.replace(/ml-file-structure\.html/, 'ml-find-file-structure.html')
str = str.replace(/security-api-get-user-privileges\.html/, 'security-api-get-privileges.html')
return str
} | javascript | function fixLink (name, str) {
/* In 6.x some API start with `xpack.` when in master they do not. We
* can safely ignore that for link generation. */
name = name.replace(/^xpack\./, '')
const override = LINK_OVERRIDES[name]
if (override) return override
if (!str) return ''
/* Replace references to the guide with the attribute {ref} because
* the json files in the Elasticsearch repo are a bit of a mess. */
str = str.replace(/^.+guide\/en\/elasticsearch\/reference\/[^/]+\/([^./]*\.html(?:#.+)?)$/, '{ref}/$1')
str = str.replace(/frozen\.html/, 'freeze-index-api.html')
str = str.replace(/ml-file-structure\.html/, 'ml-find-file-structure.html')
str = str.replace(/security-api-get-user-privileges\.html/, 'security-api-get-privileges.html')
return str
} | [
"function",
"fixLink",
"(",
"name",
",",
"str",
")",
"{",
"/* In 6.x some API start with `xpack.` when in master they do not. We\n * can safely ignore that for link generation. */",
"name",
"=",
"name",
".",
"replace",
"(",
"/",
"^xpack\\.",
"/",
",",
"''",
")",
"const",
"override",
"=",
"LINK_OVERRIDES",
"[",
"name",
"]",
"if",
"(",
"override",
")",
"return",
"override",
"if",
"(",
"!",
"str",
")",
"return",
"''",
"/* Replace references to the guide with the attribute {ref} because\n * the json files in the Elasticsearch repo are a bit of a mess. */",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"^.+guide\\/en\\/elasticsearch\\/reference\\/[^/]+\\/([^./]*\\.html(?:#.+)?)$",
"/",
",",
"'{ref}/$1'",
")",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"frozen\\.html",
"/",
",",
"'freeze-index-api.html'",
")",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"ml-file-structure\\.html",
"/",
",",
"'ml-find-file-structure.html'",
")",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"security-api-get-user-privileges\\.html",
"/",
",",
"'security-api-get-privileges.html'",
")",
"return",
"str",
"}"
] | Fixes bad urls in the JSON spec | [
"Fixes",
"bad",
"urls",
"in",
"the",
"JSON",
"spec"
] | 4fc4699a4d4474d7887bc7757e0269218a859294 | https://github.com/elastic/elasticsearch-js/blob/4fc4699a4d4474d7887bc7757e0269218a859294/scripts/utils/generateDocs.js#L163-L178 |
2,758 | eslint/eslint | lib/rules/no-useless-concat.js | getLeft | function getLeft(node) {
let left = node.left;
while (isConcatenation(left)) {
left = left.right;
}
return left;
} | javascript | function getLeft(node) {
let left = node.left;
while (isConcatenation(left)) {
left = left.right;
}
return left;
} | [
"function",
"getLeft",
"(",
"node",
")",
"{",
"let",
"left",
"=",
"node",
".",
"left",
";",
"while",
"(",
"isConcatenation",
"(",
"left",
")",
")",
"{",
"left",
"=",
"left",
".",
"right",
";",
"}",
"return",
"left",
";",
"}"
] | Get's the right most node on the left side of a BinaryExpression with + operator.
@param {ASTNode} node - A BinaryExpression node to check.
@returns {ASTNode} node | [
"Get",
"s",
"the",
"right",
"most",
"node",
"on",
"the",
"left",
"side",
"of",
"a",
"BinaryExpression",
"with",
"+",
"operator",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-concat.js#L40-L47 |
2,759 | eslint/eslint | lib/rules/no-useless-concat.js | getRight | function getRight(node) {
let right = node.right;
while (isConcatenation(right)) {
right = right.left;
}
return right;
} | javascript | function getRight(node) {
let right = node.right;
while (isConcatenation(right)) {
right = right.left;
}
return right;
} | [
"function",
"getRight",
"(",
"node",
")",
"{",
"let",
"right",
"=",
"node",
".",
"right",
";",
"while",
"(",
"isConcatenation",
"(",
"right",
")",
")",
"{",
"right",
"=",
"right",
".",
"left",
";",
"}",
"return",
"right",
";",
"}"
] | Get's the left most node on the right side of a BinaryExpression with + operator.
@param {ASTNode} node - A BinaryExpression node to check.
@returns {ASTNode} node | [
"Get",
"s",
"the",
"left",
"most",
"node",
"on",
"the",
"right",
"side",
"of",
"a",
"BinaryExpression",
"with",
"+",
"operator",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-concat.js#L54-L61 |
2,760 | eslint/eslint | lib/linter.js | createDisableDirectives | function createDisableDirectives(type, loc, value) {
const ruleIds = Object.keys(commentParser.parseListConfig(value));
const directiveRules = ruleIds.length ? ruleIds : [null];
return directiveRules.map(ruleId => ({ type, line: loc.line, column: loc.column + 1, ruleId }));
} | javascript | function createDisableDirectives(type, loc, value) {
const ruleIds = Object.keys(commentParser.parseListConfig(value));
const directiveRules = ruleIds.length ? ruleIds : [null];
return directiveRules.map(ruleId => ({ type, line: loc.line, column: loc.column + 1, ruleId }));
} | [
"function",
"createDisableDirectives",
"(",
"type",
",",
"loc",
",",
"value",
")",
"{",
"const",
"ruleIds",
"=",
"Object",
".",
"keys",
"(",
"commentParser",
".",
"parseListConfig",
"(",
"value",
")",
")",
";",
"const",
"directiveRules",
"=",
"ruleIds",
".",
"length",
"?",
"ruleIds",
":",
"[",
"null",
"]",
";",
"return",
"directiveRules",
".",
"map",
"(",
"ruleId",
"=>",
"(",
"{",
"type",
",",
"line",
":",
"loc",
".",
"line",
",",
"column",
":",
"loc",
".",
"column",
"+",
"1",
",",
"ruleId",
"}",
")",
")",
";",
"}"
] | Creates a collection of disable directives from a comment
@param {("disable"|"enable"|"disable-line"|"disable-next-line")} type The type of directive comment
@param {{line: number, column: number}} loc The 0-based location of the comment token
@param {string} value The value after the directive in the comment
comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`)
@returns {DisableDirective[]} Directives from the comment | [
"Creates",
"a",
"collection",
"of",
"disable",
"directives",
"from",
"a",
"comment"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L148-L153 |
2,761 | eslint/eslint | lib/linter.js | normalizeVerifyOptions | function normalizeVerifyOptions(providedOptions) {
const isObjectOptions = typeof providedOptions === "object";
const providedFilename = isObjectOptions ? providedOptions.filename : providedOptions;
return {
filename: typeof providedFilename === "string" ? providedFilename : "<input>",
allowInlineConfig: !isObjectOptions || providedOptions.allowInlineConfig !== false,
reportUnusedDisableDirectives: isObjectOptions && !!providedOptions.reportUnusedDisableDirectives
};
} | javascript | function normalizeVerifyOptions(providedOptions) {
const isObjectOptions = typeof providedOptions === "object";
const providedFilename = isObjectOptions ? providedOptions.filename : providedOptions;
return {
filename: typeof providedFilename === "string" ? providedFilename : "<input>",
allowInlineConfig: !isObjectOptions || providedOptions.allowInlineConfig !== false,
reportUnusedDisableDirectives: isObjectOptions && !!providedOptions.reportUnusedDisableDirectives
};
} | [
"function",
"normalizeVerifyOptions",
"(",
"providedOptions",
")",
"{",
"const",
"isObjectOptions",
"=",
"typeof",
"providedOptions",
"===",
"\"object\"",
";",
"const",
"providedFilename",
"=",
"isObjectOptions",
"?",
"providedOptions",
".",
"filename",
":",
"providedOptions",
";",
"return",
"{",
"filename",
":",
"typeof",
"providedFilename",
"===",
"\"string\"",
"?",
"providedFilename",
":",
"\"<input>\"",
",",
"allowInlineConfig",
":",
"!",
"isObjectOptions",
"||",
"providedOptions",
".",
"allowInlineConfig",
"!==",
"false",
",",
"reportUnusedDisableDirectives",
":",
"isObjectOptions",
"&&",
"!",
"!",
"providedOptions",
".",
"reportUnusedDisableDirectives",
"}",
";",
"}"
] | Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a
consistent shape.
@param {(string|{reportUnusedDisableDirectives: boolean, filename: string, allowInlineConfig: boolean})} providedOptions Options
@returns {{reportUnusedDisableDirectives: boolean, filename: string, allowInlineConfig: boolean}} Normalized options | [
"Normalizes",
"the",
"possible",
"options",
"for",
"linter",
".",
"verify",
"and",
"linter",
".",
"verifyAndFix",
"to",
"a",
"consistent",
"shape",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L339-L348 |
2,762 | eslint/eslint | lib/linter.js | resolveParserOptions | function resolveParserOptions(parserName, providedOptions, enabledEnvironments) {
const parserOptionsFromEnv = enabledEnvironments
.filter(env => env.parserOptions)
.reduce((parserOptions, env) => ConfigOps.merge(parserOptions, env.parserOptions), {});
const mergedParserOptions = ConfigOps.merge(parserOptionsFromEnv, providedOptions || {});
const isModule = mergedParserOptions.sourceType === "module";
if (isModule) {
// can't have global return inside of modules
mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false });
}
mergedParserOptions.ecmaVersion = normalizeEcmaVersion(mergedParserOptions.ecmaVersion, isModule);
return mergedParserOptions;
} | javascript | function resolveParserOptions(parserName, providedOptions, enabledEnvironments) {
const parserOptionsFromEnv = enabledEnvironments
.filter(env => env.parserOptions)
.reduce((parserOptions, env) => ConfigOps.merge(parserOptions, env.parserOptions), {});
const mergedParserOptions = ConfigOps.merge(parserOptionsFromEnv, providedOptions || {});
const isModule = mergedParserOptions.sourceType === "module";
if (isModule) {
// can't have global return inside of modules
mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false });
}
mergedParserOptions.ecmaVersion = normalizeEcmaVersion(mergedParserOptions.ecmaVersion, isModule);
return mergedParserOptions;
} | [
"function",
"resolveParserOptions",
"(",
"parserName",
",",
"providedOptions",
",",
"enabledEnvironments",
")",
"{",
"const",
"parserOptionsFromEnv",
"=",
"enabledEnvironments",
".",
"filter",
"(",
"env",
"=>",
"env",
".",
"parserOptions",
")",
".",
"reduce",
"(",
"(",
"parserOptions",
",",
"env",
")",
"=>",
"ConfigOps",
".",
"merge",
"(",
"parserOptions",
",",
"env",
".",
"parserOptions",
")",
",",
"{",
"}",
")",
";",
"const",
"mergedParserOptions",
"=",
"ConfigOps",
".",
"merge",
"(",
"parserOptionsFromEnv",
",",
"providedOptions",
"||",
"{",
"}",
")",
";",
"const",
"isModule",
"=",
"mergedParserOptions",
".",
"sourceType",
"===",
"\"module\"",
";",
"if",
"(",
"isModule",
")",
"{",
"// can't have global return inside of modules",
"mergedParserOptions",
".",
"ecmaFeatures",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"mergedParserOptions",
".",
"ecmaFeatures",
",",
"{",
"globalReturn",
":",
"false",
"}",
")",
";",
"}",
"mergedParserOptions",
".",
"ecmaVersion",
"=",
"normalizeEcmaVersion",
"(",
"mergedParserOptions",
".",
"ecmaVersion",
",",
"isModule",
")",
";",
"return",
"mergedParserOptions",
";",
"}"
] | Combines the provided parserOptions with the options from environments
@param {string} parserName The parser name which uses this options.
@param {Object} providedOptions The provided 'parserOptions' key in a config
@param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
@returns {Object} Resulting parser options after merge | [
"Combines",
"the",
"provided",
"parserOptions",
"with",
"the",
"options",
"from",
"environments"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L357-L375 |
2,763 | eslint/eslint | lib/linter.js | resolveGlobals | function resolveGlobals(providedGlobals, enabledEnvironments) {
return Object.assign(
{},
...enabledEnvironments.filter(env => env.globals).map(env => env.globals),
providedGlobals
);
} | javascript | function resolveGlobals(providedGlobals, enabledEnvironments) {
return Object.assign(
{},
...enabledEnvironments.filter(env => env.globals).map(env => env.globals),
providedGlobals
);
} | [
"function",
"resolveGlobals",
"(",
"providedGlobals",
",",
"enabledEnvironments",
")",
"{",
"return",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"...",
"enabledEnvironments",
".",
"filter",
"(",
"env",
"=>",
"env",
".",
"globals",
")",
".",
"map",
"(",
"env",
"=>",
"env",
".",
"globals",
")",
",",
"providedGlobals",
")",
";",
"}"
] | Combines the provided globals object with the globals from environments
@param {Object} providedGlobals The 'globals' key in a config
@param {Environments[]} enabledEnvironments The environments enabled in configuration and with inline comments
@returns {Object} The resolved globals object | [
"Combines",
"the",
"provided",
"globals",
"object",
"with",
"the",
"globals",
"from",
"environments"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L383-L389 |
2,764 | eslint/eslint | lib/linter.js | analyzeScope | function analyzeScope(ast, parserOptions, visitorKeys) {
const ecmaFeatures = parserOptions.ecmaFeatures || {};
const ecmaVersion = parserOptions.ecmaVersion || 5;
return eslintScope.analyze(ast, {
ignoreEval: true,
nodejsScope: ecmaFeatures.globalReturn,
impliedStrict: ecmaFeatures.impliedStrict,
ecmaVersion,
sourceType: parserOptions.sourceType || "script",
childVisitorKeys: visitorKeys || evk.KEYS,
fallback: Traverser.getKeys
});
} | javascript | function analyzeScope(ast, parserOptions, visitorKeys) {
const ecmaFeatures = parserOptions.ecmaFeatures || {};
const ecmaVersion = parserOptions.ecmaVersion || 5;
return eslintScope.analyze(ast, {
ignoreEval: true,
nodejsScope: ecmaFeatures.globalReturn,
impliedStrict: ecmaFeatures.impliedStrict,
ecmaVersion,
sourceType: parserOptions.sourceType || "script",
childVisitorKeys: visitorKeys || evk.KEYS,
fallback: Traverser.getKeys
});
} | [
"function",
"analyzeScope",
"(",
"ast",
",",
"parserOptions",
",",
"visitorKeys",
")",
"{",
"const",
"ecmaFeatures",
"=",
"parserOptions",
".",
"ecmaFeatures",
"||",
"{",
"}",
";",
"const",
"ecmaVersion",
"=",
"parserOptions",
".",
"ecmaVersion",
"||",
"5",
";",
"return",
"eslintScope",
".",
"analyze",
"(",
"ast",
",",
"{",
"ignoreEval",
":",
"true",
",",
"nodejsScope",
":",
"ecmaFeatures",
".",
"globalReturn",
",",
"impliedStrict",
":",
"ecmaFeatures",
".",
"impliedStrict",
",",
"ecmaVersion",
",",
"sourceType",
":",
"parserOptions",
".",
"sourceType",
"||",
"\"script\"",
",",
"childVisitorKeys",
":",
"visitorKeys",
"||",
"evk",
".",
"KEYS",
",",
"fallback",
":",
"Traverser",
".",
"getKeys",
"}",
")",
";",
"}"
] | Analyze scope of the given AST.
@param {ASTNode} ast The `Program` node to analyze.
@param {Object} parserOptions The parser options.
@param {Object} visitorKeys The visitor keys.
@returns {ScopeManager} The analysis result. | [
"Analyze",
"scope",
"of",
"the",
"given",
"AST",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L430-L443 |
2,765 | eslint/eslint | lib/linter.js | getScope | function getScope(scopeManager, currentNode) {
// On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope.
const inner = currentNode.type !== "Program";
for (let node = currentNode; node; node = node.parent) {
const scope = scopeManager.acquire(node, inner);
if (scope) {
if (scope.type === "function-expression-name") {
return scope.childScopes[0];
}
return scope;
}
}
return scopeManager.scopes[0];
} | javascript | function getScope(scopeManager, currentNode) {
// On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope.
const inner = currentNode.type !== "Program";
for (let node = currentNode; node; node = node.parent) {
const scope = scopeManager.acquire(node, inner);
if (scope) {
if (scope.type === "function-expression-name") {
return scope.childScopes[0];
}
return scope;
}
}
return scopeManager.scopes[0];
} | [
"function",
"getScope",
"(",
"scopeManager",
",",
"currentNode",
")",
"{",
"// On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope.",
"const",
"inner",
"=",
"currentNode",
".",
"type",
"!==",
"\"Program\"",
";",
"for",
"(",
"let",
"node",
"=",
"currentNode",
";",
"node",
";",
"node",
"=",
"node",
".",
"parent",
")",
"{",
"const",
"scope",
"=",
"scopeManager",
".",
"acquire",
"(",
"node",
",",
"inner",
")",
";",
"if",
"(",
"scope",
")",
"{",
"if",
"(",
"scope",
".",
"type",
"===",
"\"function-expression-name\"",
")",
"{",
"return",
"scope",
".",
"childScopes",
"[",
"0",
"]",
";",
"}",
"return",
"scope",
";",
"}",
"}",
"return",
"scopeManager",
".",
"scopes",
"[",
"0",
"]",
";",
"}"
] | Gets the scope for the current node
@param {ScopeManager} scopeManager The scope manager for this AST
@param {ASTNode} currentNode The node to get the scope of
@returns {eslint-scope.Scope} The scope information for this node | [
"Gets",
"the",
"scope",
"for",
"the",
"current",
"node"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L546-L563 |
2,766 | eslint/eslint | lib/linter.js | markVariableAsUsed | function markVariableAsUsed(scopeManager, currentNode, parserOptions, name) {
const hasGlobalReturn = parserOptions.ecmaFeatures && parserOptions.ecmaFeatures.globalReturn;
const specialScope = hasGlobalReturn || parserOptions.sourceType === "module";
const currentScope = getScope(scopeManager, currentNode);
// Special Node.js scope means we need to start one level deeper
const initialScope = currentScope.type === "global" && specialScope ? currentScope.childScopes[0] : currentScope;
for (let scope = initialScope; scope; scope = scope.upper) {
const variable = scope.variables.find(scopeVar => scopeVar.name === name);
if (variable) {
variable.eslintUsed = true;
return true;
}
}
return false;
} | javascript | function markVariableAsUsed(scopeManager, currentNode, parserOptions, name) {
const hasGlobalReturn = parserOptions.ecmaFeatures && parserOptions.ecmaFeatures.globalReturn;
const specialScope = hasGlobalReturn || parserOptions.sourceType === "module";
const currentScope = getScope(scopeManager, currentNode);
// Special Node.js scope means we need to start one level deeper
const initialScope = currentScope.type === "global" && specialScope ? currentScope.childScopes[0] : currentScope;
for (let scope = initialScope; scope; scope = scope.upper) {
const variable = scope.variables.find(scopeVar => scopeVar.name === name);
if (variable) {
variable.eslintUsed = true;
return true;
}
}
return false;
} | [
"function",
"markVariableAsUsed",
"(",
"scopeManager",
",",
"currentNode",
",",
"parserOptions",
",",
"name",
")",
"{",
"const",
"hasGlobalReturn",
"=",
"parserOptions",
".",
"ecmaFeatures",
"&&",
"parserOptions",
".",
"ecmaFeatures",
".",
"globalReturn",
";",
"const",
"specialScope",
"=",
"hasGlobalReturn",
"||",
"parserOptions",
".",
"sourceType",
"===",
"\"module\"",
";",
"const",
"currentScope",
"=",
"getScope",
"(",
"scopeManager",
",",
"currentNode",
")",
";",
"// Special Node.js scope means we need to start one level deeper",
"const",
"initialScope",
"=",
"currentScope",
".",
"type",
"===",
"\"global\"",
"&&",
"specialScope",
"?",
"currentScope",
".",
"childScopes",
"[",
"0",
"]",
":",
"currentScope",
";",
"for",
"(",
"let",
"scope",
"=",
"initialScope",
";",
"scope",
";",
"scope",
"=",
"scope",
".",
"upper",
")",
"{",
"const",
"variable",
"=",
"scope",
".",
"variables",
".",
"find",
"(",
"scopeVar",
"=>",
"scopeVar",
".",
"name",
"===",
"name",
")",
";",
"if",
"(",
"variable",
")",
"{",
"variable",
".",
"eslintUsed",
"=",
"true",
";",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Marks a variable as used in the current scope
@param {ScopeManager} scopeManager The scope manager for this AST. The scope may be mutated by this function.
@param {ASTNode} currentNode The node currently being traversed
@param {Object} parserOptions The options used to parse this text
@param {string} name The name of the variable that should be marked as used.
@returns {boolean} True if the variable was found and marked as used, false if not. | [
"Marks",
"a",
"variable",
"as",
"used",
"in",
"the",
"current",
"scope"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L573-L591 |
2,767 | eslint/eslint | lib/linter.js | createRuleListeners | function createRuleListeners(rule, ruleContext) {
try {
return rule.create(ruleContext);
} catch (ex) {
ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`;
throw ex;
}
} | javascript | function createRuleListeners(rule, ruleContext) {
try {
return rule.create(ruleContext);
} catch (ex) {
ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`;
throw ex;
}
} | [
"function",
"createRuleListeners",
"(",
"rule",
",",
"ruleContext",
")",
"{",
"try",
"{",
"return",
"rule",
".",
"create",
"(",
"ruleContext",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"ex",
".",
"message",
"=",
"`",
"${",
"ruleContext",
".",
"id",
"}",
"${",
"ex",
".",
"message",
"}",
"`",
";",
"throw",
"ex",
";",
"}",
"}"
] | Runs a rule, and gets its listeners
@param {Rule} rule A normalized rule with a `create` method
@param {Context} ruleContext The context that should be passed to the rule
@returns {Object} A map of selector listeners provided by the rule | [
"Runs",
"a",
"rule",
"and",
"gets",
"its",
"listeners"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L599-L606 |
2,768 | eslint/eslint | lib/linter.js | getAncestors | function getAncestors(node) {
const ancestorsStartingAtParent = [];
for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
ancestorsStartingAtParent.push(ancestor);
}
return ancestorsStartingAtParent.reverse();
} | javascript | function getAncestors(node) {
const ancestorsStartingAtParent = [];
for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
ancestorsStartingAtParent.push(ancestor);
}
return ancestorsStartingAtParent.reverse();
} | [
"function",
"getAncestors",
"(",
"node",
")",
"{",
"const",
"ancestorsStartingAtParent",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"ancestor",
"=",
"node",
".",
"parent",
";",
"ancestor",
";",
"ancestor",
"=",
"ancestor",
".",
"parent",
")",
"{",
"ancestorsStartingAtParent",
".",
"push",
"(",
"ancestor",
")",
";",
"}",
"return",
"ancestorsStartingAtParent",
".",
"reverse",
"(",
")",
";",
"}"
] | Gets all the ancestors of a given node
@param {ASTNode} node The node
@returns {ASTNode[]} All the ancestor nodes in the AST, not including the provided node, starting
from the root node and going inwards to the parent node. | [
"Gets",
"all",
"the",
"ancestors",
"of",
"a",
"given",
"node"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L614-L622 |
2,769 | eslint/eslint | lib/rules/semi.js | isRedundantSemi | function isRedundantSemi(semiToken) {
const nextToken = sourceCode.getTokenAfter(semiToken);
return (
!nextToken ||
astUtils.isClosingBraceToken(nextToken) ||
astUtils.isSemicolonToken(nextToken)
);
} | javascript | function isRedundantSemi(semiToken) {
const nextToken = sourceCode.getTokenAfter(semiToken);
return (
!nextToken ||
astUtils.isClosingBraceToken(nextToken) ||
astUtils.isSemicolonToken(nextToken)
);
} | [
"function",
"isRedundantSemi",
"(",
"semiToken",
")",
"{",
"const",
"nextToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"semiToken",
")",
";",
"return",
"(",
"!",
"nextToken",
"||",
"astUtils",
".",
"isClosingBraceToken",
"(",
"nextToken",
")",
"||",
"astUtils",
".",
"isSemicolonToken",
"(",
"nextToken",
")",
")",
";",
"}"
] | Check whether a given semicolon token is redandant.
@param {Token} semiToken A semicolon token to check.
@returns {boolean} `true` if the next token is `;` or `}`. | [
"Check",
"whether",
"a",
"given",
"semicolon",
"token",
"is",
"redandant",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi.js#L134-L142 |
2,770 | eslint/eslint | lib/rules/semi.js | isEndOfArrowBlock | function isEndOfArrowBlock(lastToken) {
if (!astUtils.isClosingBraceToken(lastToken)) {
return false;
}
const node = sourceCode.getNodeByRangeIndex(lastToken.range[0]);
return (
node.type === "BlockStatement" &&
node.parent.type === "ArrowFunctionExpression"
);
} | javascript | function isEndOfArrowBlock(lastToken) {
if (!astUtils.isClosingBraceToken(lastToken)) {
return false;
}
const node = sourceCode.getNodeByRangeIndex(lastToken.range[0]);
return (
node.type === "BlockStatement" &&
node.parent.type === "ArrowFunctionExpression"
);
} | [
"function",
"isEndOfArrowBlock",
"(",
"lastToken",
")",
"{",
"if",
"(",
"!",
"astUtils",
".",
"isClosingBraceToken",
"(",
"lastToken",
")",
")",
"{",
"return",
"false",
";",
"}",
"const",
"node",
"=",
"sourceCode",
".",
"getNodeByRangeIndex",
"(",
"lastToken",
".",
"range",
"[",
"0",
"]",
")",
";",
"return",
"(",
"node",
".",
"type",
"===",
"\"BlockStatement\"",
"&&",
"node",
".",
"parent",
".",
"type",
"===",
"\"ArrowFunctionExpression\"",
")",
";",
"}"
] | Check whether a given token is the closing brace of an arrow function.
@param {Token} lastToken A token to check.
@returns {boolean} `true` if the token is the closing brace of an arrow function. | [
"Check",
"whether",
"a",
"given",
"token",
"is",
"the",
"closing",
"brace",
"of",
"an",
"arrow",
"function",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi.js#L149-L159 |
2,771 | eslint/eslint | lib/rules/semi.js | isOnSameLineWithNextToken | function isOnSameLineWithNextToken(node) {
const prevToken = sourceCode.getLastToken(node, 1);
const nextToken = sourceCode.getTokenAfter(node);
return !!nextToken && astUtils.isTokenOnSameLine(prevToken, nextToken);
} | javascript | function isOnSameLineWithNextToken(node) {
const prevToken = sourceCode.getLastToken(node, 1);
const nextToken = sourceCode.getTokenAfter(node);
return !!nextToken && astUtils.isTokenOnSameLine(prevToken, nextToken);
} | [
"function",
"isOnSameLineWithNextToken",
"(",
"node",
")",
"{",
"const",
"prevToken",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"node",
",",
"1",
")",
";",
"const",
"nextToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"node",
")",
";",
"return",
"!",
"!",
"nextToken",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"prevToken",
",",
"nextToken",
")",
";",
"}"
] | Check whether a given node is on the same line with the next token.
@param {Node} node A statement node to check.
@returns {boolean} `true` if the node is on the same line with the next token. | [
"Check",
"whether",
"a",
"given",
"node",
"is",
"on",
"the",
"same",
"line",
"with",
"the",
"next",
"token",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi.js#L166-L171 |
2,772 | eslint/eslint | lib/rules/semi.js | maybeAsiHazardAfter | function maybeAsiHazardAfter(node) {
const t = node.type;
if (t === "DoWhileStatement" ||
t === "BreakStatement" ||
t === "ContinueStatement" ||
t === "DebuggerStatement" ||
t === "ImportDeclaration" ||
t === "ExportAllDeclaration"
) {
return false;
}
if (t === "ReturnStatement") {
return Boolean(node.argument);
}
if (t === "ExportNamedDeclaration") {
return Boolean(node.declaration);
}
if (isEndOfArrowBlock(sourceCode.getLastToken(node, 1))) {
return false;
}
return true;
} | javascript | function maybeAsiHazardAfter(node) {
const t = node.type;
if (t === "DoWhileStatement" ||
t === "BreakStatement" ||
t === "ContinueStatement" ||
t === "DebuggerStatement" ||
t === "ImportDeclaration" ||
t === "ExportAllDeclaration"
) {
return false;
}
if (t === "ReturnStatement") {
return Boolean(node.argument);
}
if (t === "ExportNamedDeclaration") {
return Boolean(node.declaration);
}
if (isEndOfArrowBlock(sourceCode.getLastToken(node, 1))) {
return false;
}
return true;
} | [
"function",
"maybeAsiHazardAfter",
"(",
"node",
")",
"{",
"const",
"t",
"=",
"node",
".",
"type",
";",
"if",
"(",
"t",
"===",
"\"DoWhileStatement\"",
"||",
"t",
"===",
"\"BreakStatement\"",
"||",
"t",
"===",
"\"ContinueStatement\"",
"||",
"t",
"===",
"\"DebuggerStatement\"",
"||",
"t",
"===",
"\"ImportDeclaration\"",
"||",
"t",
"===",
"\"ExportAllDeclaration\"",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"t",
"===",
"\"ReturnStatement\"",
")",
"{",
"return",
"Boolean",
"(",
"node",
".",
"argument",
")",
";",
"}",
"if",
"(",
"t",
"===",
"\"ExportNamedDeclaration\"",
")",
"{",
"return",
"Boolean",
"(",
"node",
".",
"declaration",
")",
";",
"}",
"if",
"(",
"isEndOfArrowBlock",
"(",
"sourceCode",
".",
"getLastToken",
"(",
"node",
",",
"1",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Check whether a given node can connect the next line if the next line is unreliable.
@param {Node} node A statement node to check.
@returns {boolean} `true` if the node can connect the next line. | [
"Check",
"whether",
"a",
"given",
"node",
"can",
"connect",
"the",
"next",
"line",
"if",
"the",
"next",
"line",
"is",
"unreliable",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi.js#L178-L201 |
2,773 | eslint/eslint | lib/rules/semi.js | maybeAsiHazardBefore | function maybeAsiHazardBefore(token) {
return (
Boolean(token) &&
OPT_OUT_PATTERN.test(token.value) &&
token.value !== "++" &&
token.value !== "--"
);
} | javascript | function maybeAsiHazardBefore(token) {
return (
Boolean(token) &&
OPT_OUT_PATTERN.test(token.value) &&
token.value !== "++" &&
token.value !== "--"
);
} | [
"function",
"maybeAsiHazardBefore",
"(",
"token",
")",
"{",
"return",
"(",
"Boolean",
"(",
"token",
")",
"&&",
"OPT_OUT_PATTERN",
".",
"test",
"(",
"token",
".",
"value",
")",
"&&",
"token",
".",
"value",
"!==",
"\"++\"",
"&&",
"token",
".",
"value",
"!==",
"\"--\"",
")",
";",
"}"
] | Check whether a given token can connect the previous statement.
@param {Token} token A token to check.
@returns {boolean} `true` if the token is one of `[`, `(`, `/`, `+`, `-`, ```, `++`, and `--`. | [
"Check",
"whether",
"a",
"given",
"token",
"can",
"connect",
"the",
"previous",
"statement",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi.js#L208-L215 |
2,774 | eslint/eslint | lib/rules/semi.js | isOneLinerBlock | function isOneLinerBlock(node) {
const parent = node.parent;
const nextToken = sourceCode.getTokenAfter(node);
if (!nextToken || nextToken.value !== "}") {
return false;
}
return (
!!parent &&
parent.type === "BlockStatement" &&
parent.loc.start.line === parent.loc.end.line
);
} | javascript | function isOneLinerBlock(node) {
const parent = node.parent;
const nextToken = sourceCode.getTokenAfter(node);
if (!nextToken || nextToken.value !== "}") {
return false;
}
return (
!!parent &&
parent.type === "BlockStatement" &&
parent.loc.start.line === parent.loc.end.line
);
} | [
"function",
"isOneLinerBlock",
"(",
"node",
")",
"{",
"const",
"parent",
"=",
"node",
".",
"parent",
";",
"const",
"nextToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"node",
")",
";",
"if",
"(",
"!",
"nextToken",
"||",
"nextToken",
".",
"value",
"!==",
"\"}\"",
")",
"{",
"return",
"false",
";",
"}",
"return",
"(",
"!",
"!",
"parent",
"&&",
"parent",
".",
"type",
"===",
"\"BlockStatement\"",
"&&",
"parent",
".",
"loc",
".",
"start",
".",
"line",
"===",
"parent",
".",
"loc",
".",
"end",
".",
"line",
")",
";",
"}"
] | Checks a node to see if it's in a one-liner block statement.
@param {ASTNode} node The node to check.
@returns {boolean} whether the node is in a one-liner block statement. | [
"Checks",
"a",
"node",
"to",
"see",
"if",
"it",
"s",
"in",
"a",
"one",
"-",
"liner",
"block",
"statement",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi.js#L246-L258 |
2,775 | eslint/eslint | lib/rules/no-mixed-operators.js | normalizeOptions | function normalizeOptions(options = {}) {
const hasGroups = options.groups && options.groups.length > 0;
const groups = hasGroups ? options.groups : DEFAULT_GROUPS;
const allowSamePrecedence = options.allowSamePrecedence !== false;
return {
groups,
allowSamePrecedence
};
} | javascript | function normalizeOptions(options = {}) {
const hasGroups = options.groups && options.groups.length > 0;
const groups = hasGroups ? options.groups : DEFAULT_GROUPS;
const allowSamePrecedence = options.allowSamePrecedence !== false;
return {
groups,
allowSamePrecedence
};
} | [
"function",
"normalizeOptions",
"(",
"options",
"=",
"{",
"}",
")",
"{",
"const",
"hasGroups",
"=",
"options",
".",
"groups",
"&&",
"options",
".",
"groups",
".",
"length",
">",
"0",
";",
"const",
"groups",
"=",
"hasGroups",
"?",
"options",
".",
"groups",
":",
"DEFAULT_GROUPS",
";",
"const",
"allowSamePrecedence",
"=",
"options",
".",
"allowSamePrecedence",
"!==",
"false",
";",
"return",
"{",
"groups",
",",
"allowSamePrecedence",
"}",
";",
"}"
] | Normalizes options.
@param {Object|undefined} options - A options object to normalize.
@returns {Object} Normalized option object. | [
"Normalizes",
"options",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-mixed-operators.js#L45-L54 |
2,776 | eslint/eslint | lib/rules/no-mixed-operators.js | includesBothInAGroup | function includesBothInAGroup(groups, left, right) {
return groups.some(group => group.indexOf(left) !== -1 && group.indexOf(right) !== -1);
} | javascript | function includesBothInAGroup(groups, left, right) {
return groups.some(group => group.indexOf(left) !== -1 && group.indexOf(right) !== -1);
} | [
"function",
"includesBothInAGroup",
"(",
"groups",
",",
"left",
",",
"right",
")",
"{",
"return",
"groups",
".",
"some",
"(",
"group",
"=>",
"group",
".",
"indexOf",
"(",
"left",
")",
"!==",
"-",
"1",
"&&",
"group",
".",
"indexOf",
"(",
"right",
")",
"!==",
"-",
"1",
")",
";",
"}"
] | Checks whether any group which includes both given operator exists or not.
@param {Array.<string[]>} groups - A list of groups to check.
@param {string} left - An operator.
@param {string} right - Another operator.
@returns {boolean} `true` if such group existed. | [
"Checks",
"whether",
"any",
"group",
"which",
"includes",
"both",
"given",
"operator",
"exists",
"or",
"not",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-mixed-operators.js#L64-L66 |
2,777 | eslint/eslint | lib/rules/no-mixed-operators.js | shouldIgnore | function shouldIgnore(node) {
const a = node;
const b = node.parent;
return (
!includesBothInAGroup(options.groups, a.operator, b.operator) ||
(
options.allowSamePrecedence &&
astUtils.getPrecedence(a) === astUtils.getPrecedence(b)
)
);
} | javascript | function shouldIgnore(node) {
const a = node;
const b = node.parent;
return (
!includesBothInAGroup(options.groups, a.operator, b.operator) ||
(
options.allowSamePrecedence &&
astUtils.getPrecedence(a) === astUtils.getPrecedence(b)
)
);
} | [
"function",
"shouldIgnore",
"(",
"node",
")",
"{",
"const",
"a",
"=",
"node",
";",
"const",
"b",
"=",
"node",
".",
"parent",
";",
"return",
"(",
"!",
"includesBothInAGroup",
"(",
"options",
".",
"groups",
",",
"a",
".",
"operator",
",",
"b",
".",
"operator",
")",
"||",
"(",
"options",
".",
"allowSamePrecedence",
"&&",
"astUtils",
".",
"getPrecedence",
"(",
"a",
")",
"===",
"astUtils",
".",
"getPrecedence",
"(",
"b",
")",
")",
")",
";",
"}"
] | Checks whether a given node should be ignored by options or not.
@param {ASTNode} node - A node to check. This is a BinaryExpression
node or a LogicalExpression node. This parent node is one of
them, too.
@returns {boolean} `true` if the node should be ignored. | [
"Checks",
"whether",
"a",
"given",
"node",
"should",
"be",
"ignored",
"by",
"options",
"or",
"not",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-mixed-operators.js#L119-L130 |
2,778 | eslint/eslint | lib/rules/no-mixed-operators.js | isMixedWithParent | function isMixedWithParent(node) {
return (
node.operator !== node.parent.operator &&
!astUtils.isParenthesised(sourceCode, node)
);
} | javascript | function isMixedWithParent(node) {
return (
node.operator !== node.parent.operator &&
!astUtils.isParenthesised(sourceCode, node)
);
} | [
"function",
"isMixedWithParent",
"(",
"node",
")",
"{",
"return",
"(",
"node",
".",
"operator",
"!==",
"node",
".",
"parent",
".",
"operator",
"&&",
"!",
"astUtils",
".",
"isParenthesised",
"(",
"sourceCode",
",",
"node",
")",
")",
";",
"}"
] | Checks whether the operator of a given node is mixed with parent
node's operator or not.
@param {ASTNode} node - A node to check. This is a BinaryExpression
node or a LogicalExpression node. This parent node is one of
them, too.
@returns {boolean} `true` if the node was mixed. | [
"Checks",
"whether",
"the",
"operator",
"of",
"a",
"given",
"node",
"is",
"mixed",
"with",
"parent",
"node",
"s",
"operator",
"or",
"not",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-mixed-operators.js#L141-L146 |
2,779 | eslint/eslint | lib/rules/no-mixed-operators.js | reportBothOperators | function reportBothOperators(node) {
const parent = node.parent;
const left = (parent.left === node) ? node : parent;
const right = (parent.left !== node) ? node : parent;
const message =
"Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'.";
const data = {
leftOperator: left.operator,
rightOperator: right.operator
};
context.report({
node: left,
loc: getOperatorToken(left).loc.start,
message,
data
});
context.report({
node: right,
loc: getOperatorToken(right).loc.start,
message,
data
});
} | javascript | function reportBothOperators(node) {
const parent = node.parent;
const left = (parent.left === node) ? node : parent;
const right = (parent.left !== node) ? node : parent;
const message =
"Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'.";
const data = {
leftOperator: left.operator,
rightOperator: right.operator
};
context.report({
node: left,
loc: getOperatorToken(left).loc.start,
message,
data
});
context.report({
node: right,
loc: getOperatorToken(right).loc.start,
message,
data
});
} | [
"function",
"reportBothOperators",
"(",
"node",
")",
"{",
"const",
"parent",
"=",
"node",
".",
"parent",
";",
"const",
"left",
"=",
"(",
"parent",
".",
"left",
"===",
"node",
")",
"?",
"node",
":",
"parent",
";",
"const",
"right",
"=",
"(",
"parent",
".",
"left",
"!==",
"node",
")",
"?",
"node",
":",
"parent",
";",
"const",
"message",
"=",
"\"Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'.\"",
";",
"const",
"data",
"=",
"{",
"leftOperator",
":",
"left",
".",
"operator",
",",
"rightOperator",
":",
"right",
".",
"operator",
"}",
";",
"context",
".",
"report",
"(",
"{",
"node",
":",
"left",
",",
"loc",
":",
"getOperatorToken",
"(",
"left",
")",
".",
"loc",
".",
"start",
",",
"message",
",",
"data",
"}",
")",
";",
"context",
".",
"report",
"(",
"{",
"node",
":",
"right",
",",
"loc",
":",
"getOperatorToken",
"(",
"right",
")",
".",
"loc",
".",
"start",
",",
"message",
",",
"data",
"}",
")",
";",
"}"
] | Reports both the operator of a given node and the operator of the
parent node.
@param {ASTNode} node - A node to check. This is a BinaryExpression
node or a LogicalExpression node. This parent node is one of
them, too.
@returns {void} | [
"Reports",
"both",
"the",
"operator",
"of",
"a",
"given",
"node",
"and",
"the",
"operator",
"of",
"the",
"parent",
"node",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-mixed-operators.js#L168-L191 |
2,780 | eslint/eslint | lib/rules/no-mixed-operators.js | check | function check(node) {
if (TARGET_NODE_TYPE.test(node.parent.type) &&
isMixedWithParent(node) &&
!shouldIgnore(node)
) {
reportBothOperators(node);
}
} | javascript | function check(node) {
if (TARGET_NODE_TYPE.test(node.parent.type) &&
isMixedWithParent(node) &&
!shouldIgnore(node)
) {
reportBothOperators(node);
}
} | [
"function",
"check",
"(",
"node",
")",
"{",
"if",
"(",
"TARGET_NODE_TYPE",
".",
"test",
"(",
"node",
".",
"parent",
".",
"type",
")",
"&&",
"isMixedWithParent",
"(",
"node",
")",
"&&",
"!",
"shouldIgnore",
"(",
"node",
")",
")",
"{",
"reportBothOperators",
"(",
"node",
")",
";",
"}",
"}"
] | Checks between the operator of this node and the operator of the
parent node.
@param {ASTNode} node - A node to check.
@returns {void} | [
"Checks",
"between",
"the",
"operator",
"of",
"this",
"node",
"and",
"the",
"operator",
"of",
"the",
"parent",
"node",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-mixed-operators.js#L200-L207 |
2,781 | eslint/eslint | lib/rules/no-lone-blocks.js | isLoneBlock | function isLoneBlock(node) {
return node.parent.type === "BlockStatement" ||
node.parent.type === "Program" ||
// Don't report blocks in switch cases if the block is the only statement of the case.
node.parent.type === "SwitchCase" && !(node.parent.consequent[0] === node && node.parent.consequent.length === 1);
} | javascript | function isLoneBlock(node) {
return node.parent.type === "BlockStatement" ||
node.parent.type === "Program" ||
// Don't report blocks in switch cases if the block is the only statement of the case.
node.parent.type === "SwitchCase" && !(node.parent.consequent[0] === node && node.parent.consequent.length === 1);
} | [
"function",
"isLoneBlock",
"(",
"node",
")",
"{",
"return",
"node",
".",
"parent",
".",
"type",
"===",
"\"BlockStatement\"",
"||",
"node",
".",
"parent",
".",
"type",
"===",
"\"Program\"",
"||",
"// Don't report blocks in switch cases if the block is the only statement of the case.",
"node",
".",
"parent",
".",
"type",
"===",
"\"SwitchCase\"",
"&&",
"!",
"(",
"node",
".",
"parent",
".",
"consequent",
"[",
"0",
"]",
"===",
"node",
"&&",
"node",
".",
"parent",
".",
"consequent",
".",
"length",
"===",
"1",
")",
";",
"}"
] | Checks for any ocurrence of a BlockStatement in a place where lists of statements can appear
@param {ASTNode} node The node to check
@returns {boolean} True if the node is a lone block. | [
"Checks",
"for",
"any",
"ocurrence",
"of",
"a",
"BlockStatement",
"in",
"a",
"place",
"where",
"lists",
"of",
"statements",
"can",
"appear"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-lone-blocks.js#L48-L54 |
2,782 | eslint/eslint | lib/rules/no-lone-blocks.js | markLoneBlock | function markLoneBlock() {
if (loneBlocks.length === 0) {
return;
}
const block = context.getAncestors().pop();
if (loneBlocks[loneBlocks.length - 1] === block) {
loneBlocks.pop();
}
} | javascript | function markLoneBlock() {
if (loneBlocks.length === 0) {
return;
}
const block = context.getAncestors().pop();
if (loneBlocks[loneBlocks.length - 1] === block) {
loneBlocks.pop();
}
} | [
"function",
"markLoneBlock",
"(",
")",
"{",
"if",
"(",
"loneBlocks",
".",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"const",
"block",
"=",
"context",
".",
"getAncestors",
"(",
")",
".",
"pop",
"(",
")",
";",
"if",
"(",
"loneBlocks",
"[",
"loneBlocks",
".",
"length",
"-",
"1",
"]",
"===",
"block",
")",
"{",
"loneBlocks",
".",
"pop",
"(",
")",
";",
"}",
"}"
] | Checks the enclosing block of the current node for block-level bindings,
and "marks it" as valid if any.
@returns {void} | [
"Checks",
"the",
"enclosing",
"block",
"of",
"the",
"current",
"node",
"for",
"block",
"-",
"level",
"bindings",
"and",
"marks",
"it",
"as",
"valid",
"if",
"any",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-lone-blocks.js#L61-L71 |
2,783 | eslint/eslint | lib/code-path-analysis/code-path-state.js | getContinueContext | function getContinueContext(state, label) {
if (!label) {
return state.loopContext;
}
let context = state.loopContext;
while (context) {
if (context.label === label) {
return context;
}
context = context.upper;
}
/* istanbul ignore next: foolproof (syntax error) */
return null;
} | javascript | function getContinueContext(state, label) {
if (!label) {
return state.loopContext;
}
let context = state.loopContext;
while (context) {
if (context.label === label) {
return context;
}
context = context.upper;
}
/* istanbul ignore next: foolproof (syntax error) */
return null;
} | [
"function",
"getContinueContext",
"(",
"state",
",",
"label",
")",
"{",
"if",
"(",
"!",
"label",
")",
"{",
"return",
"state",
".",
"loopContext",
";",
"}",
"let",
"context",
"=",
"state",
".",
"loopContext",
";",
"while",
"(",
"context",
")",
"{",
"if",
"(",
"context",
".",
"label",
"===",
"label",
")",
"{",
"return",
"context",
";",
"}",
"context",
"=",
"context",
".",
"upper",
";",
"}",
"/* istanbul ignore next: foolproof (syntax error) */",
"return",
"null",
";",
"}"
] | Gets a loop-context for a `continue` statement.
@param {CodePathState} state - A state to get.
@param {string} label - The label of a `continue` statement.
@returns {LoopContext} A loop-context for a `continue` statement. | [
"Gets",
"a",
"loop",
"-",
"context",
"for",
"a",
"continue",
"statement",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-state.js#L50-L66 |
2,784 | eslint/eslint | lib/code-path-analysis/code-path-state.js | getBreakContext | function getBreakContext(state, label) {
let context = state.breakContext;
while (context) {
if (label ? context.label === label : context.breakable) {
return context;
}
context = context.upper;
}
/* istanbul ignore next: foolproof (syntax error) */
return null;
} | javascript | function getBreakContext(state, label) {
let context = state.breakContext;
while (context) {
if (label ? context.label === label : context.breakable) {
return context;
}
context = context.upper;
}
/* istanbul ignore next: foolproof (syntax error) */
return null;
} | [
"function",
"getBreakContext",
"(",
"state",
",",
"label",
")",
"{",
"let",
"context",
"=",
"state",
".",
"breakContext",
";",
"while",
"(",
"context",
")",
"{",
"if",
"(",
"label",
"?",
"context",
".",
"label",
"===",
"label",
":",
"context",
".",
"breakable",
")",
"{",
"return",
"context",
";",
"}",
"context",
"=",
"context",
".",
"upper",
";",
"}",
"/* istanbul ignore next: foolproof (syntax error) */",
"return",
"null",
";",
"}"
] | Gets a context for a `break` statement.
@param {CodePathState} state - A state to get.
@param {string} label - The label of a `break` statement.
@returns {LoopContext|SwitchContext} A context for a `break` statement. | [
"Gets",
"a",
"context",
"for",
"a",
"break",
"statement",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-state.js#L75-L87 |
2,785 | eslint/eslint | lib/code-path-analysis/code-path-state.js | getReturnContext | function getReturnContext(state) {
let context = state.tryContext;
while (context) {
if (context.hasFinalizer && context.position !== "finally") {
return context;
}
context = context.upper;
}
return state;
} | javascript | function getReturnContext(state) {
let context = state.tryContext;
while (context) {
if (context.hasFinalizer && context.position !== "finally") {
return context;
}
context = context.upper;
}
return state;
} | [
"function",
"getReturnContext",
"(",
"state",
")",
"{",
"let",
"context",
"=",
"state",
".",
"tryContext",
";",
"while",
"(",
"context",
")",
"{",
"if",
"(",
"context",
".",
"hasFinalizer",
"&&",
"context",
".",
"position",
"!==",
"\"finally\"",
")",
"{",
"return",
"context",
";",
"}",
"context",
"=",
"context",
".",
"upper",
";",
"}",
"return",
"state",
";",
"}"
] | Gets a context for a `return` statement.
@param {CodePathState} state - A state to get.
@returns {TryContext|CodePathState} A context for a `return` statement. | [
"Gets",
"a",
"context",
"for",
"a",
"return",
"statement",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-state.js#L95-L106 |
2,786 | eslint/eslint | lib/code-path-analysis/code-path-state.js | getThrowContext | function getThrowContext(state) {
let context = state.tryContext;
while (context) {
if (context.position === "try" ||
(context.hasFinalizer && context.position === "catch")
) {
return context;
}
context = context.upper;
}
return state;
} | javascript | function getThrowContext(state) {
let context = state.tryContext;
while (context) {
if (context.position === "try" ||
(context.hasFinalizer && context.position === "catch")
) {
return context;
}
context = context.upper;
}
return state;
} | [
"function",
"getThrowContext",
"(",
"state",
")",
"{",
"let",
"context",
"=",
"state",
".",
"tryContext",
";",
"while",
"(",
"context",
")",
"{",
"if",
"(",
"context",
".",
"position",
"===",
"\"try\"",
"||",
"(",
"context",
".",
"hasFinalizer",
"&&",
"context",
".",
"position",
"===",
"\"catch\"",
")",
")",
"{",
"return",
"context",
";",
"}",
"context",
"=",
"context",
".",
"upper",
";",
"}",
"return",
"state",
";",
"}"
] | Gets a context for a `throw` statement.
@param {CodePathState} state - A state to get.
@returns {TryContext|CodePathState} A context for a `throw` statement. | [
"Gets",
"a",
"context",
"for",
"a",
"throw",
"statement",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-state.js#L114-L127 |
2,787 | eslint/eslint | lib/code-path-analysis/code-path-state.js | removeConnection | function removeConnection(prevSegments, nextSegments) {
for (let i = 0; i < prevSegments.length; ++i) {
const prevSegment = prevSegments[i];
const nextSegment = nextSegments[i];
remove(prevSegment.nextSegments, nextSegment);
remove(prevSegment.allNextSegments, nextSegment);
remove(nextSegment.prevSegments, prevSegment);
remove(nextSegment.allPrevSegments, prevSegment);
}
} | javascript | function removeConnection(prevSegments, nextSegments) {
for (let i = 0; i < prevSegments.length; ++i) {
const prevSegment = prevSegments[i];
const nextSegment = nextSegments[i];
remove(prevSegment.nextSegments, nextSegment);
remove(prevSegment.allNextSegments, nextSegment);
remove(nextSegment.prevSegments, prevSegment);
remove(nextSegment.allPrevSegments, prevSegment);
}
} | [
"function",
"removeConnection",
"(",
"prevSegments",
",",
"nextSegments",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"prevSegments",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"prevSegment",
"=",
"prevSegments",
"[",
"i",
"]",
";",
"const",
"nextSegment",
"=",
"nextSegments",
"[",
"i",
"]",
";",
"remove",
"(",
"prevSegment",
".",
"nextSegments",
",",
"nextSegment",
")",
";",
"remove",
"(",
"prevSegment",
".",
"allNextSegments",
",",
"nextSegment",
")",
";",
"remove",
"(",
"nextSegment",
".",
"prevSegments",
",",
"prevSegment",
")",
";",
"remove",
"(",
"nextSegment",
".",
"allPrevSegments",
",",
"prevSegment",
")",
";",
"}",
"}"
] | Disconnect given segments.
This is used in a process for switch statements.
If there is the "default" chunk before other cases, the order is different
between node's and running's.
@param {CodePathSegment[]} prevSegments - Forward segments to disconnect.
@param {CodePathSegment[]} nextSegments - Backward segments to disconnect.
@returns {void} | [
"Disconnect",
"given",
"segments",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-state.js#L151-L161 |
2,788 | eslint/eslint | lib/rules/dot-notation.js | checkComputedProperty | function checkComputedProperty(node, value) {
if (
validIdentifier.test(value) &&
(allowKeywords || keywords.indexOf(String(value)) === -1) &&
!(allowPattern && allowPattern.test(value))
) {
const formattedValue = node.property.type === "Literal" ? JSON.stringify(value) : `\`${value}\``;
context.report({
node: node.property,
messageId: "useDot",
data: {
key: formattedValue
},
fix(fixer) {
const leftBracket = sourceCode.getTokenAfter(node.object, astUtils.isOpeningBracketToken);
const rightBracket = sourceCode.getLastToken(node);
if (sourceCode.getFirstTokenBetween(leftBracket, rightBracket, { includeComments: true, filter: astUtils.isCommentToken })) {
// Don't perform any fixes if there are comments inside the brackets.
return null;
}
const tokenAfterProperty = sourceCode.getTokenAfter(rightBracket);
const needsSpaceAfterProperty = tokenAfterProperty &&
rightBracket.range[1] === tokenAfterProperty.range[0] &&
!astUtils.canTokensBeAdjacent(String(value), tokenAfterProperty);
const textBeforeDot = astUtils.isDecimalInteger(node.object) ? " " : "";
const textAfterProperty = needsSpaceAfterProperty ? " " : "";
return fixer.replaceTextRange(
[leftBracket.range[0], rightBracket.range[1]],
`${textBeforeDot}.${value}${textAfterProperty}`
);
}
});
}
} | javascript | function checkComputedProperty(node, value) {
if (
validIdentifier.test(value) &&
(allowKeywords || keywords.indexOf(String(value)) === -1) &&
!(allowPattern && allowPattern.test(value))
) {
const formattedValue = node.property.type === "Literal" ? JSON.stringify(value) : `\`${value}\``;
context.report({
node: node.property,
messageId: "useDot",
data: {
key: formattedValue
},
fix(fixer) {
const leftBracket = sourceCode.getTokenAfter(node.object, astUtils.isOpeningBracketToken);
const rightBracket = sourceCode.getLastToken(node);
if (sourceCode.getFirstTokenBetween(leftBracket, rightBracket, { includeComments: true, filter: astUtils.isCommentToken })) {
// Don't perform any fixes if there are comments inside the brackets.
return null;
}
const tokenAfterProperty = sourceCode.getTokenAfter(rightBracket);
const needsSpaceAfterProperty = tokenAfterProperty &&
rightBracket.range[1] === tokenAfterProperty.range[0] &&
!astUtils.canTokensBeAdjacent(String(value), tokenAfterProperty);
const textBeforeDot = astUtils.isDecimalInteger(node.object) ? " " : "";
const textAfterProperty = needsSpaceAfterProperty ? " " : "";
return fixer.replaceTextRange(
[leftBracket.range[0], rightBracket.range[1]],
`${textBeforeDot}.${value}${textAfterProperty}`
);
}
});
}
} | [
"function",
"checkComputedProperty",
"(",
"node",
",",
"value",
")",
"{",
"if",
"(",
"validIdentifier",
".",
"test",
"(",
"value",
")",
"&&",
"(",
"allowKeywords",
"||",
"keywords",
".",
"indexOf",
"(",
"String",
"(",
"value",
")",
")",
"===",
"-",
"1",
")",
"&&",
"!",
"(",
"allowPattern",
"&&",
"allowPattern",
".",
"test",
"(",
"value",
")",
")",
")",
"{",
"const",
"formattedValue",
"=",
"node",
".",
"property",
".",
"type",
"===",
"\"Literal\"",
"?",
"JSON",
".",
"stringify",
"(",
"value",
")",
":",
"`",
"\\`",
"${",
"value",
"}",
"\\`",
"`",
";",
"context",
".",
"report",
"(",
"{",
"node",
":",
"node",
".",
"property",
",",
"messageId",
":",
"\"useDot\"",
",",
"data",
":",
"{",
"key",
":",
"formattedValue",
"}",
",",
"fix",
"(",
"fixer",
")",
"{",
"const",
"leftBracket",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"node",
".",
"object",
",",
"astUtils",
".",
"isOpeningBracketToken",
")",
";",
"const",
"rightBracket",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"node",
")",
";",
"if",
"(",
"sourceCode",
".",
"getFirstTokenBetween",
"(",
"leftBracket",
",",
"rightBracket",
",",
"{",
"includeComments",
":",
"true",
",",
"filter",
":",
"astUtils",
".",
"isCommentToken",
"}",
")",
")",
"{",
"// Don't perform any fixes if there are comments inside the brackets.",
"return",
"null",
";",
"}",
"const",
"tokenAfterProperty",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"rightBracket",
")",
";",
"const",
"needsSpaceAfterProperty",
"=",
"tokenAfterProperty",
"&&",
"rightBracket",
".",
"range",
"[",
"1",
"]",
"===",
"tokenAfterProperty",
".",
"range",
"[",
"0",
"]",
"&&",
"!",
"astUtils",
".",
"canTokensBeAdjacent",
"(",
"String",
"(",
"value",
")",
",",
"tokenAfterProperty",
")",
";",
"const",
"textBeforeDot",
"=",
"astUtils",
".",
"isDecimalInteger",
"(",
"node",
".",
"object",
")",
"?",
"\" \"",
":",
"\"\"",
";",
"const",
"textAfterProperty",
"=",
"needsSpaceAfterProperty",
"?",
"\" \"",
":",
"\"\"",
";",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"leftBracket",
".",
"range",
"[",
"0",
"]",
",",
"rightBracket",
".",
"range",
"[",
"1",
"]",
"]",
",",
"`",
"${",
"textBeforeDot",
"}",
"${",
"value",
"}",
"${",
"textAfterProperty",
"}",
"`",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Check if the property is valid dot notation
@param {ASTNode} node The dot notation node
@param {string} value Value which is to be checked
@returns {void} | [
"Check",
"if",
"the",
"property",
"is",
"valid",
"dot",
"notation"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/dot-notation.js#L73-L112 |
2,789 | eslint/eslint | lib/rules/operator-linebreak.js | validateNode | function validateNode(node, leftSide) {
/*
* When the left part of a binary expression is a single expression wrapped in
* parentheses (ex: `(a) + b`), leftToken will be the last token of the expression
* and operatorToken will be the closing parenthesis.
* The leftToken should be the last closing parenthesis, and the operatorToken
* should be the token right after that.
*/
const operatorToken = sourceCode.getTokenAfter(leftSide, astUtils.isNotClosingParenToken);
const leftToken = sourceCode.getTokenBefore(operatorToken);
const rightToken = sourceCode.getTokenAfter(operatorToken);
const operator = operatorToken.value;
const operatorStyleOverride = styleOverrides[operator];
const style = operatorStyleOverride || globalStyle;
const fix = getFixer(operatorToken, style);
// if single line
if (astUtils.isTokenOnSameLine(leftToken, operatorToken) &&
astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
// do nothing.
} else if (operatorStyleOverride !== "ignore" && !astUtils.isTokenOnSameLine(leftToken, operatorToken) &&
!astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
// lone operator
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "Bad line breaking before and after '{{operator}}'.",
data: {
operator
},
fix
});
} else if (style === "before" && astUtils.isTokenOnSameLine(leftToken, operatorToken)) {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "'{{operator}}' should be placed at the beginning of the line.",
data: {
operator
},
fix
});
} else if (style === "after" && astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "'{{operator}}' should be placed at the end of the line.",
data: {
operator
},
fix
});
} else if (style === "none") {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "There should be no line break before or after '{{operator}}'.",
data: {
operator
},
fix
});
}
} | javascript | function validateNode(node, leftSide) {
/*
* When the left part of a binary expression is a single expression wrapped in
* parentheses (ex: `(a) + b`), leftToken will be the last token of the expression
* and operatorToken will be the closing parenthesis.
* The leftToken should be the last closing parenthesis, and the operatorToken
* should be the token right after that.
*/
const operatorToken = sourceCode.getTokenAfter(leftSide, astUtils.isNotClosingParenToken);
const leftToken = sourceCode.getTokenBefore(operatorToken);
const rightToken = sourceCode.getTokenAfter(operatorToken);
const operator = operatorToken.value;
const operatorStyleOverride = styleOverrides[operator];
const style = operatorStyleOverride || globalStyle;
const fix = getFixer(operatorToken, style);
// if single line
if (astUtils.isTokenOnSameLine(leftToken, operatorToken) &&
astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
// do nothing.
} else if (operatorStyleOverride !== "ignore" && !astUtils.isTokenOnSameLine(leftToken, operatorToken) &&
!astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
// lone operator
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "Bad line breaking before and after '{{operator}}'.",
data: {
operator
},
fix
});
} else if (style === "before" && astUtils.isTokenOnSameLine(leftToken, operatorToken)) {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "'{{operator}}' should be placed at the beginning of the line.",
data: {
operator
},
fix
});
} else if (style === "after" && astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "'{{operator}}' should be placed at the end of the line.",
data: {
operator
},
fix
});
} else if (style === "none") {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "There should be no line break before or after '{{operator}}'.",
data: {
operator
},
fix
});
}
} | [
"function",
"validateNode",
"(",
"node",
",",
"leftSide",
")",
"{",
"/*\n * When the left part of a binary expression is a single expression wrapped in\n * parentheses (ex: `(a) + b`), leftToken will be the last token of the expression\n * and operatorToken will be the closing parenthesis.\n * The leftToken should be the last closing parenthesis, and the operatorToken\n * should be the token right after that.\n */",
"const",
"operatorToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"leftSide",
",",
"astUtils",
".",
"isNotClosingParenToken",
")",
";",
"const",
"leftToken",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"operatorToken",
")",
";",
"const",
"rightToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"operatorToken",
")",
";",
"const",
"operator",
"=",
"operatorToken",
".",
"value",
";",
"const",
"operatorStyleOverride",
"=",
"styleOverrides",
"[",
"operator",
"]",
";",
"const",
"style",
"=",
"operatorStyleOverride",
"||",
"globalStyle",
";",
"const",
"fix",
"=",
"getFixer",
"(",
"operatorToken",
",",
"style",
")",
";",
"// if single line",
"if",
"(",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"leftToken",
",",
"operatorToken",
")",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"operatorToken",
",",
"rightToken",
")",
")",
"{",
"// do nothing.",
"}",
"else",
"if",
"(",
"operatorStyleOverride",
"!==",
"\"ignore\"",
"&&",
"!",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"leftToken",
",",
"operatorToken",
")",
"&&",
"!",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"operatorToken",
",",
"rightToken",
")",
")",
"{",
"// lone operator",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"line",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"line",
",",
"column",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"column",
"}",
",",
"message",
":",
"\"Bad line breaking before and after '{{operator}}'.\"",
",",
"data",
":",
"{",
"operator",
"}",
",",
"fix",
"}",
")",
";",
"}",
"else",
"if",
"(",
"style",
"===",
"\"before\"",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"leftToken",
",",
"operatorToken",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"line",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"line",
",",
"column",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"column",
"}",
",",
"message",
":",
"\"'{{operator}}' should be placed at the beginning of the line.\"",
",",
"data",
":",
"{",
"operator",
"}",
",",
"fix",
"}",
")",
";",
"}",
"else",
"if",
"(",
"style",
"===",
"\"after\"",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"operatorToken",
",",
"rightToken",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"line",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"line",
",",
"column",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"column",
"}",
",",
"message",
":",
"\"'{{operator}}' should be placed at the end of the line.\"",
",",
"data",
":",
"{",
"operator",
"}",
",",
"fix",
"}",
")",
";",
"}",
"else",
"if",
"(",
"style",
"===",
"\"none\"",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"line",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"line",
",",
"column",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"column",
"}",
",",
"message",
":",
"\"There should be no line break before or after '{{operator}}'.\"",
",",
"data",
":",
"{",
"operator",
"}",
",",
"fix",
"}",
")",
";",
"}",
"}"
] | Checks the operator placement
@param {ASTNode} node The node to check
@param {ASTNode} leftSide The node that comes before the operator in `node`
@private
@returns {void} | [
"Checks",
"the",
"operator",
"placement"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/operator-linebreak.js#L139-L225 |
2,790 | eslint/eslint | lib/config/config-file.js | loadJSConfigFile | function loadJSConfigFile(filePath) {
debug(`Loading JS config file: ${filePath}`);
try {
return importFresh(filePath);
} catch (e) {
debug(`Error reading JavaScript file: ${filePath}`);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
throw e;
}
} | javascript | function loadJSConfigFile(filePath) {
debug(`Loading JS config file: ${filePath}`);
try {
return importFresh(filePath);
} catch (e) {
debug(`Error reading JavaScript file: ${filePath}`);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
throw e;
}
} | [
"function",
"loadJSConfigFile",
"(",
"filePath",
")",
"{",
"debug",
"(",
"`",
"${",
"filePath",
"}",
"`",
")",
";",
"try",
"{",
"return",
"importFresh",
"(",
"filePath",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"debug",
"(",
"`",
"${",
"filePath",
"}",
"`",
")",
";",
"e",
".",
"message",
"=",
"`",
"${",
"filePath",
"}",
"\\n",
"${",
"e",
".",
"message",
"}",
"`",
";",
"throw",
"e",
";",
"}",
"}"
] | Loads a JavaScript configuration from a file.
@param {string} filePath The filename to load.
@returns {Object} The configuration object from the file.
@throws {Error} If the file cannot be read.
@private | [
"Loads",
"a",
"JavaScript",
"configuration",
"from",
"a",
"file",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L154-L163 |
2,791 | eslint/eslint | lib/config/config-file.js | loadPackageJSONConfigFile | function loadPackageJSONConfigFile(filePath) {
debug(`Loading package.json config file: ${filePath}`);
try {
return loadJSONConfigFile(filePath).eslintConfig || null;
} catch (e) {
debug(`Error reading package.json file: ${filePath}`);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
throw e;
}
} | javascript | function loadPackageJSONConfigFile(filePath) {
debug(`Loading package.json config file: ${filePath}`);
try {
return loadJSONConfigFile(filePath).eslintConfig || null;
} catch (e) {
debug(`Error reading package.json file: ${filePath}`);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
throw e;
}
} | [
"function",
"loadPackageJSONConfigFile",
"(",
"filePath",
")",
"{",
"debug",
"(",
"`",
"${",
"filePath",
"}",
"`",
")",
";",
"try",
"{",
"return",
"loadJSONConfigFile",
"(",
"filePath",
")",
".",
"eslintConfig",
"||",
"null",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"debug",
"(",
"`",
"${",
"filePath",
"}",
"`",
")",
";",
"e",
".",
"message",
"=",
"`",
"${",
"filePath",
"}",
"\\n",
"${",
"e",
".",
"message",
"}",
"`",
";",
"throw",
"e",
";",
"}",
"}"
] | Loads a configuration from a package.json file.
@param {string} filePath The filename to load.
@returns {Object} The configuration object from the file.
@throws {Error} If the file cannot be read.
@private | [
"Loads",
"a",
"configuration",
"from",
"a",
"package",
".",
"json",
"file",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L172-L181 |
2,792 | eslint/eslint | lib/config/config-file.js | configMissingError | function configMissingError(configName) {
const error = new Error(`Failed to load config "${configName}" to extend from.`);
error.messageTemplate = "extend-config-missing";
error.messageData = {
configName
};
return error;
} | javascript | function configMissingError(configName) {
const error = new Error(`Failed to load config "${configName}" to extend from.`);
error.messageTemplate = "extend-config-missing";
error.messageData = {
configName
};
return error;
} | [
"function",
"configMissingError",
"(",
"configName",
")",
"{",
"const",
"error",
"=",
"new",
"Error",
"(",
"`",
"${",
"configName",
"}",
"`",
")",
";",
"error",
".",
"messageTemplate",
"=",
"\"extend-config-missing\"",
";",
"error",
".",
"messageData",
"=",
"{",
"configName",
"}",
";",
"return",
"error",
";",
"}"
] | Creates an error to notify about a missing config to extend from.
@param {string} configName The name of the missing config.
@returns {Error} The error object to throw
@private | [
"Creates",
"an",
"error",
"to",
"notify",
"about",
"a",
"missing",
"config",
"to",
"extend",
"from",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L189-L197 |
2,793 | eslint/eslint | lib/config/config-file.js | writeJSONConfigFile | function writeJSONConfigFile(config, filePath) {
debug(`Writing JSON config file: ${filePath}`);
const content = stringify(config, { cmp: sortByKey, space: 4 });
fs.writeFileSync(filePath, content, "utf8");
} | javascript | function writeJSONConfigFile(config, filePath) {
debug(`Writing JSON config file: ${filePath}`);
const content = stringify(config, { cmp: sortByKey, space: 4 });
fs.writeFileSync(filePath, content, "utf8");
} | [
"function",
"writeJSONConfigFile",
"(",
"config",
",",
"filePath",
")",
"{",
"debug",
"(",
"`",
"${",
"filePath",
"}",
"`",
")",
";",
"const",
"content",
"=",
"stringify",
"(",
"config",
",",
"{",
"cmp",
":",
"sortByKey",
",",
"space",
":",
"4",
"}",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"filePath",
",",
"content",
",",
"\"utf8\"",
")",
";",
"}"
] | Writes a configuration file in JSON format.
@param {Object} config The configuration object to write.
@param {string} filePath The filename to write to.
@returns {void}
@private | [
"Writes",
"a",
"configuration",
"file",
"in",
"JSON",
"format",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L251-L257 |
2,794 | eslint/eslint | lib/config/config-file.js | writeYAMLConfigFile | function writeYAMLConfigFile(config, filePath) {
debug(`Writing YAML config file: ${filePath}`);
// lazy load YAML to improve performance when not used
const yaml = require("js-yaml");
const content = yaml.safeDump(config, { sortKeys: true });
fs.writeFileSync(filePath, content, "utf8");
} | javascript | function writeYAMLConfigFile(config, filePath) {
debug(`Writing YAML config file: ${filePath}`);
// lazy load YAML to improve performance when not used
const yaml = require("js-yaml");
const content = yaml.safeDump(config, { sortKeys: true });
fs.writeFileSync(filePath, content, "utf8");
} | [
"function",
"writeYAMLConfigFile",
"(",
"config",
",",
"filePath",
")",
"{",
"debug",
"(",
"`",
"${",
"filePath",
"}",
"`",
")",
";",
"// lazy load YAML to improve performance when not used",
"const",
"yaml",
"=",
"require",
"(",
"\"js-yaml\"",
")",
";",
"const",
"content",
"=",
"yaml",
".",
"safeDump",
"(",
"config",
",",
"{",
"sortKeys",
":",
"true",
"}",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"filePath",
",",
"content",
",",
"\"utf8\"",
")",
";",
"}"
] | Writes a configuration file in YAML format.
@param {Object} config The configuration object to write.
@param {string} filePath The filename to write to.
@returns {void}
@private | [
"Writes",
"a",
"configuration",
"file",
"in",
"YAML",
"format",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L266-L275 |
2,795 | eslint/eslint | lib/config/config-file.js | writeJSConfigFile | function writeJSConfigFile(config, filePath) {
debug(`Writing JS config file: ${filePath}`);
let contentToWrite;
const stringifiedContent = `module.exports = ${stringify(config, { cmp: sortByKey, space: 4 })};`;
try {
const CLIEngine = require("../cli-engine");
const linter = new CLIEngine({
baseConfig: config,
fix: true,
useEslintrc: false
});
const report = linter.executeOnText(stringifiedContent);
contentToWrite = report.results[0].output || stringifiedContent;
} catch (e) {
debug("Error linting JavaScript config file, writing unlinted version");
const errorMessage = e.message;
contentToWrite = stringifiedContent;
e.message = "An error occurred while generating your JavaScript config file. ";
e.message += "A config file was still generated, but the config file itself may not follow your linting rules.";
e.message += `\nError: ${errorMessage}`;
throw e;
} finally {
fs.writeFileSync(filePath, contentToWrite, "utf8");
}
} | javascript | function writeJSConfigFile(config, filePath) {
debug(`Writing JS config file: ${filePath}`);
let contentToWrite;
const stringifiedContent = `module.exports = ${stringify(config, { cmp: sortByKey, space: 4 })};`;
try {
const CLIEngine = require("../cli-engine");
const linter = new CLIEngine({
baseConfig: config,
fix: true,
useEslintrc: false
});
const report = linter.executeOnText(stringifiedContent);
contentToWrite = report.results[0].output || stringifiedContent;
} catch (e) {
debug("Error linting JavaScript config file, writing unlinted version");
const errorMessage = e.message;
contentToWrite = stringifiedContent;
e.message = "An error occurred while generating your JavaScript config file. ";
e.message += "A config file was still generated, but the config file itself may not follow your linting rules.";
e.message += `\nError: ${errorMessage}`;
throw e;
} finally {
fs.writeFileSync(filePath, contentToWrite, "utf8");
}
} | [
"function",
"writeJSConfigFile",
"(",
"config",
",",
"filePath",
")",
"{",
"debug",
"(",
"`",
"${",
"filePath",
"}",
"`",
")",
";",
"let",
"contentToWrite",
";",
"const",
"stringifiedContent",
"=",
"`",
"${",
"stringify",
"(",
"config",
",",
"{",
"cmp",
":",
"sortByKey",
",",
"space",
":",
"4",
"}",
")",
"}",
"`",
";",
"try",
"{",
"const",
"CLIEngine",
"=",
"require",
"(",
"\"../cli-engine\"",
")",
";",
"const",
"linter",
"=",
"new",
"CLIEngine",
"(",
"{",
"baseConfig",
":",
"config",
",",
"fix",
":",
"true",
",",
"useEslintrc",
":",
"false",
"}",
")",
";",
"const",
"report",
"=",
"linter",
".",
"executeOnText",
"(",
"stringifiedContent",
")",
";",
"contentToWrite",
"=",
"report",
".",
"results",
"[",
"0",
"]",
".",
"output",
"||",
"stringifiedContent",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"debug",
"(",
"\"Error linting JavaScript config file, writing unlinted version\"",
")",
";",
"const",
"errorMessage",
"=",
"e",
".",
"message",
";",
"contentToWrite",
"=",
"stringifiedContent",
";",
"e",
".",
"message",
"=",
"\"An error occurred while generating your JavaScript config file. \"",
";",
"e",
".",
"message",
"+=",
"\"A config file was still generated, but the config file itself may not follow your linting rules.\"",
";",
"e",
".",
"message",
"+=",
"`",
"\\n",
"${",
"errorMessage",
"}",
"`",
";",
"throw",
"e",
";",
"}",
"finally",
"{",
"fs",
".",
"writeFileSync",
"(",
"filePath",
",",
"contentToWrite",
",",
"\"utf8\"",
")",
";",
"}",
"}"
] | Writes a configuration file in JavaScript format.
@param {Object} config The configuration object to write.
@param {string} filePath The filename to write to.
@throws {Error} If an error occurs linting the config file contents.
@returns {void}
@private | [
"Writes",
"a",
"configuration",
"file",
"in",
"JavaScript",
"format",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L285-L313 |
2,796 | eslint/eslint | lib/config/config-file.js | write | function write(config, filePath) {
switch (path.extname(filePath)) {
case ".js":
writeJSConfigFile(config, filePath);
break;
case ".json":
writeJSONConfigFile(config, filePath);
break;
case ".yaml":
case ".yml":
writeYAMLConfigFile(config, filePath);
break;
default:
throw new Error("Can't write to unknown file type.");
}
} | javascript | function write(config, filePath) {
switch (path.extname(filePath)) {
case ".js":
writeJSConfigFile(config, filePath);
break;
case ".json":
writeJSONConfigFile(config, filePath);
break;
case ".yaml":
case ".yml":
writeYAMLConfigFile(config, filePath);
break;
default:
throw new Error("Can't write to unknown file type.");
}
} | [
"function",
"write",
"(",
"config",
",",
"filePath",
")",
"{",
"switch",
"(",
"path",
".",
"extname",
"(",
"filePath",
")",
")",
"{",
"case",
"\".js\"",
":",
"writeJSConfigFile",
"(",
"config",
",",
"filePath",
")",
";",
"break",
";",
"case",
"\".json\"",
":",
"writeJSONConfigFile",
"(",
"config",
",",
"filePath",
")",
";",
"break",
";",
"case",
"\".yaml\"",
":",
"case",
"\".yml\"",
":",
"writeYAMLConfigFile",
"(",
"config",
",",
"filePath",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"\"Can't write to unknown file type.\"",
")",
";",
"}",
"}"
] | Writes a configuration file.
@param {Object} config The configuration object to write.
@param {string} filePath The filename to write to.
@returns {void}
@throws {Error} When an unknown file type is specified.
@private | [
"Writes",
"a",
"configuration",
"file",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L323-L341 |
2,797 | eslint/eslint | lib/config/config-file.js | getEslintCoreConfigPath | function getEslintCoreConfigPath(name) {
if (name === "eslint:recommended") {
/*
* Add an explicit substitution for eslint:recommended to
* conf/eslint-recommended.js.
*/
return path.resolve(__dirname, "../../conf/eslint-recommended.js");
}
if (name === "eslint:all") {
/*
* Add an explicit substitution for eslint:all to conf/eslint-all.js
*/
return path.resolve(__dirname, "../../conf/eslint-all.js");
}
throw configMissingError(name);
} | javascript | function getEslintCoreConfigPath(name) {
if (name === "eslint:recommended") {
/*
* Add an explicit substitution for eslint:recommended to
* conf/eslint-recommended.js.
*/
return path.resolve(__dirname, "../../conf/eslint-recommended.js");
}
if (name === "eslint:all") {
/*
* Add an explicit substitution for eslint:all to conf/eslint-all.js
*/
return path.resolve(__dirname, "../../conf/eslint-all.js");
}
throw configMissingError(name);
} | [
"function",
"getEslintCoreConfigPath",
"(",
"name",
")",
"{",
"if",
"(",
"name",
"===",
"\"eslint:recommended\"",
")",
"{",
"/*\n * Add an explicit substitution for eslint:recommended to\n * conf/eslint-recommended.js.\n */",
"return",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"\"../../conf/eslint-recommended.js\"",
")",
";",
"}",
"if",
"(",
"name",
"===",
"\"eslint:all\"",
")",
"{",
"/*\n * Add an explicit substitution for eslint:all to conf/eslint-all.js\n */",
"return",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"\"../../conf/eslint-all.js\"",
")",
";",
"}",
"throw",
"configMissingError",
"(",
"name",
")",
";",
"}"
] | Resolves a eslint core config path
@param {string} name The eslint config name.
@returns {string} The resolved path of the config.
@private | [
"Resolves",
"a",
"eslint",
"core",
"config",
"path"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L349-L368 |
2,798 | eslint/eslint | lib/config/config-file.js | applyExtends | function applyExtends(config, configContext, filePath) {
const extendsList = Array.isArray(config.extends) ? config.extends : [config.extends];
// Make the last element in an array take the highest precedence
const flattenedConfig = extendsList.reduceRight((previousValue, extendedConfigReference) => {
try {
debug(`Loading ${extendedConfigReference}`);
// eslint-disable-next-line no-use-before-define
return ConfigOps.merge(load(extendedConfigReference, configContext, filePath), previousValue);
} catch (err) {
/*
* If the file referenced by `extends` failed to load, add the path
* to the configuration file that referenced it to the error
* message so the user is able to see where it was referenced from,
* then re-throw.
*/
err.message += `\nReferenced from: ${filePath}`;
if (err.messageTemplate === "plugin-missing") {
err.messageData.configStack.push(filePath);
}
throw err;
}
}, Object.assign({}, config));
delete flattenedConfig.extends;
return flattenedConfig;
} | javascript | function applyExtends(config, configContext, filePath) {
const extendsList = Array.isArray(config.extends) ? config.extends : [config.extends];
// Make the last element in an array take the highest precedence
const flattenedConfig = extendsList.reduceRight((previousValue, extendedConfigReference) => {
try {
debug(`Loading ${extendedConfigReference}`);
// eslint-disable-next-line no-use-before-define
return ConfigOps.merge(load(extendedConfigReference, configContext, filePath), previousValue);
} catch (err) {
/*
* If the file referenced by `extends` failed to load, add the path
* to the configuration file that referenced it to the error
* message so the user is able to see where it was referenced from,
* then re-throw.
*/
err.message += `\nReferenced from: ${filePath}`;
if (err.messageTemplate === "plugin-missing") {
err.messageData.configStack.push(filePath);
}
throw err;
}
}, Object.assign({}, config));
delete flattenedConfig.extends;
return flattenedConfig;
} | [
"function",
"applyExtends",
"(",
"config",
",",
"configContext",
",",
"filePath",
")",
"{",
"const",
"extendsList",
"=",
"Array",
".",
"isArray",
"(",
"config",
".",
"extends",
")",
"?",
"config",
".",
"extends",
":",
"[",
"config",
".",
"extends",
"]",
";",
"// Make the last element in an array take the highest precedence",
"const",
"flattenedConfig",
"=",
"extendsList",
".",
"reduceRight",
"(",
"(",
"previousValue",
",",
"extendedConfigReference",
")",
"=>",
"{",
"try",
"{",
"debug",
"(",
"`",
"${",
"extendedConfigReference",
"}",
"`",
")",
";",
"// eslint-disable-next-line no-use-before-define",
"return",
"ConfigOps",
".",
"merge",
"(",
"load",
"(",
"extendedConfigReference",
",",
"configContext",
",",
"filePath",
")",
",",
"previousValue",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"/*\n * If the file referenced by `extends` failed to load, add the path\n * to the configuration file that referenced it to the error\n * message so the user is able to see where it was referenced from,\n * then re-throw.\n */",
"err",
".",
"message",
"+=",
"`",
"\\n",
"${",
"filePath",
"}",
"`",
";",
"if",
"(",
"err",
".",
"messageTemplate",
"===",
"\"plugin-missing\"",
")",
"{",
"err",
".",
"messageData",
".",
"configStack",
".",
"push",
"(",
"filePath",
")",
";",
"}",
"throw",
"err",
";",
"}",
"}",
",",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"config",
")",
")",
";",
"delete",
"flattenedConfig",
".",
"extends",
";",
"return",
"flattenedConfig",
";",
"}"
] | Applies values from the "extends" field in a configuration file.
@param {Object} config The configuration information.
@param {Config} configContext Plugin context for the config instance
@param {string} filePath The file path from which the configuration information
was loaded.
@returns {Object} A new configuration object with all of the "extends" fields
loaded and merged.
@private | [
"Applies",
"values",
"from",
"the",
"extends",
"field",
"in",
"a",
"configuration",
"file",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L380-L411 |
2,799 | eslint/eslint | lib/config/config-file.js | isExistingFile | function isExistingFile(filename) {
try {
return fs.statSync(filename).isFile();
} catch (err) {
if (err.code === "ENOENT") {
return false;
}
throw err;
}
} | javascript | function isExistingFile(filename) {
try {
return fs.statSync(filename).isFile();
} catch (err) {
if (err.code === "ENOENT") {
return false;
}
throw err;
}
} | [
"function",
"isExistingFile",
"(",
"filename",
")",
"{",
"try",
"{",
"return",
"fs",
".",
"statSync",
"(",
"filename",
")",
".",
"isFile",
"(",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"\"ENOENT\"",
")",
"{",
"return",
"false",
";",
"}",
"throw",
"err",
";",
"}",
"}"
] | Checks whether the given filename points to a file
@param {string} filename A path to a file
@returns {boolean} `true` if a file exists at the given location | [
"Checks",
"whether",
"the",
"given",
"filename",
"points",
"to",
"a",
"file"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L568-L577 |
Subsets and Splits