Compare commits

...

3 Commits

Author SHA1 Message Date
Milan Burda
07c7cc97be wip 2023-08-05 20:45:12 +02:00
Milan Burda
be63ccb124 refactor: fix errors reported by unicorn/no-array-for-each + enable linting 2023-08-05 20:45:12 +02:00
Milan Burda
1992f374e1 refactor: fix errors reported by unicorn/prefer-logical-operator-over-ternary + enable linting 2023-08-05 20:43:52 +02:00
35 changed files with 152 additions and 136 deletions

View File

@@ -2,7 +2,7 @@
"root": true,
"extends": "standard",
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"plugins": ["@typescript-eslint", "unicorn"],
"env": {
"browser": true
},
@@ -19,7 +19,8 @@
"prefer-const": ["error", {
"destructuring": "all"
}],
"standard/no-callback-literal": "off"
"standard/no-callback-literal": "off",
"unicorn/no-this-assignment": "error"
},
"parserOptions": {
"ecmaVersion": 6,

View File

@@ -319,7 +319,7 @@ export const wrapFsWithAsar = (fs: Record<string, any>) => {
const wrapRealpathSync = function (realpathSync: Function) {
return function (this: any, pathArgument: string, options: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return realpathSync.apply(this, arguments);
if (!pathInfo.isAsar) return Reflect.apply(realpathSync, this, arguments);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
@@ -343,7 +343,7 @@ export const wrapFsWithAsar = (fs: Record<string, any>) => {
const wrapRealpath = function (realpath: Function) {
return function (this: any, pathArgument: string, options: any, callback: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return realpath.apply(this, arguments);
if (!pathInfo.isAsar) return Reflect.apply(realpath, this, arguments);
const { asarPath, filePath } = pathInfo;
if (arguments.length < 3) {
@@ -428,7 +428,7 @@ export const wrapFsWithAsar = (fs: Record<string, any>) => {
const { access } = fs;
fs.access = function (pathArgument: string, mode: any, callback: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return access.apply(this, arguments);
if (!pathInfo.isAsar) return Reflect.apply(access, this, arguments);
const { asarPath, filePath } = pathInfo;
if (typeof mode === 'function') {
@@ -476,7 +476,7 @@ export const wrapFsWithAsar = (fs: Record<string, any>) => {
const { accessSync } = fs;
fs.accessSync = function (pathArgument: string, mode: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return accessSync.apply(this, arguments);
if (!pathInfo.isAsar) return Reflect.apply(accessSync, this, arguments);
const { asarPath, filePath } = pathInfo;
if (mode == null) mode = fs.constants.F_OK;
@@ -567,7 +567,7 @@ export const wrapFsWithAsar = (fs: Record<string, any>) => {
fs.readFile = function (pathArgument: string, options: any, callback: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) {
return readFile.apply(this, arguments);
return Reflect.apply(readFile, this, arguments);
}
return fsReadFileAsar(pathArgument, options, callback);
@@ -577,7 +577,7 @@ export const wrapFsWithAsar = (fs: Record<string, any>) => {
fs.promises.readFile = function (pathArgument: string, options: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) {
return readFilePromise.apply(this, arguments);
return Reflect.apply(readFilePromise, this, arguments);
}
const p = util.promisify(fsReadFileAsar);
@@ -587,7 +587,7 @@ export const wrapFsWithAsar = (fs: Record<string, any>) => {
const { readFileSync } = fs;
fs.readFileSync = function (pathArgument: string, options: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return readFileSync.apply(this, arguments);
if (!pathInfo.isAsar) return Reflect.apply(readFileSync, this, arguments);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
@@ -628,7 +628,7 @@ export const wrapFsWithAsar = (fs: Record<string, any>) => {
callback = options;
options = undefined;
}
if (!pathInfo.isAsar) return readdir.apply(this, arguments);
if (!pathInfo.isAsar) return Reflect.apply(readdir, this, arguments);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
@@ -677,7 +677,7 @@ export const wrapFsWithAsar = (fs: Record<string, any>) => {
const { readdirSync } = fs;
fs.readdirSync = function (pathArgument: string, options: ReaddirSyncOptions | BufferEncoding | null) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return readdirSync.apply(this, arguments);
if (!pathInfo.isAsar) return Reflect.apply(readdirSync, this, arguments);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
@@ -793,7 +793,7 @@ export const wrapFsWithAsar = (fs: Record<string, any>) => {
const processNoAsarOriginalValue = process.noAsar;
process.noAsar = true;
try {
return func.apply(this, arguments);
return Reflect.apply(func, this, arguments);
} finally {
process.noAsar = processNoAsarOriginalValue;
}

View File

@@ -194,8 +194,8 @@ const messageBox = (sync: boolean, window: BrowserWindow | null, options?: Messa
if (cancelId == null) {
// If the defaultId is set to 0, ensure the cancel button is a different index (1)
cancelId = (defaultId === 0 && buttons.length > 1) ? 1 : 0;
for (let i = 0; i < buttons.length; i++) {
const text = buttons[i].toLowerCase();
for (const [i, button] of buttons.entries()) {
const text = button.toLowerCase();
if (text === 'cancel' || text === 'no') {
cancelId = i;
break;

View File

@@ -57,12 +57,17 @@ function sortTopologically<T> (originalOrder: T[], edgesById: Map<T, T[]>) {
marked.add(mark);
const edges = edgesById.get(mark);
if (edges != null) {
edges.forEach(visit);
for (const edge of edges) {
visit(edge);
}
}
sorted.push(mark);
};
originalOrder.forEach(visit);
for (const edge of originalOrder) {
visit(edge);
}
return sorted;
}
@@ -98,24 +103,24 @@ function sortItemsInGroup<T> (group: {before?: T[], after?: T[], id?: T}[]) {
const edges = new Map();
const idToIndex = new Map(group.map((item, i) => [item.id, i]));
group.forEach((item, i) => {
for (const [i, item] of group.entries()) {
if (item.before) {
item.before.forEach(toID => {
for (const toID of item.before) {
const to = idToIndex.get(toID);
if (to != null) {
pushOntoMultiMap(edges, to, i);
}
});
}
}
if (item.after) {
item.after.forEach(toID => {
for (const toID of item.after) {
const to = idToIndex.get(toID);
if (to != null) {
pushOntoMultiMap(edges, i, to);
}
});
}
}
});
}
const sortedNodes = sortTopologically(originalOrder, edges);
return sortedNodes.map(i => group[i]);

View File

@@ -153,9 +153,9 @@ Menu.prototype.insert = function (pos, item) {
Menu.prototype._callMenuWillShow = function () {
if (this.delegate) this.delegate.menuWillShow(this);
this.items.forEach(item => {
for (const item of this.items) {
if (item.submenu) item.submenu._callMenuWillShow();
});
}
};
/* Static Methods */
@@ -196,13 +196,13 @@ Menu.buildFromTemplate = function (template) {
const filtered = removeExtraSeparators(sorted);
const menu = new Menu();
filtered.forEach(item => {
for (const item of filtered) {
if (item instanceof MenuItem) {
menu.append(item);
} else {
menu.append(new MenuItem(item));
}
});
}
return menu;
};
@@ -280,9 +280,9 @@ function insertItemByType (this: MenuType, item: MenuItem, pos: number) {
enumerable: true,
get: () => checked.get(item),
set: () => {
this.groupsMap[item.groupId].forEach(other => {
for (const other of this.groupsMap[item.groupId]) {
if (other !== item) checked.set(other, false);
});
}
checked.set(item, true);
}
});

View File

@@ -70,9 +70,9 @@ class IncomingMessage extends Readable {
get rawHeaders () {
const rawHeadersArr: string[] = [];
const { rawHeaders } = this._responseHead;
rawHeaders.forEach(header => {
for (const header of rawHeaders) {
rawHeadersArr.push(header.key, header.value);
});
}
return rawHeadersArr;
}

View File

@@ -323,13 +323,15 @@ class TouchBar extends EventEmitter implements Electron.TouchBar {
this.items.set(item.id, item);
item.on('change', this.changeListener);
if (item.child instanceof TouchBar) {
item.child.orderedItems.forEach(registerItem);
for (const child of item.child.orderedItems) {
registerItem(child);
}
}
};
let hasOtherItemsProxy = false;
const idSet = new Set();
items.forEach((item) => {
for (const item of items) {
if (!(item instanceof TouchBarItem)) {
throw new TypeError('Each item must be an instance of TouchBarItem');
}
@@ -347,7 +349,7 @@ class TouchBar extends EventEmitter implements Electron.TouchBar {
} else {
throw new Error('Cannot add a single instance of TouchBarItem multiple times in a TouchBar');
}
});
}
// register in separate loop after all items are validated
for (const item of (items as TouchBarItem<any>[])) {

View File

@@ -140,9 +140,9 @@ const createGuest = function (embedder: Electron.WebContents, embedderFrameId: n
const makeProps = (eventKey: string, args: any[]) => {
const props: Record<string, any> = {};
webViewEvents[eventKey].forEach((prop, index) => {
for (const [index, prop] of webViewEvents[eventKey].entries()) {
props[prop] = args[index];
});
}
return props;
};

View File

@@ -31,7 +31,7 @@ process.on('uncaughtException', function (error) {
// so we import it inside the handler down here
import('electron')
.then(({ dialog }) => {
const stack = error.stack ? error.stack : `${error.name}: ${error.message}`;
const stack = error.stack || `${error.name}: ${error.message}`;
const message = 'Uncaught Exception:\n' + stack;
dialog.showErrorBox('A JavaScript error occurred in the main process', message);
});

View File

@@ -80,11 +80,11 @@ export function parseFeatures (features: string) {
const parsed = parseCommaSeparatedKeyValue(features);
const webPreferences: { [K in AllowedWebPreference]?: any } = {};
allowedWebPreferences.forEach((key) => {
if (parsed[key] === undefined) return;
for (const key of allowedWebPreferences) {
if (parsed[key] === undefined) continue;
webPreferences[key] = parsed[key];
delete parsed[key];
});
}
if (parsed.left !== undefined) parsed.x = parsed.left;
if (parsed.top !== undefined) parsed.y = parsed.top;

View File

@@ -52,7 +52,7 @@ export function removeFunction<T extends Function> (fn: T, removedName: string):
const warn = warnOnce(`${fn.name} function`);
return function (this: any) {
warn();
fn.apply(this, arguments);
Reflect.apply(fn, this, arguments);
} as unknown as typeof fn;
}
@@ -61,7 +61,7 @@ export function renameFunction<T extends Function> (fn: T, newName: string): T {
const warn = warnOnce(`${fn.name} function`, `${newName} function`);
return function (this: any) {
warn();
return fn.apply(this, arguments);
return Reflect.apply(fn, this, arguments);
} as unknown as typeof fn;
}
@@ -138,6 +138,6 @@ export function moveAPI<T extends Function> (fn: T, oldUsage: string, newUsage:
const warn = warnOnce(oldUsage, newUsage);
return function (this: any) {
warn();
return fn.apply(this, arguments);
return Reflect.apply(fn, this, arguments);
} as unknown as typeof fn;
}

View File

@@ -10,7 +10,7 @@ if (process.type === 'renderer') {
if (request === 'vm') {
console.warn('The vm module of Node.js is deprecated in the renderer process and will be removed.');
}
return _load.apply(this, arguments);
return Reflect.apply(_load, this, arguments);
};
}

View File

@@ -94,7 +94,7 @@ function useAppVeyorImage (targetBranch, options) {
assert(validJobs.includes(options.job), `Unknown AppVeyor CI job name: ${options.job}. Valid values are: ${validJobs}.`);
callAppVeyorBuildJobs(targetBranch, options.job, options);
} else {
validJobs.forEach((job) => callAppVeyorBuildJobs(targetBranch, job, options));
for (const job of validJobs) callAppVeyorBuildJobs(targetBranch, job, options);
}
}

View File

@@ -193,7 +193,9 @@ function buildAppVeyor (targetBranch, options) {
assert(validJobs.includes(options.job), `Unknown AppVeyor CI job name: ${options.job}. Valid values are: ${validJobs}.`);
callAppVeyor(targetBranch, options.job, options);
} else {
validJobs.forEach((job) => callAppVeyor(targetBranch, job, options));
for (const job of validJobs) {
callAppVeyor(targetBranch, job, options);
}
}
}
@@ -243,7 +245,9 @@ function buildCircleCI (targetBranch, options) {
} else {
assert(!options.arch, 'Cannot provide a single architecture while building all workflows, please specify a single workflow via --workflow');
options.runningPublishWorkflows = true;
circleCIPublishWorkflows.forEach((job) => circleCIcall(targetBranch, job, options));
for (const job of circleCIPublishWorkflows) {
circleCIcall(targetBranch, job, options);
}
}
}

View File

@@ -365,12 +365,14 @@ async function getMergedTrops (commit, pool) {
};
const comments = await getComments(ghKey);
((comments && comments.data) ? comments.data : [])
for (const [branch, key] of (comments?.data || [])
.filter(isTropComment)
.map(getBranchNameAndPullKey)
.filter(pair => pair)
.filter(([branch]) => mergedBranches.has(branch))
.forEach(([branch, key]) => branches.set(branch, key));
) {
branches.set(branch, key);
}
}
}
@@ -461,7 +463,7 @@ const getNotes = async (fromRef, toRef, newVersion) => {
toBranch
};
pool.commits.forEach(commit => {
for (const commit of pool.commits) {
const str = commit.semanticType;
if (commit.isBreakingChange) {
notes.breaking.push(commit);
@@ -478,7 +480,7 @@ const getNotes = async (fromRef, toRef, newVersion) => {
} else {
notes.unknown.push(commit);
}
});
}
return notes;
};

View File

@@ -197,7 +197,7 @@ async function prepareRelease (isBeta, notesOnly) {
const newVersion = await getNewVersion(true);
console.log(newVersion);
} else {
const currentBranch = (args.branch) ? args.branch : await getCurrentBranch(ELECTRON_DIR);
const currentBranch = args.branch || await getCurrentBranch(ELECTRON_DIR);
if (notesOnly) {
const newVersion = await getNewVersion(true);
const releaseNotes = await getReleaseNotes(currentBranch, newVersion);

View File

@@ -58,18 +58,18 @@ new Promise((resolve, reject) => {
.then((dirPath) => {
tempDir = dirPath;
// copy files from `/npm` to temp directory
files.forEach((name) => {
for (const name of files) {
const noThirdSegment = name === 'README.md' || name === 'LICENSE';
fs.writeFileSync(
path.join(tempDir, name),
fs.readFileSync(path.join(ELECTRON_DIR, noThirdSegment ? '' : 'npm', name))
);
});
}
// copy from root package.json to temp/package.json
const packageJson = require(path.join(tempDir, 'package.json'));
jsonFields.forEach((fieldName) => {
for (const fieldName of jsonFields) {
packageJson[fieldName] = rootPackageJson[fieldName];
});
}
packageJson.version = currentElectronVersion;
fs.writeFileSync(
path.join(tempDir, 'package.json'),

View File

@@ -65,9 +65,9 @@ async function validateReleaseAssets (release, validatingRelease) {
const downloadUrls = release.assets.map(asset => ({ url: asset.browser_download_url, file: asset.name })).sort((a, b) => a.file.localeCompare(b.file));
failureCount = 0;
requiredAssets.forEach(asset => {
for (const asset of requiredAssets) {
check(extantAssets.includes(asset), asset);
});
}
check((failureCount === 0), 'All required GitHub assets exist for release', true);
if (!validatingRelease || !release.draft) {

View File

@@ -1229,9 +1229,9 @@ describe('app module', () => {
'http://',
'https://'
];
protocols.forEach((protocol) => {
for (const protocol of protocols) {
expect(app.getApplicationNameForProtocol(protocol)).to.not.equal('');
});
}
});
it('returns an empty string for a bogus protocol', () => {

View File

@@ -276,9 +276,9 @@ describe('BrowserWindow module', () => {
}
};
const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions));
windows.forEach(win => win.show());
windows.forEach(win => win.focus());
windows.forEach(win => win.destroy());
for (const win of windows) win.show();
for (const win of windows) win.focus();
for (const win of windows) win.destroy();
app.removeListener('browser-window-focus', focusListener);
});
});
@@ -1331,31 +1331,31 @@ describe('BrowserWindow module', () => {
const fakeSourceIds = [
'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2'
];
fakeSourceIds.forEach((sourceId) => {
for (const sourceId of fakeSourceIds) {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/);
});
}
});
it('should throw an exception if wrong type', async () => {
const fakeSourceIds = [null as any, 123 as any];
fakeSourceIds.forEach((sourceId) => {
for (const sourceId of fakeSourceIds) {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Error processing argument at index 0 */);
});
}
});
it('should throw an exception if invalid window', async () => {
// It is very unlikely that these window id exist.
const fakeSourceIds = ['window:99999999:0', 'window:123456:1',
'window:123456:9'];
fakeSourceIds.forEach((sourceId) => {
for (const sourceId of fakeSourceIds) {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/);
});
}
});
it('should not throw an exception', async () => {

View File

@@ -1006,10 +1006,10 @@ describe('contextBridge', () => {
}
};
const keys: string[] = [];
Object.entries(toExpose).forEach(([key, value]) => {
for (const [key, value] of Object.entries(toExpose)) {
keys.push(key);
contextBridge.exposeInMainWorld(key, value);
});
}
contextBridge.exposeInMainWorld('keys', keys);
});
const result = await callWithBindings(async (root: any) => {

View File

@@ -60,8 +60,8 @@ ifdescribe(!process.arch.includes('arm') && process.platform !== 'win32')('deskt
const sources = await desktopCapturer.getSources({ types: ['screen'] });
expect(sources).to.be.an('array').of.length(displays.length);
for (let i = 0; i < sources.length; i++) {
expect(sources[i].display_id).to.equal(displays[i].id.toString());
for (const [i, source] of sources.entries()) {
expect(source.display_id).to.equal(displays[i].id.toString());
}
});

View File

@@ -136,9 +136,9 @@ describe('MenuItems', () => {
const groups = findRadioGroups(template);
groups.forEach(g => {
for (const g of groups) {
expect(findChecked(menu.items, g.begin!, g.end!)).to.deep.equal([g.begin]);
});
}
});
it('should assign groupId automatically', () => {
@@ -146,7 +146,7 @@ describe('MenuItems', () => {
const usedGroupIds = new Set();
const groups = findRadioGroups(template);
groups.forEach(g => {
for (const g of groups) {
const groupId = (menu.items[g.begin!] as any).groupId;
// groupId should be previously unused
@@ -158,14 +158,14 @@ describe('MenuItems', () => {
for (let i = g.begin!; i < g.end!; ++i) {
expect((menu.items[i] as any).groupId).to.equal(groupId);
}
});
}
});
it("setting 'checked' should flip other items' 'checked' property", () => {
const menu = Menu.buildFromTemplate(template);
const groups = findRadioGroups(template);
groups.forEach(g => {
for (const g of groups) {
expect(findChecked(menu.items, g.begin!, g.end!)).to.deep.equal([]);
menu.items[g.begin!].checked = true;
@@ -173,7 +173,7 @@ describe('MenuItems', () => {
menu.items[g.end! - 1].checked = true;
expect(findChecked(menu.items, g.begin!, g.end!)).to.deep.equal([g.end! - 1]);
});
}
});
});
});

View File

@@ -68,7 +68,7 @@ async function respondNTimes (fn: http.RequestListener, n: number): Promise<stri
server.on('connection', s => sockets.push(s));
defer(() => {
server.close();
sockets.forEach(s => s.destroy());
for (const s of sockets) s.destroy();
});
return (await listen(server)).url;
}
@@ -771,7 +771,7 @@ describe('net module', () => {
});
});
['Lax', 'Strict'].forEach((mode) => {
for (const mode of ['Lax', 'Strict']) {
it(`should be able to use the sessions cookie store with same-site ${mode} cookies`, async () => {
const serverUrl = await respondNTimes.toSingleURL((request, response) => {
response.statusCode = 200;
@@ -812,7 +812,7 @@ describe('net module', () => {
const response2 = await getResponse(urlRequest2);
expect(response2.headers['x-cookie']).to.equal('same=site');
});
});
}
it('should be able to use the sessions cookie store safely across redirects', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
@@ -1065,7 +1065,7 @@ describe('net module', () => {
await collectStreamBody(await getResponse(urlRequest));
});
['navigate', 'cors', 'no-cors', 'same-origin'].forEach((mode) => {
for (const mode of ['navigate', 'cors', 'no-cors', 'same-origin']) {
it(`should set sec-fetch-mode to ${mode} if requested`, async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-mode']).to.equal(mode);
@@ -1080,7 +1080,7 @@ describe('net module', () => {
urlRequest.setHeader('sec-fetch-mode', mode);
await collectStreamBody(await getResponse(urlRequest));
});
});
}
it('should set sec-fetch-dest to empty by default', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
@@ -1095,12 +1095,12 @@ describe('net module', () => {
await collectStreamBody(await getResponse(urlRequest));
});
[
for (const dest of [
'empty', 'audio', 'audioworklet', 'document', 'embed', 'font',
'frame', 'iframe', 'image', 'manifest', 'object', 'paintworklet',
'report', 'script', 'serviceworker', 'style', 'track', 'video',
'worker', 'xslt'
].forEach((dest) => {
]) {
it(`should set sec-fetch-dest to ${dest} if requested`, async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-dest']).to.equal(dest);
@@ -1115,7 +1115,7 @@ describe('net module', () => {
urlRequest.setHeader('sec-fetch-dest', dest);
await collectStreamBody(await getResponse(urlRequest));
});
});
}
it('should be able to abort an HTTP request before first write', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
@@ -1691,11 +1691,11 @@ describe('net module', () => {
await once(urlRequest, 'close');
await new Promise((resolve, reject) => {
['finish', 'abort', 'close', 'error'].forEach(evName => {
for (const evName of ['finish', 'abort', 'close', 'error']) {
urlRequest.on(evName as any, () => {
reject(new Error(`Unexpected ${evName} event`));
});
});
}
setTimeout(50).then(resolve);
});
});
@@ -1934,9 +1934,9 @@ describe('net module', () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
customHeaders.forEach((headerTuple) => {
for (const headerTuple of customHeaders) {
response.setHeader(headerTuple[0], headerTuple[1]);
});
}
response.end();
});
const urlRequest = net.request(serverUrl);
@@ -1948,15 +1948,15 @@ describe('net module', () => {
expect(rawHeaders).to.be.an('array');
let rawHeadersIdx = 0;
customHeaders.forEach((headerTuple) => {
for (const headerTuple of customHeaders) {
const headerKey = headerTuple[0];
const headerValues = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]];
headerValues.forEach((headerValue) => {
for (const headerValue of headerValues) {
expect(rawHeaders[rawHeadersIdx]).to.equal(headerKey);
expect(rawHeaders[rawHeadersIdx + 1]).to.equal(headerValue);
rawHeadersIdx += 2;
});
});
}
}
await collectStreamBody(response);
});
@@ -2265,7 +2265,7 @@ describe('net module', () => {
const resp = await net.fetch(url.pathToFileURL(path.join(__dirname, 'fixtures', 'hello.txt')).toString());
expect(resp.ok).to.be.true();
// trimRight instead of asserting the whole string to avoid line ending shenanigans on WOA
expect((await resp.text()).trimRight()).to.equal('hello world');
expect((await resp.text()).trimEnd()).to.equal('hello world');
});
it('can make requests to custom protocols', async () => {

View File

@@ -133,14 +133,14 @@ describe('renderer nodeIntegrationInSubFrames', () => {
const generateConfigs = (webPreferences: any, ...permutations: {name: string, webPreferences: any}[]) => {
const configs = [{ webPreferences, names: [] as string[] }];
for (let i = 0; i < permutations.length; i++) {
for (const permutation of permutations) {
const length = configs.length;
for (let j = 0; j < length; j++) {
const newConfig = Object.assign({}, configs[j]);
newConfig.webPreferences = Object.assign({},
newConfig.webPreferences, permutations[i].webPreferences);
newConfig.webPreferences, permutation.webPreferences);
newConfig.names = newConfig.names.slice(0);
newConfig.names.push(permutations[i].name);
newConfig.names.push(permutation.name);
configs.push(newConfig);
}
}
@@ -157,7 +157,7 @@ describe('renderer nodeIntegrationInSubFrames', () => {
});
};
generateConfigs(
for (const config of generateConfigs(
{
preload: path.resolve(__dirname, 'fixtures/sub-frames/preload.js'),
nodeIntegrationInSubFrames: true
@@ -174,9 +174,9 @@ describe('renderer nodeIntegrationInSubFrames', () => {
name: 'webview',
webPreferences: { webviewTag: true, preload: false }
}
).forEach(config => {
)) {
generateTests(config.title, config.webPreferences);
});
}
describe('internal <iframe> inside of <webview>', () => {
let w: BrowserWindow;

View File

@@ -31,7 +31,7 @@ describe('systemPreferences module', () => {
];
const defaultsDict: Record<string, any> = {};
defaultsMap.forEach(row => { defaultsDict[row.key] = row.value; });
for (const row of defaultsMap) { defaultsDict[row.key] = row.value; }
systemPreferences.registerDefaults(defaultsDict);
@@ -159,10 +159,10 @@ describe('systemPreferences module', () => {
it('returns a valid system color', () => {
const colors = ['blue', 'brown', 'gray', 'green', 'orange', 'pink', 'purple', 'red', 'yellow'];
colors.forEach(color => {
for (const color of colors) {
const sysColor = systemPreferences.getSystemColor(color as any);
expect(sysColor).to.be.a('string');
});
}
});
});
@@ -211,10 +211,10 @@ describe('systemPreferences module', () => {
'window-frame-text'
];
colors.forEach(color => {
for (const color of colors) {
const sysColor = systemPreferences.getColor(color as any);
expect(sysColor).to.be.a('string');
});
}
});
});

View File

@@ -1281,10 +1281,10 @@ describe('webContents module', () => {
'default_public_and_private_interfaces',
'disable_non_proxied_udp'
];
policies.forEach((policy) => {
for (const policy of policies) {
w.webContents.setWebRTCIPHandlingPolicy(policy as any);
expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy);
});
}
});
});

View File

@@ -904,7 +904,7 @@ describe('chromium features', () => {
await closeAllWindows();
});
[true, false].forEach((isSandboxEnabled) =>
for (const isSandboxEnabled of [true, false]) {
describe(`sandbox=${isSandboxEnabled}`, () => {
it('posts data in the same window', async () => {
const w = new BrowserWindow({
@@ -954,8 +954,8 @@ describe('chromium features', () => {
const res = await newWin.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello');
});
})
);
});
}
});
describe('window.open', () => {
@@ -1913,7 +1913,7 @@ describe('chromium features', () => {
});
describe('DOM storage quota increase', () => {
['localStorage', 'sessionStorage'].forEach((storageName) => {
for (const storageName of ['localStorage', 'sessionStorage']) {
it(`allows saving at least 40MiB in ${storageName}`, async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
@@ -1959,7 +1959,7 @@ describe('chromium features', () => {
}
})()).to.eventually.be.rejected();
});
});
}
});
describe('persistent storage', () => {

View File

@@ -44,9 +44,9 @@ describe('chrome extensions', () => {
});
afterEach(closeAllWindows);
afterEach(() => {
session.defaultSession.getAllExtensions().forEach((e: any) => {
for (const e of session.defaultSession.getAllExtensions()) {
session.defaultSession.removeExtension(e.id);
});
}
});
it('does not crash when using chrome.management', async () => {
@@ -698,9 +698,9 @@ describe('chrome extensions', () => {
describe('extension ui pages', () => {
afterEach(() => {
session.defaultSession.getAllExtensions().forEach(e => {
for (const e of session.defaultSession.getAllExtensions()) {
session.defaultSession.removeExtension(e.id);
});
}
});
it('loads a ui page of an extension', async () => {

View File

@@ -33,7 +33,7 @@ const testMap = {
connectTab (name) {
chrome.runtime.onConnect.addListener(port => {
port.onMessage.addListener(message => {
console.log([port.name, message].join());
console.log([port.name, message].join(','));
});
});
chrome.runtime.sendMessage({ method: 'connectTab', args: [name] });

View File

@@ -27,7 +27,9 @@ describe('webContents.setWindowOpenHandler', () => {
done(e);
} finally {
process.removeAllListeners('uncaughtException');
listeners.forEach((listener) => process.on('uncaughtException', listener));
for (const listener of listeners) {
process.on('uncaughtException', listener);
}
}
});

View File

@@ -148,9 +148,9 @@ app.whenReady().then(async () => {
const { getFiles } = require('./get-files');
const testFiles = await getFiles(__dirname, { filter });
testFiles.sort().forEach((file) => {
for (const file of testFiles.sort()) {
mocha.addFile(file);
});
}
if (validTestPaths && validTestPaths.length > 0 && testFiles.length === 0) {
console.error('Test files were provided, but they did not match any searched files');

View File

@@ -313,16 +313,16 @@ function bitsToBuffer (bits) {
function generateEBML (json) {
const ebml = [];
for (let i = 0; i < json.length; i++) {
if (!('id' in json[i])) {
for (const element of json) {
if (!('id' in element)) {
// already encoded blob or byteArray
ebml.push(json[i]);
ebml.push(element);
continue;
}
let data = json[i].data;
let data = element.data;
if (typeof data === 'object') data = generateEBML(data);
if (typeof data === 'number') data = ('size' in json[i]) ? numToFixedBuffer(data, json[i].size) : bitsToBuffer(data.toString(2));
if (typeof data === 'number') data = ('size' in element) ? numToFixedBuffer(data, element.size) : bitsToBuffer(data.toString(2));
if (typeof data === 'string') data = strToBuffer(data);
const len = data.size || data.byteLength || data.length;
@@ -335,7 +335,7 @@ function generateEBML (json) {
// going to fix this, i'm probably just going to write some hacky thing which
// converts that string into a buffer-esque thing
ebml.push(numToBuffer(json[i].id));
ebml.push(numToBuffer(element.id));
ebml.push(bitsToBuffer(size));
ebml.push(data);
}
@@ -349,13 +349,13 @@ function toFlatArray (arr, outBuffer) {
if (outBuffer == null) {
outBuffer = [];
}
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] === 'object') {
for (const element of arr) {
if (typeof element === 'object') {
// an array
toFlatArray(arr[i], outBuffer);
toFlatArray(element, outBuffer);
} else {
// a simple element
outBuffer.push(arr[i]);
outBuffer.push(element);
}
}
return outBuffer;

View File

@@ -195,9 +195,9 @@ describe('node feature', () => {
emitter.removeAllListeners(eventName);
emitter.once(eventName, (...args) => {
emitter.removeAllListeners(eventName);
listeners.forEach((listener) => {
for (const listener of listeners) {
emitter.on(eventName, listener);
});
}
callback(...args);
});

View File

@@ -74,14 +74,14 @@ crashReporter.start({
// https://github.com/electron/electron/blob/main/docs/api/desktop-capturer.md
getSources({ types: ['window', 'screen'] }).then(sources => {
for (let i = 0; i < sources.length; ++i) {
if (sources[i].name === 'Electron') {
for (const source of sources) {
if (source.name === 'Electron') {
(navigator as any).webkitGetUserMedia({
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: sources[i].id,
chromeMediaSourceId: source.id,
minWidth: 1280,
maxWidth: 1280,
minHeight: 720,