1
0
mirror of https://github.com/laurent22/joplin.git synced 2025-01-08 13:06:15 +02:00

Tools: Apply eslint rule @typescript-eslint/no-inferrable-types with ignoreArguments=false

This commit is contained in:
Laurent Cozic 2023-06-30 09:11:26 +01:00
parent 315f071337
commit e89b59be8e
80 changed files with 120 additions and 120 deletions

View File

@ -183,7 +183,7 @@ module.exports = {
'rules': {
'@typescript-eslint/explicit-member-accessibility': ['error'],
'@typescript-eslint/type-annotation-spacing': ['error', { 'before': false, 'after': true }],
'@typescript-eslint/no-inferrable-types': ['error', { 'ignoreParameters': true }],
'@typescript-eslint/no-inferrable-types': ['error'],
'@typescript-eslint/comma-dangle': ['error', {
'arrays': 'always-multiline',
'objects': 'always-multiline',

View File

@ -12,7 +12,7 @@ import { newPluginScript } from '../../testUtils';
const testPluginDir = `${supportDir}/plugins`;
function newPluginService(appVersion: string = '1.4') {
function newPluginService(appVersion = '1.4') {
const runner = new PluginRunner();
const service = new PluginService();
service.initialize(

View File

@ -7,7 +7,7 @@ import Setting from '@joplin/lib/models/Setting';
const testPluginDir = `${supportDir}/plugins`;
function newPluginService(appVersion: string = '1.4') {
function newPluginService(appVersion = '1.4') {
const runner = new PluginRunner();
const service = new PluginService();
service.initialize(

View File

@ -8,7 +8,7 @@ export const declaration: CommandDeclaration = {
export const runtime = (): CommandRuntime => {
return {
execute: async (_context: CommandContext, noteId: string, reverseRevIndex: number = 0) => {
execute: async (_context: CommandContext, noteId: string, reverseRevIndex = 0) => {
try {
const note = await RevisionService.instance().restoreNoteById(noteId, reverseRevIndex);
alert(RevisionService.instance().restoreSuccessMessage(note));

View File

@ -11,7 +11,7 @@ export const declaration: CommandDeclaration = {
export const runtime = (): CommandRuntime => {
return {
execute: async (_context: CommandContext, body: string = '', isTodo: boolean = false) => {
execute: async (_context: CommandContext, body = '', isTodo = false) => {
const folderId = Setting.value('activeFolderId');
if (!folderId) return;

View File

@ -9,7 +9,7 @@ export const declaration: CommandDeclaration = {
export const runtime = (): CommandRuntime => {
return {
execute: async (_context: CommandContext, body: string = '') => {
execute: async (_context: CommandContext, body = '') => {
return CommandService.instance().execute('newNote', body, true);
},
enabledCondition: 'oneFolderSelected && !inConflictFolder',

View File

@ -47,7 +47,7 @@ function findBlockSource(node: any): SourceInfo {
};
}
function newBlockSource(language: string = '', content: string = '', previousSource: SourceInfo = null): SourceInfo {
function newBlockSource(language = '', content = '', previousSource: SourceInfo = null): SourceInfo {
let fence = '```';
if (language === 'katex') {

View File

@ -30,7 +30,7 @@ async function saveFileData(data: any, filename: string) {
await writeFile(newFilePath, data);
}
export async function openItemById(itemId: string, dispatch: Function, hash: string = '') {
export async function openItemById(itemId: string, dispatch: Function, hash = '') {
const item = await BaseItem.loadItemById(itemId);

View File

@ -135,7 +135,7 @@ export function calculateMaxSizeAvailableForItem(item: LayoutItem, parent: Layou
return availableSize;
}
export default function useLayoutItemSizes(layout: LayoutItem, makeAllVisible: boolean = false) {
export default function useLayoutItemSizes(layout: LayoutItem, makeAllVisible = false) {
return useMemo(() => {
let sizes: LayoutItemSizes = {};

View File

@ -2,7 +2,7 @@ import Setting from '@joplin/lib/models/Setting';
import bridge from './bridge';
export default async (linuxSafeRestart: boolean = true) => {
export default async (linuxSafeRestart = true) => {
Setting.setValue('wasClosedSuccessfully', true);
await Setting.saveAll();

View File

@ -59,7 +59,7 @@ export function initCodeMirror(
let searchVisible = false;
let schedulePostUndoRedoDepthChangeId_: any = 0;
const schedulePostUndoRedoDepthChange = (editor: EditorView, doItNow: boolean = false) => {
const schedulePostUndoRedoDepthChange = (editor: EditorView, doItNow = false) => {
if (schedulePostUndoRedoDepthChangeId_) {
if (doItNow) {
clearTimeout(schedulePostUndoRedoDepthChangeId_);

View File

@ -3,7 +3,7 @@ import { ProfileConfig } from '@joplin/lib/services/profileConfig/types';
import { useState } from 'react';
import { loadProfileConfig } from '../../services/profiles';
export default (timestamp: number = 0) => {
export default (timestamp = 0) => {
const [profileConfig, setProfileConfig] = useState<ProfileConfig>(null);
useAsyncEffect(async (event: AsyncEffectEvent) => {

View File

@ -25,7 +25,7 @@ export const getResourceDir = (profile: Profile, isSubProfile: boolean) => {
};
// The suffix is for debugging only
export const getDatabaseName = (profile: Profile, isSubProfile: boolean, suffix: string = '') => {
export const getDatabaseName = (profile: Profile, isSubProfile: boolean, suffix = '') => {
if (!isSubProfile) return `joplin${suffix}.sqlite`;
return `joplin-${profile.id}${suffix}.sqlite`;
};

View File

@ -26,7 +26,7 @@ export default class AsyncActionQueue {
private scheduleProcessingIID_: any = null;
private processing_ = false;
public constructor(interval: number = 100, intervalType: IntervalType = IntervalType.Debounce) {
public constructor(interval = 100, intervalType: IntervalType = IntervalType.Debounce) {
this.interval_ = interval;
this.intervalType_ = intervalType;
}

View File

@ -157,7 +157,7 @@ export default class BaseApplication {
// Handles the initial flags passed to main script and
// returns the remaining args.
private async handleStartFlags_(argv: string[], setDefaults: boolean = true) {
private async handleStartFlags_(argv: string[], setDefaults = true) {
const matched: any = {};
argv = argv.slice(0);
argv.splice(0, 2); // First arguments are the node executable, and the node JS file
@ -318,7 +318,7 @@ export default class BaseApplication {
process.exit(code);
}
public async refreshNotes(state: any, useSelectedNoteId: boolean = false, noteHash: string = '') {
public async refreshNotes(state: any, useSelectedNoteId = false, noteHash = '') {
let parentType = state.notesParentType;
let parentId = null;

View File

@ -185,7 +185,7 @@ class BaseModel {
return fields.indexOf(name) >= 0;
}
public static fieldNames(withPrefix: boolean = false) {
public static fieldNames(withPrefix = false) {
const output = this.db().tableFieldNames(this.tableName());
if (!withPrefix) return output;

View File

@ -29,7 +29,7 @@ export default class Cache {
private expirableKeys_: ExpirableKeys = {};
private recordKeyHistory_: string[] = [];
public constructor(maxRecords: number = 50) {
public constructor(maxRecords = 50) {
this.maxRecords_ = maxRecords;
}
@ -62,7 +62,7 @@ export default class Cache {
return defaultValue;
}
public setValue(key: string, value: any, ttl: number = 0) {
public setValue(key: string, value: any, ttl = 0) {
this.checkExpiredRecords();
this.records_[key] = {

View File

@ -132,7 +132,7 @@ export default class JoplinServerApi {
return output.join(' ');
}
private async exec_(method: string, path: string = '', query: Record<string, any> = null, body: any = null, headers: any = null, options: ExecOptions = null) {
private async exec_(method: string, path = '', query: Record<string, any> = null, body: any = null, headers: any = null, options: ExecOptions = null) {
if (headers === null) headers = {};
if (options === null) options = {};
if (!options.responseFormat) options.responseFormat = ExecOptionsResponseFormat.Json;
@ -203,7 +203,7 @@ export default class JoplinServerApi {
};
// Creates an error object with as much data as possible as it will appear in the log, which will make debugging easier
const newError = (message: string, code: number = 0) => {
const newError = (message: string, code = 0) => {
// Gives a shorter response for error messages. Useful for cases where a full HTML page is accidentally loaded instead of
// JSON. That way the error message will still show there's a problem but without filling up the log or screen.
// return new JoplinError(`${method} ${path}: ${message} (${code}): ${shortResponseText}`, code);
@ -268,7 +268,7 @@ export default class JoplinServerApi {
}
}
public async exec(method: string, path: string = '', query: Record<string, any> = null, body: any = null, headers: any = null, options: ExecOptions = null) {
public async exec(method: string, path = '', query: Record<string, any> = null, body: any = null, headers: any = null, options: ExecOptions = null) {
for (let i = 0; i < 2; i++) {
try {
const response = await this.exec_(method, path, query, body, headers, options);

View File

@ -179,7 +179,7 @@ class Logger {
}
// Only for database at the moment
public async lastEntries(limit: number = 100, options: any = null) {
public async lastEntries(limit = 100, options: any = null) {
if (options === null) options = {};
if (!options.levels) options.levels = [LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error];
if (!options.levels.length) return [];

View File

@ -193,7 +193,7 @@ export default class Synchronizer {
return lines;
}
public logSyncOperation(action: string, local: any = null, remote: RemoteItem = null, message: string = null, actionCount: number = 1) {
public logSyncOperation(action: string, local: any = null, remote: RemoteItem = null, message: string = null, actionCount = 1) {
const line = ['Sync'];
line.push(action);
if (message) line.push(message);

View File

@ -9,7 +9,7 @@ export const declaration: CommandDeclaration = {
export const runtime = (): CommandRuntime => {
return {
execute: async (context: CommandContext, isOpen: boolean = true) => {
execute: async (context: CommandContext, isOpen = true) => {
context.dispatch({
type: 'DIALOG_OPEN',
name: 'masterPassword',

View File

@ -49,7 +49,7 @@ export default class FileApiDriverJoplinServer {
return 3;
}
private metadataToStat_(md: any, path: string, isDeleted: boolean = false, rootPath: string) {
private metadataToStat_(md: any, path: string, isDeleted = false, rootPath: string) {
const output = {
path: rootPath ? path.substr(rootPath.length + 1) : path,
updated_time: md.updated_time,

View File

@ -21,7 +21,7 @@ export default class FsDriverBase {
throw new Error('Not implemented');
}
public async readFile(_path: string, _encoding: string = 'utf8'): Promise<any> {
public async readFile(_path: string, _encoding = 'utf8'): Promise<any> {
throw new Error('Not implemented');
}
@ -41,7 +41,7 @@ export default class FsDriverBase {
throw new Error('Not implemented');
}
public async readFileChunk(_handle: any, _length: number, _encoding: string = 'base64'): Promise<string> {
public async readFileChunk(_handle: any, _length: number, _encoding = 'base64'): Promise<string> {
throw new Error('Not implemented');
}
@ -70,7 +70,7 @@ export default class FsDriverBase {
return !stat ? false : stat.isDirectory();
}
public async writeFile(_path: string, _content: string, _encoding: string = 'base64'): Promise<void> {
public async writeFile(_path: string, _content: string, _encoding = 'base64'): Promise<void> {
throw new Error('Not implemented');
}
@ -88,7 +88,7 @@ export default class FsDriverBase {
return output;
}
public async findUniqueFilename(name: string, reservedNames: string[] = null, markdownSafe: boolean = false): Promise<string> {
public async findUniqueFilename(name: string, reservedNames: string[] = null, markdownSafe = false): Promise<string> {
if (reservedNames === null) {
reservedNames = [];
}
@ -128,7 +128,7 @@ export default class FsDriverBase {
}
}
public async waitTillExists(path: string, timeout: number = 10000) {
public async waitTillExists(path: string, timeout = 10000) {
const startTime = Date.now();
while (true) {

View File

@ -18,7 +18,7 @@ export default class FsDriverNode extends FsDriverBase {
return fs.appendFileSync(path, string);
}
public async appendFile(path: string, string: string, encoding: string = 'base64') {
public async appendFile(path: string, string: string, encoding = 'base64') {
try {
return await fs.appendFile(path, string, { encoding: encoding });
} catch (error) {
@ -26,7 +26,7 @@ export default class FsDriverNode extends FsDriverBase {
}
}
public async writeFile(path: string, string: string, encoding: string = 'base64') {
public async writeFile(path: string, string: string, encoding = 'base64') {
try {
if (encoding === 'buffer') {
return await fs.writeFile(path, string);
@ -144,7 +144,7 @@ export default class FsDriverNode extends FsDriverBase {
}
}
public async readFile(path: string, encoding: string = 'utf8') {
public async readFile(path: string, encoding = 'utf8') {
try {
if (encoding === 'Buffer') return await fs.readFile(path); // Returns the raw buffer
return await fs.readFile(path, encoding);
@ -171,7 +171,7 @@ export default class FsDriverNode extends FsDriverBase {
}
}
public async readFileChunk(handle: any, length: number, encoding: string = 'base64') {
public async readFileChunk(handle: any, length: number, encoding = 'base64') {
// let buffer = new Buffer(length);
let buffer = Buffer.alloc(length);
const result = await fs.read(handle, buffer, 0, length, null);

View File

@ -360,7 +360,7 @@ function tagAttributeToMdText(attr: string): string {
return attr;
}
function addResourceTag(lines: string[], resource: ResourceEntity, alt: string = ''): string[] {
function addResourceTag(lines: string[], resource: ResourceEntity, alt = ''): string[] {
// Note: refactor to use Resource.markdownTag
if (!alt) alt = resource.title;

View File

@ -483,7 +483,7 @@ function supportedLocalesToLanguages(options: SupportedLocalesToLanguagesOptions
return output;
}
function closestSupportedLocale(canonicalName: string, defaultToEnglish: boolean = true, locales: string[] = null) {
function closestSupportedLocale(canonicalName: string, defaultToEnglish = true, locales: string[] = null) {
locales = locales === null ? supportedLocales() : locales;
if (locales.indexOf(canonicalName) >= 0) return canonicalName;
@ -508,7 +508,7 @@ function languageNameInEnglish(languageCode: string) {
return codeToLanguageE_[languageCode] ? codeToLanguageE_[languageCode] : '';
}
function languageName(canonicalName: string, defaultToEnglish: boolean = true) {
function languageName(canonicalName: string, defaultToEnglish = true) {
const languageCode = languageCodeOnly(canonicalName);
if (codeToLanguage_[languageCode]) return codeToLanguage_[languageCode];
if (defaultToEnglish) return languageNameInEnglish(languageCode);

View File

@ -1848,7 +1848,7 @@ class Setting extends BaseModel {
return this.metadata()[key] && this.metadata()[key].secure === true;
}
public static keys(publicOnly: boolean = false, appType: AppType = null, options: KeysOptions = null) {
public static keys(publicOnly = false, appType: AppType = null, options: KeysOptions = null) {
options = { secureOnly: false, ...options };
if (!this.keys_) {

View File

@ -28,7 +28,7 @@ const serializeUserData = (d: UserData): string => {
return JSON.stringify(d);
};
export const setUserData = <T>(userData: UserData, namespace: string, key: string, value: T, deleted: boolean = false): UserData => {
export const setUserData = <T>(userData: UserData, namespace: string, key: string, value: T, deleted = false): UserData => {
if (key.length > maxKeyLength) new Error(`Key must no be longer than ${maxKeyLength} characters`);
if (!(namespace in userData)) userData[namespace] = {};
if (key in userData[namespace] && userData[namespace][key].v === value) return userData;
@ -60,7 +60,7 @@ const checkIsSupportedItemType = (itemType: ModelType) => {
}
};
export const setItemUserData = async <T>(itemType: ModelType, itemId: string, namespace: string, key: string, value: T, deleted: boolean = false): Promise<SupportedEntity> => {
export const setItemUserData = async <T>(itemType: ModelType, itemId: string, namespace: string, key: string, value: T, deleted = false): Promise<SupportedEntity> => {
checkIsSupportedItemType(itemType);
interface ItemSlice {
@ -97,7 +97,7 @@ export const setItemUserData = async <T>(itemType: ModelType, itemId: string, na
};
// Deprecated - don't use
export const setNoteUserData = async <T>(note: NoteEntity, namespace: string, key: string, value: T, deleted: boolean = false): Promise<NoteEntity> => {
export const setNoteUserData = async <T>(note: NoteEntity, namespace: string, key: string, value: T, deleted = false): Promise<NoteEntity> => {
return setItemUserData(ModelType.Note, note.id, namespace, key, value, deleted);
};

View File

@ -15,7 +15,7 @@ export function basename(path: string) {
return s[s.length - 1];
}
export function filename(path: string, includeDir: boolean = false) {
export function filename(path: string, includeDir = false) {
if (!path) throw new Error('Path is empty');
const output = includeDir ? path : basename(path);
if (output.indexOf('.') < 0) return output;
@ -50,7 +50,7 @@ export function safeFileExtension(e: string, maxLength: number = null) {
return e.replace(/[^a-zA-Z0-9]/g, '').substr(0, maxLength);
}
export function safeFilename(e: string, maxLength: number = null, allowSpaces: boolean = false) {
export function safeFilename(e: string, maxLength: number = null, allowSpaces = false) {
if (maxLength === null) maxLength = 32;
if (!e || !e.replace) return '';
const regex = allowSpaces ? /[^a-zA-Z0-9\-_\(\)\. ]/g : /[^a-zA-Z0-9\-_\(\)\.]/g;
@ -73,7 +73,7 @@ const friendlySafeFilename_blackListNames = ['.', '..', 'CON', 'PRN', 'AUX', 'NU
// Markdown, etc.) - it still needs to be encoded by the calling code according
// to the context.
export function friendlySafeFilename(e: string, maxLength: number = null, preserveExtension: boolean = false) {
export function friendlySafeFilename(e: string, maxLength: number = null, preserveExtension = false) {
// Although Windows supports paths up to 255 characters, but that includes the filename and its
// parent directory path. Also there's generally no good reason for dir or file names
// to be so long, so keep it at 50, which should prevent various errors.

View File

@ -406,7 +406,7 @@ function handleItemDelete(draft: Draft<State>, action: any) {
}
}
function updateOneItem(draft: Draft<State>, action: any, keyName: string = '') {
function updateOneItem(draft: Draft<State>, action: any, keyName = '') {
let itemsKey = null;
if (keyName) { itemsKey = keyName; } else {
if (action.type === 'TAG_UPDATE_ONE') itemsKey = 'tags';

View File

@ -86,7 +86,7 @@ class Registry {
}
};
public scheduleSync = async (delay: number = null, syncOptions: any = null, doWifiConnectionCheck: boolean = false) => {
public scheduleSync = async (delay: number = null, syncOptions: any = null, doWifiConnectionCheck = false) => {
this.schedSyncCalls_.push(true);
try {

View File

@ -50,7 +50,7 @@ export default class AlarmService {
// When passing a note, make sure it has all the required properties
// (better to pass a complete note or else just the ID)
public static async updateNoteNotification(noteOrId: any, isDeleted: boolean = false) {
public static async updateNoteNotification(noteOrId: any, isDeleted = false) {
try {
let note = null;
let noteId = null;

View File

@ -119,7 +119,7 @@ export default class CommandService extends BaseService {
eventManager.off(eventName, callback);
}
public searchCommands(query: string, returnAllWhenEmpty: boolean, excludeWithoutLabel: boolean = true): SearchResult[] {
public searchCommands(query: string, returnAllWhenEmpty: boolean, excludeWithoutLabel = true): SearchResult[] {
query = query.toLowerCase();
const output = [];
@ -148,7 +148,7 @@ export default class CommandService extends BaseService {
return output;
}
public commandNames(publicOnly: boolean = false) {
public commandNames(publicOnly = false) {
if (publicOnly) {
const output = [];
for (const name in this.commands_) {
@ -298,7 +298,7 @@ export default class CommandService extends BaseService {
return command.declaration.iconName;
}
public label(commandName: string, fullLabel: boolean = false): string {
public label(commandName: string, fullLabel = false): string {
const command = this.commandByName(commandName);
if (!command) throw new Error(`Command: ${commandName} is not declared`);
const output = [];

View File

@ -87,7 +87,7 @@ export default class KvStore extends BaseService {
// Note: atomicity is done at application level so two difference instances
// accessing the db at the same time could mess up the increment.
public async incValue(key: string, inc: number = 1) {
public async incValue(key: string, inc = 1) {
const release = await this.incMutex_.acquire();
try {

View File

@ -134,7 +134,7 @@ export default class ResourceService extends BaseService {
}
}
private static async autoSetFileSize(resourceId: string, filePath: string, waitTillExists: boolean = true) {
private static async autoSetFileSize(resourceId: string, filePath: string, waitTillExists = true) {
const itDoes = await shim.fsDriver().waitTillExists(filePath, waitTillExists ? 10000 : 0);
if (!itDoes) {
// this.logger().warn('Trying to set file size on non-existent resource:', resourceId, filePath);

View File

@ -60,7 +60,7 @@ export default class WhenClause {
private validate_: boolean;
private ruleCache_: Record<string, ContextKeyExpression> = {};
public constructor(expression: string, validate: boolean = true) {
public constructor(expression: string, validate = true) {
this.expression_ = parseAdvancedExpression(expression);
this.validate_ = validate;
}

View File

@ -102,7 +102,7 @@ const desktopData = {
// This can be used to run integration tests directly on device. It will throw
// an error if something cannot be decrypted, or else print info messages.
export const runIntegrationTests = async (silent: boolean = false) => {
export const runIntegrationTests = async (silent = false) => {
const log = (s: string) => {
if (silent) return;
// eslint-disable-next-line no-console

View File

@ -216,7 +216,7 @@ export function getDefaultMasterKey(): MasterKeyEntity {
// Get the master password if set, or throw an exception. This ensures that
// things aren't accidentally encrypted with an empty string. Calling code
// should look for "undefinedMasterPassword" code and prompt for password.
export function getMasterPassword(throwIfNotSet: boolean = true): string {
export function getMasterPassword(throwIfNotSet = true): string {
const password = Setting.value('encryption.masterPassword');
if (!password && throwIfNotSet) throw new JoplinError('Master password is not set', 'undefinedMasterPassword');
return password;

View File

@ -23,7 +23,7 @@ export default class InteropService_Exporter_Md extends InteropService_Exporter_
await shim.fsDriver().mkdir(this.resourceDir_);
}
private async makeDirPath_(item: any, pathPart: string = null, findUniqueFilename: boolean = true) {
private async makeDirPath_(item: any, pathPart: string = null, findUniqueFilename = true) {
let output = '';
while (true) {
if (item.type_ === BaseModel.TYPE_FOLDER) {

View File

@ -143,7 +143,7 @@ export default class Plugin {
return this.viewControllers_[handle];
}
public deprecationNotice(goneInVersion: string, message: string, isError: boolean = false) {
public deprecationNotice(goneInVersion: string, message: string, isError = false) {
if (isError) {
throw new Error(`"${this.id}": No longer supported: ${message} (deprecated since version ${goneInVersion})`);
} else {

View File

@ -207,7 +207,7 @@ export default class PluginService extends BaseService {
};
}
public async loadPluginFromJsBundle(baseDir: string, jsBundleString: string, pluginIdIfNotSpecified: string = ''): Promise<Plugin> {
public async loadPluginFromJsBundle(baseDir: string, jsBundleString: string, pluginIdIfNotSpecified = ''): Promise<Plugin> {
baseDir = rtrimSlashes(baseDir);
const r = await this.parsePluginJsBundle(jsBundleString);
@ -341,7 +341,7 @@ export default class PluginService extends BaseService {
return this.runner_.callStatsSummary(pluginId, duration);
}
public async loadAndRunPlugins(pluginDirOrPaths: string | string[], settings: PluginSettings, devMode: boolean = false) {
public async loadAndRunPlugins(pluginDirOrPaths: string | string[], settings: PluginSettings, devMode = false) {
let pluginPaths = [];
if (Array.isArray(pluginDirOrPaths)) {
@ -438,7 +438,7 @@ export default class PluginService extends BaseService {
return this.installPluginFromRepo(repoApi, pluginId);
}
public async installPlugin(jplPath: string, loadPlugin: boolean = true): Promise<Plugin | null> {
public async installPlugin(jplPath: string, loadPlugin = true): Promise<Plugin | null> {
logger.info(`Installing plugin: "${jplPath}"`);
// Before moving the plugin to the profile directory, we load it

View File

@ -134,7 +134,7 @@ export default class WebviewController extends ViewController {
// Specific to panels
// ---------------------------------------------
public async show(show: boolean = true): Promise<void> {
public async show(show = true): Promise<void> {
this.store.dispatch({
type: 'MAIN_LAYOUT_SET_ITEM_PROP',
itemKey: this.handle,

View File

@ -101,7 +101,7 @@ export default class JoplinViewsPanels {
/**
* Shows the panel
*/
public async show(handle: ViewHandle, show: boolean = true): Promise<void> {
public async show(handle: ViewHandle, show = true): Promise<void> {
await this.controller(handle).show(show);
}

View File

@ -3,28 +3,28 @@ import validatePluginId from './validatePluginId';
export default function manifestFromObject(o: any): PluginManifest {
const getString = (name: string, required: boolean = true, defaultValue: string = ''): string => {
const getString = (name: string, required = true, defaultValue = ''): string => {
if (required && !o[name]) throw new Error(`Missing required field: ${name}`);
if (!o[name]) return defaultValue;
if (typeof o[name] !== 'string') throw new Error(`Field must be a string: ${name}`);
return o[name];
};
const getNumber = (name: string, required: boolean = true): number => {
const getNumber = (name: string, required = true): number => {
if (required && !o[name]) throw new Error(`Missing required field: ${name}`);
if (!o[name]) return 0;
if (typeof o[name] !== 'number') throw new Error(`Field must be a number: ${name}`);
return o[name];
};
const getStrings = (name: string, required: boolean = true, defaultValue: string[] = []): string[] => {
const getStrings = (name: string, required = true, defaultValue: string[] = []): string[] => {
if (required && !o[name]) throw new Error(`Missing required field: ${name}`);
if (!o[name]) return defaultValue;
if (!Array.isArray(o[name])) throw new Error(`Field must be an array: ${name}`);
return o[name];
};
const getBoolean = (name: string, required: boolean = true, defaultValue: boolean = false): boolean => {
const getBoolean = (name: string, required = true, defaultValue = false): boolean => {
if (required && !o[name]) throw new Error(`Missing required field: ${name}`);
if (!o[name]) return defaultValue;
if (typeof o[name] !== 'boolean') throw new Error(`Field must be a boolean: ${name}`);

View File

@ -1,7 +1,7 @@
class ApiError extends Error {
private httpCode_: number;
public constructor(message: string, httpCode: number = 400) {
public constructor(message: string, httpCode = 400) {
super(message);
this.httpCode_ = httpCode;
}

View File

@ -1,6 +1,6 @@
import filterParser from './filterParser';
const makeTerm = (name: string, value: string, negated: boolean, quoted: boolean = false, wildcard: boolean = false) => {
const makeTerm = (name: string, value: string, negated: boolean, quoted = false, wildcard = false) => {
if (name === 'text') { return { name, value, negated, quoted, wildcard }; }
if (name === 'title' || name === 'body') { return { name, value, negated, wildcard }; }
return { name, value, negated };

View File

@ -43,7 +43,7 @@ describe('ShareService', () => {
it('should not change the note user timestamps when sharing or unsharing', async () => {
let note = await Note.save({});
const service = mockService({
exec: (method: string, path: string = '', _query: Record<string, any> = null, _body: any = null, _headers: any = null, _options: any = null): Promise<any> => {
exec: (method: string, path = '', _query: Record<string, any> = null, _body: any = null, _headers: any = null, _options: any = null): Promise<any> => {
if (method === 'GET' && path === 'api/shares') return { items: [] } as any;
return null;
},

View File

@ -80,7 +80,7 @@ export default class MigrationHandler extends BaseService {
}
}
public async upgrade(targetVersion: number = 0) {
public async upgrade(targetVersion = 0) {
const supportedSyncTargetVersion = Setting.value('syncVersion');
const syncTargetInfo = await this.fetchSyncTargetInfo();

View File

@ -296,7 +296,7 @@ export function getEncryptionEnabled() {
return localSyncInfo().e2ee;
}
export function setEncryptionEnabled(v: boolean, activeMasterKeyId: string = '') {
export function setEncryptionEnabled(v: boolean, activeMasterKeyId = '') {
const s = localSyncInfo();
s.e2ee = v;
if (activeMasterKeyId) s.activeMasterKeyId = activeMasterKeyId;
@ -319,7 +319,7 @@ export function getActiveMasterKey(s: SyncInfo = null): MasterKeyEntity | null {
return s.masterKeys.find(mk => mk.id === s.activeMasterKeyId);
}
export function setMasterKeyEnabled(mkId: string, enabled: boolean = true) {
export function setMasterKeyEnabled(mkId: string, enabled = true) {
const s = localSyncInfo();
const idx = s.masterKeys.findIndex(mk => mk.id === mkId);
if (idx < 0) throw new Error(`No such master key: ${mkId}`);

View File

@ -26,7 +26,7 @@ function lockHandler(): LockHandler {
return lockHandler_;
}
function migrationHandler(clientId: string = 'abcd'): MigrationHandler {
function migrationHandler(clientId = 'abcd'): MigrationHandler {
if (migrationHandler_) return migrationHandler_;
migrationHandler_ = new MigrationHandler(fileApi(), db(), lockHandler(), LockClientType.Desktop, clientId);
return migrationHandler_;

View File

@ -228,7 +228,7 @@ const shim = {
throw new Error('Not implemented');
},
imageToDataUrl: async (_filePath: string, _maxSize: number = 0): Promise<string> => {
imageToDataUrl: async (_filePath: string, _maxSize = 0): Promise<string> => {
throw new Error('Not implemented');
},

View File

@ -375,7 +375,7 @@ async function clearSettingFile(id: number) {
await fs.remove(Setting.settingFilePath);
}
export async function createFolderTree(parentId: string, tree: any[], num: number = 0): Promise<FolderEntity> {
export async function createFolderTree(parentId: string, tree: any[], num = 0): Promise<FolderEntity> {
let rootFolder: FolderEntity = null;
for (const item of tree) {
@ -803,7 +803,7 @@ async function createNTestFolders(n: number) {
return folders;
}
async function createNTestNotes(n: number, folder: any, tagIds: string[] = null, title: string = 'note') {
async function createNTestNotes(n: number, folder: any, tagIds: string[] = null, title = 'note') {
const notes = [];
for (let i = 0; i < n; i++) {
const title_ = n > 1 ? `${title}${i}` : title;

View File

@ -39,7 +39,7 @@ export function credentialFile(filename: string) {
return output;
}
export function readCredentialFile(filename: string, defaultValue: string = '') {
export function readCredentialFile(filename: string, defaultValue = '') {
try {
const filePath = credentialFile(filename);
const r = readFileSync(filePath);

View File

@ -29,7 +29,7 @@ export default class Cache {
private expirableKeys_: ExpirableKeys = {};
private recordKeyHistory_: string[] = [];
public constructor(maxRecords: number = 50) {
public constructor(maxRecords = 50) {
this.maxRecords_ = maxRecords;
}
@ -62,7 +62,7 @@ export default class Cache {
return defaultValue;
}
public setValue(key: string, value: any, ttl: number = 0) {
public setValue(key: string, value: any, ttl = 0) {
this.checkExpiredRecords();
this.records_[key] = {

View File

@ -11,7 +11,7 @@ export function basename(path: string) {
return s[s.length - 1];
}
export function filename(path: string, includeDir: boolean = false): string {
export function filename(path: string, includeDir = false): string {
if (!path) throw new Error('Path is empty');
const output = includeDir ? path : basename(path);
if (output.indexOf('.') < 0) return output;

View File

@ -277,7 +277,7 @@ export async function migrateUnlock(db: DbConnection) {
await db.migrate.forceFreeMigrationsLock();
}
export async function migrateList(db: DbConnection, asString: boolean = true) {
export async function migrateList(db: DbConnection, asString = true) {
const migrations: any = await db.migrate.list({
directory: migrationDir,
});

View File

@ -15,7 +15,7 @@ export default class BackupItemModel extends BaseModel<BackupItem> {
return false;
}
public async add(type: BackupItemType, key: string, content: any, userId: string = ''): Promise<BackupItem> {
public async add(type: BackupItemType, key: string, content: any, userId = ''): Promise<BackupItem> {
const item: BackupItem = {
user_id: userId,
key,

View File

@ -129,7 +129,7 @@ export default abstract class BaseModel<T> {
throw new Error('Must be overriden');
}
protected selectFields(options: LoadOptions, defaultFields: string[] = null, mainTable: string = '', requiredFields: string[] = []): string[] {
protected selectFields(options: LoadOptions, defaultFields: string[] = null, mainTable = '', requiredFields: string[] = []): string[] {
let output: string[] = [];
if (options && options.fields) {
output = options.fields;

View File

@ -16,7 +16,7 @@ export default class EventModel extends BaseModel<Event> {
return UuidType.Native;
}
public async create(type: EventType, name: string = '') {
public async create(type: EventType, name = '') {
await this.save({
name,
type,

View File

@ -460,7 +460,7 @@ export default class ItemModel extends BaseModel<Item> {
return row.content;
}
public async sharedFolderChildrenItems(shareUserIds: Uuid[], folderId: string, includeResources: boolean = true): Promise<Item[]> {
public async sharedFolderChildrenItems(shareUserIds: Uuid[], folderId: string, includeResources = true): Promise<Item[]> {
if (!shareUserIds.length) throw new Error('User IDs must be specified');
let output: Item[] = [];
@ -715,7 +715,7 @@ export default class ItemModel extends BaseModel<Item> {
}
private childrenQuery(userId: Uuid, pathQuery: string = '', count: boolean = false, options: ItemLoadOptions = {}): Knex.QueryBuilder {
private childrenQuery(userId: Uuid, pathQuery = '', count = false, options: ItemLoadOptions = {}): Knex.QueryBuilder {
const query = this
.db('user_items')
.innerJoin('items', 'user_items.item_id', 'items.id')
@ -745,13 +745,13 @@ export default class ItemModel extends BaseModel<Item> {
return `${this.baseUrl}/items/${itemId}/content`;
}
public async children(userId: Uuid, pathQuery: string = '', pagination: Pagination = null, options: ItemLoadOptions = {}): Promise<PaginatedItems> {
public async children(userId: Uuid, pathQuery = '', pagination: Pagination = null, options: ItemLoadOptions = {}): Promise<PaginatedItems> {
pagination = pagination || defaultPagination();
const query = this.childrenQuery(userId, pathQuery, false, options);
return paginateDbQuery(query, pagination, 'items');
}
public async childrenCount(userId: Uuid, pathQuery: string = ''): Promise<number> {
public async childrenCount(userId: Uuid, pathQuery = ''): Promise<number> {
const query = this.childrenQuery(userId, pathQuery, true);
const r = await query.first();
return r ? r.total : 0;

View File

@ -97,7 +97,7 @@ export default class NotificationModel extends BaseModel<Notification> {
return this.add(userId, NotificationKey.Any, NotificationLevel.Error, message);
}
public async setRead(userId: Uuid, key: NotificationKey, read: boolean = true): Promise<void> {
public async setRead(userId: Uuid, key: NotificationKey, read = true): Promise<void> {
const n = await this.loadByKey(userId, key);
if (!n) return;

View File

@ -80,7 +80,7 @@ export default class ShareUserModel extends BaseModel<ShareUser> {
return this.db(this.tableName).where(link).first();
}
public async shareWithUserAndAccept(share: Share, shareeId: Uuid, masterKey: string = '') {
public async shareWithUserAndAccept(share: Share, shareeId: Uuid, masterKey = '') {
await this.models().shareUser().addById(share.id, shareeId, masterKey);
await this.models().shareUser().setStatus(share.id, shareeId, ShareUserStatus.Accepted);
}

View File

@ -42,7 +42,7 @@ export default class TaskStateModel extends BaseModel<TaskState> {
await this.save({ id: state.id, running: 0 });
}
public async enable(taskId: TaskId, enabled: boolean = true) {
public async enable(taskId: TaskId, enabled = true) {
const state = await this.loadByTaskId(taskId);
if (state.enabled && enabled) throw new Error(`Task is already enabled: ${taskId}`);
if (!state.enabled && !enabled) throw new Error(`Task is already disabled: ${taskId}`);

View File

@ -14,7 +14,7 @@ const serializeMode = (mode: StorageDriverMode): string => {
throw new Error(`Invalid type: "${mode}"`);
};
export default function(config: StorageDriverConfig, locationOnly: boolean = true): string {
export default function(config: StorageDriverConfig, locationOnly = true): string {
if (!config) return '';
const items: string[] = [];

View File

@ -214,7 +214,7 @@ export function createPaginationLinks(page: number, pageCount: number, urlTempla
// }
export async function paginateDbQuery(query: Knex.QueryBuilder, pagination: Pagination, mainTable: string = ''): Promise<PaginatedResults<any>> {
export async function paginateDbQuery(query: Knex.QueryBuilder, pagination: Pagination, mainTable = ''): Promise<PaginatedResults<any>> {
pagination = {
...defaultPagination(),
...pagination,

View File

@ -28,7 +28,7 @@ async function postUser(sessionId: string, email: string, password: string = nul
return context.response.body;
}
async function patchUser(sessionId: string, user: any, url: string = ''): Promise<User> {
async function patchUser(sessionId: string, user: any, url = ''): Promise<User> {
const context = await koaAppContext({
sessionId: sessionId,
request: {

View File

@ -84,7 +84,7 @@ export async function putItemContents(path: SubPath, ctx: AppContext, isBatch: b
// within that folder. Except that they cannot delete the root folder if they
// are not the owner, so there's a check in this case.
async function itemFromPath(userId: Uuid, itemModel: ItemModel, path: SubPath, mustExists: boolean = true): Promise<Item> {
async function itemFromPath(userId: Uuid, itemModel: ItemModel, path: SubPath, mustExists = true): Promise<Item> {
const name = itemModel.pathToName(path.id);
const item = await itemModel.loadByName(userId, name);
if (mustExists && !item) throw new ErrorNotFound(`Not found: ${path.id}`);

View File

@ -218,7 +218,7 @@ export const postHandlers: PostHandlers = {
return { sessionId: session.id };
},
webhook: async (stripe: Stripe, _path: SubPath, ctx: AppContext, event: Stripe.Event = null, logErrors: boolean = true) => {
webhook: async (stripe: Stripe, _path: SubPath, ctx: AppContext, event: Stripe.Event = null, logErrors = true) => {
event = event ? event : await stripeEvent(stripe, ctx.req);
const models = ctx.joplin.models;

View File

@ -30,7 +30,7 @@ async function postUser(sessionId: string, email: string, password: string = nul
return context.response.body;
}
async function patchUser(sessionId: string, user: any, url: string = ''): Promise<User> {
async function patchUser(sessionId: string, user: any, url = ''): Promise<User> {
const context = await koaAppContext({
sessionId: sessionId,
request: {

View File

@ -58,7 +58,7 @@ export default class EmailService extends BaseService {
return f.replace(/[\n\r"<>]/g, '');
}
private formatNameAndEmail(email: string, name: string = ''): string {
private formatNameAndEmail(email: string, name = ''): string {
if (!email) throw new Error('Email is required');
const output: string[] = [];
if (name) output.push(`"${this.escapeEmailField(name)}"`);

View File

@ -137,7 +137,7 @@ export default class TaskService extends BaseService {
logger.info(`Completed ${this.taskDisplayString(id)} in ${Date.now() - startTime}ms`);
}
public async enableTask(taskId: TaskId, enabled: boolean = true) {
public async enableTask(taskId: TaskId, enabled = true) {
await this.models.taskState().enable(taskId, enabled);
}

View File

@ -48,7 +48,7 @@ export class ErrorWithCode extends ApiError {
export class ErrorMethodNotAllowed extends ApiError {
public static httpCode = 400;
public constructor(message: string = 'Method Not Allowed', options: ErrorOptions = null) {
public constructor(message = 'Method Not Allowed', options: ErrorOptions = null) {
super(message, ErrorMethodNotAllowed.httpCode, options);
Object.setPrototypeOf(this, ErrorMethodNotAllowed.prototype);
}
@ -57,7 +57,7 @@ export class ErrorMethodNotAllowed extends ApiError {
export class ErrorNotFound extends ApiError {
public static httpCode = 404;
public constructor(message: string = 'Not Found', code: ErrorCode = undefined) {
public constructor(message = 'Not Found', code: ErrorCode = undefined) {
super(message, ErrorNotFound.httpCode, code);
Object.setPrototypeOf(this, ErrorNotFound.prototype);
}
@ -66,7 +66,7 @@ export class ErrorNotFound extends ApiError {
export class ErrorForbidden extends ApiError {
public static httpCode = 403;
public constructor(message: string = 'Forbidden', options: ErrorOptions = null) {
public constructor(message = 'Forbidden', options: ErrorOptions = null) {
super(message, ErrorForbidden.httpCode, options);
Object.setPrototypeOf(this, ErrorForbidden.prototype);
}
@ -75,7 +75,7 @@ export class ErrorForbidden extends ApiError {
export class ErrorBadRequest extends ApiError {
public static httpCode = 400;
public constructor(message: string = 'Bad Request', options: ErrorOptions = null) {
public constructor(message = 'Bad Request', options: ErrorOptions = null) {
super(message, ErrorBadRequest.httpCode, options);
Object.setPrototypeOf(this, ErrorBadRequest.prototype);
}
@ -85,7 +85,7 @@ export class ErrorBadRequest extends ApiError {
export class ErrorPreconditionFailed extends ApiError {
public static httpCode = 412;
public constructor(message: string = 'Precondition Failed', options: ErrorOptions = null) {
public constructor(message = 'Precondition Failed', options: ErrorOptions = null) {
super(message, ErrorPreconditionFailed.httpCode, options);
Object.setPrototypeOf(this, ErrorPreconditionFailed.prototype);
}
@ -95,7 +95,7 @@ export class ErrorPreconditionFailed extends ApiError {
export class ErrorUnprocessableEntity extends ApiError {
public static httpCode = 422;
public constructor(message: string = 'Unprocessable Entity', options: ErrorOptions = null) {
public constructor(message = 'Unprocessable Entity', options: ErrorOptions = null) {
super(message, ErrorUnprocessableEntity.httpCode, options);
Object.setPrototypeOf(this, ErrorUnprocessableEntity.prototype);
}
@ -104,7 +104,7 @@ export class ErrorUnprocessableEntity extends ApiError {
export class ErrorConflict extends ApiError {
public static httpCode = 409;
public constructor(message: string = 'Conflict', code: ErrorCode = undefined) {
public constructor(message = 'Conflict', code: ErrorCode = undefined) {
super(message, ErrorConflict.httpCode, code);
Object.setPrototypeOf(this, ErrorConflict.prototype);
}
@ -113,7 +113,7 @@ export class ErrorConflict extends ApiError {
export class ErrorResyncRequired extends ApiError {
public static httpCode = 400;
public constructor(message: string = 'Delta cursor is invalid and the complete data should be resynced') {
public constructor(message = 'Delta cursor is invalid and the complete data should be resynced') {
super(message, ErrorResyncRequired.httpCode, ErrorCode.ResyncRequired);
Object.setPrototypeOf(this, ErrorResyncRequired.prototype);
}
@ -122,7 +122,7 @@ export class ErrorResyncRequired extends ApiError {
export class ErrorPayloadTooLarge extends ApiError {
public static httpCode = 413;
public constructor(message: string = 'Payload Too Large', options: ErrorOptions = null) {
public constructor(message = 'Payload Too Large', options: ErrorOptions = null) {
super(message, ErrorPayloadTooLarge.httpCode, options);
Object.setPrototypeOf(this, ErrorPayloadTooLarge.prototype);
}
@ -132,7 +132,7 @@ export class ErrorTooManyRequests extends ApiError {
public static httpCode = 429;
public retryAfterMs = 0;
public constructor(message: string = null, retryAfterMs: number = 0) {
public constructor(message: string = null, retryAfterMs = 0) {
super(message === null ? 'Too Many Requests' : message, ErrorTooManyRequests.httpCode);
this.retryAfterMs = retryAfterMs;
Object.setPrototypeOf(this, ErrorTooManyRequests.prototype);

View File

@ -126,7 +126,7 @@ export async function isBetaUser(models: Models, userId: Uuid): Promise<boolean>
return !sub;
}
export function betaUserTrialPeriodDays(userCreatedTime: number, fromDateTime: number = 0, minDays: number = 7): number {
export function betaUserTrialPeriodDays(userCreatedTime: number, fromDateTime = 0, minDays = 7): number {
fromDateTime = fromDateTime ? fromDateTime : Date.now();
const oneDayMs = 86400 * 1000;

View File

@ -15,7 +15,7 @@ import { AppContext } from '../types';
import { checkContextError, koaAppContext, testAssetDir } from './testUtils';
import * as fs from 'fs-extra';
export function testFilePath(ext: string = 'jpg') {
export function testFilePath(ext = 'jpg') {
const basename = ext === 'jpg' ? 'photo' : 'poster';
return `${testAssetDir}/${basename}.${ext}`;
}

View File

@ -66,7 +66,7 @@ async function createItemTree3(sessionId: Uuid, userId: Uuid, parentFolderId: st
}
}
export async function inviteUserToShare(share: Share, sharerSessionId: string, recipientEmail: string, acceptShare: boolean = true) {
export async function inviteUserToShare(share: Share, sharerSessionId: string, recipientEmail: string, acceptShare = true) {
let shareUser = await postApi(sharerSessionId, `shares/${share.id}/users`, {
email: recipientEmail,
}) as ShareUser;
@ -81,7 +81,7 @@ export async function inviteUserToShare(share: Share, sharerSessionId: string, r
return shareUser;
}
export async function shareFolderWithUser(sharerSessionId: string, shareeSessionId: string, sharedFolderId: string, itemTree: any, acceptShare: boolean = true): Promise<ShareResult> {
export async function shareFolderWithUser(sharerSessionId: string, shareeSessionId: string, sharedFolderId: string, itemTree: any, acceptShare = true): Promise<ShareResult> {
itemTree = Array.isArray(itemTree) ? itemTree : convertTree(itemTree);
const sharee = await models().session().sessionUser(shareeSessionId);

View File

@ -6,7 +6,7 @@ require('source-map-support').install();
const { stringify } = require('query-string');
const execCommand = function(command: string, returnStdErr: boolean = false): Promise<string> {
const execCommand = function(command: string, returnStdErr = false): Promise<string> {
const exec = require('child_process').exec;
return new Promise((resolve, reject) => {

View File

@ -259,7 +259,7 @@ interface CreateUserAndSessionOptions {
password?: string;
}
export const createUserAndSession = async function(index: number = 1, isAdmin: boolean = false, options: CreateUserAndSessionOptions = null): Promise<UserAndSession> {
export const createUserAndSession = async function(index = 1, isAdmin = false, options: CreateUserAndSessionOptions = null): Promise<UserAndSession> {
const password = uuidgen();
options = {
@ -278,7 +278,7 @@ export const createUserAndSession = async function(index: number = 1, isAdmin: b
};
};
export const createUser = async function(index: number = 1, isAdmin: boolean = false): Promise<User> {
export const createUser = async function(index = 1, isAdmin = false): Promise<User> {
return models().user().save({ email: `user${index}@localhost`, password: '123456', is_admin: isAdmin ? 1 : 0 }, { skipValidation: true });
};

View File

@ -38,7 +38,7 @@ export function helpUrl(): string {
return `${config().baseUrl}/help`;
}
export function confirmUrl(userId: Uuid, validationToken: string, autoConfirmEmail: boolean = true): string {
export function confirmUrl(userId: Uuid, validationToken: string, autoConfirmEmail = true): string {
return `${config().baseUrl}/users/${userId}/confirm?token=${validationToken}${autoConfirmEmail ? '' : '&confirm_email=0'}`;
}

View File

@ -5,6 +5,6 @@ const generate = require('nanoid/generate');
// > On the other hand, 128 bits (between 21 and 22 characters
// > alphanumeric) is beyond the reach of brute-force attacks pretty much
// > indefinitely
export default function uuidgen(length: number = 22): string {
export default function uuidgen(length = 22): string {
return generate('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', length);
}

View File

@ -20,7 +20,7 @@ export interface GitHubRelease {
draft: boolean;
}
async function insertChangelog(tag: string, changelogPath: string, changelog: string, isPrerelease: boolean, repoTagUrl: string = '') {
async function insertChangelog(tag: string, changelogPath: string, changelog: string, isPrerelease: boolean, repoTagUrl = '') {
repoTagUrl = repoTagUrl || 'https://github.com/laurent22/joplin/releases/tag';
const currentText = await readFile(changelogPath, 'utf8');