Skip to content

Commit

Permalink
stricter eslint done i thinks
Browse files Browse the repository at this point in the history
  • Loading branch information
Gnuxie committed Jul 22, 2024
1 parent cff1908 commit 3c6cae0
Show file tree
Hide file tree
Showing 26 changed files with 253 additions and 177 deletions.
22 changes: 9 additions & 13 deletions src/commands/interface-manager/DeadDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export interface AbstractNode {

export interface DocumentNode extends AbstractNode {
readonly leafNode: false;
attributeMap: Map<string, any>,
attributeMap: Map<string, string>,
addChild<Node extends DocumentNode|LeafNode>(node: Node): Node
getChildren(): (DocumentNode|LeafNode)[]
getFirstChild(): DocumentNode|LeafNode|undefined;
Expand Down Expand Up @@ -81,7 +81,7 @@ export enum NodeTag {
*/
interface DeadDocumentNode extends DocumentNode {
children: (DocumentNode|LeafNode)[];
attributeMap: Map<string, any>,
attributeMap: Map<string, string>,
}

export function addChild<Node extends DocumentNode|LeafNode>(this: DeadDocumentNode, node: Node): Node {
Expand Down Expand Up @@ -202,9 +202,6 @@ export class SimpleFringeRenderer<Context> implements FringeRenderer<Context> {
private readonly preRenderers = new Map<NodeTag, FringeInnerRenderFunction<Context>>();
private readonly leafRenderers = new Map<NodeTag, FringeLeafRenderFunction<Context>>();
private readonly postRenderers = new Map<NodeTag, FringeInnerRenderFunction<Context>>();
constructor() {

}

private getRenderer<T>(table: Map<NodeTag, T>, type: FringeType, tag: NodeTag): T {
const entry = table.get(tag);
Expand Down Expand Up @@ -326,11 +323,10 @@ export class FringeWalker<Context> {
postNode(annotatedNode);
break;
case FringeType.Leaf:
if (annotatedNode.node.leafNode !== true) {
if (!annotatedNode.node.leafNode) {
throw new TypeError("Leaf nodes should not be marked as an inner node");
}
this.renderer.getLeafRenderer(annotatedNode.node.tag)
(annotatedNode.node.tag, annotatedNode.node as unknown as LeafNode, this.context);
this.renderer.getLeafRenderer(annotatedNode.node.tag)(annotatedNode.node.tag, annotatedNode.node as unknown as LeafNode, this.context);
break;
default:
throw new TypeError(`Uknown fringe type ${annotatedNode.type}`);
Expand All @@ -348,7 +344,7 @@ export class FringeWalker<Context> {
export class TagDynamicEnvironmentEntry {
constructor(
public readonly node: DocumentNode,
public value: any,
public value: unknown,
public readonly previous: undefined|TagDynamicEnvironmentEntry,
) {

Expand Down Expand Up @@ -376,16 +372,16 @@ export class TagDynamicEnvironmentEntry {
export class TagDynamicEnvironment {
private readonly environments = new Map<string, TagDynamicEnvironmentEntry|undefined>();

public read(variableName: string): any {
public read<T = unknown>(variableName: string): T {
const variableEntry = this.environments.get(variableName);
if (variableEntry) {
return variableEntry.value;
return variableEntry.value as T;
} else {
throw new TypeError(`The variable ${variableName} is unbound.`);
}
}

public write(variableName: string, value: any): any {
public write<T = unknown>(variableName: string, value: T): T {
const variableEntry = this.environments.get(variableName);
if (variableEntry) {
return variableEntry.value = value;
Expand All @@ -394,7 +390,7 @@ export class TagDynamicEnvironment {
}
}

public bind(variableName: string, node: DocumentNode, value: any): any {
public bind<T = unknown>(variableName: string, node: DocumentNode, value: T): T {
const entry = this.environments.get(variableName);
const newEntry = new TagDynamicEnvironmentEntry(node, value, entry);
this.environments.set(variableName, newEntry);
Expand Down
16 changes: 8 additions & 8 deletions src/commands/interface-manager/DeadDocumentMarkdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ export function blank() { }
export function incrementDynamicEnvironment(_fringe: FringeType, node: DocumentNode, _context: TransactionalOutputContext, environment: TagDynamicEnvironment) {
const value = (() => {
try {
return environment.read(MarkdownVariables.IndentationLevel);
} catch (_e: any) {
return environment.read<undefined | number>(MarkdownVariables.IndentationLevel);
} catch (_e: unknown) {
return environment.bind(MarkdownVariables.IndentationLevel, node, 0);
}
})();
Expand Down Expand Up @@ -75,24 +75,24 @@ MARKDOWN_RENDERER.registerRenderer<FringeLeafRenderFunction<TransactionalOutputC
staticString('**'),
staticString('**')
).registerInnerNode(NodeTag.UnorderedList,
function(_fringe: FringeType, node: DocumentNode, context: TransactionalOutputContext, environment: TagDynamicEnvironment) {
incrementDynamicEnvironment.apply(undefined, arguments);
function(fringe: FringeType, node: DocumentNode, context: TransactionalOutputContext, environment: TagDynamicEnvironment) {
incrementDynamicEnvironment(fringe, node, context, environment);
environment.bind(MarkdownVariables.ListType, node, NodeTag.UnorderedList);
environment.bind(MarkdownVariables.ListItemCount, node, 0);
},
blank
).registerInnerNode(NodeTag.ListItem,
function(_fringe, node, context, environment) {
const indentationLevel: number = (() => {
const value = environment.read(MarkdownVariables.IndentationLevel);
const value = environment.read<number>(MarkdownVariables.IndentationLevel);
if (!Number.isInteger(value)) {
throw new TypeError(`Cannot render the list ${node.tag} because someone clobbered the dynamic environment, should only have integers. Did you forget to enclose in <ul> or <ol>?`)
} else {
return value;
}
})();
const listItemCount = (() => {
const currentCount = environment.read(MarkdownVariables.ListItemCount);
const currentCount = environment.read<number>(MarkdownVariables.ListItemCount);
if (!Number.isInteger(currentCount)) {
throw new TypeError(`Cannot render the list ${node.tag} because someone clobbered the dynamic environment.`);
}
Expand All @@ -111,8 +111,8 @@ MARKDOWN_RENDERER.registerRenderer<FringeLeafRenderFunction<TransactionalOutputC
},
staticString('\n')
).registerInnerNode(NodeTag.OrderedList,
function(_fringe: FringeType, node: DocumentNode, context: TransactionalOutputContext, environment: TagDynamicEnvironment) {
incrementDynamicEnvironment.apply(undefined, arguments);
function(fringe: FringeType, node: DocumentNode, context: TransactionalOutputContext, environment: TagDynamicEnvironment) {
incrementDynamicEnvironment(fringe, node, context, environment);
environment.bind(MarkdownVariables.ListType, node, NodeTag.OrderedList);
environment.bind(MarkdownVariables.ListItemCount, node, 0);
},
Expand Down
15 changes: 12 additions & 3 deletions src/commands/interface-manager/DeadDocumentMatrix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { AbstractNode, DocumentNode, FringeWalker, NodeTag } from "./DeadDocumen
import { HTML_RENDERER } from "./DeadDocumentHtml";
import { MARKDOWN_RENDERER } from "./DeadDocumentMarkdown";
import { PagedDuplexStream } from "./PagedDuplexStream";
import { RoomEvent } from "matrix-protection-suite";

function checkEqual(node1: AbstractNode|undefined, node2: AbstractNode|undefined): true {
if (!Object.is(node1, node2)) {
Expand Down Expand Up @@ -59,7 +60,11 @@ export async function renderMatrix(node: DocumentNode, cb: SendMatrixEventCB): P
// so that the same committed nodes end up in the same message.
outputs.filter(o => !o.peekPage()).forEach(o => { o.ensureNewPage(); });
// Send the new pages as an event.
eventIds.push(await cb(markdownOutput.readPage()!, htmlOutput.readPage()!));
const [nextMakrdownPage, nextHtmlPage] = [markdownOutput.readPage(), htmlOutput.readPage()];
if (nextMakrdownPage === undefined || nextHtmlPage === undefined) {
throw new TypeError(`The code is wrong!!`);
}
eventIds.push(await cb(nextMakrdownPage, nextHtmlPage));
}
// prepare next iteration
currentMarkdownNode = markdownWalker.increment();
Expand All @@ -68,7 +73,11 @@ export async function renderMatrix(node: DocumentNode, cb: SendMatrixEventCB): P
}
outputs.forEach(o => { o.ensureNewPage(); });
if (outputs.some(o => o.peekPage())) {
eventIds.push(await cb(markdownOutput.readPage()!, htmlOutput.readPage()!));
const [nextMakrdownPage, nextHtmlPage] = [markdownOutput.readPage(), htmlOutput.readPage()];
if (nextMakrdownPage === undefined || nextHtmlPage === undefined) {
throw new TypeError(`The code is wrong!!`);
}
eventIds.push(await cb(nextMakrdownPage, nextHtmlPage));
}
return eventIds;
}
Expand All @@ -80,7 +89,7 @@ export async function renderMatrix(node: DocumentNode, cb: SendMatrixEventCB): P
* @param event An event to reply to, if any.
* @param client A MatrixClient to send the events with.
*/
export async function renderMatrixAndSend(node: DocumentNode, roomId: string, event: any|undefined, client: MatrixSendClient, additionalContent = {}): Promise<string[]> {
export async function renderMatrixAndSend(node: DocumentNode, roomId: string, event: RoomEvent | undefined, client: MatrixSendClient, additionalContent = {}): Promise<string[]> {
const baseContent = (text: string, html: string) => {
return {
msgtype: "m.notice",
Expand Down
1 change: 1 addition & 0 deletions src/commands/interface-manager/DeadDocumentPresentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export const DeadDocumentPresentationMirror = Object.freeze({
const renderer = findPresentationRenderer(presentationType);
return renderer(object);
} else {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new TypeError(`Unable to present: ${object}`);
}
}
Expand Down
7 changes: 5 additions & 2 deletions src/commands/interface-manager/JSXFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ type JSXChild = DocumentNode|LeafNode|string|number|JSXChild[];
type NodeProperties = { children?: JSXChild[]|JSXChild };
type LeafNodeProperties = { children?: never[] };

// We need to use a namespace here for the JSXFactory, at least i think.
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace DeadDocumentJSX {
export function JSXFactory(tag: NodeTag, properties: unknown, ...rawChildren: (DocumentNode|LeafNode|string)[]) {
const node = makeDocumentNode(tag);
Expand All @@ -35,7 +37,7 @@ export namespace DeadDocumentJSX {
// Then it's a DocumentNode|LeafNode
} else if (typeof rawChild.leafNode === 'boolean') {
if (rawChild.tag === NodeTag.Fragment) {
(rawChild as DocumentNode).getChildren().forEach(node.addChild, node);
(rawChild as DocumentNode).getChildren().forEach(node.addChild.bind(node));
} else {
node.addChild(rawChild);
}
Expand All @@ -46,6 +48,7 @@ export namespace DeadDocumentJSX {
rawChildren.forEach(ensureChild);
return node;
}
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace JSX {
export interface IntrinsicElements {
a: NodeProperties & { href?: string, name?: string, target?: string },
Expand Down Expand Up @@ -74,7 +77,7 @@ export namespace DeadDocumentJSX {
}
export type Element = DocumentNode
export type ElementChildrenAttribute = {
children?: JSXChild[]|JSXChild|never[]|never
children?: JSXChild[]|JSXChild|never[]
}
}
}
5 changes: 3 additions & 2 deletions src/commands/interface-manager/MatrixHelpRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { LogService } from "matrix-bot-sdk";
import { MatrixSendClient } from "matrix-protection-suite-for-matrix-bot-sdk";
import { ActionError, ActionException, ActionExceptionKind, ActionResult, MatrixRoomReference, Ok, RoomEvent, StringRoomID, Task, isError, isOk } from "matrix-protection-suite";
import { renderDetailsNotice, renderElaborationTrail, renderExceptionTrail } from "../../capabilities/CommonRenderers";
import { printReadably } from "./PrintReadably";

function requiredArgument(argumentName: string): string {
return `<${argumentName}>`;
Expand Down Expand Up @@ -77,7 +78,7 @@ function renderTableHelp(table: CommandTable): DocumentNode {
</root>
}

export async function renderHelp(client: MatrixSendClient, commandRoomID: StringRoomID, event: any, result: ActionResult<CommandTable>): Promise<void> {
export async function renderHelp(client: MatrixSendClient, commandRoomID: StringRoomID, event: RoomEvent, result: ActionResult<CommandTable>): Promise<void> {
if (isError(result)) {
throw new TypeError("This command isn't supposed to fail");
}
Expand Down Expand Up @@ -176,7 +177,7 @@ function formattedArgumentHint(command: InterfaceCommand, error: ArgumentParseEr
for (const argument of argumentsUpToError) {
commandContext += ` ${JSON.stringify(argument)}`;
}
const badArgument = ` ${error.stream.peekItem()}\n${Array(commandContext.length + 1).join(' ')} ^ expected ${error.parameter.acceptor.name} here`;
const badArgument = ` ${printReadably(error.stream.peekItem())}\n${Array(commandContext.length + 1).join(' ')} ^ expected ${error.parameter.acceptor.name} here`;
return commandContext + badArgument;
}

Expand Down
12 changes: 6 additions & 6 deletions src/commands/interface-manager/MatrixInterfaceAdaptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import { InterfaceAcceptor, PromptOptions, PromptableArgumentStream } from "./Pr
import { ParameterDescription } from "./ParameterParsing";
import { promptDefault, promptSuggestions } from "./MatrixPromptForAccept";
import { MatrixSendClient } from "matrix-protection-suite-for-matrix-bot-sdk";
import { ActionError, ActionResult, ClientPlatform, ResultError, RoomEvent, StringRoomID, isError } from "matrix-protection-suite";
import { ActionError, ActionResult, ClientPlatform, ResultError, RoomEvent, StringRoomID, Task, isError } from "matrix-protection-suite";
import { MatrixReactionHandler } from "./MatrixReactionHandler";
import { PromptRequiredError } from "./PromptRequiredError";

Expand Down Expand Up @@ -100,7 +100,7 @@ export class MatrixInterfaceAdaptor<C extends MatrixContext, ExecutorType extend
}
return;
} else {
this.reportValidationError(matrixContext.client, matrixContext.roomID, matrixContext.event, executorResult.error);
void Task(this.reportValidationError(matrixContext.client, matrixContext.roomID, matrixContext.event, executorResult.error));
return;
}
}
Expand All @@ -117,7 +117,7 @@ export class MatrixInterfaceAdaptor<C extends MatrixContext, ExecutorType extend
private async reportValidationError(client: MatrixSendClient, roomID: StringRoomID, event: RoomEvent, validationError: ActionError): Promise<void> {
LogService.info("MatrixInterfaceCommand", `User input validation error when parsing command ${JSON.stringify(this.interfaceCommand.designator)}: ${validationError.message}`);
if (this.validationErrorHandler) {
await this.validationErrorHandler.apply(this, arguments);
await this.validationErrorHandler(client, roomID, event, validationError);
return;
}
await tickCrossRenderer.call(this, client, roomID, event, ResultError(validationError));
Expand All @@ -128,7 +128,7 @@ const MATRIX_INTERFACE_ADAPTORS = new Map<InterfaceCommand, MatrixInterfaceAdapt

function internMatrixInterfaceAdaptor(interfaceCommand: InterfaceCommand, adapator: MatrixInterfaceAdaptor<MatrixContext>): void {
if (MATRIX_INTERFACE_ADAPTORS.has(interfaceCommand)) {
throw new TypeError(`An adaptor is already defined for the command ${interfaceCommand.designator}`);
throw new TypeError(`An adaptor is already defined for the command ${interfaceCommand.designator.toString()}`);
}
MATRIX_INTERFACE_ADAPTORS.set(interfaceCommand, adapator);
}
Expand All @@ -138,7 +138,7 @@ export function findMatrixInterfaceAdaptor(interfaceCommand: InterfaceCommand):
if (entry) {
return entry
}
throw new TypeError(`Couldn't find an adaptor for the command ${interfaceCommand.designator}`);
throw new TypeError(`Couldn't find an adaptor for the command ${interfaceCommand.designator.toString()}`);
}

/**
Expand All @@ -148,7 +148,7 @@ export function findMatrixInterfaceAdaptor(interfaceCommand: InterfaceCommand):
* @param applicationCommmand The ApplicationCommand this is an interface wrapper for.
* @param renderer Render the result of the application command back to a room.
*/
export function defineMatrixInterfaceAdaptor<ExecutorType extends (...args: any) => Promise<any>>(details: {
export function defineMatrixInterfaceAdaptor<ExecutorType extends BaseFunction>(details: {
interfaceCommand: InterfaceCommand<ExecutorType>,
renderer: RendererSignature<MatrixContext, ExecutorType>
}) {
Expand Down
2 changes: 1 addition & 1 deletion src/commands/interface-manager/MatrixPromptForAccept.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ function continueCommandAcceptingPrompt<CommandContext extends MatrixContext = M
event: annotatedEvent,
...additionalCommandContext,
};
Task((async () => { await adaptor.invoke(commandContext, commandContext, ...itemStream.rest()); })());
void Task((async () => { await adaptor.invoke(commandContext, commandContext, ...itemStream.rest()); })());
}

export const DEFAUILT_ARGUMENT_PROMPT_LISTENER = 'ge.applied-langua.ge.draupnir.default_argument_prompt';
Expand Down
Loading

0 comments on commit 3c6cae0

Please sign in to comment.