From c9eb4bcd9e3c8d2dddd9811819c84169930fa64f Mon Sep 17 00:00:00 2001 From: fisker Cheung Date: Sun, 21 Dec 2025 23:44:08 +0800 Subject: [PATCH] Remove useless `u` flags in regular expressions (#18509) --- benchmarks/trim-indentation.js | 5 +- eslint.config.js | 6 ++ scripts/build/builders/javascript-module.js | 4 +- scripts/build/hacks/build-oxc-wasm-parser.js | 2 +- .../build/hacks/esmify-typescript-eslint.js | 18 ++-- .../build/hacks/modify-typescript-module.js | 6 +- .../build/packages/prettier-package-json.js | 6 +- scripts/build/packages/prettier.js | 56 +++++----- .../create-method-call-transform.js | 2 +- scripts/draft-blog-post.js | 2 +- .../generate-flow-estree-type-definition.js | 8 +- .../generate-unused-typescript-specifiers.js | 2 +- scripts/lint-changelog.js | 10 +- scripts/nodejs-14-test-loader.js | 2 +- scripts/production-eslint-config.js | 2 +- .../release/steps/update-dependents-count.js | 8 +- scripts/release/steps/update-version.js | 8 +- scripts/tools/bundle-test/index.js | 2 +- scripts/utilities/changelog.js | 16 +-- src/cli/context.js | 2 +- src/cli/format.js | 2 +- src/cli/logger.js | 2 +- src/cli/usage.js | 2 +- src/common/end-of-line.js | 8 +- src/language-css/clean.js | 14 +-- src/language-css/loc.js | 4 +- src/language-css/parse/parse-selector.js | 2 +- src/language-css/parse/parse-value.js | 2 +- src/language-css/parser-postcss.js | 12 +-- src/language-css/print/misc.js | 14 +-- src/language-css/printer-postcss.js | 20 ++-- src/language-css/utilities/index.js | 8 +- .../utilities/is-scss-nested-property-node.js | 4 +- src/language-graphql/printer-graphql.js | 2 +- src/language-handlebars/parser-glimmer.js | 10 +- src/language-handlebars/printer-glimmer.js | 16 +-- src/language-handlebars/utilities.js | 2 +- src/language-html/clean.js | 4 +- src/language-html/constants.evaluate.js | 4 +- src/language-html/embed.js | 4 +- src/language-html/embed/angular-attributes.js | 6 +- .../angular-control-flow-block-parameters.js | 2 +- .../embed/angular-interpolation.js | 2 +- src/language-html/embed/class-names.js | 2 +- .../embed/vue-v-for-directive.js | 6 +- .../parse/conditional-comment.js | 10 +- src/language-html/parse/postprocess.js | 4 +- src/language-html/print-preprocess.js | 4 +- src/language-html/print/element.js | 1 - src/language-html/print/tag.js | 6 +- src/language-html/printer-html.js | 4 +- src/language-html/utilities/index.js | 6 +- src/language-js/clean.js | 4 +- src/language-js/comments/is-gap.js | 2 +- src/language-js/embed/css.js | 22 ++-- src/language-js/embed/graphql.js | 4 +- src/language-js/embed/html.js | 8 +- src/language-js/embed/markdown.js | 6 +- src/language-js/parentheses/identifier.js | 2 +- src/language-js/parse/acorn.js | 2 +- src/language-js/parse/babel.js | 4 +- src/language-js/parse/oxc.js | 4 +- src/language-js/parse/typescript.js | 2 +- .../parse/utilities/jsx-regexp.evaluate.js | 2 +- .../parse/utilities/source-types.js | 4 +- src/language-js/print/angular.js | 2 +- src/language-js/print/estree.js | 2 +- src/language-js/print/jsx.js | 10 +- src/language-js/print/mapped-type.js | 2 +- src/language-js/print/member-chain.js | 2 +- src/language-js/print/property.js | 4 +- src/language-js/print/template-literal.js | 8 +- src/language-js/print/type-parameters.js | 2 +- .../utilities/is-type-cast-comment.js | 2 +- src/language-markdown/clean.js | 4 +- src/language-markdown/parse/mdx.js | 8 +- .../parse/unified-plugins/liquid.js | 2 +- .../parse/unified-plugins/wiki-link.js | 2 +- src/language-markdown/print/mdast.js | 13 ++- src/language-markdown/print/preprocess.js | 4 +- src/language-markdown/print/word.js | 2 +- src/language-markdown/utilities.js | 14 ++- src/language-yaml/clean.js | 2 +- src/language-yaml/embed.js | 2 +- src/language-yaml/print/mapping-item.js | 4 +- src/language-yaml/printer-yaml.js | 2 +- src/language-yaml/utilities.js | 18 ++-- src/main/comments/attach.js | 4 +- src/main/core.js | 2 +- src/main/front-matter/parse.js | 2 +- src/main/range.js | 4 +- src/universal/index.browser.js | 2 +- src/utilities/get-indent-size.js | 2 +- src/utilities/get-interpreter.js | 4 +- src/utilities/get-max-continuous-count.js | 2 +- .../get-min-not-present-continuous-count.js | 2 +- src/utilities/get-string-width.js | 2 +- src/utilities/make-string.js | 2 +- src/utilities/pragma/pragma.evaluate.js | 15 +-- src/utilities/print-number.js | 10 +- src/utilities/print-string.js | 2 +- src/utilities/public.js | 4 +- src/utilities/skip.js | 4 +- src/utilities/whitespace-utilities.js | 7 +- tests/config/install-prettier.js | 6 +- .../prettier-plugin-async-printer/index.cjs | 2 +- tests/config/run-format-test.js | 4 +- .../utilities/consistent-end-of-line.js | 2 +- tests/config/utilities/create-snapshot.js | 2 +- .../config/utilities/visualize-end-of-line.js | 2 +- .../format/markdown/trim-space/format.test.js | 2 +- tests/integration/__tests__/cache.js | 100 +++++++++--------- .../__tests__/config-file-typescript.js | 6 +- tests/integration/__tests__/config-invalid.js | 2 +- .../__tests__/config-resolution.js | 6 +- tests/integration/__tests__/infer-parser.js | 4 +- tests/integration/__tests__/invalid-ignore.js | 2 +- tests/integration/__tests__/log-level.js | 2 +- tests/integration/__tests__/patterns-dirs.js | 4 +- .../__tests__/plugin-options-string.js | 2 +- .../__tests__/print-doc-to-string.js | 2 +- .../plugins/languages/is-supported.js | 2 +- tests/integration/run-cli.js | 2 +- tests/unit/whitespace-utilities.js | 2 +- website/playground/VersionLink.jsx | 4 +- website/playground/dummyId.js | 2 +- website/playground/index.jsx | 2 +- website/playground/markdown.js | 2 +- website/playground/utilities.js | 16 +-- website/plugins/llms-txt-plugin.mjs | 6 +- website/static/service-worker.mjs | 2 +- 131 files changed, 388 insertions(+), 405 deletions(-) diff --git a/benchmarks/trim-indentation.js b/benchmarks/trim-indentation.js index f5595d6a1..893ffdd96 100644 --- a/benchmarks/trim-indentation.js +++ b/benchmarks/trim-indentation.js @@ -13,12 +13,11 @@ for (const size of [1, 1e1, 1e2]) { }, { loop: () => trimIndentation(text).text, - "RegExp (inline)": () => text.replace(/[ \t]*$/u, ""), + "RegExp (inline)": () => text.replace(/[ \t]*$/, ""), "RegExp (stored)": ( (regexp) => () => text.replace(regexp, "") - )(/[ \t]*$/gu), - "RegExp (no `u` flag)": () => text.replace(/[ \t]*$/, ""), + )(/[ \t]*$/g), }, ); } diff --git a/eslint.config.js b/eslint.config.js index ef6336078..0844df824 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -140,6 +140,12 @@ const configs = [ exceptRange: true, }, ], + "no-restricted-syntax": [ + "error", + // Forbid `u` flag in regexp, kept for refactoring + // "Literal[regex.flags=/u/]", + // 'NewExpression[callee.name="RegExp"] > Literal.arguments:nth-child(2)[value=/u/]', + ], // Internal rules "prettier-internal-rules/jsx-identifier-case": "error", diff --git a/scripts/build/builders/javascript-module.js b/scripts/build/builders/javascript-module.js index 27998b6a4..4c687ff8b 100644 --- a/scripts/build/builders/javascript-module.js +++ b/scripts/build/builders/javascript-module.js @@ -49,7 +49,7 @@ function getEsbuildOptions({ packageConfig, file, cliOptions, buildOptions }) { process(text) { const exports = [ ...text.matchAll( - /(?<=\n)exports\.(?\w+) = \k;/gu, + /(?<=\n)exports\.(?\w+) = \k;/g, ), ].map((match) => match.groups.specifier); @@ -93,7 +93,7 @@ function getEsbuildOptions({ packageConfig, file, cliOptions, buildOptions }) { // #12493, not sure what the problem is, but replace the cjs version with esm version seems fix it { module: require.resolve("tslib"), - path: require.resolve("tslib").replace(/tslib\.js$/u, "tslib.es6.js"), + path: require.resolve("tslib").replace(/tslib\.js$/, "tslib.es6.js"), }, // https://github.com/evanw/esbuild/issues/2103 { diff --git a/scripts/build/hacks/build-oxc-wasm-parser.js b/scripts/build/hacks/build-oxc-wasm-parser.js index 48e659077..0c7f2f9ef 100644 --- a/scripts/build/hacks/build-oxc-wasm-parser.js +++ b/scripts/build/hacks/build-oxc-wasm-parser.js @@ -61,7 +61,7 @@ async function inlineWasmBinary(directory) { `; text = text.replaceAll( - /new URL\((?".*?"), import\.meta\.url\)/gu, + /new URL\((?".*?"), import\.meta\.url\)/g, "{/* $ */}", ); diff --git a/scripts/build/hacks/esmify-typescript-eslint.js b/scripts/build/hacks/esmify-typescript-eslint.js index 5fd45bbce..9393752b2 100644 --- a/scripts/build/hacks/esmify-typescript-eslint.js +++ b/scripts/build/hacks/esmify-typescript-eslint.js @@ -17,7 +17,7 @@ function esmifyTypescriptEslint(text) { */ text = text.replaceAll( // TODO: Use duplicate capture group name when eslint supports - /(?<=\n)(?:const|let|var) (?\w+) = (?:__importStar\(require\(["'](?.*?)["']\)\)|require\(["'](?.*?)["']\));/gu, + /(?<=\n)(?:const|let|var) (?\w+) = (?:__importStar\(require\(["'](?.*?)["']\)\)|require\(["'](?.*?)["']\));/g, (...args) => { const groups = args.at(-1); return `import * as ${groups.variable} from "${groups.moduleName1 || groups.moduleName2}";`; @@ -35,7 +35,7 @@ function esmifyTypescriptEslint(text) { ```` */ text = text.replaceAll( - /(?<=\n)(?:const|let|var) (?\w+) = __importDefault\(require\(["'](?.*?)["']\)\);/gu, + /(?<=\n)(?:const|let|var) (?\w+) = __importDefault\(require\(["'](?.*?)["']\)\);/g, outdent` import $_default_export from "$"; const $ = {default: $_default_export}; @@ -57,9 +57,9 @@ function esmifyTypescriptEslint(text) { "", ); - text = text.replaceAll(/(?<=\n)(?:exports\.\w+ = )+void 0;/gu, ""); + text = text.replaceAll(/(?<=\n)(?:exports\.\w+ = )+void 0;/g, ""); text = text.replaceAll( - /(?<=\n)exports\.(?\w+) = (?\w+);/gu, + /(?<=\n)exports\.(?\w+) = (?\w+);/g, (...args) => { const { variable, specifier } = args.at(-1); if (specifier === variable) { @@ -71,7 +71,7 @@ function esmifyTypescriptEslint(text) { ); text = text.replaceAll( - /(?<=\n)exports\.(?\w+)(?= = `)/gu, + /(?<=\n)exports\.(?\w+)(?= = `)/g, "export const $", ); @@ -85,7 +85,7 @@ function esmifyTypescriptEslint(text) { ```` */ text = text.replaceAll( - /(?<=\n)__exportStar\(require\(["'](?.*?)["']\), exports\);/gu, + /(?<=\n)__exportStar\(require\(["'](?.*?)["']\), exports\);/g, 'export * from "$";', ); @@ -99,7 +99,7 @@ function esmifyTypescriptEslint(text) { ```` */ text = text.replaceAll( - /(?<=\n)Object\.defineProperty\(exports, "(?\w+)", \{ enumerable: true, get: function \(\) \{ return (?.*?); \} \}\);/gu, + /(?<=\n)Object\.defineProperty\(exports, "(?\w+)", \{ enumerable: true, get: function \(\) \{ return (?.*?); \} \}\);/g, "export const $ = $;", ); @@ -114,7 +114,7 @@ function esmifyTypescriptEslint(text) { ```` */ text = text.replaceAll( - /(?<=\n)exports\.(?\w+) = __importStar\(require\(["'](?.*?)["']\)\);/gu, + /(?<=\n)exports\.(?\w+) = __importStar\(require\(["'](?.*?)["']\)\);/g, outdent` import * as $_namespace_export from "$"; export {$_namespace_export as $}; @@ -136,7 +136,7 @@ function esmifyTypescriptEslint(text) { ``` */ text = text.replaceAll( - /(?<=\n\}\))\((?\S+) \|\| \(exports\.\k = \k = \{\}\)\);/gu, + /(?<=\n\}\))\((?\S+) \|\| \(exports\.\k = \k = \{\}\)\);/g, outdent` ($ ??= {}); export {$}; diff --git a/scripts/build/hacks/modify-typescript-module.js b/scripts/build/hacks/modify-typescript-module.js index 6b1976b94..545e34948 100644 --- a/scripts/build/hacks/modify-typescript-module.js +++ b/scripts/build/hacks/modify-typescript-module.js @@ -6,7 +6,7 @@ import { PROJECT_ROOT, writeFile } from "../../utilities/index.js"; import UNUSED_SPECIFIERS from "./typescript-unused-specifiers.js"; function* getModules(text) { - const parts = text.split(/(?<=\n)(\/\/ src\/\S+\n)/u); + const parts = text.split(/(?<=\n)(\/\/ src\/\S+\n)/); let start = parts[0].length; @@ -73,7 +73,7 @@ class TypeScriptModuleSource { escapeStringRegexp(end), "(?=\n)", ].join(""), - "gsu", + "gs", ); this.#source.replaceAll(regexp, replacement); @@ -150,7 +150,7 @@ function getExports(entry) { const exports = lines .map((line) => { const match = line.match( - /^\s*(?.*?): \(\) => (?.*?),?$/u, + /^\s*(?.*?): \(\) => (?.*?),?$/, ); if (!match) { diff --git a/scripts/build/packages/prettier-package-json.js b/scripts/build/packages/prettier-package-json.js index 5bee07b9c..77f0ffbbf 100644 --- a/scripts/build/packages/prettier-package-json.js +++ b/scripts/build/packages/prettier-package-json.js @@ -26,11 +26,11 @@ function generatePackageJson(packageJson, { packageConfig }) { return [ isPlugin ? `./plugins/${basename}` : `./${basename}`, { - types: `./${file.output.replace(/\.js$/u, ".d.ts")}`, + types: `./${file.output.replace(/\.js$/, ".d.ts")}`, // `module-sync` condition can prevent CJS plugins from working: https://github.com/prettier/prettier/issues/17139 // Perform a test before re-adding it. require: `./${file.output}`, - default: `./${file.output.replace(/\.js$/u, ".mjs")}`, + default: `./${file.output.replace(/\.js$/, ".mjs")}`, }, ]; }), @@ -56,7 +56,7 @@ function generatePackageJson(packageJson, { packageConfig }) { [`./parser-${basename}.js`, `./${file.output}`], [ `./esm/parser-${basename}.mjs`, - `./${file.output.replace(/\.js$/u, ".mjs")}`, + `./${file.output.replace(/\.js$/, ".mjs")}`, ], ]; }), diff --git a/scripts/build/packages/prettier.js b/scripts/build/packages/prettier.js index c512ace9b..080205dfe 100644 --- a/scripts/build/packages/prettier.js +++ b/scripts/build/packages/prettier.js @@ -99,17 +99,17 @@ const mainModule = { ); text = text.replaceAll( - /(?<=\n)let tokenize;\n\{\n.*?\n\}(?=\n)/gsu, + /(?<=\n)let tokenize;\n\{\n.*?\n\}(?=\n)/gs, "", ); text = text.replaceAll( - /(?<=\n)function highlight\(text\) \{\n.*?\n\}(?=\n)/gsu, + /(?<=\n)function highlight\(text\) \{\n.*?\n\}(?=\n)/gs, "function highlight(text) {return text}", ); text = text.replaceAll( - /(?<=\n)function getDefs\(enabled\) \{\n.*?\n\}(?=\n)/gsu, + /(?<=\n)function getDefs\(enabled\) \{\n.*?\n\}(?=\n)/gs, outdent` function getDefs() { return new Proxy({}, {get: () => (text) => text}) @@ -269,7 +269,7 @@ const pluginFiles = [ module: require.resolve("@babel/parser"), process: (text) => text.replaceAll( - /const entity\s?=\s?entities\[desc\];/gu, + /const entity\s?=\s?entities\[desc\];/g, "const entity = undefined;", ), }, @@ -360,7 +360,7 @@ const pluginFiles = [ { module: "*", process(text, file) { - if (/require\(["'](?:typescript|ts-api-utils)["']\)/u.test(text)) { + if (/require\(["'](?:typescript|ts-api-utils)["']\)/.test(text)) { throw new Error(`Unexpected \`require("typescript")\` in ${file}.`); } @@ -476,7 +476,7 @@ const pluginFiles = [ process(text) { const typescriptVariables = [ ...text.matchAll( - /import (?\w+) from ["']typescript["']/gu, + /import (?\w+) from ["']typescript["']/g, ), ].map((match) => match.groups.variable); @@ -484,13 +484,13 @@ const pluginFiles = [ text = text.replaceAll( new RegExp( String.raw`".*?" in (?:${typescriptVariables.join("|")})(?=\W)`, - "gu", + "g", ), "true", ); text = text.replaceAll( - /(?<=import )(?=\w+ from ["']typescript["'])/gu, + /(?<=import )(?=\w+ from ["']typescript["'])/g, "* as ", ); @@ -601,10 +601,10 @@ const pluginFiles = [ ); text = text.replace("const _visitor = new _Visitor$2()", ""); text = text.replaceAll( - /const (.*?) = new BuiltinType\(BuiltinTypeName\..*?\);/gu, + /const (.*?) = new BuiltinType\(BuiltinTypeName\..*?\);/g, "const $1 = undefined;", ); - text = text.replaceAll(/var output_ast =.*?;\n/gsu, "var output_ast"); + text = text.replaceAll(/var output_ast =.*?;\n/gs, "var output_ast"); text = text.replace( "const serializer = new IcuSerializerVisitor();", @@ -616,62 +616,62 @@ const pluginFiles = [ ); text = text.replaceAll( - /function transformExpressionsInExpression\(.*?\n.*?\n\}\n/gsu, + /function transformExpressionsInExpression\(.*?\n.*?\n\}\n/gs, "function transformExpressionsInExpression(){}", ); text = text.replaceAll( - /const deferTriggerToR3TriggerInstructionsMap = new Map\(\[\n.*?\n\]\);\n/gsu, + /const deferTriggerToR3TriggerInstructionsMap = new Map\(\[\n.*?\n\]\);\n/gs, "const deferTriggerToR3TriggerInstructionsMap = undefined;", ); text = text.replaceAll( - /const BINARY_OPERATORS = new Map\(\[\n.*?\n\]\);\n/gsu, + /const BINARY_OPERATORS = new Map\(\[\n.*?\n\]\);\n/gs, "const BINARY_OPERATORS = undefined;", ); text = text.replaceAll( - /const PIPE_BINDINGS = \[\n.*?\n\];\n/gsu, + /const PIPE_BINDINGS = \[\n.*?\n\];\n/gs, "const PIPE_BINDINGS = undefined;", ); text = text.replaceAll( - /const TEXT_INTERPOLATE_CONFIG = \{\n.*?\n\};\n/gsu, + /const TEXT_INTERPOLATE_CONFIG = \{\n.*?\n\};\n/gs, "const TEXT_INTERPOLATE_CONFIG = undefined;", ); text = text.replaceAll( - /const CHAINABLE = new Set\(\[\n.*?\n\]\);\n/gsu, + /const CHAINABLE = new Set\(\[\n.*?\n\]\);\n/gs, "const CHAINABLE = undefined;", ); text = text.replaceAll( - /const PROPERTY_INTERPOLATE_CONFIG = \{\n.*?\n\};\n/gsu, + /const PROPERTY_INTERPOLATE_CONFIG = \{\n.*?\n\};\n/gs, "const PROPERTY_INTERPOLATE_CONFIG = undefined;", ); text = text.replaceAll( - /const STYLE_PROP_INTERPOLATE_CONFIG = \{\n.*?\n\};\n/gsu, + /const STYLE_PROP_INTERPOLATE_CONFIG = \{\n.*?\n\};\n/gs, "const STYLE_PROP_INTERPOLATE_CONFIG = undefined;", ); text = text.replaceAll( - /const ATTRIBUTE_INTERPOLATE_CONFIG = \{\n.*?\n\};\n/gsu, + /const ATTRIBUTE_INTERPOLATE_CONFIG = \{\n.*?\n\};\n/gs, "const ATTRIBUTE_INTERPOLATE_CONFIG = undefined;", ); text = text.replaceAll( - /const STYLE_MAP_INTERPOLATE_CONFIG = \{\n.*?\n\};\n/gsu, + /const STYLE_MAP_INTERPOLATE_CONFIG = \{\n.*?\n\};\n/gs, "const STYLE_MAP_INTERPOLATE_CONFIG = undefined;", ); text = text.replaceAll( - /const CLASS_MAP_INTERPOLATE_CONFIG = \{\n.*?\n\};\n/gsu, + /const CLASS_MAP_INTERPOLATE_CONFIG = \{\n.*?\n\};\n/gs, "const CLASS_MAP_INTERPOLATE_CONFIG = undefined;", ); text = text.replaceAll( - /const PURE_FUNCTION_CONFIG = \{\n.*?\n\};\n/gsu, + /const PURE_FUNCTION_CONFIG = \{\n.*?\n\};\n/gs, "const PURE_FUNCTION_CONFIG = undefined;", ); text = text.replaceAll( - /const NAMED_ENTITIES = \{\n.*?\n\};\n/gsu, + /const NAMED_ENTITIES = \{\n.*?\n\};\n/gs, "const NAMED_ENTITIES = {};", ); @@ -749,15 +749,15 @@ const pluginFiles = [ ); // This passed to plugins, our plugin don't need access to the options - text = text.replace(/(?<=\sconst syntax = )\{.*?\n\}(?=;\n)/su, "{}"); + text = text.replace(/(?<=\sconst syntax = )\{.*?\n\}(?=;\n)/s, "{}"); text = text.replaceAll( - /\sclass \S+ extends[(\s]+node\(.*?\).*?\{(?:\n.*?\n)?\}\n/gsu, + /\sclass \S+ extends[(\s]+node\(.*?\).*?\{(?:\n.*?\n)?\}\n/gs, "\n", ); text = text.replaceAll( - /\nvar api\S* = \s*(?:\/\*#__PURE__\*\/)?\s*Object\.freeze\(\{.*?\n\}\);/gsu, + /\nvar api\S* = \s*(?:\/\*#__PURE__\*\/)?\s*Object\.freeze\(\{.*?\n\}\);/gs, "", ); @@ -777,7 +777,7 @@ const pluginFiles = [ ); text = text.replace( - /(?<=\n)export .*?;/u, + /(?<=\n)export .*?;/, "export { preprocess, getVoidTags, visitorKeys };", ); @@ -801,7 +801,7 @@ function createPluginModule(file) { const { input, ...buildOptions } = file; const { pluginName } = input.match( - /\/plugins\/(?.*?)\.js$/u, + /\/plugins\/(?.*?)\.js$/, ).groups; const umdVariableName = `prettierPlugins.${pluginName}`; diff --git a/scripts/build/transform/transforms/create-method-call-transform.js b/scripts/build/transform/transforms/create-method-call-transform.js index f3aead2d2..7d26a900d 100644 --- a/scripts/build/transform/transforms/create-method-call-transform.js +++ b/scripts/build/transform/transforms/create-method-call-transform.js @@ -66,7 +66,7 @@ function transformMethodCallToFunctionCall(node, functionName) { function createMethodCallTransform({ methodName, argumentsLength }) { const functionName = `__${methodName}`; const fileName = `method-${methodName.replaceAll( - /[A-Z]/gu, + /[A-Z]/g, (character) => `-${character.toLowerCase()}`, )}.js`; const functionImplementationUrl = new URL( diff --git a/scripts/draft-blog-post.js b/scripts/draft-blog-post.js index 305924c3e..09e96971d 100644 --- a/scripts/draft-blog-post.js +++ b/scripts/draft-blog-post.js @@ -34,7 +34,7 @@ const nextVersion = `${semver.major(version)}.${semver.minor( const postGlob = path.join(blogDir, `????-??-??-${nextVersion}.md`); const postFile = path.join( blogDir, - `${new Date().toISOString().replace(/T.+/u, "")}-${nextVersion}.md`, + `${new Date().toISOString().replace(/T.+/, "")}-${nextVersion}.md`, ); const categoriesByDir = new Map( diff --git a/scripts/generate-flow-estree-type-definition.js b/scripts/generate-flow-estree-type-definition.js index 721e70b9e..b6d6cb650 100644 --- a/scripts/generate-flow-estree-type-definition.js +++ b/scripts/generate-flow-estree-type-definition.js @@ -66,20 +66,20 @@ function toDts(text) { text = text.replaceAll("'use strict';", " "); // `{+foo: string}` -> `{foo: string}` - text = text.replaceAll(/(?<=\n)(?[ {2}]+)\+/gu, "$"); + text = text.replaceAll(/(?<=\n)(?[ {2}]+)\+/g, "$"); // `{foo: interface {}}` -> `{foo: {}}` text = text.replaceAll(": interface {", ": {"); // `{foo: interface extends T {}}` -> `{foo: T & {}}` text = text.replaceAll( - /(?<=: )interface extends (?\w+)(?= \{)/gu, + /(?<=: )interface extends (?\w+)(?= \{)/g, "$ & ", ); // `$ReadOnlyArray` -> `ReadonlyArray` text = text.replaceAll( - /\$ReadOnlyArray<\?(\w+)>/gu, + /\$ReadOnlyArray<\?(\w+)>/g, "ReadonlyArray<$1 | null>", ); @@ -91,7 +91,7 @@ function toDts(text) { // `{[string]: T}` -> `{[key: string]: T}` text = text.replaceAll( - /(?<=\n)(?[ {2}]+)\[(?string)\](?=: )/gu, + /(?<=\n)(?[ {2}]+)\[(?string)\](?=: )/g, "$[key: $]", ); diff --git a/scripts/generate-unused-typescript-specifiers.js b/scripts/generate-unused-typescript-specifiers.js index f4cbb9e40..c93c800d4 100644 --- a/scripts/generate-unused-typescript-specifiers.js +++ b/scripts/generate-unused-typescript-specifiers.js @@ -19,7 +19,7 @@ async function getRemovedSpecifiers(code, exports) { const specifiers = []; for (const { text } of errors) { const match = text.match( - /^"(?.*?)" is not declared in this file$/u, + /^"(?.*?)" is not declared in this file$/, ); if (match) { diff --git a/scripts/lint-changelog.js b/scripts/lint-changelog.js index 26ceec1c6..9f5d61868 100644 --- a/scripts/lint-changelog.js +++ b/scripts/lint-changelog.js @@ -39,14 +39,14 @@ for (const file of [ } } -const authorRegex = /by @[\w-]+|by \[@([\w-]+)\]\(https:\/\/github\.com\/\1\)/u; -const titleRegex = /^#{4} (.*?)\((#\d{4,}|\[#\d{4,}\])/u; +const authorRegex = /by @[\w-]+|by \[@([\w-]+)\]\(https:\/\/github\.com\/\1\)/; +const titleRegex = /^#{4} (.*?)\((#\d{4,}|\[#\d{4,}\])/; const template = fs.readFileSync( new URL(TEMPLATE_FILE, CHANGELOG_ROOT), "utf8", ); -const templateComments = template.match(//gsu); +const templateComments = template.match(//gs); const [templateAuthorLink] = template.match(authorRegex); const checkedFiles = new Map(); @@ -63,7 +63,7 @@ for (const category of CHANGELOG_CATEGORIES) { continue; } - const match = prFile.match(/^(\d{4,})(-\d+)?\.md$/u); + const match = prFile.match(/^(\d{4,})(-\d+)?\.md$/); const displayPath = `${CHANGELOG_DIR}/${category}/${prFile}`; if (!match) { @@ -137,7 +137,7 @@ for (const category of CHANGELOG_CATEGORIES) { ); } - if (/prettier master/iu.test(content)) { + if (/prettier master/i.test(content)) { showErrorMessage( `[${displayPath}]: Please use "main" instead of "master".`, ); diff --git a/scripts/nodejs-14-test-loader.js b/scripts/nodejs-14-test-loader.js index 5e952883a..b3cb380e0 100644 --- a/scripts/nodejs-14-test-loader.js +++ b/scripts/nodejs-14-test-loader.js @@ -9,7 +9,7 @@ import esbuild from "esbuild"; export async function getSource(url, context, defaultGetSource) { if ( - !/node_modules\/@babel\/(?:code-frame|highlight)/u.test(url) || + !/node_modules\/@babel\/(?:code-frame|highlight)/.test(url) || context.format !== "module" ) { return defaultGetSource(url, context, defaultGetSource); diff --git a/scripts/production-eslint-config.js b/scripts/production-eslint-config.js index f74fbfa0e..c5f76b58c 100644 --- a/scripts/production-eslint-config.js +++ b/scripts/production-eslint-config.js @@ -13,7 +13,7 @@ const jsFiles = packageBuildConfigs .flatMap((packageConfig) => packageConfig.modules.flatMap((module) => module.files - .filter((file) => /\.[cm]?js$/u.test(file.output)) + .filter((file) => /\.[cm]?js$/.test(file.output)) .map((file) => path.join(packageConfig.distDirectory, file.output)), ), ) diff --git a/scripts/release/steps/update-dependents-count.js b/scripts/release/steps/update-dependents-count.js index 07dcd083f..ebd17a1be 100644 --- a/scripts/release/steps/update-dependents-count.js +++ b/scripts/release/steps/update-dependents-count.js @@ -7,7 +7,7 @@ async function getNpmDependentsCount() { fetchText("https://www.npmjs.com/package/prettier"), ); const dependentsCountNpm = Number( - npmPage.match(/"dependentsCount":"(?\d+)",/u).groups + npmPage.match(/"dependentsCount":"(?\d+)",/).groups .dependentsCount, ); if (Number.isNaN(dependentsCountNpm)) { @@ -28,7 +28,7 @@ async function getGithubDependentsCount() { githubPage .replaceAll("\n", "") .match( - /.*?<\/svg>\s*(?[\d,]+)\s*Repositories\s*<\/a>/u, + /.*?<\/svg>\s*(?[\d,]+)\s*Repositories\s*<\/a>/, ) .groups.dependentsCount.replaceAll(",", ""), ); @@ -54,14 +54,14 @@ async function update({ repo }) { processFile("website/src/pages/index.jsx", (content) => { if (dependentsCountNpm) { content = content.replace( - /()(.*?)(<\/strong>)/u, + /()(.*?)(<\/strong>)/, `$1${formatNumber(dependentsCountNpm)}$3`, ); } if (dependentsCountGithub) { content = content.replace( - /()(.*?)(<\/strong>)/u, + /()(.*?)(<\/strong>)/, `$1${formatNumber(dependentsCountGithub)}$3`, ); } diff --git a/scripts/release/steps/update-version.js b/scripts/release/steps/update-version.js index 28c69a739..271c200d1 100644 --- a/scripts/release/steps/update-version.js +++ b/scripts/release/steps/update-version.js @@ -12,16 +12,14 @@ export default async function updateVersion({ version, next }) { // Update github issue templates processFile(".github/ISSUE_TEMPLATE/formatting.md", (content) => - content.replace(/^(\*\*Prettier ).*?(\*\*)$/mu, `$1${version}$2`), + content.replace(/^(\*\*Prettier ).*?(\*\*)$/m, `$1${version}$2`), ); processFile(".github/ISSUE_TEMPLATE/integration.md", (content) => - content.replace(/^(- Prettier Version: ).*$/mu, `$1${version}`), + content.replace(/^(- Prettier Version: ).*$/m, `$1${version}`), ); await runYarn(["install"], { cwd: "./website" }); process.env.PRETTIER_VERSION = version; - await runYarn(["update-stable-docs"], { - cwd: "./website", - }); + await runYarn(["update-stable-docs"], { cwd: "./website" }); } diff --git a/scripts/tools/bundle-test/index.js b/scripts/tools/bundle-test/index.js index 078175795..a8e24978b 100644 --- a/scripts/tools/bundle-test/index.js +++ b/scripts/tools/bundle-test/index.js @@ -50,7 +50,7 @@ for (const packageConfig of packageBuildConfigs) { /* `require` in `parser-typescript.js`, #12338 */ for (const module of modules) { for (const file of module.files) { - if (!/\.m?js$/u.test(file.output) || excludedFiles.has(file.output)) { + if (!/\.m?js$/.test(file.output) || excludedFiles.has(file.output)) { continue; } console.log(`${file.output}: `); diff --git a/scripts/utilities/changelog.js b/scripts/utilities/changelog.js index 2932f7b4d..ad352c7f1 100644 --- a/scripts/utilities/changelog.js +++ b/scripts/utilities/changelog.js @@ -48,7 +48,7 @@ export function getEntries(dirPath, options) { const filePath = path.join(dirPath, fileName); let [title, ...rest] = fs.readFileSync(filePath, "utf8").trim().split("\n"); - const improvement = title.match(/\[IMPROVEMENT(:(\d+))?\]/u); + const improvement = title.match(/\[IMPROVEMENT(:(\d+))?\]/); const section = title.includes("[HIGHLIGHT]") ? "highlight" @@ -100,11 +100,11 @@ export function replaceVersions(data, prevVer, newVer, isPatch = false) { return data .replaceAll( - /prettier stable/giu, + /prettier stable/gi, `Prettier ${isPatch ? prevVer : formatVersion(prevVer)}`, ) .replaceAll( - /prettier main/giu, + /prettier main/gi, `Prettier ${isPatch ? newVer : formatVersion(newVer)}`, ); } @@ -115,12 +115,12 @@ function formatVersion(version) { function processTitle(title) { return title - .replaceAll(/\[(BREAKING|HIGHLIGHT|IMPROVEMENT(:\d+)?)\]/gu, "") - .replaceAll(/\s+/gu, " ") - .replace(/^#{4} [a-z]/u, (s) => s.toUpperCase()) - .replaceAll(/(? s.toUpperCase()) + .replaceAll(/(?["'])(?.*?)\k$/u, + /^(?["'])(?.*?)\k$/, "$", ); @@ -147,7 +147,7 @@ function clean(original, cloned, parent) { original.value ) { cloned.value = cloned.value.replaceAll( - /([\d+.e-]+)([a-z]*)/giu, + /([\d+.e-]+)([a-z]*)/gi, (match, numStr, unit) => { const num = Number(numStr); return Number.isNaN(num) ? match : num + unit.toLowerCase(); @@ -220,7 +220,7 @@ function clean(original, cloned, parent) { clean.ignoredProperties = ignoredProperties; function cleanCSSStrings(value) { - return value.replaceAll("'", '"').replaceAll(/\\([^\da-f])/giu, "$1"); + return value.replaceAll("'", '"').replaceAll(/\\([^\da-f])/gi, "$1"); } export default clean; diff --git a/src/language-css/loc.js b/src/language-css/loc.js index c781b8caa..7820306ab 100644 --- a/src/language-css/loc.js +++ b/src/language-css/loc.js @@ -109,7 +109,7 @@ function getValueRootOffset(node) { if (node.type === "css-atrule" && typeof node.name === "string") { result += - 1 + node.name.length + node.raws.afterName.match(/^\s*:?\s*/u)[0].length; + 1 + node.name.length + node.raws.afterName.match(/^\s*:?\s*/)[0].length; } if (node.type !== "css-atrule" && typeof node.raws?.between === "string") { @@ -238,7 +238,7 @@ function replaceQuotesInInlineComments(text) { for (const [start, end] of inlineCommentsToReplace) { text = text.slice(0, start) + - text.slice(start, end).replaceAll(/["'*]/gu, " ") + + text.slice(start, end).replaceAll(/["'*]/g, " ") + text.slice(end); } diff --git a/src/language-css/parse/parse-selector.js b/src/language-css/parse/parse-selector.js index 9816d7447..8b0a887b9 100644 --- a/src/language-css/parse/parse-selector.js +++ b/src/language-css/parse/parse-selector.js @@ -6,7 +6,7 @@ function parseSelector(selector) { // the content of the comment as selectors which turns it into complete // garbage. Better to print the whole selector as-is and not try to parse // and reformat it. - if (/\/[/*]/u.test(selector.replaceAll(/"[^"]+"|'[^']+'/gu, ""))) { + if (/\/[/*]/.test(selector.replaceAll(/"[^"]+"|'[^']+'/g, ""))) { return { type: "selector-unknown", value: selector.trim(), diff --git a/src/language-css/parse/parse-value.js b/src/language-css/parse/parse-value.js index 0a275c124..c792111e3 100644 --- a/src/language-css/parse/parse-value.js +++ b/src/language-css/parse/parse-value.js @@ -192,7 +192,7 @@ function parseValue(value, options) { const parsedResult = parseNestedValue(result, options); - return addTypePrefix(parsedResult, "value-", /^selector-/u); + return addTypePrefix(parsedResult, "value-", /^selector-/); } export default parseValue; diff --git a/src/language-css/parser-postcss.js b/src/language-css/parser-postcss.js index eeb97da8c..ce4e8af8b 100644 --- a/src/language-css/parser-postcss.js +++ b/src/language-css/parser-postcss.js @@ -19,8 +19,8 @@ import { hasIgnorePragma, hasPragma } from "./pragma.js"; import isModuleRuleName from "./utilities/is-module-rule-name.js"; import isSCSSNestedPropertyNode from "./utilities/is-scss-nested-property-node.js"; -const DEFAULT_SCSS_DIRECTIVE = /(\s*)(!default).*$/u; -const GLOBAL_SCSS_DIRECTIVE = /(\s*)(!global).*$/u; +const DEFAULT_SCSS_DIRECTIVE = /(\s*)(!default).*$/; +const GLOBAL_SCSS_DIRECTIVE = /(\s*)(!global).*$/; function parseNestedCSS(node, options) { if (isObject(node)) { @@ -232,7 +232,7 @@ function parseNestedCSS(node, options) { // only css support custom-selector if (options.parser === "css" && node.name === "custom-selector") { - const customSelector = node.params.match(/:--\S+\s+/u)[0].trim(); + const customSelector = node.params.match(/:--\S+\s+/)[0].trim(); node.customSelector = customSelector; node.selector = parseSelector( node.params.slice(customSelector.length).trim(), @@ -307,7 +307,7 @@ function parseNestedCSS(node, options) { } if (name === "at-root") { - if (/^\(\s*(?:without|with)\s*:.+\)$/su.test(params)) { + if (/^\(\s*(?:without|with)\s*:.+\)$/s.test(params)) { node.params = parseValue(params, options); } else { node.selector = parseSelector(params); @@ -344,11 +344,11 @@ function parseNestedCSS(node, options) { ) { // Remove unnecessary spaces in SCSS variable arguments // Move spaces after the `...`, so we can keep the range correct - params = params.replace(/(\$\S+?)(\s+)?\.{3}/u, "$1...$2"); + params = params.replace(/(\$\S+?)(\s+)?\.{3}/, "$1...$2"); // Remove unnecessary spaces before SCSS control, mixin and function directives // Move spaces after the `(`, so we can keep the range correct // Only match the first function call at the beginning, not nested ones - params = params.replace(/^(?!if)([^"'\s(]+)(\s+)\(/u, "$1($2"); + params = params.replace(/^(?!if)([^"'\s(]+)(\s+)\(/, "$1($2"); node.value = parseValue(params, options); delete node.params; diff --git a/src/language-css/print/misc.js b/src/language-css/print/misc.js index 5b90035f9..15a141a4c 100644 --- a/src/language-css/print/misc.js +++ b/src/language-css/print/misc.js @@ -7,10 +7,10 @@ function printUnit(unit) { return CSS_UNITS.has(lowercased) ? CSS_UNITS.get(lowercased) : unit; } -const STRING_REGEX = /(["'])(?:(?!\1)[^\\]|\\.)*\1/gsu; -const NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:e[+-]?\d+)?/giu; -const STANDARD_UNIT_REGEX = /[a-z]+/giu; -const WORD_PART_REGEX = /[$@]?[_a-z\u0080-\uFFFF][\w\u0080-\uFFFF-]*/giu; +const STRING_REGEX = /(["'])(?:(?!\1)[^\\]|\\.)*\1/gs; +const NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:e[+-]?\d+)?/gi; +const STANDARD_UNIT_REGEX = /[a-z]+/gi; +const WORD_PART_REGEX = /[$@]?[_a-z\u0080-\uFFFF][\w\u0080-\uFFFF-]*/gi; const ADJUST_NUMBERS_REGEX = new RegExp( STRING_REGEX.source + "|" + @@ -18,7 +18,7 @@ const ADJUST_NUMBERS_REGEX = new RegExp( `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, - "giu", + "gi", ); function adjustStrings(value, options) { @@ -33,7 +33,7 @@ function quoteAttributeValue(value, options) { // To support future flags, we simply check if it's an alphabet letter // https://github.com/prettier/prettier/pull/17865#discussion_r2332698101 let flag = ""; - const match = value.match(/^(?.+?)\s+(?[a-zA-Z])$/u); + const match = value.match(/^(?.+?)\s+(?[a-z])$/i); if (match) { ({ value, flag } = match.groups); } @@ -72,7 +72,7 @@ function printCssNumber(rawNumber) { return ( printNumber(rawNumber) // Remove trailing `.0`. - .replace(/\.0(?=$|e)/u, "") + .replace(/\.0(?=$|e)/, "") ); } diff --git a/src/language-css/printer-postcss.js b/src/language-css/printer-postcss.js index 0d3895a06..eafb289c1 100644 --- a/src/language-css/printer-postcss.js +++ b/src/language-css/printer-postcss.js @@ -112,7 +112,7 @@ function genericPrint(path, options, print) { const isColon = trimmedBetween === ":"; const hasSpaceAfterColon = rawBetween.endsWith(" ") && isColon; const isValueAllSpace = - typeof node.value === "string" && /^ *$/u.test(node.value); + typeof node.value === "string" && /^ *$/.test(node.value); let value = typeof node.value === "string" ? node.value : print("value"); value = hasComposesNode(node) ? removeLines(value) : value; @@ -126,7 +126,7 @@ function genericPrint(path, options, print) { } return [ - node.raws.before.replaceAll(/[\s;]/gu, ""), + node.raws.before.replaceAll(/[\s;]/g, ""), // Less variable (parentNode.type === "css-atrule" && parentNode.variable) || insideIcssRuleNode(path) @@ -147,17 +147,17 @@ function genericPrint(path, options, print) { : "", value, node.raws.important - ? node.raws.important.replace(/\s*!\s*important/iu, " !important") + ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault - ? node.raws.scssDefault.replace(/\s*!default/iu, " !default") + ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal - ? node.raws.scssGlobal.replace(/\s*!global/iu, " !global") + ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", @@ -248,9 +248,9 @@ function genericPrint(path, options, print) { ? "" : node.name.endsWith(":") ? " " - : /^\s*\n\s*\n/u.test(node.raws.afterName) + : /^\s*\n\s*\n/.test(node.raws.afterName) ? [hardline, hardline] - : /^\s*\n/u.test(node.raws.afterName) + : /^\s*\n/.test(node.raws.afterName) ? hardline : " " : " ", @@ -323,7 +323,7 @@ function genericPrint(path, options, print) { case "media-feature": return maybeToLowerCase( - adjustStrings(node.value.replaceAll(/ +/gu, " "), options), + adjustStrings(node.value.replaceAll(/ +/g, " "), options), ); case "media-colon": @@ -337,9 +337,7 @@ function genericPrint(path, options, print) { case "media-url": return adjustStrings( - node.value - .replaceAll(/^url\(\s+/giu, "url(") - .replaceAll(/\s+\)$/gu, ")"), + node.value.replaceAll(/^url\(\s+/gi, "url(").replaceAll(/\s+\)$/g, ")"), options, ); diff --git a/src/language-css/utilities/index.js b/src/language-css/utilities/index.js index 6477cb24a..1d71d087d 100644 --- a/src/language-css/utilities/index.js +++ b/src/language-css/utilities/index.js @@ -123,8 +123,8 @@ function isDetachedRulesetDeclarationNode(node) { } return ( - (typeof selector === "string" && /^@.+:.*$/u.test(selector)) || - (selector.value && /^@.+:.*$/u.test(selector.value)) + (typeof selector === "string" && /^@.+:.*$/.test(selector)) || + (selector.value && /^@.+:.*$/.test(selector.value)) ); } @@ -194,7 +194,7 @@ function isSCSSControlDirectiveNode(node, options) { } function isDetachedRulesetCallNode(node) { - return node.raws?.params && /^\(\s*\)$/u.test(node.raws.params); + return node.raws?.params && /^\(\s*\)$/.test(node.raws.params); } function isTemplatePlaceholderNode(node) { @@ -356,7 +356,7 @@ function isColorAdjusterFuncNode(node) { } function lastLineHasInlineComment(text) { - return /\/\//u.test(text.split(/[\n\r]/u).pop()); + return /\/\//.test(text.split(/[\n\r]/).pop()); } function isAtWordPlaceholderNode(node) { diff --git a/src/language-css/utilities/is-scss-nested-property-node.js b/src/language-css/utilities/is-scss-nested-property-node.js index 4564e526c..e05d87463 100644 --- a/src/language-css/utilities/is-scss-nested-property-node.js +++ b/src/language-css/utilities/is-scss-nested-property-node.js @@ -9,8 +9,8 @@ function isSCSSNestedPropertyNode(node, options) { } return node.selector - .replace(/\/\*.*?\*\//u, "") - .replace(/\/\/.*\n/u, "") + .replace(/\/\*.*?\*\//, "") + .replace(/\/\/.*\n/, "") .trim() .endsWith(":"); } diff --git a/src/language-graphql/printer-graphql.js b/src/language-graphql/printer-graphql.js index f87a794f1..67d0c4058 100644 --- a/src/language-graphql/printer-graphql.js +++ b/src/language-graphql/printer-graphql.js @@ -109,7 +109,7 @@ function genericPrint(path, options, print) { return [ '"', node.value - .replaceAll(/["\\]/gu, String.raw`\$&`) + .replaceAll(/["\\]/g, String.raw`\$&`) .replaceAll("\n", String.raw`\n`), '"', ]; diff --git a/src/language-handlebars/parser-glimmer.js b/src/language-handlebars/parser-glimmer.js index ef1efb9a5..6fb2369e4 100644 --- a/src/language-handlebars/parser-glimmer.js +++ b/src/language-handlebars/parser-glimmer.js @@ -26,7 +26,7 @@ function addBackslash(node) { childrenOrBody[i + 1].type === "MustacheStatement" ) { childrenOrBody[i].chars = childrenOrBody[i].chars.replace( - /\\$/u, + /\\$/, "\\\\", ); } @@ -126,8 +126,8 @@ function getErrorMessage(error) { */ if ( lines.length >= 4 && - /^Parse error on line \d+:$/u.test(lines[0]) && - /^-*\^$/u.test(lines.at(-2)) + /^Parse error on line \d+:$/.test(lines[0]) && + /^-*\^$/.test(lines.at(-2)) ) { return lines.at(-1); } @@ -147,8 +147,8 @@ function getErrorMessage(error) { */ if ( lines.length >= 4 && - /:\s?$/u.test(lines[0]) && - /^\(error occurred in '.*?' @ line \d+ : column \d+\)$/u.test( + /:\s?$/.test(lines[0]) && + /^\(error occurred in '.*?' @ line \d+ : column \d+\)$/.test( lines.at(-1), ) && lines[1] === "" && diff --git a/src/language-handlebars/printer-glimmer.js b/src/language-handlebars/printer-glimmer.js index 724771bd1..49fe24c78 100644 --- a/src/language-handlebars/printer-glimmer.js +++ b/src/language-handlebars/printer-glimmer.js @@ -173,7 +173,7 @@ function print(path, options, print) { } if (parent.tag === "style") { - text = text.replaceAll(/^\n+/gu, ""); + text = text.replaceAll(/^\n+/g, ""); text = htmlWhitespace.trimEnd(text); text = htmlWhitespace.dedentString(text); @@ -191,7 +191,7 @@ function print(path, options, print) { if (attrName) { // TODO: format style and srcset attributes if (attrName === "class") { - const formattedClasses = text.trim().split(/\s+/u).join(" "); + const formattedClasses = text.trim().split(/\s+/).join(" "); let leadingSpace = false; let trailingSpace = false; @@ -199,13 +199,13 @@ function print(path, options, print) { if (path.parent.type === "ConcatStatement") { if ( path.previous?.type === "MustacheStatement" && - /^\s/u.test(text) + /^\s/.test(text) ) { leadingSpace = true; } if ( path.next?.type === "MustacheStatement" && - /\s$/u.test(text) && + /\s$/.test(text) && formattedClasses !== "" ) { trailingSpace = true; @@ -695,14 +695,14 @@ function countNewLines(string) { function countLeadingNewLines(string) { /* c8 ignore next */ string = typeof string === "string" ? string : ""; - const newLines = (string.match(/^([^\S\n\r]*[\n\r])+/gu) || [])[0] || ""; + const newLines = (string.match(/^([^\S\n\r]*[\n\r])+/g) || [])[0] || ""; return countNewLines(newLines); } function countTrailingNewLines(string) { /* c8 ignore next */ string = typeof string === "string" ? string : ""; - const newLines = (string.match(/([\n\r][^\S\n\r]*)+$/gu) || [])[0] || ""; + const newLines = (string.match(/([\n\r][^\S\n\r]*)+$/g) || [])[0] || ""; return countNewLines(newLines); } @@ -817,8 +817,8 @@ const isPathExpressionPartNeedBrackets = (part, index) => { return ( (index !== 0 && PATH_EXPRESSION_FORBIDDEN_IN_FIRST_PART.has(part)) || - /\s/u.test(part) || - /^\d/u.test(part) || + /\s/.test(part) || + /^\d/.test(part) || Array.prototype.some.call(part, (character) => PATH_EXPRESSION_FORBIDDEN_CHARACTERS.has(character), ) diff --git a/src/language-handlebars/utilities.js b/src/language-handlebars/utilities.js index fe10c2831..8bccd6421 100644 --- a/src/language-handlebars/utilities.js +++ b/src/language-handlebars/utilities.js @@ -31,7 +31,7 @@ function isVoidElement(node) { } function isWhitespaceNode(node) { - return node.type === "TextNode" && !/\S/u.test(node.chars); + return node.type === "TextNode" && !/\S/.test(node.chars); } function isPrettierIgnoreNode(node) { diff --git a/src/language-html/clean.js b/src/language-html/clean.js index 177b9cc91..b9491ba3a 100644 --- a/src/language-html/clean.js +++ b/src/language-html/clean.js @@ -64,12 +64,12 @@ function clean(original, cloned, parent) { ) { delete cloned.value; } else if (value) { - cloned.value = value.replaceAll(/'|"|'/gu, '"'); + cloned.value = value.replaceAll(/'|"|'/g, '"'); } } if (original.kind === "docType") { - cloned.value = original.value.toLowerCase().replaceAll(/\s+/gu, " "); + cloned.value = original.value.toLowerCase().replaceAll(/\s+/g, " "); } if ( diff --git a/src/language-html/constants.evaluate.js b/src/language-html/constants.evaluate.js index 56bde52fc..18585b11c 100644 --- a/src/language-html/constants.evaluate.js +++ b/src/language-html/constants.evaluate.js @@ -5,7 +5,7 @@ function expandHeadingPseudoClassSelector(selector) { return ["h1", "h2", "h3", "h4", "h5", "h6"]; } - const match = selector.match(/^:heading\((?\d+(?:,\s*\d+)*)\)$/u); + const match = selector.match(/^:heading\((?\d+(?:,\s*\d+)*)\)$/); if (!match) { return; } @@ -28,7 +28,7 @@ const getCssStyleTags = (property) => return selectors.flatMap((selector) => { const tagNames = expandHeadingPseudoClassSelector(selector) ?? - (/^[\da-z]+$/iu.test(selector) ? [selector] : []); + (/^[\da-z]+$/i.test(selector) ? [selector] : []); return tagNames.map((tagName) => [tagName, style.value]); }); diff --git a/src/language-html/embed.js b/src/language-html/embed.js index 2a13c90fc..e0ba2fa47 100644 --- a/src/language-html/embed.js +++ b/src/language-html/embed.js @@ -51,7 +51,7 @@ function embed(path, options) { return async (textToDoc, print) => { const content = getNodeContent(node, options); - let isEmpty = /^\s*$/u.test(content); + let isEmpty = /^\s*$/.test(content); let doc = ""; if (!isEmpty) { doc = await textToDoc(htmlTrimPreserveIndentation(content), { @@ -82,7 +82,7 @@ function embed(path, options) { const value = parser === "markdown" ? htmlWhitespace.dedentString( - node.value.replace(/^[^\S\n]*\n/u, ""), + node.value.replace(/^[^\S\n]*\n/, ""), ) : node.value; const textToDocOptions = { parser, __embeddedInHtml: true }; diff --git a/src/language-html/embed/angular-attributes.js b/src/language-html/embed/angular-attributes.js index 7d91f3b7c..a580b6373 100644 --- a/src/language-html/embed/angular-attributes.js +++ b/src/language-html/embed/angular-attributes.js @@ -52,9 +52,9 @@ const printers = [ const name = path.node.fullName; return ( (name.startsWith("[") && name.endsWith("]")) || - /^bind(?:on)?-/u.test(name) || + /^bind(?:on)?-/.test(name) || // Unofficial rudimentary support for some of the most used directives of AngularJS 1.x - /^ng-(?:if|show|hide|class|style)$/u.test(name) + /^ng-(?:if|show|hide|class|style)$/.test(name) ); }, print: createAngularPrinter("__ng_binding"), @@ -71,7 +71,7 @@ const printers = [ - `i18n="longDescription"` - `i18n-attr="longDescription"` */ - test: (path /* , options */) => /^i18n(?:-.+)?$/u.test(path.node.fullName), + test: (path /* , options */) => /^i18n(?:-.+)?$/.test(path.node.fullName), print: printAngularI18n, }, { diff --git a/src/language-html/embed/angular-control-flow-block-parameters.js b/src/language-html/embed/angular-control-flow-block-parameters.js index cee397078..56aa8cefc 100644 --- a/src/language-html/embed/angular-control-flow-block-parameters.js +++ b/src/language-html/embed/angular-control-flow-block-parameters.js @@ -12,7 +12,7 @@ function printAngularControlFlowBlockParameters( node.sourceSpan.start.offset, node.sourceSpan.end.offset, ); - const isEmpty = /^\s*$/u.test(content); + const isEmpty = /^\s*$/.test(content); if (isEmpty) { return ""; diff --git a/src/language-html/embed/angular-interpolation.js b/src/language-html/embed/angular-interpolation.js index 188721f7f..69526f072 100644 --- a/src/language-html/embed/angular-interpolation.js +++ b/src/language-html/embed/angular-interpolation.js @@ -2,7 +2,7 @@ import { group, indent, line, replaceEndOfLine } from "../../document/index.js"; import { getUnescapedAttributeValue } from "../utilities/index.js"; import { formatAttributeValue } from "./utilities.js"; -const interpolationRegex = /\{\{(.+?)\}\}/su; +const interpolationRegex = /\{\{(.+?)\}\}/s; const isAngularInterpolation = ({ node: { value } } /* , options*/) => interpolationRegex.test(value); diff --git a/src/language-html/embed/class-names.js b/src/language-html/embed/class-names.js index 8cacf92fe..58b16a78a 100644 --- a/src/language-html/embed/class-names.js +++ b/src/language-html/embed/class-names.js @@ -12,6 +12,6 @@ const isClassNames = ({ node }, options) => /** @type {AttributeValuePrint} */ const printClassNames = (textToDoc, print, path /* , options*/) => - getUnescapedAttributeValue(path.node).trim().split(/\s+/u).join(" "); + getUnescapedAttributeValue(path.node).trim().split(/\s+/).join(" "); export { isClassNames, printClassNames }; diff --git a/src/language-html/embed/vue-v-for-directive.js b/src/language-html/embed/vue-v-for-directive.js index 929a912e5..39d1452f1 100644 --- a/src/language-html/embed/vue-v-for-directive.js +++ b/src/language-html/embed/vue-v-for-directive.js @@ -38,9 +38,9 @@ async function printVueVForDirective(textToDoc, print, path, options) { // modified from https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/parser/index.js#L370-L387 function parseVueVForDirective(value) { - const forAliasRE = /(.*?)\s+(in|of)\s+(.*)/su; - const forIteratorRE = /,([^,\]}]*)(?:,([^,\]}]*))?$/u; - const stripParensRE = /^\(|\)$/gu; + const forAliasRE = /(.*?)\s+(in|of)\s+(.*)/s; + const forIteratorRE = /,([^,\]}]*)(?:,([^,\]}]*))?$/; + const stripParensRE = /^\(|\)$/g; const inMatch = value.match(forAliasRE); if (!inMatch) { diff --git a/src/language-html/parse/conditional-comment.js b/src/language-html/parse/conditional-comment.js index b62cc9a69..7b255f36f 100644 --- a/src/language-html/parse/conditional-comment.js +++ b/src/language-html/parse/conditional-comment.js @@ -10,17 +10,17 @@ const parseFunctions = [ { // regex: - /^(?\[if(?[^\]]*)\]>)(?.*?)\[if(?[^\]]*)\]>)(?.*?) - regex: /^\[if(?[^\]]*)\]>[^\]]*)\]> - regex: /^ { if (!canHaveInterpolation(node, options)) { return; @@ -348,7 +348,7 @@ function addHasHtmComponentClosingTag(ast, options) { node.hasHtmComponentClosingTag = node.endSourceSpan && - /^<\s*\/\s*\/\s*>$/u.test( + /^<\s*\/\s*\/\s*>$/.test( options.originalText.slice( node.endSourceSpan.start.offset, node.endSourceSpan.end.offset, diff --git a/src/language-html/print/element.js b/src/language-html/print/element.js index 3ae5ab6e0..b8826d647 100644 --- a/src/language-html/print/element.js +++ b/src/language-html/print/element.js @@ -140,7 +140,6 @@ function printElement(path, options, print) { node.isIndentationSensitive)) && new RegExp( String.raw`\n[\t ]{${options.tabWidth * (path.ancestors.length - 1)}}$`, - "u", ).test(node.lastChild.value) ) { return ""; diff --git a/src/language-html/print/tag.js b/src/language-html/print/tag.js index 429f1d9e5..57968903d 100644 --- a/src/language-html/print/tag.js +++ b/src/language-html/print/tag.js @@ -192,7 +192,7 @@ function needsToBorrowNextOpeningTagStartMarker(node) { } function getPrettierIgnoreAttributeCommentData(value) { - const match = value.trim().match(/^prettier-ignore-attribute(?:\s+(.+))?$/su); + const match = value.trim().match(/^prettier-ignore-attribute(?:\s+(.+))?$/s); if (!match) { return false; @@ -202,7 +202,7 @@ function getPrettierIgnoreAttributeCommentData(value) { return true; } - return match[1].split(/\s+/u); + return match[1].split(/\s+/); } function needsToBorrowParentOpeningTagEndMarker(node) { @@ -356,7 +356,7 @@ function printOpeningTagStartMarker(node, options) { // Only lowercase HTML5 doctype in `.html` and `.htm` files if (node.value === "html") { const { filepath } = options; - if (filepath && /\.html?$/u.test(filepath)) { + if (filepath && /\.html?$/.test(filepath)) { return HTML5_DOCTYPE_START_MARKER; } } diff --git a/src/language-html/printer-html.js b/src/language-html/printer-html.js index ffd261275..e0cd1ea8e 100644 --- a/src/language-html/printer-html.js +++ b/src/language-html/printer-html.js @@ -90,7 +90,7 @@ function genericPrint(path, options, print) { case "text": { if (node.parent.kind === "interpolation") { // replace the trailing literalline with hardline for better readability - const trailingNewlineRegex = /\n[^\S\n]*$/u; + const trailingNewlineRegex = /\n[^\S\n]*$/; const hasTrailingNewline = trailingNewlineRegex.test(node.value); const value = hasTrailingNewline ? node.value.replace(trailingNewlineRegex, "") @@ -115,7 +115,7 @@ function genericPrint(path, options, print) { group([ printOpeningTagStart(node, options), " ", - node.value.replace(/^html\b/iu, "html").replaceAll(/\s+/gu, " "), + node.value.replace(/^html\b/i, "html").replaceAll(/\s+/g, " "), ]), printClosingTagEnd(node, options), ]; diff --git a/src/language-html/utilities/index.js b/src/language-html/utilities/index.js index 266f2647b..259099379 100644 --- a/src/language-html/utilities/index.js +++ b/src/language-html/utilities/index.js @@ -20,7 +20,7 @@ import { import isUnknownNamespace from "./is-unknown-namespace.js"; const htmlTrimLeadingBlankLines = (string) => - string.replaceAll(/^[\t\f\r ]*\n/gu, ""); + string.replaceAll(/^[\t\f\r ]*\n/g, ""); const htmlTrimPreserveIndentation = (string) => htmlTrimLeadingBlankLines(htmlWhitespace.trimEnd(string)); const getLeadingAndTrailingHtmlWhitespace = (string) => { @@ -482,7 +482,7 @@ function getNodeCssStyleDisplay(node, options) { if (node.prev?.kind === "comment") { // - const match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/u); + const match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/); if (match) { return match[1]; } @@ -614,7 +614,7 @@ function shouldUnquoteAttributeValue(node, options) { return ( // Embedded HTML in JS: `` /* HTML */ `` `` - /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/u.test(value) || + /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(value) || // LWC `
` (options.parser === "lwc" && value.startsWith("{") && value.endsWith("}")) ); diff --git a/src/language-js/clean.js b/src/language-js/clean.js index 986bcbe47..5e64738ed 100644 --- a/src/language-js/clean.js +++ b/src/language-js/clean.js @@ -118,10 +118,10 @@ function clean(original, cloned, parent) { if ( original.type === "JSXAttribute" && original.value?.type === "Literal" && - /["']|"|'/u.test(original.value.value) + /["']|"|'/.test(original.value.value) ) { cloned.value.value = original.value.value.replaceAll( - /["']|"|'/gu, + /["']|"|'/g, '"', ); } diff --git a/src/language-js/comments/is-gap.js b/src/language-js/comments/is-gap.js index d49562176..ce901e85c 100644 --- a/src/language-js/comments/is-gap.js +++ b/src/language-js/comments/is-gap.js @@ -2,7 +2,7 @@ function isGap(text, { parser }) { if (parser === "flow" || parser === "hermes" || parser === "babel-flow") { // Example: (a /* b */ /* : c */) // gap ^^^^ - text = text.replaceAll(/[\s(]/gu, ""); + text = text.replaceAll(/[\s(]/g, ""); return text === "" || text === "/*" || text === "/*::"; } } diff --git a/src/language-js/embed/css.js b/src/language-js/embed/css.js index 5551215c9..0c3b901fa 100644 --- a/src/language-js/embed/css.js +++ b/src/language-js/embed/css.js @@ -50,18 +50,16 @@ function replacePlaceholders(quasisDoc, expressionDocs) { } // When we have multiple placeholders in one line, like: // ${Child}${Child2}:not(:first-child) - return doc - .split(/@prettier-placeholder-(\d+)-id/u) - .map((component, idx) => { - // The placeholder is always at odd indices - if (idx % 2 === 0) { - return replaceEndOfLine(component); - } + return doc.split(/@prettier-placeholder-(\d+)-id/).map((component, idx) => { + // The placeholder is always at odd indices + if (idx % 2 === 0) { + return replaceEndOfLine(component); + } - // The component will always be a number at odd index - replaceCounter++; - return expressionDocs[component]; - }); + // The component will always be a number at odd index + replaceCounter++; + return expressionDocs[component]; + }); }); return expressionDocs.length === replaceCounter ? newDoc : null; } @@ -106,7 +104,7 @@ function isStyledIdentifier(node) { } function isStyledExtend(node) { - return /^[A-Z]/u.test(node.object.name) && node.property.name === "extend"; + return /^[A-Z]/.test(node.object.name) && node.property.name === "extend"; } /** diff --git a/src/language-js/embed/graphql.js b/src/language-js/embed/graphql.js index 1f478a966..6e6a8270e 100644 --- a/src/language-js/embed/graphql.js +++ b/src/language-js/embed/graphql.js @@ -30,11 +30,11 @@ async function printEmbedGraphQL(textToDoc, print, path, options) { lines[numLines - 2].trim() === ""; const commentsAndWhitespaceOnly = lines.every((line) => - /^\s*(?:#[^\n\r]*)?$/u.test(line), + /^\s*(?:#[^\n\r]*)?$/.test(line), ); // Bail out if an interpolation occurs within a comment. - if (!isLast && /#[^\n\r]*$/u.test(lines[numLines - 1])) { + if (!isLast && /#[^\n\r]*$/.test(lines[numLines - 1])) { return null; } diff --git a/src/language-js/embed/html.js b/src/language-js/embed/html.js index 1b45cddad..e2ac60357 100644 --- a/src/language-js/embed/html.js +++ b/src/language-js/embed/html.js @@ -34,7 +34,7 @@ async function printEmbedHtmlLike(parser, textToDoc, print, path, options) { const placeholderRegex = new RegExp( composePlaceholder(String.raw`(\d+)`), - "gu", + "g", ); let topLevelCount = 0; const doc = await textToDoc(text, { @@ -60,7 +60,7 @@ async function printEmbedHtmlLike(parser, textToDoc, print, path, options) { component = uncookTemplateElementValue(component); if (options.__embeddedInHtml) { component = component.replaceAll( - /<\/(?=script\b)/giu, + /<\/(?=script\b)/gi, String.raw`<\/`, ); } @@ -76,8 +76,8 @@ async function printEmbedHtmlLike(parser, textToDoc, print, path, options) { return parts; }); - const leadingWhitespace = /^\s/u.test(text) ? " " : ""; - const trailingWhitespace = /\s$/u.test(text) ? " " : ""; + const leadingWhitespace = /^\s/.test(text) ? " " : ""; + const trailingWhitespace = /\s$/.test(text) ? " " : ""; const linebreak = options.htmlWhitespaceSensitivity === "ignore" diff --git a/src/language-js/embed/markdown.js b/src/language-js/embed/markdown.js index a45b09f0d..df0b24716 100644 --- a/src/language-js/embed/markdown.js +++ b/src/language-js/embed/markdown.js @@ -9,13 +9,13 @@ import { escapeTemplateCharacters } from "../print/template-literal.js"; async function printEmbedMarkdown(textToDoc, print, path /* , options*/) { const { node } = path; let text = node.quasis[0].value.raw.replaceAll( - /((?:\\\\)*)\\`/gu, + /((?:\\\\)*)\\`/g, (_, backslashes) => "\\".repeat(backslashes.length / 2) + "`", ); const indentation = getIndentation(text); const hasIndent = indentation !== ""; if (hasIndent) { - text = text.replaceAll(new RegExp(`^${indentation}`, "gmu"), ""); + text = text.replaceAll(new RegExp(`^${indentation}`, "gm"), ""); } const doc = escapeTemplateCharacters( await textToDoc(text, { parser: "markdown", __inJsTemplate: true }), @@ -30,7 +30,7 @@ async function printEmbedMarkdown(textToDoc, print, path /* , options*/) { } function getIndentation(str) { - const firstMatchedIndent = str.match(/^([^\S\n]*)\S/mu); + const firstMatchedIndent = str.match(/^([^\S\n]*)\S/m); return firstMatchedIndent === null ? "" : firstMatchedIndent[1]; } diff --git a/src/language-js/parentheses/identifier.js b/src/language-js/parentheses/identifier.js index 2aa45afdc..e417493b1 100644 --- a/src/language-js/parentheses/identifier.js +++ b/src/language-js/parentheses/identifier.js @@ -18,7 +18,7 @@ function shouldAddParenthesesToIdentifier(path) { // f((a + b) / 2) vs f(a + b / 2) if ( node.extra?.parenthesized && - /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/u.test(node.name) + /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(node.name) ) { return true; } diff --git a/src/language-js/parse/acorn.js b/src/language-js/parse/acorn.js index 11efa0406..429e5e93c 100644 --- a/src/language-js/parse/acorn.js +++ b/src/language-js/parse/acorn.js @@ -44,7 +44,7 @@ function createParseError(error) { const { line, column } = loc; - return createError(message.replace(/ \(\d+:\d+\)$/u, ""), { + return createError(message.replace(/ \(\d+:\d+\)$/, ""), { loc: { start: { line, column: column + 1 }, }, diff --git a/src/language-js/parse/babel.js b/src/language-js/parse/babel.js index 4fe61bceb..608e3de7d 100644 --- a/src/language-js/parse/babel.js +++ b/src/language-js/parse/babel.js @@ -72,7 +72,7 @@ const appendPlugins = (plugins, options = parseOptions) => ({ // Similar to babel // https://github.com/babel/babel/pull/7934/files#diff-a739835084910b0ee3ea649df5a4d223R67 -const FLOW_PRAGMA_REGEX = /@(?:no)?flow\b/u; +const FLOW_PRAGMA_REGEX = /@(?:no)?flow\b/; function isFlowFile(text, filepath) { if (filepath?.endsWith(".js.flow")) { return true; @@ -135,7 +135,7 @@ function createParse({ isExpression = false, optionsCombinations }) { })); } - const shouldEnableV8intrinsicPlugin = /%[A-Z]/u.test(text); + const shouldEnableV8intrinsicPlugin = /%[A-Z]/.test(text); if (text.includes("|>")) { const conflictsPlugins = shouldEnableV8intrinsicPlugin ? [...pipelineOperatorPlugins, v8intrinsicPlugin] diff --git a/src/language-js/parse/oxc.js b/src/language-js/parse/oxc.js index ead89e169..d17e12d37 100644 --- a/src/language-js/parse/oxc.js +++ b/src/language-js/parse/oxc.js @@ -67,7 +67,7 @@ async function parseWithOptions(filepath, text, options) { error.severity === "Error" && (error.message === "A 'return' statement can only be used within a function body." || - /^Identifier `.*` has already been declared$/u.test(error.message)) + /^Identifier `.*` has already been declared$/.test(error.message)) ) { continue; } @@ -103,7 +103,7 @@ function getLanguageCombinations(text, options) { const filepath = options?.filepath; if (typeof filepath === "string") { - if (/\.(?:jsx|tsx)$/iu.test(filepath)) { + if (/\.(?:jsx|tsx)$/i.test(filepath)) { return ["tsx"]; } diff --git a/src/language-js/parse/typescript.js b/src/language-js/parse/typescript.js index 16d3ea6c8..b33709b5a 100644 --- a/src/language-js/parse/typescript.js +++ b/src/language-js/parse/typescript.js @@ -50,7 +50,7 @@ function createParseError(error) { // https://typescript-eslint.io/packages/parser/#jsx const isKnownFileType = (filepath) => - filepath && /\.(?:js|mjs|cjs|jsx|ts|mts|cts|tsx)$/iu.test(filepath); + filepath && /\.(?:js|mjs|cjs|jsx|ts|mts|cts|tsx)$/i.test(filepath); function getParseOptionsCombinations(text, filepath) { let combinations = [{ ...baseParseOptions, filePath: filepath }]; diff --git a/src/language-js/parse/utilities/jsx-regexp.evaluate.js b/src/language-js/parse/utilities/jsx-regexp.evaluate.js index 12e70b269..6e8173aa0 100644 --- a/src/language-js/parse/utilities/jsx-regexp.evaluate.js +++ b/src/language-js/parse/utilities/jsx-regexp.evaluate.js @@ -8,5 +8,5 @@ export default new RegExp( "|", "^[^/]{2}.*/>", // Contains "/>" on line not starting with "//" ].join(""), - "mu", + "m", ); diff --git a/src/language-js/parse/utilities/source-types.js b/src/language-js/parse/utilities/source-types.js index cdcec7f88..f69467620 100644 --- a/src/language-js/parse/utilities/source-types.js +++ b/src/language-js/parse/utilities/source-types.js @@ -16,11 +16,11 @@ export function getSourceType(filepath) { filepath = filepath.toLowerCase(); - if (/\.(?:mjs|mts)$/iu.test(filepath)) { + if (/\.(?:mjs|mts)$/i.test(filepath)) { return SOURCE_TYPE_MODULE; } - if (/\.(?:cjs|cts)$/iu.test(filepath)) { + if (/\.(?:cjs|cts)$/i.test(filepath)) { return SOURCE_TYPE_COMMONJS; } } diff --git a/src/language-js/print/angular.js b/src/language-js/print/angular.js index 30285d466..e77d48029 100644 --- a/src/language-js/print/angular.js +++ b/src/language-js/print/angular.js @@ -39,7 +39,7 @@ function printAngular(path, options, print) { "body", ); case "NGMicrosyntaxKey": - return /^[$_a-z][\w$]*(?:-[$_a-z][\w$])*$/iu.test(node.name) + return /^[$_a-z][\w$]*(?:-[$_a-z][\w$])*$/i.test(node.name) ? node.name : JSON.stringify(node.name); case "NGMicrosyntaxExpression": diff --git a/src/language-js/print/estree.js b/src/language-js/print/estree.js index a7ada34af..66aba617f 100644 --- a/src/language-js/print/estree.js +++ b/src/language-js/print/estree.js @@ -228,7 +228,7 @@ function printEstree(path, options, print, args) { case "UnaryExpression": { const parts = [node.operator]; - if (/[a-z]$/u.test(node.operator)) { + if (/[a-z]$/.test(node.operator)) { parts.push(" "); } diff --git a/src/language-js/print/jsx.js b/src/language-js/print/jsx.js index 6426cb746..a9462bf24 100644 --- a/src/language-js/print/jsx.js +++ b/src/language-js/print/jsx.js @@ -347,7 +347,7 @@ function printJsxChildren( // Starts with whitespace if (words[0] === "") { words.shift(); - if (/\n/u.test(words[0])) { + if (/\n/.test(words[0])) { pushLine( separatorWithWhitespace( isFacebookTranslationTag, @@ -383,7 +383,7 @@ function printJsxChildren( } if (endWhitespace !== undefined) { - if (/\n/u.test(endWhitespace)) { + if (/\n/.test(endWhitespace)) { pushLine( separatorWithWhitespace( isFacebookTranslationTag, @@ -405,10 +405,10 @@ function printJsxChildren( ), ); } - } else if (/\n/u.test(text)) { + } else if (/\n/.test(text)) { // Keep (up to one) blank line between tags/expressions/text. // Note: We don't keep blank lines between text elements. - if (text.match(/\n/gu).length > 1) { + if (text.match(/\n/g).length > 1) { pushLine(hardline); } } else { @@ -864,7 +864,7 @@ function isMeaningfulJsxText(node) { return ( node.type === "JSXText" && (jsxWhitespace.hasNonWhitespaceCharacter(getRaw(node)) || - !/\n/u.test(getRaw(node))) + !/\n/.test(getRaw(node))) ); } diff --git a/src/language-js/print/mapped-type.js b/src/language-js/print/mapped-type.js index 5784272f4..6d4071061 100644 --- a/src/language-js/print/mapped-type.js +++ b/src/language-js/print/mapped-type.js @@ -70,7 +70,7 @@ function printTypeScriptMappedType(path, options, print) { start + 1, locStart(node.key), ); - const nextTokenIndex = start + 1 + textAfter.search(/\S/u); + const nextTokenIndex = start + 1 + textAfter.search(/\S/); if (hasNewlineInRange(options.originalText, start, nextTokenIndex)) { shouldBreak = true; } diff --git a/src/language-js/print/member-chain.js b/src/language-js/print/member-chain.js index 41a7311ad..3915a034a 100644 --- a/src/language-js/print/member-chain.js +++ b/src/language-js/print/member-chain.js @@ -272,7 +272,7 @@ function printMemberChain(path, options, print) { // letter or just a sequence of _$. The rationale is that they are // likely to be factories. function isFactory(name) { - return /^[A-Z]|^[$_]+$/u.test(name); + return /^[A-Z]|^[$_]+$/.test(name); } // In case the Identifier is shorter than tab width, we can keep the diff --git a/src/language-js/print/property.js b/src/language-js/print/property.js index a1a68ac42..2a6bbdd5b 100644 --- a/src/language-js/print/property.js +++ b/src/language-js/print/property.js @@ -10,7 +10,7 @@ const needsQuoteProps = new WeakMap(); // Matches “simple” numbers like `123` and `2.5` but not `1_000`, `1e+100` or `0b10`. function isSimpleNumber(numberString) { - return /^(?:\d+|\d+\.\d+)$/u.test(numberString); + return /^(?:\d+|\d+\.\d+)$/.test(numberString); } // Note: Quoting/unquoting numbers in TypeScript is not safe. @@ -169,7 +169,7 @@ function printPropertyKey(path, options, print) { () => printComments( path, - /^\d/u.test(key.value) ? printNumber(key.value) : key.value, + /^\d/.test(key.value) ? printNumber(key.value) : key.value, options, ), "key", diff --git a/src/language-js/print/template-literal.js b/src/language-js/print/template-literal.js index 1e2e2e9e5..4bd301cee 100644 --- a/src/language-js/print/template-literal.js +++ b/src/language-js/print/template-literal.js @@ -90,7 +90,7 @@ function printJestEachTemplateLiteral(path, options, print) { * ${2} | ${1} | ${3} */ const { node } = path; - const headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/u); + const headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/); if ( headerNames.length > 1 || headerNames.some((headerName) => headerName.length > 0) @@ -275,7 +275,7 @@ function escapeTemplateCharacters(doc, raw) { return mapDoc(doc, (currentDoc) => { if (typeof currentDoc === "string") { return raw - ? currentDoc.replaceAll(/(\\*)`/gu, "$1$1\\`") + ? currentDoc.replaceAll(/(\\*)`/g, "$1$1\\`") : uncookTemplateElementValue(currentDoc); } @@ -284,7 +284,7 @@ function escapeTemplateCharacters(doc, raw) { } function uncookTemplateElementValue(cookedValue) { - return cookedValue.replaceAll(/([\\`]|\$\{)/gu, String.raw`\$1`); + return cookedValue.replaceAll(/([\\`]|\$\{)/g, String.raw`\$1`); } /** @@ -297,7 +297,7 @@ function uncookTemplateElementValue(cookedValue) { * * Ref: https://github.com/facebook/jest/pull/6102 */ -const jestEachTriggerRegex = /^[fx]?(?:describe|it|test)$/u; +const jestEachTriggerRegex = /^[fx]?(?:describe|it|test)$/; function isJestEachTemplateLiteral({ node, parent }) { return ( node.type === "TemplateLiteral" && diff --git a/src/language-js/print/type-parameters.js b/src/language-js/print/type-parameters.js index 19a8aa0fd..779b27aaf 100644 --- a/src/language-js/print/type-parameters.js +++ b/src/language-js/print/type-parameters.js @@ -39,7 +39,7 @@ function shouldForceTrailingComma(path, options, paramsKey) { node.type.startsWith("TS") && !node[paramsKey][0].constraint && path.parent.type === "ArrowFunctionExpression" && - !(options.filepath && /\.ts$/u.test(options.filepath)) + !(options.filepath && /\.ts$/.test(options.filepath)) ); } diff --git a/src/language-js/utilities/is-type-cast-comment.js b/src/language-js/utilities/is-type-cast-comment.js index 41f5d4ec2..00dd25851 100644 --- a/src/language-js/utilities/is-type-cast-comment.js +++ b/src/language-js/utilities/is-type-cast-comment.js @@ -19,7 +19,7 @@ function isTypeCastComment(comment) { // TypeScript expects the type to be enclosed in curly brackets, however // Closure Compiler accepts types in parens and even without any delimiters at all. // That's why we just search for "@type" and "@satisfies". - /@(?:type|satisfies)\b/u.test(comment.value), + /@(?:type|satisfies)\b/.test(comment.value), ); } diff --git a/src/language-markdown/clean.js b/src/language-markdown/clean.js index 1abd60eb3..031283dd4 100644 --- a/src/language-markdown/clean.js +++ b/src/language-markdown/clean.js @@ -36,7 +36,7 @@ function clean(original, cloned, parent) { } if (original.type === "wikiLink") { - cloned.value = original.value.trim().replaceAll(/[\t\n]+/gu, " "); + cloned.value = original.value.trim().replaceAll(/[\t\n]+/g, " "); } if ( @@ -66,7 +66,7 @@ function clean(original, cloned, parent) { original.type === "image") && original.title ) { - cloned.title = original.title.replaceAll(/\\(?=["')])/gu, ""); + cloned.title = original.title.replaceAll(/\\(?=["')])/g, ""); } // for insert pragma diff --git a/src/language-markdown/parse/mdx.js b/src/language-markdown/parse/mdx.js index f5d1aa918..032dd264b 100644 --- a/src/language-markdown/parse/mdx.js +++ b/src/language-markdown/parse/mdx.js @@ -22,11 +22,11 @@ * THE SOFTWARE. */ -const IMPORT_REGEX = /^import\s/u; -const EXPORT_REGEX = /^export\s/u; +const IMPORT_REGEX = /^import\s/; +const EXPORT_REGEX = /^export\s/; const BLOCKS_REGEX = String.raw`[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*|`; -const COMMENT_REGEX = /|/u; -const ES_COMMENT_REGEX = /^\{\s*\/\*(.*)\*\/\s*\}/u; +const COMMENT_REGEX = /|/; +const ES_COMMENT_REGEX = /^\{\s*\/\*(.*)\*\/\s*\}/; const EMPTY_NEWLINE = "\n\n"; const isImport = (text) => IMPORT_REGEX.test(text); diff --git a/src/language-markdown/parse/unified-plugins/liquid.js b/src/language-markdown/parse/unified-plugins/liquid.js index 4071cfa49..3ee5ab045 100644 --- a/src/language-markdown/parse/unified-plugins/liquid.js +++ b/src/language-markdown/parse/unified-plugins/liquid.js @@ -10,7 +10,7 @@ const liquid = function () { proto.inlineTokenizers.liquid = tokenizer; function tokenizer(eat, value) { - const match = value.match(/^(\{%.*?%\}|\{\{.*?\}\})/su); + const match = value.match(/^(\{%.*?%\}|\{\{.*?\}\})/s); if (match) { return eat(match[0])({ diff --git a/src/language-markdown/parse/unified-plugins/wiki-link.js b/src/language-markdown/parse/unified-plugins/wiki-link.js index 797b30ed2..1ff7ea3b4 100644 --- a/src/language-markdown/parse/unified-plugins/wiki-link.js +++ b/src/language-markdown/parse/unified-plugins/wiki-link.js @@ -5,7 +5,7 @@ */ const wikiLink = function () { const entityType = "wikiLink"; - const wikiLinkRegex = /^\[\[(?.+?)\]\]/su; + const wikiLinkRegex = /^\[\[(?.+?)\]\]/s; const proto = this.Parser.prototype; const methods = proto.inlineMethods; methods.splice(methods.indexOf("link"), 0, entityType); diff --git a/src/language-markdown/print/mdast.js b/src/language-markdown/print/mdast.js index 32c74ede1..2c0050078 100644 --- a/src/language-markdown/print/mdast.js +++ b/src/language-markdown/print/mdast.js @@ -101,7 +101,7 @@ function printMdast(path, options, print) { const proseWrap = // leading char that may cause different syntax - next && /^>|^(?:[*+-]|#{1,6}|\d+[).])$/u.test(next.value) + next && /^>|^(?:[*+-]|#{1,6}|\d+[).])$/.test(next.value) ? "never" : options.proseWrap; @@ -140,7 +140,7 @@ function printMdast(path, options, print) { const padding = code.startsWith("`") || code.endsWith("`") || - (/^[\n ]/u.test(code) && /[\n ]$/u.test(code) && /[^\n ]/u.test(code)) + (/^[\n ]/.test(code) && /[\n ]$/.test(code) && /[^\n ]/.test(code)) ? " " : ""; return [backtickString, padding, code, padding, backtickString]; @@ -150,7 +150,7 @@ function printMdast(path, options, print) { if (options.proseWrap === "preserve") { contents = node.value; } else { - contents = node.value.replaceAll(/[\t\n]+/gu, " "); + contents = node.value.replaceAll(/[\t\n]+/g, " "); } return ["[[", contents, "]]"]; @@ -233,7 +233,7 @@ function printMdast(path, options, print) { const { parent, isLast } = path; const value = parent.type === "root" && isLast ? node.value.trimEnd() : node.value; - const isHtmlComment = /^$/su.test(value); + const isHtmlComment = /^$/s.test(value); return replaceEndOfLine( value, @@ -327,7 +327,7 @@ function printMdast(path, options, print) { case "tableCell": return printChildren(path, options, print); case "break": - return /\s/u.test(options.originalText[node.position.start.offset]) + return /\s/.test(options.originalText[node.position.start.offset]) ? [" ", markAsRoot(literalline)] : ["\\", hardline]; case "liquidNode": @@ -471,7 +471,6 @@ function printUrl(url, dangerousCharOrChars = []) { return new RegExp( dangerousChars.map((x) => escapeStringRegexp(x)).join("|"), - "u", ).test(url) ? `<${encodeUrl(url, "<>")}>` : url; @@ -486,7 +485,7 @@ function printTitle(title, options, printSpace = true) { } // title is escaped after `remark-parse` v7 - title = title.replaceAll(/\\(?=["')])/gu, ""); + title = title.replaceAll(/\\(?=["')])/g, ""); if (title.includes('"') && title.includes("'") && !title.includes(")")) { return `(${title})`; // avoid escaped quotes diff --git a/src/language-markdown/print/preprocess.js b/src/language-markdown/print/preprocess.js index 0f2ac799f..4210a061f 100644 --- a/src/language-markdown/print/preprocess.js +++ b/src/language-markdown/print/preprocess.js @@ -3,7 +3,7 @@ import { getOrderedListItemInfo, mapAst, splitText } from "../utilities.js"; // 0x0 ~ 0x10ffff const isSingleCharRegex = /^\\?.$/su; -const isNewLineBlockquoteRegex = /^\n *>[ >]*$/u; +const isNewLineBlockquoteRegex = /^\n *>[ >]*$/; function preprocess(ast, options) { ast = restoreUnescapedCharacter(ast, options); @@ -116,7 +116,7 @@ function transformIndentedCodeblockAndMarkItsParentList(ast, options) { return mapAst(ast, (node, index, parentStack) => { if (node.type === "code") { // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it - const isIndented = /^\n?(?: {4,}|\t)/u.test( + const isIndented = /^\n?(?: {4,}|\t)/.test( options.originalText.slice( node.position.start.offset, node.position.end.offset, diff --git a/src/language-markdown/print/word.js b/src/language-markdown/print/word.js index 35feed9e4..ab7b46c19 100644 --- a/src/language-markdown/print/word.js +++ b/src/language-markdown/print/word.js @@ -45,7 +45,7 @@ function printWord(path) { )) ) { // backslash is parsed as part of autolinks, so we need to remove it - escapedValue = escapedValue.replace(/^(\\?[*_])+/u, (prefix) => + escapedValue = escapedValue.replace(/^(\\?[*_])+/, (prefix) => prefix.replaceAll("\\", ""), ); } diff --git a/src/language-markdown/utilities.js b/src/language-markdown/utilities.js index aef293bf8..a6f5f10b4 100644 --- a/src/language-markdown/utilities.js +++ b/src/language-markdown/utilities.js @@ -65,13 +65,13 @@ function splitText(text) { /** @type {Array} */ const nodes = []; - const tokens = text.split(/([\t\n ]+)/u); + const tokens = text.split(/([\t\n ]+)/); for (const [index, token] of tokens.entries()) { // whitespace if (index % 2 === 1) { nodes.push({ type: "whitespace", - value: /\n/u.test(token) ? "\n" : " ", + value: /\n/.test(token) ? "\n" : " ", }); continue; } @@ -165,7 +165,7 @@ function splitText(text) { lastNode?.type === "word" && !isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace - ![lastNode.value, node.value].some((value) => /\u3000/u.test(value)) + ![lastNode.value, node.value].some((value) => /\u3000/.test(value)) ) { nodes.push({ type: "whitespace", value: "" }); } @@ -187,7 +187,7 @@ function getOrderedListItemInfo(orderListItem, options) { ); const { numberText, leadingSpaces } = text.match( - /^\s*(?\d+)(\.|\))(?\s*)/u, + /^\s*(?\d+)(\.|\))(?\s*)/, ).groups; return { number: Number(numberText), leadingSpaces }; @@ -257,9 +257,7 @@ function isPrettierIgnore(node) { let match; if (node.type === "html") { - match = node.value.match( - /^$/u, - ); + match = node.value.match(/^$/); } else { let comment; @@ -274,7 +272,7 @@ function isPrettierIgnore(node) { } if (comment) { - match = comment.value.match(/^prettier-ignore(?:-(start|end))?$/u); + match = comment.value.match(/^prettier-ignore(?:-(start|end))?$/); } } diff --git a/src/language-yaml/clean.js b/src/language-yaml/clean.js index 8505c3414..41145f1f3 100644 --- a/src/language-yaml/clean.js +++ b/src/language-yaml/clean.js @@ -29,7 +29,7 @@ function clean(original, cloned /* , parent */) { if (original.chomping === "keep") { cloned.value = original.value .split("\n") - .map((line) => line.replace(/[ \t]+$/u, "")) + .map((line) => line.replace(/[ \t]+$/, "")) .join("\n"); } break; diff --git a/src/language-yaml/embed.js b/src/language-yaml/embed.js index 47aaf250c..05eff01c0 100644 --- a/src/language-yaml/embed.js +++ b/src/language-yaml/embed.js @@ -7,7 +7,7 @@ function embed(path, options) { if ( node.type === "root" && options.filepath && - /(?:[/\\]|^)\.(?:prettier|stylelint|lintstaged)rc$/u.test(options.filepath) + /(?:[/\\]|^)\.(?:prettier|stylelint|lintstaged)rc$/.test(options.filepath) ) { return async (textToDoc) => { const doc = await textToDoc(options.originalText, { parser: "json" }); diff --git a/src/language-yaml/print/mapping-item.js b/src/language-yaml/print/mapping-item.js index e0781eeca..43a837b23 100644 --- a/src/language-yaml/print/mapping-item.js +++ b/src/language-yaml/print/mapping-item.js @@ -173,7 +173,7 @@ function isAbsolutelyPrintedAsSingleLineNode(node, options) { if ( // backslash-newline - /\\$/mu.test( + /\\$/m.test( options.originalText.slice( node.position.start.offset, node.position.end.offset, @@ -187,7 +187,7 @@ function isAbsolutelyPrintedAsSingleLineNode(node, options) { case "never": return !node.value.includes("\n"); case "always": - return !/[\n ]/u.test(node.value); + return !/[\n ]/.test(node.value); default: /* c8 ignore next */ return false; diff --git a/src/language-yaml/printer-yaml.js b/src/language-yaml/printer-yaml.js index 834fad171..2506bea7d 100644 --- a/src/language-yaml/printer-yaml.js +++ b/src/language-yaml/printer-yaml.js @@ -266,7 +266,7 @@ function printNode(path, options, print) { if ( (node.type === "quoteSingle" && raw.includes("\\")) || - (node.type === "quoteDouble" && /\\[^"]/u.test(raw)) + (node.type === "quoteDouble" && /\\[^"]/.test(raw)) ) { // only quoteDouble can use escape chars // and quoteSingle do not need to escape backslashes diff --git a/src/language-yaml/utilities.js b/src/language-yaml/utilities.js index be2caef3d..f1dbae10d 100644 --- a/src/language-yaml/utilities.js +++ b/src/language-yaml/utilities.js @@ -39,7 +39,7 @@ function isNextLineEmpty(node, text) { newlineCount++; } - if (newlineCount === 1 && /\S/u.test(char)) { + if (newlineCount === 1 && /\S/.test(char)) { return false; } @@ -145,7 +145,7 @@ function hasEndComments(node) { @param {string} text */ function splitWithSingleSpace(text) { - return text ? text.split(/(?` or `|` - .match(/^[^\n]*\n(.*)$/su)[1]; + .match(/^[^\n]*\n(.*)$/s)[1]; if (content === "") { return []; @@ -216,7 +216,7 @@ function getBlockValueLineContents( /** @type {number} */ let leadingSpaceCount; if (node.indent === null) { - const matches = content.match(/^(? *)[^\n\r ]/mu); + const matches = content.match(/^(? *)[^\n\r ]/m); leadingSpaceCount = matches ? matches.groups.leadingSpace.length : Number.POSITIVE_INFINITY; @@ -243,11 +243,11 @@ function getBlockValueLineContents( index > 0 && words.length > 0 && rawLineContents[index - 1].length > 0 && - !/^\s/u.test(words[0]) && + !/^\s/.test(words[0]) && // This test against a `string[]`, should be a mistake // originally introduced in https://github.com/prettier/prettier/pull/4742/files#diff-a4dc2e1922e1d8d5ac20818480f777c9a2d5af739eaa3a0409b08bf29a9d0f74R282 // @ts-expect-error -- see comment above - !/^\s|\s$/u.test(lines.at(-1)) + !/^\s|\s$/.test(lines.at(-1)) ) { lines[lines.length - 1] = [...lines.at(-1), ...words]; } else { @@ -259,7 +259,7 @@ function getBlockValueLineContents( const words = []; for (const word of originalWords) { // disallow trailing spaces - if (words.length > 0 && /\s$/u.test(words.at(-1))) { + if (words.length > 0 && /\s$/.test(words.at(-1))) { words[words.length - 1] += " " + word; } else { words.push(word); @@ -286,9 +286,7 @@ function getBlockValueLineContents( let trailingNewlineCount = 0; for (let i = lineContents.length - 1; i >= 0; i--) { - if ( - lineContents[i].every((line) => line.replace(/[ \t]+$/u, "") === "") - ) { + if (lineContents[i].every((line) => line.replace(/[ \t]+$/, "") === "")) { trailingNewlineCount++; } else { break; diff --git a/src/main/comments/attach.js b/src/main/comments/attach.js index ae8ed3b9c..851cea323 100644 --- a/src/main/comments/attach.js +++ b/src/main/comments/attach.js @@ -244,7 +244,7 @@ function attachComments(ast, options) { } } -const isAllEmptyAndNoLineBreak = (text) => !/[\S\n\u2028\u2029]/u.test(text); +const isAllEmptyAndNoLineBreak = (text) => !/[\S\n\u2028\u2029]/.test(text); function isOwnLineComment(text, options, decoratedComments, commentIndex) { const { comment, precedingNode } = decoratedComments[commentIndex]; const { locStart, locEnd } = options; @@ -325,7 +325,7 @@ function breakTies(tiesToBreak, options) { const gap = options.originalText.slice(options.locEnd(comment), gapEndPos); - if (options.printer.isGap?.(gap, options) ?? /^[\s(]*$/u.test(gap)) { + if (options.printer.isGap?.(gap, options) ?? /^[\s(]*$/.test(gap)) { gapEndPos = options.locStart(comment); } else { // The gap string contained something other than whitespace or open diff --git a/src/main/core.js b/src/main/core.js index 36067f14c..dad5a071f 100644 --- a/src/main/core.js +++ b/src/main/core.js @@ -192,7 +192,7 @@ async function formatRange(originalText, opts) { rangeStart, text.lastIndexOf("\n", rangeStart) + 1, ); - const indentString = text.slice(rangeStart2, rangeStart).match(/^\s*/u)[0]; + const indentString = text.slice(rangeStart2, rangeStart).match(/^\s*/)[0]; const alignmentSize = getAlignmentSize(indentString, opts.tabWidth); diff --git a/src/main/front-matter/parse.js b/src/main/front-matter/parse.js index 24a277d10..2cf0bd70a 100644 --- a/src/main/front-matter/parse.js +++ b/src/main/front-matter/parse.js @@ -65,7 +65,7 @@ function getFrontMatter(text) { const frontMatterEndIndex = endDelimiterIndex + 1 + DELIMITER_LENGTH; const nextCharacter = text.charAt(frontMatterEndIndex + 1); - if (!/\s?/u.test(nextCharacter)) { + if (!/\s?/.test(nextCharacter)) { return; } diff --git a/src/main/range.js b/src/main/range.js index bb2d87007..811bded7b 100644 --- a/src/main/range.js +++ b/src/main/range.js @@ -201,12 +201,12 @@ function calculateRange(text, opts, ast) { assert.ok(end > start); // Contract the range so that it has non-whitespace characters at its endpoints. // This ensures we can format a range that doesn't end on a node. - const firstNonWhitespaceCharacterIndex = text.slice(start, end).search(/\S/u); + const firstNonWhitespaceCharacterIndex = text.slice(start, end).search(/\S/); const isAllWhitespace = firstNonWhitespaceCharacterIndex === -1; if (!isAllWhitespace) { start += firstNonWhitespaceCharacterIndex; for (; end > start; --end) { - if (/\S/u.test(text[end - 1])) { + if (/\S/.test(text[end - 1])) { break; } } diff --git a/src/universal/index.browser.js b/src/universal/index.browser.js index 450055a4f..4e9c47055 100644 --- a/src/universal/index.browser.js +++ b/src/universal/index.browser.js @@ -2,7 +2,7 @@ @param {string | URL} file @returns {string} */ -const getFileBasename = (file) => String(file).split(/[/\\]/u).pop(); +const getFileBasename = (file) => String(file).split(/[/\\]/).pop(); // Ideally, we should only allow `URL` with `file:` protocol and // string starts with `file:`, but `URL` is missing in some environments diff --git a/src/utilities/get-indent-size.js b/src/utilities/get-indent-size.js index dc2c721cf..f615f56d9 100644 --- a/src/utilities/get-indent-size.js +++ b/src/utilities/get-indent-size.js @@ -14,7 +14,7 @@ function getIndentSize(value, tabWidth) { return getAlignmentSize( // All the leading whitespaces - value.slice(lastNewlineIndex + 1).match(/^[\t ]*/u)[0], + value.slice(lastNewlineIndex + 1).match(/^[\t ]*/)[0], tabWidth, ); } diff --git a/src/utilities/get-interpreter.js b/src/utilities/get-interpreter.js index 17e19da67..7158acb6b 100644 --- a/src/utilities/get-interpreter.js +++ b/src/utilities/get-interpreter.js @@ -33,13 +33,13 @@ function getInterpreter(file) { } // #!/bin/env node, #!/usr/bin/env node - const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/u); + const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/); if (m1) { return m1[1]; } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node - const m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/u); + const m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/); if (m2) { return m2[1]; } diff --git a/src/utilities/get-max-continuous-count.js b/src/utilities/get-max-continuous-count.js index cdcab36a5..2c1bd1c43 100644 --- a/src/utilities/get-max-continuous-count.js +++ b/src/utilities/get-max-continuous-count.js @@ -7,7 +7,7 @@ import escapeStringRegexp from "escape-string-regexp"; */ function getMaxContinuousCount(text, searchString) { let results = text.matchAll( - new RegExp(`(?:${escapeStringRegexp(searchString)})+`, "gu"), + new RegExp(`(?:${escapeStringRegexp(searchString)})+`, "g"), ); // TODO: Use `Iterator#reduce` when we drop support for Node.js < 22 diff --git a/src/utilities/get-min-not-present-continuous-count.js b/src/utilities/get-min-not-present-continuous-count.js index d79fa564f..486b6905d 100644 --- a/src/utilities/get-min-not-present-continuous-count.js +++ b/src/utilities/get-min-not-present-continuous-count.js @@ -11,7 +11,7 @@ import escapeStringRegexp from "escape-string-regexp"; */ function getMinNotPresentContinuousCount(text, searchString) { const matches = text.match( - new RegExp(`(${escapeStringRegexp(searchString)})+`, "gu"), + new RegExp(`(${escapeStringRegexp(searchString)})+`, "g"), ); if (matches === null) { diff --git a/src/utilities/get-string-width.js b/src/utilities/get-string-width.js index b1f24a7ce..cac3c4822 100644 --- a/src/utilities/get-string-width.js +++ b/src/utilities/get-string-width.js @@ -7,7 +7,7 @@ import { } from "get-east-asian-width"; import narrowEmojis from "./narrow-emojis.evaluate.js"; -const notAsciiRegex = /[^\x20-\x7F]/u; +const notAsciiRegex = /[^\x20-\x7F]/; const narrowEmojisSet = new Set(narrowEmojis); // Similar to https://github.com/sindresorhus/string-width diff --git a/src/utilities/make-string.js b/src/utilities/make-string.js index 44178d74a..572ad4478 100644 --- a/src/utilities/make-string.js +++ b/src/utilities/make-string.js @@ -4,7 +4,7 @@ import { DOUBLE_QUOTE, SINGLE_QUOTE } from "./get-preferred-quote.js"; // Matches _any_ escape and unescaped quotes (both single and double). // Matching `\` in first group, so we won't treat `\\"` as escaped quote. -const REGEX = /\\(["'\\])|(["'])/gu; +const REGEX = /\\(["'\\])|(["'])/g; /** * @param {string} rawText diff --git a/src/utilities/pragma/pragma.evaluate.js b/src/utilities/pragma/pragma.evaluate.js index fddc57cb1..d55f59c59 100644 --- a/src/utilities/pragma/pragma.evaluate.js +++ b/src/utilities/pragma/pragma.evaluate.js @@ -8,7 +8,6 @@ export const FORMAT_PRAGMA_TO_INSERT = FORMAT_PRAGMAS[0]; export const YAML_IS_PRAGMA_REGEXP = new RegExp( String.raw`^\s*@(?:${FORMAT_PRAGMAS.join("|")})\s*$`, - "u", ); export const [YAML_HAS_PRAGMA_REGEXP, YAML_HAS_IGNORE_PRAGMA_REGEXP] = [ @@ -16,10 +15,7 @@ export const [YAML_HAS_PRAGMA_REGEXP, YAML_HAS_IGNORE_PRAGMA_REGEXP] = [ FORMAT_IGNORE_PRAGMAS, ].map( (pragmas) => - new RegExp( - String.raw`^\s*#[^\S\n]*@(?:${pragmas.join("|")})\s*?(?:\n|$)`, - "u", - ), + new RegExp(String.raw`^\s*#[^\S\n]*@(?:${pragmas.join("|")})\s*?(?:\n|$)`), ); export const [GRAPHQL_HAS_PRAGMA_REGEXP, GRAPHQL_HAS_IGNORE_PRAGMA_REGEXP] = [ @@ -27,10 +23,7 @@ export const [GRAPHQL_HAS_PRAGMA_REGEXP, GRAPHQL_HAS_IGNORE_PRAGMA_REGEXP] = [ FORMAT_IGNORE_PRAGMAS, ].map( (pragmas) => - new RegExp( - String.raw`^\s*#[^\S\n]*@(?:${pragmas.join("|")})\s*(?:\n|$)`, - "u", - ), + new RegExp(String.raw`^\s*#[^\S\n]*@(?:${pragmas.join("|")})\s*(?:\n|$)`), ); export const [HTML_HAS_PRAGMA_REGEXP, HTML_HAS_IGNORE_PRAGMA_REGEXP] = [ @@ -38,7 +31,7 @@ export const [HTML_HAS_PRAGMA_REGEXP, HTML_HAS_IGNORE_PRAGMA_REGEXP] = [ FORMAT_IGNORE_PRAGMAS, ].map( (pragmas) => - new RegExp(String.raw`^\s*`, "u"), + new RegExp(String.raw`^\s*`), ); export const [MARKDOWN_HAS_PRAGMA_REGEXP, MARKDOWN_HAS_IGNORE_PRAGMA_REGEXP] = [ @@ -52,6 +45,6 @@ export const [MARKDOWN_HAS_PRAGMA_REGEXP, MARKDOWN_HAS_IGNORE_PRAGMA_REGEXP] = [ String.raw`\{\s*\/\*\s*${pragma}\s*\*\/\s*\}`, ``, ].join("|"), - "mu", + "m", ); }); diff --git a/src/utilities/print-number.js b/src/utilities/print-number.js index 03c8672a7..ef2161741 100644 --- a/src/utilities/print-number.js +++ b/src/utilities/print-number.js @@ -6,15 +6,15 @@ function printNumber(rawNumber) { rawNumber .toLowerCase() // Remove unnecessary plus and zeroes from scientific notation. - .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(?=\d)/u, "$1$2") + .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(?=\d)/, "$1$2") // Remove unnecessary scientific notation (1e0). - .replace(/^([+-]?[\d.]+)e[+-]?0+$/u, "$1") + .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit. - .replace(/^([+-])?\./u, "$10.") + .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes. - .replace(/(\.\d+?)0+(?=e|$)/u, "$1") + .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot. - .replace(/\.(?=e|$)/u, "") + .replace(/\.(?=e|$)/, "") ); } diff --git a/src/utilities/print-string.js b/src/utilities/print-string.js index e6ac91374..954800660 100644 --- a/src/utilities/print-string.js +++ b/src/utilities/print-string.js @@ -9,7 +9,7 @@ import makeString from "./make-string.js"; /** @import {Quote} from "./get-preferred-quote.js" */ function printString(raw, options) { - assert.ok(/^(?["']).*\k$/su.test(raw)); + assert.ok(/^(?["']).*\k$/s.test(raw)); // `rawContent` is the string exactly like it appeared in the input source // code, without its enclosing quotes. diff --git a/src/utilities/public.js b/src/utilities/public.js index 64b788afd..a8bc4968c 100644 --- a/src/utilities/public.js +++ b/src/utilities/public.js @@ -85,7 +85,7 @@ export function makeString( const otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double). - const regex = /\\(.)|(["'])/gsu; + const regex = /\\(.)|(["'])/gs; // Escape and unescape single and double quotes as needed to be able to // enclose `rawText` with `enclosingQuote`. @@ -111,7 +111,7 @@ export function makeString( // Unescape any unnecessarily escaped character. // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27 return unescapeUnnecessaryEscapes && - /^[^\n\r"'0-7\\bfnrt-vx\u2028\u2029]$/u.test(escaped) + /^[^\n\r"'0-7\\bfnrt-vx\u2028\u2029]$/.test(escaped) ? escaped : "\\" + escaped; }); diff --git a/src/utilities/skip.js b/src/utilities/skip.js index eaaa6c2f7..e72ff8774 100644 --- a/src/utilities/skip.js +++ b/src/utilities/skip.js @@ -46,7 +46,7 @@ function skip(characters) { /** * @type {(text: string, startIndex: number | false, options?: SkipOptions) => number | false} */ -const skipWhitespace = skip(/\s/u); +const skipWhitespace = skip(/\s/); /** * @type {(text: string, startIndex: number | false, options?: SkipOptions) => number | false} */ @@ -58,7 +58,7 @@ const skipToLineEnd = skip(",; \t"); /** * @type {(text: string, startIndex: number | false, options?: SkipOptions) => number | false} */ -const skipEverythingButNewLine = skip(/[^\n\r]/u); +const skipEverythingButNewLine = skip(/[^\n\r]/); export { skip, diff --git a/src/utilities/whitespace-utilities.js b/src/utilities/whitespace-utilities.js index 7d451467a..3e19f36c3 100644 --- a/src/utilities/whitespace-utilities.js +++ b/src/utilities/whitespace-utilities.js @@ -11,7 +11,7 @@ class WhitespaceUtilities { (this.#whitespaceCharacters.size === 0 || Array.prototype.some.call( whitespaceCharacters, - (character) => !/^\s$/u.test(character), + (character) => !/^\s$/.test(character), )) ) { throw new TypeError( @@ -86,10 +86,7 @@ class WhitespaceUtilities { const pattern = `[${escapeStringRegexp( [...this.#whitespaceCharacters].join(""), )}]+`; - const regexp = new RegExp( - captureWhitespace ? `(${pattern})` : pattern, - "u", - ); + const regexp = new RegExp(captureWhitespace ? `(${pattern})` : pattern); return text.split(regexp); } diff --git a/tests/config/install-prettier.js b/tests/config/install-prettier.js index 8b118ca90..d47ef4554 100644 --- a/tests/config/install-prettier.js +++ b/tests/config/install-prettier.js @@ -10,7 +10,7 @@ import picocolors from "picocolors"; const isWindows = process.platform === "win32"; // https://github.com/sindresorhus/nano-spawn/blob/7f3fbe6590eec44f7e90f7735d173258dd80b420/source/windows.js#L71 const escapeFile = isWindows - ? (file) => file.replace(/([()\][%!^"`<>&|;, *?])/gu, "^$1") + ? (file) => file.replace(/([()\][%!^"`<>&|;, *?])/g, "^$1") : (file) => file; // https://github.com/sindresorhus/nano-spawn/blob/7f3fbe6590eec44f7e90f7735d173258dd80b420/source/windows.js#L66 const escapeArgument = isWindows @@ -18,8 +18,8 @@ const escapeArgument = isWindows escapeFile( escapeFile( `"${argument - .replace(/(\\*)"/gu, String.raw`$1$1\"`) - .replace(/(\\*)$/u, "$1$1")}"`, + .replace(/(\\*)"/g, String.raw`$1$1\"`) + .replace(/(\\*)$/, "$1$1")}"`, ), ) : (argument) => argument; diff --git a/tests/config/prettier-plugins/prettier-plugin-async-printer/index.cjs b/tests/config/prettier-plugins/prettier-plugin-async-printer/index.cjs index 28552aea1..7030218e4 100644 --- a/tests/config/prettier-plugins/prettier-plugin-async-printer/index.cjs +++ b/tests/config/prettier-plugins/prettier-plugin-async-printer/index.cjs @@ -31,7 +31,7 @@ module.exports = { return Promise.resolve( JSON.stringify({ ...ast, - print: ast.print?.replace(/\s+/gu, " ") ?? "", + print: ast.print?.replace(/\s+/g, " ") ?? "", }), ); }, diff --git a/tests/config/run-format-test.js b/tests/config/run-format-test.js index f40127d5f..6367eaf23 100644 --- a/tests/config/run-format-test.js +++ b/tests/config/run-format-test.js @@ -449,7 +449,7 @@ async function runTest({ if (!shouldSkipEolTest(code, formatResult.options)) { for (const eol of ["\r\n", "\r"]) { const { eolVisualizedOutput: output } = await format( - code.replace(/\n/gu, eol), + code.replace(/\n/g, eol), formatOptions, ); // Only if `endOfLine: "auto"` the result will be different @@ -457,7 +457,7 @@ async function runTest({ formatOptions.endOfLine === "auto" ? visualizeEndOfLine( // All `code` use `LF`, so the `eol` of result is always `LF` - formatResult.outputWithCursor.replace(/\n/gu, eol), + formatResult.outputWithCursor.replace(/\n/g, eol), ) : formatResult.eolVisualizedOutput; expect(output).toEqual(expected); diff --git a/tests/config/utilities/consistent-end-of-line.js b/tests/config/utilities/consistent-end-of-line.js index ecedbf7b0..e618ab542 100644 --- a/tests/config/utilities/consistent-end-of-line.js +++ b/tests/config/utilities/consistent-end-of-line.js @@ -1,6 +1,6 @@ function consistentEndOfLine(text) { let firstEndOfLine; - return text.replace(/\r\n?|\n/gu, (endOfLine) => { + return text.replace(/\r\n?|\n/g, (endOfLine) => { firstEndOfLine = firstEndOfLine ?? endOfLine; return firstEndOfLine; }); diff --git a/tests/config/utilities/create-snapshot.js b/tests/config/utilities/create-snapshot.js index 34ca8f54e..b8a217399 100644 --- a/tests/config/utilities/create-snapshot.js +++ b/tests/config/utilities/create-snapshot.js @@ -73,7 +73,7 @@ function createSnapshot( } input = visualizeRange(input, { rangeStart, rangeEnd }); - codeOffset = input.match(/^>?\s+1 \|/u)[0].length + 1; + codeOffset = input.match(/^>?\s+1 \|/)[0].length + 1; } if ("endOfLine" in formatOptions) { diff --git a/tests/config/utilities/visualize-end-of-line.js b/tests/config/utilities/visualize-end-of-line.js index 1db619aeb..9dec987e0 100644 --- a/tests/config/utilities/visualize-end-of-line.js +++ b/tests/config/utilities/visualize-end-of-line.js @@ -1,5 +1,5 @@ function visualizeEndOfLine(text) { - return text.replace(/\r\n?|\n/gu, (endOfLine) => { + return text.replace(/\r\n?|\n/g, (endOfLine) => { switch (endOfLine) { case "\n": return "\n"; diff --git a/tests/format/markdown/trim-space/format.test.js b/tests/format/markdown/trim-space/format.test.js index 95bcec5e2..74a758b71 100644 --- a/tests/format/markdown/trim-space/format.test.js +++ b/tests/format/markdown/trim-space/format.test.js @@ -6,7 +6,7 @@ function leadingTestCase() { return { name: "Trim leading U+0020 less than 4", code: paragraphs.join("\n"), - output: paragraphs.map((p) => p.replace(/^ +/u, "")).join("\n"), + output: paragraphs.map((p) => p.replace(/^ +/, "")).join("\n"), }; } diff --git a/tests/integration/__tests__/cache.js b/tests/integration/__tests__/cache.js index a466fb09d..5a7089cc6 100644 --- a/tests/integration/__tests__/cache.js +++ b/tests/integration/__tests__/cache.js @@ -114,7 +114,7 @@ describe("--cache option", () => { ]); expect(stderr.trim()).toEqual( expect.stringMatching( - /\[error\] Resolved --cache-location '.+' is a directory/u, + /\[error\] Resolved --cache-location '.+' is a directory/, ), ); }); @@ -144,8 +144,8 @@ describe("--cache option", () => { ]); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -158,8 +158,8 @@ describe("--cache option", () => { ]); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms \(unchanged\) \(cached\)$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/u), + expect.stringMatching(/^a\.js .+ms \(unchanged\) \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -178,8 +178,8 @@ describe("--cache option", () => { ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -193,8 +193,8 @@ describe("--cache option", () => { expect(secondStdout.split("\n")).toEqual( // the cache of `b.js` is only available. expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -213,8 +213,8 @@ describe("--cache option", () => { ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -229,8 +229,8 @@ describe("--cache option", () => { expect(secondStdout.split("\n")).toEqual( // the cache of `b.js` is only available. expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -245,8 +245,8 @@ describe("--cache option", () => { ]); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -261,8 +261,8 @@ describe("--cache option", () => { ]); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); }); @@ -284,8 +284,8 @@ describe("--cache option", () => { ]); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -320,8 +320,8 @@ describe("--cache option", () => { ); expect(thirdStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -347,8 +347,8 @@ describe("--cache option", () => { ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -405,8 +405,8 @@ describe("--cache option", () => { ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -416,8 +416,8 @@ describe("--cache option", () => { ); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms \(unchanged\) \(cached\)$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/u), + expect.stringMatching(/^a\.js .+ms \(unchanged\) \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -436,8 +436,8 @@ describe("--cache option", () => { ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -451,8 +451,8 @@ describe("--cache option", () => { expect(secondStdout.split("\n")).toEqual( // the cache of `b.js` is only available. expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -471,8 +471,8 @@ describe("--cache option", () => { ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -486,8 +486,8 @@ describe("--cache option", () => { ); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms \(unchanged\) \(cached\)$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/u), + expect.stringMatching(/^a\.js .+ms \(unchanged\) \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -502,8 +502,8 @@ describe("--cache option", () => { ]); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -518,8 +518,8 @@ describe("--cache option", () => { ]); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); }); @@ -541,8 +541,8 @@ describe("--cache option", () => { ]); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -577,8 +577,8 @@ describe("--cache option", () => { ); expect(thirdStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -604,8 +604,8 @@ describe("--cache option", () => { ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -653,7 +653,7 @@ describe("--cache option", () => { "*.js", ]); expect(stderr.trim()).toEqual( - expect.stringMatching(/\[error\] '.+' isn't a valid JSON file/u), + expect.stringMatching(/\[error\] '.+' isn't a valid JSON file/), ); }); @@ -686,8 +686,8 @@ describe("--cache option", () => { ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\)$/u), + expect.stringMatching(/^a\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -697,8 +697,8 @@ describe("--cache option", () => { ); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms \(unchanged\) \(cached\)$/u), - expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/u), + expect.stringMatching(/^a\.js .+ms \(unchanged\) \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); diff --git a/tests/integration/__tests__/config-file-typescript.js b/tests/integration/__tests__/config-file-typescript.js index f24b82ff4..1d6eb6fd1 100644 --- a/tests/integration/__tests__/config-file-typescript.js +++ b/tests/integration/__tests__/config-file-typescript.js @@ -7,7 +7,7 @@ const NODE_TS_SUPPORT_FLAGS = ["--experimental-strip-types"]; const NODE_JS_MAJOR_VERSION = Number(process.versions.node.split(".")[0]); const getOutputTabWidth = (code) => - code.match(/\n(?\s+)return/u).groups.indention.length; + code.match(/\n(?\s+)return/).groups.indention.length; const code = "function foo() {return bar}"; const TAB_WIDTH_3_OUTPUT = outdent` @@ -58,7 +58,7 @@ if (NODE_JS_MAJOR_VERSION < 22) { status: "non-zero", stdout: "", write: [], - stderr: expect.stringMatching(/Unknown file extension ".ts" for/u), + stderr: expect.stringMatching(/Unknown file extension ".ts" for/), }); runCli("cli/config/ts/auto-discovery/", ["--stdin-filepath", "foo.js"], { @@ -68,7 +68,7 @@ if (NODE_JS_MAJOR_VERSION < 22) { status: "non-zero", stdout: "", write: [], - stderr: expect.stringMatching(/bad option: --experimental-strip-types/u), + stderr: expect.stringMatching(/bad option: --experimental-strip-types/), }); }); } diff --git a/tests/integration/__tests__/config-invalid.js b/tests/integration/__tests__/config-invalid.js index d6840ae62..14238d463 100644 --- a/tests/integration/__tests__/config-invalid.js +++ b/tests/integration/__tests__/config-invalid.js @@ -16,7 +16,7 @@ describe("throw error for unsupported extension", () => { describe("throw error with invalid config format", () => { runCli("cli/config/invalid", ["--config", "file/.prettierrc"]).test({ status: "non-zero", - stderr: expect.stringMatching(/Cannot find package '--invalid--'/u), + stderr: expect.stringMatching(/Cannot find package '--invalid--'/), }); }); diff --git a/tests/integration/__tests__/config-resolution.js b/tests/integration/__tests__/config-resolution.js index b2f733dd7..9a581276a 100644 --- a/tests/integration/__tests__/config-resolution.js +++ b/tests/integration/__tests__/config-resolution.js @@ -292,7 +292,7 @@ test(".js config file", async () => { await expect(prettier.resolveConfig(file)).resolves.toMatchObject(config); } - const cjsError = /module is not defined in ES module scope/u; + const cjsError = /module is not defined in ES module scope/; for (const directoryName of [ "cjs-prettier-config-js-in-type-module", "cjs-prettierrc-js-in-type-module", @@ -301,7 +301,7 @@ test(".js config file", async () => { await expect(prettier.resolveConfig(file)).rejects.toThrow(cjsError); } - const mjsError = /Unexpected token 'export'/u; + const mjsError = /Unexpected token 'export'/; for (const directoryName of [ "mjs-prettier-config-js-in-type-commonjs", // Node.js v22.7 throws `MODULE_TYPELESS_PACKAGE_JSON` when `type` missed in package.json @@ -371,7 +371,7 @@ test(".json5 config file", async () => { test(".json5 config file(invalid)", async () => { const parentDirectory = new URL("../cli/config/rc-json5/", import.meta.url); const file = new URL("./invalid/foo.js", parentDirectory); - const error = /JSON5: invalid end of input at 2:1/u; + const error = /JSON5: invalid end of input at 2:1/; await expect(prettier.resolveConfig(file)).rejects.toThrow(error); }); diff --git a/tests/integration/__tests__/infer-parser.js b/tests/integration/__tests__/infer-parser.js index b80d452b0..180902a45 100644 --- a/tests/integration/__tests__/infer-parser.js +++ b/tests/integration/__tests__/infer-parser.js @@ -191,13 +191,13 @@ describe("Allow plugin to override builtin plugins", () => { describe("API with no path and no parser", () => { test("prettier.format", async () => { await expect(prettier.format(" foo ( )")).rejects.toThrow( - /No parser and no file path given, couldn't infer a parser\./u, + /No parser and no file path given, couldn't infer a parser\./, ); }); test("prettier.check", async () => { await expect(prettier.check(" foo ( )")).rejects.toThrow( - /No parser and no file path given, couldn't infer a parser\./u, + /No parser and no file path given, couldn't infer a parser\./, ); }); }); diff --git a/tests/integration/__tests__/invalid-ignore.js b/tests/integration/__tests__/invalid-ignore.js index 7df8708f7..c7caa4a03 100644 --- a/tests/integration/__tests__/invalid-ignore.js +++ b/tests/integration/__tests__/invalid-ignore.js @@ -17,6 +17,6 @@ describe("throw error with invalid ignore", () => { "../cli/invalid-ignore/.prettierignore", ), }), - ).rejects.toThrow(/EISDIR: illegal operation on a directory/u); + ).rejects.toThrow(/EISDIR: illegal operation on a directory/); }); }); diff --git a/tests/integration/__tests__/log-level.js b/tests/integration/__tests__/log-level.js index ba51ac3ee..2bc539305 100644 --- a/tests/integration/__tests__/log-level.js +++ b/tests/integration/__tests__/log-level.js @@ -128,6 +128,6 @@ async function runCliWithLogLevel(logLevel, patterns) { expect(stderr).toMatch(pattern); } } else { - expect(stderr).toMatch(/^\s*$/u); + expect(stderr).toMatch(/^\s*$/); } } diff --git a/tests/integration/__tests__/patterns-dirs.js b/tests/integration/__tests__/patterns-dirs.js index b73d531ee..683238305 100644 --- a/tests/integration/__tests__/patterns-dirs.js +++ b/tests/integration/__tests__/patterns-dirs.js @@ -41,7 +41,7 @@ testPatterns("1a - with *.foo plugin", [ "--plugin=../../plugins/extensions/plugin.cjs", ]); testPatterns("1b - special characters in dir name", ["dir1", "!dir"], { - stdout: expect.stringMatching(/!dir[/\\]a\.js/u), + stdout: expect.stringMatching(/!dir[/\\]a\.js/), }); testPatterns("1c", ["dir1", "empty"], { status: 1 }); @@ -376,7 +376,7 @@ function testPatterns( (namePrefix ? namePrefix + ": " : "") + "prettier " + cliArgs - .map((arg) => (/^[\w./=-]+$/u.test(arg) ? arg : `'${arg}'`)) + .map((arg) => (/^[\w./=-]+$/.test(arg) ? arg : `'${arg}'`)) .join(" "); describe(testName, () => { diff --git a/tests/integration/__tests__/plugin-options-string.js b/tests/integration/__tests__/plugin-options-string.js index f6ad61b37..27c393de8 100644 --- a/tests/integration/__tests__/plugin-options-string.js +++ b/tests/integration/__tests__/plugin-options-string.js @@ -66,7 +66,7 @@ describe("Non exists plugin", () => { { input: "hello-world" }, ).test({ stdout: "", - stderr: expect.stringMatching(/Cannot find package '--invalid--'/u), + stderr: expect.stringMatching(/Cannot find package '--invalid--'/), status: 1, write: [], }); diff --git a/tests/integration/__tests__/print-doc-to-string.js b/tests/integration/__tests__/print-doc-to-string.js index deb2987d6..076dd9046 100644 --- a/tests/integration/__tests__/print-doc-to-string.js +++ b/tests/integration/__tests__/print-doc-to-string.js @@ -20,7 +20,7 @@ test("Throw error on invalid doc", () => { null, Promise.resolve("1"), (function* () {})(), - /regexp/gu, + /regexp/g, new Date(), new Error("error"), Buffer.from("buffer"), diff --git a/tests/integration/plugins/languages/is-supported.js b/tests/integration/plugins/languages/is-supported.js index 6bea97665..6a766348a 100644 --- a/tests/integration/plugins/languages/is-supported.js +++ b/tests/integration/plugins/languages/is-supported.js @@ -14,7 +14,7 @@ const languages = [ throw new Error("Unexpected non absolute path"); } - return /(?[\\/])\.husky\k[^\\/]+$/u.test(filepath); + return /(?[\\/])\.husky\k[^\\/]+$/.test(filepath); }, }, ]; diff --git a/tests/integration/run-cli.js b/tests/integration/run-cli.js index 4959bfaa7..19b7e562f 100644 --- a/tests/integration/run-cli.js +++ b/tests/integration/run-cli.js @@ -185,7 +185,7 @@ function runCli(dir, args = [], options = {}) { // If ignoreLineEndings is specified, \r is simply deleted instead if (name === "stdout" || name === "stderr") { value = result[name].replace( - /\r/gu, + /\r/g, options.ignoreLineEndings ? "" : "/*CR*/", ); } diff --git a/tests/unit/whitespace-utilities.js b/tests/unit/whitespace-utilities.js index b2d22cd37..67f28e34f 100644 --- a/tests/unit/whitespace-utilities.js +++ b/tests/unit/whitespace-utilities.js @@ -111,7 +111,7 @@ describe("split", () => { " a a a ", ]) { it(JSON.stringify(string), () => { - expect(utils.split(string)).toEqual(string.split(/ +/u)); + expect(utils.split(string)).toEqual(string.split(/ +/)); }); } }); diff --git a/website/playground/VersionLink.jsx b/website/playground/VersionLink.jsx index e96cfad0a..5ba62f54d 100644 --- a/website/playground/VersionLink.jsx +++ b/website/playground/VersionLink.jsx @@ -1,11 +1,11 @@ import { Teleport } from "vue"; export default function VersionLink({ version }) { - const match = version.match(/^pr-(\d+)$/u); + const match = version.match(/^pr-(\d+)$/); let href; if (match) { href = `pull/${match[1]}`; - } else if (/\.0$/u.test(version)) { + } else if (/\.0$/.test(version)) { href = `releases/tag/${version}`; } else { href = `blob/main/CHANGELOG.md#${version.replaceAll(".", "")}`; diff --git a/website/playground/dummyId.js b/website/playground/dummyId.js index 7bf01a9bb..ea8f9b2a6 100644 --- a/website/playground/dummyId.js +++ b/website/playground/dummyId.js @@ -48,7 +48,7 @@ function getRandomElement(array) { } function camelCase(string) { - return string.replaceAll(/_(\w)/gu, (_, c) => c.toUpperCase()); + return string.replaceAll(/_(\w)/g, (_, c) => c.toUpperCase()); } export default function generateDummyId() { diff --git a/website/playground/index.jsx b/website/playground/index.jsx index da7e1de58..9613f749b 100644 --- a/website/playground/index.jsx +++ b/website/playground/index.jsx @@ -123,7 +123,7 @@ function augmentOption(option) { option.cliName = "--" + (option.inverted ? "no-" : "") + - option.name.replaceAll(/(?<=[a-z])(?=[A-Z])/gu, "-").toLowerCase(); + option.name.replaceAll(/(?<=[a-z])(?=[A-Z])/g, "-").toLowerCase(); return option; } diff --git a/website/playground/markdown.js b/website/playground/markdown.js index af0339e58..f8c8ab085 100644 --- a/website/playground/markdown.js +++ b/website/playground/markdown.js @@ -71,7 +71,7 @@ function formatCLIOptions(cliOptions) { } function codeBlock(content, syntax) { - const backtickSequences = content.match(/`+/gu) || []; + const backtickSequences = content.match(/`+/g) || []; const longestBacktickSequenceLength = Math.max( ...backtickSequences.map(({ length }) => length), ); diff --git a/website/playground/utilities.js b/website/playground/utilities.js index 2a954ff32..371556f86 100644 --- a/website/playground/utilities.js +++ b/website/playground/utilities.js @@ -1,5 +1,5 @@ export function fixPrettierVersion(version) { - const match = version.match(/^\d+\.\d+\.\d+-pr.(\d+)$/u); + const match = version.match(/^\d+\.\d+\.\d+-pr.(\d+)$/); if (match) { return `pr-${match[1]}`; } @@ -53,13 +53,13 @@ export function getCodemirrorMode(parser) { } const astAutoFold = { - estree: /^\s*"(loc|start|end|tokens|\w+Comments|comments)":/u, - postcss: /^\s*"(source|input|raws|file)":/u, - html: /^\s*"(\w+Span|valueTokens|tokens|file|tagDefinition)":/u, - mdast: /^\s*"position":/u, - yaml: /^\s*"position":/u, - glimmer: /^\s*"loc":/u, - graphql: /^\s*"loc":/u, + estree: /^\s*"(loc|start|end|tokens|\w+Comments|comments)":/, + postcss: /^\s*"(source|input|raws|file)":/, + html: /^\s*"(\w+Span|valueTokens|tokens|file|tagDefinition)":/, + mdast: /^\s*"position":/, + yaml: /^\s*"position":/, + glimmer: /^\s*"loc":/, + graphql: /^\s*"loc":/, }; export function getAstAutoFold(parser) { diff --git a/website/plugins/llms-txt-plugin.mjs b/website/plugins/llms-txt-plugin.mjs index dd60b5c9c..f312eea27 100644 --- a/website/plugins/llms-txt-plugin.mjs +++ b/website/plugins/llms-txt-plugin.mjs @@ -44,11 +44,11 @@ export default function llmsTxtPlugin(context) { let title = entry.name.replace(".md", ""); let description = ""; - const frontmatterMatch = content.match(/^---\n(.*?)\n---/su); + const frontmatterMatch = content.match(/^---\n(.*?)\n---/s); if (frontmatterMatch) { - const titleMatch = frontmatterMatch[1].match(/title:\s*(.+)/u); + const titleMatch = frontmatterMatch[1].match(/title:\s*(.+)/); const descriptionMatch = - frontmatterMatch[1].match(/description:\s*(.+)/u); + frontmatterMatch[1].match(/description:\s*(.+)/); if (titleMatch) { title = titleMatch[1].trim(); diff --git a/website/static/service-worker.mjs b/website/static/service-worker.mjs index 8b92d0796..2366739d2 100644 --- a/website/static/service-worker.mjs +++ b/website/static/service-worker.mjs @@ -47,4 +47,4 @@ toolbox.router.default = toolbox.networkFirst; // For scripts, stylesheets and images, we can use the "fastest" strategy // This means you need to reload twice to get new changes -toolbox.router.get(/\.(js|css|png|svg)$/u, toolbox.fastest); +toolbox.router.get(/\.(js|css|png|svg)$/, toolbox.fastest);