Merge pull request #1430 from valadaptive/eslint-fixes-2

ESLint fixes, part 2 - bulky changes
This commit is contained in:
Cohee 2023-12-02 19:43:11 +02:00 committed by GitHub
commit a367285ac2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 67 additions and 68 deletions

View File

@ -51,17 +51,12 @@ module.exports = {
// linting passes.
rules: {
'no-unused-vars': 'off',
'no-useless-escape': 'off',
'no-control-regex': 'off',
'no-redeclare': 'off',
'no-async-promise-executor': 'off',
'no-inner-declarations': 'off',
'no-extra-semi': 'off',
'no-undef': 'off',
'no-prototype-builtins': 'off',
'no-extra-boolean-cast': 'off',
'require-yield': 'off',
'no-case-declarations': 'off',
'no-constant-condition': ['error', {checkLoops: false}]
}
};

View File

@ -1460,9 +1460,9 @@ function messageFormatting(mes, ch_name, isSystem, isUser) {
.replace(/\*\*(.+?)\*\*/g, "<b>$1</b>")
.replace(/\n/g, "<br/>");
} else if (!isSystem) {
mes = mes.replace(/```[\s\S]*?```|``[\s\S]*?``|`[\s\S]*?`|(\".+?\")|(\u201C.+?\u201D)/gm, function (match, p1, p2) {
mes = mes.replace(/```[\s\S]*?```|``[\s\S]*?``|`[\s\S]*?`|(".+?")|(\u201C.+?\u201D)/gm, function (match, p1, p2) {
if (p1) {
return '<q>"' + p1.replace(/\"/g, "") + '"</q>';
return '<q>"' + p1.replace(/"/g, "") + '"</q>';
} else if (p2) {
return '<q>“' + p2.replace(/\u201C|\u201D/g, "") + '”</q>';
} else {
@ -1686,10 +1686,6 @@ function addOneMessage(mes, { type = "normal", insertAfter = null, scroll = true
mes.swipes = [mes.mes];
}
if (mes.name === name1) {
var characterName = name1; //set to user's name by default
} else { var characterName = mes.name }
var avatarImg = getUserAvatar(user_avatar);
const isSystem = mes.is_system;
const title = mes.title;
@ -1722,7 +1718,7 @@ function addOneMessage(mes, { type = "normal", insertAfter = null, scroll = true
}
messageText = messageFormatting(
messageText,
characterName,
mes.name,
isSystem,
mes.is_user,
);
@ -1741,7 +1737,7 @@ function addOneMessage(mes, { type = "normal", insertAfter = null, scroll = true
}*/
let params = {
mesId: forceId ?? count_view_mes,
characterName: characterName,
characterName: mes.name,
isUser: mes.is_user,
avatarImg: avatarImg,
bias: bias,
@ -2755,10 +2751,11 @@ export async function generateRaw(prompt, api, instructOverride) {
generateData = getKoboldGenerationData(prompt, koboldSettings, amount_gen, max_context, isHorde, 'quiet');
}
break;
case 'novel':
case 'novel': {
const novelSettings = novelai_settings[novelai_setting_names[nai_settings.preset_settings_novel]];
generateData = getNovelGenerationData(prompt, novelSettings, amount_gen, false, false, null);
break;
}
case 'textgenerationwebui':
generateData = getTextGenGenerationData(prompt, amount_gen, false, false, null);
break;
@ -3834,7 +3831,7 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject,
triggerAutoContinue(messageChunk, isImpersonate);
resolve();
}
};
}
function onError(exception) {
if (typeof exception?.error?.message === 'string') {
@ -3845,7 +3842,7 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject,
unblockGeneration();
console.log(exception);
streamingProcessor = null;
};
}
} //rungenerate ends
} else { //generate's primary loop ends, after this is error handling for no-connection or safety-id
@ -7889,7 +7886,7 @@ jQuery(async function () {
if (popup_type == 'avatarToCrop') {
dialogueResolve($("#avatarToCrop").data('cropper').getCroppedCanvas().toDataURL('image/jpeg'));
};
}
if (popup_type == "del_chat") {
//close past chat popup
@ -9170,7 +9167,7 @@ jQuery(async function () {
$(document).on('click', '.inline-drawer-toggle', function (e) {
if ($(e.target).hasClass('text_pole')) {
return;
};
}
var icon = $(this).find('.inline-drawer-icon');
icon.toggleClass('down up');
icon.toggleClass('fa-circle-chevron-down fa-circle-chevron-up');

View File

@ -1643,7 +1643,7 @@ PromptManagerModule.prototype.import = function (importData) {
*/
PromptManagerModule.prototype.validateObject = function (controlObj, object) {
for (let key in controlObj) {
if (!object.hasOwnProperty(key)) {
if (!Object.hasOwn(object, key)) {
if (controlObj[key] === null) continue;
else return false;
}
@ -1818,7 +1818,7 @@ const chatCompletionDefaultPrompts = {
"identifier": "enhanceDefinitions",
"role": "system",
"name": "Enhance Definitions",
"content": "If you have more knowledge of {{char}}, add to the character\'s lore and personality to enhance them but keep the Character Sheet\'s definitions absolute.",
"content": "If you have more knowledge of {{char}}, add to the character's lore and personality to enhance them but keep the Character Sheet's definitions absolute.",
"system_prompt": true,
"marker": false,
},

View File

@ -819,7 +819,7 @@ export function initRossMods() {
//console.log('setting pin class via local var');
$(RightNavPanel).addClass('pinnedOpen');
}
if (!!$(RPanelPin).prop('checked')) {
if ($(RPanelPin).prop('checked')) {
console.debug('setting pin class via checkbox state');
$(RightNavPanel).addClass('pinnedOpen');
}
@ -829,7 +829,7 @@ export function initRossMods() {
//console.log('setting pin class via local var');
$(LeftNavPanel).addClass('pinnedOpen');
}
if (!!$(LPanelPin).prop('checked')) {
if ($(LPanelPin).prop('checked')) {
console.debug('setting pin class via checkbox state');
$(LeftNavPanel).addClass('pinnedOpen');
}
@ -841,7 +841,7 @@ export function initRossMods() {
$(WorldInfo).addClass('pinnedOpen');
}
if (!!$(WIPanelPin).prop('checked')) {
if ($(WIPanelPin).prop('checked')) {
console.debug('setting pin class via checkbox state');
$(WorldInfo).addClass('pinnedOpen');
}

View File

@ -691,7 +691,7 @@ async function onDeleteClick() {
if (confirmation) {
await deleteExtension(extensionName);
}
};
}
export async function deleteExtension(extensionName) {
try {

View File

@ -763,7 +763,7 @@ function sampleClassifyText(text) {
}
// Remove asterisks and quotes
let result = text.replace(/[\*\"]/g, '');
let result = text.replace(/[*"]/g, '');
const SAMPLE_THRESHOLD = 500;
const HALF_SAMPLE_THRESHOLD = SAMPLE_THRESHOLD / 2;

View File

@ -2416,7 +2416,7 @@ async function sdMessageButton(e) {
context.saveChat();
}
};
}
$("#sd_dropdown [id]").on("click", function () {
const id = $(this).attr("id");

View File

@ -151,7 +151,7 @@ function showKeysButton() {
function loadSettings() {
for (const key in defaultSettings) {
if (!extension_settings.translate.hasOwnProperty(key)) {
if (!Object.hasOwn(extension_settings.translate, key)) {
extension_settings.translate[key] = defaultSettings[key];
}
}

View File

@ -492,7 +492,7 @@ async function processTtsQueue() {
currentTtsJob = ttsJobQueue.shift()
let text = extension_settings.tts.narrate_translated_only ? (currentTtsJob?.extra?.display_text || currentTtsJob.mes) : currentTtsJob.mes
text = extension_settings.tts.narrate_dialogues_only
? text.replace(/\*[^\*]*?(\*|$)/g, '').trim() // remove asterisks content
? text.replace(/\*[^*]*?(\*|$)/g, '').trim() // remove asterisks content
: text.replaceAll('*', '').trim() // remove just the asterisks
if (extension_settings.tts.narrate_quoted_only) {

View File

@ -46,7 +46,7 @@ var speechUtteranceChunker = function (utt, settings, callback) {
newUtt = new SpeechSynthesisUtterance(chunk);
var x;
for (x in utt) {
if (utt.hasOwnProperty(x) && x !== 'text') {
if (Object.hasOwn(utt, x) && x !== 'text') {
newUtt[x] = utt[x];
}
}

View File

@ -145,7 +145,7 @@ const hashCache = {};
*/
function getStringHash(str) {
// Check if the hash is already in the cache
if (hashCache.hasOwnProperty(str)) {
if (Object.hasOwn(hashCache, str)) {
return hashCache[str];
}

View File

@ -1277,7 +1277,7 @@ function select_group_chats(groupId, skipAnimation) {
const replyStrategy = Number(group?.activation_strategy ?? group_activation_strategy.NATURAL);
const generationMode = Number(group?.generation_mode ?? group_generation_mode.SWAP);
setMenuType(!!group ? 'group_edit' : 'group_create');
setMenuType(group ? 'group_edit' : 'group_create');
$("#group_avatar_preview").empty().append(getGroupAvatar(group));
$("#rm_group_restore_avatar").toggle(!!group && isValidImageUrl(group.avatar_url));
$("#rm_group_filter").val("").trigger("input");

View File

@ -124,4 +124,4 @@ export function initLocales() {
registerDebugFunction('getMissingTranslations', 'Get missing translations', 'Detects missing localization data and dumps the data into the browser console.', getMissingTranslations);
registerDebugFunction('applyLocale', 'Apply locale', 'Reapplies the currently selected locale to the page.', applyLocale);
};
}

View File

@ -87,11 +87,11 @@ export function loadKoboldSettings(preset) {
$(slider.counterId).val(formattedValue);
}
if (preset.hasOwnProperty('streaming_kobold')) {
if (Object.hasOwn(preset, 'streaming_kobold')) {
kai_settings.streaming_kobold = preset.streaming_kobold;
$('#streaming_kobold').prop('checked', kai_settings.streaming_kobold);
}
if (preset.hasOwnProperty('use_default_badwordsids')) {
if (Object.hasOwn(preset, 'use_default_badwordsids')) {
kai_settings.use_default_badwordsids = preset.use_default_badwordsids;
$('#use_default_badwordsids').prop('checked', kai_settings.use_default_badwordsids);
}

View File

@ -655,7 +655,7 @@ function calculateLogitBias() {
* @returns Processed prompt
*/
export function adjustNovelInstructionPrompt(prompt) {
const stripedPrompt = prompt.replace(/[\[\]]/g, '').trim();
const stripedPrompt = prompt.replace(/[[\]]/g, '').trim();
if (!stripedPrompt.includes('{ ')) {
return `{ ${stripedPrompt} }`;
}

View File

@ -1860,7 +1860,7 @@ class Message {
* Returns the number of tokens in the message.
* @returns {number} Number of tokens in the message.
*/
getTokens() { return this.tokens };
getTokens() { return this.tokens }
}
/**
@ -2239,14 +2239,14 @@ class ChatCompletion {
reserveBudget(message) {
const tokens = typeof message === 'number' ? message : message.getTokens();
this.decreaseTokenBudgetBy(tokens);
};
}
/**
* Frees up the tokens used by the given message from the token budget.
*
* @param {Message|MessageCollection} message - The message whose tokens to free.
*/
freeBudget(message) { this.increaseTokenBudgetBy(message.getTokens()) };
freeBudget(message) { this.increaseTokenBudgetBy(message.getTokens()) }
/**
* Increases the token budget by the given number of tokens.
@ -2832,7 +2832,8 @@ async function onLogitBiasPresetImportFileChange(e) {
for (const entry of importedFile) {
if (typeof entry == 'object' && entry !== null) {
if (entry.hasOwnProperty('text') && entry.hasOwnProperty('value')) {
if (Object.hasOwn(entry, 'text') &&
Object.hasOwn(entry, 'value')) {
validEntries.push(entry);
}
}

View File

@ -340,7 +340,7 @@ function collapseNewlines(x) {
*/
function fixMarkdown(text, forDisplay) {
// Find pairs of formatting characters and capture the text in between them
const format = /([\*_]{1,2})([\s\S]*?)\1/gm;
const format = /([*_]{1,2})([\s\S]*?)\1/gm;
let matches = [];
let match;
while ((match = format.exec(text)) !== null) {
@ -834,7 +834,7 @@ async function CreateZenSliders(elmnt) {
originalSlider.data("newSlider", newSlider);
await delay(1)
originalSlider.hide();
};
}
function switchUiMode() {
const fastUi = localStorage.getItem(storage_keys.fast_ui_mode);
power_user.fast_ui_mode = fastUi === null ? true : fastUi == "true";
@ -894,7 +894,7 @@ function switchMovingUI() {
if (power_user.movingUIState) {
loadMovingUIState();
}
};
}
}
function noShadows() {
@ -1239,7 +1239,7 @@ async function applyTheme(name) {
if (type) await applyThemeColor(type);
if (action) await action();
} else {
if (selector) { $(selector).attr('color', 'rgba(0,0,0,0)') };
if (selector) { $(selector).attr('color', 'rgba(0,0,0,0)') }
console.debug(`Empty theme key: ${key}`);
power_user[key] = '';
}
@ -2985,7 +2985,7 @@ $(document).ready(() => {
if (power_user.enableZenSliders === true && value === true) {
//disallow Lab Mode if ZenSliders are active
toastr.warning('Disable Zen Sliders before enabling Mad Lab Mode')
$(this).prop('checked', false).trigger('input');;
$(this).prop('checked', false).trigger('input');
return
}

View File

@ -236,14 +236,16 @@ class PresetManager {
return nai_settings;
case "textgenerationwebui":
return textgenerationwebui_settings;
case "context":
case "context": {
const context_preset = getContextSettings();
context_preset['name'] = name || power_user.context.preset;
return context_preset;
case "instruct":
}
case "instruct": {
const instruct_preset = structuredClone(power_user.instruct);
instruct_preset['name'] = name || power_user.instruct.preset;
return instruct_preset;
}
default:
console.warn(`Unknown API ID ${apiId}`);
return {};
@ -268,7 +270,7 @@ class PresetManager {
const settings = Object.assign({}, getSettingsByApiId(this.apiId));
for (const key of filteredKeys) {
if (settings.hasOwnProperty(key)) {
if (Object.hasOwn(settings, key)) {
delete settings[key];
}
}

View File

@ -58,7 +58,7 @@ class SlashCommandParser {
addCommand(command, callback, aliases, helpString = '', interruptsGeneration = false, purgeFromMessage = true) {
const fnObj = { callback, helpString, interruptsGeneration, purgeFromMessage };
if ([command, ...aliases].some(x => this.commands.hasOwnProperty(x))) {
if ([command, ...aliases].some(x => Object.hasOwn(this.commands, x))) {
console.trace('WARN: Duplicate slash command registered!');
}

View File

@ -261,7 +261,7 @@ async function importTags(imported_char) {
tag_map[imported_char.avatar].push(tag.id);
console.debug('added tag to map', tag, imported_char.name);
}
};
}
saveSettingsDebounced();
await getCharacters();
printTagFilters(tag_filter_types.character);

View File

@ -517,9 +517,10 @@ export function getTextTokens(tokenizerType, str) {
return getTextTokensRemote('/api/tokenize/mistral', str);
case tokenizers.YI:
return getTextTokensRemote('/api/tokenize/yi', str);
case tokenizers.OPENAI:
case tokenizers.OPENAI: {
const model = getTokenizerModel();
return getTextTokensRemote('/api/tokenize/openai-encode', str, model);
}
case tokenizers.API:
return getTextTokensRemote('/tokenize_via_api', str);
default:
@ -547,9 +548,10 @@ export function decodeTextTokens(tokenizerType, ids) {
return decodeTextTokensRemote('/api/decode/mistral', ids);
case tokenizers.YI:
return decodeTextTokensRemote('/api/decode/yi', ids);
case tokenizers.OPENAI:
case tokenizers.OPENAI: {
const model = getTokenizerModel();
return decodeTextTokensRemote('/api/decode/openai', ids, model);
}
default:
console.warn("Calling decodeTextTokens with unsupported tokenizer type", tokenizerType);
return '';

View File

@ -244,7 +244,7 @@ export function getStringHash(str, seed = 0) {
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
};
}
/**
* Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked.
@ -344,7 +344,7 @@ export function incrementString(str) {
// Take the substring up until where the integer was matched
// Concatenate it to the matched count incremented by 1
return str.substring(0, count.index) + (Number(count[0]) + 1);
};
}
/**
* Formats a string using the specified arguments.
@ -361,7 +361,7 @@ export function stringFormat(format) {
: match
;
});
};
}
/**
* Save the caret position in a contenteditable element.
@ -694,7 +694,7 @@ export function splitRecursive(input, length, delimiters = ['\n\n', '\n', ' ', '
* isDataURL('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA...'); // true
*/
export function isDataURL(str) {
const regex = /^data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)*;?)?(base64)?,([a-z0-9!$&',()*+;=\-_%.~:@\/?#]+)?$/i;
const regex = /^data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)*;?)?(base64)?,([a-z0-9!$&',()*+;=\-_%.~:@/?#]+)?$/i;
return regex.test(str);
}

View File

@ -133,7 +133,7 @@ export function replaceVariableMacros(input) {
// Replace {{addvar::name::value}} with empty string and add value to the variable value
line = line.replace(/{{addvar::([^:]+)::([^}]+)}}/gi, (_, name, value) => {
name = name.trim();
addLocalVariable(name, value);;
addLocalVariable(name, value);
return '';
});

View File

@ -778,7 +778,7 @@ function setOriginalDataValue(data, uid, key, value) {
for (let i = 0; i < keyParts.length - 1; i++) {
const part = keyParts[i];
if (!currentObject.hasOwnProperty(part)) {
if (!Object.hasOwn(currentObject, part)) {
currentObject[part] = {};
}
@ -855,7 +855,7 @@ function getWorldEntry(name, data, entry) {
// Character filter
const characterFilterLabel = template.find(`label[for="characterFilter"] > small`);
characterFilterLabel.text(!!(entry.characterFilter?.isExclude) ? "Exclude Character(s)" : "Filter to Character(s)");
characterFilterLabel.text(entry.characterFilter?.isExclude ? "Exclude Character(s)" : "Filter to Character(s)");
// exclude characters checkbox
const characterExclusionInput = template.find(`input[name="character_exclusion"]`);
@ -1898,7 +1898,7 @@ async function checkWorldInfo(chat, maxContext) {
case world_info_position.ANBottom:
ANBottomEntries.unshift(entry.content);
break;
case world_info_position.atDepth:
case world_info_position.atDepth: {
const existingDepthIndex = WIDepthEntries.findIndex((e) => e.depth === entry.depth ?? DEFAULT_DEPTH);
if (existingDepthIndex !== -1) {
WIDepthEntries[existingDepthIndex].entries.unshift(entry.content);
@ -1909,6 +1909,7 @@ async function checkWorldInfo(chat, maxContext) {
});
}
break;
}
default:
break;
}

View File

@ -204,7 +204,7 @@ function humanizedISO8601DateTime(date) {
let humanMillisecond = (baseDate.getMilliseconds() < 10 ? '0' : '') + baseDate.getMilliseconds();
let HumanizedDateTime = (humanYear + "-" + humanMonth + "-" + humanDate + " @" + humanHour + "h " + humanMinute + "m " + humanSecond + "s " + humanMillisecond + "ms");
return HumanizedDateTime;
};
}
var charactersPath = 'public/characters/';
var chatsPath = 'public/chats/';
@ -464,7 +464,7 @@ app.post("/generate", jsonParser, async function (request, response_generate) {
grammar: request.body.grammar,
sampler_seed: request.body.sampler_seed,
};
if (!!request.body.stop_sequence) {
if (request.body.stop_sequence) {
this_settings['stop_sequence'] = request.body.stop_sequence;
}
}

View File

@ -20,7 +20,7 @@ function checkAssetFileName(inputFilename) {
return '';
}
if (!/^[a-zA-Z0-9_\-\.]+$/.test(inputFilename)) {
if (!/^[a-zA-Z0-9_\-.]+$/.test(inputFilename)) {
console.debug("Bad request: illegal character in filename, only alphanumeric, '_', '-' are accepted.");
return '';
}
@ -35,7 +35,7 @@ function checkAssetFileName(inputFilename) {
return '';
}
return path.normalize(inputFilename).replace(/^(\.\.(\/|\\|$))+/, '');;
return path.normalize(inputFilename).replace(/^(\.\.(\/|\\|$))+/, '');
}
// Recursive function to get files

View File

@ -7,7 +7,7 @@ const parse = async (cardUrl, format) => {
let fileFormat = format === undefined ? 'png' : format;
switch (fileFormat) {
case 'png':
case 'png': {
const buffer = fs.readFileSync(cardUrl);
const chunks = extract(buffer);
@ -23,6 +23,7 @@ const parse = async (cardUrl, format) => {
}
return Buffer.from(textChunks[0].text, 'base64').toString('utf8');
}
default:
break;
}

View File

@ -24,7 +24,7 @@ function registerEndpoints(app, jsonParser) {
const { text } = req.body;
async function getResult(text) {
if (cacheObject.hasOwnProperty(text)) {
if (Object.hasOwn(cacheObject, text)) {
return cacheObject[text];
} else {
const module = await import('./transformers.mjs');

View File

@ -48,7 +48,7 @@ class TavernCardValidator {
validateV1() {
const requiredFields = ['name', 'description', 'personality', 'scenario', 'first_mes', 'mes_example'];
return requiredFields.every(field => {
if (!this.card.hasOwnProperty(field)) {
if (!Object.hasOwn(this.card, field)) {
this.#lastValidationError = field;
return false;
}
@ -94,7 +94,7 @@ class TavernCardValidator {
const requiredFields = ['name', 'description', 'personality', 'scenario', 'first_mes', 'mes_example', 'creator_notes', 'system_prompt', 'post_history_instructions', 'alternate_greetings', 'tags', 'creator', 'character_version', 'extensions'];
const isAllRequiredFieldsPresent = requiredFields.every(field => {
if (!data.hasOwnProperty(field)) {
if (!Object.hasOwn(data, field)) {
this.#lastValidationError = `data.${field}`;
return false;
}
@ -113,7 +113,7 @@ class TavernCardValidator {
const requiredFields = ['extensions', 'entries'];
const isAllRequiredFieldsPresent = requiredFields.every(field => {
if (!characterBook.hasOwnProperty(field)) {
if (!Object.hasOwn(characterBook, field)) {
this.#lastValidationError = `data.character_book.${field}`;
return false;
}