mirror of
https://github.com/pagefaultgames/pokerogue.git
synced 2025-09-23 15:03:24 +02:00
Merge branch 'beta' into reorganize-ui-files
This commit is contained in:
commit
962924220b
81
.github/workflows/linting.yml
vendored
81
.github/workflows/linting.yml
vendored
@ -18,7 +18,7 @@ on:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
run-linters:
|
run-linters:
|
||||||
name: Run linters
|
name: Run all linters
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
@ -26,27 +26,86 @@ jobs:
|
|||||||
- name: Check out Git repository
|
- name: Check out Git repository
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
submodules: 'recursive'
|
submodules: "recursive"
|
||||||
|
|
||||||
- name: Install pnpm
|
- name: Install pnpm
|
||||||
uses: pnpm/action-setup@v4
|
uses: pnpm/action-setup@v4
|
||||||
with:
|
with:
|
||||||
version: 10
|
version: 10
|
||||||
|
|
||||||
- name: Set up Node.js
|
- name: Set up Node
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version-file: '.nvmrc'
|
node-version-file: ".nvmrc"
|
||||||
cache: 'pnpm'
|
cache: "pnpm"
|
||||||
|
|
||||||
- name: Install Node.js dependencies
|
- name: Install Node modules
|
||||||
run: pnpm i
|
run: pnpm i
|
||||||
|
|
||||||
- name: Lint with Biome
|
# Lint files with Biome-Lint - https://biomejs.dev/linter/
|
||||||
|
- name: Run Biome-Lint
|
||||||
run: pnpm biome-ci
|
run: pnpm biome-ci
|
||||||
|
id: biome_lint
|
||||||
|
continue-on-error: true
|
||||||
|
|
||||||
- name: Check dependencies with depcruise
|
# Validate dependencies with dependency-cruiser - https://github.com/sverweij/dependency-cruiser
|
||||||
|
- name: Run Dependency-Cruise
|
||||||
run: pnpm depcruise
|
run: pnpm depcruise
|
||||||
|
id: depcruise
|
||||||
- name: Lint with ls-lint
|
continue-on-error: true
|
||||||
run: pnpm ls-lint
|
|
||||||
|
# Validate types with tsc - https://www.typescriptlang.org/docs/handbook/compiler-options.html#using-the-cli
|
||||||
|
- name: Run Typecheck
|
||||||
|
run: pnpm typecheck
|
||||||
|
id: typecheck
|
||||||
|
continue-on-error: true
|
||||||
|
|
||||||
|
# The exact same thing
|
||||||
|
- name: Run Typecheck (scripts)
|
||||||
|
run: pnpm typecheck:scripts
|
||||||
|
id: typecheck-scripts
|
||||||
|
continue-on-error: true
|
||||||
|
|
||||||
|
- name: Evaluate for Errors
|
||||||
|
env:
|
||||||
|
BIOME_LINT_OUTCOME: ${{ steps.biome_lint.outcome }}
|
||||||
|
DEPCRUISE_OUTCOME: ${{ steps.depcruise.outcome }}
|
||||||
|
TYPECHECK_OUTCOME: ${{ steps.typecheck.outcome }}
|
||||||
|
TYPECHECK_SCRIPTS_OUTCOME: ${{ steps.typecheck-scripts.outcome }}
|
||||||
|
run: |
|
||||||
|
# Check for Errors
|
||||||
|
|
||||||
|
# Make text red.
|
||||||
|
red () {
|
||||||
|
printf "\e[31m%s\e[0m" "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Make text green.
|
||||||
|
green () {
|
||||||
|
printf "\e[32m%s\e[0m" "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
print_result() {
|
||||||
|
local name=$1
|
||||||
|
local outcome=$2
|
||||||
|
if [ "$outcome" == "success" ]; then
|
||||||
|
printf "$(green "✅ $name: $outcome")\n"
|
||||||
|
else
|
||||||
|
printf "$(red "❌ $name: $outcome")\n"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
print_result "Biome" "$BIOME_LINT_OUTCOME"
|
||||||
|
print_result "Depcruise" "$DEPCRUISE_OUTCOME"
|
||||||
|
print_result "Typecheck" "$TYPECHECK_OUTCOME"
|
||||||
|
print_result "Typecheck scripts" "$TYPECHECK_SCRIPTS_OUTCOME"
|
||||||
|
|
||||||
|
if [[ "$BIOME_LINT_OUTCOME" != "success" || \
|
||||||
|
"$DEPCRUISE_OUTCOME" != "success" || \
|
||||||
|
"$TYPECHECK_OUTCOME" != "success" || \
|
||||||
|
"$TYPECHECK_SCRIPTS_OUTCOME" != "success" ]]; then
|
||||||
|
printf "$(red "❌ One or more checks failed!")\n" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf "$(green "✅ All checks passed!")\n"
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
<picture><img src="./public/images/logo.png" width="300" alt="PokéRogue"></picture>
|
<div align="center"><picture><img src="./public/images/logo.png" width="300" alt="PokéRogue"></picture>
|
||||||
|
|
||||||
[](https://discord.gg/pokerogue)
|
[](https://discord.gg/pokerogue)
|
||||||
[](https://pagefaultgames.github.io/pokerogue/beta)
|
[](https://pagefaultgames.github.io/pokerogue/beta)
|
||||||
[](https://github.com/pagefaultgames/pokerogue/actions/workflows/tests.yml)
|
[](https://github.com/pagefaultgames/pokerogue/actions/workflows/tests.yml)
|
||||||
[](https://www.gnu.org/licenses/agpl-3.0)
|
[](https://www.gnu.org/licenses/agpl-3.0)</div>
|
||||||
|
|
||||||
PokéRogue is a browser based Pokémon fangame heavily inspired by the roguelite genre. Battle endlessly while gathering stacking items, exploring many different biomes, fighting trainers, bosses, and more!
|
PokéRogue is a browser based Pokémon fangame heavily inspired by the roguelite genre. Battle endlessly while gathering stacking items, exploring many different biomes, fighting trainers, bosses, and more!
|
||||||
|
|
||||||
|
15
biome.jsonc
15
biome.jsonc
@ -175,10 +175,17 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// Overrides to prevent unused import removal inside `overrides.ts` and enums files (for TSDoc linkcodes),
|
// Overrides to prevent unused import removal inside `overrides.ts`, enums & `.d.ts` files (for TSDoc linkcodes),
|
||||||
// as well as in all TS files in `scripts/` (which are assumed to be boilerplate templates).
|
// as well as inside script boilerplate files.
|
||||||
{
|
{
|
||||||
"includes": ["**/src/overrides.ts", "**/src/enums/**/*", "**/scripts/**/*.ts", "**/*.d.ts"],
|
// TODO: Rename existing boilerplates in the folder and remove this last alias
|
||||||
|
"includes": [
|
||||||
|
"**/src/overrides.ts",
|
||||||
|
"**/src/enums/**/*",
|
||||||
|
"**/*.d.ts",
|
||||||
|
"scripts/**/*.boilerplate.ts",
|
||||||
|
"**/boilerplates/*.ts"
|
||||||
|
],
|
||||||
"linter": {
|
"linter": {
|
||||||
"rules": {
|
"rules": {
|
||||||
"correctness": {
|
"correctness": {
|
||||||
@ -188,7 +195,7 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"includes": ["**/src/overrides.ts", "**/scripts/**/*.ts"],
|
"includes": ["**/src/overrides.ts"],
|
||||||
"linter": {
|
"linter": {
|
||||||
"rules": {
|
"rules": {
|
||||||
"style": {
|
"style": {
|
||||||
|
@ -15,8 +15,10 @@
|
|||||||
"test:watch": "vitest watch --coverage --no-isolate",
|
"test:watch": "vitest watch --coverage --no-isolate",
|
||||||
"test:silent": "vitest run --silent='passed-only' --no-isolate",
|
"test:silent": "vitest run --silent='passed-only' --no-isolate",
|
||||||
"test:create": "node scripts/create-test/create-test.js",
|
"test:create": "node scripts/create-test/create-test.js",
|
||||||
|
"eggMoves:parse": "node scripts/parse-egg-moves/main.js",
|
||||||
"scrape-trainers": "node scripts/scrape-trainer-names/main.js",
|
"scrape-trainers": "node scripts/scrape-trainer-names/main.js",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
|
"typecheck:scripts": "tsc -p scripts/jsconfig.json",
|
||||||
"biome": "biome check --write --changed --no-errors-on-unmatched --diagnostic-level=error",
|
"biome": "biome check --write --changed --no-errors-on-unmatched --diagnostic-level=error",
|
||||||
"biome-ci": "biome ci --diagnostic-level=error --reporter=github --no-errors-on-unmatched",
|
"biome-ci": "biome ci --diagnostic-level=error --reporter=github --no-errors-on-unmatched",
|
||||||
"typedoc": "typedoc",
|
"typedoc": "typedoc",
|
||||||
@ -34,6 +36,7 @@
|
|||||||
"@types/node": "^22.16.5",
|
"@types/node": "^22.16.5",
|
||||||
"@vitest/coverage-istanbul": "^3.2.4",
|
"@vitest/coverage-istanbul": "^3.2.4",
|
||||||
"@vitest/expect": "^3.2.4",
|
"@vitest/expect": "^3.2.4",
|
||||||
|
"@vitest/utils": "^3.2.4",
|
||||||
"chalk": "^5.4.1",
|
"chalk": "^5.4.1",
|
||||||
"dependency-cruiser": "^16.10.4",
|
"dependency-cruiser": "^16.10.4",
|
||||||
"inquirer": "^12.8.2",
|
"inquirer": "^12.8.2",
|
||||||
|
@ -63,6 +63,9 @@ importers:
|
|||||||
'@vitest/expect':
|
'@vitest/expect':
|
||||||
specifier: ^3.2.4
|
specifier: ^3.2.4
|
||||||
version: 3.2.4
|
version: 3.2.4
|
||||||
|
'@vitest/utils':
|
||||||
|
specifier: ^3.2.4
|
||||||
|
version: 3.2.4
|
||||||
chalk:
|
chalk:
|
||||||
specifier: ^5.4.1
|
specifier: ^5.4.1
|
||||||
version: 5.4.1
|
version: 5.4.1
|
||||||
|
@ -1 +1 @@
|
|||||||
Subproject commit 2686cd3edc0bd2c7a7f12cc54c00c109e51a48d7
|
Subproject commit 102cbdcd924e2a7cdc7eab64d1ce79f6ec7604ff
|
@ -156,7 +156,7 @@ async function runInteractive() {
|
|||||||
console.log(chalk.green.bold(`✔ File created at: test/${localDir}/${fileName}.test.ts\n`));
|
console.log(chalk.green.bold(`✔ File created at: test/${localDir}/${fileName}.test.ts\n`));
|
||||||
console.groupEnd();
|
console.groupEnd();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(chalk.red("✗ Error: ", err.message));
|
console.error(chalk.red("✗ Error: ", err));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
// Usage: node decrypt-save.js <encrypted-file> [save-file]
|
// Usage: node decrypt-save.js <encrypted-file> [save-file]
|
||||||
|
|
||||||
// biome-ignore lint/performance/noNamespaceImport: This is how you import fs from node
|
import fs from "node:fs";
|
||||||
import * as fs from "node:fs";
|
|
||||||
import crypto_js from "crypto-js";
|
import crypto_js from "crypto-js";
|
||||||
|
|
||||||
const { AES, enc } = crypto_js;
|
const { AES, enc } = crypto_js;
|
||||||
@ -60,6 +59,11 @@ function decryptSave(path) {
|
|||||||
try {
|
try {
|
||||||
fileData = fs.readFileSync(path, "utf8");
|
fileData = fs.readFileSync(path, "utf8");
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
if (!(e instanceof Error)) {
|
||||||
|
console.error(`Unrecognized error: ${e}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
// @ts-expect-error - e is usually a SystemError (all of which have codes)
|
||||||
switch (e.code) {
|
switch (e.code) {
|
||||||
case "ENOENT":
|
case "ENOENT":
|
||||||
console.error(`File not found: ${path}`);
|
console.error(`File not found: ${path}`);
|
||||||
@ -104,6 +108,13 @@ function writeToFile(filePath, data) {
|
|||||||
try {
|
try {
|
||||||
fs.writeFileSync(filePath, data);
|
fs.writeFileSync(filePath, data);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
if (!(e instanceof Error)) {
|
||||||
|
console.error("Unknown error detected: ", e);
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// @ts-expect-error - e is usually a SystemError (all of which have codes)
|
||||||
switch (e.code) {
|
switch (e.code) {
|
||||||
case "EACCES":
|
case "EACCES":
|
||||||
console.error(`Could not open ${filePath}: Permission denied`);
|
console.error(`Could not open ${filePath}: Permission denied`);
|
||||||
@ -114,7 +125,8 @@ function writeToFile(filePath, data) {
|
|||||||
default:
|
default:
|
||||||
console.error(`Error writing file: ${e.message}`);
|
console.error(`Error writing file: ${e.message}`);
|
||||||
}
|
}
|
||||||
process.exit(1);
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
17
scripts/jsconfig.json
Normal file
17
scripts/jsconfig.json
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"include": ["**/*.js"],
|
||||||
|
"compilerOptions": {
|
||||||
|
"allowJs": true,
|
||||||
|
"checkJs": true,
|
||||||
|
"rootDir": ".",
|
||||||
|
"target": "esnext",
|
||||||
|
"module": "nodenext",
|
||||||
|
"moduleResolution": "nodenext",
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"strict": true,
|
||||||
|
"noEmit": true,
|
||||||
|
// Forcibly disable `node_modules` recursion to prevent TSC from typechecking random JS files.
|
||||||
|
// This is disabled by default in `tsconfig.json`, but needs to be explicitly disabled from the default of `2`
|
||||||
|
"maxNodeModuleJsDepth": 0
|
||||||
|
}
|
||||||
|
}
|
10
scripts/parse-egg-moves/egg-move-template.boilerplate.ts
Normal file
10
scripts/parse-egg-moves/egg-move-template.boilerplate.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
//! DO NOT EDIT THIS FILE - CREATED BY THE `eggMoves:parse` script automatically
|
||||||
|
import { MoveId } from "#enums/move-id";
|
||||||
|
import { SpeciesId } from "#enums/species-id";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An object mapping all base form {@linkcode SpeciesId}s to an array of {@linkcode MoveId}s corresponding
|
||||||
|
* to their current egg moves.
|
||||||
|
* Generated by the `eggMoves:parse` script using a CSV sourced from the current Balance Team spreadsheet.
|
||||||
|
*/
|
||||||
|
export const speciesEggMoves = "{{table}}";
|
17
scripts/parse-egg-moves/help-message.js
Normal file
17
scripts/parse-egg-moves/help-message.js
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
import chalk from "chalk";
|
||||||
|
|
||||||
|
/** Show help/usage text for the `eggMoves:parse` CLI. */
|
||||||
|
export function showHelpText() {
|
||||||
|
console.log(`
|
||||||
|
Usage: ${chalk.cyan("pnpm eggMoves:parse [options]")}
|
||||||
|
If given no options, assumes ${chalk.blue("\`--interactive\`")}.
|
||||||
|
If given only a file path, assumes ${chalk.blue("\`--file\`")}.
|
||||||
|
|
||||||
|
${chalk.hex("#ffa500")("Options:")}
|
||||||
|
${chalk.blue("-h, --help")} Show this help message.
|
||||||
|
${chalk.blue("-f, --file[=PATH]")} Specify a path to a CSV file to read, or provide one from stdin.
|
||||||
|
${chalk.blue("-t, --text[=TEXT]")}
|
||||||
|
${chalk.blue("-c, --console[=TEXT]")} Specify CSV text to read, or provide it from stdin.
|
||||||
|
${chalk.blue("-i, --interactive")} Run in interactive mode (default)
|
||||||
|
`);
|
||||||
|
}
|
108
scripts/parse-egg-moves/interactive.js
Normal file
108
scripts/parse-egg-moves/interactive.js
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
import fs from "fs";
|
||||||
|
import chalk from "chalk";
|
||||||
|
import inquirer from "inquirer";
|
||||||
|
import { showHelpText } from "./help-message.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @import { Option } from "./main.js"
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prompt the user to interactively select an option (console/file) to retrieve the egg move CSV.
|
||||||
|
* @returns {Promise<Option>} The selected option with value
|
||||||
|
*/
|
||||||
|
export async function runInteractive() {
|
||||||
|
/** @type {"Console" | "File" | "Help" | "Exit"} */
|
||||||
|
const answer = await inquirer
|
||||||
|
.prompt([
|
||||||
|
{
|
||||||
|
type: "list",
|
||||||
|
name: "type",
|
||||||
|
message: "Select the method to obtain egg moves.",
|
||||||
|
choices: ["Console", "File", "Help", "Exit"],
|
||||||
|
},
|
||||||
|
])
|
||||||
|
.then(a => a.type);
|
||||||
|
|
||||||
|
if (answer === "Exit") {
|
||||||
|
console.log("Exiting...");
|
||||||
|
process.exitCode = 1;
|
||||||
|
return { type: "Exit" };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (answer === "Help") {
|
||||||
|
showHelpText();
|
||||||
|
return { type: "Exit" };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!["Console", "File"].includes(answer)) {
|
||||||
|
console.error(chalk.red("Please provide a valid type!"));
|
||||||
|
return await runInteractive();
|
||||||
|
}
|
||||||
|
|
||||||
|
return { type: answer, value: await promptForValue(answer) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prompt the user to give a value (either the direct CSV or the file path).
|
||||||
|
* @param {"Console" | "File"} type - The input method
|
||||||
|
* @returns {Promise<string>} A Promise resolving with the CSV/file path.
|
||||||
|
*/
|
||||||
|
function promptForValue(type) {
|
||||||
|
switch (type) {
|
||||||
|
case "Console":
|
||||||
|
return doPromptConsole();
|
||||||
|
case "File":
|
||||||
|
return getFilePath();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prompt the user to enter a file path from the console.
|
||||||
|
* @returns {Promise<string>} The file path inputted by the user.
|
||||||
|
*/
|
||||||
|
async function getFilePath() {
|
||||||
|
return await inquirer
|
||||||
|
.prompt([
|
||||||
|
{
|
||||||
|
type: "input",
|
||||||
|
name: "path",
|
||||||
|
message: "Please enter the path to the egg move CSV file.",
|
||||||
|
validate: input => {
|
||||||
|
if (input.trim() === "") {
|
||||||
|
return "File path cannot be empty!";
|
||||||
|
}
|
||||||
|
if (!fs.existsSync(input)) {
|
||||||
|
return "File does not exist!";
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
.then(answer => answer.path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prompt the user for CSV input from the console.
|
||||||
|
* @returns {Promise<string>} The CSV input from the user.
|
||||||
|
*/
|
||||||
|
async function doPromptConsole() {
|
||||||
|
return await inquirer
|
||||||
|
.prompt([
|
||||||
|
{
|
||||||
|
type: "input",
|
||||||
|
name: "csv",
|
||||||
|
message: "Please enter the egg move CSV text.",
|
||||||
|
validate: input => {
|
||||||
|
if (input.trim() === "") {
|
||||||
|
return "CSV text cannot be empty!";
|
||||||
|
}
|
||||||
|
if (!input.match(/^[^,]+(,[^,]+){4}$/gm)) {
|
||||||
|
return "CSV text malformed - should contain 5 consecutive comma-separated values per line!";
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
.then(answer => answer.csv);
|
||||||
|
}
|
168
scripts/parse-egg-moves/main.js
Normal file
168
scripts/parse-egg-moves/main.js
Normal file
@ -0,0 +1,168 @@
|
|||||||
|
/*
|
||||||
|
* This script accepts a CSV value or file path as input, parses the egg moves,
|
||||||
|
* and writes the output to a TypeScript file.
|
||||||
|
* It can be run interactively or with command line arguments.
|
||||||
|
* Usage: `pnpm eggMoves:parse`
|
||||||
|
*/
|
||||||
|
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import chalk from "chalk";
|
||||||
|
import { showHelpText } from "./help-message.js";
|
||||||
|
import { runInteractive } from "./interactive.js";
|
||||||
|
import { parseEggMoves } from "./parse.js";
|
||||||
|
|
||||||
|
const version = "1.0.0";
|
||||||
|
|
||||||
|
// Get the directory name of the current module file
|
||||||
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
|
const __dirname = path.dirname(__filename);
|
||||||
|
const projectRoot = path.join(__dirname, "..", "..");
|
||||||
|
const templatePath = path.join(__dirname, "egg-move-template.ts");
|
||||||
|
// TODO: Do we want this to be configurable?
|
||||||
|
const eggMoveTargetPath = path.join(projectRoot, "src/data/balance/egg-moves.ts");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @typedef {{type: "Console" | "File", value: string} | {type: "Exit"}}
|
||||||
|
* Option
|
||||||
|
* An option selected by the user.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs the interactive eggMoves:parse CLI.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async function start() {
|
||||||
|
console.log(chalk.yellow(`🥚 Egg Move Parser - v${version}`));
|
||||||
|
|
||||||
|
if (process.argv.length > 4) {
|
||||||
|
console.error(
|
||||||
|
chalk.redBright.bold(
|
||||||
|
`✗ Error: Too many arguments provided!\nArgs: ${chalk.hex("#7310fdff")(process.argv.slice(2).join(" "))}`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
showHelpText();
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let csv = "";
|
||||||
|
const inputType = await parseArguments();
|
||||||
|
if (process.exitCode) {
|
||||||
|
// If exit code is non-zero, return to allow it to propagate up the chain.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
switch (inputType.type) {
|
||||||
|
case "Console":
|
||||||
|
csv = inputType.value;
|
||||||
|
break;
|
||||||
|
case "File":
|
||||||
|
csv = await fs.promises.readFile(inputType.value, "utf-8");
|
||||||
|
break;
|
||||||
|
case "Exit":
|
||||||
|
// Help screen triggered; break out
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await writeToFile(parseEggMoves(csv));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the arguments passed to the script and obtain the CSV input type.
|
||||||
|
* @returns {Promise<{type: "Console" | "File", value: string} | {type: "Exit"}>} The input method selected by the user
|
||||||
|
*/
|
||||||
|
async function parseArguments() {
|
||||||
|
const args = process.argv.slice(2); // first 2 args are node and script name (irrelevant)
|
||||||
|
|
||||||
|
/** @type {string | undefined} */
|
||||||
|
const arg = args[0].split("=")[0]; // Yoink everything up to the first "=" to get the raw command
|
||||||
|
switch (arg) {
|
||||||
|
case "-f":
|
||||||
|
case "--file":
|
||||||
|
return { type: "File", value: getArgValue() };
|
||||||
|
case "-t":
|
||||||
|
case "--text":
|
||||||
|
case "-c":
|
||||||
|
case "--console":
|
||||||
|
return { type: "Console", value: getArgValue() };
|
||||||
|
case "-h":
|
||||||
|
case "--help":
|
||||||
|
showHelpText();
|
||||||
|
process.exitCode = 0;
|
||||||
|
return { type: "Exit" };
|
||||||
|
case "--interactive":
|
||||||
|
case "-i":
|
||||||
|
case undefined:
|
||||||
|
return await runInteractive();
|
||||||
|
default:
|
||||||
|
// If no arguments are found, check if it's a file path
|
||||||
|
if (fs.existsSync(arg)) {
|
||||||
|
console.log(chalk.green(`Using file path from stdin: ${chalk.blue(arg)}`));
|
||||||
|
return { type: "File", value: arg };
|
||||||
|
}
|
||||||
|
badArgs();
|
||||||
|
return { type: "Exit" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the value of the argument provided.
|
||||||
|
* @returns {string} The CSV or file path from the arguments
|
||||||
|
* @throws {Error} If arguments are malformed
|
||||||
|
*/
|
||||||
|
function getArgValue() {
|
||||||
|
// If the user provided a value as argument 2, take that as the argument.
|
||||||
|
// Otherwise, check the 1st argument to see if it contains an `=` and extract everything afterwards.
|
||||||
|
/** @type {string | undefined} */
|
||||||
|
let filePath = process.argv[3];
|
||||||
|
const equalsIndex = process.argv[2].indexOf("=");
|
||||||
|
if (equalsIndex > -1) {
|
||||||
|
// If arg 3 was aleady existing and someone used `=` notation to assign a property, throw an error.
|
||||||
|
filePath = filePath ? undefined : process.argv[2].slice(equalsIndex + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!filePath?.trim()) {
|
||||||
|
badArgs();
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
// NB: It doesn't really matter that this can be `undefined` - we'll always break out by lieu of setting the exit code
|
||||||
|
return filePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write out the parsed CSV to a file.
|
||||||
|
* @param {string} moves - The parsed CSV
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function writeToFile(moves) {
|
||||||
|
try {
|
||||||
|
// Read the template file, replacing the placeholder with the move table.
|
||||||
|
const content = fs.readFileSync(templatePath, "utf8").replace(`"{{table}}"`, moves);
|
||||||
|
|
||||||
|
if (fs.existsSync(eggMoveTargetPath)) {
|
||||||
|
console.warn(chalk.hex("#ffa500")("\nEgg moves file already exists, overwriting...\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write the template content to the file
|
||||||
|
fs.writeFileSync(eggMoveTargetPath, content, "utf8");
|
||||||
|
|
||||||
|
console.log(chalk.green.bold(`\n✔ Egg Moves written to ${eggMoveTargetPath}`));
|
||||||
|
console.groupEnd();
|
||||||
|
} catch (err) {
|
||||||
|
console.error(chalk.red(`✗ Error while writing egg moves: ${err}`));
|
||||||
|
process.exitCode = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Do logging for incorrect or malformed CLI arguments.
|
||||||
|
* @returns {void}
|
||||||
|
*/
|
||||||
|
function badArgs() {
|
||||||
|
chalk.red.bold(`✗ Error: Malformed arguments!\nArgs: ${chalk.hex("#7310fdff")(process.argv.slice(2).join(" "))}`);
|
||||||
|
showHelpText();
|
||||||
|
process.exitCode = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
start();
|
79
scripts/parse-egg-moves/parse.js
Normal file
79
scripts/parse-egg-moves/parse.js
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
import chalk from "chalk";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A single line of the inputted CSV.
|
||||||
|
* @typedef {[speciesName: string, move1: string, move2: string, move3: string, move4: string]}
|
||||||
|
* CSVLine
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regex to determine if a string follows the required CSV format.
|
||||||
|
*/
|
||||||
|
const csvRegex = /^((?:[^,]+?,){4}(?:\w|\s)+?,?\n?)+$/g;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Given a CSV string, parse it and return a structured table ready to be inputted into code.
|
||||||
|
* @param {string} csv - The formatted CSV string.
|
||||||
|
* @returns {string} The fully formatted table.
|
||||||
|
*/
|
||||||
|
export function parseEggMoves(csv) {
|
||||||
|
console.log(chalk.grey("⚙️ Parsing egg moves..."));
|
||||||
|
if (!csvRegex.test(csv)) {
|
||||||
|
console.error(chalk.redBright("! Input was not proper CSV!"));
|
||||||
|
process.exitCode = 1;
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
let output = "{\n";
|
||||||
|
|
||||||
|
const lines = csv.split(/\n/g);
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
/**
|
||||||
|
* The individual CSV column for this species.
|
||||||
|
*/
|
||||||
|
const cols =
|
||||||
|
/** @type {CSVLine} */
|
||||||
|
(line.split(",").slice(0, 5));
|
||||||
|
const speciesName = toUpperSnakeCase(cols[0]);
|
||||||
|
|
||||||
|
const eggMoves =
|
||||||
|
/** @type {string[]} */
|
||||||
|
([]);
|
||||||
|
|
||||||
|
for (let m = 1; m < 5; m++) {
|
||||||
|
const moveName = cols[m].trim();
|
||||||
|
if (!moveName || moveName === "N/A") {
|
||||||
|
console.warn(`Species ${speciesName} missing ${m}th egg move!`);
|
||||||
|
eggMoves.push("MoveId.NONE");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove (N) and (P) from the ends of move names before UPPER_SNAKE_CASE-ing them
|
||||||
|
const moveNameTitle = toUpperSnakeCase(moveName.replace(/ \([A-Z]\)$/, ""));
|
||||||
|
eggMoves.push("MoveId." + moveNameTitle);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (eggMoves.every(move => move === "MoveId.NONE")) {
|
||||||
|
console.warn(`Species ${speciesName} could not be parsed, excluding from output...`);
|
||||||
|
output += ` // [SpeciesId.${speciesName}]: [ MoveId.NONE, MoveId.NONE, MoveId.NONE, MoveId.NONE ],\n`;
|
||||||
|
} else {
|
||||||
|
output += ` [SpeciesId.${speciesName}]: [ ${eggMoves.join(", ")} ],\n`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NB: We omit the semicolon as it is contained in the template string itself
|
||||||
|
return output + "} satisfies Partial<Record<SpeciesId, [MoveId, MoveId, MoveId, MoveId]>>";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to convert a string into `UPPER_SNAKE_CASE`.
|
||||||
|
* @param {string} str - The string being converted
|
||||||
|
* @returns {string} The result of converting `str` into upper snake case.
|
||||||
|
*/
|
||||||
|
function toUpperSnakeCase(str) {
|
||||||
|
return str
|
||||||
|
.split(/[_ -]+/g)
|
||||||
|
.map(word => word.toUpperCase())
|
||||||
|
.join("_");
|
||||||
|
}
|
@ -31,11 +31,11 @@ export function fetchNames(trainerListHeader, knownFemale = false) {
|
|||||||
|
|
||||||
// Grab all the trainer name tables sorted by generation
|
// Grab all the trainer name tables sorted by generation
|
||||||
const tables = elements.slice(startChildIndex, endChildIndex).filter(
|
const tables = elements.slice(startChildIndex, endChildIndex).filter(
|
||||||
/** @type {(t: ChildNode) => t is Element} */
|
/** @type {(t: ChildNode) => t is HTMLTableElement} */
|
||||||
(
|
(
|
||||||
t =>
|
t =>
|
||||||
// Only grab expandable tables within the header block
|
// Only grab expandable tables within the header block
|
||||||
t.nodeName === "TABLE" && t["className"] === "expandable"
|
t.nodeName === "TABLE" && /** @type {HTMLTableElement} */ (t)["className"] === "expandable"
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -48,7 +48,7 @@ export function fetchNames(trainerListHeader, knownFemale = false) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse the table in question.
|
* Parse the table in question.
|
||||||
* @param {Element[]} tables - The array of Elements forming the current table
|
* @param {HTMLTableElement[]} tables - The array of Elements forming the current table
|
||||||
* @param {boolean} isFemale - Whether the trainer is known to be female or not
|
* @param {boolean} isFemale - Whether the trainer is known to be female or not
|
||||||
* @param {Set<string>} trainerNames A Set containing the male trainer names
|
* @param {Set<string>} trainerNames A Set containing the male trainer names
|
||||||
* @param {Set<string>} femaleTrainerNames - A Set containing the female trainer names
|
* @param {Set<string>} femaleTrainerNames - A Set containing the female trainer names
|
||||||
@ -56,7 +56,7 @@ export function fetchNames(trainerListHeader, knownFemale = false) {
|
|||||||
function parseTable(tables, isFemale, trainerNames, femaleTrainerNames) {
|
function parseTable(tables, isFemale, trainerNames, femaleTrainerNames) {
|
||||||
for (const table of tables) {
|
for (const table of tables) {
|
||||||
// Grab all rows past the first header with exactly 9 children in them (Name, Battle, Winnings, 6 party slots)
|
// Grab all rows past the first header with exactly 9 children in them (Name, Battle, Winnings, 6 party slots)
|
||||||
const trainerRows = [...table.querySelectorAll("tr:not(:first-child)")].filter(r => r.children.length === 9);
|
const trainerRows = [...table.rows].slice(1).filter(r => r.children.length === 9);
|
||||||
for (const row of trainerRows) {
|
for (const row of trainerRows) {
|
||||||
const content = row.firstElementChild?.innerHTML;
|
const content = row.firstElementChild?.innerHTML;
|
||||||
// Skip empty elements & ones without anchors
|
// Skip empty elements & ones without anchors
|
||||||
|
25
src/constants/colors.ts
Normal file
25
src/constants/colors.ts
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
/**
|
||||||
|
* @module
|
||||||
|
* A big file storing colors used in logging.
|
||||||
|
* Minified by Terser during production builds, so has no overhead.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Colors used in prod
|
||||||
|
/** Color used for "Start Phase <Phase>" logs */
|
||||||
|
export const PHASE_START_COLOR = "green" as const;
|
||||||
|
/** Color used for logs in `MovePhase` */
|
||||||
|
export const MOVE_COLOR = "orchid" as const;
|
||||||
|
|
||||||
|
// Colors used for testing code
|
||||||
|
export const NEW_TURN_COLOR = "#ffad00ff" as const;
|
||||||
|
export const UI_MSG_COLOR = "#009dffff" as const;
|
||||||
|
export const OVERRIDES_COLOR = "#b0b01eff" as const;
|
||||||
|
export const SETTINGS_COLOR = "#008844ff" as const;
|
||||||
|
|
||||||
|
// Colors used for Vitest-related test utils
|
||||||
|
export const TEST_NAME_COLOR = "#008886ff" as const;
|
||||||
|
export const VITEST_PINK_COLOR = "#c162de" as const;
|
||||||
|
|
||||||
|
// Mock console log stuff
|
||||||
|
export const TRACE_COLOR = "#b700ff" as const;
|
||||||
|
export const DEBUG_COLOR = "#874600ff" as const;
|
@ -1,9 +1,12 @@
|
|||||||
import { allMoves } from "#data/data-lists";
|
//! DO NOT EDIT THIS FILE - CREATED BY THE `eggMoves:parse` script automatically
|
||||||
import { MoveId } from "#enums/move-id";
|
import { MoveId } from "#enums/move-id";
|
||||||
import { SpeciesId } from "#enums/species-id";
|
import { SpeciesId } from "#enums/species-id";
|
||||||
import { getEnumKeys, getEnumValues } from "#utils/enums";
|
|
||||||
import { toTitleCase } from "#utils/strings";
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An object mapping all base form {@linkcode SpeciesId}s to an array of {@linkcode MoveId}s corresponding
|
||||||
|
* to their current egg moves.
|
||||||
|
* Generated by the `eggMoves:parse` script using a CSV sourced from the current Balance Team spreadsheet.
|
||||||
|
*/
|
||||||
export const speciesEggMoves = {
|
export const speciesEggMoves = {
|
||||||
[SpeciesId.BULBASAUR]: [ MoveId.SAPPY_SEED, MoveId.MALIGNANT_CHAIN, MoveId.EARTH_POWER, MoveId.MATCHA_GOTCHA ],
|
[SpeciesId.BULBASAUR]: [ MoveId.SAPPY_SEED, MoveId.MALIGNANT_CHAIN, MoveId.EARTH_POWER, MoveId.MATCHA_GOTCHA ],
|
||||||
[SpeciesId.CHARMANDER]: [ MoveId.DRAGON_DANCE, MoveId.AEROBLAST, MoveId.EARTH_POWER, MoveId.BITTER_BLADE ],
|
[SpeciesId.CHARMANDER]: [ MoveId.DRAGON_DANCE, MoveId.AEROBLAST, MoveId.EARTH_POWER, MoveId.BITTER_BLADE ],
|
||||||
@ -582,55 +585,4 @@ export const speciesEggMoves = {
|
|||||||
[SpeciesId.PALDEA_TAUROS]: [ MoveId.NO_RETREAT, MoveId.BLAZING_TORQUE, MoveId.AQUA_STEP, MoveId.THUNDEROUS_KICK ],
|
[SpeciesId.PALDEA_TAUROS]: [ MoveId.NO_RETREAT, MoveId.BLAZING_TORQUE, MoveId.AQUA_STEP, MoveId.THUNDEROUS_KICK ],
|
||||||
[SpeciesId.PALDEA_WOOPER]: [ MoveId.STONE_AXE, MoveId.RECOVER, MoveId.BANEFUL_BUNKER, MoveId.BARB_BARRAGE ],
|
[SpeciesId.PALDEA_WOOPER]: [ MoveId.STONE_AXE, MoveId.RECOVER, MoveId.BANEFUL_BUNKER, MoveId.BARB_BARRAGE ],
|
||||||
[SpeciesId.BLOODMOON_URSALUNA]: [ MoveId.NASTY_PLOT, MoveId.ROCK_POLISH, MoveId.SANDSEAR_STORM, MoveId.BOOMBURST ]
|
[SpeciesId.BLOODMOON_URSALUNA]: [ MoveId.NASTY_PLOT, MoveId.ROCK_POLISH, MoveId.SANDSEAR_STORM, MoveId.BOOMBURST ]
|
||||||
};
|
} satisfies Partial<Record<SpeciesId, [MoveId, MoveId, MoveId, MoveId]>>;
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse a CSV-separated list of Egg Moves (such as one sourced from a Google Sheets)
|
|
||||||
* into code able to form the `speciesEggMoves` const object as above.
|
|
||||||
* @param content - The CSV-formatted string to convert into code.
|
|
||||||
*/
|
|
||||||
// TODO: Move this into the scripts folder and stop running it on initialization
|
|
||||||
function parseEggMoves(content: string): void {
|
|
||||||
let output = "";
|
|
||||||
|
|
||||||
const speciesNames = getEnumKeys(SpeciesId);
|
|
||||||
const speciesValues = getEnumValues(SpeciesId);
|
|
||||||
const moveNames = allMoves.map(m => m.name.replace(/ \([A-Z]\)$/, "").toLowerCase());
|
|
||||||
const lines = content.split(/\n/g);
|
|
||||||
|
|
||||||
for (const line of lines) {
|
|
||||||
const cols = line.split(",").slice(0, 5);
|
|
||||||
const enumSpeciesName = cols[0].toUpperCase().replace(/[ -]/g, "_") as keyof typeof SpeciesId;
|
|
||||||
// TODO: This should use reverse mapping instead of `indexOf`
|
|
||||||
const species = speciesValues[speciesNames.indexOf(enumSpeciesName)];
|
|
||||||
|
|
||||||
const eggMoves: MoveId[] = [];
|
|
||||||
|
|
||||||
for (let m = 0; m < 4; m++) {
|
|
||||||
const moveName = cols[m + 1].trim();
|
|
||||||
const moveIndex = moveName !== "N/A" ? moveNames.indexOf(moveName.toLowerCase()) : -1;
|
|
||||||
if (moveIndex === -1) {
|
|
||||||
console.warn(moveName, "could not be parsed");
|
|
||||||
}
|
|
||||||
|
|
||||||
eggMoves.push(moveIndex > -1 ? moveIndex as MoveId : MoveId.NONE);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (eggMoves.every(m => m === MoveId.NONE)) {
|
|
||||||
console.warn(`Species ${toTitleCase(SpeciesId[species])} could not be parsed, excluding from output...`)
|
|
||||||
} else {
|
|
||||||
output += `[SpeciesId.${SpeciesId[species]}]: [ ${eggMoves.map(m => `MoveId.${MoveId[m]}`).join(", ")} ],\n`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(output);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function initEggMoves() {
|
|
||||||
const eggMovesStr = "";
|
|
||||||
if (eggMovesStr) {
|
|
||||||
setTimeout(() => {
|
|
||||||
parseEggMoves(eggMovesStr);
|
|
||||||
}, 1000);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
import { initAbilities } from "#abilities/ability";
|
import { initAbilities } from "#abilities/ability";
|
||||||
import { initBiomes } from "#balance/biomes";
|
import { initBiomes } from "#balance/biomes";
|
||||||
import { initEggMoves } from "#balance/egg-moves";
|
|
||||||
import { initPokemonPrevolutions, initPokemonStarters } from "#balance/pokemon-evolutions";
|
import { initPokemonPrevolutions, initPokemonStarters } from "#balance/pokemon-evolutions";
|
||||||
import { initSpecies } from "#balance/pokemon-species";
|
import { initSpecies } from "#balance/pokemon-species";
|
||||||
import { initChallenges } from "#data/challenge";
|
import { initChallenges } from "#data/challenge";
|
||||||
@ -24,7 +23,6 @@ export function initializeGame() {
|
|||||||
initPokemonPrevolutions();
|
initPokemonPrevolutions();
|
||||||
initPokemonStarters();
|
initPokemonStarters();
|
||||||
initBiomes();
|
initBiomes();
|
||||||
initEggMoves();
|
|
||||||
initPokemonForms();
|
initPokemonForms();
|
||||||
initTrainerTypeDialogue();
|
initTrainerTypeDialogue();
|
||||||
initSpecies();
|
initSpecies();
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
import { PHASE_START_COLOR } from "#app/constants/colors";
|
||||||
import { globalScene } from "#app/global-scene";
|
import { globalScene } from "#app/global-scene";
|
||||||
import type { Phase } from "#app/phase";
|
import type { Phase } from "#app/phase";
|
||||||
import { type PhasePriorityQueue, PostSummonPhasePriorityQueue } from "#data/phase-priority-queue";
|
import { type PhasePriorityQueue, PostSummonPhasePriorityQueue } from "#data/phase-priority-queue";
|
||||||
@ -392,7 +393,7 @@ export class PhaseManager {
|
|||||||
* Helper method to start and log the current phase.
|
* Helper method to start and log the current phase.
|
||||||
*/
|
*/
|
||||||
private startCurrentPhase(): void {
|
private startCurrentPhase(): void {
|
||||||
console.log(`%cStart Phase ${this.currentPhase.phaseName}`, "color:green;");
|
console.log(`%cStart Phase ${this.currentPhase.phaseName}`, `color:${PHASE_START_COLOR};`);
|
||||||
this.currentPhase.start();
|
this.currentPhase.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
import { applyAbAttrs } from "#abilities/apply-ab-attrs";
|
import { applyAbAttrs } from "#abilities/apply-ab-attrs";
|
||||||
|
import { MOVE_COLOR } from "#app/constants/colors";
|
||||||
import { globalScene } from "#app/global-scene";
|
import { globalScene } from "#app/global-scene";
|
||||||
import { getPokemonNameWithAffix } from "#app/messages";
|
import { getPokemonNameWithAffix } from "#app/messages";
|
||||||
import Overrides from "#app/overrides";
|
import Overrides from "#app/overrides";
|
||||||
@ -118,7 +119,10 @@ export class MovePhase extends BattlePhase {
|
|||||||
public start(): void {
|
public start(): void {
|
||||||
super.start();
|
super.start();
|
||||||
|
|
||||||
console.log(MoveId[this.move.moveId], enumValueToKey(MoveUseMode, this.useMode));
|
console.log(
|
||||||
|
`%cMove: ${MoveId[this.move.moveId]}\nUse Mode: ${enumValueToKey(MoveUseMode, this.useMode)}`,
|
||||||
|
`color:${MOVE_COLOR}`,
|
||||||
|
);
|
||||||
|
|
||||||
// Check if move is unusable (e.g. running out of PP due to a mid-turn Spite
|
// Check if move is unusable (e.g. running out of PP due to a mid-turn Spite
|
||||||
// or the user no longer being on field), ending the phase early if not.
|
// or the user no longer being on field), ending the phase early if not.
|
||||||
|
@ -544,8 +544,13 @@ export abstract class AbstractControlSettingsUiHandler extends UiHandler {
|
|||||||
}
|
}
|
||||||
if (this.settingBlacklisted.includes(setting) || setting.includes("BUTTON_")) {
|
if (this.settingBlacklisted.includes(setting) || setting.includes("BUTTON_")) {
|
||||||
success = false;
|
success = false;
|
||||||
} else if (this.optionCursors[cursor]) {
|
} else {
|
||||||
success = this.setOptionCursor(cursor, this.optionCursors[cursor] - 1, true);
|
// Cycle to the rightmost position when at the leftmost, otherwise move left
|
||||||
|
success = this.setOptionCursor(
|
||||||
|
cursor,
|
||||||
|
Phaser.Math.Wrap(this.optionCursors[cursor] - 1, 0, this.optionValueLabels[cursor].length),
|
||||||
|
true,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case Button.RIGHT: // Move selection right within the current option set.
|
case Button.RIGHT: // Move selection right within the current option set.
|
||||||
@ -554,8 +559,13 @@ export abstract class AbstractControlSettingsUiHandler extends UiHandler {
|
|||||||
}
|
}
|
||||||
if (this.settingBlacklisted.includes(setting) || setting.includes("BUTTON_")) {
|
if (this.settingBlacklisted.includes(setting) || setting.includes("BUTTON_")) {
|
||||||
success = false;
|
success = false;
|
||||||
} else if (this.optionCursors[cursor] < this.optionValueLabels[cursor].length - 1) {
|
} else {
|
||||||
success = this.setOptionCursor(cursor, this.optionCursors[cursor] + 1, true);
|
// Cycle to the leftmost position when at the rightmost, otherwise move right
|
||||||
|
success = this.setOptionCursor(
|
||||||
|
cursor,
|
||||||
|
Phaser.Math.Wrap(this.optionCursors[cursor] + 1, 0, this.optionValueLabels[cursor].length),
|
||||||
|
true,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case Button.CYCLE_FORM:
|
case Button.CYCLE_FORM:
|
||||||
|
@ -318,16 +318,20 @@ export class AbstractSettingsUiHandler extends MessageUiHandler {
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case Button.LEFT:
|
case Button.LEFT:
|
||||||
if (this.optionCursors[cursor]) {
|
// Cycle to the rightmost position when at the leftmost, otherwise move left
|
||||||
// Moves the option cursor left, if possible.
|
success = this.setOptionCursor(
|
||||||
success = this.setOptionCursor(cursor, this.optionCursors[cursor] - 1, true);
|
cursor,
|
||||||
}
|
Phaser.Math.Wrap(this.optionCursors[cursor] - 1, 0, this.optionValueLabels[cursor].length),
|
||||||
|
true,
|
||||||
|
);
|
||||||
break;
|
break;
|
||||||
case Button.RIGHT:
|
case Button.RIGHT:
|
||||||
// Moves the option cursor right, if possible.
|
// Cycle to the leftmost position when at the rightmost, otherwise move right
|
||||||
if (this.optionCursors[cursor] < this.optionValueLabels[cursor].length - 1) {
|
success = this.setOptionCursor(
|
||||||
success = this.setOptionCursor(cursor, this.optionCursors[cursor] + 1, true);
|
cursor,
|
||||||
}
|
Phaser.Math.Wrap(this.optionCursors[cursor] + 1, 0, this.optionValueLabels[cursor].length),
|
||||||
|
true,
|
||||||
|
);
|
||||||
break;
|
break;
|
||||||
case Button.CYCLE_FORM:
|
case Button.CYCLE_FORM:
|
||||||
case Button.CYCLE_SHINY:
|
case Button.CYCLE_SHINY:
|
||||||
|
12
test/@types/vitest.d.ts
vendored
12
test/@types/vitest.d.ts
vendored
@ -4,8 +4,6 @@ import type { Phase } from "#app/phase";
|
|||||||
import type Overrides from "#app/overrides";
|
import type Overrides from "#app/overrides";
|
||||||
import type { ArenaTag } from "#data/arena-tag";
|
import type { ArenaTag } from "#data/arena-tag";
|
||||||
import type { TerrainType } from "#data/terrain";
|
import type { TerrainType } from "#data/terrain";
|
||||||
import type { BattlerTag } from "#data/battler-tags";
|
|
||||||
import type { PositionalTag } from "#data/positional-tags/positional-tag";
|
|
||||||
import type { AbilityId } from "#enums/ability-id";
|
import type { AbilityId } from "#enums/ability-id";
|
||||||
import type { ArenaTagSide } from "#enums/arena-tag-side";
|
import type { ArenaTagSide } from "#enums/arena-tag-side";
|
||||||
import type { ArenaTagType } from "#enums/arena-tag-type";
|
import type { ArenaTagType } from "#enums/arena-tag-type";
|
||||||
@ -13,12 +11,8 @@ import type { BattlerTagType } from "#enums/battler-tag-type";
|
|||||||
import type { MoveId } from "#enums/move-id";
|
import type { MoveId } from "#enums/move-id";
|
||||||
import type { PokemonType } from "#enums/pokemon-type";
|
import type { PokemonType } from "#enums/pokemon-type";
|
||||||
import type { PositionalTagType } from "#enums/positional-tag-type";
|
import type { PositionalTagType } from "#enums/positional-tag-type";
|
||||||
import type { BattleStat, EffectiveStat, Stat } from "#enums/stat";
|
import type { BattleStat, EffectiveStat } from "#enums/stat";
|
||||||
import type { StatusEffect } from "#enums/status-effect";
|
|
||||||
import type { WeatherType } from "#enums/weather-type";
|
import type { WeatherType } from "#enums/weather-type";
|
||||||
import type { Arena } from "#field/arena";
|
|
||||||
import type { Pokemon } from "#field/pokemon";
|
|
||||||
import type { PokemonMove } from "#moves/pokemon-move";
|
|
||||||
import type { toHaveArenaTagOptions } from "#test/test-utils/matchers/to-have-arena-tag";
|
import type { toHaveArenaTagOptions } from "#test/test-utils/matchers/to-have-arena-tag";
|
||||||
import type { toHaveEffectiveStatOptions } from "#test/test-utils/matchers/to-have-effective-stat";
|
import type { toHaveEffectiveStatOptions } from "#test/test-utils/matchers/to-have-effective-stat";
|
||||||
import type { toHavePositionalTagOptions } from "#test/test-utils/matchers/to-have-positional-tag";
|
import type { toHavePositionalTagOptions } from "#test/test-utils/matchers/to-have-positional-tag";
|
||||||
@ -27,9 +21,9 @@ import type { toHaveTypesOptions } from "#test/test-utils/matchers/to-have-types
|
|||||||
import type { PhaseString } from "#types/phase-types";
|
import type { PhaseString } from "#types/phase-types";
|
||||||
import type { TurnMove } from "#types/turn-move";
|
import type { TurnMove } from "#types/turn-move";
|
||||||
import type { AtLeastOne } from "#types/type-helpers";
|
import type { AtLeastOne } from "#types/type-helpers";
|
||||||
import type { toDmgValue } from "utils/common";
|
import type { toDmgValue } from "#utils/common";
|
||||||
import type { expect } from "vitest";
|
import type { expect } from "vitest";
|
||||||
import { toHaveBattlerTagOptions } from "#test/test-utils/matchers/to-have-battler-tag";
|
import type { toHaveBattlerTagOptions } from "#test/test-utils/matchers/to-have-battler-tag";
|
||||||
|
|
||||||
declare module "vitest" {
|
declare module "vitest" {
|
||||||
interface Assertion<T> {
|
interface Assertion<T> {
|
||||||
|
@ -99,7 +99,7 @@ describe("Abilities - Cud Chew", () => {
|
|||||||
expect(abDisplaySpy.mock.calls[1][2]).toBe(false);
|
expect(abDisplaySpy.mock.calls[1][2]).toBe(false);
|
||||||
|
|
||||||
// should display messgae
|
// should display messgae
|
||||||
expect(game.textInterceptor.getLatestMessage()).toBe(
|
expect(game.textInterceptor.logs).toContain(
|
||||||
i18next.t("battle:hpIsFull", {
|
i18next.t("battle:hpIsFull", {
|
||||||
pokemonName: getPokemonNameWithAffix(farigiraf),
|
pokemonName: getPokemonNameWithAffix(farigiraf),
|
||||||
}),
|
}),
|
||||||
|
@ -9,7 +9,7 @@ import { TurnStartPhase } from "#phases/turn-start-phase";
|
|||||||
import { GameManager } from "#test/test-utils/game-manager";
|
import { GameManager } from "#test/test-utils/game-manager";
|
||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
import Phaser from "phaser";
|
import Phaser from "phaser";
|
||||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
describe("Moves - Focus Punch", () => {
|
describe("Moves - Focus Punch", () => {
|
||||||
let phaserGame: Phaser.Game;
|
let phaserGame: Phaser.Game;
|
||||||
@ -125,8 +125,8 @@ describe("Moves - Focus Punch", () => {
|
|||||||
game.move.select(MoveId.FOCUS_PUNCH);
|
game.move.select(MoveId.FOCUS_PUNCH);
|
||||||
await game.phaseInterceptor.to("MoveEndPhase", true);
|
await game.phaseInterceptor.to("MoveEndPhase", true);
|
||||||
await game.phaseInterceptor.to("MessagePhase", false);
|
await game.phaseInterceptor.to("MessagePhase", false);
|
||||||
const consoleSpy = vi.spyOn(console, "log");
|
|
||||||
await game.phaseInterceptor.to("MoveEndPhase", true);
|
await game.phaseInterceptor.to("MoveEndPhase", true);
|
||||||
expect(consoleSpy).nthCalledWith(1, i18next.t("moveTriggers:lostFocus", { pokemonName: "Charizard" }));
|
expect(game.textInterceptor.logs).toContain(i18next.t("moveTriggers:lostFocus", { pokemonName: "Charizard" }));
|
||||||
|
expect(game.textInterceptor.logs).not.toContain(i18next.t("battle:attackFailed"));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -6,17 +6,13 @@ import * as bypassLoginModule from "#app/global-vars/bypass-login";
|
|||||||
import { MoveAnim } from "#data/battle-anims";
|
import { MoveAnim } from "#data/battle-anims";
|
||||||
import { Pokemon } from "#field/pokemon";
|
import { Pokemon } from "#field/pokemon";
|
||||||
import { version } from "#package.json";
|
import { version } from "#package.json";
|
||||||
import { blobToString } from "#test/test-utils/game-manager-utils";
|
|
||||||
import { MockClock } from "#test/test-utils/mocks/mock-clock";
|
import { MockClock } from "#test/test-utils/mocks/mock-clock";
|
||||||
import { MockFetch } from "#test/test-utils/mocks/mock-fetch";
|
|
||||||
import { MockGameObjectCreator } from "#test/test-utils/mocks/mock-game-object-creator";
|
import { MockGameObjectCreator } from "#test/test-utils/mocks/mock-game-object-creator";
|
||||||
import { MockLoader } from "#test/test-utils/mocks/mock-loader";
|
import { MockLoader } from "#test/test-utils/mocks/mock-loader";
|
||||||
import { MockTextureManager } from "#test/test-utils/mocks/mock-texture-manager";
|
import { MockTextureManager } from "#test/test-utils/mocks/mock-texture-manager";
|
||||||
import { MockTimedEventManager } from "#test/test-utils/mocks/mock-timed-event-manager";
|
import { MockTimedEventManager } from "#test/test-utils/mocks/mock-timed-event-manager";
|
||||||
import { MockContainer } from "#test/test-utils/mocks/mocks-container/mock-container";
|
import { MockContainer } from "#test/test-utils/mocks/mocks-container/mock-container";
|
||||||
import { PokedexMonContainer } from "#ui/containers/pokedex-mon-container";
|
import { PokedexMonContainer } from "#ui/containers/pokedex-mon-container";
|
||||||
import { sessionIdKey } from "#utils/common";
|
|
||||||
import { setCookie } from "#utils/cookies";
|
|
||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import Phaser from "phaser";
|
import Phaser from "phaser";
|
||||||
import { vi } from "vitest";
|
import { vi } from "vitest";
|
||||||
@ -28,20 +24,6 @@ const GamepadPlugin = Phaser.Input.Gamepad.GamepadPlugin;
|
|||||||
const EventEmitter = Phaser.Events.EventEmitter;
|
const EventEmitter = Phaser.Events.EventEmitter;
|
||||||
const UpdateList = Phaser.GameObjects.UpdateList;
|
const UpdateList = Phaser.GameObjects.UpdateList;
|
||||||
|
|
||||||
window.URL.createObjectURL = (blob: Blob) => {
|
|
||||||
blobToString(blob).then((data: string) => {
|
|
||||||
localStorage.setItem("toExport", data);
|
|
||||||
});
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
navigator.getGamepads = () => [];
|
|
||||||
global.fetch = vi.fn(MockFetch);
|
|
||||||
setCookie(sessionIdKey, "fake_token");
|
|
||||||
|
|
||||||
window.matchMedia = () => ({
|
|
||||||
matches: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
export class GameWrapper {
|
export class GameWrapper {
|
||||||
public game: Phaser.Game;
|
public game: Phaser.Game;
|
||||||
public scene: BattleScene;
|
public scene: BattleScene;
|
||||||
@ -99,6 +81,7 @@ export class GameWrapper {
|
|||||||
removeAll: () => null,
|
removeAll: () => null,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// TODO: Can't we just turn on `noAudio` in audio config?
|
||||||
this.scene.sound = {
|
this.scene.sound = {
|
||||||
play: () => null,
|
play: () => null,
|
||||||
pause: () => null,
|
pause: () => null,
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
import overrides from "#app/overrides";
|
import overrides from "#app/overrides";
|
||||||
import type { Challenge } from "#data/challenge";
|
import type { Challenge } from "#data/challenge";
|
||||||
|
import { copyChallenge } from "#data/challenge";
|
||||||
import { BattleStyle } from "#enums/battle-style";
|
import { BattleStyle } from "#enums/battle-style";
|
||||||
import type { Challenges } from "#enums/challenges";
|
import type { Challenges } from "#enums/challenges";
|
||||||
import type { SpeciesId } from "#enums/species-id";
|
import type { SpeciesId } from "#enums/species-id";
|
||||||
@ -10,7 +11,6 @@ import { SelectStarterPhase } from "#phases/select-starter-phase";
|
|||||||
import { TurnInitPhase } from "#phases/turn-init-phase";
|
import { TurnInitPhase } from "#phases/turn-init-phase";
|
||||||
import { generateStarter } from "#test/test-utils/game-manager-utils";
|
import { generateStarter } from "#test/test-utils/game-manager-utils";
|
||||||
import { GameManagerHelper } from "#test/test-utils/helpers/game-manager-helper";
|
import { GameManagerHelper } from "#test/test-utils/helpers/game-manager-helper";
|
||||||
import { copyChallenge } from "data/challenge";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper to handle Challenge mode specifics
|
* Helper to handle Challenge mode specifics
|
||||||
|
@ -1,7 +1,9 @@
|
|||||||
/** biome-ignore-start lint/correctness/noUnusedImports: tsdoc imports */
|
/** biome-ignore-start lint/correctness/noUnusedImports: tsdoc imports */
|
||||||
import type { NewArenaEvent } from "#events/battle-scene";
|
import type { NewArenaEvent } from "#events/battle-scene";
|
||||||
|
|
||||||
/** biome-ignore-end lint/correctness/noUnusedImports: tsdoc imports */
|
/** biome-ignore-end lint/correctness/noUnusedImports: tsdoc imports */
|
||||||
|
|
||||||
|
import { OVERRIDES_COLOR } from "#app/constants/colors";
|
||||||
import type { BattleStyle, RandomTrainerOverride } from "#app/overrides";
|
import type { BattleStyle, RandomTrainerOverride } from "#app/overrides";
|
||||||
import Overrides from "#app/overrides";
|
import Overrides from "#app/overrides";
|
||||||
import { AbilityId } from "#enums/ability-id";
|
import { AbilityId } from "#enums/ability-id";
|
||||||
@ -19,6 +21,7 @@ import type { ModifierOverride } from "#modifiers/modifier-type";
|
|||||||
import type { Variant } from "#sprites/variant";
|
import type { Variant } from "#sprites/variant";
|
||||||
import { GameManagerHelper } from "#test/test-utils/helpers/game-manager-helper";
|
import { GameManagerHelper } from "#test/test-utils/helpers/game-manager-helper";
|
||||||
import { coerceArray, shiftCharCodes } from "#utils/common";
|
import { coerceArray, shiftCharCodes } from "#utils/common";
|
||||||
|
import chalk from "chalk";
|
||||||
import { vi } from "vitest";
|
import { vi } from "vitest";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -665,6 +668,6 @@ export class OverridesHelper extends GameManagerHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private log(...params: any[]) {
|
private log(...params: any[]) {
|
||||||
console.log("Overrides:", ...params);
|
console.log(chalk.hex(OVERRIDES_COLOR)(...params));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,9 @@
|
|||||||
|
import { SETTINGS_COLOR } from "#app/constants/colors";
|
||||||
import { BattleStyle } from "#enums/battle-style";
|
import { BattleStyle } from "#enums/battle-style";
|
||||||
import { ExpGainsSpeed } from "#enums/exp-gains-speed";
|
import { ExpGainsSpeed } from "#enums/exp-gains-speed";
|
||||||
import { PlayerGender } from "#enums/player-gender";
|
import { PlayerGender } from "#enums/player-gender";
|
||||||
import { GameManagerHelper } from "#test/test-utils/helpers/game-manager-helper";
|
import { GameManagerHelper } from "#test/test-utils/helpers/game-manager-helper";
|
||||||
|
import chalk from "chalk";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper to handle settings for tests
|
* Helper to handle settings for tests
|
||||||
@ -49,6 +51,6 @@ export class SettingsHelper extends GameManagerHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private log(...params: any[]) {
|
private log(...params: any[]) {
|
||||||
console.log("Settings:", ...params);
|
console.log(chalk.hex(SETTINGS_COLOR)(...params));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,80 +0,0 @@
|
|||||||
const originalLog = console.log;
|
|
||||||
const originalError = console.error;
|
|
||||||
const originalDebug = console.debug;
|
|
||||||
const originalWarn = console.warn;
|
|
||||||
|
|
||||||
const blacklist = ["Phaser", "variant icon does not exist", 'Texture "%s" not found'];
|
|
||||||
const whitelist = ["Phase"];
|
|
||||||
|
|
||||||
export class MockConsoleLog {
|
|
||||||
constructor(
|
|
||||||
private logDisabled = false,
|
|
||||||
private phaseText = false,
|
|
||||||
) {}
|
|
||||||
private logs: any[] = [];
|
|
||||||
private notified: any[] = [];
|
|
||||||
|
|
||||||
public log(...args) {
|
|
||||||
const argsStr = this.getStr(args);
|
|
||||||
this.logs.push(argsStr);
|
|
||||||
if (this.logDisabled && !this.phaseText) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if ((this.phaseText && !whitelist.some(b => argsStr.includes(b))) || blacklist.some(b => argsStr.includes(b))) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
originalLog(args);
|
|
||||||
}
|
|
||||||
public error(...args) {
|
|
||||||
const argsStr = this.getStr(args);
|
|
||||||
this.logs.push(argsStr);
|
|
||||||
originalError(args); // Appelle le console.error originel
|
|
||||||
}
|
|
||||||
public debug(...args) {
|
|
||||||
const argsStr = this.getStr(args);
|
|
||||||
this.logs.push(argsStr);
|
|
||||||
if (this.logDisabled && !this.phaseText) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!whitelist.some(b => argsStr.includes(b)) || blacklist.some(b => argsStr.includes(b))) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
originalDebug(args);
|
|
||||||
}
|
|
||||||
warn(...args) {
|
|
||||||
const argsStr = this.getStr(args);
|
|
||||||
this.logs.push(args);
|
|
||||||
if (this.logDisabled && !this.phaseText) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!whitelist.some(b => argsStr.includes(b)) || blacklist.some(b => argsStr.includes(b))) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
originalWarn(args);
|
|
||||||
}
|
|
||||||
notify(msg) {
|
|
||||||
originalLog(msg);
|
|
||||||
this.notified.push(msg);
|
|
||||||
}
|
|
||||||
getLogs() {
|
|
||||||
return this.logs;
|
|
||||||
}
|
|
||||||
clearLogs() {
|
|
||||||
this.logs = [];
|
|
||||||
}
|
|
||||||
getStr(...args) {
|
|
||||||
return args
|
|
||||||
.map(arg => {
|
|
||||||
if (typeof arg === "object" && arg !== null) {
|
|
||||||
// Handle objects including arrays
|
|
||||||
return JSON.stringify(arg, (_key, value) => (typeof value === "bigint" ? value.toString() : value));
|
|
||||||
}
|
|
||||||
if (typeof arg === "bigint") {
|
|
||||||
// Handle BigInt values
|
|
||||||
return arg.toString();
|
|
||||||
}
|
|
||||||
return arg.toString();
|
|
||||||
})
|
|
||||||
.join(";");
|
|
||||||
}
|
|
||||||
}
|
|
150
test/test-utils/mocks/mock-console/color-map.json
Normal file
150
test/test-utils/mocks/mock-console/color-map.json
Normal file
@ -0,0 +1,150 @@
|
|||||||
|
{
|
||||||
|
"AliceBlue": "f0f8ff",
|
||||||
|
"AntiqueWhite": "faebd7",
|
||||||
|
"Aqua": "00ffff",
|
||||||
|
"Aquamarine": "7fffd4",
|
||||||
|
"Azure": "f0ffff",
|
||||||
|
"Beige": "f5f5dc",
|
||||||
|
"Bisque": "ffe4c4",
|
||||||
|
"Black": "000000",
|
||||||
|
"BlanchedAlmond": "ffebcd",
|
||||||
|
"Blue": "0000ff",
|
||||||
|
"BlueViolet": "8a2be2",
|
||||||
|
"Brown": "a52a2a",
|
||||||
|
"BurlyWood": "deb887",
|
||||||
|
"CadetBlue": "5f9ea0",
|
||||||
|
"Chartreuse": "7fff00",
|
||||||
|
"Chocolate": "d2691e",
|
||||||
|
"Coral": "ff7f50",
|
||||||
|
"CornflowerBlue": "6495ed",
|
||||||
|
"Cornsilk": "fff8dc",
|
||||||
|
"Crimson": "dc143c",
|
||||||
|
"Cyan": "00ffff",
|
||||||
|
"DarkBlue": "00008b",
|
||||||
|
"DarkCyan": "008b8b",
|
||||||
|
"DarkGoldenRod": "b8860b",
|
||||||
|
"DarkGray": "a9a9a9",
|
||||||
|
"DarkGrey": "a9a9a9",
|
||||||
|
"DarkGreen": "006400",
|
||||||
|
"DarkKhaki": "bdb76b",
|
||||||
|
"DarkMagenta": "8b008b",
|
||||||
|
"DarkOliveGreen": "556b2f",
|
||||||
|
"DarkOrange": "ff8c00",
|
||||||
|
"DarkOrchid": "9932cc",
|
||||||
|
"DarkRed": "8b0000",
|
||||||
|
"DarkSalmon": "e9967a",
|
||||||
|
"DarkSeaGreen": "8fbc8f",
|
||||||
|
"DarkSlateBlue": "483d8b",
|
||||||
|
"DarkSlateGray": "2f4f4f",
|
||||||
|
"DarkSlateGrey": "2f4f4f",
|
||||||
|
"DarkTurquoise": "00ced1",
|
||||||
|
"DarkViolet": "9400d3",
|
||||||
|
"DeepPink": "ff1493",
|
||||||
|
"DeepSkyBlue": "00bfff",
|
||||||
|
"DimGray": "696969",
|
||||||
|
"DimGrey": "696969",
|
||||||
|
"DodgerBlue": "1e90ff",
|
||||||
|
"FireBrick": "b22222",
|
||||||
|
"FloralWhite": "fffaf0",
|
||||||
|
"ForestGreen": "228b22",
|
||||||
|
"Fuchsia": "ff00ff",
|
||||||
|
"Gainsboro": "dcdcdc",
|
||||||
|
"GhostWhite": "f8f8ff",
|
||||||
|
"Gold": "ffd700",
|
||||||
|
"GoldenRod": "daa520",
|
||||||
|
"Gray": "808080",
|
||||||
|
"Grey": "808080",
|
||||||
|
"Green": "008000",
|
||||||
|
"GreenYellow": "adff2f",
|
||||||
|
"HoneyDew": "f0fff0",
|
||||||
|
"HotPink": "ff69b4",
|
||||||
|
"IndianRed": "cd5c5c",
|
||||||
|
"Indigo": "4b0082",
|
||||||
|
"Ivory": "fffff0",
|
||||||
|
"Khaki": "f0e68c",
|
||||||
|
"Lavender": "e6e6fa",
|
||||||
|
"LavenderBlush": "fff0f5",
|
||||||
|
"LawnGreen": "7cfc00",
|
||||||
|
"LemonChiffon": "fffacd",
|
||||||
|
"LightBlue": "add8e6",
|
||||||
|
"LightCoral": "f08080",
|
||||||
|
"LightCyan": "e0ffff",
|
||||||
|
"LightGoldenRodYellow": "fafad2",
|
||||||
|
"LightGray": "d3d3d3",
|
||||||
|
"LightGrey": "d3d3d3",
|
||||||
|
"LightGreen": "90ee90",
|
||||||
|
"LightPink": "ffb6c1",
|
||||||
|
"LightSalmon": "ffa07a",
|
||||||
|
"LightSeaGreen": "20b2aa",
|
||||||
|
"LightSkyBlue": "87cefa",
|
||||||
|
"LightSlateGray": "778899",
|
||||||
|
"LightSlateGrey": "778899",
|
||||||
|
"LightSteelBlue": "b0c4de",
|
||||||
|
"LightYellow": "ffffe0",
|
||||||
|
"Lime": "00ff00",
|
||||||
|
"LimeGreen": "32cd32",
|
||||||
|
"Linen": "faf0e6",
|
||||||
|
"Magenta": "ff00ff",
|
||||||
|
"Maroon": "800000",
|
||||||
|
"MediumAquaMarine": "66cdaa",
|
||||||
|
"MediumBlue": "0000cd",
|
||||||
|
"MediumOrchid": "ba55d3",
|
||||||
|
"MediumPurple": "9370db",
|
||||||
|
"MediumSeaGreen": "3cb371",
|
||||||
|
"MediumSlateBlue": "7b68ee",
|
||||||
|
"MediumSpringGreen": "00fa9a",
|
||||||
|
"MediumTurquoise": "48d1cc",
|
||||||
|
"MediumVioletRed": "c71585",
|
||||||
|
"MidnightBlue": "191970",
|
||||||
|
"MintCream": "f5fffa",
|
||||||
|
"MistyRose": "ffe4e1",
|
||||||
|
"Moccasin": "ffe4b5",
|
||||||
|
"NavajoWhite": "ffdead",
|
||||||
|
"Navy": "000080",
|
||||||
|
"OldLace": "fdf5e6",
|
||||||
|
"Olive": "808000",
|
||||||
|
"OliveDrab": "6b8e23",
|
||||||
|
"Orange": "ffa500",
|
||||||
|
"OrangeRed": "ff4500",
|
||||||
|
"Orchid": "da70d6",
|
||||||
|
"PaleGoldenRod": "eee8aa",
|
||||||
|
"PaleGreen": "98fb98",
|
||||||
|
"PaleTurquoise": "afeeee",
|
||||||
|
"PaleVioletRed": "db7093",
|
||||||
|
"PapayaWhip": "ffefd5",
|
||||||
|
"PeachPuff": "ffdab9",
|
||||||
|
"Peru": "cd853f",
|
||||||
|
"Pink": "ffc0cb",
|
||||||
|
"Plum": "dda0dd",
|
||||||
|
"PowderBlue": "b0e0e6",
|
||||||
|
"Purple": "800080",
|
||||||
|
"RebeccaPurple": "663399",
|
||||||
|
"Red": "ff0000",
|
||||||
|
"RosyBrown": "bc8f8f",
|
||||||
|
"RoyalBlue": "4169e1",
|
||||||
|
"SaddleBrown": "8b4513",
|
||||||
|
"Salmon": "fa8072",
|
||||||
|
"SandyBrown": "f4a460",
|
||||||
|
"SeaGreen": "2e8b57",
|
||||||
|
"SeaShell": "fff5ee",
|
||||||
|
"Sienna": "a0522d",
|
||||||
|
"Silver": "c0c0c0",
|
||||||
|
"SkyBlue": "87ceeb",
|
||||||
|
"SlateBlue": "6a5acd",
|
||||||
|
"SlateGray": "708090",
|
||||||
|
"SlateGrey": "708090",
|
||||||
|
"Snow": "fffafa",
|
||||||
|
"SpringGreen": "00ff7f",
|
||||||
|
"SteelBlue": "4682b4",
|
||||||
|
"Tan": "d2b48c",
|
||||||
|
"Teal": "008080",
|
||||||
|
"Thistle": "d8bfd8",
|
||||||
|
"Tomato": "ff6347",
|
||||||
|
"Turquoise": "40e0d0",
|
||||||
|
"Violet": "ee82ee",
|
||||||
|
"Wheat": "f5deb3",
|
||||||
|
"White": "ffffff",
|
||||||
|
"WhiteSmoke": "f5f5f5",
|
||||||
|
"Yellow": "ffff00",
|
||||||
|
"YellowGreen": "9acd32"
|
||||||
|
}
|
61
test/test-utils/mocks/mock-console/infer-color.ts
Normal file
61
test/test-utils/mocks/mock-console/infer-color.ts
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
import { hslToHex } from "#utils/common";
|
||||||
|
import chalk, { type ChalkInstance, type ForegroundColorName, foregroundColorNames } from "chalk";
|
||||||
|
import colorMap from "./color-map.json";
|
||||||
|
|
||||||
|
export function inferColorFormat(data: [string, ...unknown[]]): ChalkInstance {
|
||||||
|
// Remove all CSS format strings and find the first one containing something vaguely resembling a color
|
||||||
|
data[0] = data[0].replaceAll("%c", "");
|
||||||
|
const args = data.slice(1).filter(t => typeof t === "string");
|
||||||
|
const color = findColorPrefix(args);
|
||||||
|
|
||||||
|
// If the color is within Chalk's native roster, use it directly.
|
||||||
|
if ((foregroundColorNames as string[]).includes(color)) {
|
||||||
|
return chalk[color as ForegroundColorName];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise, coerce it to hex before feeding it in.
|
||||||
|
return getColor(color);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the first string with a "color:" CSS directive in an argument list.
|
||||||
|
* @param args - The arguments containing the color directive
|
||||||
|
* @returns The found color, or `"green"` if none were found
|
||||||
|
*/
|
||||||
|
function findColorPrefix(args: string[]): string {
|
||||||
|
for (const arg of args) {
|
||||||
|
const match = /color:\s*(.+?)(?:;|$)/g.exec(arg);
|
||||||
|
if (match === null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return match[1];
|
||||||
|
}
|
||||||
|
return "green";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Coerce an arbitrary CSS color string to a Chalk instance.
|
||||||
|
* @param color - The color to coerce
|
||||||
|
* @returns The Chalk color equivalent.
|
||||||
|
*/
|
||||||
|
function getColor(color: string): ChalkInstance {
|
||||||
|
if (/^#([a-z0-9]{3,4}|[a-z0-9]{6}|[a-z0-9]{8})$/i.test(color)) {
|
||||||
|
// already in hex
|
||||||
|
return chalk.hex(color);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rgbMatch = /^rgba?\((\d{1,3})%?,\s*(\d{1,3})%?,?\s*(\d{1,3})%?,\s*/i.exec(color);
|
||||||
|
if (rgbMatch) {
|
||||||
|
const [red, green, blue] = rgbMatch;
|
||||||
|
return chalk.rgb(+red, +green, +blue);
|
||||||
|
}
|
||||||
|
|
||||||
|
const hslMatch = /^hslv?\((\d{1,3}),\s*(\d{1,3})%,\s*(\d{1,3})%\)$/i.exec(color);
|
||||||
|
if (hslMatch) {
|
||||||
|
const [hue, saturation, light] = hslMatch;
|
||||||
|
return chalk.hex(hslToHex(+hue, +saturation / 100, +light / 100));
|
||||||
|
}
|
||||||
|
|
||||||
|
return chalk.hex(colorMap[color] ?? "#00ff95ff");
|
||||||
|
}
|
211
test/test-utils/mocks/mock-console/mock-console.ts
Normal file
211
test/test-utils/mocks/mock-console/mock-console.ts
Normal file
@ -0,0 +1,211 @@
|
|||||||
|
import { DEBUG_COLOR, NEW_TURN_COLOR, TRACE_COLOR, UI_MSG_COLOR } from "#app/constants/colors";
|
||||||
|
import { inferColorFormat } from "#test/test-utils/mocks/mock-console/infer-color";
|
||||||
|
import { coerceArray } from "#utils/common";
|
||||||
|
import { type InspectOptions, inspect } from "node:util";
|
||||||
|
import chalk, { type ChalkInstance } from "chalk";
|
||||||
|
|
||||||
|
// Tell chalk we support truecolor
|
||||||
|
chalk.level = 3;
|
||||||
|
|
||||||
|
// TODO: Review this
|
||||||
|
const blacklist = [
|
||||||
|
"variant icon does not exist", // Repetitive warnings about icons not found
|
||||||
|
'Texture "%s" not found', // Repetitive warnings about textures not found
|
||||||
|
"type: 'Pokemon',", // Large Pokemon objects
|
||||||
|
"gameVersion: ", // Large session-data and system-data objects
|
||||||
|
"Phaser v", // Phaser version text
|
||||||
|
"Seed:", // Stuff about wave seed (we should really stop logging this shit)
|
||||||
|
"Wave Seed:", // Stuff about wave seed (we should really stop logging this shit)
|
||||||
|
] as const;
|
||||||
|
const whitelist = ["Start Phase"] as const;
|
||||||
|
|
||||||
|
const inspectOptions: InspectOptions = { sorted: true, breakLength: 120, numericSeparator: true };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The {@linkcode MockConsole} is a wrapper around the global {@linkcode console} object.
|
||||||
|
* It automatically colors text and such.
|
||||||
|
*/
|
||||||
|
export class MockConsole implements Omit<Console, "Console"> {
|
||||||
|
/**
|
||||||
|
* A list of warnings that are queued to be displayed after all tests in the same file are finished.
|
||||||
|
*/
|
||||||
|
private static readonly queuedWarnings: unknown[][] = [];
|
||||||
|
/**
|
||||||
|
* The original `Console` object, preserved to avoid overwriting
|
||||||
|
* Vitest's native `console.log` wrapping.
|
||||||
|
*/
|
||||||
|
private console = console;
|
||||||
|
|
||||||
|
//#region Static Properties
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queue a warning to be printed after all tests in the same file are finished.
|
||||||
|
*/
|
||||||
|
// TODO: Add some warnings
|
||||||
|
public static queuePostTestWarning(...data: unknown[]): void {
|
||||||
|
MockConsole.queuedWarnings.push(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Print and reset all post-test warnings.
|
||||||
|
*/
|
||||||
|
public static printPostTestWarnings(): void {
|
||||||
|
for (const data of MockConsole.queuedWarnings) {
|
||||||
|
console.warn(...data);
|
||||||
|
}
|
||||||
|
MockConsole.queuedWarnings.splice(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
//#endregion Private Properties
|
||||||
|
|
||||||
|
//#region Utilities
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether a given set of data is in the blacklist to be barred from logging.
|
||||||
|
* @param data - The data being logged
|
||||||
|
* @returns Whether `data` is blacklisted from console logging
|
||||||
|
*/
|
||||||
|
private checkBlacklist(data: unknown[]): boolean {
|
||||||
|
const dataStr = this.getStr(data);
|
||||||
|
return !whitelist.some(b => dataStr.includes(b)) && blacklist.some(b => dataStr.includes(b));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a human-readable string representation of `data`.
|
||||||
|
*/
|
||||||
|
private getStr(data: unknown): string {
|
||||||
|
return inspect(data, inspectOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stringify the given data in a manner fit for logging.
|
||||||
|
* @param color - A Chalk instance or other transformation function used to transform the output,
|
||||||
|
* or `undefined` to not transform it at all.
|
||||||
|
* @param data - The data that the format should be applied to.
|
||||||
|
* @returns A stringified copy of `data` with {@linkcode color} applied to each individual argument.
|
||||||
|
* @todo Do we need to apply color to each entry or just run it through `util.format`?
|
||||||
|
*/
|
||||||
|
private format(color: ((s: unknown) => unknown) | undefined, data: unknown | unknown[]): unknown[] {
|
||||||
|
data = coerceArray(data);
|
||||||
|
color ??= a => a;
|
||||||
|
return (data as unknown[]).map(a => color(typeof a === "function" || typeof a === "object" ? this.getStr(a) : a));
|
||||||
|
}
|
||||||
|
|
||||||
|
//#endregion Utilities
|
||||||
|
|
||||||
|
//#region Custom wrappers
|
||||||
|
public info(...data: unknown[]) {
|
||||||
|
return this.log(...data);
|
||||||
|
}
|
||||||
|
|
||||||
|
public trace(...data: unknown[]) {
|
||||||
|
if (this.checkBlacklist(data)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Figure out how to add color to the full trace text
|
||||||
|
this.console.trace(...this.format(chalk.hex(TRACE_COLOR), data));
|
||||||
|
}
|
||||||
|
|
||||||
|
public debug(...data: unknown[]) {
|
||||||
|
if (this.checkBlacklist(data)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.console.debug(...this.format(chalk.hex(DEBUG_COLOR), data));
|
||||||
|
}
|
||||||
|
|
||||||
|
public log(...data: unknown[]): void {
|
||||||
|
if (this.checkBlacklist(data)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let formatter: ChalkInstance | undefined;
|
||||||
|
|
||||||
|
if (data.some(d => typeof d === "string" && d.includes("color:"))) {
|
||||||
|
// Infer the color format from the arguments, then remove everything but the message.
|
||||||
|
formatter = inferColorFormat(data as [string, ...unknown[]]);
|
||||||
|
data.splice(1);
|
||||||
|
} else if (data[0] === "[UI]") {
|
||||||
|
// Cyan for UI debug messages
|
||||||
|
formatter = chalk.hex(UI_MSG_COLOR);
|
||||||
|
} else if (typeof data[0] === "string" && data[0].startsWith("=====")) {
|
||||||
|
// Orange logging for "New Turn"/etc messages
|
||||||
|
formatter = chalk.hex(NEW_TURN_COLOR);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.console.log(...this.format(formatter, data));
|
||||||
|
}
|
||||||
|
|
||||||
|
public warn(...data: unknown[]) {
|
||||||
|
if (this.checkBlacklist(data)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.console.warn(...this.format(chalk.yellow, data));
|
||||||
|
}
|
||||||
|
|
||||||
|
public error(...data: unknown[]) {
|
||||||
|
if (this.checkBlacklist(data)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.console.error(...this.format(chalk.redBright, data));
|
||||||
|
}
|
||||||
|
|
||||||
|
//#endregion Custom Wrappers
|
||||||
|
|
||||||
|
//#region Copy-pasted Console code
|
||||||
|
// TODO: Progressively add proper coloration and support for all these methods
|
||||||
|
public dir(...args: Parameters<(typeof console)["dir"]>): ReturnType<(typeof console)["dir"]> {
|
||||||
|
return this.console.dir(...args);
|
||||||
|
}
|
||||||
|
public dirxml(...args: Parameters<(typeof console)["dirxml"]>): ReturnType<(typeof console)["dirxml"]> {
|
||||||
|
return this.console.dirxml(...args);
|
||||||
|
}
|
||||||
|
public table(...args: Parameters<(typeof console)["table"]>): ReturnType<(typeof console)["table"]> {
|
||||||
|
return this.console.table(...args);
|
||||||
|
}
|
||||||
|
public group(...args: Parameters<(typeof console)["group"]>): ReturnType<(typeof console)["group"]> {
|
||||||
|
return this.console.group(...args);
|
||||||
|
}
|
||||||
|
public groupCollapsed(
|
||||||
|
...args: Parameters<(typeof console)["groupCollapsed"]>
|
||||||
|
): ReturnType<(typeof console)["groupCollapsed"]> {
|
||||||
|
return this.console.groupCollapsed(...args);
|
||||||
|
}
|
||||||
|
public groupEnd(...args: Parameters<(typeof console)["groupEnd"]>): ReturnType<(typeof console)["groupEnd"]> {
|
||||||
|
return this.console.groupEnd(...args);
|
||||||
|
}
|
||||||
|
public clear(...args: Parameters<(typeof console)["clear"]>): ReturnType<(typeof console)["clear"]> {
|
||||||
|
return this.console.clear(...args);
|
||||||
|
}
|
||||||
|
public count(...args: Parameters<(typeof console)["count"]>): ReturnType<(typeof console)["count"]> {
|
||||||
|
return this.console.count(...args);
|
||||||
|
}
|
||||||
|
public countReset(...args: Parameters<(typeof console)["countReset"]>): ReturnType<(typeof console)["countReset"]> {
|
||||||
|
return this.console.countReset(...args);
|
||||||
|
}
|
||||||
|
public assert(...args: Parameters<(typeof console)["assert"]>): ReturnType<(typeof console)["assert"]> {
|
||||||
|
return this.console.assert(...args);
|
||||||
|
}
|
||||||
|
public profile(...args: Parameters<(typeof console)["profile"]>): ReturnType<(typeof console)["profile"]> {
|
||||||
|
return this.console.profile(...args);
|
||||||
|
}
|
||||||
|
public profileEnd(...args: Parameters<(typeof console)["profileEnd"]>): ReturnType<(typeof console)["profileEnd"]> {
|
||||||
|
return this.console.profileEnd(...args);
|
||||||
|
}
|
||||||
|
public time(...args: Parameters<(typeof console)["time"]>): ReturnType<(typeof console)["time"]> {
|
||||||
|
return this.console.time(...args);
|
||||||
|
}
|
||||||
|
public timeLog(...args: Parameters<(typeof console)["timeLog"]>): ReturnType<(typeof console)["timeLog"]> {
|
||||||
|
return this.console.timeLog(...args);
|
||||||
|
}
|
||||||
|
public timeEnd(...args: Parameters<(typeof console)["timeEnd"]>): ReturnType<(typeof console)["timeEnd"]> {
|
||||||
|
return this.console.timeEnd(...args);
|
||||||
|
}
|
||||||
|
public timeStamp(...args: Parameters<(typeof console)["timeStamp"]>): ReturnType<(typeof console)["timeStamp"]> {
|
||||||
|
return this.console.timeStamp(...args);
|
||||||
|
}
|
||||||
|
//#endregion Copy-pasted Console code
|
||||||
|
}
|
@ -1,4 +1,5 @@
|
|||||||
import type { MockGameObject } from "#test/test-utils/mocks/mock-game-object";
|
import type { MockGameObject } from "#test/test-utils/mocks/mock-game-object";
|
||||||
|
import type { TextInterceptor } from "#test/test-utils/text-interceptor";
|
||||||
import { UI } from "#ui/ui";
|
import { UI } from "#ui/ui";
|
||||||
|
|
||||||
export class MockText implements MockGameObject {
|
export class MockText implements MockGameObject {
|
||||||
@ -82,13 +83,14 @@ export class MockText implements MockGameObject {
|
|||||||
|
|
||||||
showText(
|
showText(
|
||||||
text: string,
|
text: string,
|
||||||
delay?: number | null,
|
_delay?: number | null,
|
||||||
callback?: Function | null,
|
callback?: Function | null,
|
||||||
callbackDelay?: number | null,
|
_callbackDelay?: number | null,
|
||||||
prompt?: boolean | null,
|
_prompt?: boolean | null,
|
||||||
promptDelay?: number | null,
|
_promptDelay?: number | null,
|
||||||
) {
|
) {
|
||||||
this.scene.messageWrapper.showText(text, delay, callback, callbackDelay, prompt, promptDelay);
|
// TODO: this is a very bad way to pass calls around
|
||||||
|
(this.scene.messageWrapper as TextInterceptor).showText(text);
|
||||||
if (callback) {
|
if (callback) {
|
||||||
callback();
|
callback();
|
||||||
}
|
}
|
||||||
@ -96,13 +98,13 @@ export class MockText implements MockGameObject {
|
|||||||
|
|
||||||
showDialogue(
|
showDialogue(
|
||||||
keyOrText: string,
|
keyOrText: string,
|
||||||
name: string | undefined,
|
name: string,
|
||||||
delay: number | null = 0,
|
_delay: number | null,
|
||||||
callback: Function,
|
callback: Function,
|
||||||
callbackDelay?: number,
|
_callbackDelay?: number,
|
||||||
promptDelay?: number,
|
_promptDelay?: number,
|
||||||
) {
|
) {
|
||||||
this.scene.messageWrapper.showDialogue(keyOrText, name, delay, callback, callbackDelay, promptDelay);
|
(this.scene.messageWrapper as TextInterceptor).showDialogue(keyOrText, name);
|
||||||
if (callback) {
|
if (callback) {
|
||||||
callback();
|
callback();
|
||||||
}
|
}
|
||||||
|
62
test/test-utils/reporters/custom-default-reporter.ts
Normal file
62
test/test-utils/reporters/custom-default-reporter.ts
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
import { relative } from "node:path";
|
||||||
|
import { parseStacktrace } from "@vitest/utils/source-map";
|
||||||
|
import chalk from "chalk";
|
||||||
|
import type { UserConsoleLog } from "vitest";
|
||||||
|
import type { TestState } from "vitest/node";
|
||||||
|
import { DefaultReporter } from "vitest/reporters";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Custom Vitest reporter to strip the current file names from the output.
|
||||||
|
*/
|
||||||
|
export default class CustomDefaultReporter extends DefaultReporter {
|
||||||
|
public override onUserConsoleLog(log: UserConsoleLog, taskState?: TestState): void {
|
||||||
|
// This code is more or less copied verbatim from `vitest/reporters` source, with minor tweaks to use
|
||||||
|
// dependencies we actually _have_ (i.e. chalk) rather than ones we don't (i.e. tinyrainbow).
|
||||||
|
|
||||||
|
// SPDX-SnippetBegin
|
||||||
|
// SPDX-SnippetCopyrightText: 2021 VoidZero Inc. and Vitest contributors
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
if (!super.shouldLog(log, taskState)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const output = log.type === "stdout" ? this.ctx.logger.outputStream : this.ctx.logger.errorStream;
|
||||||
|
|
||||||
|
const write = (msg: string) => output.write(msg);
|
||||||
|
|
||||||
|
const task = log.taskId ? this.ctx.state.idMap.get(log.taskId) : undefined;
|
||||||
|
|
||||||
|
write(log.content); // this is about the only changed line (that and us skipping a newline)
|
||||||
|
|
||||||
|
if (!log.origin) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Code for stack trace, ripped directly out of Vitest source code.
|
||||||
|
// I wish they had a helper function to do this so we didn't have to import `@vitest/utils`, but oh well...
|
||||||
|
// browser logs don't have an extra end of line at the end like Node.js does
|
||||||
|
if (log.browser) {
|
||||||
|
write("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
const project = task ? this.ctx.getProjectByName(task.file.projectName ?? "") : this.ctx.getRootProject();
|
||||||
|
|
||||||
|
const stack = log.browser ? (project.browser?.parseStacktrace(log.origin) ?? []) : parseStacktrace(log.origin);
|
||||||
|
|
||||||
|
const highlight = task && stack.find(i => i.file === task.file.filepath);
|
||||||
|
|
||||||
|
for (const frame of stack) {
|
||||||
|
const color = frame === highlight ? chalk.cyan : chalk.gray;
|
||||||
|
const path = relative(project.config.root, frame.file);
|
||||||
|
|
||||||
|
const positions = [frame.method, `${path}:${chalk.dim(`${frame.line}:${frame.column}`)}`]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" ");
|
||||||
|
|
||||||
|
write(color(` ${chalk.dim(">")} ${positions}\n`));
|
||||||
|
}
|
||||||
|
|
||||||
|
// SPDX-SnippetEnd
|
||||||
|
}
|
||||||
|
}
|
113
test/test-utils/setup/test-end-log.ts
Normal file
113
test/test-utils/setup/test-end-log.ts
Normal file
@ -0,0 +1,113 @@
|
|||||||
|
// biome-ignore lint/correctness/noUnusedImports: TSDoc
|
||||||
|
import type CustomDefaultReporter from "#test/test-utils/reporters/custom-default-reporter";
|
||||||
|
import { basename, join, relative } from "path";
|
||||||
|
import chalk from "chalk";
|
||||||
|
import type { RunnerTask, RunnerTaskResult, RunnerTestCase } from "vitest";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @module
|
||||||
|
* Code to add markers to the beginning and end of tests.
|
||||||
|
* Intended for use with {@linkcode CustomDefaultReporter}, and placed inside test hooks
|
||||||
|
* (rather than as part of the reporter) to ensure Vitest waits for the log messages to be printed.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** A long string of "="s to partition off each test from one another. */
|
||||||
|
const TEST_END_BARRIER = chalk.bold.hex("#ff7c7cff")("==================");
|
||||||
|
|
||||||
|
// Colors used for Vitest-related test utils
|
||||||
|
const TEST_NAME_COLOR = "#008886ff" as const;
|
||||||
|
const VITEST_PINK_COLOR = "#c162de" as const;
|
||||||
|
|
||||||
|
const testRoot = join(import.meta.dirname, "..", "..", "..");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log the testfile name and path upon a case starting. \
|
||||||
|
* Used to compensate for us overridding the global Console object and removing Vitest's
|
||||||
|
* test name annotations.
|
||||||
|
* @param test - The {@linkcode RunnerTask} passed from the context
|
||||||
|
*/
|
||||||
|
export function logTestStart(test: RunnerTask): void {
|
||||||
|
console.log(TEST_END_BARRIER);
|
||||||
|
console.log(
|
||||||
|
`${chalk.dim("> ")}${chalk.hex(VITEST_PINK_COLOR)("Starting test: ")}${chalk.hex(TEST_NAME_COLOR)(getTestName(test))}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log the testfile name, path and result upon a case ending. \
|
||||||
|
* Used to compensate for us overridding the global Console object and removing Vitest's
|
||||||
|
* test name annotations.
|
||||||
|
* @param task - The {@linkcode RunnerTestCase} passed from the hook
|
||||||
|
*/
|
||||||
|
export function logTestEnd(task: RunnerTestCase): void {
|
||||||
|
const durationStr = getDurationPrefix(task.result);
|
||||||
|
const resultStr = getResultStr(task.result);
|
||||||
|
console.log(`${chalk.dim("> ")}${chalk.black.bgHex(VITEST_PINK_COLOR)(" Test finished! ")}
|
||||||
|
Name: ${chalk.hex(TEST_NAME_COLOR)(getTestName(task))}
|
||||||
|
Result: ${resultStr}${durationStr}
|
||||||
|
File: ${chalk.hex("#d29b0eff")(
|
||||||
|
getPathFromTest(task.file.filepath) + (task.location ? `:${task.location.line}:${task.location.column}` : ""),
|
||||||
|
)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the path of the current test file relative to the `test` directory.
|
||||||
|
* @param abs - The absolute path to the file
|
||||||
|
* @returns The relative path with `test/` appended to it.
|
||||||
|
*/
|
||||||
|
function getPathFromTest(abs: string): string {
|
||||||
|
return join(basename(testRoot), relative(testRoot, abs));
|
||||||
|
}
|
||||||
|
|
||||||
|
function getResultStr(result: RunnerTaskResult | undefined): string {
|
||||||
|
if (result?.state !== "pass" && result?.state !== "fail") {
|
||||||
|
return "Unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
const resultStr =
|
||||||
|
result.state === "pass"
|
||||||
|
? chalk.green.bold("✔ Passed")
|
||||||
|
: (result?.duration ?? 0) > 2
|
||||||
|
? chalk.cyan.bold("◴ Timed out")
|
||||||
|
: chalk.red.bold("✗ Failed");
|
||||||
|
|
||||||
|
return resultStr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the text to be displayed for a test's duration.
|
||||||
|
* @param result - The {@linkcode RunnerTaskResult} of the finished test
|
||||||
|
* @returns An appropriately colored suffix for the start time.
|
||||||
|
* Will return an empty string if `result.startTime` is `undefined`
|
||||||
|
*/
|
||||||
|
function getDurationPrefix(result?: RunnerTaskResult): string {
|
||||||
|
const startTime = result?.startTime;
|
||||||
|
if (!startTime) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
const duration = Math.round(Date.now() - startTime);
|
||||||
|
|
||||||
|
// TODO: Figure out a way to access the current vitest config from a hook
|
||||||
|
const color = duration > 10_000 ? chalk.yellow : chalk.green;
|
||||||
|
return ` ${chalk.dim("in")} ${color(duration)}${chalk.dim("ms")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function copied from vitest source to avoid having to import `@vitest/runner/utils` for 1 function
|
||||||
|
|
||||||
|
// SPDX-SnippetBegin
|
||||||
|
// SPDX-SnippetCopyrightText: 2021 VoidZero Inc. and Vitest contributors
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
function getTestName(task: RunnerTask, separator = " > "): string {
|
||||||
|
const names: string[] = [task.name];
|
||||||
|
let current: RunnerTask | undefined = task;
|
||||||
|
|
||||||
|
while ((current = current?.suite)) {
|
||||||
|
if (current?.name) {
|
||||||
|
names.unshift(current.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return names.join(separator);
|
||||||
|
}
|
||||||
|
|
||||||
|
// SPDX-SnippetEnd
|
@ -3,7 +3,7 @@ import { initializeGame } from "#app/init/init";
|
|||||||
import { initI18n } from "#plugins/i18n";
|
import { initI18n } from "#plugins/i18n";
|
||||||
import { blobToString } from "#test/test-utils/game-manager-utils";
|
import { blobToString } from "#test/test-utils/game-manager-utils";
|
||||||
import { manageListeners } from "#test/test-utils/listeners-manager";
|
import { manageListeners } from "#test/test-utils/listeners-manager";
|
||||||
import { MockConsoleLog } from "#test/test-utils/mocks/mock-console-log";
|
import { MockConsole } from "#test/test-utils/mocks/mock-console/mock-console";
|
||||||
import { mockContext } from "#test/test-utils/mocks/mock-context-canvas";
|
import { mockContext } from "#test/test-utils/mocks/mock-context-canvas";
|
||||||
import { mockLocalStorage } from "#test/test-utils/mocks/mock-local-storage";
|
import { mockLocalStorage } from "#test/test-utils/mocks/mock-local-storage";
|
||||||
import { MockImage } from "#test/test-utils/mocks/mocks-container/mock-image";
|
import { MockImage } from "#test/test-utils/mocks/mocks-container/mock-image";
|
||||||
@ -38,14 +38,22 @@ function initTestFile(): void {
|
|||||||
/**
|
/**
|
||||||
* Setup various stubs for testing.
|
* Setup various stubs for testing.
|
||||||
* @todo Move this into a dedicated stub file instead of running it once per test instance
|
* @todo Move this into a dedicated stub file instead of running it once per test instance
|
||||||
|
* @todo review these to see which are actually necessary
|
||||||
* @todo Investigate why this resets on new test suite start
|
* @todo Investigate why this resets on new test suite start
|
||||||
*/
|
*/
|
||||||
function setupStubs(): void {
|
function setupStubs(): void {
|
||||||
Object.defineProperty(window, "localStorage", {
|
Object.defineProperties(global, {
|
||||||
value: mockLocalStorage(),
|
localStorage: {
|
||||||
});
|
value: mockLocalStorage(),
|
||||||
Object.defineProperty(window, "console", {
|
},
|
||||||
value: new MockConsoleLog(false),
|
console: {
|
||||||
|
value: new MockConsole(),
|
||||||
|
},
|
||||||
|
matchMedia: {
|
||||||
|
value: () => ({
|
||||||
|
matches: false,
|
||||||
|
}),
|
||||||
|
},
|
||||||
});
|
});
|
||||||
Object.defineProperty(document, "fonts", {
|
Object.defineProperty(document, "fonts", {
|
||||||
writable: true,
|
writable: true,
|
||||||
@ -69,11 +77,6 @@ function setupStubs(): void {
|
|||||||
navigator.getGamepads = () => [];
|
navigator.getGamepads = () => [];
|
||||||
setCookie(SESSION_ID_COOKIE_NAME, "fake_token");
|
setCookie(SESSION_ID_COOKIE_NAME, "fake_token");
|
||||||
|
|
||||||
window.matchMedia = () =>
|
|
||||||
({
|
|
||||||
matches: false,
|
|
||||||
}) as any;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets this object's position relative to another object with a given offset
|
* Sets this object's position relative to another object with a given offset
|
||||||
* @param guideObject - The {@linkcode Phaser.GameObjects.GameObject} to base the position off of
|
* @param guideObject - The {@linkcode Phaser.GameObjects.GameObject} to base the position off of
|
||||||
|
@ -1,39 +1,49 @@
|
|||||||
|
import type { BattleScene } from "#app/battle-scene";
|
||||||
|
import chalk from "chalk";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class will intercept any text or dialogue message calls and log them for test purposes
|
* The {@linkcode TextInterceptor} is a wrapper class that intercepts and logs any messages
|
||||||
|
* that would be displayed on-screen.
|
||||||
*/
|
*/
|
||||||
export class TextInterceptor {
|
export class TextInterceptor {
|
||||||
private scene;
|
/** A log containing messages having been displayed on screen, sorted in FIFO order. */
|
||||||
public logs: string[] = [];
|
public readonly logs: string[] = [];
|
||||||
constructor(scene) {
|
|
||||||
this.scene = scene;
|
constructor(scene: BattleScene) {
|
||||||
|
// @ts-expect-error: Find another more sanitary way of doing this
|
||||||
scene.messageWrapper = this;
|
scene.messageWrapper = this;
|
||||||
}
|
}
|
||||||
|
|
||||||
showText(
|
/** Clear the current content of the TextInterceptor. */
|
||||||
text: string,
|
public clearLogs(): void {
|
||||||
_delay?: number,
|
this.logs.splice(0);
|
||||||
_callback?: Function,
|
}
|
||||||
_callbackDelay?: number,
|
|
||||||
_prompt?: boolean,
|
showText(text: string): void {
|
||||||
_promptDelay?: number,
|
// NB: We do not format the raw _logs_ themselves as tests will be actively checking it.
|
||||||
): void {
|
console.log(this.formatText(text));
|
||||||
console.log(text);
|
|
||||||
this.logs.push(text);
|
this.logs.push(text);
|
||||||
}
|
}
|
||||||
|
|
||||||
showDialogue(
|
showDialogue(text: string, name: string): void {
|
||||||
text: string,
|
console.log(`${name}: \n${this.formatText(text)}`);
|
||||||
name: string,
|
|
||||||
_delay?: number,
|
|
||||||
_callback?: Function,
|
|
||||||
_callbackDelay?: number,
|
|
||||||
_promptDelay?: number,
|
|
||||||
): void {
|
|
||||||
console.log(name, text);
|
|
||||||
this.logs.push(name, text);
|
this.logs.push(name, text);
|
||||||
}
|
}
|
||||||
|
|
||||||
getLatestMessage(): string {
|
/**
|
||||||
return this.logs.pop() ?? "";
|
* Format text to be displayed to the test console, as follows:
|
||||||
|
* 1. Replaces new lines and new text boxes (marked by `$`) with indented new lines.
|
||||||
|
* 2. Removes all `@c{}`, `@d{}`, `@s{}`, and `@f{}` flags from the text.
|
||||||
|
* 3. Makes text blue
|
||||||
|
* @param text - The unformatted text
|
||||||
|
* @returns The formatted text
|
||||||
|
*/
|
||||||
|
private formatText(text: string): string {
|
||||||
|
return chalk.blue(
|
||||||
|
text
|
||||||
|
.replace(/\n/g, " ")
|
||||||
|
.replace(/\$/g, "\n ")
|
||||||
|
.replace(/@\w{.*?}/g, ""),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,16 +1,21 @@
|
|||||||
import "vitest-canvas-mock";
|
import "vitest-canvas-mock";
|
||||||
|
import { MockConsole } from "#test/test-utils/mocks/mock-console/mock-console";
|
||||||
|
import { logTestEnd, logTestStart } from "#test/test-utils/setup/test-end-log";
|
||||||
import { initTests } from "#test/test-utils/test-file-initialization";
|
import { initTests } from "#test/test-utils/test-file-initialization";
|
||||||
import { afterAll, beforeAll, vi } from "vitest";
|
import chalk from "chalk";
|
||||||
|
import { afterAll, afterEach, beforeAll, beforeEach, vi } from "vitest";
|
||||||
|
|
||||||
/** Set the timezone to UTC for tests. */
|
//#region Mocking
|
||||||
|
|
||||||
/** Mock the override import to always return default values, ignoring any custom overrides. */
|
// Mock the override import to always return default values, ignoring any custom overrides.
|
||||||
vi.mock("#app/overrides", async importOriginal => {
|
vi.mock(import("#app/overrides"), async importOriginal => {
|
||||||
const { defaultOverrides } = await importOriginal<typeof import("#app/overrides")>();
|
const { defaultOverrides } = await importOriginal();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
default: defaultOverrides,
|
default: defaultOverrides,
|
||||||
defaultOverrides,
|
// Export `defaultOverrides` as a *copy*.
|
||||||
|
// This ensures we can easily reset `overrides` back to its default values after modifying it.
|
||||||
|
defaultOverrides: { ...defaultOverrides },
|
||||||
} satisfies typeof import("#app/overrides");
|
} satisfies typeof import("#app/overrides");
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -20,7 +25,7 @@ vi.mock("#app/overrides", async importOriginal => {
|
|||||||
* This is necessary because how our code is structured.
|
* This is necessary because how our code is structured.
|
||||||
* Do NOT try to put any of this code into external functions, it won't work as it's elevated during runtime.
|
* Do NOT try to put any of this code into external functions, it won't work as it's elevated during runtime.
|
||||||
*/
|
*/
|
||||||
vi.mock("i18next", async importOriginal => {
|
vi.mock(import("i18next"), async importOriginal => {
|
||||||
console.log("Mocking i18next");
|
console.log("Mocking i18next");
|
||||||
const { setupServer } = await import("msw/node");
|
const { setupServer } = await import("msw/node");
|
||||||
const { http, HttpResponse } = await import("msw");
|
const { http, HttpResponse } = await import("msw");
|
||||||
@ -30,8 +35,11 @@ vi.mock("i18next", async importOriginal => {
|
|||||||
const filename = req.params[0];
|
const filename = req.params[0];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const json = await import(`../public/locales/en/${req.params[0]}`);
|
const localeFiles = import.meta.glob("../public/locales/en/**/*.json", { eager: true });
|
||||||
console.log("Loaded locale", filename);
|
const json = localeFiles[`../public/locales/en/${filename}`] || {};
|
||||||
|
if (import.meta.env.VITE_I18N_DEBUG === "1") {
|
||||||
|
console.log("Loaded locale", filename);
|
||||||
|
}
|
||||||
return HttpResponse.json(json);
|
return HttpResponse.json(json);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(`Failed to load locale ${filename}!`, err);
|
console.log(`Failed to load locale ${filename}!`, err);
|
||||||
@ -54,7 +62,15 @@ beforeAll(() => {
|
|||||||
initTests();
|
initTests();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
beforeEach(context => {
|
||||||
|
logTestStart(context.task);
|
||||||
|
});
|
||||||
|
afterEach(context => {
|
||||||
|
logTestEnd(context.task);
|
||||||
|
});
|
||||||
|
|
||||||
afterAll(() => {
|
afterAll(() => {
|
||||||
global.server.close();
|
global.server.close();
|
||||||
console.log("Closing i18n MSW server!");
|
MockConsole.printPostTestWarnings();
|
||||||
|
console.log(chalk.hex("#dfb8d8")("Closing i18n MSW server!"));
|
||||||
});
|
});
|
||||||
|
@ -18,47 +18,47 @@
|
|||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"strictNullChecks": true,
|
"strictNullChecks": true,
|
||||||
"sourceMap": false,
|
"sourceMap": false,
|
||||||
"checkJs": true,
|
|
||||||
"strict": false, // TODO: Enable this eventually
|
"strict": false, // TODO: Enable this eventually
|
||||||
"rootDir": ".",
|
"rootDir": ".",
|
||||||
"baseUrl": "./src",
|
|
||||||
"paths": {
|
|
||||||
"#abilities/*": ["./data/abilities/*.ts"],
|
|
||||||
"#api/*": ["./plugins/api/*.ts"],
|
|
||||||
"#balance/*": ["./data/balance/*.ts"],
|
|
||||||
"#enums/*": ["./enums/*.ts"],
|
|
||||||
"#events/*": ["./events/*.ts"],
|
|
||||||
"#field/*": ["./field/*.ts"],
|
|
||||||
"#inputs/*": ["./configs/inputs/*.ts"],
|
|
||||||
"#modifiers/*": ["./modifier/*.ts"],
|
|
||||||
"#moves/*": ["./data/moves/*.ts"],
|
|
||||||
"#mystery-encounters/*": [
|
|
||||||
"./data/mystery-encounters/utils/*.ts",
|
|
||||||
"./data/mystery-encounters/encounters/*.ts",
|
|
||||||
"./data/mystery-encounters/requirements/*.ts",
|
|
||||||
"./data/mystery-encounters/*.ts"
|
|
||||||
],
|
|
||||||
"#package.json": ["../package.json"],
|
|
||||||
"#phases/*": ["./phases/*.ts"],
|
|
||||||
"#plugins/*": ["./plugins/vite/*.ts", "./plugins/*.ts"],
|
|
||||||
"#sprites/*": ["./sprites/*.ts"],
|
|
||||||
"#system/*": [
|
|
||||||
"./system/settings/*.ts",
|
|
||||||
"./system/version-migration/versions/*.ts",
|
|
||||||
"./system/version-migration/*.ts",
|
|
||||||
"./system/*.ts"
|
|
||||||
],
|
|
||||||
"#trainers/*": ["./data/trainers/*.ts"],
|
|
||||||
"#types/*": ["./@types/helpers/*.ts", "./@types/*.ts", "./typings/phaser/*.ts"],
|
|
||||||
"#ui/*": ["./ui/battle-info/*.ts", "./ui/settings/*.ts", "./ui/*.ts"],
|
|
||||||
"#utils/*": ["./utils/*.ts"],
|
|
||||||
"#data/*": ["./data/pokemon-forms/*.ts", "./data/pokemon/*.ts", "./data/*.ts"],
|
|
||||||
"#test/*": ["../test/*.ts"],
|
|
||||||
"#app/*": ["*.ts"]
|
|
||||||
},
|
|
||||||
"outDir": "./build",
|
"outDir": "./build",
|
||||||
"noEmit": true
|
"noEmit": true,
|
||||||
|
"paths": {
|
||||||
|
"#abilities/*": ["./src/data/abilities/*.ts"],
|
||||||
|
"#api/*": ["./src/plugins/api/*.ts"],
|
||||||
|
"#balance/*": ["./src/data/balance/*.ts"],
|
||||||
|
"#enums/*": ["./src/enums/*.ts"],
|
||||||
|
"#events/*": ["./src/events/*.ts"],
|
||||||
|
"#field/*": ["./src/field/*.ts"],
|
||||||
|
"#inputs/*": ["./src/configs/inputs/*.ts"],
|
||||||
|
"#modifiers/*": ["./src/modifier/*.ts"],
|
||||||
|
"#moves/*": ["./src/data/moves/*.ts"],
|
||||||
|
"#mystery-encounters/*": [
|
||||||
|
"./src/data/mystery-encounters/utils/*.ts",
|
||||||
|
"./src/data/mystery-encounters/encounters/*.ts",
|
||||||
|
"./src/data/mystery-encounters/requirements/*.ts",
|
||||||
|
"./src/data/mystery-encounters/*.ts"
|
||||||
|
],
|
||||||
|
"#package.json": ["./package.json"],
|
||||||
|
"#phases/*": ["./src/phases/*.ts"],
|
||||||
|
"#plugins/*": ["./src/plugins/vite/*.ts", "./src/plugins/*.ts"],
|
||||||
|
"#sprites/*": ["./src/sprites/*.ts"],
|
||||||
|
"#system/*": [
|
||||||
|
"./src/system/settings/*.ts",
|
||||||
|
"./src/system/version-migration/versions/*.ts",
|
||||||
|
"./src/system/version-migration/*.ts",
|
||||||
|
"./src/system/*.ts"
|
||||||
|
],
|
||||||
|
"#trainers/*": ["./src/data/trainers/*.ts"],
|
||||||
|
"#types/*": ["./src/@types/helpers/*.ts", "./src/@types/*.ts", "./src/typings/phaser/*.ts"],
|
||||||
|
"#ui/*": ["./src/ui/battle-info/*.ts", "./src/ui/settings/*.ts", "./src/ui/*.ts"],
|
||||||
|
"#utils/*": ["./src/utils/*.ts"],
|
||||||
|
"#data/*": ["./src/data/pokemon-forms/*.ts", "./src/data/pokemon/*.ts", "./src/data/*.ts"],
|
||||||
|
"#test/*": ["./test/*.ts"],
|
||||||
|
"#app/*": ["./src/*.ts"]
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
// Exclude checking for script JS files as those are covered by the folder's `jsconfig.json`
|
||||||
|
"include": ["**/*.ts", "**/*.d.ts"],
|
||||||
"exclude": [
|
"exclude": [
|
||||||
"node_modules",
|
"node_modules",
|
||||||
"dist",
|
"dist",
|
||||||
|
@ -19,15 +19,10 @@ export function load(app) {
|
|||||||
app.renderer.on(Renderer.EVENT_END_PAGE, page => {
|
app.renderer.on(Renderer.EVENT_END_PAGE, page => {
|
||||||
if (page.pageKind === PageKind.Index && page.contents) {
|
if (page.pageKind === PageKind.Index && page.contents) {
|
||||||
page.contents = page.contents
|
page.contents = page.contents
|
||||||
// Replace links to the beta documentation site with the current ref name
|
// Replace the SVG to the beta documentation site with the current ref name
|
||||||
.replace(
|
.replace(
|
||||||
/href="(.*pagefaultgames.github.io\/pokerogue\/).*?"/, // formatting
|
/^<a href="(.*?)\/beta(.*?)"><img src=".*coverage.svg"/m, // formatting
|
||||||
`href="$1/${process.env.REF_NAME}"`,
|
`<a href="$1/${process.env.REF_NAME}$2"><img src="coverage.svg"`,
|
||||||
)
|
|
||||||
// Replace the link to Beta's coverage SVG with the SVG file for the branch in question.
|
|
||||||
.replace(
|
|
||||||
/img src=".*?coverage.svg/, // formatting
|
|
||||||
`img src="coverage.svg"`,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
@ -8,7 +8,13 @@ const dryRun = !!process.env.DRY_RUN?.match(/true/gi);
|
|||||||
const config = {
|
const config = {
|
||||||
entryPoints: ["./src", "./test/test-utils"],
|
entryPoints: ["./src", "./test/test-utils"],
|
||||||
entryPointStrategy: "expand",
|
entryPointStrategy: "expand",
|
||||||
exclude: ["**/*+.test.ts", "src/polyfills.ts", "src/vite.env.d.ts"],
|
exclude: [
|
||||||
|
"src/polyfills.ts",
|
||||||
|
"src/vite.env.d.ts",
|
||||||
|
"**/*+.test.ts",
|
||||||
|
"test/test-utils/setup",
|
||||||
|
"test/test-utils/reporters",
|
||||||
|
],
|
||||||
excludeReferences: true, // prevent documenting re-exports
|
excludeReferences: true, // prevent documenting re-exports
|
||||||
requiredToBeDocumented: [
|
requiredToBeDocumented: [
|
||||||
"Enum",
|
"Enum",
|
||||||
|
@ -1,18 +1,25 @@
|
|||||||
import { defineProject } from "vitest/config";
|
import { defineConfig } from "vitest/config";
|
||||||
import { BaseSequencer, type TestSpecification } from "vitest/node";
|
import { BaseSequencer, type TestSpecification } from "vitest/node";
|
||||||
import { defaultConfig } from "./vite.config";
|
import { defaultConfig } from "./vite.config";
|
||||||
|
|
||||||
export default defineProject(({ mode }) => ({
|
export default defineConfig(({ mode }) => ({
|
||||||
...defaultConfig,
|
...defaultConfig,
|
||||||
test: {
|
test: {
|
||||||
|
reporters: process.env.GITHUB_ACTIONS
|
||||||
|
? ["github-actions", "./test/test-utils/reporters/custom-default-reporter.ts"]
|
||||||
|
: ["./test/test-utils/reporters/custom-default-reporter.ts"],
|
||||||
env: {
|
env: {
|
||||||
TZ: "UTC",
|
TZ: "UTC",
|
||||||
},
|
},
|
||||||
testTimeout: 20000,
|
testTimeout: 20_000,
|
||||||
|
slowTestThreshold: 10_000,
|
||||||
|
// TODO: Consider enabling
|
||||||
|
// expect: {requireAssertions: true},
|
||||||
setupFiles: ["./test/font-face.setup.ts", "./test/vitest.setup.ts", "./test/matchers.setup.ts"],
|
setupFiles: ["./test/font-face.setup.ts", "./test/vitest.setup.ts", "./test/matchers.setup.ts"],
|
||||||
sequence: {
|
sequence: {
|
||||||
sequencer: MySequencer,
|
sequencer: MySequencer,
|
||||||
},
|
},
|
||||||
|
includeTaskLocation: true,
|
||||||
environment: "jsdom" as const,
|
environment: "jsdom" as const,
|
||||||
environmentOptions: {
|
environmentOptions: {
|
||||||
jsdom: {
|
jsdom: {
|
||||||
|
Loading…
Reference in New Issue
Block a user