Skip to content

Commit

Permalink
Updating code to adhere to new linting rules
Browse files Browse the repository at this point in the history
  • Loading branch information
ForestOfLight committed Jan 27, 2025
1 parent e8f4297 commit 664988c
Show file tree
Hide file tree
Showing 92 changed files with 936 additions and 816 deletions.
52 changes: 24 additions & 28 deletions Canopy [BP]/scripts/include/utils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable max-lines */
import { world, ItemStack, DimensionTypes } from '@minecraft/server';

class Utils {
Expand All @@ -18,21 +19,19 @@ class Utils {
}

static parseLookingAtBlock(lookingAtBlock) {
let block;
let blockName = '';
let raycastHitFace;

block = lookingAtBlock?.block ?? undefined;
const block = lookingAtBlock?.block ?? undefined;
if (block) {
raycastHitFace = lookingAtBlock.face;
try {
blockName = `§a${Utils.parseName(block)}`;
} catch (error) {
if (error.message.includes('loaded')) {
if (error.message.includes('loaded'))
blockName = `§c${Utils.stringifyLocation(block.location, 0)} Unloaded`;
} else if (error.message.includes('undefined')) {
else if (error.message.includes('undefined'))
blockName = '§7Undefined';
}

}
}

Expand All @@ -47,15 +46,15 @@ class Utils {
try {
entityName = `§a${Utils.parseName(entity)}`;

if (entity.typeId === 'minecraft:player') {
if (entity.typeId === 'minecraft:player')
entityName = `§a§o${entity.name}§r`;
}

} catch (error) {
if (error.message.includes('loaded')) {
if (error.message.includes('loaded'))
entityName = `§c${Utils.stringifyLocation(entity.location, 0)} Unloaded`;
} else if (error.message.includes('undefined')) {
else if (error.message.includes('undefined'))
entityName = '§7Undefined';
}

}
}

Expand All @@ -80,7 +79,9 @@ class Utils {
}

static parseName(target, includePrefix = true) {
return target.typeId.replace('minecraft:', '') === 'player' ? `§o${target.name}§r` : (includePrefix ? target.typeId : target.typeId.replace('minecraft:', ''));
if (target.typeId.replace('minecraft:', '') === 'player')
return `§o${target.name}§r`;
return includePrefix ? target.typeId : target.typeId.replace('minecraft:', '');
}

static stringifyLocation(location, precision = 0) {
Expand All @@ -90,14 +91,14 @@ class Utils {
}

static populateItems(inventory) {
let items = {};
const items = {};

inventory = inventory.container;
for (let i=0; i<inventory.size; i++) {
try {
const item = inventory.getSlot(i);

let data = item.typeId.replace('minecraft:','');
const data = item.typeId.replace('minecraft:','');
if (items[data]) items[data] += item.amount;
else items[data] = item.amount;
} catch {
Expand Down Expand Up @@ -131,11 +132,11 @@ class Utils {
}

static wait(ms) {
let startTime = Date.now();
const startTime = Date.now();
let endTime = Date.now();
while (endTime - startTime < ms) {
while (endTime - startTime < ms)
endTime = Date.now();
}

return { startTime, endTime };
}

Expand Down Expand Up @@ -220,8 +221,7 @@ class Utils {
case 'Entity':
if (event.sourceEntity.typeId === 'minecraft:player')
return event.sourceEntity.name;
else
return event.sourceEntity.typeId;
return event.sourceEntity.typeId;
case 'Server':
return 'Server';
default:
Expand Down Expand Up @@ -256,16 +256,16 @@ class Utils {
let currentIndex = 0;

for (let i = 0; i < splitText.length; i++) {
let splice = splitText[i];
let originalSplice = text.slice(currentIndex, currentIndex + splice.length);
const splice = splitText[i];
const originalSplice = text.slice(currentIndex, currentIndex + splice.length);
currentIndex += splice.length;

if (i === splitText.length - 1) {
newText += originalSplice;
continue;
}

let colorCodeIndex = originalSplice.lastIndexOf('§');
const colorCodeIndex = originalSplice.lastIndexOf('§');
if (colorCodeIndex === -1) {
newText += originalSplice + colorCode + text.slice(currentIndex, currentIndex + term.length) + lastColorCode;
} else {
Expand All @@ -290,12 +290,8 @@ class Utils {
}

static getRaycastResults(player, distance) {
let blockRayResult;
let entityRayResult;

blockRayResult = player.getBlockFromViewDirection({ includeLiquidBlocks: false, includePassableBlocks: true, maxDistance: distance });
entityRayResult = player.getEntitiesFromViewDirection({ ignoreBlockCollision: false, includeLiquidBlocks: false, includePassableBlocks: false, maxDistance: distance });

const blockRayResult = player.getBlockFromViewDirection({ includeLiquidBlocks: false, includePassableBlocks: true, maxDistance: distance });
const entityRayResult = player.getEntitiesFromViewDirection({ ignoreBlockCollision: false, includeLiquidBlocks: false, includePassableBlocks: false, maxDistance: distance });
return { blockRayResult, entityRayResult };
}

Expand Down
43 changes: 23 additions & 20 deletions Canopy [BP]/scripts/lib/canopy/ArgumentParser.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,45 @@
class ArgumentParser {
static regex = /(@[aepsr]\[|@"[^"]*"|"[^"]*"|\[[^\]]*\]|\S+)/g;
static booleans = ['true', 'false'];
static stringRE = /^"|"$/g;
static arrayRE = /^\[|\]$/g;
static entityRE = /@[aepsr]\[/g;
static stringRegEx = /^"|"$/g;
static arrayRegEx = /^\[|\]$/g;
static entityRegEx = /@[aepsr]\[/g;

static parseArgs(text) {
let args = [];
let raw = text.match(this.regex);
const args = [];
const raw = text.match(this.regex);

if (!raw) return [];
raw.forEach((arg, index) => {
let argData = this.#argParser(arg, index, raw);
const argData = this.#argParser(arg, index, raw);
args[index] = argData;
});

return args.filter(_ => _ != '$nll_');
return args.filter(_ => _ !== '$nll_');
}

static #argParser(char, idx, raw) {
let data;

const isBoolean = this.booleans.includes(char);
const isNumber = !isNaN(Number(char));
const isString = this.stringRE.test(char);
const isArray = idx < raw.length - 1 && this.arrayRE.test(raw[idx + 1]);
const isEntity = this.entityRE.test(char);

if (isBoolean) data = char == 'true';
else if (isNumber) data = Number(char);
else if (isString) data = char.replace(this.stringRE, '');
else if (isEntity && isArray) {
const isString = this.stringRegEx.test(char);
const isArray = idx < raw.length - 1 && this.arrayRegEx.test(raw[idx + 1]);
const isEntity = this.entityRegEx.test(char);

let data;
if (isBoolean) {
data = char === 'true';
} else if (isNumber) {
data = Number(char);
} else if (isString) {
data = char.replace(this.stringRegEx, '');
} else if (isEntity && isArray) {
data = raw[idx] += raw[idx + 1];
raw[idx + 1] = '$nll_';
} else if (char.match(this.arrayRegEx)) {
data = JSON.parse(char);
} else {
data = char.trim();
}
else if (char.match(this.arrayRE)) data = JSON.parse(char);
else data = char.trim();

return data;
}
}
Expand Down
4 changes: 1 addition & 3 deletions Canopy [BP]/scripts/lib/canopy/Command.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ class Command {
this.#extensionName = extensionName;

this.checkMembers();
if (Commands.exists(this.#name))
throw new Error(`[Command] Command '${this.#name}' already exists.`);
Commands.add(this);
Commands.register(this);
}

checkMembers() {
Expand Down
49 changes: 28 additions & 21 deletions Canopy [BP]/scripts/lib/canopy/Commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ export class Commands {
static #commands = {};
static #prefix = COMMAND_PREFIX;

static add(command) {
static register(command) {
if (this.exists(command.getName()))
throw new Error(`[Canopy] Command with name '${command.getName()}' already exists.`);
this.#commands[command.getName()] = command;
}

Expand Down Expand Up @@ -39,42 +41,47 @@ export class Commands {
}

static getNativeCommands() {
let result = Object.values(this.#commands).filter(cmd => !cmd.getExtensionName());
const result = Object.values(this.#commands).filter(cmd => !cmd.getExtensionName());
result.sort((a, b) => a.getName().localeCompare(b.getName()));
return result;
}

static checkArg(value, type) {
let data;
if (type == 'array' && Array.isArray(value)) data = value;
else if (type == 'identifier' && /@[aepsr]\[/g.test(value)) data = value;
else if (type == 'identifier' && /@[aepsr]/g.test(value) && value.length == 2) data = value;
else if (type == 'player' && value.startsWith('@"') && value.endsWith('"')) data = value;
else if (type == 'player' && value.startsWith('@') && !value.includes(' ')) data = value;
else if (type.includes('|')) {
let ts = type.split('|');
let tv = typeof value;
if (type === 'array' && Array.isArray(value)) {
data = value;
} else if (type === 'identifier' && /@[aepsr]\[/g.test(value)) {
data = value;
} else if (type === 'identifier' && /@[aepsr]/g.test(value) && value.length === 2) {
data = value;
} else if (type === 'player' && value.startsWith('@"') && value.endsWith('"')) {
data = value;
} else if (type === 'player' && value.startsWith('@') && !value.includes(' ')) {
data = value;
} else if (type.includes('|')) {
const ts = type.split('|');
const tv = typeof value;

if (ts.includes(tv)) data = value;
else data = null;
} else if (typeof value == type) {
data = value;
} else {
data = null;
}
else if (typeof value == type) data = value;
else data = null;

return data;
}

static handleGetPrefixRequest() {
IPC.on('canopy:getCommandPrefix', () => {
return this.#prefix;
});
IPC.on('canopy:getCommandPrefix', () => this.#prefix);
}

static handleChatCommands() {
world.beforeEvents.chatSend.subscribe((event) => {
const { sender, message } = event;

let [name, ...args] = ArgumentParser.parseArgs(message);
const [...args] = ArgumentParser.parseArgs(message);
let name = args.shift();
if (!String(name).startsWith(this.getPrefix()))
return;
name = name.replace(this.getPrefix(), '');
Expand All @@ -86,14 +93,14 @@ export class Commands {
return sender.sendMessage({ translate: 'commands.generic.nopermission' });

system.run(async () => {
for (let ruleID of command.getContingentRules()) {
for (const ruleID of command.getContingentRules()) {
const ruleValue = await Rules.getValue(ruleID);
if (!ruleValue) {
if (!ruleValue)
return sender.sendMessage({ translate: 'rules.generic.blocked', with: [ruleID] });
}

}

let parsedArgs = {};
const parsedArgs = {};
command.getArgs().forEach((argData, index) => {
parsedArgs[argData.name] = this.checkArg(args[index], argData.type);
});
Expand Down
14 changes: 8 additions & 6 deletions Canopy [BP]/scripts/lib/canopy/Rule.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { world } from '@minecraft/server';
import IPC from "../ipc/ipc";
import Rules from "./Rules";

export class Rule {
#category;
Expand All @@ -18,6 +19,7 @@ export class Rule {
this.#contingentRules = contingentRules;
this.#independentRules = independentRules;
this.#extensionName = extensionName;
Rules.register(this);
}

getCategory() {
Expand Down Expand Up @@ -47,10 +49,10 @@ export class Rule {
async getValue() {
if (this.#extensionName) {
// console.warn(`[Canopy] [Rule] Attempting to get value for ${this.#identifier} from extension ${this.#extensionName}.`);
return await IPC.invoke(`canopyExtension:${this.#extensionName}:ruleValueRequest`, { ruleID: this.#identifier }).then(result => {
return await IPC.invoke(`canopyExtension:${this.#extensionName}:ruleValueRequest`, { ruleID: this.#identifier }).then(result =>
// console.warn(`[Canopy] [Rule] Received value for ${this.#identifier} from extension ${this.#extensionName}: ${result}`);
return result;
});
result
);
}
return this.parseValue(world.getDynamicProperty(this.#identifier));
}
Expand All @@ -73,11 +75,11 @@ export class Rule {
}

setValue(value) {
if (this.#extensionName) {
if (this.#extensionName)
IPC.send(`canopyExtension:${this.#extensionName}:ruleValueSet`, { extensionName: this.#extensionName, ruleID: this.#identifier, value: value });
} else {
else
world.setDynamicProperty(this.#identifier, value);
}

}
}

Expand Down
7 changes: 3 additions & 4 deletions Canopy [BP]/scripts/lib/canopy/Rules.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
export class Rules {
static rules = {};

static add(rule) {
if (this.exists(rule.getID())) {
static register(rule) {
if (this.exists(rule.getID()))
throw new Error(`[Canopy] Rule with identifier '${rule.getID()}' already exists.`);
}
this.rules[rule.getID()] = rule;
}

Expand Down Expand Up @@ -57,7 +56,7 @@ export class Rules {
const rule = this.get(identifier);
if (!rule)
throw new Error(`[Canopy] Rule with identifier '${identifier}' does not exist.`);
return Rules.getAll().filter(rule => rule.getContigentRuleIDs().includes(identifier)).map(rule => rule.getID());
return Rules.getAll().filter(r => r.getContigentRuleIDs().includes(identifier)).map(r => r.getID());
}
}

Expand Down
19 changes: 19 additions & 0 deletions Canopy [BP]/scripts/lib/canopy/help/CommandHelpEntry.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import HelpEntry from './HelpEntry';
import Commands from '../Commands';

class CommandHelpEntry extends HelpEntry {
constructor(command) {
super(command.getName(), command.getDescription());
this.command = command;
}

toRawMessage() {
const message = { rawtext: [{ text: `§2${this.command.getUsage()}§8 - ` }, this.description] };
for (const helpEntry of this.command.getHelpEntries())
message.rawtext.push({ rawtext: [{ text: `\n §7> §2${Commands.getPrefix()}${helpEntry.usage}§8 - ` }, helpEntry.description] });

return message;
}
}

export default CommandHelpEntry;
Loading

0 comments on commit 664988c

Please sign in to comment.