Skip to content

Commit

Permalink
refactor(scripts): fix type definitions
Browse files Browse the repository at this point in the history
follow f1bc534
  • Loading branch information
AnYiEE committed Dec 21, 2023
1 parent f1bc534 commit c1b7189
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 51 deletions.
5 changes: 4 additions & 1 deletion scripts/modules/babel-plugin-import-polyfills.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* eslint-disable camelcase */
/* eslint-disable camelcase, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return */
/**
* @file Automatically import any missing polyfills
* @see {@link https://github.com/zloirock/core-js#missing-polyfills}
Expand All @@ -8,6 +8,7 @@ import {type BrowserSupport, getSupport} from 'caniuse-api';
/**
* @see {@link https://babeljs.io/docs/babel-helper-compilation-targets#filteritems}
*/
// @ts-expect-error TS7016
import {filterItems} from '@babel/helper-compilation-targets';
import {getRootDir} from './utils/general-util';
import {join} from 'node:path';
Expand Down Expand Up @@ -119,11 +120,13 @@ const polyfills: Record<
* @param {Object} types
* @param {string} packageName
*/
// @ts-expect-error TS7006
const addImport = (path, types: BabelAPI['types'], packageName: (typeof polyfills)[Features]['package']): void => {
const stringLiteral = types.stringLiteral(packageName);
const importDeclaration = types.importDeclaration([], stringLiteral);

path
// @ts-expect-error TS7006
.findParent((parent): boolean => {
return parent.isProgram();
})
Expand Down
3 changes: 3 additions & 0 deletions scripts/modules/build-esbuild_options.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
/* eslint-disable @typescript-eslint/no-unsafe-call */
import {type BuildOptions} from 'esbuild';
// @ts-expect-error TS7016
import LessPluginNpmImport from 'less-plugin-npm-import';
// @ts-expect-error TS7016
import LessPluginPresetEnv from 'less-plugin-preset-env';
import {lessLoader} from 'esbuild-plugin-less';
import postcss from 'esbuild-postcss';
Expand Down
76 changes: 40 additions & 36 deletions scripts/modules/utils/build-util.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as PACKAGE from '../../../package.json';
import {BANNER, DEFAULT_DEFINITION, GLOBAL_REQUIRES_ES6, HEADER} from '../../constant';
import {type BabelFileResult, type PluginItem, type TransformOptions, transformAsync} from '@babel/core';
import {type BabelFileResult, type TransformOptions, transformAsync} from '@babel/core';
import {type BuildResult, type OutputFile, build as esbuild} from 'esbuild';
import type {DefaultDefinition, ExcludeItem, SourceFiles} from '../types';
import {
Expand Down Expand Up @@ -56,7 +56,7 @@ const writeFile = (sourceCode: string, outputFilePath: string, licenseText: stri
*/
const getBuildResult = (buildResult: BuildResult): string => {
const outputFiles: OutputFile[] = buildResult.outputFiles as OutputFile[];
const [{text}] = outputFiles;
const {text} = outputFiles[0] as OutputFile;

return text;
};
Expand Down Expand Up @@ -91,7 +91,7 @@ const bundle = async (inputFilePath: string, code: string): Promise<string> => {
resolveDir: rootDir,
sourcefile: inputFilePath,
},
target: GLOBAL_REQUIRES_ES6 ? undefined : 'es5',
target: GLOBAL_REQUIRES_ES6 ? 'exnext' : 'es5',
});

return getBuildResult(buildResult);
Expand Down Expand Up @@ -122,8 +122,8 @@ const generateTransformOptions = (): TransformOptions => {
};

if (GLOBAL_REQUIRES_ES6) {
const [[, {exclude}]] = options.presets as ExcludeItem;
(options.presets as PluginItem[])[0][1].exclude = [...exclude, 'es.array.push'];
const [, {exclude}] = options.presets as ExcludeItem[0];
(options.presets as ExcludeItem[0])[1].exclude = [...exclude, 'es.array.push'];
// 以下关键字和运算符无法被 MediaWiki(>= 1.39)的 JavaScript 压缩器良好支持,即使设置了 requiresES6 标识
// The following keywords and operators are not well supported by MediaWiki's (>= 1.39) JavaScript minifier, even if the `requiresES6` flag is true
options.plugins = [
Expand Down Expand Up @@ -238,7 +238,7 @@ const buildFiles = (
const buildFile: typeof buildScript | typeof buildStyle = type === 'script' ? buildScript : buildStyle;

for (const file of files) {
queue.add(async (): Promise<void> => {
void queue.add(async (): Promise<void> => {
await buildFile(name, file, licenseText);
});
}
Expand Down Expand Up @@ -273,61 +273,65 @@ const findSourceFile = (currentPath: string = 'src'): SourceFiles => {
continue;
}

const [_rootDir, gadgetName, fileName] = pathSplitArray;
const [_rootDir, gadgetName, fileName] = pathSplitArray as [string, string, string];
sourceFiles[gadgetName] ??= {} as SourceFiles[keyof SourceFiles];

switch (fileName) {
case 'definition.json':
sourceFiles[gadgetName].definition = fileName;
(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).definition = fileName;
break;
case 'index.js':
case 'index.ts':
sourceFiles[gadgetName].script = fileName;
(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).script = fileName;
break;
case `${gadgetName}.js`:
case `${gadgetName}.ts`:
if (!sourceFiles[gadgetName].script) {
sourceFiles[gadgetName].script = fileName;
if (!(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).script) {
(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).script = fileName;
}
break;
case 'index.css':
case 'index.less':
sourceFiles[gadgetName].style = fileName;
(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).style = fileName;
break;
case `${gadgetName}.css`:
case `${gadgetName}.less`:
if (!sourceFiles[gadgetName].style) {
sourceFiles[gadgetName].style = fileName;
if (!(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).style) {
(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).style = fileName;
}
break;
case 'LICENSE':
sourceFiles[gadgetName].license = fileName;
(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).license = fileName;
break;
}

sourceFiles[gadgetName].scripts ??= [];
(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).scripts ??= [];
if (/\.[jt]s$/.test(fileName)) {
sourceFiles[gadgetName].scripts.push(fileName);
(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).scripts.push(fileName);
if (/\.ts$/.test(fileName)) {
sourceFiles[gadgetName].scripts = [
(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).scripts = [
...new Set(
sourceFiles[gadgetName].scripts.filter((script: string): boolean => {
return script !== fileName.replace(/\.ts$/, '.js');
})
(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).scripts.filter(
(script: string): boolean => {
return script !== fileName.replace(/\.ts$/, '.js');
}
)
),
];
}
}

sourceFiles[gadgetName].styles ??= [];
(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).styles ??= [];
if (/\.(?:css|less)$/.test(fileName)) {
sourceFiles[gadgetName].styles.push(fileName);
(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).styles.push(fileName);
if (/\.less$/.test(fileName)) {
sourceFiles[gadgetName].styles = [
(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).styles = [
...new Set(
sourceFiles[gadgetName].styles.filter((style: string): boolean => {
return style !== fileName.replace(/\.less$/, '.css');
})
(sourceFiles[gadgetName] as SourceFiles[keyof SourceFiles]).styles.filter(
(style: string): boolean => {
return style !== fileName.replace(/\.less$/, '.css');
}
)
),
];
}
Expand Down Expand Up @@ -364,9 +368,9 @@ const generateDefinitionItem = (name: string, definition: string | undefined, fi
)
);
}
const definitionObject: DefaultDefinition = {
const definitionObject: DefaultDefinition & {requiresES6: boolean} = {
...DEFAULT_DEFINITION,
...JSON.parse(definitionJsonText),
...(JSON.parse(definitionJsonText) as DefaultDefinition),
requiresES6: GLOBAL_REQUIRES_ES6,
};

Expand All @@ -378,8 +382,8 @@ const generateDefinitionItem = (name: string, definition: string | undefined, fi
const isArray: boolean = Array.isArray(value);
if (
['description', 'section', 'type'].includes(key) ||
[false, undefined].includes(value) ||
(isArray && !value.length)
[false, undefined].includes(value as boolean | undefined) ||
(isArray && !(value as []).length)
) {
continue;
}
Expand All @@ -392,7 +396,7 @@ const generateDefinitionItem = (name: string, definition: string | undefined, fi
break;
case 'object':
if (isArray) {
definitionText += `${key}=${value.join(',')}|`;
definitionText += `${key}=${(value as []).join(',')}|`;
}
break;
case 'string':
Expand Down Expand Up @@ -465,7 +469,7 @@ const getLicense = (name: string, license: string | undefined): string | undefin
const licenseFilePath: string = join(rootDir, `src/${name}/${license}`);
const fileBuffer: Buffer = readFileSync(licenseFilePath);

return fileBuffer.toString().trim() ? `${fileBuffer}\n` : undefined;
return fileBuffer.toString().trim() ? `${fileBuffer.toString()}\n` : undefined;
};

/**
Expand All @@ -476,14 +480,14 @@ const getLicense = (name: string, license: string | undefined): string | undefin
const saveDefinition = (definitions: string[]): void => {
const definitionObject: Record<string, typeof definitions> = {};
for (const definition of definitions) {
const [, section] = definition.match(/.*?(\S+?)/) as RegExpExecArray;
const [, section] = definition.match(/.*?(\S+?)/) as [string, string];
definitionObject[section] ??= [];
definitionObject[section].push(definition.replace(/.*/, ''));
(definitionObject[section] as string[]).push(definition.replace(/.*/, ''));
}

const definitionObjectSorted: typeof definitionObject = {};
for (const key of Object.keys(definitionObject).sort()) {
definitionObjectSorted[key] = definitionObject[key];
definitionObjectSorted[key] = definitionObject[key] as string[];
}

let definitionText: string = '';
Expand Down
29 changes: 16 additions & 13 deletions scripts/modules/utils/deploy-util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,23 @@ const generateTargets = (definitions: string[]): DeploymentTargets => {
const targets: DeploymentTargets = {};

for (const definition of definitions) {
const [_, name, files, description] = definition.match(
/^\*\s(\S+?)\[\S+?]\|(\S+?)\S*?(.+?)$/
) as RegExpMatchArray;
const [_, name, files, description] = definition.match(/^\*\s(\S+?)\[\S+?]\|(\S+?)\S*?(.+?)$/) as [
string,
string,
string,
string,
];

targets[name] = {} as DeploymentTargets[keyof DeploymentTargets];
targets[name].files = files
(targets[name] as DeploymentTargets[keyof DeploymentTargets]).files = files
.split('|')
.filter((file: string): boolean => {
return !!file;
})
.map((file: string): string => {
return file.replace(/\S+?/, '');
});
targets[name].description = description || name;
(targets[name] as DeploymentTargets[keyof DeploymentTargets]).description = description || name;
}

return targets;
Expand Down Expand Up @@ -93,7 +96,7 @@ const loadConfig = (): Partial<Credentials> => {
);
}

return JSON.parse(credentialsJsonText);
return JSON.parse(credentialsJsonText) as ReturnType<typeof loadConfig>;
};

/**
Expand Down Expand Up @@ -242,7 +245,7 @@ const convertVariant = (pageTitle: string, content: string, {api, queue}: ApiQue
);

const window: Window = new Window({
url: api.options.apiUrl,
url: api.options.apiUrl as string,
});
const {document} = window;
document.body.innerHTML = `<div>${parsedHtml}</div>`;
Expand Down Expand Up @@ -290,7 +293,7 @@ const saveDefinition = (definitionText: string, {api, queue}: ApiQueue, editSumm
const pageTitle: string = 'MediaWiki:Gadgets-definition';
deployPages.push(pageTitle);

queue.add(async (): Promise<void> => {
void queue.add(async (): Promise<void> => {
try {
const response: ApiEditResponse = await api.save(pageTitle, definitionText, editSummary);
if (response.nochange) {
Expand Down Expand Up @@ -325,10 +328,10 @@ const saveDefinitionSectionPage = (definitionText: string, apiQueue: ApiQueue, e
for (const [index, section] of sections.entries()) {
const sectionText: string = DEFINITION_SECTION_MAP[section] || section;

const pageTitle: string = pageTitles[index];
const pageTitle: string = pageTitles[index] as string;
deployPages.push(pageTitle);

apiQueue.queue.add(async (): Promise<void> => {
void apiQueue.queue.add(async (): Promise<void> => {
try {
const response: ApiEditResponse = await apiQueue.api.save(pageTitle, sectionText, editSummary);
if (response.nochange) {
Expand Down Expand Up @@ -360,7 +363,7 @@ const saveDescription = (name: string, description: string, apiQueue: ApiQueue,
const pageTitle: string = `MediaWiki:Gadget-${name}`;
deployPages.push(pageTitle);

apiQueue.queue.add(async (): Promise<void> => {
void apiQueue.queue.add(async (): Promise<void> => {
try {
const response: ApiEditResponse = await apiQueue.api.save(pageTitle, description, editSummary);
if (response.nochange) {
Expand Down Expand Up @@ -403,7 +406,7 @@ const saveFiles = (
const pageTitle: string = `MediaWiki:Gadget-${fileName}`;
deployPages.push(pageTitle);

queue.add(async (): Promise<void> => {
void queue.add(async (): Promise<void> => {
try {
const response: ApiEditResponse = await api.save(pageTitle, fileContent, editSummary);
if (response.nochange) {
Expand Down Expand Up @@ -481,7 +484,7 @@ const deleteUnusedPages = async ({api, queue}: ApiQueue, editSummary: string): P
};

for (const page of needToDeletePages) {
queue.add(async (): Promise<void> => {
void queue.add(async (): Promise<void> => {
await deletePage(page);
});
}
Expand Down
2 changes: 1 addition & 1 deletion scripts/modules/utils/general-util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const prompt = async (message: string, type: PromptType = 'text', initial: boole
type,
});

const answer: string | undefined = answers[name];
const answer: string | undefined = answers[name] as string | undefined;
if (answer === undefined || (type === 'confirm' && !answer)) {
// User pressed [ctrl + C] or not confirmed
console.log(chalk.red('Input cancelled, program terminated.'));
Expand Down

0 comments on commit c1b7189

Please sign in to comment.