Skip to content

Commit

Permalink
fix: apply some rudimentary fixes for outstanding TS issues
Browse files Browse the repository at this point in the history
  • Loading branch information
brotheroftux committed Jul 5, 2024
1 parent aa7ea2d commit aa60a93
Show file tree
Hide file tree
Showing 19 changed files with 114 additions and 71 deletions.
6 changes: 6 additions & 0 deletions src/@types/nodeError.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
declare interface Error {
name: string;
message: string;
stack?: string;
code?: number | string;
}
32 changes: 19 additions & 13 deletions src/cmd/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import {
import {prepareMapFile} from '../../steps/processMapFile';
import {copyFiles, logger} from '../../utils';
import {upload as publishFilesToS3} from '../../commands/publish/upload';
import {YfmArgv} from '../../models';
import {Run} from '../../commands/publish';

export const build = {
command: ['build', '$0'],
Expand Down Expand Up @@ -174,7 +176,7 @@ function builder<T>(argv: Argv<T>) {
);
}

async function handler(args: Arguments<any>) {
async function handler(args: Arguments<YfmArgv>) {
const userOutputFolder = resolve(args.output);
const tmpInputFolder = resolve(args.output, TMP_INPUT_FOLDER);
const tmpOutputFolder = resolve(args.output, TMP_OUTPUT_FOLDER);
Expand Down Expand Up @@ -231,7 +233,6 @@ async function handler(args: Arguments<any>) {
outputFormat,
outputBundlePath,
tmpOutputFolder,
userOutputFolder,
});

await processChangelogs();
Expand All @@ -255,20 +256,25 @@ async function handler(args: Arguments<any>) {
storageSecretKey: secretAccessKey,
} = ArgvService.getConfig();

await publishFilesToS3({
input: userOutputFolder,
region: storageRegion,
ignore: [...ignore, TMP_INPUT_FOLDER, TMP_OUTPUT_FOLDER],
endpoint,
bucket,
prefix,
accessKeyId,
secretAccessKey,
});
await publishFilesToS3(
new Run({
input: userOutputFolder,
region: storageRegion,
hidden: [...ignore, TMP_INPUT_FOLDER, TMP_OUTPUT_FOLDER],
endpoint,
bucket,
prefix,
accessKeyId,
secretAccessKey,
quiet: false,
}),
);
}
}
} catch (err) {
logger.error('', err.message);
const message = err instanceof Error ? err.message : String(err);

logger.error('', message);
} finally {
processLogs(tmpInputFolder);

Expand Down
18 changes: 13 additions & 5 deletions src/commands/build/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import type {IProgram} from '~/program';
import type {IProgram, ProgramArgs} from '~/program';
import yargs from 'yargs';
import {hideBin} from 'yargs/helpers';
import {Help} from 'commander';
import log from '@diplodoc/transform/lib/log';

import {BaseProgram} from '~/program/base';
import {BaseHooks, BaseProgram} from '~/program/base';
import {Command} from '~/config';
import {build} from '~/cmd';

Expand All @@ -15,6 +15,10 @@ export type BuildArgs = {};
export type BuildConfig = {};

const parser = yargs
// FIXME: Since we're adding more arguments to the mix with
// `argvValidator` (see src/cmd/build/index.ts#L170), the type safety just completely breaks here
// (which makes sense, because stuff we do is absurdly unsound)
// @ts-expect-error
.command(build)
.option('config', {
alias: 'c',
Expand All @@ -34,20 +38,21 @@ const parser = yargs
type: 'boolean',
})
.group(['config', 'strict', 'quiet', 'help', 'version'], 'Common options:')
.version(typeof VERSION !== 'undefined' ? VERSION : '')
.version(typeof VERSION === 'undefined' ? '' : VERSION)
.help();

export class Build
// eslint-disable-next-line new-cap
extends BaseProgram<BuildConfig, BuildArgs>(command, {
extends BaseProgram<BuildConfig, ProgramArgs>(command, {
config: {
// scope: 'build',
defaults: () => ({}),
},
command: {
isDefault: true,
},
hooks: () => {},
// FIXME: This is a temporary workaround
hooks: (() => {}) as unknown as BaseHooks<BuildConfig, ProgramArgs>,
})
implements IProgram<BuildArgs>
{
Expand All @@ -62,6 +67,9 @@ export class Build

this.command.createHelp = function () {
const help = new Help();
// FIXME: This is not supposed to work, since `parser.getHelp` returns a Promise
// I'm not building a sync bridge for this right now
// @ts-expect-error
help.formatHelp = () => parser.getHelp();
return help;
};
Expand Down
1 change: 1 addition & 0 deletions src/commands/publish/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {describe, expect, it} from 'vitest';
// @ts-expect-error FIXME
import {runPublish as run, testConfig as test} from './__tests__';

describe('Publish command', () => {
Expand Down
2 changes: 1 addition & 1 deletion src/commands/translate/__tests__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export function testConfig<Config = TranslateConfig>(defaultArgs: string) {
});

if (result instanceof Error || typeof result === 'string') {
const message = result.message || result;
const message = result instanceof Error ? result.message : result;
await expect(async () => runTranslate(defaultArgs + ' ' + args)).rejects.toThrow(
message,
);
Expand Down
2 changes: 2 additions & 0 deletions src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ export function args(command: Command | null) {
let args: string[] | undefined;

while (command) {
// FIXME: This is probably broken
// @ts-expect-error
args = command.rawArgs || args;
command = command.parent;
}
Expand Down
6 changes: 3 additions & 3 deletions src/program/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,13 @@ export class Program
}),
},
})
implements IProgram
implements IProgram<ProgramArgs>
{
readonly command: Command = new Command(NAME)
.helpOption(true)
.allowUnknownOption(false)
.version(
typeof VERSION !== 'undefined' ? VERSION : '',
typeof VERSION === 'undefined' ? '' : VERSION,
'--version',
'Output the version number',
)
Expand All @@ -75,7 +75,7 @@ export class Program
.helpOption(false)
.allowUnknownOption(true);

private readonly modules: ICallable[] = [this.build, this.publish, this.translate];
private readonly modules: ICallable<ProgramArgs>[] = [this.build, this.publish, this.translate];

async init(argv: string[]) {
const args = this.parser.parse(argv).opts() as ProgramArgs;
Expand Down
4 changes: 2 additions & 2 deletions src/program/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import type {Logger} from '~/logger';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Hooks = Record<string, Hook<any, any> | HookMap<any>>;

export interface ICallable {
apply(program?: IProgram): void;
export interface ICallable<Args extends Hash = Hash> {
apply(program?: IProgram<Args>): void;
}

/**
Expand Down
8 changes: 5 additions & 3 deletions src/resolvers/lintPage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {dirname, relative, resolve} from 'path';
import {load} from 'js-yaml';
import log from '@diplodoc/transform/lib/log';
import log, {LogLevels} from '@diplodoc/transform/lib/log';
import {
LintMarkdownFunctionOptions,
PluginOptions,
Expand Down Expand Up @@ -76,15 +76,17 @@ function YamlFileLinter(content: string, lintOptions: FileTransformOptions): voi
defaultLevel: log.LogLevels.ERROR,
});

const contentLinks = findAllValuesByKeys(load(content), LINK_KEYS);
const contentLinks = findAllValuesByKeys(load(content) as object, LINK_KEYS);
const localLinks = contentLinks.filter(
(link) => getLinksWithExtension(link) && isLocalUrl(link),
);

const loggerForLogLevel = logLevel === LogLevels.DISABLED ? () => undefined : log[logLevel];

return localLinks.forEach(
(link) =>
checkPathExists(link, currentFilePath) ||
log[logLevel](`Link is unreachable: ${bold(link)} in ${bold(currentFilePath)}`),
loggerForLogLevel(`Link is unreachable: ${bold(link)} in ${bold(currentFilePath)}`),
);
}

Expand Down
12 changes: 11 additions & 1 deletion src/resolvers/md2html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,13 @@ export async function resolveMd2HTML(options: ResolverOptions): Promise<DocInner
const {outputPath, inputPath, deep, deepBase} = options;
const props = await getFileProps(options);

// FIXME: Whatever we're doing with app props in CLI is pretty unsound
// @ts-expect-error
const outputFileContent = generateStaticMarkup(props, deepBase, deep);
writeFileSync(outputPath, outputFileContent);
logger.info(inputPath, PROCESSING_FINISHED);

// @ts-expect-error
return props;
}

Expand Down Expand Up @@ -170,11 +173,18 @@ function YamlFileTransformer(content: string, transformOptions: FileTransformOpt
if (isString(link) && getLinksWithContentExtersion(link)) {
return link.replace(/.(md|yaml)$/gmu, '.html');
}

return link;
});

// FIXME: This is unsound, since `lang` does not exist on FileTransformOptions
// I'll leave this here for the sake of not breaking stuff
// @ts-expect-error
const {path, lang} = transformOptions;
const transformFn: Function = FileTransformer['.md'];

// FIXME: Whatever we're doing here with prop transformations, it seems quite unsound
// @ts-expect-error
data = preprocess(data, {lang}, (lang, content) => {
const {result} = transformFn(content, {path});
return result?.html;
Expand Down Expand Up @@ -221,7 +231,7 @@ function MdFileTransformer(content: string, transformOptions: FileTransformOptio

return transform(content, {
...options,
plugins: plugins as MarkdownItPluginCb<unknown>[],
plugins: plugins as MarkdownItPluginCb[],
vars,
root,
path,
Expand Down
10 changes: 7 additions & 3 deletions src/services/contributors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ async function getContributorsForNestedFiles(
try {
contentIncludeFile = await readFile(relativeIncludeFilePath, 'utf8');
} catch (err) {
if (err.code === 'ENOENT') {
if (err instanceof Error && err.code === 'ENOENT') {
continue;
}
throw err;
Expand Down Expand Up @@ -135,14 +135,18 @@ async function getFileIncludes(
);
for (const relativeIncludeFilePath of relativeIncludeFilePaths.values()) {
const relativeFilePath = relativeIncludeFilePath.substring(inputFolderPathLength + 1);
if (results.has(relativeFilePath)) continue;

if (results.has(relativeFilePath)) {
continue;
}

results.add(relativeFilePath);

let contentIncludeFile: string;
try {
contentIncludeFile = await readFile(relativeIncludeFilePath, 'utf8');
} catch (err) {
if (err.code === 'ENOENT') {
if (err instanceof Error && err.code === 'ENOENT') {
continue;
}
throw err;
Expand Down
4 changes: 3 additions & 1 deletion src/services/includers/batteries/generic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,9 @@ async function includerFunction(params: IncluderFunctionParams<Params>) {

await writeFile(join(writePath, 'toc.yaml'), dump(toc));
} catch (err) {
throw new GenericIncluderError(err.toString(), tocPath);
const message = err instanceof Error ? err.message : String(err);

throw new GenericIncluderError(message, tocPath);
}
}

Expand Down
4 changes: 3 additions & 1 deletion src/services/includers/batteries/unarchive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ async function includerFunction(params: IncluderFunctionParams<Params>) {
try {
await pipeline(contentPath, writePath);
} catch (err) {
throw new UnarchiveIncluderError(err.toString(), tocPath);
const message = err instanceof Error ? err.message : String(err);

throw new UnarchiveIncluderError(message, tocPath);
}
}

Expand Down
Loading

0 comments on commit aa60a93

Please sign in to comment.