diff --git a/scripts/.eslintrc.js b/scripts/.eslintrc.js index 1de7cbccd..ac57cfcac 100644 --- a/scripts/.eslintrc.js +++ b/scripts/.eslintrc.js @@ -1,366 +1,434 @@ +const numSpaces = 4; +const maxLineLength = 160; + module.exports = { - env: { - node: true, - es6: true, - }, - extends: "eslint:recommended", - parserOptions: { - ecmaVersion: 8, - sourceType: "module", - ecmaFeatures: { - experimentalObjectRestSpread: true, + "env": { + "es6": true, + "node": true }, - }, - rules: { - "accessor-pairs": [ - "error", - { - setWithoutGet: true, - getWithoutSet: false, - }, - ], - "array-bracket-newline": ["error"], - "array-bracket-spacing": ["error"], - "array-callback-return": ["error"], - "array-element-newline": ["error"], - "arrow-body-style": ["error"], - "arrow-parens": ["error"], - "arrow-spacing": ["error"], - "block-scoped-var": ["error"], - "block-spacing": ["error"], - "brace-style": ["error"], - "callback-return": ["error"], - camelcase: ["error"], - "capitalized-comments": ["error"], - "class-methods-use-this": ["error"], - "comma-dangle": ["error"], - "comma-spacing": ["error"], - "comma-style": ["error", "last"], - complexity: ["error"], - "computed-property-spacing": ["error", "never"], - "consistent-return": ["error"], - "consistent-this": ["error"], - "constructor-super": ["error"], - curly: ["error"], - "default-case": ["error"], - "dot-location": ["error", "property"], - "dot-notation": ["error"], - "eol-last": ["error"], - eqeqeq: ["error"], - "for-direction": ["error"], - "func-call-spacing": ["error"], - "func-name-matching": ["error"], - "func-names": ["error", "never"], - "func-style": ["error"], - "function-paren-newline": ["error"], - "generator-star-spacing": ["error", "before"], - "getter-return": [ - "error", - { - allowImplicit: false, - }, - ], - "global-require": ["error"], - "guard-for-in": ["error"], - "handle-callback-err": ["error"], - "id-blacklist": ["error"], - "id-length": ["error"], - "id-match": ["error"], - "implicit-arrow-linebreak": ["error", "beside"], - indent: [ - "error", - 4, - { - SwitchCase: 1, - }, - ], - "init-declarations": ["error"], - "jsx-quotes": ["error"], - "key-spacing": ["error"], - "keyword-spacing": ["error"], - "line-comment-position": ["error"], - "linebreak-style": ["error", "windows"], - "lines-around-comment": ["error"], - "lines-between-class-members": ["error"], - "max-depth": ["error"], - "max-len": ["error", 160], - "max-lines": [ - "error", - { - skipBlankLines: true, - skipComments: true, - }, - ], - "max-nested-callbacks": ["error"], - "max-params": ["error"], - "max-statements": ["error"], - "max-statements-per-line": ["error"], - "multiline-comment-style": ["off", "starred-block"], - "multiline-ternary": ["error", "never"], - "new-cap": ["error"], - "new-parens": ["error"], - "newline-before-return": [ - "error", // TODO: configure this... - ], - "newline-per-chained-call": ["error"], - "no-alert": ["error"], - "no-array-constructor": ["error"], - "no-await-in-loop": ["error"], - "no-bitwise": ["error"], - "no-buffer-constructor": ["error"], - "no-caller": ["error"], - "no-case-declarations": ["error"], - "no-catch-shadow": ["error"], - "no-class-assign": ["error"], - "no-compare-neg-zero": ["error"], - "no-cond-assign": ["error", "except-parens"], - "no-confusing-arrow": ["error"], - "no-console": ["error"], - "no-const-assign": ["error"], - "no-constant-condition": [ - "error", - { - checkLoops: false, - }, - ], - "no-continue": ["off"], - "no-control-regex": ["error"], - "no-debugger": ["error"], - "no-delete-var": ["error"], - "no-div-regex": ["error"], - "no-dupe-args": ["error"], - "no-dupe-class-members": ["error"], - "no-dupe-keys": ["error"], - "no-duplicate-case": ["error"], - "no-duplicate-imports": [ - "error", - { - includeExports: true, - }, - ], - "no-else-return": ["error"], - "no-empty": [ - "error", - { - allowEmptyCatch: false, - }, - ], - "no-empty-character-class": ["error"], - "no-empty-function": ["error"], - "no-empty-pattern": ["error"], - "no-eq-null": ["error"], - "no-ex-assign": ["error"], - "no-extra-boolean-cast": ["error"], - "no-extra-parens": [ - "error", - "all", - { - conditionalAssign: false, - }, - ], - "no-extra-semi": ["error"], - "no-eval": ["error"], - "no-extend-native": ["error"], - "no-extra-bind": ["error"], - "no-extra-label": ["error"], - "no-extra-parens": ["error"], - "no-fallthrough": ["error"], - "no-floating-decimal": ["error"], - "no-func-assign": ["error"], - "no-global-assign": ["error"], - "no-implicit-coercion": ["error"], - "no-implicit-globals": ["error"], - "no-implied-eval": ["error"], - "no-inline-comments": ["error"], - "no-inner-declarations": ["error", "both"], - "no-invalid-regexp": ["error"], - "no-invalid-this": ["error"], - "no-irregular-whitespace": [ - "error", - { - skipStrings: false, - skipComments: false, - skipRegExps: false, - skipTemplates: false, - }, - ], - "no-iterator": ["error"], - "no-label-var": ["error"], - "no-labels": ["error"], - "no-lone-blocks": ["error"], - "no-lonely-if": ["error"], - "no-loop-func": ["error"], - "no-magic-numbers": [ - "error", - { - ignore: [-1, 0, 1], - ignoreArrayIndexes: true, - }, - ], - "no-mixed-operators": ["error"], - "no-mixed-requires": ["error"], - "no-mixed-spaces-and-tabs": ["error"], - "no-multi-assign": ["error"], - "no-multi-spaces": ["error"], - "no-multi-str": ["error"], - "no-multiple-empty-lines": [ - "error", - { - max: 1, - }, - ], - "no-native-reassign": ["error"], - "no-negated-condition": ["error"], - "no-negated-in-lhs": ["error"], - "no-nested-ternary": ["error"], - "no-new": ["error"], - "no-new-func": ["error"], - "no-new-object": ["error"], - "no-new-require": ["error"], - "no-new-symbol": ["error"], - "no-new-wrappers": ["error"], - "no-octal": ["error"], - "no-octal-escape": ["error"], - "no-obj-calls": ["error"], - "no-param-reassign": ["error"], - "no-path-concat": ["error"], - "no-plusplus": [ - "error", - { - allowForLoopAfterthoughts: true, - }, - ], - "no-process-env": ["error"], - "no-process-exit": ["error"], - "no-proto": ["error"], - "no-prototype-builtins": ["error"], - "no-redeclare": ["error"], - "no-regex-spaces": ["error"], - "no-restricted-globals": ["error"], - "no-restricted-imports": ["error"], - "no-restricted-modules": ["error"], - "no-restricted-properties": [ - "error", - { - object: "console", - property: "log", - message: "'log' is too general, use an appropriate level when logging.", - }, - ], - "no-restricted-syntax": ["error"], - "no-return-assign": ["error"], - "no-return-await": ["error"], - "no-script-url": ["error"], - "no-self-assign": [ - "error", - { - props: false, - }, - ], - "no-self-compare": ["error"], - "no-sequences": ["error"], - "no-shadow": ["error"], - "no-shadow-restricted-names": ["error"], - "no-spaced-func": ["error"], - "no-sparse-arrays": ["error"], - "no-sync": ["error"], - "no-tabs": ["error"], - "no-template-curly-in-string": ["error"], - "no-ternary": ["off"], - "no-this-before-super": ["error"], - "no-throw-literal": ["error"], - "no-trailing-spaces": ["error"], - "no-undef": ["error"], - "no-undef-init": ["error"], - "no-undefined": ["error"], - "no-underscore-dangle": ["error"], - "no-unexpected-multiline": ["error"], - "no-unmodified-loop-condition": ["error"], - "no-unneeded-ternary": ["error"], - "no-unreachable": ["error"], - "no-unsafe-finally": ["error"], - "no-unsafe-negation": ["error"], - "no-unused-expressions": ["error"], - "no-unused-labels": ["error"], - "no-unused-vars": ["error"], - "no-use-before-define": ["error"], - "no-useless-call": ["error"], - "no-useless-computed-key": ["error"], - "no-useless-concat": ["error"], - "no-useless-constructor": ["error"], - "no-useless-escape": ["error"], - "no-useless-rename": [ - "error", - { - ignoreDestructuring: false, - ignoreExport: false, - ignoreImport: false, - }, - ], - "no-useless-return": ["error"], - "no-var": ["error"], - "no-void": ["error"], - "no-warning-comments": ["error"], - "no-whitespace-before-property": ["error"], - "no-with": ["error"], - "nonblock-statement-body-position": ["error", "below"], - "object-curly-newline": ["error"], - "object-curly-spacing": ["error"], - "object-property-newline": ["error"], - "object-shorthand": ["error"], - "one-var": ["off"], - "one-var-declaration-per-line": ["error"], - "operator-assignment": ["error"], - "operator-linebreak": ["error", "none"], - "padded-blocks": ["off"], - "padding-line-between-statements": ["error"], - "prefer-arrow-callback": ["error"], - "prefer-const": ["error"], - "prefer-destructuring": ["off"], - "prefer-numeric-literals": ["error"], - "prefer-promise-reject-errors": ["off"], - "prefer-reflect": ["error"], - "prefer-rest-params": ["error"], - "prefer-spread": ["error"], - "prefer-template": ["error"], - "quote-props": ["error"], - quotes: ["error"], - radix: ["error", "as-needed"], - "require-await": ["error"], - "require-jsdoc": ["off"], - "require-yield": ["error"], - "rest-spread-spacing": ["error", "never"], - semi: ["error"], - "semi-spacing": ["error"], - "semi-style": ["error", "last"], - "sort-imports": ["error"], - "sort-keys": ["error"], - "sort-vars": ["error"], - "space-before-blocks": ["error"], - "space-before-function-paren": ["off"], - "space-in-parens": ["error"], - "space-infix-ops": ["error"], - "space-unary-ops": ["error"], - "spaced-comment": ["error"], - strict: ["error"], - "switch-colon-spacing": [ - "error", - { - after: true, - before: false, - }, - ], - "symbol-description": ["error"], - "template-curly-spacing": ["error"], - "template-tag-spacing": ["error"], - "unicode-bom": ["error", "never"], - "use-isnan": ["error"], - "valid-jsdoc": ["error"], - "valid-typeof": ["error"], - "vars-on-top": ["error"], - "wrap-iife": ["error", "any"], - "wrap-regex": ["error"], - "yield-star-spacing": ["error", "before"], - yoda: ["error", "never"], - }, + "extends": "eslint:recommended", + "parserOptions": { + "ecmaFeatures": { + "experimentalObjectRestSpread": true + }, + "ecmaVersion": 8, + "sourceType": "module" + }, + "rules": { + "accessor-pairs": [ + "error", + { + "getWithoutSet": false, + "setWithoutGet": true + } + ], + "array-bracket-newline": ["error"], + "array-bracket-spacing": ["error"], + "array-callback-return": ["error"], + "array-element-newline": ["error"], + "arrow-body-style": ["error"], + "arrow-parens": ["error"], + "arrow-spacing": ["error"], + "block-scoped-var": ["error"], + "block-spacing": ["error"], + "brace-style": ["error"], + "callback-return": ["error"], + "camelcase": ["error"], + "capitalized-comments": ["error"], + "class-methods-use-this": ["error"], + "comma-dangle": ["error"], + "comma-spacing": ["error"], + "comma-style": [ + "error", + "last" + ], + "complexity": ["error"], + "computed-property-spacing": [ + "error", + "never" + ], + "consistent-return": ["error"], + "consistent-this": ["error"], + "constructor-super": ["error"], + "curly": ["error"], + "default-case": ["error"], + "dot-location": [ + "error", + "property" + ], + "dot-notation": ["error"], + "eol-last": ["error"], + "eqeqeq": ["error"], + "for-direction": ["error"], + "func-call-spacing": ["error"], + "func-name-matching": ["error"], + "func-names": [ + "error", + "never" + ], + "func-style": ["error"], + "function-paren-newline": ["error"], + "generator-star-spacing": [ + "error", + "before" + ], + "getter-return": [ + "error", + { + "allowImplicit": false + } + ], + "global-require": ["error"], + "guard-for-in": ["error"], + "handle-callback-err": ["error"], + "id-blacklist": ["error"], + "id-length": ["error"], + "id-match": ["error"], + "implicit-arrow-linebreak": [ + "error", + "beside" + ], + "indent": [ + "error", + numSpaces, + { + "SwitchCase": 1 + } + ], + "init-declarations": ["error"], + "jsx-quotes": ["error"], + "key-spacing": ["error"], + "keyword-spacing": ["error"], + "line-comment-position": ["error"], + "linebreak-style": [ + "error", + "windows" + ], + "lines-around-comment": ["error"], + "lines-between-class-members": ["error"], + "max-depth": ["error"], + "max-len": [ + "error", + maxLineLength + ], + "max-lines": [ + "error", + { + "skipBlankLines": true, + "skipComments": true + } + ], + "max-nested-callbacks": ["error"], + "max-params": ["error"], + "max-statements": ["error"], + "max-statements-per-line": ["error"], + "multiline-comment-style": [ + "off", + "starred-block" + ], + "multiline-ternary": [ + "error", + "never" + ], + "new-cap": ["error"], + "new-parens": ["error"], + // TODO: configure this... + "newline-before-return": ["error"], + "newline-per-chained-call": ["error"], + "no-alert": ["error"], + "no-array-constructor": ["error"], + "no-await-in-loop": ["error"], + "no-bitwise": ["error"], + "no-buffer-constructor": ["error"], + "no-caller": ["error"], + "no-case-declarations": ["error"], + "no-catch-shadow": ["error"], + "no-class-assign": ["error"], + "no-compare-neg-zero": ["error"], + "no-cond-assign": [ + "error", + "except-parens" + ], + "no-confusing-arrow": ["error"], + "no-console": ["error"], + "no-const-assign": ["error"], + "no-constant-condition": [ + "error", + { + "checkLoops": false + } + ], + "no-continue": ["off"], + "no-control-regex": ["error"], + "no-debugger": ["error"], + "no-delete-var": ["error"], + "no-div-regex": ["error"], + "no-dupe-args": ["error"], + "no-dupe-class-members": ["error"], + "no-dupe-keys": ["error"], + "no-duplicate-case": ["error"], + "no-duplicate-imports": [ + "error", + { + "includeExports": true + } + ], + "no-else-return": ["error"], + "no-empty": [ + "error", + { + "allowEmptyCatch": false + } + ], + "no-empty-character-class": ["error"], + "no-empty-function": ["error"], + "no-empty-pattern": ["error"], + "no-eq-null": ["error"], + "no-eval": ["error"], + "no-ex-assign": ["error"], + "no-extend-native": ["error"], + "no-extra-bind": ["error"], + "no-extra-boolean-cast": ["error"], + "no-extra-label": ["error"], + "no-extra-parens": [ + "error", + "all", + { + "conditionalAssign": false + } + ], + "no-extra-semi": ["error"], + "no-fallthrough": ["error"], + "no-floating-decimal": ["error"], + "no-func-assign": ["error"], + "no-global-assign": ["error"], + "no-implicit-coercion": ["error"], + "no-implicit-globals": ["error"], + "no-implied-eval": ["error"], + "no-inline-comments": ["error"], + "no-inner-declarations": [ + "error", + "both" + ], + "no-invalid-regexp": ["error"], + "no-invalid-this": ["error"], + "no-irregular-whitespace": [ + "error", + { + "skipComments": false, + "skipRegExps": false, + "skipStrings": false, + "skipTemplates": false + } + ], + "no-iterator": ["error"], + "no-label-var": ["error"], + "no-labels": ["error"], + "no-lone-blocks": ["error"], + "no-lonely-if": ["error"], + "no-loop-func": ["error"], + "no-magic-numbers": [ + "error", + { + "ignore": [ + -1, + 0, + 1 + ], + "ignoreArrayIndexes": true + } + ], + "no-mixed-operators": ["error"], + "no-mixed-requires": ["error"], + "no-mixed-spaces-and-tabs": ["error"], + "no-multi-assign": ["error"], + "no-multi-spaces": ["error"], + "no-multi-str": ["error"], + "no-multiple-empty-lines": [ + "error", + { + "max": 1 + } + ], + "no-native-reassign": ["error"], + "no-negated-condition": ["error"], + "no-negated-in-lhs": ["error"], + "no-nested-ternary": ["error"], + "no-new": ["error"], + "no-new-func": ["error"], + "no-new-object": ["error"], + "no-new-require": ["error"], + "no-new-symbol": ["error"], + "no-new-wrappers": ["error"], + "no-obj-calls": ["error"], + "no-octal": ["error"], + "no-octal-escape": ["error"], + "no-param-reassign": ["error"], + "no-path-concat": ["error"], + "no-plusplus": [ + "error", + { + "allowForLoopAfterthoughts": true + } + ], + "no-process-env": ["error"], + "no-process-exit": ["error"], + "no-proto": ["error"], + "no-prototype-builtins": ["error"], + "no-redeclare": ["error"], + "no-regex-spaces": ["error"], + "no-restricted-globals": ["error"], + "no-restricted-imports": ["error"], + "no-restricted-modules": ["error"], + "no-restricted-properties": [ + "error", + { + "message": "'log' is too general, use an appropriate level when logging.", + "object": "console", + "property": "log" + } + ], + "no-restricted-syntax": ["error"], + "no-return-assign": ["error"], + "no-return-await": ["error"], + "no-script-url": ["error"], + "no-self-assign": [ + "error", + { + "props": false + } + ], + "no-self-compare": ["error"], + "no-sequences": ["error"], + "no-shadow": ["error"], + "no-shadow-restricted-names": ["error"], + "no-spaced-func": ["error"], + "no-sparse-arrays": ["error"], + "no-sync": ["error"], + "no-tabs": ["error"], + "no-template-curly-in-string": ["error"], + "no-ternary": ["off"], + "no-this-before-super": ["error"], + "no-throw-literal": ["error"], + "no-trailing-spaces": ["error"], + "no-undef": ["error"], + "no-undef-init": ["error"], + "no-undefined": ["error"], + "no-underscore-dangle": ["error"], + "no-unexpected-multiline": ["error"], + "no-unmodified-loop-condition": ["error"], + "no-unneeded-ternary": ["error"], + "no-unreachable": ["error"], + "no-unsafe-finally": ["error"], + "no-unsafe-negation": ["error"], + "no-unused-expressions": ["error"], + "no-unused-labels": ["error"], + "no-unused-vars": ["error"], + "no-use-before-define": ["error"], + "no-useless-call": ["error"], + "no-useless-computed-key": ["error"], + "no-useless-concat": ["error"], + "no-useless-constructor": ["error"], + "no-useless-escape": ["error"], + "no-useless-rename": [ + "error", + { + "ignoreDestructuring": false, + "ignoreExport": false, + "ignoreImport": false + } + ], + "no-useless-return": ["error"], + "no-var": ["error"], + "no-void": ["error"], + "no-warning-comments": ["error"], + "no-whitespace-before-property": ["error"], + "no-with": ["error"], + "nonblock-statement-body-position": [ + "error", + "below" + ], + "object-curly-newline": ["error"], + "object-curly-spacing": ["error"], + "object-property-newline": ["error"], + "object-shorthand": ["error"], + "one-var": ["off"], + "one-var-declaration-per-line": ["error"], + "operator-assignment": ["error"], + "operator-linebreak": [ + "error", + "none" + ], + "padded-blocks": ["off"], + "padding-line-between-statements": ["error"], + "prefer-arrow-callback": ["error"], + "prefer-const": ["error"], + "prefer-destructuring": ["off"], + "prefer-numeric-literals": ["error"], + "prefer-promise-reject-errors": ["off"], + "prefer-reflect": ["error"], + "prefer-rest-params": ["error"], + "prefer-spread": ["error"], + "prefer-template": ["error"], + "quote-props": ["error"], + "quotes": ["error"], + "radix": [ + "error", + "as-needed" + ], + "require-await": ["error"], + "require-jsdoc": ["off"], + "require-yield": ["error"], + "rest-spread-spacing": [ + "error", + "never" + ], + "semi": ["error"], + "semi-spacing": ["error"], + "semi-style": [ + "error", + "last" + ], + "sort-imports": ["error"], + "sort-keys": ["error"], + "sort-vars": ["error"], + "space-before-blocks": ["error"], + "space-before-function-paren": ["off"], + "space-in-parens": ["error"], + "space-infix-ops": ["error"], + "space-unary-ops": ["error"], + "spaced-comment": ["error"], + "strict": ["error"], + "switch-colon-spacing": [ + "error", + { + "after": true, + "before": false + } + ], + "symbol-description": ["error"], + "template-curly-spacing": ["error"], + "template-tag-spacing": ["error"], + "unicode-bom": [ + "error", + "never" + ], + "use-isnan": ["error"], + "valid-jsdoc": ["error"], + "valid-typeof": ["error"], + "vars-on-top": ["error"], + "wrap-iife": [ + "error", + "any" + ], + "wrap-regex": ["error"], + "yield-star-spacing": [ + "error", + "before" + ], + "yoda": [ + "error", + "never" + ] + } }; diff --git a/scripts/engines-check.js b/scripts/engines-check.js index c00ba229d..5db6af9ac 100644 --- a/scripts/engines-check.js +++ b/scripts/engines-check.js @@ -8,74 +8,66 @@ const path = require("path"); const exec = require("child_process").exec; const semver = require("./semver"); -const getPackageJson = () => - new Promise((resolve, reject) => { +const getPackageJson = () => new Promise((resolve, reject) => { try { - /* eslint-disable-next-line global-require */ - resolve(require(path.resolve(process.cwd(), "package.json"))); + /* eslint-disable-next-line global-require */ + resolve(require(path.resolve(process.cwd(), "package.json"))); } catch (error) { - reject(error); + reject(error); } - }); +}); -const getEngines = (data) => - new Promise((resolve, reject) => { +const getEngines = (data) => new Promise((resolve, reject) => { let versions = null; if (data.engines) { - versions = data.engines; + versions = data.engines; } if (versions) { - resolve(versions); + resolve(versions); } else { - reject("Missing or improper 'engines' property in 'package.json'"); + reject("Missing or improper 'engines' property in 'package.json'"); } - }); +}); -const checkNpmVersion = (engines) => - new Promise((resolve, reject) => { +const checkNpmVersion = (engines) => new Promise((resolve, reject) => { exec("npm -v", (error, stdout, stderr) => { - if (error) { - reject(`Unable to find NPM version\n${stderr}`); - } + if (error) { + reject(`Unable to find NPM version\n${stderr}`); + } - const npmVersion = stdout.trim(); - const engineVersion = engines.npm || ">=0"; + const npmVersion = stdout.trim(); + const engineVersion = engines.npm || ">=0"; - if (semver.satisfies(npmVersion, engineVersion)) { - resolve(); - } else { - reject( - `Incorrect npm version\n'package.json' specifies "${engineVersion}", you are currently running "${npmVersion}".`, - ); - } + if (semver.satisfies(npmVersion, engineVersion)) { + resolve(); + } else { + reject(`Incorrect npm version\n'package.json' specifies "${engineVersion}", you are currently running "${npmVersion}".`); + } }); - }); +}); -const checkNodeVersion = (engines) => - new Promise((resolve, reject) => { +const checkNodeVersion = (engines) => new Promise((resolve, reject) => { const nodeVersion = process.version.substring(1); if (semver.satisfies(nodeVersion, engines.node)) { - resolve(engines); + resolve(engines); } else { - reject( - `Incorrect node version\n'package.json' specifies "${engines.node}", you are currently running "${process.version}".`, - ); + reject(`Incorrect node version\n'package.json' specifies "${engines.node}", you are currently running "${process.version}".`); } - }); +}); getPackageJson() - .then(getEngines) - .then(checkNodeVersion) - .then(checkNpmVersion) - .then( - () => true, - (error) => { - // Specifically disable these as the error message gets lost in the normal unhandled output. - /* eslint-disable no-console, no-process-exit */ - console.error(error); - process.exit(1); - }, - ); + .then(getEngines) + .then(checkNodeVersion) + .then(checkNpmVersion) + .then( + () => true, + (error) => { + // Specifically disable these as the error message gets lost in the normal unhandled output. + /* eslint-disable no-console, no-process-exit */ + console.error(error); + process.exit(1); + } + ); diff --git a/scripts/semver.js b/scripts/semver.js index 461b71565..b5d015570 100644 --- a/scripts/semver.js +++ b/scripts/semver.js @@ -82,28 +82,28 @@ src[NONNUMERICIDENTIFIER] = "\\d*[a-zA-Z-][a-zA-Z0-9-]*"; // ## Main Version // Three dot-separated numeric identifiers. src[ - MAINVERSION + MAINVERSION ] = `(${src[NUMERICIDENTIFIER]})\\.(${src[NUMERICIDENTIFIER]})\\.(${src[NUMERICIDENTIFIER]})`; src[ - MAINVERSIONLOOSE + MAINVERSIONLOOSE ] = `(${src[NUMERICIDENTIFIERLOOSE]})\\.(${src[NUMERICIDENTIFIERLOOSE]})\\.(${src[NUMERICIDENTIFIERLOOSE]})`; // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. src[ - PRERELEASEIDENTIFIER + PRERELEASEIDENTIFIER ] = `(?:${src[NUMERICIDENTIFIER]}|${src[NONNUMERICIDENTIFIER]})`; src[ - PRERELEASEIDENTIFIERLOOSE + PRERELEASEIDENTIFIERLOOSE ] = `(?:${src[NUMERICIDENTIFIERLOOSE]}|${src[NONNUMERICIDENTIFIER]})`; // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version identifiers. src[ - PRERELEASE + PRERELEASE ] = `(?:-(${src[PRERELEASEIDENTIFIER]}(?:\\.${src[PRERELEASEIDENTIFIER]})*))`; src[ - PRERELEASELOOSE + PRERELEASELOOSE ] = `(?:-?(${src[PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[PRERELEASEIDENTIFIERLOOSE]})*))`; // ## Build Metadata Identifier @@ -136,13 +136,13 @@ src[XRANGEIDENTIFIER] = `${src[NUMERICIDENTIFIER]}|x|X|\\*`; /* eslint-disable-next-line max-len */ src[ - XRANGEPLAIN + XRANGEPLAIN ] = `[v=\\s]*(${src[XRANGEIDENTIFIER]})(?:\\.(${src[XRANGEIDENTIFIER]})(?:\\.(${src[XRANGEIDENTIFIER]})(?:${src[PRERELEASE]})?${src[BUILD]}?)?)?`; /* eslint-disable-next-line max-len */ -src[ - XRANGEPLAINLOOSE -] = `[v=\\s]*(${src[XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[XRANGEIDENTIFIERLOOSE]})(?:${src[PRERELEASELOOSE]})?${src[BUILD]}?)?)?`; +src[XRANGEPLAINLOOSE] = + `[v=\\s]*(${src[XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[XRANGEIDENTIFIERLOOSE]})(?:${src[PRERELEASELOOSE]})?${src[BUILD]}?)?)?`; src[XRANGE] = `^${src[GTLT]}\\s*${src[XRANGEPLAIN]}$`; src[XRANGELOOSE] = `^${src[GTLT]}\\s*${src[XRANGEPLAINLOOSE]}$`; @@ -151,7 +151,7 @@ src[XRANGELOOSE] = `^${src[GTLT]}\\s*${src[XRANGEPLAINLOOSE]}$`; // Extract anything that could conceivably be a part of a valid semver /* eslint-disable-next-line max-len */ src[ - COERCE + COERCE ] = `(?:^|[^\\d])(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:$|[^\\d])`; // Tilde ranges. @@ -181,7 +181,7 @@ src[COMPARATOR] = `^${src[GTLT]}\\s*(${FULLPLAIN})$|^$`; // An expression to strip any whitespace between the gtlt and the thing it modifies, so that `> 1.2.3` ==> `>1.2.3` src[ - COMPARATORTRIM + COMPARATORTRIM ] = `(\\s*)${src[GTLT]}\\s*(${LOOSEPLAIN}|${src[XRANGEPLAIN]})`; // This one has to use the /g flag @@ -191,11 +191,11 @@ const comparatorTrimReplace = "$1$2$3"; // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be checked against either the strict or loose comparator form later. src[ - HYPHENRANGE + HYPHENRANGE ] = `^\\s*(${src[XRANGEPLAIN]})\\s+-\\s+(${src[XRANGEPLAIN]})\\s*$`; src[ - HYPHENRANGELOOSE + HYPHENRANGELOOSE ] = `^\\s*(${src[XRANGEPLAINLOOSE]})\\s+-\\s+(${src[XRANGEPLAINLOOSE]})\\s*$`; // Star ranges basically just allow anything at all. @@ -205,40 +205,40 @@ src[STAR] = "(<|>)?=?\\s*\\*"; // Compile to actual regexp objects. // All are flag-free, unless they were created above with a flag. for (let idx = 0; idx <= STAR; idx++) { - if (!re[idx]) { - re[idx] = new RegExp(src[idx]); - } + if (!re[idx]) { + re[idx] = new RegExp(src[idx]); + } } const ANY = {}; const isX = (id) => !id || id.toLowerCase() === "x" || id === "*"; function compareIdentifiers(left, right) { - const numeric = /^[0-9]+$/; - const leftIsNumeric = numeric.test(left); - const rightIsNumeric = numeric.test(right); - if (leftIsNumeric && !rightIsNumeric) { - return -1; - } + const numeric = /^[0-9]+$/; + const leftIsNumeric = numeric.test(left); + const rightIsNumeric = numeric.test(right); + if (leftIsNumeric && !rightIsNumeric) { + return -1; + } - if (rightIsNumeric && !leftIsNumeric) { - return 1; - } + if (rightIsNumeric && !leftIsNumeric) { + return 1; + } - if (leftIsNumeric && rightIsNumeric) { - left = Number(left); - right = Number(right); - } + if (leftIsNumeric && rightIsNumeric) { + left = Number(left); + right = Number(right); + } - if (left < right) { - return -1; - } + if (left < right) { + return -1; + } - if (left > right) { - return 1; - } + if (left > right) { + return 1; + } - return 0; + return 0; } // This function is passed to string.replace(re[HYPHENRANGE]) @@ -247,58 +247,58 @@ function compareIdentifiers(left, right) { // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0 function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) { - if (isX(fM)) { - from = ""; - } else if (isX(fm)) { - from = `>=${fM}.0.0`; - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0`; - } else { - from = `>=${from}`; - } + if (isX(fM)) { + from = ""; + } else if (isX(fm)) { + from = `>=${fM}.0.0`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0`; + } else { + from = `>=${from}`; + } - if (isX(tM)) { - to = ""; - } else if (isX(tm)) { - to = `<${Number(tM) + 1}.0.0`; - } else if (isX(tp)) { - to = `<${tM}.${Number(tm) + 1}.0`; - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}`; - } else { - to = `<=${to}`; - } + if (isX(tM)) { + to = ""; + } else if (isX(tm)) { + to = `<${Number(tM) + 1}.0.0`; + } else if (isX(tp)) { + to = `<${tM}.${Number(tm) + 1}.0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else { + to = `<=${to}`; + } - return `${from} ${to}`.trim(); + return `${from} ${to}`.trim(); } function replaceTilde(comp, loose) { - const regex = loose ? re[TILDELOOSE] : re[TILDE]; + const regex = loose ? re[TILDELOOSE] : re[TILDE]; - return comp.replace(regex, function (match, major, minor, patch, prerelease) { - let ret; + return comp.replace(regex, function (match, major, minor, patch, prerelease) { + let ret; - if (isX(major)) { - ret = ""; - } else if (isX(minor)) { - ret = `>=${major}.0.0 <${Number(major) + 1}.0.0`; - } else if (isX(patch)) { - // ~1.2 == >=1.2.0 <1.3.0 - ret = `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0`; - } else if (prerelease) { - if (prerelease.charAt(0) !== "-") { - prerelease = `-${prerelease}`; - } - ret = `>=${major}.${minor}.${patch}${prerelease} <${major}.${ - Number(minor) + 1 - }.0`; - } else { - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = `>=${major}.${minor}.${patch} <${major}.${Number(minor) + 1}.0`; - } + if (isX(major)) { + ret = ""; + } else if (isX(minor)) { + ret = `>=${major}.0.0 <${Number(major) + 1}.0.0`; + } else if (isX(patch)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0`; + } else if (prerelease) { + if (prerelease.charAt(0) !== "-") { + prerelease = `-${prerelease}`; + } + ret = `>=${major}.${minor}.${patch}${prerelease} <${major}.${ + Number(minor) + 1 + }.0`; + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = `>=${major}.${minor}.${patch} <${major}.${Number(minor) + 1}.0`; + } - return ret; - }); + return ret; + }); } // ~, ~> --> * (any, kinda silly) @@ -308,62 +308,62 @@ function replaceTilde(comp, loose) { // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 function replaceTildes(comp, loose) { - return comp - .trim() - .split(/\s+/) - .map((comp1) => replaceTilde(comp1, loose)) - .join(" "); + return comp + .trim() + .split(/\s+/) + .map((comp1) => replaceTilde(comp1, loose)) + .join(" "); } function replaceCaret(comp, loose) { - const regex = loose ? re[CARETLOOSE] : re[CARET]; + const regex = loose ? re[CARETLOOSE] : re[CARET]; - return comp.replace(regex, function (match, major, minor, patch, prerelease) { - let ret; + return comp.replace(regex, function (match, major, minor, patch, prerelease) { + let ret; - if (isX(major)) { - ret = ""; - } else if (isX(minor)) { - ret = `>=${major}.0.0 <${Number(major) + 1}.0.0`; - } else if (isX(patch)) { - if (major === "0") { - ret = `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0`; - } else { - ret = `>=${major}.${minor}.0 <${Number(major) + 1}.0.0`; - } - } else if (prerelease) { - if (prerelease.charAt(0) !== "-") { - prerelease = `-${prerelease}`; - } - if (major === "0") { - if (minor === "0") { - ret = `>=${major}.${minor}.${patch}${prerelease} <${major}.${minor}.${ - Number(patch) + 1 - }`; + if (isX(major)) { + ret = ""; + } else if (isX(minor)) { + ret = `>=${major}.0.0 <${Number(major) + 1}.0.0`; + } else if (isX(patch)) { + if (major === "0") { + ret = `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0`; + } else { + ret = `>=${major}.${minor}.0 <${Number(major) + 1}.0.0`; + } + } else if (prerelease) { + if (prerelease.charAt(0) !== "-") { + prerelease = `-${prerelease}`; + } + if (major === "0") { + if (minor === "0") { + ret = `>=${major}.${minor}.${patch}${prerelease} <${major}.${minor}.${ + Number(patch) + 1 + }`; + } else { + ret = `>=${major}.${minor}.${patch}${prerelease} <${major}.${ + Number(minor) + 1 + }.0`; + } + } else { + ret = `>=${major}.${minor}.${patch}${prerelease} <${ + Number(major) + 1 + }.0.0`; + } + } else if (major === "0") { + if (minor === "0") { + ret = `>=${major}.${minor}.${patch} <${major}.${minor}.${ + Number(patch) + 1 + }`; + } else { + ret = `>=${major}.${minor}.${patch} <${major}.${Number(minor) + 1}.0`; + } } else { - ret = `>=${major}.${minor}.${patch}${prerelease} <${major}.${ - Number(minor) + 1 - }.0`; + ret = `>=${major}.${minor}.${patch} <${Number(major) + 1}.0.0`; } - } else { - ret = `>=${major}.${minor}.${patch}${prerelease} <${ - Number(major) + 1 - }.0.0`; - } - } else if (major === "0") { - if (minor === "0") { - ret = `>=${major}.${minor}.${patch} <${major}.${minor}.${ - Number(patch) + 1 - }`; - } else { - ret = `>=${major}.${minor}.${patch} <${major}.${Number(minor) + 1}.0`; - } - } else { - ret = `>=${major}.${minor}.${patch} <${Number(major) + 1}.0.0`; - } - return ret; - }); + return ret; + }); } // ^ --> * (any, kinda silly) @@ -373,380 +373,370 @@ function replaceCaret(comp, loose) { // ^1.2.3 --> >=1.2.3 <2.0.0 // ^1.2.0 --> >=1.2.0 <2.0.0 function replaceCarets(comp, loose) { - return comp - .trim() - .split(/\s+/) - .map((comp1) => replaceCaret(comp1, loose)) - .join(" "); + return comp + .trim() + .split(/\s+/) + .map((comp1) => replaceCaret(comp1, loose)) + .join(" "); } function replaceXRange(comp, loose) { - comp = comp.trim(); - const regex = loose ? re[XRANGELOOSE] : re[XRANGE]; + comp = comp.trim(); + const regex = loose ? re[XRANGELOOSE] : re[XRANGE]; - return comp.replace(regex, function (ret, operator, major, minor, patch) { - const xM = isX(major); - const xm = xM || isX(minor); - const xp = xm || isX(patch); - const anyX = xp; + return comp.replace(regex, function (ret, operator, major, minor, patch) { + const xM = isX(major); + const xm = xM || isX(minor); + const xp = xm || isX(patch); + const anyX = xp; - if (operator === "=" && anyX) { - operator = ""; - } + if (operator === "=" && anyX) { + operator = ""; + } - if (xM) { - if (operator === ">" || operator === "<") { - // Nothing is allowed - ret = "<0.0.0"; - } else { - // Nothing is forbidden - ret = "*"; - } - } else if (operator && anyX) { - // Replace X with 0 - if (xm) { - minor = 0; - } - if (xp) { - patch = 0; - } + if (xM) { + if (operator === ">" || operator === "<") { + // Nothing is allowed + ret = "<0.0.0"; + } else { + // Nothing is forbidden + ret = "*"; + } + } else if (operator && anyX) { + // Replace X with 0 + if (xm) { + minor = 0; + } + if (xp) { + patch = 0; + } - if (operator === ">") { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - operator = ">="; - if (xm) { - major = Number(major) + 1; - minor = 0; - patch = 0; + if (operator === ">") { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + operator = ">="; + if (xm) { + major = Number(major) + 1; + minor = 0; + patch = 0; + } else if (xp) { + minor = Number(minor) + 1; + patch = 0; + } + } else if (operator === "<=") { + // <=0.7.x is actually <0.8.0, since any 0.7.x should pass. Similarly, <=7.x is actually <8.0.0, etc. + operator = "<"; + if (xm) { + major = Number(major) + 1; + } else { + minor = Number(minor) + 1; + } + } + + ret = `${operator}${major}.${minor}.${patch}`; + } else if (xm) { + ret = `>=${major}.0.0 <${Number(major) + 1}.0.0`; } else if (xp) { - minor = Number(minor) + 1; - patch = 0; + ret = `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0`; } - } else if (operator === "<=") { - // <=0.7.x is actually <0.8.0, since any 0.7.x should pass. Similarly, <=7.x is actually <8.0.0, etc. - operator = "<"; - if (xm) { - major = Number(major) + 1; - } else { - minor = Number(minor) + 1; - } - } - ret = `${operator}${major}.${minor}.${patch}`; - } else if (xm) { - ret = `>=${major}.0.0 <${Number(major) + 1}.0.0`; - } else if (xp) { - ret = `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0`; - } - - return ret; - }); + return ret; + }); } function replaceXRanges(comp, loose) { - return comp - .split(/\s+/) - .map((comp1) => replaceXRange(comp1, loose)) - .join(" "); + return comp + .split(/\s+/) + .map((comp1) => replaceXRange(comp1, loose)) + .join(" "); } // Because * is AND-ed with everything else in the comparator, and '' means "any version", just remove the *s entirely. function replaceStars(comp) { - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], ""); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], ""); } // Comprised of xranges, tildes, stars, and gtlt's at this point. // Already replaced the hyphen ranges turn into a set of JUST comparators. function parseComparator(comp, loose) { - comp = replaceCarets(comp, loose); - comp = replaceTildes(comp, loose); - comp = replaceXRanges(comp, loose); - comp = replaceStars(comp, loose); + comp = replaceCarets(comp, loose); + comp = replaceTildes(comp, loose); + comp = replaceXRanges(comp, loose); + comp = replaceStars(comp, loose); - return comp; + return comp; } class SemVer { - /** + + /** * A semantic version. * @param {string} version The version. * @param {boolean} loose If this is a loose representation of a version. * @returns {SemVer} a new instance. */ - constructor(version, loose) { - if (version instanceof SemVer) { - if (version.loose === loose) { - return version; - } - version = version.version; - } else if (typeof version !== "string") { - throw new TypeError(`Invalid Version: ${version}`); + constructor(version, loose) { + if (version instanceof SemVer) { + if (version.loose === loose) { + return version; + } + version = version.version; + } else if (typeof version !== "string") { + throw new TypeError(`Invalid Version: ${version}`); + } + if (version.length > MAX_LENGTH) { + throw new TypeError(`version is longer than ${MAX_LENGTH} characters`); + } + if (!(this instanceof SemVer)) { + return new SemVer(version, loose); + } + this.loose = loose; + const matches = version.trim().match(loose ? re[LOOSE] : re[FULL]); + if (!matches) { + throw new TypeError(`Invalid Version: ${version}`); + } + this.raw = version; + // These are actually numbers + this.major = Number(matches[1]); + this.minor = Number(matches[2]); + this.patch = Number(matches[3]); + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError("Invalid major version"); + } + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError("Invalid minor version"); + } + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError("Invalid patch version"); + } + // Numberify any prerelease numeric ids + if (matches[4]) { + this.prerelease = matches[4].split(".").map((id) => { + if ((/^[0-9]+$/).test(id)) { + const num = Number(id); + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num; + } + } + + return id; + }); + } else { + this.prerelease = []; + } + this.build = matches[5] ? matches[5].split(".") : []; + this.format(); } - if (version.length > MAX_LENGTH) { - throw new TypeError(`version is longer than ${MAX_LENGTH} characters`); - } - if (!(this instanceof SemVer)) { - return new SemVer(version, loose); - } - this.loose = loose; - const matches = version.trim().match(loose ? re[LOOSE] : re[FULL]); - if (!matches) { - throw new TypeError(`Invalid Version: ${version}`); - } - this.raw = version; - // These are actually numbers - this.major = Number(matches[1]); - this.minor = Number(matches[2]); - this.patch = Number(matches[3]); - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError("Invalid major version"); - } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError("Invalid minor version"); - } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError("Invalid patch version"); - } - // Numberify any prerelease numeric ids - if (matches[4]) { - this.prerelease = matches[4].split(".").map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = Number(id); - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num; - } + + format() { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join(".")}`; } - return id; - }); - } else { - this.prerelease = []; - } - this.build = matches[5] ? matches[5].split(".") : []; - this.format(); - } - - format() { - this.version = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease.length) { - this.version += `-${this.prerelease.join(".")}`; + return this.version; } - return this.version; - } + toString() { + return this.version; + } - toString() { - return this.version; - } - - /** + /** * Comares the current instance against another instance. * @param {SemVer} other The SemVer to comare to. * @returns {0|1|-1} A comparable value for sorting. */ - compare(other) { - return this.compareMain(other) || this.comparePre(other); - } - - compareMain(other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.loose); + compare(other) { + return this.compareMain(other) || this.comparePre(other); } - return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) - ); - } + compareMain(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.loose); + } - comparePre(other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.loose); + return ( + compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) + ); } - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1; - } else if (!this.prerelease.length && other.prerelease.length) { - return 1; - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0; - } - let idx = 0; - do { - const thisPrelease = this.prerelease[idx]; - const otherPrelease = other.prerelease[idx]; - const thisPreleaseIsUndefined = typeof thisPrelease === "undefined"; - const otherPreleaseIsUndefined = typeof otherPrelease === "undefined"; - if (thisPreleaseIsUndefined && otherPreleaseIsUndefined) { + + comparePre(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.loose); + } + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + let idx = 0; + do { + const thisPrelease = this.prerelease[idx]; + const otherPrelease = other.prerelease[idx]; + const thisPreleaseIsUndefined = typeof thisPrelease === "undefined"; + const otherPreleaseIsUndefined = typeof otherPrelease === "undefined"; + if (thisPreleaseIsUndefined && otherPreleaseIsUndefined) { + return 0; + } else if (otherPreleaseIsUndefined) { + return 1; + } else if (thisPreleaseIsUndefined) { + return -1; + } else if (thisPrelease === otherPrelease) { + continue; + } else { + return compareIdentifiers(thisPrelease, otherPrelease); + } + } while ((idx += 1) > 0); + + // Should not hit this point, but assume equal ranking. return 0; - } else if (otherPreleaseIsUndefined) { - return 1; - } else if (thisPreleaseIsUndefined) { - return -1; - } else if (thisPrelease === otherPrelease) { - continue; - } else { - return compareIdentifiers(thisPrelease, otherPrelease); - } - } while ((idx += 1) > 0); - - // Should not hit this point, but assume equal ranking. - return 0; - } + } } -const compare = (leftVersion, rightVersion, loose) => - new SemVer(leftVersion, loose).compare(new SemVer(rightVersion, loose)); -const gt = (leftVersion, rightVersion, loose) => - compare(leftVersion, rightVersion, loose) > 0; -const lt = (leftVersion, rightVersion, loose) => - compare(leftVersion, rightVersion, loose) < 0; -const eq = (leftVersion, rightVersion, loose) => - compare(leftVersion, rightVersion, loose) === 0; -const neq = (leftVersion, rightVersion, loose) => - compare(leftVersion, rightVersion, loose) !== 0; -const gte = (leftVersion, rightVersion, loose) => - compare(leftVersion, rightVersion, loose) >= 0; -const lte = (leftVersion, rightVersion, loose) => - compare(leftVersion, rightVersion, loose) <= 0; +const compare = (leftVersion, rightVersion, loose) => new SemVer(leftVersion, loose).compare(new SemVer(rightVersion, loose)); +const gt = (leftVersion, rightVersion, loose) => compare(leftVersion, rightVersion, loose) > 0; +const lt = (leftVersion, rightVersion, loose) => compare(leftVersion, rightVersion, loose) < 0; +const eq = (leftVersion, rightVersion, loose) => compare(leftVersion, rightVersion, loose) === 0; +const neq = (leftVersion, rightVersion, loose) => compare(leftVersion, rightVersion, loose) !== 0; +const gte = (leftVersion, rightVersion, loose) => compare(leftVersion, rightVersion, loose) >= 0; +const lte = (leftVersion, rightVersion, loose) => compare(leftVersion, rightVersion, loose) <= 0; function cmp(left, op, right, loose) { - let ret; - switch (op) { - case "===": - if (typeof left === "object") { - left = left.version; - } - if (typeof right === "object") { - right = right.version; - } - ret = left === right; - break; - case "!==": - if (typeof left === "object") { - left = left.version; - } - if (typeof right === "object") { - right = right.version; - } - ret = left !== right; - break; - case "": - case "=": - case "==": - ret = eq(left, right, loose); - break; - case "!=": - ret = neq(left, right, loose); - break; - case ">": - ret = gt(left, right, loose); - break; - case ">=": - ret = gte(left, right, loose); - break; - case "<": - ret = lt(left, right, loose); - break; - case "<=": - ret = lte(left, right, loose); - break; - default: - throw new TypeError(`Invalid operator: ${op}`); - } + let ret; + switch (op) { + case "===": + if (typeof left === "object") { + left = left.version; + } + if (typeof right === "object") { + right = right.version; + } + ret = left === right; + break; + case "!==": + if (typeof left === "object") { + left = left.version; + } + if (typeof right === "object") { + right = right.version; + } + ret = left !== right; + break; + case "": + case "=": + case "==": + ret = eq(left, right, loose); + break; + case "!=": + ret = neq(left, right, loose); + break; + case ">": + ret = gt(left, right, loose); + break; + case ">=": + ret = gte(left, right, loose); + break; + case "<": + ret = lt(left, right, loose); + break; + case "<=": + ret = lte(left, right, loose); + break; + default: + throw new TypeError(`Invalid operator: ${op}`); + } - return ret; + return ret; } function testSet(set, version) { - for (let idx = 0; idx < set.length; idx++) { - if (!set[idx].test(version)) { - return false; + for (let idx = 0; idx < set.length; idx++) { + if (!set[idx].test(version)) { + return false; + } } - } - if (version.prerelease.length) { + if (version.prerelease.length) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, even though it's within the range set by the comparators. - for (let idx = 0; idx < set.length; idx++) { - if (set[idx].semver !== ANY) { - if (set[idx].semver.prerelease.length > 0) { - const allowed = set[idx].semver; - if ( - allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch - ) { - return true; - } + for (let idx = 0; idx < set.length; idx++) { + if (set[idx].semver !== ANY) { + if (set[idx].semver.prerelease.length > 0) { + const allowed = set[idx].semver; + if ( + allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch + ) { + return true; + } + } + } } - } + + // Version has a -pre, but it's not one of the ones we like. + return false; } - // Version has a -pre, but it's not one of the ones we like. - return false; - } - - return true; + return true; } class Comparator { - constructor(comp, loose) { - if (comp instanceof Comparator) { - if (comp.loose === loose) { - return comp; - } - comp = comp.value; - } - if (!(this instanceof Comparator)) { - return new Comparator(comp, loose); - } - this.loose = loose; - this.parse(comp); - if (this.semver === ANY) { - this.value = ""; - } else { - this.value = this.operator + this.semver.version; - } - } - - parse(comp) { - const regex = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - const matches = comp.match(regex); - if (!matches) { - throw new TypeError(`Invalid comparator: ${comp}`); - } - this.operator = matches[1]; - if (this.operator === "=") { - this.operator = ""; - } - // If it literally is just '>' or '' then allow anything. - if (matches[2]) { - this.semver = new SemVer(matches[2], this.loose); - } else { - this.semver = ANY; - } - } - - toString() { - return this.value; - } - - test(version) { - if (this.semver === ANY) { - return true; - } - if (typeof version === "string") { - version = new SemVer(version, this.loose); + constructor(comp, loose) { + if (comp instanceof Comparator) { + if (comp.loose === loose) { + return comp; + } + comp = comp.value; + } + if (!(this instanceof Comparator)) { + return new Comparator(comp, loose); + } + this.loose = loose; + this.parse(comp); + if (this.semver === ANY) { + this.value = ""; + } else { + this.value = this.operator + this.semver.version; + } } - return cmp(version, this.operator, this.semver, this.loose); - } + parse(comp) { + const regex = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + const matches = comp.match(regex); + if (!matches) { + throw new TypeError(`Invalid comparator: ${comp}`); + } + this.operator = matches[1]; + if (this.operator === "=") { + this.operator = ""; + } + // If it literally is just '>' or '' then allow anything. + if (matches[2]) { + this.semver = new SemVer(matches[2], this.loose); + } else { + this.semver = ANY; + } + } + + toString() { + return this.value; + } + + test(version) { + if (this.semver === ANY) { + return true; + } + if (typeof version === "string") { + version = new SemVer(version, this.loose); + } + + return cmp(version, this.operator, this.semver, this.loose); + } } /** @@ -756,99 +746,99 @@ class Comparator { * @returns {Range} the Range instace. */ class Range { - constructor(range, loose) { - if (range instanceof Range) { - if (range.loose === loose) { - return range; - } + constructor(range, loose) { + if (range instanceof Range) { + if (range.loose === loose) { + return range; + } - return new Range(range.raw, loose); - } - if (range instanceof Comparator) { - return new Range(range.value, loose); - } - if (!(this instanceof Range)) { - return new Range(range, loose); - } - this.loose = loose; - // First, split based on boolean or || - /** + return new Range(range.raw, loose); + } + if (range instanceof Comparator) { + return new Range(range.value, loose); + } + if (!(this instanceof Range)) { + return new Range(range, loose); + } + this.loose = loose; + // First, split based on boolean or || + /** * @type {string} */ - this.raw = range; - // Throw out any that are not relevant for whatever reason - const hasLength = (item) => item.length; - this.set = this.raw - .split(/\s*\|\|\s*/) - .map(function (range1) { - return this.parseRange(range1.trim()); - }, this) - .filter(hasLength); - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${range}`); - } - this.format(); - } - - format() { - this.range = this.set - .map((comps) => comps.join(" ").trim()) - .join("||") - .trim(); - - return this.range; - } - - toString() { - return this.range; - } - - parseRange(range) { - const loose = this.loose; - range = range.trim(); - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; - range = range.replace(hr, hyphenReplace); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace); - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace); - // Normalize spaces - range = range.split(/\s+/).join(" "); - // At this point, the range is completely trimmed and ready to be split into comparators. - const compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - let set = range - .split(" ") - .map((comp) => parseComparator(comp, loose)) - .join(" ") - .split(/\s+/); - if (loose) { - // In loose mode, throw out any that are not valid comparators - set = set.filter((comp) => Boolean(comp.match(compRe))); - } - set = set.map((comp) => new Comparator(comp, loose)); - - return set; - } - - // If ANY of the sets match ALL of its comparators, then pass - test(version) { - if (!version) { - return false; - } - if (typeof version === "string") { - version = new SemVer(version, this.loose); - } - for (let idx = 0; idx < this.set.length; idx++) { - if (testSet(this.set[idx], version)) { - return true; - } + this.raw = range; + // Throw out any that are not relevant for whatever reason + const hasLength = (item) => item.length; + this.set = this.raw + .split(/\s*\|\|\s*/) + .map(function (range1) { + return this.parseRange(range1.trim()); + }, this) + .filter(hasLength); + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`); + } + this.format(); } - return false; - } + format() { + this.range = this.set + .map((comps) => comps.join(" ").trim()) + .join("||") + .trim(); + + return this.range; + } + + toString() { + return this.range; + } + + parseRange(range) { + const loose = this.loose; + range = range.trim(); + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace); + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace); + // Normalize spaces + range = range.split(/\s+/).join(" "); + // At this point, the range is completely trimmed and ready to be split into comparators. + const compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + let set = range + .split(" ") + .map((comp) => parseComparator(comp, loose)) + .join(" ") + .split(/\s+/); + if (loose) { + // In loose mode, throw out any that are not valid comparators + set = set.filter((comp) => Boolean(comp.match(compRe))); + } + set = set.map((comp) => new Comparator(comp, loose)); + + return set; + } + + // If ANY of the sets match ALL of its comparators, then pass + test(version) { + if (!version) { + return false; + } + if (typeof version === "string") { + version = new SemVer(version, this.loose); + } + for (let idx = 0; idx < this.set.length; idx++) { + if (testSet(this.set[idx], version)) { + return true; + } + } + + return false; + } } /** @@ -859,13 +849,13 @@ class Range { * @returns {boolean} Whether the versions successfully satisfies the range. */ function satisfies(version, range, loose) { - try { - const rangeObj = new Range(range, loose); + try { + const rangeObj = new Range(range, loose); - return rangeObj.test(version); - } catch (er) { - return false; - } + return rangeObj.test(version); + } catch (er) { + return false; + } } module.exports.satisfies = satisfies; diff --git a/src/Augmentation/AugmentationHelpers.jsx b/src/Augmentation/AugmentationHelpers.jsx index 7a3d00b06..135f08773 100644 --- a/src/Augmentation/AugmentationHelpers.jsx +++ b/src/Augmentation/AugmentationHelpers.jsx @@ -139,8 +139,7 @@ function initAugmentations() { "unpredictable results based on your circadian rhythm.", }; Object.keys(randomBonuses.bonuses).forEach( - (key) => - (UnstableCircadianModulatorParams[key] = randomBonuses.bonuses[key]), + (key) => (UnstableCircadianModulatorParams[key] = randomBonuses.bonuses[key]), ); const UnstableCircadianModulator = new Augmentation( UnstableCircadianModulatorParams, diff --git a/src/Bladeburner/Bladeburner.ts b/src/Bladeburner/Bladeburner.ts index fa9d402bc..34e314ee6 100644 --- a/src/Bladeburner/Bladeburner.ts +++ b/src/Bladeburner/Bladeburner.ts @@ -2472,9 +2472,10 @@ export class Bladeburner implements IBladeburner { case ActionTypes["Diplomacy"]: case ActionTypes["Hyperbolic Regeneration Chamber"]: return [1, 1]; - case ActionTypes["Recruitment"]: + case ActionTypes["Recruitment"]: { const recChance = this.getRecruitmentSuccessChance(player); return [recChance, recChance]; + } default: workerScript.log( "bladeburner.getActionEstimatedSuccessChance", diff --git a/src/Bladeburner/ui/BlackOpList.tsx b/src/Bladeburner/ui/BlackOpList.tsx index 0bf21ac89..a001578d0 100644 --- a/src/Bladeburner/ui/BlackOpList.tsx +++ b/src/Bladeburner/ui/BlackOpList.tsx @@ -22,8 +22,7 @@ export function BlackOpList(props: IProps): React.ReactElement { }); blackops = blackops.filter( - (blackop: BlackOperation, i: number) => - !( + (blackop: BlackOperation, i: number) => !( props.bladeburner.blackops[blackops[i].name] == null && i !== 0 && props.bladeburner.blackops[blackops[i - 1].name] == null diff --git a/src/Bladeburner/ui/BlackOpPage.tsx b/src/Bladeburner/ui/BlackOpPage.tsx index f841d7ebd..0c158eec5 100644 --- a/src/Bladeburner/ui/BlackOpPage.tsx +++ b/src/Bladeburner/ui/BlackOpPage.tsx @@ -2,7 +2,6 @@ import * as React from "react"; import { BlackOpList } from "./BlackOpList"; import { IBladeburner } from "../IBladeburner"; import { IPlayer } from "../../PersonObjects/IPlayer"; -import { CopyableText } from "../../ui/React/CopyableText"; interface IProps { bladeburner: IBladeburner; diff --git a/src/Bladeburner/ui/ContractElem.tsx b/src/Bladeburner/ui/ContractElem.tsx index 303524cee..9c9b51dd7 100644 --- a/src/Bladeburner/ui/ContractElem.tsx +++ b/src/Bladeburner/ui/ContractElem.tsx @@ -26,7 +26,6 @@ export function ContractElem(props: IProps): React.ReactElement { const estimatedSuccessChance = props.action.getEstSuccessChance( props.bladeburner, ); - const successChance = props.action.getSuccessChance(props.bladeburner); const computedActionTimeCurrent = Math.min( props.bladeburner.actionTimeCurrent + props.bladeburner.actionTimeOverflow, props.bladeburner.actionTimeToComplete, diff --git a/src/Constants.ts b/src/Constants.ts index 08f6bf0e8..cdc44704e 100644 --- a/src/Constants.ts +++ b/src/Constants.ts @@ -3,8 +3,6 @@ * * Constants for specific mechanics or features will NOT be here. */ -import { IMap } from "./types"; - export const CONSTANTS: { Version: string; _idleSpeed: number; diff --git a/src/Corporation/Actions.ts b/src/Corporation/Actions.ts index f6a34bd4e..9b80b9871 100644 --- a/src/Corporation/Actions.ts +++ b/src/Corporation/Actions.ts @@ -25,7 +25,7 @@ export function NewIndustry( const cost = IndustryStartingCosts[industry]; if (cost === undefined) { - throw new Error("Invalid industry: ${industry}"); + throw new Error(`Invalid industry: '${industry}'`); } if (corporation.funds.lt(cost)) { throw new Error( diff --git a/src/Corporation/Corporation.tsx b/src/Corporation/Corporation.tsx index 6408f4221..37ad20b7c 100644 --- a/src/Corporation/Corporation.tsx +++ b/src/Corporation/Corporation.tsx @@ -32,7 +32,6 @@ import { removeElementById } from "../../utils/uiHelpers/removeElementById"; import React from "react"; import ReactDOM from "react-dom"; import { CorporationRoot } from "./ui/Root"; -import { CorporationRouting } from "./ui/Routing"; import Decimal from "decimal.js"; @@ -40,7 +39,6 @@ interface IParams { name?: string; } -let corpRouting: CorporationRouting; let companyManagementDiv: HTMLDivElement | null = null; export class Corporation { @@ -483,22 +481,20 @@ export class Corporation { const game = document.getElementById("entire-game-container"); if (game) game.appendChild(companyManagementDiv); - corpRouting = new CorporationRouting(this); - this.rerender(player); } rerender(player: IPlayer): void { - if (companyManagementDiv == null || corpRouting == null) { + if (companyManagementDiv == null) { console.warn( - `Corporation.rerender() called when companyManagementDiv, corpRouting, or eventHandler is null`, + `Corporation.rerender() called when companyManagementDiv is null`, ); return; } if (!routing.isOn(Page.Corporation)) return; ReactDOM.render( - , + , companyManagementDiv, ); } diff --git a/src/Corporation/ui/CityTabs.tsx b/src/Corporation/ui/CityTabs.tsx index 94f77f607..03684af8c 100644 --- a/src/Corporation/ui/CityTabs.tsx +++ b/src/Corporation/ui/CityTabs.tsx @@ -1,50 +1,67 @@ // React Components for the Corporation UI's City navigation tabs // These allow player to navigate between different cities for each industry -import React from "react"; +import React, { useState } from "react"; import { CityTab } from "./CityTab"; import { ExpandNewCityPopup } from "./ExpandNewCityPopup"; import { createPopup } from "../../ui/React/createPopup"; import { ICorporation } from "../ICorporation"; -import { CorporationRouting } from "./Routing"; +import { IIndustry } from "../IIndustry"; +import { OfficeSpace } from "../OfficeSpace"; +import { Industry } from "./Industry"; +import { IPlayer } from "../../PersonObjects/IPlayer"; interface IProps { - routing: CorporationRouting; - onClicks: { [key: string]: () => void }; - city: string; // currentCity - cityStateSetter: (city: string) => void; + city: string; + division: IIndustry; corp: ICorporation; + player: IPlayer; } export function CityTabs(props: IProps): React.ReactElement { - const division = props.routing.currentDivision; + const [city, setCity] = useState(props.city); function openExpandNewCityModal(): void { - if (division === null) return; const popupId = "cmpy-mgmt-expand-city-popup"; createPopup(popupId, ExpandNewCityPopup, { popupId: popupId, corp: props.corp, - division: division, - cityStateSetter: props.cityStateSetter, + division: props.division, + cityStateSetter: setCity, }); } + const office = props.division.offices[city]; + if (office === 0) { + setCity("Sector-12"); + return <>; + } + return ( <> - {Object.keys(props.onClicks).map((cityName: string) => ( - - ))} + {Object.values(props.division.offices).map( + (office: OfficeSpace | 0) => office !== 0 && ( + setCity(office.loc)} + /> + ), + )} + ); } diff --git a/src/Corporation/ui/ExpandNewCityPopup.tsx b/src/Corporation/ui/ExpandNewCityPopup.tsx index 13a574870..d909afc7b 100644 --- a/src/Corporation/ui/ExpandNewCityPopup.tsx +++ b/src/Corporation/ui/ExpandNewCityPopup.tsx @@ -4,7 +4,6 @@ import { numeralWrapper } from "../../ui/numeralFormat"; import { CorporationConstants } from "../data/Constants"; import { removePopup } from "../../ui/React/createPopup"; import { dialogBoxCreate } from "../../../utils/DialogBox"; -import { OfficeSpace } from "../OfficeSpace"; import { ICorporation } from "../ICorporation"; import { NewCity } from "../Actions"; diff --git a/src/Corporation/ui/HeaderTabs.tsx b/src/Corporation/ui/HeaderTabs.tsx index 371ec2aa5..f5a277dab 100644 --- a/src/Corporation/ui/HeaderTabs.tsx +++ b/src/Corporation/ui/HeaderTabs.tsx @@ -1,60 +1,60 @@ // React Components for the Corporation UI's navigation tabs // These are the tabs at the top of the UI that let you switch to different // divisions, see an overview of your corporation, or create a new industry -import React from "react"; +import React, { useState } from "react"; import { HeaderTab } from "./HeaderTab"; import { IIndustry } from "../IIndustry"; import { NewIndustryPopup } from "./NewIndustryPopup"; import { createPopup } from "../../ui/React/createPopup"; import { ICorporation } from "../ICorporation"; -import { CorporationRouting } from "./Routing"; import { IPlayer } from "../../PersonObjects/IPlayer"; +import { MainPanel } from "./MainPanel"; interface IProps { corp: ICorporation; - routing: CorporationRouting; player: IPlayer; } export function HeaderTabs(props: IProps): React.ReactElement { - function overviewOnClick(): void { - props.routing.routeToOverviewPage(); - props.corp.rerender(props.player); - } + const [divisionName, setDivisionName] = useState("Overview"); function openNewIndustryPopup(): void { const popupId = "cmpy-mgmt-expand-industry-popup"; createPopup(popupId, NewIndustryPopup, { corp: props.corp, - routing: props.routing, + setDivisionName: setDivisionName, popupId: popupId, }); } return ( -
- - {props.corp.divisions.map((division: IIndustry) => ( + <> +
{ - props.routing.routeTo(division.name); - props.corp.rerender(props.player); - }} - text={division.name} + current={divisionName === "Overview"} + key={"overview"} + onClick={() => setDivisionName("Overview")} + text={props.corp.name} /> - ))} - ( + setDivisionName(division.name)} + text={division.name} + /> + ))} + +
+ -
+ ); } diff --git a/src/Corporation/ui/Industry.tsx b/src/Corporation/ui/Industry.tsx index b7ed6d224..9f90d2acd 100644 --- a/src/Corporation/ui/Industry.tsx +++ b/src/Corporation/ui/Industry.tsx @@ -5,14 +5,18 @@ import React from "react"; import { IndustryOffice } from "./IndustryOffice"; import { IndustryOverview } from "./IndustryOverview"; import { IndustryWarehouse } from "./IndustryWarehouse"; +import { Warehouse } from "../Warehouse"; import { ICorporation } from "../ICorporation"; -import { CorporationRouting } from "./Routing"; +import { OfficeSpace } from "../OfficeSpace"; +import { IIndustry } from "../IIndustry"; import { IPlayer } from "../../PersonObjects/IPlayer"; interface IProps { - routing: CorporationRouting; corp: ICorporation; - currentCity: string; + division: IIndustry; + city: string; + warehouse: Warehouse | 0; + office: OfficeSpace; player: IPlayer; } @@ -22,23 +26,25 @@ export function Industry(props: IProps): React.ReactElement {
diff --git a/src/Corporation/ui/IndustryOffice.tsx b/src/Corporation/ui/IndustryOffice.tsx index 22a9f99dc..1f8f1bf82 100644 --- a/src/Corporation/ui/IndustryOffice.tsx +++ b/src/Corporation/ui/IndustryOffice.tsx @@ -3,6 +3,7 @@ import React, { useState } from "react"; import { OfficeSpace } from "../OfficeSpace"; +import { IIndustry } from "../IIndustry"; import { Employee } from "../Employee"; import { EmployeePositions } from "../EmployeePositions"; @@ -15,20 +16,17 @@ import { HireEmployeePopup } from "./HireEmployeePopup"; import { ThrowPartyPopup } from "./ThrowPartyPopup"; import { ICorporation } from "../ICorporation"; import { IPlayer } from "../../PersonObjects/IPlayer"; -import { CorporationRouting } from "./Routing"; interface IProps { - routing: CorporationRouting; corp: ICorporation; - currentCity: string; + division: IIndustry; + office: OfficeSpace; player: IPlayer; } export function IndustryOffice(props: IProps): React.ReactElement { const [employeeManualAssignMode, setEmployeeManualAssignMode] = useState(false); - const [city, setCity] = useState(""); - const [divisionName, setDivisionName] = useState(""); const [employee, setEmployee] = useState(null); const [numEmployees, setNumEmployees] = useState(0); const [numOperations, setNumOperations] = useState(0); @@ -51,28 +49,8 @@ export function IndustryOffice(props: IProps): React.ReactElement { } function updateEmployeeCount(): void { - const division = props.routing.currentDivision; - if (division == null) { - throw new Error( - `Routing does not hold reference to the current Industry`, - ); - } - const office = division.offices[props.currentCity]; - if (!(office instanceof OfficeSpace)) { - throw new Error( - `Current City (${props.currentCity}) for UI does not have an OfficeSpace object`, - ); - } - - // If we're in a new city, we have to reset the state - if (division.name !== divisionName || props.currentCity !== city) { - resetEmployeeCount(); - setDivisionName(division.name); - setCity(props.currentCity); - } - // Calculate how many NEW employees we need to account for - const currentNumEmployees = office.employees.length; + const currentNumEmployees = props.office.employees.length; let newOperations = numOperations; let newEngineers = numEngineers; @@ -83,8 +61,8 @@ export function IndustryOffice(props: IProps): React.ReactElement { let newTraining = numTraining; // Record the number of employees in each position, for NEW employees only - for (let i = numEmployees; i < office.employees.length; ++i) { - switch (office.employees[i].pos) { + for (let i = numEmployees; i < props.office.employees.length; ++i) { + switch (props.office.employees[i].pos) { case EmployeePositions.Operations: newOperations++; break; @@ -108,7 +86,7 @@ export function IndustryOffice(props: IProps): React.ReactElement { break; default: console.error( - "Unrecognized employee position: " + office.employees[i].pos, + "Unrecognized employee position: " + props.office.employees[i].pos, ); break; } @@ -139,10 +117,6 @@ export function IndustryOffice(props: IProps): React.ReactElement { } function renderAutomaticEmployeeManagement(): React.ReactElement { - const division = props.routing.currentDivision; // Validated in constructor - if (division === null) return <>; - const office = division.offices[props.currentCity]; // Validated in constructor - if (office === 0) return <>; const vechain = props.corp.unlockUpgrades[4] === 1; // Has Vechain upgrade function switchModeOnClick(): void { @@ -156,26 +130,24 @@ export function IndustryOffice(props: IProps): React.ReactElement { totalHappiness = 0, totalEnergy = 0, totalSalary = 0; - for (let i = 0; i < office.employees.length; ++i) { - totalMorale += office.employees[i].mor; - totalHappiness += office.employees[i].hap; - totalEnergy += office.employees[i].ene; - totalSalary += office.employees[i].sal; + for (let i = 0; i < props.office.employees.length; ++i) { + totalMorale += props.office.employees[i].mor; + totalHappiness += props.office.employees[i].hap; + totalEnergy += props.office.employees[i].ene; + totalSalary += props.office.employees[i].sal; } let avgMorale = 0, avgHappiness = 0, avgEnergy = 0; - if (office.employees.length > 0) { - avgMorale = totalMorale / office.employees.length; - avgHappiness = totalHappiness / office.employees.length; - avgEnergy = totalEnergy / office.employees.length; + if (props.office.employees.length > 0) { + avgMorale = totalMorale / props.office.employees.length; + avgHappiness = totalHappiness / props.office.employees.length; + avgEnergy = totalEnergy / props.office.employees.length; } // Helper functions for (re-)assigning employees to different positions function assignEmployee(to: string): void { - if (office === 0) return; - if (division === null) return; if (numUnassigned <= 0) { console.warn( "Cannot assign employee. No unassigned employees available", @@ -211,14 +183,12 @@ export function IndustryOffice(props: IProps): React.ReactElement { } setNumUnassigned((n) => n - 1); - office.assignEmployeeToJob(to); - office.calculateEmployeeProductivity(props.corp, division); + props.office.assignEmployeeToJob(to); + props.office.calculateEmployeeProductivity(props.corp, props.division); props.corp.rerender(props.player); } function unassignEmployee(from: string): void { - if (office === 0) return; - if (division === null) return; function logWarning(pos: string): void { console.warn( `Cannot unassign from ${pos} because there is nobody assigned to that position`, @@ -271,8 +241,8 @@ export function IndustryOffice(props: IProps): React.ReactElement { } setNumUnassigned((n) => n + 1); - office.unassignEmployeeFromJob(from); - office.calculateEmployeeProductivity(props.corp, division); + props.office.unassignEmployeeFromJob(from); + props.office.calculateEmployeeProductivity(props.corp, props.division); props.corp.rerender(props.player); } @@ -375,7 +345,7 @@ export function IndustryOffice(props: IProps): React.ReactElement {

Material Production:{" "} {numeralWrapper.format( - division.getOfficeProductivity(office), + props.division.getOfficeProductivity(props.office), "0.000", )} @@ -391,7 +361,9 @@ export function IndustryOffice(props: IProps): React.ReactElement {

Product Production:{" "} {numeralWrapper.format( - division.getOfficeProductivity(office, { forProduct: true }), + props.division.getOfficeProductivity(props.office, { + forProduct: true, + }), "0.000", )} @@ -406,7 +378,10 @@ export function IndustryOffice(props: IProps): React.ReactElement { {vechain && (

Business Multiplier: x - {numeralWrapper.format(division.getBusinessFactor(office), "0.000")} + {numeralWrapper.format( + props.division.getBusinessFactor(props.office), + "0.000", + )} The effect this office's 'Business' employees has on boosting sales @@ -542,12 +517,6 @@ export function IndustryOffice(props: IProps): React.ReactElement { } function renderManualEmployeeManagement(): React.ReactElement { - const corp = props.corp; - const division = props.routing.currentDivision; // Validated in constructor - if (division === null) return <>; - const office = division.offices[props.currentCity]; // Validated in constructor - if (office === 0) return <>; - function switchModeOnClick(): void { setEmployeeManualAssignMode(false); props.corp.rerender(props.player); @@ -561,10 +530,10 @@ export function IndustryOffice(props: IProps): React.ReactElement { // Employee Selector const employees = []; - for (let i = 0; i < office.employees.length; ++i) { + for (let i = 0; i < props.office.employees.length; ++i) { employees.push( - , ); } @@ -572,16 +541,15 @@ export function IndustryOffice(props: IProps): React.ReactElement { function employeeSelectorOnChange( e: React.ChangeEvent, ): void { - if (office === 0) return; const name = getSelectText(e.target); - for (let i = 0; i < office.employees.length; ++i) { - if (name === office.employees[i].name) { - setEmployee(office.employees[i]); + for (let i = 0; i < props.office.employees.length; ++i) { + if (name === props.office.employees[i].name) { + setEmployee(props.office.employees[i]); break; } } - corp.rerender(props.player); + props.corp.rerender(props.player); } // Employee Positions Selector @@ -607,7 +575,7 @@ export function IndustryOffice(props: IProps): React.ReactElement { const pos = getSelectText(e.target); employee.pos = pos; resetEmployeeCount(); - corp.rerender(props.player); + props.corp.rerender(props.player); } // Numeraljs formatter @@ -616,23 +584,23 @@ export function IndustryOffice(props: IProps): React.ReactElement { // Employee stats (after applying multipliers) const effCre = emp ? emp.cre * - corp.getEmployeeCreMultiplier() * - division.getEmployeeCreMultiplier() + props.corp.getEmployeeCreMultiplier() * + props.division.getEmployeeCreMultiplier() : 0; const effCha = emp ? emp.cha * - corp.getEmployeeChaMultiplier() * - division.getEmployeeChaMultiplier() + props.corp.getEmployeeChaMultiplier() * + props.division.getEmployeeChaMultiplier() : 0; const effInt = emp ? emp.int * - corp.getEmployeeIntMultiplier() * - division.getEmployeeIntMultiplier() + props.corp.getEmployeeIntMultiplier() * + props.division.getEmployeeIntMultiplier() : 0; const effEff = emp ? emp.eff * - corp.getEmployeeEffMultiplier() * - division.getEmployeeEffMultiplier() + props.corp.getEmployeeEffMultiplier() * + props.division.getEmployeeEffMultiplier() : 0; return ( @@ -682,30 +650,25 @@ export function IndustryOffice(props: IProps): React.ReactElement { ); } - const division = props.routing.currentDivision; // Validated in constructor - if (division === null) return <>; - const office = division.offices[props.currentCity]; // Validated in constructor - if (office === 0) return <>; const buttonStyle = { fontSize: "13px", }; // Hire Employee button let hireEmployeeButtonClass = "tooltip"; - if (office.atCapacity()) { + if (props.office.atCapacity()) { hireEmployeeButtonClass += " a-link-button-inactive"; } else { hireEmployeeButtonClass += " std-button"; - if (office.employees.length === 0) { + if (props.office.employees.length === 0) { hireEmployeeButtonClass += " flashing-button"; } } function openHireEmployeePopup(): void { - if (office === 0) return; const popupId = "cmpy-mgmt-hire-employee-popup"; createPopup(popupId, HireEmployeePopup, { - office: office, + office: props.office, corp: props.corp, popupId: popupId, player: props.player, @@ -714,23 +677,21 @@ export function IndustryOffice(props: IProps): React.ReactElement { // Autohire employee button let autohireEmployeeButtonClass = "tooltip"; - if (office.atCapacity()) { + if (props.office.atCapacity()) { autohireEmployeeButtonClass += " a-link-button-inactive"; } else { autohireEmployeeButtonClass += " std-button"; } function autohireEmployeeButtonOnClick(): void { - if (office === 0) return; - if (office.atCapacity()) return; - office.hireRandomEmployee(); + if (props.office.atCapacity()) return; + props.office.hireRandomEmployee(); props.corp.rerender(props.player); } function openUpgradeOfficeSizePopup(): void { - if (office === 0) return; const popupId = "cmpy-mgmt-upgrade-office-size-popup"; createPopup(popupId, UpgradeOfficeSizePopup, { - office: office, + office: props.office, corp: props.corp, popupId: popupId, player: props.player, @@ -738,10 +699,9 @@ export function IndustryOffice(props: IProps): React.ReactElement { } function openThrowPartyPopup(): void { - if (office === 0) return; const popupId = "cmpy-mgmt-throw-office-party-popup"; createPopup(popupId, ThrowPartyPopup, { - office: office, + office: props.office, corp: props.corp, popupId: popupId, }); @@ -751,7 +711,7 @@ export function IndustryOffice(props: IProps): React.ReactElement {

Office Space

- Size: {office.employees.length} / {office.size} employees + Size: {props.office.employees.length} / {props.office.size} employees

- {!division.hasResearch("AutoPartyManager") && ( + {!props.division.hasResearch("AutoPartyManager") && ( @@ -119,16 +117,13 @@ export function IndustryOverview(props: IProps): React.ReactElement { } function renderText(): React.ReactElement { - const corp = props.corp; - const division = props.routing.currentDivision; // Validated inside render() - if (division === null) return <>; - const vechain = corp.unlockUpgrades[4] === 1; - const profit = division.lastCycleRevenue - .minus(division.lastCycleExpenses) + const vechain = props.corp.unlockUpgrades[4] === 1; + const profit = props.division.lastCycleRevenue + .minus(props.division.lastCycleExpenses) .toNumber(); let advertisingInfo = false; - const advertisingFactors = division.getAdvertisingFactors(); + const advertisingFactors = props.division.getAdvertisingFactors(); const awarenessFac = advertisingFactors[1]; const popularityFac = advertisingFactors[2]; const ratioFac = advertisingFactors[3]; @@ -138,7 +133,6 @@ export function IndustryOverview(props: IProps): React.ReactElement { } function productionMultHelpTipOnClick(): void { - if (division === null) return; // Wrapper for createProgressBarText() // Converts the industry's "effectiveness factors" // into a graphic (string) depicting how high that effectiveness is @@ -163,34 +157,41 @@ export function IndustryOverview(props: IProps): React.ReactElement { "Below are approximations for how effective each material is at boosting " + "this industry's production multiplier (Bigger bars = more effective):

" + `Hardware:    ${convertEffectFacToGraphic( - division.hwFac, + props.division.hwFac, )}
` + `Robots:      ${convertEffectFacToGraphic( - division.robFac, + props.division.robFac, )}
` + `AI Cores:    ${convertEffectFacToGraphic( - division.aiFac, + props.division.aiFac, )}
` + - `Real Estate: ${convertEffectFacToGraphic(division.reFac)}`, + `Real Estate: ${convertEffectFacToGraphic(props.division.reFac)}`, ); } function openResearchPopup(): void { - if (division === null) return; const popupId = "corporation-research-popup-box"; createPopup(popupId, ResearchPopup, { - industry: division, + industry: props.division, popupId: popupId, }); } return (
- Industry: {division.type} (Corp Funds:{" "} - ) + Industry: {props.division.type} (Corp Funds:{" "} + )

- Awareness: {numeralWrapper.format(division.awareness, "0.000")}
- Popularity: {numeralWrapper.format(division.popularity, "0.000")}
+ Awareness: {numeralWrapper.format( + props.division.awareness, + "0.000", + )}{" "} +
+ Popularity: {numeralWrapper.format( + props.division.popularity, + "0.000", + )}{" "} +
{advertisingInfo !== false && (

Advertising Multiplier: x @@ -213,16 +214,17 @@ export function IndustryOverview(props: IProps): React.ReactElement { {advertisingInfo}

- Revenue: / s{" "} -
+ Revenue: / + s
Expenses: /s
+ money={props.division.lastCycleExpenses.toNumber()} + />{" "} + /s
Profit: / s

Production Multiplier:{" "} - {numeralWrapper.format(division.prodMult, "0.00")} + {numeralWrapper.format(props.division.prodMult, "0.00")} Production gain from owning production-boosting materials such as hardware, Robots, AI Cores, and Real Estate @@ -234,7 +236,7 @@ export function IndustryOverview(props: IProps): React.ReactElement {

Scientific Research:{" "} - {numeralWrapper.format(division.sciResearch.qty, "0.000a")} + {numeralWrapper.format(props.division.sciResearch.qty, "0.000a")} Scientific Research increases the quality of the materials and products that you produce. @@ -248,22 +250,12 @@ export function IndustryOverview(props: IProps): React.ReactElement { } function renderUpgrades(): React.ReactElement[] { - const corp = props.corp; - const division = props.routing.currentDivision; // Validated inside render() - if (division === null) return [<>]; - const office = division.offices[props.currentCity]; - if (!(office instanceof OfficeSpace)) { - throw new Error( - `Current City (${props.currentCity}) for UI does not have an OfficeSpace object`, - ); - } - const upgrades = []; for (const index in IndustryUpgrades) { const upgrade = IndustryUpgrades[index]; // AutoBrew research disables the Coffee upgrade - if (division.hasResearch("AutoBrew") && upgrade[4] === "Coffee") { + if (props.division.hasResearch("AutoBrew") && upgrade[4] === "Coffee") { continue; } @@ -273,26 +265,24 @@ export function IndustryOverview(props: IProps): React.ReactElement { let cost = 0; switch (i) { case 0: //Coffee, cost is static per employee - cost = office.employees.length * baseCost; + cost = props.office.employees.length * baseCost; break; default: - cost = baseCost * Math.pow(priceMult, division.upgrades[i]); + cost = baseCost * Math.pow(priceMult, props.division.upgrades[i]); break; } function onClick(): void { - if (office === 0) return; - if (division === null) return; - if (corp.funds.lt(cost)) { + if (props.corp.funds.lt(cost)) { dialogBoxCreate("Insufficient funds"); } else { - corp.funds = corp.funds.minus(cost); - division.upgrade(upgrade, { - corporation: corp, - office: office, + props.corp.funds = props.corp.funds.minus(cost); + props.division.upgrade(upgrade, { + corporation: props.corp, + office: props.office, }); // corp.displayDivisionContent(division, city); - corp.rerender(props.player); + props.corp.rerender(props.player); } } @@ -335,11 +325,6 @@ export function IndustryOverview(props: IProps): React.ReactElement { ); } - const division = props.routing.currentDivision; - if (division == null) { - throw new Error(`Routing does not hold reference to the current Industry`); - } - const makeProductButton = renderMakeProductButton(); return ( @@ -351,7 +336,7 @@ export function IndustryOverview(props: IProps): React.ReactElement {
{renderUpgrades()}
- {division.makesProducts && makeProductButton} + {props.division.makesProducts && makeProductButton}

); } diff --git a/src/Corporation/ui/IndustryWarehouse.tsx b/src/Corporation/ui/IndustryWarehouse.tsx index ff150d49d..11a3feb36 100644 --- a/src/Corporation/ui/IndustryWarehouse.tsx +++ b/src/Corporation/ui/IndustryWarehouse.tsx @@ -23,7 +23,6 @@ import { createPopup } from "../../ui/React/createPopup"; import { isString } from "../../../utils/helpers/isString"; import { ICorporation } from "../ICorporation"; import { IIndustry } from "../IIndustry"; -import { CorporationRouting } from "./Routing"; import { IPlayer } from "../../PersonObjects/IPlayer"; import { SetSmartSupply } from "../Actions"; @@ -438,7 +437,8 @@ function MaterialComponent(props: IMaterialProps): React.ReactElement { interface IProps { corp: ICorporation; - routing: CorporationRouting; + division: IIndustry; + warehouse: Warehouse | 0; currentCity: string; player: IPlayer; } @@ -464,53 +464,49 @@ export function IndustryWarehouse(props: IProps): React.ReactElement { } function renderWarehouseUI(): React.ReactElement { - const corp = props.corp; - const division = props.routing.currentDivision; // Validated in render() - if (division === null) return <>; - const warehouse = division.warehouses[props.currentCity]; // Validated in render() - if (warehouse === 0) return <>; - + if (props.warehouse === 0) return <>; // General Storage information at the top const sizeUsageStyle = { - color: warehouse.sizeUsed >= warehouse.size ? "red" : "white", + color: props.warehouse.sizeUsed >= props.warehouse.size ? "red" : "white", margin: "5px", }; // Upgrade Warehouse size button const sizeUpgradeCost = CorporationConstants.WarehouseUpgradeBaseCost * - Math.pow(1.07, warehouse.level + 1); - const canAffordUpgrade = corp.funds.gt(sizeUpgradeCost); + Math.pow(1.07, props.warehouse.level + 1); + const canAffordUpgrade = props.corp.funds.gt(sizeUpgradeCost); const upgradeWarehouseClass = canAffordUpgrade ? "std-button" : "a-link-button-inactive"; function upgradeWarehouseOnClick(): void { - if (division === null) return; - if (warehouse === 0) return; - ++warehouse.level; - warehouse.updateSize(corp, division); - corp.funds = corp.funds.minus(sizeUpgradeCost); - corp.rerender(props.player); + if (props.division === null) return; + if (props.warehouse === 0) return; + ++props.warehouse.level; + props.warehouse.updateSize(props.corp, props.division); + props.corp.funds = props.corp.funds.minus(sizeUpgradeCost); + props.corp.rerender(props.player); } // Industry material Requirements let generalReqsText = "This Industry uses [" + - Object.keys(division.reqMats).join(", ") + + Object.keys(props.division.reqMats).join(", ") + "] in order to "; - if (division.prodMats.length > 0) { - generalReqsText += "produce [" + division.prodMats.join(", ") + "] "; - if (division.makesProducts) { - generalReqsText += " and " + division.getProductDescriptionText(); + if (props.division.prodMats.length > 0) { + generalReqsText += + "produce [" + props.division.prodMats.join(", ") + "] "; + if (props.division.makesProducts) { + generalReqsText += " and " + props.division.getProductDescriptionText(); } - } else if (division.makesProducts) { - generalReqsText += division.getProductDescriptionText() + "."; + } else if (props.division.makesProducts) { + generalReqsText += props.division.getProductDescriptionText() + "."; } const ratioLines = []; - for (const matName in division.reqMats) { - if (division.reqMats.hasOwnProperty(matName)) { - const text = [" *", division.reqMats[matName], matName].join(" "); + for (const matName in props.division.reqMats) { + if (props.division.reqMats.hasOwnProperty(matName)) { + const text = [" *", props.division.reqMats[matName], matName].join(" "); ratioLines.push(

{text}

@@ -520,19 +516,21 @@ export function IndustryWarehouse(props: IProps): React.ReactElement { } let createdItemsText = "in order to create "; - if (division.prodMats.length > 0) { + if (props.division.prodMats.length > 0) { createdItemsText += - "one of each produced Material (" + division.prodMats.join(", ") + ") "; - if (division.makesProducts) { + "one of each produced Material (" + + props.division.prodMats.join(", ") + + ") "; + if (props.division.makesProducts) { createdItemsText += "or to create one of its Products"; } - } else if (division.makesProducts) { + } else if (props.division.makesProducts) { createdItemsText += "one of its Products"; } // Current State: let stateText; - switch (division.state) { + switch (props.division.state) { case "START": stateText = "Current state: Preparing..."; break; @@ -549,32 +547,32 @@ export function IndustryWarehouse(props: IProps): React.ReactElement { stateText = "Current state: Exporting materials and/or products..."; break; default: - console.error(`Invalid state: ${division.state}`); + console.error(`Invalid state: ${props.division.state}`); break; } // Smart Supply Checkbox const smartSupplyCheckboxId = "cmpy-mgmt-smart-supply-checkbox"; function smartSupplyOnChange(e: React.ChangeEvent): void { - if (warehouse === 0) return; - SetSmartSupply(warehouse, e.target.checked); - corp.rerender(props.player); + if (props.warehouse === 0) return; + SetSmartSupply(props.warehouse, e.target.checked); + props.corp.rerender(props.player); } // Create React components for materials const mats = []; - for (const matName in warehouse.materials) { - if (warehouse.materials[matName] instanceof Material) { + for (const matName in props.warehouse.materials) { + if (props.warehouse.materials[matName] instanceof Material) { // Only create UI for materials that are relevant for the industry - if (isRelevantMaterial(matName, division)) { + if (isRelevantMaterial(matName, props.division)) { mats.push( , ); } @@ -583,16 +581,19 @@ export function IndustryWarehouse(props: IProps): React.ReactElement { // Create React components for products const products = []; - if (division.makesProducts && Object.keys(division.products).length > 0) { - for (const productName in division.products) { - const product = division.products[productName]; + if ( + props.division.makesProducts && + Object.keys(props.division.products).length > 0 + ) { + for (const productName in props.division.products) { + const product = props.division.products[productName]; if (product instanceof Product) { products.push( , @@ -604,11 +605,11 @@ export function IndustryWarehouse(props: IProps): React.ReactElement { return (

- Storage: {numeralWrapper.formatBigNumber(warehouse.sizeUsed)} /{" "} - {numeralWrapper.formatBigNumber(warehouse.size)} + Storage: {numeralWrapper.formatBigNumber(props.warehouse.sizeUsed)} /{" "} + {numeralWrapper.formatBigNumber(props.warehouse.size)}

@@ -632,7 +633,7 @@ export function IndustryWarehouse(props: IProps): React.ReactElement {

{stateText}

- {corp.unlockUpgrades[1] && ( + {props.corp.unlockUpgrades[1] && (
)} @@ -654,12 +655,6 @@ export function IndustryWarehouse(props: IProps): React.ReactElement { ); } - const division = props.routing.currentDivision; - if (division == null) { - throw new Error(`Routing does not hold reference to the current Industry`); - } - const warehouse = division.warehouses[props.currentCity]; - function purchaseWarehouse(division: IIndustry, city: string): void { if (props.corp.funds.lt(CorporationConstants.WarehouseInitialCost)) { dialogBoxCreate("You do not have enough funds to do this!"); @@ -677,14 +672,14 @@ export function IndustryWarehouse(props: IProps): React.ReactElement { } } - if (warehouse instanceof Warehouse) { + if (props.warehouse instanceof Warehouse) { return renderWarehouseUI(); } else { return (
); } diff --git a/src/Corporation/ui/Routing.ts b/src/Corporation/ui/Routing.ts deleted file mode 100644 index fe0d97083..000000000 --- a/src/Corporation/ui/Routing.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { ICorporation } from "../ICorporation"; -import { IIndustry } from "../IIndustry"; - -export const overviewPage = "Overview"; - -/** - * Keeps track of what content is currently being displayed for the Corporation UI - */ -export class CorporationRouting { - private currentPage: string = overviewPage; - - // Stores a reference to the Corporation instance - private corp: ICorporation; - - // Stores a reference to the Division instance that the routing is currently on - // This will be null if routing is on the overview page - currentDivision: IIndustry | null = null; - - constructor(corp: ICorporation) { - this.corp = corp; - } - - current(): string { - return this.currentPage; - } - - /** - * Checks that the specified page has a valid value - */ - isValidPage(page: string): boolean { - if (page === overviewPage) { - return true; - } - - for (const division of this.corp.divisions) { - if (division.name === page) { - return true; - } - } - - return false; - } - - /** - * Returns a boolean indicating whether or not the player is on the given page - */ - isOn(page: string): boolean { - if (!this.isValidPage(page)) { - return false; - } - - return page === this.currentPage; - } - - isOnOverviewPage(): boolean { - return this.currentPage === overviewPage; - } - - /** - * Routes to the specified page - */ - routeTo(page: string): void { - if (!this.isValidPage(page)) { - return; - } - - this.currentDivision = null; - if (page !== overviewPage) { - // Iterate through Corporation data to get a reference to the current division - for (let i = 0; i < this.corp.divisions.length; ++i) { - if (this.corp.divisions[i].name === page) { - this.currentDivision = this.corp.divisions[i]; - } - } - - // 'currentDivision' should not be null, since the routing is either on - // the overview page or a division page - if (this.currentDivision == null) { - console.warn(`Routing could not find division ${page}`); - } - } - - this.currentPage = page; - } - - routeToOverviewPage(): void { - this.currentPage = overviewPage; - this.currentDivision = null; - } -} diff --git a/src/Corporation/ui/SellProductPopup.tsx b/src/Corporation/ui/SellProductPopup.tsx index 101d8369a..b50d7b49a 100644 --- a/src/Corporation/ui/SellProductPopup.tsx +++ b/src/Corporation/ui/SellProductPopup.tsx @@ -1,7 +1,6 @@ import React, { useState } from "react"; import { dialogBoxCreate } from "../../../utils/DialogBox"; import { removePopup } from "../../ui/React/createPopup"; -import { Cities } from "../../Locations/Cities"; import { Product } from "../Product"; import { SellProduct } from "../Actions"; diff --git a/src/Corporation/ui/UnlockUpgrade.tsx b/src/Corporation/ui/UnlockUpgrade.tsx index a14466e5b..6198f5c5d 100644 --- a/src/Corporation/ui/UnlockUpgrade.tsx +++ b/src/Corporation/ui/UnlockUpgrade.tsx @@ -1,7 +1,6 @@ // React Components for the Unlock upgrade buttons on the overview page import React from "react"; -import { numeralWrapper } from "../../ui/numeralFormat"; import { dialogBoxCreate } from "../../../utils/DialogBox"; import { CorporationUnlockUpgrade } from "../data/CorporationUnlockUpgrades"; import { ICorporation } from "../ICorporation"; diff --git a/src/DevMenu.jsx b/src/DevMenu.jsx index bbcb9bd52..010d221db 100644 --- a/src/DevMenu.jsx +++ b/src/DevMenu.jsx @@ -746,8 +746,7 @@ class DevMenuComponent extends Component { } let sourceFiles = []; - validSFN.forEach((i) => - sourceFiles.push( + validSFN.forEach((i) => sourceFiles.push( SF-{i}: diff --git a/src/Diagnostic/FileDiagnosticPopup.tsx b/src/Diagnostic/FileDiagnosticPopup.tsx index 7287a1d87..9f456c914 100644 --- a/src/Diagnostic/FileDiagnosticPopup.tsx +++ b/src/Diagnostic/FileDiagnosticPopup.tsx @@ -1,7 +1,5 @@ import React from "react"; import { AllServers } from "../Server/AllServers"; -import { Script } from "../Script/Script"; -import { TextFile } from "../TextFile"; import { Accordion } from "../ui/React/Accordion"; import { numeralWrapper } from "../ui/numeralFormat"; @@ -61,9 +59,7 @@ export function ServerAccordion(props: IServerProps): React.ReactElement { ); } -interface IProps {} - -export function FileDiagnosticPopup(props: IProps): React.ReactElement { +export function FileDiagnosticPopup(): React.ReactElement { const ips: string[] = []; for (const ip of Object.keys(AllServers)) { ips.push(ip); diff --git a/src/Faction/Faction.ts b/src/Faction/Faction.ts index 368ff91d4..79dab3ca0 100644 --- a/src/Faction/Faction.ts +++ b/src/Faction/Faction.ts @@ -1,4 +1,3 @@ -import { CONSTANTS } from "../Constants"; import { FactionInfo, FactionInfos } from "./FactionInfo"; import { favorToRep, repToFavor } from "./formulas/favor"; import { diff --git a/src/Faction/ui/AugmentationsPage.tsx b/src/Faction/ui/AugmentationsPage.tsx index a0505b913..3c55e44ed 100644 --- a/src/Faction/ui/AugmentationsPage.tsx +++ b/src/Faction/ui/AugmentationsPage.tsx @@ -124,8 +124,7 @@ export class AugmentationsPage extends React.Component { render(): React.ReactNode { const augs = this.getAugsSorted(); const purchasable = augs.filter( - (aug: string) => - aug === AugmentationNames.NeuroFluxGovernor || + (aug: string) => aug === AugmentationNames.NeuroFluxGovernor || (!this.props.p.augmentations.some((a) => a.name === aug) && !this.props.p.queuedAugmentations.some((a) => a.name === aug)), ); @@ -142,8 +141,7 @@ export class AugmentationsPage extends React.Component { ); }; - const augListElems = purchasable.map((aug) => - purchaseableAugmentation(aug), + const augListElems = purchasable.map((aug) => purchaseableAugmentation(aug), ); let ownedElem = <>; @@ -172,20 +170,17 @@ export class AugmentationsPage extends React.Component { will enhance your abilities.

- this.switchSortOrder(PurchaseAugmentationsOrderSetting.Cost) + onClick={() => this.switchSortOrder(PurchaseAugmentationsOrderSetting.Cost) } text={"Sort by Cost"} /> - this.switchSortOrder(PurchaseAugmentationsOrderSetting.Reputation) + onClick={() => this.switchSortOrder(PurchaseAugmentationsOrderSetting.Reputation) } text={"Sort by Reputation"} /> - this.switchSortOrder(PurchaseAugmentationsOrderSetting.Default) + onClick={() => this.switchSortOrder(PurchaseAugmentationsOrderSetting.Default) } text={"Sort by Default Order"} /> diff --git a/src/Faction/ui/DonateOption.tsx b/src/Faction/ui/DonateOption.tsx index 56043a114..aedfd7a1d 100644 --- a/src/Faction/ui/DonateOption.tsx +++ b/src/Faction/ui/DonateOption.tsx @@ -31,8 +31,6 @@ const inputStyleMarkup = { height: "26px", }; -const blockStyle = { display: "block" }; - export function DonateOption(props: IProps): React.ReactElement { const [donateAmt, setDonateAmt] = useState(null); const digits = (CONSTANTS.DonateMoneyToRepDivisor + "").length - 1; diff --git a/src/Gang/ui/GangMemberList.tsx b/src/Gang/ui/GangMemberList.tsx index 8815f1a89..ecb5b36c9 100644 --- a/src/Gang/ui/GangMemberList.tsx +++ b/src/Gang/ui/GangMemberList.tsx @@ -33,8 +33,7 @@ export function GangMemberList(props: IProps): React.ReactElement { } const members = props.gang.members.filter( - (member: GangMember) => - member.name.indexOf(filter) > -1 || member.task.indexOf(filter) > -1, + (member: GangMember) => member.name.indexOf(filter) > -1 || member.task.indexOf(filter) > -1, ); return ( diff --git a/src/Gang/ui/TerritorySubpage.tsx b/src/Gang/ui/TerritorySubpage.tsx index 52b50c76a..c3467909d 100644 --- a/src/Gang/ui/TerritorySubpage.tsx +++ b/src/Gang/ui/TerritorySubpage.tsx @@ -90,8 +90,7 @@ export function TerritorySubpage(props: IProps): React.ReactElement { id="warfare" type="checkbox" style={{ display: "inline-block", margin: "2px" }} - onChange={(event) => - (props.gang.territoryWarfareEngaged = event.target.checked) + onChange={(event) => (props.gang.territoryWarfareEngaged = event.target.checked) } />