From 105c303f1ac99f1a192ed5be9f4f76b9eb8ef2bd Mon Sep 17 00:00:00 2001 From: Evan Jacobs Date: Thu, 19 Nov 2026 15:19:00 -0500 Subject: [PATCH 01/15] build: run the build, tests, and tooling as strict TypeScript Node runs the .mts build and test scripts directly (Node 22.18 or later), and tsc typechecks every TypeScript file. The integration suites are bundled with esbuild before the test run, and unit tests run in Node without a VS Code window. glob and d3-color are no longer dependencies. --- .gitignore | 3 + .prettierignore | 6 +- .vscode/launch.json | 7 +- .vscode/tasks.json | 7 ++ .vscodeignore | 8 ++- build.mjs | 41 ------------ build.mts | 65 +++++++++++++++++++ package-lock.json | 40 ++++++------ package.json | 26 +++++--- scripts/bundle-integration-tests.mts | 24 +++++++ scripts/unit-tests.mts | 43 ++++++++++++ src/tests/runTests.js | 39 ----------- src/tests/runTests.mts | 32 +++++++++ .../{extension.test.js => extension.test.ts} | 5 +- src/tests/suite/index.js | 26 -------- src/tests/suite/index.ts | 25 +++++++ src/tests/vscodeVersion.mts | 2 + tsconfig.json | 34 ++++------ 18 files changed, 267 insertions(+), 166 deletions(-) delete mode 100644 build.mjs create mode 100644 build.mts create mode 100644 scripts/bundle-integration-tests.mts create mode 100644 scripts/unit-tests.mts delete mode 100644 src/tests/runTests.js create mode 100644 src/tests/runTests.mts rename src/tests/suite/{extension.test.js => extension.test.ts} (81%) delete mode 100644 src/tests/suite/index.js create mode 100644 src/tests/suite/index.ts create mode 100644 src/tests/vscodeVersion.mts diff --git a/.gitignore b/.gitignore index 556fd86..45382a3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +.DS_Store node_modules dist .vscode-test +.integration-test/ +syntaxes/*.json diff --git a/.prettierignore b/.prettierignore index 33e61f4..135cf98 100644 --- a/.prettierignore +++ b/.prettierignore @@ -2,5 +2,9 @@ package-lock.json .github node_modules .vscode-test -src/tests +.integration-test/ +src/tests/suite/colorize-fixtures +src/tests/suite/colorize-results dist +.claude/ +syntaxes/src/css.tmLanguage.json diff --git a/.vscode/launch.json b/.vscode/launch.json index 5c79200..a75a1a5 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -8,7 +8,7 @@ "request": "launch", "runtimeExecutable": "${execPath}", "args": [ - "--extensionDevelopmentPath=${workspaceRoot}", + "--extensionDevelopmentPath=${workspaceFolder}", "${workspaceFolder}/src/tests/suite/colorize-fixtures" ], "outFiles": ["${workspaceFolder}/dist/**/*.js"], @@ -24,9 +24,10 @@ "args": [ "--disable-extensions", "--extensionDevelopmentPath=${workspaceFolder}", - "--extensionTestsPath=${workspaceFolder}/src/tests/suite/index.js" + "--extensionTestsPath=${workspaceFolder}/.integration-test/index.js" ], - "internalConsoleOptions": "openOnSessionStart" + "internalConsoleOptions": "openOnSessionStart", + "preLaunchTask": "npm: pretest" } ] } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 8d8c38f..a084f36 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -19,6 +19,13 @@ }, "label": "npm: watch", "detail": "ESBuild watch mode" + }, + { + "type": "npm", + "script": "pretest", + "problemMatcher": [], + "label": "npm: pretest", + "detail": "Build the extension and bundle the integration tests" } ] } diff --git a/.vscodeignore b/.vscodeignore index e927842..57c2ff0 100644 --- a/.vscodeignore +++ b/.vscodeignore @@ -1,15 +1,19 @@ .changeset/** +.claude/** .editorConfig .github/** .gitignore .husky/** .nvmrc .prettierignore +.integration-test/** .vscode-test/** .vscode/** **/*.map -build.mjs +AGENTS.md +build.mts +scripts/** docs/** src/** -test/ +syntaxes/src/** tsconfig.json diff --git a/build.mjs b/build.mjs deleted file mode 100644 index 6a004c6..0000000 --- a/build.mjs +++ /dev/null @@ -1,41 +0,0 @@ -import esbuild from "esbuild"; - -const production = process.argv[2] === "--production"; -const watch = process.argv[2] === "--watch"; -const context = await esbuild - .context({ - entryPoints: ["./src/extension.ts"], - bundle: true, - outdir: "dist", - external: ["vscode"], - format: "cjs", - sourcemap: !production, - minify: production, - platform: "node", - mainFields: ["module", "main"], - target: "ES2022", - plugins: [ - { - name: "watch", - setup(build) { - build.onEnd(() => { - if (watch) console.log("build finished"); - }); - build.onStart(() => { - if (watch) console.log("building..."); - }); - }, - }, - ], - }) - .catch((e) => { - console.error(e); - process.exit(1); - }); - -if (watch) { - await context.watch(); -} else { - context.rebuild(); - context.dispose(); -} diff --git a/build.mts b/build.mts new file mode 100644 index 0000000..07a1df7 --- /dev/null +++ b/build.mts @@ -0,0 +1,65 @@ +import { spawnSync } from "node:child_process"; +import { watch as watchFiles } from "node:fs"; + +import esbuild from "esbuild"; + +const production = process.argv[2] === "--production"; +const watch = process.argv[2] === "--watch"; + +// A subprocess, not an import: watch mode regenerates, and a module imported once would serve stale grammars. +const generateGrammars = () => + spawnSync(process.execPath, ["./syntaxes/src/generate.mts"], { + stdio: "inherit", + }).status === 0; + +if (!generateGrammars()) process.exit(1); + +const context = await esbuild + .context({ + entryPoints: ["./src/extension.ts"], + bundle: true, + outdir: "dist", + external: ["vscode"], + format: "cjs", + sourcemap: !production, + minify: production, + platform: "node", + mainFields: ["module", "main"], + target: "ES2022", + plugins: watch + ? [ + { + name: "watch", + setup(build) { + build.onEnd(() => console.log("build finished")); + build.onStart(() => console.log("building...")); + }, + }, + ] + : [], + }) + .catch((e) => { + console.error(e); + process.exit(1); + }); + +if (watch) { + let pending: NodeJS.Timeout | undefined; + watchFiles("./syntaxes/src", { recursive: true }, () => { + clearTimeout(pending); + pending = setTimeout(() => { + console.log("building..."); + if (!generateGrammars()) console.error("grammar generation failed"); + console.log("build finished"); + }, 100); + }); + await context.watch(); +} else { + // esbuild has already printed the errors when rebuild rejects. + const built = await context.rebuild().then( + () => true, + () => false, + ); + await context.dispose(); + if (!built) process.exit(1); +} diff --git a/package-lock.json b/package-lock.json index b2cac86..4ef66bd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,33 +1,32 @@ { "name": "vscode-styled-components", - "version": "1.7.9", + "version": "1.7.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "vscode-styled-components", - "version": "1.7.9", + "version": "1.7.10", "license": "MIT", "dependencies": { "@styled/typescript-styled-plugin": "^1.1.1", - "d3-color": "^3.1.0", "vscode-css-languageservice": "^6.3.10" }, "devDependencies": { "@changesets/changelog-github": "^1.0.1", "@changesets/cli": "^3.0.3", - "@types/d3-color": "^3.1.3", "@types/mocha": "^10.0.10", "@types/node": "^24.19.2", "@types/vscode": "^1.73.1", "@vscode/test-electron": "^3.1.0", "@vscode/vsce": "^4.1.0", "esbuild": "^0.28.2", - "glob": "^13.0.6", "husky": "^9.1.7", "mocha": "^12.0.3", "prettier": "^3.9.10", - "typescript": "^7.0.2" + "typescript": "^7.0.2", + "vscode-oniguruma": "^2.0.1", + "vscode-textmate": "^9.3.2" }, "engines": { "vscode": "^1.73.0" @@ -1374,13 +1373,6 @@ "vscode-languageserver-types": "3.18.4" } }, - "node_modules/@types/d3-color": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz", - "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/mocha": { "version": "10.0.10", "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.10.tgz", @@ -2282,14 +2274,6 @@ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", "dev": true }, - "node_modules/d3-color": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", - "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", - "engines": { - "node": ">=12" - } - }, "node_modules/dataloader": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/dataloader/-/dataloader-2.2.3.tgz", @@ -4032,6 +4016,20 @@ "integrity": "sha512-nQsacoiijvl0fRf2q28uFDrAVwRhdCa3QveiF7/CX0r18mLR5FU/1WskSsCKOjmEbtteKUnY8x8Yzxop+k0zwg==", "license": "MIT" }, + "node_modules/vscode-oniguruma": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/vscode-oniguruma/-/vscode-oniguruma-2.0.1.tgz", + "integrity": "sha512-poJU8iHIWnC3vgphJnrLZyI3YdqRlR27xzqDmpPXYzA93R4Gk8z7T6oqDzDoHjoikA2aS82crdXFkjELCdJsjQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vscode-textmate": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/vscode-textmate/-/vscode-textmate-9.3.2.tgz", + "integrity": "sha512-n2uGbUcrjhUEBH16uGA0TvUfhWwliFZ1e3+pTjrkim1Mt7ydB41lV08aUvsi70OlzDWp6X7Bx3w/x3fAXIsN0Q==", + "dev": true, + "license": "MIT" + }, "node_modules/vscode-uri": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.2.0.tgz", diff --git a/package.json b/package.json index 58b3ebb..673fa4b 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,12 @@ "url": "https://github.com/styled-components/vscode-styled-components.git" }, "main": "dist/extension.js", + "devEngines": { + "runtime": { + "name": "node", + "version": ">=22.18" + } + }, "engines": { "vscode": "^1.73.0" }, @@ -22,11 +28,14 @@ "scripts": { "format": "prettier --write .", "lint": "prettier --check .", - "compile": "node ./build.mjs", - "pretest": "npm run compile", - "test": "node ./src/tests/runTests.js", - "watch": "node ./build.mjs --watch", - "vscode:prepublish": "node ./build.mjs --production", + "compile": "node ./build.mts", + "pretest": "npm run compile && node ./scripts/bundle-integration-tests.mts", + "test": "node ./src/tests/runTests.mts", + "test:unit": "node ./scripts/unit-tests.mts", + "tokenize": "node scripts/tokenize.mts", + "bench:grammar": "node scripts/bench-grammar.mts", + "watch": "node ./build.mts --watch", + "vscode:prepublish": "node ./build.mts --production", "prepare": "husky", "release": "gh release view \"v$npm_package_version\" >/dev/null 2>&1 || (vsce publish --oidc --skip-duplicate && changeset publish)" }, @@ -90,23 +99,22 @@ }, "dependencies": { "@styled/typescript-styled-plugin": "^1.1.1", - "d3-color": "^3.1.0", "vscode-css-languageservice": "^6.3.10" }, "devDependencies": { "@changesets/changelog-github": "^1.0.1", "@changesets/cli": "^3.0.3", - "@types/d3-color": "^3.1.3", "@types/mocha": "^10.0.10", "@types/node": "^24.19.2", "@types/vscode": "^1.73.1", "@vscode/test-electron": "^3.1.0", "@vscode/vsce": "^4.1.0", "esbuild": "^0.28.2", - "glob": "^13.0.6", "husky": "^9.1.7", "mocha": "^12.0.3", "prettier": "^3.9.10", - "typescript": "^7.0.2" + "typescript": "^7.0.2", + "vscode-oniguruma": "^2.0.1", + "vscode-textmate": "^9.3.2" } } diff --git a/scripts/bundle-integration-tests.mts b/scripts/bundle-integration-tests.mts new file mode 100644 index 0000000..55f9992 --- /dev/null +++ b/scripts/bundle-integration-tests.mts @@ -0,0 +1,24 @@ +// Bundles the integration suites into .integration-test/ for VS Code's extension host, whose Node does not strip types. +// "vscode" is supplied by the host; mocha loads from node_modules. +import { globSync, rmSync } from "node:fs"; + +import esbuild from "esbuild"; + +const outdir = ".integration-test"; + +rmSync(outdir, { recursive: true, force: true }); + +await esbuild.build({ + entryPoints: [ + "src/tests/suite/index.ts", + ...globSync("src/tests/suite/*.test.ts"), + ], + outbase: "src/tests/suite", + outdir, + bundle: true, + external: ["vscode", "mocha"], + format: "cjs", + platform: "node", + sourcemap: true, + target: "node22", +}); diff --git a/scripts/unit-tests.mts b/scripts/unit-tests.mts new file mode 100644 index 0000000..ce2ad24 --- /dev/null +++ b/scripts/unit-tests.mts @@ -0,0 +1,43 @@ +import { spawnSync } from "node:child_process"; +import { globSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import esbuild from "esbuild"; + +const entryPoints = [ + // The integration suites need VS Code's extension host (scripts/bundle-integration-tests.mts). + ...globSync("src/**/*.test.ts", { exclude: ["src/tests/suite/**"] }), + ...globSync("syntaxes/src/**/*.test.ts"), +]; + +if (entryPoints.length === 0) { + console.error("No unit test files found."); + process.exit(1); +} + +// Each run bundles into its own folder, so concurrent runs in one checkout do not delete each other's files. +const outdir = mkdtempSync(join(tmpdir(), "unit-test-")); + +try { + const { metafile } = await esbuild.build({ + entryPoints, + outdir, + bundle: true, + format: "cjs", + metafile: true, + platform: "node", + target: "node22", + }); + + const bundles = Object.keys(metafile.outputs).filter((file) => + file.endsWith(".js"), + ); + const result = spawnSync(process.execPath, ["--test", ...bundles], { + stdio: "inherit", + }); + + process.exitCode = result.status ?? 1; +} finally { + rmSync(outdir, { recursive: true, force: true }); +} diff --git a/src/tests/runTests.js b/src/tests/runTests.js deleted file mode 100644 index 6121631..0000000 --- a/src/tests/runTests.js +++ /dev/null @@ -1,39 +0,0 @@ -const fs = require('fs'); -const os = require('os'); -const path = require('path'); -const runTests = require('@vscode/test-electron').runTests; - -// Built-in themes and grammars change between VS Code releases, so colorize-results only match the version they were captured with. Bump deliberately and regenerate. -const vscodeVersion = '1.145.2'; - -async function main() { - try { - // The folder containing the Extension Manifest package.json - // Passed to `--extensionDevelopmentPath` - const extensionDevelopmentPath = path.resolve(__dirname, '../../'); - - // The path to the extension test script - // Passed to --extensionTestsPath - const extensionTestsPath = path.resolve(__dirname, './suite/index'); - - const launchArgs = [ - // This disables all extensions except the one being tested - '--disable-extensions', - // The default user-data dir sits under the checkout, which pushes VS Code's IPC socket past macOS's 103-char limit (listen EINVAL). - `--user-data-dir=${fs.mkdtempSync(path.join(os.tmpdir(), 'vsc-'))}`, - ]; - - // Download VS Code, unzip it and run the integration test - await runTests({ - extensionDevelopmentPath, - extensionTestsPath, - launchArgs, - version: vscodeVersion, - }); - } catch (err) { - console.error('Failed to run tests', err); - process.exit(1); - } -} - -main(); diff --git a/src/tests/runTests.mts b/src/tests/runTests.mts new file mode 100644 index 0000000..4d94247 --- /dev/null +++ b/src/tests/runTests.mts @@ -0,0 +1,32 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { runTests } from "@vscode/test-electron"; + +import vscodeVersion from "./vscodeVersion.mts"; + +const extensionDevelopmentPath = path.resolve(import.meta.dirname, "../../"); + +// The bundle scripts/bundle-integration-tests.mts writes in `pretest`. +const extensionTestsPath = path.resolve( + extensionDevelopmentPath, + ".integration-test/index", +); + +// The default user-data dir sits under the checkout, which pushes VS Code's IPC socket past macOS's 103-char limit (listen EINVAL). +const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "vsc-")); + +try { + await runTests({ + extensionDevelopmentPath, + extensionTestsPath, + launchArgs: ["--disable-extensions", `--user-data-dir=${userDataDir}`], + version: vscodeVersion, + }); +} catch (err) { + console.error("Failed to run tests", err); + process.exitCode = 1; +} finally { + fs.rmSync(userDataDir, { recursive: true, force: true }); +} diff --git a/src/tests/suite/extension.test.js b/src/tests/suite/extension.test.ts similarity index 81% rename from src/tests/suite/extension.test.js rename to src/tests/suite/extension.test.ts index 462d844..9f03a84 100644 --- a/src/tests/suite/extension.test.js +++ b/src/tests/suite/extension.test.ts @@ -1,7 +1,6 @@ -"use strict"; +import assert from "node:assert"; -const assert = require("assert"); -const vscode = require("vscode"); +import * as vscode from "vscode"; const EXTENSION_ID = "styled-components.vscode-styled-components"; diff --git a/src/tests/suite/index.js b/src/tests/suite/index.js deleted file mode 100644 index 8e89bc7..0000000 --- a/src/tests/suite/index.js +++ /dev/null @@ -1,26 +0,0 @@ -const path = require('path'); -const Mocha = require('mocha'); -const { glob } = require('glob'); - -async function run() { - const mocha = new Mocha({ - ui: 'tdd' - }); - - const testsRoot = path.resolve(__dirname, '..'); - const files = await glob('**/**.test.js', { cwd: testsRoot }); - - files.forEach(f => mocha.addFile(path.resolve(testsRoot, f))); - - return new Promise((resolve, reject) => { - mocha.run(failures => { - if (failures > 0) { - reject(new Error(`${failures} tests failed.`)); - } else { - resolve(); - } - }); - }); -} - -module.exports.run = run; diff --git a/src/tests/suite/index.ts b/src/tests/suite/index.ts new file mode 100644 index 0000000..ef69e92 --- /dev/null +++ b/src/tests/suite/index.ts @@ -0,0 +1,25 @@ +import fs from "node:fs"; +import path from "node:path"; + +import Mocha from "mocha"; + +// Runs inside the bundle in .integration-test/, which holds every *.test.js next to this file. +export async function run() { + const mocha = new Mocha({ + ui: "tdd", + }); + + fs.readdirSync(__dirname) + .filter((file) => file.endsWith(".test.js")) + .forEach((file) => mocha.addFile(path.resolve(__dirname, file))); + + return new Promise((resolve, reject) => { + mocha.run((failures) => { + if (failures > 0) { + reject(new Error(`${failures} tests failed.`)); + } else { + resolve(); + } + }); + }); +} diff --git a/src/tests/vscodeVersion.mts b/src/tests/vscodeVersion.mts new file mode 100644 index 0000000..f425602 --- /dev/null +++ b/src/tests/vscodeVersion.mts @@ -0,0 +1,2 @@ +// Built-in themes and grammars change between VS Code releases, so colorize-results only match the version they were captured with. Bump deliberately and regenerate. +export default "1.145.2"; diff --git a/tsconfig.json b/tsconfig.json index 2a4e03d..eb02417 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,26 +1,18 @@ { "compilerOptions": { - "module": "commonjs", - "target": "ES2021", - "outDir": "dist", - "rootDir": ".", - "lib": ["ES2021"], - "types": ["node"], - "sourceMap": true, + "allowImportingTsExtensions": true, + "erasableSyntaxOnly": true, + "lib": ["ES2022"], + "module": "esnext", + "moduleDetection": "force", + "moduleResolution": "bundler", + "noEmit": true, "resolveJsonModule": true, - "esModuleInterop": true, - "strict": true /* enable all strict type-checking options */ - /* Additional Checks */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - - // uncomment the below when debugging the typescript styled plugin - // "plugins": [ - // { - // "name": "../typescript-styled-plugin" - // } - // ] + "strict": true, + "target": "ES2022", + "types": ["node", "mocha"], + "verbatimModuleSyntax": true }, - "exclude": ["node_modules", ".vscode-test", "src/tests"] + "include": ["build.mts", "scripts", "src", "syntaxes"], + "exclude": ["node_modules", "src/tests/suite/colorize-fixtures"] } From f4ecc8f59d98e8dd5c9439b8c3f80911b2d57c06 Mon Sep 17 00:00:00 2001 From: Evan Jacobs Date: Thu, 19 Nov 2026 15:19:01 -0500 Subject: [PATCH 02/15] ci: check Conventional Commits on every commit and PR title A commit-msg hook and a "Commit messages" CI job check each message and the PR title. The release PR and Dependabot PRs use conventional titles, and CI runs the unit tests and typecheck in the Lint job. --- .github/dependabot.yml | 2 ++ .github/workflows/ci.yml | 6 ++++ .github/workflows/commit-messages.yml | 42 +++++++++++++++++++++++++++ .github/workflows/release.yml | 4 ++- .husky/commit-msg | 1 + docs/changesets.md | 22 ++++++++++++-- docs/github-actions.md | 2 +- scripts/check-commit-message.sh | 30 +++++++++++++++++++ 8 files changed, 104 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/commit-messages.yml create mode 100644 .husky/commit-msg create mode 100755 scripts/check-commit-message.sh diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 1e7dba6..c2c464d 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -3,6 +3,8 @@ version: 2 updates: - package-ecosystem: github-actions directory: / + commit-message: + prefix: ci cooldown: default-days: 7 schedule: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 05b1b33..fc2df8c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,6 +37,12 @@ jobs: - name: Check formatting run: npm run lint + - name: Typecheck + run: npx tsc --noEmit -p . + + - name: Unit tests + run: npm run test:unit + test: name: Test (${{ matrix.os }}) strategy: diff --git a/.github/workflows/commit-messages.yml b/.github/workflows/commit-messages.yml new file mode 100644 index 0000000..cb8a694 --- /dev/null +++ b/.github/workflows/commit-messages.yml @@ -0,0 +1,42 @@ +name: Commit Messages + +# Separate from ci.yml so editing a PR title reruns only this check, not the OS matrix. +on: + pull_request: + branches: + - main + types: [opened, edited, synchronize, reopened] + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + commit-messages: + name: Commit messages + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + # A squash merge commits the PR title; a rebase merge commits each commit. + - name: Check the PR title and every commit + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + PR_TITLE: ${{ github.event.pull_request.title }} + run: | + status=0 + sh scripts/check-commit-message.sh -m "$PR_TITLE" || status=1 + for sha in $(git rev-list "$BASE_SHA..$HEAD_SHA"); do + git log -1 --format=%B "$sha" > "$RUNNER_TEMP/message" + sh scripts/check-commit-message.sh "$RUNNER_TEMP/message" || status=1 + done + exit $status diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1ff3f7e..a0e4083 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -44,11 +44,13 @@ jobs: - run: npm ci - # With pending changesets this opens or updates the "Version Packages" PR; once that PR merges, + # With pending changesets this opens or updates the "chore: version packages" PR; once that PR merges, # `npm run release` publishes to the VS Code Marketplace via trusted publishing (OIDC) and tags vX.Y.Z. # RELEASE_GITHUB_TOKEN (a PAT) lets CI run on the version PR; the job token works but triggers no checks. - name: Version or publish uses: changesets/action@ae32849d5ba541f9ae29e40e22a623bc13562f51 # v2.1.2 with: + commit-message: "chore: version packages" github-token: ${{ secrets.RELEASE_GITHUB_TOKEN || github.token }} + pr-title: "chore: version packages" publish-script: npm run release diff --git a/.husky/commit-msg b/.husky/commit-msg new file mode 100644 index 0000000..d216181 --- /dev/null +++ b/.husky/commit-msg @@ -0,0 +1 @@ +sh scripts/check-commit-message.sh --local "$1" diff --git a/docs/changesets.md b/docs/changesets.md index bad5015..4e0f543 100644 --- a/docs/changesets.md +++ b/docs/changesets.md @@ -4,16 +4,32 @@ Checked 2026-11-18 against @changesets/cli 3.0.3, @changesets/config 4.0.1, chan ## How a release happens -- A PR with a user-facing change adds a changeset (`npx changeset`). On merge to `main`, `release.yml` runs changesets/action: with pending changesets it opens or updates the "Version Packages" PR (version bump and `CHANGELOG.md`). -- Merging the Version Packages PR leaves no pending changesets, so the next run calls `npm run release`. That script skips when the GitHub release `v` already exists, otherwise runs `vsce publish --oidc --skip-duplicate` and then `changeset publish`. +- A PR with a user-facing change adds a changeset (`npx changeset`). On merge to `main`, `release.yml` runs changesets/action: with pending changesets it opens or updates the version PR (version bump and `CHANGELOG.md`). +- Merging the version PR ("chore: version packages", set by the action's `pr-title` and `commit-message` inputs) leaves no pending changesets, so the next run calls `npm run release`. That script skips when the GitHub release `v` already exists, otherwise runs `vsce publish --oidc --skip-duplicate` and then `changeset publish`. - The package is `private: true` (it never goes to npm). `.changeset/config.json` sets `privatePackages: { "version": true, "tag": true }`, so `changeset publish` only creates the `v` tag, and the action creates the GitHub release from it. - A push with nothing to release (CI or docs changes) takes the publish path and stops at the existing-release check. +## Writing a changeset + +One file per user-noticeable change, named `.changeset/.md`: + +```md +--- +"vscode-styled-components": patch +--- + +Highlighting no longer spills out of a styled template when its tag spans several lines. +``` + +- The bump is `patch` for a fix or a speedup, `minor` for new behavior, and `major` for a change to the public contract (docs/spec.md, "Public contract"). +- The body is one short paragraph for users of the extension; its writing rules are in AGENTS.md, "Prose and communication". +- `npx changeset` writes the same file interactively. + ## Rules and traps - CLI and action move together: @changesets/cli 3.x needs changesets/action v2 (it throws at startup on a CLI 2 range), and v2 inputs are kebab-case (`publish-script`, `github-token`). Bumping only one passes PR CI and fails the first release run on `main`. - Pin the config `$schema` to the installed `@changesets/config` major.minor (4.0.x for CLI 3). The 3.1.x schema belongs to CLI 2 and still loads, so a stale pin validates against the wrong schema without complaint. -- Never hand-edit `version` in `package.json` or `CHANGELOG.md`; the Version Packages PR owns both. +- Never hand-edit `version` in `package.json` or `CHANGELOG.md`; the version PR owns both. - A changeset body uses no markdown headings (changesets nests it under its own `### Patch Changes`); use bold labels. - A malformed changeset (no closing `---` fence, or a bump that is not `"vscode-styled-components": patch|minor|major`) passes PR CI, because the changeset is markdown, and then blocks the release on `main`. - `changeset publish` has no `--dry-run`; test the publish path by running the release script with credentials removed, never by hoping it stops in time. diff --git a/docs/github-actions.md b/docs/github-actions.md index ac82d37..1c4bdaf 100644 --- a/docs/github-actions.md +++ b/docs/github-actions.md @@ -16,7 +16,7 @@ Checked 2026-11-18 against actions/checkout v7.0.1, actions/setup-node v7.1.0, a - Publishing uses VS Code Marketplace trusted publishing: `id-token: write` plus `vsce publish --oidc`, no stored token. Never reintroduce a long-lived publish secret. - No dependency cache in the release job (`package-manager-cache: false`, no `cache:` input, no `actions/cache`). A poisoned cache entry would run with the publish identity; the cold install is the accepted cost. - A manual run on a ref other than `main` fails at its first step. That guards against a mistaken dispatch only: a branch can edit the workflow itself, so the Marketplace trusted-publisher binding is the real control. -- Events created with the job's `GITHUB_TOKEN` (the Version Packages PR) start no workflows, so required checks never run on that PR. Setting a `RELEASE_GITHUB_TOKEN` secret (a PAT or GitHub App token) fixes this; `release.yml` already prefers it. +- Events created with the job's `GITHUB_TOKEN` (the version PR) start no workflows, so required checks never run on that PR. Setting a `RELEASE_GITHUB_TOKEN` secret (a PAT or GitHub App token) fixes this; `release.yml` already prefers it. ## Repository settings this baseline assumes diff --git a/scripts/check-commit-message.sh b/scripts/check-commit-message.sh new file mode 100755 index 0000000..cfa8d57 --- /dev/null +++ b/scripts/check-commit-message.sh @@ -0,0 +1,30 @@ +#!/bin/sh +# Usage: check-commit-message.sh [--local] | check-commit-message.sh [--local] -m "" +# Checks the first line against Conventional Commits: type(scope)!: subject. +# --local (the commit-msg hook) also accepts the subjects git writes itself: fixup!, squash!, amend!, and Revert "...". +# CI omits it, so those commits must be squashed or reworded before merge. +local=0 +if [ "$1" = "--local" ]; then + local=1 + shift +fi + +if [ "$1" = "-m" ]; then + subject=$(printf '%s\n' "$2" | head -n 1) +else + subject=$(head -n 1 "$1") +fi + +pattern='^(feat|fix|perf|refactor|style|test|docs|build|ci|chore|revert)(\([a-z0-9-]+\))?!?: [^ ].*$' +if printf '%s\n' "$subject" | grep -Eq "$pattern"; then + exit 0 +fi + +if [ "$local" = 1 ] && printf '%s\n' "$subject" | grep -Eq '^((fixup|squash|amend)! .|Revert ".)'; then + exit 0 +fi + +echo "Commit message \"$subject\" is not a Conventional Commit." >&2 +echo "Write it as \"type(scope): subject\", e.g. \"fix(grammar): stop highlighting after an empty template\"." >&2 +echo "Types: feat, fix, perf, refactor, style, test, docs, build, ci, chore, revert. See CONTRIBUTING.md, \"Commit messages\"." >&2 +exit 1 From fa3875a3972e5f3d2cebbc9b48b62e57107378dc Mon Sep 17 00:00:00 2001 From: Evan Jacobs Date: Thu, 19 Nov 2026 15:19:03 -0500 Subject: [PATCH 03/15] test: add a headless tokenizer, a grammar benchmark, and leak sentinels The tokenizer prints tokens with the pinned VS Code's grammars without opening a window, checks sentinel lines, and compares fixtures with their committed results. The benchmark compares grammar speed against other grammar folders. Every fixture ends with a sentinel line that fails the colorization suite when highlighting leaks. --- scripts/bench-grammar.mts | 196 ++++++++++++++++++++++++ scripts/grammarRegistry.mts | 108 ++++++++++++++ scripts/tokenize.mts | 215 +++++++++++++++++++++++++++ scripts/webAssembly.d.ts | 8 + src/tests/colorizeToken.mts | 89 +++++++++++ src/tests/suite/colorization.test.js | 90 ----------- src/tests/suite/colorization.test.ts | 209 ++++++++++++++++++++++++++ 7 files changed, 825 insertions(+), 90 deletions(-) create mode 100644 scripts/bench-grammar.mts create mode 100644 scripts/grammarRegistry.mts create mode 100644 scripts/tokenize.mts create mode 100644 scripts/webAssembly.d.ts create mode 100644 src/tests/colorizeToken.mts delete mode 100644 src/tests/suite/colorization.test.js create mode 100644 src/tests/suite/colorization.test.ts diff --git a/scripts/bench-grammar.mts b/scripts/bench-grammar.mts new file mode 100644 index 0000000..0416156 --- /dev/null +++ b/scripts/bench-grammar.mts @@ -0,0 +1,196 @@ +// Usage: npm run bench:grammar -- [ [...]] [--fixtures ] [--app-root ] [--rounds ] [--runs ] +// Tokenizes the colorize fixtures, repeated to about 5,000 lines, under a tsx and a js host. +// Every (round, host, variant) cell runs in a fresh process, with the variant order rotating each round, so no cell inherits another's warmed regex cache or JIT. +// Reports the median first pass (cold) and the median of each process's warm median. The "current" variant is generated from syntaxes/src into a temp folder; nothing is written into the repo. +import { execFileSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; + +import vscodeTextmate from "vscode-textmate"; +import type { IGrammar } from "vscode-textmate"; + +import { fixtureFileNames } from "../src/tests/colorizeToken.mts"; +import { writeGrammars } from "../syntaxes/src/generate.mts"; +import { + createRegistry, + repoRoot, + resolveAppRoot, +} from "./grammarRegistry.mts"; + +const { INITIAL } = vscodeTextmate; + +const TARGET_LINES = 5000; +const hosts = ["source.tsx", "source.js"]; + +const { positionals: otherDirs, values: flags } = (() => { + try { + return parseArgs({ + options: { + "app-root": { type: "string" }, + child: { type: "string" }, + fixtures: { type: "string" }, + host: { type: "string" }, + rounds: { type: "string" }, + runs: { type: "string" }, + }, + allowPositionals: true, + }); + } catch (error) { + console.error(error instanceof Error ? error.message : error); + process.exit(2); + } +})(); +const requiredFlag = (flag: "app-root" | "host") => { + const value = flags[flag]; + if (value === undefined) throw new Error(`--${flag} needs a value`); + return value; +}; +const positiveIntegerFlag = (flag: "rounds" | "runs", fallback: number) => { + const raw = flags[flag]; + if (raw === undefined) return fallback; + + const value = Number(raw); + if (!Number.isInteger(value) || value < 1) { + console.error(`--${flag} needs a positive whole number, got "${raw}"`); + process.exit(2); + } + return value; +}; +const runs = positiveIntegerFlag("runs", 7); +const rounds = positiveIntegerFlag("rounds", 5); +const fixturesDir = resolve( + flags.fixtures ?? join(repoRoot, "src/tests/suite/colorize-fixtures"), +); + +const median = (values: number[]) => + [...values].sort((a, b) => a - b)[values.length >> 1]; + +const loadCorpus = () => { + const documents = fixtureFileNames(fixturesDir).map((file) => + readFileSync(join(fixturesDir, file), "utf8").split(/\r?\n/), + ); + if (documents.length === 0) { + console.error( + `No fixtures found in ${fixturesDir}; pass --fixtures .`, + ); + process.exit(2); + } + + // Every document restarts from the initial state, so one fixture's leak does not change what the next costs. + const corpus: string[][] = []; + let lineCount = 0; + while (lineCount < TARGET_LINES) { + for (const document of documents) { + corpus.push(document); + lineCount += document.length; + } + } + + return { corpus, lineCount }; +}; + +const tokenizeCorpus = (grammar: IGrammar, corpus: string[][]) => { + const start = performance.now(); + for (const document of corpus) { + let ruleStack = INITIAL; + for (const line of document) { + ruleStack = grammar.tokenizeLine(line, ruleStack).ruleStack; + } + } + return performance.now() - start; +}; + +const childDir = flags.child; +if (childDir !== undefined) { + // One cell: a fresh process, first pass then warm passes; prints " ". + const registry = await createRegistry( + resolve(childDir), + resolve(requiredFlag("app-root")), + ); + const host = requiredFlag("host"); + const grammar = await registry.loadGrammar(host); + if (grammar === null) throw new Error(`no grammar loaded for ${host}`); + const { corpus } = loadCorpus(); + const first = tokenizeCorpus(grammar, corpus); + const warm = Array.from({ length: runs }, () => + tokenizeCorpus(grammar, corpus), + ); + console.log(`${first} ${median(warm)}`); + process.exit(0); +} + +// Fails before any variant runs when the fixtures folder is empty. +const { lineCount } = loadCorpus(); + +const currentDir = mkdtempSync(join(tmpdir(), "bench-grammar-")); + +try { + writeGrammars(currentDir); + + const variants = [ + ...otherDirs.map((dir, index) => ({ + name: index === 0 ? "baseline" : `other${index}`, + dir: resolve(dir), + })), + { name: "current", dir: currentDir }, + ]; + + const appRoot = await resolveAppRoot(flags["app-root"]); + const script = fileURLToPath(import.meta.url); + const cells = new Map(); + + for (let round = 0; round < rounds; round++) { + for (const host of hosts) { + for (let i = 0; i < variants.length; i++) { + const variant = variants[(i + round) % variants.length]; + const [first, warm] = execFileSync( + process.execPath, + [ + script, + "--child", + variant.dir, + "--host", + host, + "--app-root", + appRoot, + "--fixtures", + fixturesDir, + "--runs", + String(runs), + ], + { encoding: "utf8" }, + ) + .trim() + .split(" ") + .map(Number); + const cell = cells.get(`${host} ${variant.name}`) ?? { + first: [], + warm: [], + }; + cell.first.push(first); + cell.warm.push(warm); + cells.set(`${host} ${variant.name}`, cell); + } + } + } + + console.log( + `${lineCount} lines, ${rounds} fresh processes per row, ${runs} warm passes per process`, + ); + console.log("host variant first pass ms warm median ms"); + + for (const host of hosts) { + for (const variant of variants) { + const cell = cells.get(`${host} ${variant.name}`); + if (cell === undefined) continue; + console.log( + `${host.padEnd(11)} ${variant.name.padEnd(9)} ${median(cell.first).toFixed(0).padStart(13)} ${median(cell.warm).toFixed(0).padStart(16)}`, + ); + } + } +} finally { + rmSync(currentDir, { recursive: true, force: true }); +} diff --git a/scripts/grammarRegistry.mts b/scripts/grammarRegistry.mts new file mode 100644 index 0000000..300b2f6 --- /dev/null +++ b/scripts/grammarRegistry.mts @@ -0,0 +1,108 @@ +import { createRequire } from "node:module"; +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { downloadAndUnzipVSCode, SilentReporter } from "@vscode/test-electron"; +import vscodeOniguruma from "vscode-oniguruma"; +import vscodeTextmate from "vscode-textmate"; +import type { IRawGrammar } from "vscode-textmate"; + +import vscodeVersion from "../src/tests/vscodeVersion.mts"; +import pkg from "../package.json" with { type: "json" }; + +const require = createRequire(import.meta.url); +const { Registry, parseRawGrammar } = vscodeTextmate; +const { createOnigScanner, createOnigString, loadWASM } = vscodeOniguruma; + +export const repoRoot = resolve(fileURLToPath(import.meta.url), "../.."); + +const injectionHosts = new Set( + pkg.contributes.grammars.find((grammar) => grammar.scopeName === "styled") + ?.injectTo ?? [], +); +if (injectionHosts.size === 0) { + throw new Error('package.json has no "styled" grammar with an injectTo list'); +} + +const builtInGrammarFiles = [ + "extensions/typescript-basics/syntaxes/TypeScript.tmLanguage.json", + "extensions/typescript-basics/syntaxes/TypeScriptReact.tmLanguage.json", + "extensions/javascript/syntaxes/JavaScript.tmLanguage.json", + "extensions/javascript/syntaxes/JavaScriptReact.tmLanguage.json", + "extensions/css/syntaxes/css.tmLanguage.json", +]; + +const repoGrammarFiles = ["styled-components.json", "css.styled.json"]; + +function appRootOf(executablePath: string) { + if (process.platform === "darwin") { + const marker = ".app/"; + const end = executablePath.indexOf(marker); + if (end === -1) { + throw new Error(`Cannot find the .app bundle in ${executablePath}`); + } + return join( + executablePath.slice(0, end + marker.length - 1), + "Contents/Resources/app", + ); + } + + if (process.platform === "win32") { + const installDir = dirname(executablePath); + // Recent Windows archives nest resources/app under a 10-hex-character commit folder. + const commitDir = readdirSync(installDir).find( + (name) => + /^[0-9a-f]{10}$/.test(name) && + existsSync(join(installDir, name, "resources/app")), + ); + return join(installDir, commitDir ?? "", "resources/app"); + } + + if (process.platform === "linux") { + return join(dirname(executablePath), "resources/app"); + } + + throw new Error( + `This script supports macOS, Linux, and Windows; ${process.platform} is not supported.`, + ); +} + +// loadWASM returns its first load's promise on every later call. +const loadOniguruma = () => + loadWASM(readFileSync(require.resolve("vscode-oniguruma/release/onig.wasm"))); + +// appRoot is the pinned VS Code's app folder; it is downloaded when omitted. +export async function resolveAppRoot(appRoot?: string) { + if (appRoot !== undefined) return resolve(appRoot); + + const executablePath = await downloadAndUnzipVSCode({ + // The library defaults to a cache under the working directory, which re-downloads VS Code when run from a subfolder. + cachePath: join(repoRoot, ".vscode-test"), + version: vscodeVersion, + reporter: new SilentReporter(), + }); + return appRootOf(executablePath); +} + +// Builds a registry of the pinned VS Code's grammars plus the two repo grammars found in grammarDir. +export async function createRegistry(grammarDir: string, appRoot: string) { + await loadOniguruma(); + + const grammars = new Map(); + const grammarSources = [ + ...builtInGrammarFiles.map((file) => join(appRoot, file)), + ...repoGrammarFiles.map((file) => join(grammarDir, file)), + ]; + for (const path of grammarSources) { + const raw = parseRawGrammar(readFileSync(path, "utf8"), path); + grammars.set(raw.scopeName, raw); + } + + return new Registry({ + onigLib: Promise.resolve({ createOnigScanner, createOnigString }), + getInjections: (scopeName) => + injectionHosts.has(scopeName) ? ["styled"] : undefined, + loadGrammar: async (scopeName) => grammars.get(scopeName) ?? null, + }); +} diff --git a/scripts/tokenize.mts b/scripts/tokenize.mts new file mode 100644 index 0000000..a1ae6d8 --- /dev/null +++ b/scripts/tokenize.mts @@ -0,0 +1,215 @@ +import { existsSync, readFileSync } from "node:fs"; +import { basename, dirname, extname, resolve } from "node:path"; +import { parseArgs } from "node:util"; + +import vscodeTextmate from "vscode-textmate"; +import type { IGrammar } from "vscode-textmate"; + +import { + endsWithSentinel, + leakedSentinelLines, + readColorizeResult, + resultFileName, + rootScopeByExtension, + SENTINEL_LINE, +} from "../src/tests/colorizeToken.mts"; +import { + defaultGrammarsDir, + writeGrammars, +} from "../syntaxes/src/generate.mts"; +import { createRegistry, resolveAppRoot } from "./grammarRegistry.mts"; + +const { INITIAL } = vscodeTextmate; + +type Token = { text: string; scopes: string[] }; +type TokenizedLine = { number: number; text: string; tokens: Token[] }; + +function tokenizeText(grammar: IGrammar, text: string): TokenizedLine[] { + const lines = text.split(/\r?\n/); + let ruleStack = INITIAL; + + return lines.map((line, index) => { + const result = grammar.tokenizeLine(line, ruleStack); + ruleStack = result.ruleStack; + + // Adjacent tokens with identical scopes merge, as in VS Code's captured tokens. + const tokens: Token[] = []; + for (const token of result.tokens) { + const text = line.slice( + token.startIndex, + Math.min(token.endIndex, line.length), + ); + if (text.length === 0) { + continue; + } + + const previous = tokens.at(-1); + if (previous && previous.scopes.join(" ") === token.scopes.join(" ")) { + previous.text += text; + } else { + tokens.push({ text, scopes: token.scopes }); + } + } + + return { number: index + 1, text: line, tokens }; + }); +} + +function printFile(file: string, lines: TokenizedLine[]) { + console.log(`# ${file}`); + for (const line of lines) { + console.log(`${line.number}: ${line.text}`); + for (const token of line.tokens) { + console.log( + ` ${JSON.stringify(token.text)} => ${token.scopes.join(" ")}`, + ); + } + } +} + +function checkSentinel( + file: string, + rootScope: string, + lines: TokenizedLine[], +) { + // A CSS fixture cannot hold the JavaScript sentinel. + if (extname(file) === ".css") { + console.log(`SKIP ${file}: CSS has no sentinel`); + return true; + } + + const texts = lines.map((line) => line.text); + if (!endsWithSentinel(texts)) { + console.log(`FAIL ${file}: no "${SENTINEL_LINE}" last line`); + return false; + } + + const leaked = leakedSentinelLines(texts, rootScope, (index) => { + const token = lines[index].tokens[0]; + return token && { text: token.text, scopes: token.scopes.join(" ") }; + }); + if (leaked.length === 0) { + console.log(`PASS ${file}`); + return true; + } + + for (const { line, token } of leaked) { + console.log( + `FAIL ${file}:${line}: sentinel scopes ${token?.scopes ?? "(none)"}`, + ); + } + return false; +} + +// Compares a file's tokens (text and scopes) with its committed colorize-results file. +function checkDrift(file: string, lines: TokenizedLine[], showCount: number) { + const resultPath = resolve( + dirname(file), + "../colorize-results", + resultFileName(basename(file)), + ); + if (!existsSync(resultPath)) { + console.log(`NO RESULT ${file}: ${resultPath} does not exist`); + return false; + } + + const expected = readColorizeResult(resultPath).map((token) => ({ + text: token.c, + scopes: token.t, + })); + const actual = lines + .flatMap((line) => line.tokens) + .map((token) => ({ text: token.text, scopes: token.scopes.join(" ") })); + + const diffs = []; + for (let i = 0; i < Math.max(expected.length, actual.length); i++) { + const a = expected[i]; + const b = actual[i]; + if (a?.text !== b?.text || a?.scopes !== b?.scopes) { + diffs.push({ index: i, expected: a, actual: b }); + } + } + + console.log( + `${diffs.length === 0 ? "same " : "DRIFT"} ${file}: ${diffs.length} differing tokens (committed ${expected.length}, now ${actual.length})`, + ); + for (const diff of diffs.slice(0, showCount)) { + console.log(` #${diff.index} committed ${JSON.stringify(diff.expected)}`); + console.log(` #${diff.index} now ${JSON.stringify(diff.actual)}`); + } + return diffs.length === 0; +} + +const usage = + "Usage: npm run tokenize -- [--sentinel | --drift [--show ]] [--grammars ] "; + +const parsed = (() => { + try { + return parseArgs({ + options: { + drift: { type: "boolean" }, + grammars: { type: "string" }, + sentinel: { type: "boolean" }, + show: { type: "string" }, + }, + allowPositionals: true, + }); + } catch (error) { + console.error( + `${error instanceof Error ? error.message : error}\n${usage}`, + ); + process.exit(2); + } +})(); +const { drift, sentinel, show } = parsed.values; +const files = parsed.positionals; +const showCount = Number(show ?? 0); +const grammarDirFlag = parsed.values.grammars; + +if (!Number.isInteger(showCount) || showCount < 0) { + console.error(`--show needs a whole number, got "${show}"`); + process.exit(2); +} + +if (files.length === 0) { + console.error(usage); + process.exit(2); +} + +// The grammar JSON files are generated; an explicit --grammars directory is used as is. +if (grammarDirFlag === undefined) { + writeGrammars(defaultGrammarsDir); +} + +const registry = await createRegistry( + grammarDirFlag === undefined ? defaultGrammarsDir : resolve(grammarDirFlag), + await resolveAppRoot(), +); +let allPassed = true; + +for (const file of files) { + const rootScope = rootScopeByExtension[extname(file)]; + if (rootScope === undefined) { + console.error( + `${file}: unsupported extension; use ${Object.keys(rootScopeByExtension).join(", ")}`, + ); + process.exit(2); + } + + const grammar = await registry.loadGrammar(rootScope); + if (grammar === null) { + console.error(`${file}: no grammar loaded for ${rootScope}`); + process.exit(2); + } + + const lines = tokenizeText(grammar, readFileSync(file, "utf8")); + if (sentinel) { + allPassed = checkSentinel(file, rootScope, lines) && allPassed; + } else if (drift) { + allPassed = checkDrift(file, lines, showCount) && allPassed; + } else { + printFile(file, lines); + } +} + +process.exit(allPassed ? 0 : 1); diff --git a/scripts/webAssembly.d.ts b/scripts/webAssembly.d.ts new file mode 100644 index 0000000..9307f16 --- /dev/null +++ b/scripts/webAssembly.d.ts @@ -0,0 +1,8 @@ +// vscode-oniguruma's typings name these two types from TypeScript's DOM lib, which this repo does not load; Node's typings omit them. +declare namespace WebAssembly { + type ImportValue = object | number; + interface WebAssemblyInstantiatedSource { + instance: object; + module: object; + } +} diff --git a/src/tests/colorizeToken.mts b/src/tests/colorizeToken.mts new file mode 100644 index 0000000..8ccd0c0 --- /dev/null +++ b/src/tests/colorizeToken.mts @@ -0,0 +1,89 @@ +import { readdirSync, readFileSync } from "node:fs"; + +// One token of a colorize-results file: its text, its space-joined scopes, and its color per theme. +export type ColorizeToken = { c: string; t: string; r: Record }; + +// The colorize-results file name of a fixture: "styled.js" is "styled_js.json". +export const resultFileName = (fixtureName: string) => + `${fixtureName.replace(".", "_")}.json`; + +// A fixtures folder's file names, sorted; folders a tool leaves behind (a `.vscode-test` cache) are skipped. +export const fixtureFileNames = (dir: string) => + readdirSync(dir, { withFileTypes: true }) + .filter((entry) => entry.isFile()) + .map((entry) => entry.name) + .sort(); + +const isColorizeToken = (value: unknown): value is ColorizeToken => + typeof value === "object" && + value !== null && + "c" in value && + typeof value.c === "string" && + "t" in value && + typeof value.t === "string" && + "r" in value && + typeof value.r === "object" && + value.r !== null && + Object.values(value.r).every((color: unknown) => typeof color === "string"); + +export const isColorizeTokens = (value: unknown): value is ColorizeToken[] => + Array.isArray(value) && value.every(isColorizeToken); + +// Reads a colorize-results file, throwing when it is not a list of colorize tokens. +export const readColorizeResult = (resultPath: string) => { + const parsed: unknown = JSON.parse(readFileSync(resultPath, "utf8")); + if (!isColorizeTokens(parsed)) { + throw new Error(`${resultPath} is not a list of colorize tokens`); + } + + return parsed; +}; + +// A fixture's last non-empty line, and any line before it, that must tokenize at the file's root scope. +export const SENTINEL_LINE = "const sentinel = 1;"; + +export type ColorizeSentinelToken = { text: string; scopes: string }; + +// Whether a fixture ends with the sentinel line (blank lines after it are ignored). +export const endsWithSentinel = (lines: string[]) => + lines.filter((line) => line.trim() !== "").at(-1) === SENTINEL_LINE; + +// source.js.jsx yields meta.var.expr.js.jsx, so the suffix is everything after "source." +const sentinelScopes = (rootScope: string) => { + const lang = rootScope.slice("source.".length); + return [rootScope, `meta.var.expr.${lang}`, `storage.type.${lang}`]; +}; + +// Every sentinel line whose first token is not at root scope, so a leak that recovers before the last line still fails. +// `firstTokenOfLine` takes a zero-based line index and returns that line's first token. +export const leakedSentinelLines = ( + lines: string[], + rootScope: string, + firstTokenOfLine: (lineIndex: number) => ColorizeSentinelToken | undefined, +) => { + const expected = sentinelScopes(rootScope).join(" "); + const leaked: { line: number; token: ColorizeSentinelToken | undefined }[] = + []; + + lines.forEach((text, index) => { + if (text !== SENTINEL_LINE) { + return; + } + + const token = firstTokenOfLine(index); + if (token?.text !== "const" || token.scopes !== expected) { + leaked.push({ line: index + 1, token }); + } + }); + + return leaked; +}; + +// Plain CSS is here to compare a template's tokens with what VS Code gives the same CSS in a .css file. +export const rootScopeByExtension: Partial> = { + ".css": "source.css", + ".js": "source.js", + ".jsx": "source.js.jsx", + ".ts": "source.ts", + ".tsx": "source.tsx", +}; diff --git a/src/tests/suite/colorization.test.js b/src/tests/suite/colorization.test.js deleted file mode 100644 index d37dfcc..0000000 --- a/src/tests/suite/colorization.test.js +++ /dev/null @@ -1,90 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -"use strict"; - -const assert = require("assert"); -const { commands, Uri } = require("vscode"); -const { join, basename, dirname } = require("path"); -const fs = require("fs"); - -function assertUnchangedTokens(testFixurePath, done) { - let fileName = basename(testFixurePath); - - return commands - .executeCommand("_workbench.captureSyntaxTokens", Uri.file(testFixurePath)) - .then((data) => { - try { - let resultsFolderPath = join( - dirname(dirname(testFixurePath)), - "colorize-results" - ); - if (!fs.existsSync(resultsFolderPath)) { - fs.mkdirSync(resultsFolderPath); - } - let resultPath = join( - resultsFolderPath, - fileName.replace(".", "_") + ".json" - ); - if (fs.existsSync(resultPath)) { - let previousData = JSON.parse(fs.readFileSync(resultPath).toString()); - try { - assert.deepStrictEqual(data, previousData); - } catch (e) { - fs.writeFileSync(resultPath, JSON.stringify(data, null, "\t"), { - flag: "w", - }); - if ( - Array.isArray(data) && - Array.isArray(previousData) && - data.length === previousData.length - ) { - for (let i = 0; i < data.length; i++) { - let d = data[i]; - let p = previousData[i]; - if (d.c !== p.c || hasThemeChange(d.r, p.r)) { - throw e; - } - } - // different but no tokenization ot color change: no failure - } else { - throw e; - } - } - } else { - fs.writeFileSync(resultPath, JSON.stringify(data, null, "\t")); - } - done(); - } catch (e) { - done(e); - } - }, done); -} - -function hasThemeChange(d, p) { - let keys = Object.keys(d); - for (let key of keys) { - if (d[key] !== p[key]) { - return true; - } - } - return false; -} - -suite("colorization", () => { - let extensionColorizeFixturePath = join(__dirname, "colorize-fixtures"); - if (fs.existsSync(extensionColorizeFixturePath)) { - let fixturesFiles = fs.readdirSync(extensionColorizeFixturePath); - fixturesFiles.forEach((fixturesFile) => { - // define a test for each fixture - test(fixturesFile, function(done) { - this.timeout(5000); // Needed to try and fix macos timeout issues - assertUnchangedTokens( - join(extensionColorizeFixturePath, fixturesFile), - done - ); - }); - }); - } -}); diff --git a/src/tests/suite/colorization.test.ts b/src/tests/suite/colorization.test.ts new file mode 100644 index 0000000..d1910a4 --- /dev/null +++ b/src/tests/suite/colorization.test.ts @@ -0,0 +1,209 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import assert from "node:assert"; +import fs from "node:fs"; +import { join, basename, dirname, extname } from "node:path"; +import { isDeepStrictEqual } from "node:util"; + +import { commands, Uri } from "vscode"; + +import { + endsWithSentinel, + fixtureFileNames, + isColorizeTokens, + leakedSentinelLines, + readColorizeResult, + resultFileName, + rootScopeByExtension, + SENTINEL_LINE, +} from "../colorizeToken.mts"; +import type { ColorizeToken } from "../colorizeToken.mts"; + +// Fixtures whose sentinel line is mis-scoped by a known grammar leak; the value is the open issue. +const KNOWN_LEAKS: Partial> = {}; + +// Fixtures of shapes that must stay plain code: none of their tokens may be CSS. Every other fixture must hold at least one CSS token. +const PLAIN_FIXTURES = [ + "comment.js", + "plain-comparisons.js", + "plain-jsx.js", + "plain-jsx.tsx", + "plain-typescript.ts", +]; + +// Under CI every difference from the committed result fails, so a scope-only change cannot pass unreviewed. +const isCI = process.env.CI === "true"; + +function rootScopeOf(fileName: string) { + const rootScope = rootScopeByExtension[extname(fileName)]; + if (rootScope === undefined) { + throw new Error(`No root scope known for ${fileName}`); + } + return rootScope; +} + +// Token texts concatenate to the source minus newlines, so each line consumes tokens until its length is covered. +function firstTokenIndexByLine(tokens: ColorizeToken[], lineLengths: number[]) { + const firstIndexes: number[] = []; + let tokenIndex = 0; + lineLengths.forEach((length, lineIndex) => { + firstIndexes.push(tokenIndex); + + let remaining = length; + while (remaining > 0) { + remaining -= tokens[tokenIndex].c.length; + tokenIndex++; + } + assert.strictEqual( + remaining, + 0, + `a token spans the end of line ${lineIndex + 1}`, + ); + }); + return firstIndexes; +} + +function assertSentinelScopes(fixturePath: string, tokens: ColorizeToken[]) { + const fileName = basename(fixturePath); + const lines = fs.readFileSync(fixturePath, "utf8").split(/\r?\n/); + // A CSS fixture cannot hold the JavaScript sentinel. + if (extname(fileName) === ".css") { + return; + } + if (!endsWithSentinel(lines)) { + throw new Error( + `${fileName}: the last non-blank line must be "${SENTINEL_LINE}"; it proves no earlier construct leaked`, + ); + } + + const firstIndexes = firstTokenIndexByLine( + tokens, + lines.map((line) => line.length), + ); + const leaked = leakedSentinelLines( + lines, + rootScopeOf(fileName), + (lineIndex) => { + const token = tokens[firstIndexes[lineIndex]]; + return token && { text: token.c, scopes: token.t }; + }, + ); + + const knownLeak = KNOWN_LEAKS[fileName]; + if (knownLeak !== undefined) { + assert.ok( + leaked.length > 0, + `${fileName} no longer leaks; remove its KNOWN_LEAKS entry (issue #${knownLeak})`, + ); + return; + } + + assert.deepStrictEqual( + leaked, + [], + `${fileName}: every sentinel line must have root-level scopes; an earlier construct leaked`, + ); +} + +function assertCssTokens(fixturePath: string, tokens: ColorizeToken[]) { + const fileName = basename(fixturePath); + const cssTokenCount = tokens.filter((token) => + token.t.split(" ").includes("source.css.scss"), + ).length; + + if (PLAIN_FIXTURES.includes(fileName)) { + assert.strictEqual( + cssTokenCount, + 0, + `${fileName} is listed in PLAIN_FIXTURES but ${cssTokenCount} tokens are CSS`, + ); + return; + } + + assert.ok( + cssTokenCount > 0, + `${fileName} has no CSS token; highlight the template or list the fixture in PLAIN_FIXTURES`, + ); +} + +// A scope-only change passes locally, since the result file is rewritten and the diff is reviewed in git. +function isTextAndColorUnchanged( + data: ColorizeToken[], + previousData: ColorizeToken[], +) { + return ( + data.length === previousData.length && + data.every( + (token, i) => + token.c === previousData[i].c && + isDeepStrictEqual(token.r, previousData[i].r), + ) + ); +} + +async function assertUnchangedTokens(fixturePath: string) { + const fileName = basename(fixturePath); + const data = await commands.executeCommand( + "_workbench.captureSyntaxTokens", + Uri.file(fixturePath), + ); + if (!isColorizeTokens(data)) { + throw new Error( + `${fileName}: the captured tokens are not a list of colorize tokens`, + ); + } + + const resultPath = join( + dirname(dirname(fixturePath)), + "colorize-results", + resultFileName(fileName), + ); + const serialized = JSON.stringify(data, null, "\t"); + + if (!fs.existsSync(resultPath)) { + fs.writeFileSync(resultPath, serialized); + if (isCI) { + throw new Error( + `${fileName} has no committed result; the generated colorize-results file is uploaded as a CI artifact, review and commit it`, + ); + } + } else { + const previousData = readColorizeResult(resultPath); + try { + assert.deepStrictEqual(data, previousData); + } catch (e) { + fs.writeFileSync(resultPath, serialized); + if (isCI || !isTextAndColorUnchanged(data, previousData)) { + throw e; + } + } + } + + assertSentinelScopes(fixturePath, data); + assertCssTokens(fixturePath, data); +} + +suite("colorization", () => { + // The bundle runs from .integration-test/, one folder below the repo root. + const extensionColorizeFixturePath = join( + __dirname, + "../src/tests/suite/colorize-fixtures", + ); + // readdirSync throws on a missing folder, so a wrong path fails the run instead of defining zero tests. + const fixturesFiles = fixtureFileNames(extensionColorizeFixturePath); + if (fixturesFiles.length === 0) { + throw new Error(`No colorize fixtures in ${extensionColorizeFixturePath}`); + } + + fixturesFiles.forEach((fixturesFile) => { + test(fixturesFile, async function () { + // The first capture in a fresh VS Code includes loading the grammars. + this.timeout(5000); + await assertUnchangedTokens( + join(extensionColorizeFixturePath, fixturesFile), + ); + }); + }); +}); From fd97a2637ceac7649fe83806e35faac01b8114c7 Mon Sep 17 00:00:00 2001 From: Evan Jacobs Date: Thu, 19 Nov 2026 15:19:05 -0500 Subject: [PATCH 04/15] feat(grammar): generate the grammars from source, stop highlighting leaks, and highlight modern CSS The grammars are generated from TypeScript sources, with VS Code's CSS grammar vendored and its rules copied in. Highlighting no longer spills past a template's closing backtick, more tag shapes are recognized, modern CSS functions highlight as functions, and CSS tokenizes faster. Fixes #383, #292, #358, #442, #196 --- ThirdPartyNotices.txt | 17 + .../colorize-fixtures/arrow-call-same-line.js | 5 + .../colorize-fixtures/arrow-call-same-line.ts | 4 + .../suite/colorize-fixtures/arrow-function.js | 1 + .../colorize-fixtures/attrs-arrow-template.js | 32 + .../attrs-arrow-template.tsx | 32 + src/tests/suite/colorize-fixtures/attrs.js | 1 + .../suite/colorize-fixtures/await-member.js | 12 + .../suite/colorize-fixtures/body-edges.js | 22 + .../suite/colorize-fixtures/body-edges.tsx | 14 + .../colorize-fixtures/call-prefix-root.js | 5 + src/tests/suite/colorize-fixtures/closers.js | 24 + src/tests/suite/colorize-fixtures/comment.js | 1 + .../suite/colorize-fixtures/component.js | 1 + .../colorize-fixtures/createGlobalStyle.js | 1 + src/tests/suite/colorize-fixtures/css-prop.js | 1 + .../suite/colorize-fixtures/custom-at-rule.js | 1 + src/tests/suite/colorize-fixtures/dot-tag.js | 1 + .../suite/colorize-fixtures/export-default.js | 1 + .../suite/colorize-fixtures/extend-chain.js | 12 + src/tests/suite/colorize-fixtures/extend.js | 1 + .../colorize-fixtures/function-call-space.js | 1 + .../function-call-with-css-helper.js | 1 + .../suite/colorize-fixtures/function-call.js | 1 + .../function-media-queries.js | 1 + src/tests/suite/colorize-fixtures/generics.ts | 124 + .../suite/colorize-fixtures/generics.tsx | 124 + .../colorize-fixtures/head-chain-newline.js | 14 + .../suite/colorize-fixtures/head-comment.js | 9 + .../suite/colorize-fixtures/head-multiline.js | 97 + .../suite/colorize-fixtures/head-multiline.ts | 97 + .../suite/colorize-fixtures/injectGlobal.js | 1 + .../colorize-fixtures/inside-function.js | 1 + .../suite/colorize-fixtures/inside-method.js | 1 + .../interpolation-in-function.js | 10 + .../suite/colorize-fixtures/jsx-in-head.js | 12 + .../suite/colorize-fixtures/jsx-in-head.tsx | 12 + .../keyframes-prefixed-generics.ts | 7 + .../colorize-fixtures/keyframes-selectors.js | 16 + .../suite/colorize-fixtures/keyframes.js | 1 + .../colorize-fixtures/last-declaration.js | 11 + src/tests/suite/colorize-fixtures/mixin.js | 1 + .../colorize-fixtures/modern-css-functions.js | 27 + .../nested-template-strings-with-helper.js | 3 +- .../suite/colorize-fixtures/nextStyle.js | 1 + .../suite/colorize-fixtures/object-literal.js | 1 + .../colorize-fixtures/plain-comparisons.js | 53 + .../suite/colorize-fixtures/plain-jsx.js | 19 + .../suite/colorize-fixtures/plain-jsx.tsx | 19 + .../colorize-fixtures/plain-typescript.ts | 20 + .../colorize-fixtures/segmented-component.js | 1 + .../suite/colorize-fixtures/string-tagname.js | 1 + .../suite/colorize-fixtures/stylesheet.js | 1 + .../colorize-fixtures/tag-shape-agreement.js | 28 + .../suite/colorize-fixtures/tag-shapes.js | 45 + .../suite/colorize-fixtures/tag-shapes.ts | 45 + .../suite/colorize-fixtures/theme-function.js | 1 + .../colorize-fixtures/typescript-attr.ts | 1 + .../suite/colorize-fixtures/typescript-css.ts | 1 + .../colorize-fixtures/typescript-emotion.ts | 3 +- .../colorize-fixtures/typescript-multiline.ts | 1 + .../suite/colorize-fixtures/typescript-tag.ts | 3 +- .../suite/colorize-fixtures/typescript.ts | 3 +- .../colorize-fixtures/variable-assignment.js | 1 + .../colorize-fixtures/white-space-property.js | 1 + .../suite/colorize-fixtures/withComponent.js | 1 + .../suite/colorize-fixtures/withConfig.js | 1 + .../arrow-call-same-line_js.json | 2098 +++ .../arrow-call-same-line_ts.json | 1714 ++ .../colorize-results/arrow-function_js.json | 128 + .../attrs-arrow-template_js.json | 9906 +++++++++++ .../attrs-arrow-template_tsx.json | 9906 +++++++++++ .../suite/colorize-results/attrs_js.json | 156 +- .../colorize-results/await-member_js.json | 1858 ++ .../suite/colorize-results/body-edges_js.json | 7362 ++++++++ .../colorize-results/body-edges_tsx.json | 3266 ++++ .../colorize-results/call-prefix-root_js.json | 1410 ++ .../suite/colorize-results/closers_js.json | 3058 ++++ .../suite/colorize-results/comment_js.json | 128 + .../suite/colorize-results/component_js.json | 128 + .../createGlobalStyle_js.json | 128 + .../suite/colorize-results/css-prop_js.json | 128 + .../colorize-results/custom-at-rule_js.json | 128 + .../suite/colorize-results/dot-tag_js.json | 128 + .../colorize-results/export-default_js.json | 128 + .../colorize-results/extend-chain_js.json | 2034 +++ .../suite/colorize-results/extend_js.json | 256 +- .../function-call-space_js.json | 128 + .../function-call-with-css-helper_js.json | 128 + .../colorize-results/function-call_js.json | 128 + .../function-media-queries_js.json | 458 +- .../suite/colorize-results/generics_ts.json | 14114 ++++++++++++++++ .../suite/colorize-results/generics_tsx.json | 14114 ++++++++++++++++ .../head-chain-newline_js.json | 2098 +++ .../colorize-results/head-comment_js.json | 1010 ++ .../colorize-results/head-multiline_js.json | 11842 +++++++++++++ .../colorize-results/head-multiline_ts.json | 11842 +++++++++++++ .../colorize-results/injectGlobal_js.json | 128 + .../colorize-results/inside-function_js.json | 128 + .../colorize-results/inside-method_js.json | 128 + .../interpolation-in-function_js.json | 1954 +++ .../colorize-results/jsx-in-head_js.json | 1906 +++ .../colorize-results/jsx-in-head_tsx.json | 1906 +++ .../keyframes-prefixed-generics_ts.json | 1154 ++ .../keyframes-selectors_js.json | 1554 ++ .../suite/colorize-results/keyframes_js.json | 258 +- .../colorize-results/last-declaration_js.json | 1426 ++ .../suite/colorize-results/mixin_js.json | 128 + .../modern-css-functions_js.json | 6050 +++++++ ...ested-template-strings-with-helper_js.json | 200 +- .../suite/colorize-results/nextStyle_js.json | 128 + .../colorize-results/object-literal_js.json | 128 + .../plain-comparisons_js.json | 6946 ++++++++ .../suite/colorize-results/plain-jsx_js.json | 3602 ++++ .../suite/colorize-results/plain-jsx_tsx.json | 3602 ++++ .../colorize-results/plain-typescript_ts.json | 2290 +++ .../segmented-component_js.json | 128 + .../colorize-results/string-tagname_js.json | 128 + .../suite/colorize-results/stylesheet_js.json | 128 + .../tag-shape-agreement_js.json | 6338 +++++++ .../suite/colorize-results/tag-shapes_js.json | 4146 +++++ .../suite/colorize-results/tag-shapes_ts.json | 4146 +++++ .../colorize-results/theme-function_js.json | 128 + .../colorize-results/typescript-attr_ts.json | 162 +- .../colorize-results/typescript-css_ts.json | 128 + .../typescript-emotion_ts.json | 128 + .../typescript-multiline_ts.json | 188 +- .../colorize-results/typescript-tag_ts.json | 128 + .../suite/colorize-results/typescript_ts.json | 128 + .../variable-assignment_js.json | 128 + .../white-space-property_js.json | 128 + .../colorize-results/withComponent_js.json | 176 +- .../suite/colorize-results/withConfig_js.json | 160 +- syntaxes/css.styled.json | 1230 -- syntaxes/src/css.styled.mts | 870 + syntaxes/src/css.tmLanguage.json | 1 + syntaxes/src/generate.mts | 29 + syntaxes/src/grammar.test.ts | 346 + syntaxes/src/grammarTypes.ts | 29 + syntaxes/src/ownCss.mts | 425 + syntaxes/src/styled-components.mts | 297 + syntaxes/styled-components.json | 349 - 142 files changed, 152736 insertions(+), 1974 deletions(-) create mode 100644 ThirdPartyNotices.txt create mode 100644 src/tests/suite/colorize-fixtures/arrow-call-same-line.js create mode 100644 src/tests/suite/colorize-fixtures/arrow-call-same-line.ts create mode 100644 src/tests/suite/colorize-fixtures/attrs-arrow-template.js create mode 100644 src/tests/suite/colorize-fixtures/attrs-arrow-template.tsx create mode 100644 src/tests/suite/colorize-fixtures/await-member.js create mode 100644 src/tests/suite/colorize-fixtures/body-edges.js create mode 100644 src/tests/suite/colorize-fixtures/body-edges.tsx create mode 100644 src/tests/suite/colorize-fixtures/call-prefix-root.js create mode 100644 src/tests/suite/colorize-fixtures/closers.js create mode 100644 src/tests/suite/colorize-fixtures/extend-chain.js create mode 100644 src/tests/suite/colorize-fixtures/generics.ts create mode 100644 src/tests/suite/colorize-fixtures/generics.tsx create mode 100644 src/tests/suite/colorize-fixtures/head-chain-newline.js create mode 100644 src/tests/suite/colorize-fixtures/head-comment.js create mode 100644 src/tests/suite/colorize-fixtures/head-multiline.js create mode 100644 src/tests/suite/colorize-fixtures/head-multiline.ts create mode 100644 src/tests/suite/colorize-fixtures/interpolation-in-function.js create mode 100644 src/tests/suite/colorize-fixtures/jsx-in-head.js create mode 100644 src/tests/suite/colorize-fixtures/jsx-in-head.tsx create mode 100644 src/tests/suite/colorize-fixtures/keyframes-prefixed-generics.ts create mode 100644 src/tests/suite/colorize-fixtures/keyframes-selectors.js create mode 100644 src/tests/suite/colorize-fixtures/last-declaration.js create mode 100644 src/tests/suite/colorize-fixtures/modern-css-functions.js create mode 100644 src/tests/suite/colorize-fixtures/plain-comparisons.js create mode 100644 src/tests/suite/colorize-fixtures/plain-jsx.js create mode 100644 src/tests/suite/colorize-fixtures/plain-jsx.tsx create mode 100644 src/tests/suite/colorize-fixtures/plain-typescript.ts create mode 100644 src/tests/suite/colorize-fixtures/tag-shape-agreement.js create mode 100644 src/tests/suite/colorize-fixtures/tag-shapes.js create mode 100644 src/tests/suite/colorize-fixtures/tag-shapes.ts create mode 100644 src/tests/suite/colorize-results/arrow-call-same-line_js.json create mode 100644 src/tests/suite/colorize-results/arrow-call-same-line_ts.json create mode 100644 src/tests/suite/colorize-results/attrs-arrow-template_js.json create mode 100644 src/tests/suite/colorize-results/attrs-arrow-template_tsx.json create mode 100644 src/tests/suite/colorize-results/await-member_js.json create mode 100644 src/tests/suite/colorize-results/body-edges_js.json create mode 100644 src/tests/suite/colorize-results/body-edges_tsx.json create mode 100644 src/tests/suite/colorize-results/call-prefix-root_js.json create mode 100644 src/tests/suite/colorize-results/closers_js.json create mode 100644 src/tests/suite/colorize-results/extend-chain_js.json create mode 100644 src/tests/suite/colorize-results/generics_ts.json create mode 100644 src/tests/suite/colorize-results/generics_tsx.json create mode 100644 src/tests/suite/colorize-results/head-chain-newline_js.json create mode 100644 src/tests/suite/colorize-results/head-comment_js.json create mode 100644 src/tests/suite/colorize-results/head-multiline_js.json create mode 100644 src/tests/suite/colorize-results/head-multiline_ts.json create mode 100644 src/tests/suite/colorize-results/interpolation-in-function_js.json create mode 100644 src/tests/suite/colorize-results/jsx-in-head_js.json create mode 100644 src/tests/suite/colorize-results/jsx-in-head_tsx.json create mode 100644 src/tests/suite/colorize-results/keyframes-prefixed-generics_ts.json create mode 100644 src/tests/suite/colorize-results/keyframes-selectors_js.json create mode 100644 src/tests/suite/colorize-results/last-declaration_js.json create mode 100644 src/tests/suite/colorize-results/modern-css-functions_js.json create mode 100644 src/tests/suite/colorize-results/plain-comparisons_js.json create mode 100644 src/tests/suite/colorize-results/plain-jsx_js.json create mode 100644 src/tests/suite/colorize-results/plain-jsx_tsx.json create mode 100644 src/tests/suite/colorize-results/plain-typescript_ts.json create mode 100644 src/tests/suite/colorize-results/tag-shape-agreement_js.json create mode 100644 src/tests/suite/colorize-results/tag-shapes_js.json create mode 100644 src/tests/suite/colorize-results/tag-shapes_ts.json delete mode 100644 syntaxes/css.styled.json create mode 100644 syntaxes/src/css.styled.mts create mode 100644 syntaxes/src/css.tmLanguage.json create mode 100644 syntaxes/src/generate.mts create mode 100644 syntaxes/src/grammar.test.ts create mode 100644 syntaxes/src/grammarTypes.ts create mode 100644 syntaxes/src/ownCss.mts create mode 100644 syntaxes/src/styled-components.mts delete mode 100644 syntaxes/styled-components.json diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt new file mode 100644 index 0000000..67661f0 --- /dev/null +++ b/ThirdPartyNotices.txt @@ -0,0 +1,17 @@ +THIRD-PARTY SOFTWARE NOTICES AND INFORMATION + +This package includes material from the project below. The notice is provided for information only. + +1. microsoft/vscode-css (https://github.com/microsoft/vscode-css), as shipped in Visual Studio Code + + The CSS rules in syntaxes/css.styled.json are copied from Visual Studio Code's CSS grammar (css.tmLanguage.json), which its header describes as converted from https://github.com/microsoft/vscode-css/blob/master/grammars/css.cson (commit de9e6beee756760f31b15efbd782735fc25de3db). + + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/tests/suite/colorize-fixtures/arrow-call-same-line.js b/src/tests/suite/colorize-fixtures/arrow-call-same-line.js new file mode 100644 index 0000000..2f2d270 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/arrow-call-same-line.js @@ -0,0 +1,5 @@ +const A = styled.div(({ theme }) => `color: red;`); +const B = styled(Button)(({ theme }) => `color: red;`); +const C = styled.div.attrs({ a: 1 })(({ theme }) => `color: red;`); +const D = styled.div(($props) => `color: red;`); +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/arrow-call-same-line.ts b/src/tests/suite/colorize-fixtures/arrow-call-same-line.ts new file mode 100644 index 0000000..4f83cc0 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/arrow-call-same-line.ts @@ -0,0 +1,4 @@ +const A = styled.div(({ theme }) => `color: red;`); +const B = styled.div<{ a: number }>(({ theme }) => `color: red;`); +const C = styled.div(($props) => `color: red;`); +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/arrow-function.js b/src/tests/suite/colorize-fixtures/arrow-function.js index f305d9a..bef2956 100644 --- a/src/tests/suite/colorize-fixtures/arrow-function.js +++ b/src/tests/suite/colorize-fixtures/arrow-function.js @@ -1,3 +1,4 @@ const arrowFun = (...args) => css` height: 12px; `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/attrs-arrow-template.js b/src/tests/suite/colorize-fixtures/attrs-arrow-template.js new file mode 100644 index 0000000..529c7f3 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/attrs-arrow-template.js @@ -0,0 +1,32 @@ +const A = styled.div.attrs((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const B = styled.div.withConfig((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const C = styled(Button).attrs((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const D = styled(Button).withConfig((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const E = Button.extend.attrs((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const F = Button.extend.withConfig((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const G = foo().styled.div.attrs((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const H = foo().styled.div.withConfig((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const I = styled.div.attrs((p) => + `color: red;`)`color: blue;`; +const sentinel = 1; +const J = styled.div.attrs((p) => `color: red;`) +`color: blue;`; +const sentinel = 1; +const K = styled.div.attrs({ title: (p) => `x` })`color: blue;`; +const sentinel = 1; +const L = styled.div.withConfig({ displayName: (p) => `x` })`color: blue;`; +const sentinel = 1; +const M = styled(Button).attrs({ title: (p) => `x` })`color: blue;`; +const sentinel = 1; +const N = styled.div.attrs({ a: 1 })((p) => `color: red;`); +const sentinel = 1; +const O = styled.div.attrs((p) => `x`).attrs((q) => `y`)`color: blue;`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/attrs-arrow-template.tsx b/src/tests/suite/colorize-fixtures/attrs-arrow-template.tsx new file mode 100644 index 0000000..529c7f3 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/attrs-arrow-template.tsx @@ -0,0 +1,32 @@ +const A = styled.div.attrs((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const B = styled.div.withConfig((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const C = styled(Button).attrs((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const D = styled(Button).withConfig((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const E = Button.extend.attrs((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const F = Button.extend.withConfig((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const G = foo().styled.div.attrs((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const H = foo().styled.div.withConfig((p) => `color: red;`)`color: blue;`; +const sentinel = 1; +const I = styled.div.attrs((p) => + `color: red;`)`color: blue;`; +const sentinel = 1; +const J = styled.div.attrs((p) => `color: red;`) +`color: blue;`; +const sentinel = 1; +const K = styled.div.attrs({ title: (p) => `x` })`color: blue;`; +const sentinel = 1; +const L = styled.div.withConfig({ displayName: (p) => `x` })`color: blue;`; +const sentinel = 1; +const M = styled(Button).attrs({ title: (p) => `x` })`color: blue;`; +const sentinel = 1; +const N = styled.div.attrs({ a: 1 })((p) => `color: red;`); +const sentinel = 1; +const O = styled.div.attrs((p) => `x`).attrs((q) => `y`)`color: blue;`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/attrs.js b/src/tests/suite/colorize-fixtures/attrs.js index a6843e2..1494791 100644 --- a/src/tests/suite/colorize-fixtures/attrs.js +++ b/src/tests/suite/colorize-fixtures/attrs.js @@ -3,3 +3,4 @@ const Link = styled.a.attrs({ })` color: red; `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/await-member.js b/src/tests/suite/colorize-fixtures/await-member.js new file mode 100644 index 0000000..d07d5d6 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/await-member.js @@ -0,0 +1,12 @@ +async function load() { + const A = (await import("styled-components")).styled.div` + color: red; + `; + const B = (await import("styled-components")).styled(Button).attrs({ b: 2 })` + margin: 0; + `; + const C = items[0].styled.div` + padding: 0; + `; +} +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/body-edges.js b/src/tests/suite/colorize-fixtures/body-edges.js new file mode 100644 index 0000000..ab43349 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/body-edges.js @@ -0,0 +1,22 @@ +const A = styled.div``; +const B = styled.div` +`; +const C = styled.div`color: red;`; const D = css``; const E = css`a{b:c}` +const F = styled.div` + ${p => p.x && css` + color: ${q => `${q}`}; + `} + &:hover { color: BLUE; COLOR: Red; } + font: 12px/1.5 Helvetica, sans-serif; + transition: color 1s ease-in-out, fill 2s; + border-start-end-radius: 1px; fieldset > style { x: y } + background: rgba(0,0,0,.5) url("a.png"); width: calc(100% - 10px); + @media (max-width: 10px) and (orientation: landscape) { DIV.a, Span#b { margin: 0 } } + @font-face { font-family: X; src: url(x.woff) format("woff"); } +`; +const G = keyframes`from { opacity: 0 } 50% { opacity: .5 } to { opacity: 1 }`; +const H = createGlobalStyle`body { margin: 0 } :root { --x: 1px; }`; +const I = styled(Button).attrs({ a: 1 })` + color: ${({ theme }) => theme.c};`; +const J = styled.div`;`; const K = styled.div` `; const L = styled.div`${x}`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/body-edges.tsx b/src/tests/suite/colorize-fixtures/body-edges.tsx new file mode 100644 index 0000000..b513544 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/body-edges.tsx @@ -0,0 +1,14 @@ +const a =
x
; +const b =
x
; +const c = ; +const d = ; +const e = ; +const f = styled.div<{ a: boolean }>` + color: ${(p) => (p.a ? "red" : "blue")}; +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/call-prefix-root.js b/src/tests/suite/colorize-fixtures/call-prefix-root.js new file mode 100644 index 0000000..6e62c6e --- /dev/null +++ b/src/tests/suite/colorize-fixtures/call-prefix-root.js @@ -0,0 +1,5 @@ +const i = foo().styled.div`color: red;`; +const j = foo().styled(Button)`color: red;`; +const k = foo().styled.div.attrs({})`color: red;`; +foo().styled.div`color: red;`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/closers.js b/src/tests/suite/colorize-fixtures/closers.js new file mode 100644 index 0000000..f3e7a7d --- /dev/null +++ b/src/tests/suite/colorize-fixtures/closers.js @@ -0,0 +1,24 @@ +// A tag after a closer of an earlier line: the tag rule must not consume what the host needs to close its frame +function g() { + return [Comp.extend`color: red;`]; +} + +function f() { + return foo({ a: keyframes`from { color: red; }` }); +} + +const X = cond ? ( + a +) : Comp.extend`color: red;`; + +const anims = [ + 1, 2 ].concat(keyframes`from { color: red; }`); + +const y = cond ? ( + a +) : keyframes`from { color: red; }`; + +const z = cond ? ( + a +) : styled.div`color: red;`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/comment.js b/src/tests/suite/colorize-fixtures/comment.js index b36ad28..af14b32 100644 --- a/src/tests/suite/colorize-fixtures/comment.js +++ b/src/tests/suite/colorize-fixtures/comment.js @@ -2,3 +2,4 @@ // height: 20px; // padding: 5px; // ` +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/component.js b/src/tests/suite/colorize-fixtures/component.js index 9bdc2e5..c48ef5a 100644 --- a/src/tests/suite/colorize-fixtures/component.js +++ b/src/tests/suite/colorize-fixtures/component.js @@ -1,3 +1,4 @@ const Component = styled(Component)` color: #ebebeb; `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/createGlobalStyle.js b/src/tests/suite/colorize-fixtures/createGlobalStyle.js index 0064b41..4e73343 100644 --- a/src/tests/suite/colorize-fixtures/createGlobalStyle.js +++ b/src/tests/suite/colorize-fixtures/createGlobalStyle.js @@ -3,3 +3,4 @@ const GlobalStyles = createGlobalStyle` color: 'red'; } `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/css-prop.js b/src/tests/suite/colorize-fixtures/css-prop.js index 0887aff..c01708f 100644 --- a/src/tests/suite/colorize-fixtures/css-prop.js +++ b/src/tests/suite/colorize-fixtures/css-prop.js @@ -4,3 +4,4 @@ color: ${props => props.theme.colors.text}; `} />; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/custom-at-rule.js b/src/tests/suite/colorize-fixtures/custom-at-rule.js index 8ea27a3..75ce6b4 100644 --- a/src/tests/suite/colorize-fixtures/custom-at-rule.js +++ b/src/tests/suite/colorize-fixtures/custom-at-rule.js @@ -12,3 +12,4 @@ const customAtRule = styled.div` background-color: red; } ` +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/dot-tag.js b/src/tests/suite/colorize-fixtures/dot-tag.js index 98ffe16..53a905a 100644 --- a/src/tests/suite/colorize-fixtures/dot-tag.js +++ b/src/tests/suite/colorize-fixtures/dot-tag.js @@ -4,3 +4,4 @@ const DotTag = styled.div` font-family: Helvetica; ${mixin}; `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/export-default.js b/src/tests/suite/colorize-fixtures/export-default.js index 6ef358f..7723db5 100644 --- a/src/tests/suite/colorize-fixtures/export-default.js +++ b/src/tests/suite/colorize-fixtures/export-default.js @@ -1,3 +1,4 @@ export default styled(ExportComponent)` max-width: 100%; `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/extend-chain.js b/src/tests/suite/colorize-fixtures/extend-chain.js new file mode 100644 index 0000000..4cd2707 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/extend-chain.js @@ -0,0 +1,12 @@ +const B = Button.extend.attrs({ a: 1 })`color: red;`; +const C = Button.extend.withConfig({ a: 1 })`color: red;`; +const D = Button.extend.attrs({ + a: 1, +})` + color: red; +`; +const E = Button.extend + .attrs({ a: 1 })` + color: red; +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/extend.js b/src/tests/suite/colorize-fixtures/extend.js index f605b7b..c5adbaa 100644 --- a/src/tests/suite/colorize-fixtures/extend.js +++ b/src/tests/suite/colorize-fixtures/extend.js @@ -15,3 +15,4 @@ const foo = { const Half = getFull().extend` max-width: 100%; ` +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/function-call-space.js b/src/tests/suite/colorize-fixtures/function-call-space.js index 50b8872..7ec3e95 100644 --- a/src/tests/suite/colorize-fixtures/function-call-space.js +++ b/src/tests/suite/colorize-fixtures/function-call-space.js @@ -1,3 +1,4 @@ const Component = styled (Component)` max-width: 100%; `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/function-call-with-css-helper.js b/src/tests/suite/colorize-fixtures/function-call-with-css-helper.js index 87d7eb4..85f3318 100644 --- a/src/tests/suite/colorize-fixtures/function-call-with-css-helper.js +++ b/src/tests/suite/colorize-fixtures/function-call-with-css-helper.js @@ -21,3 +21,4 @@ const Component3 = styled.div` width: 100%; `)} `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/function-call.js b/src/tests/suite/colorize-fixtures/function-call.js index 492c0ac..fcb7b99 100644 --- a/src/tests/suite/colorize-fixtures/function-call.js +++ b/src/tests/suite/colorize-fixtures/function-call.js @@ -1,3 +1,4 @@ const Component = styled(getComponent(props))` max-width: 100%; `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/function-media-queries.js b/src/tests/suite/colorize-fixtures/function-media-queries.js index d55e03b..abc95b1 100644 --- a/src/tests/suite/colorize-fixtures/function-media-queries.js +++ b/src/tests/suite/colorize-fixtures/function-media-queries.js @@ -88,3 +88,4 @@ const Input = styled.input.attrs({ margin: ${props => props.margin}; padding: ${props => props.padding}; `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/generics.ts b/src/tests/suite/colorize-fixtures/generics.ts new file mode 100644 index 0000000..24ba889 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/generics.ts @@ -0,0 +1,124 @@ +// #358 and #442: type arguments that span lines +const Container = styled.div<{ + fullWidth?: boolean; + isMyMessage?: boolean | null; +}>` + color: red; +`; + +const B = styled.div< + Props +>` + color: red; +`; +const D = styled.div` + color: red; +`; + +const A = styled(Button)<{ + a: string; +}>` + color: red; +`; +const C = styled("div")<{ + a: string; +}>` + color: red; +`; + +const R = styled.div<{ + a: Record; + b: Array; +}>` + color: red; + ${(p) => p.a && css` + color: red; + `} +`; + +const Pick1 = styled.div & { + b: string +}>` + color: red; +`; + +const X = styled.div<{ a: string; + b: number; +}>` + color: red; +`; +const E = styled.div<{ onClick: () => void; + b: string }>` + color: red; +`; + +// .attrs after and around a generic +const AG = styled.div.attrs((p) => ({ + a: 1, +}))` + color: red; +`; +const ML = styled.div< + Props +>.attrs((p) => ({ + title: `${p.s}`, +}))` + color: red; +`; +const G = styled.div.attrs((p) => ({ + a: 1, +}))<{ b: string }>` + color: red; +`; +const H = styled.div.attrs({ a: 1 })<{ + b: string +}>` + color: red; +`; +const I = styled(Link).attrs<{ $a: boolean }>(({ $a }) => ({ + role: $a ? "x" : "y", +}))` + color: red; +`; +const M6 = styled(Button).attrs({ type: "button" })<{ + a: string +}>` + color: red; +`; +const M7 = styled.div.attrs(p => ({}))` + color: red; +`; + +// helper generics +const GS = createGlobalStyle<{ + dark: boolean; +}>` + body { color: red; } +`; +const c = css<{ + a: string; +}>` + color: red; +`; +const k = keyframes<{ + a: string; +}>` + from { color: red; } +`; + +const T3 = styled(Button)<{ + v: `a-${string}` +}>` + color: red; +`; +const E1 = styled("div")` + color: red; +`; +const E2 = styled.div<{ a: (x: number) => void }>` + color: red; +`; +const E3 = styled.div` + ${(p: Props) => p.a && css`color: red;`} +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/generics.tsx b/src/tests/suite/colorize-fixtures/generics.tsx new file mode 100644 index 0000000..24ba889 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/generics.tsx @@ -0,0 +1,124 @@ +// #358 and #442: type arguments that span lines +const Container = styled.div<{ + fullWidth?: boolean; + isMyMessage?: boolean | null; +}>` + color: red; +`; + +const B = styled.div< + Props +>` + color: red; +`; +const D = styled.div` + color: red; +`; + +const A = styled(Button)<{ + a: string; +}>` + color: red; +`; +const C = styled("div")<{ + a: string; +}>` + color: red; +`; + +const R = styled.div<{ + a: Record; + b: Array; +}>` + color: red; + ${(p) => p.a && css` + color: red; + `} +`; + +const Pick1 = styled.div & { + b: string +}>` + color: red; +`; + +const X = styled.div<{ a: string; + b: number; +}>` + color: red; +`; +const E = styled.div<{ onClick: () => void; + b: string }>` + color: red; +`; + +// .attrs after and around a generic +const AG = styled.div.attrs((p) => ({ + a: 1, +}))` + color: red; +`; +const ML = styled.div< + Props +>.attrs((p) => ({ + title: `${p.s}`, +}))` + color: red; +`; +const G = styled.div.attrs((p) => ({ + a: 1, +}))<{ b: string }>` + color: red; +`; +const H = styled.div.attrs({ a: 1 })<{ + b: string +}>` + color: red; +`; +const I = styled(Link).attrs<{ $a: boolean }>(({ $a }) => ({ + role: $a ? "x" : "y", +}))` + color: red; +`; +const M6 = styled(Button).attrs({ type: "button" })<{ + a: string +}>` + color: red; +`; +const M7 = styled.div.attrs(p => ({}))` + color: red; +`; + +// helper generics +const GS = createGlobalStyle<{ + dark: boolean; +}>` + body { color: red; } +`; +const c = css<{ + a: string; +}>` + color: red; +`; +const k = keyframes<{ + a: string; +}>` + from { color: red; } +`; + +const T3 = styled(Button)<{ + v: `a-${string}` +}>` + color: red; +`; +const E1 = styled("div")` + color: red; +`; +const E2 = styled.div<{ a: (x: number) => void }>` + color: red; +`; +const E3 = styled.div` + ${(p: Props) => p.a && css`color: red;`} +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/head-chain-newline.js b/src/tests/suite/colorize-fixtures/head-chain-newline.js new file mode 100644 index 0000000..325aba2 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/head-chain-newline.js @@ -0,0 +1,14 @@ +const A = styled.div + .attrs({ a: 1 }) + .withConfig({ displayName: "A" })` + color: red; +`; +const B = styled(Button) + .attrs({ b: 2 })` + margin: 0; +`; +const C = styled.div.attrs({ c: 3 }) + .withConfig({ displayName: "C" })` + padding: 0; +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/head-comment.js b/src/tests/suite/colorize-fixtures/head-comment.js new file mode 100644 index 0000000..8646d7d --- /dev/null +++ b/src/tests/suite/colorize-fixtures/head-comment.js @@ -0,0 +1,9 @@ +const A = styled.div // why +` + color: red; +`; +const B = styled.div.attrs({ b: 2 }) /* why */ +` + margin: 0; +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/head-multiline.js b/src/tests/suite/colorize-fixtures/head-multiline.js new file mode 100644 index 0000000..7e7a0c2 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/head-multiline.js @@ -0,0 +1,97 @@ +// #292: .attrs given a props value, and heads that span lines +const M1 = styled.div.attrs(({}))` color: red; `; +const M2 = styled.div.attrs(()=>({}))` color: red; `; +const M3 = styled.div.attrs((someVar))` color: red; `; +const M4 = styled.div.attrs(someFunc())` color: red; `; +const Root = styled.div.attrs(props=>({ + "data-status": `${props.status}` +}))` + color: red; +`; + +const B = styled.div.attrs((p) => ({ + className: `x-${p.a}`, +}))` + color: red; +`; + +const C = styled.div.withConfig({ + shouldForwardProp: (prop) => !["a"].includes(prop), +})` + color: red; +`; + +// #383: a call whose argument is an arrow function returning an object, before a tag's template +const D = styled("div")(({ theme }) => ` + color: red; +`); +const E = styled.div(({ theme }) => ` + color: red; +`); + +const F = styled.div.attrs({ + // a comment with a ) paren + a: 1, /* and ( one */ +})` + color: red; +`; + +const G = styled.div.attrs({ + + a: 1, +})` + color: red; +`; + +const H = styled.div.attrs((p) => ({ + a: 1, +}))` + color: red; + ${(p) => p.a && css` + color: red; + `} +`; +const S = { a: css`color: red;`, b: styled.p`color: red;` }; + +const I = styled( + Button +)` + color: red; +`; +const J = styled + .div` + color: red; +`; + +const K = styled(Button, { + shouldForwardProp: (p) => p.length < 3 && p !== "x", +})` + color: red; +`; + +const L = styled.div.attrs((p) => ({ + a: p?.b ?? 1, + c: [1, 2].map((x) => x < 2), +}))` + color: red; +`; + +const M = styled.div.attrs({ + re: /[(`]/g, +})` + color: red; +`; + +const N = styled.div.attrs({ + s: "(", + t: ")))", +})` + color: red; +`; + +const O = styled.div.attrs({ + title: `a ${b} (`, +})` + color: red; +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/head-multiline.ts b/src/tests/suite/colorize-fixtures/head-multiline.ts new file mode 100644 index 0000000..7e7a0c2 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/head-multiline.ts @@ -0,0 +1,97 @@ +// #292: .attrs given a props value, and heads that span lines +const M1 = styled.div.attrs(({}))` color: red; `; +const M2 = styled.div.attrs(()=>({}))` color: red; `; +const M3 = styled.div.attrs((someVar))` color: red; `; +const M4 = styled.div.attrs(someFunc())` color: red; `; +const Root = styled.div.attrs(props=>({ + "data-status": `${props.status}` +}))` + color: red; +`; + +const B = styled.div.attrs((p) => ({ + className: `x-${p.a}`, +}))` + color: red; +`; + +const C = styled.div.withConfig({ + shouldForwardProp: (prop) => !["a"].includes(prop), +})` + color: red; +`; + +// #383: a call whose argument is an arrow function returning an object, before a tag's template +const D = styled("div")(({ theme }) => ` + color: red; +`); +const E = styled.div(({ theme }) => ` + color: red; +`); + +const F = styled.div.attrs({ + // a comment with a ) paren + a: 1, /* and ( one */ +})` + color: red; +`; + +const G = styled.div.attrs({ + + a: 1, +})` + color: red; +`; + +const H = styled.div.attrs((p) => ({ + a: 1, +}))` + color: red; + ${(p) => p.a && css` + color: red; + `} +`; +const S = { a: css`color: red;`, b: styled.p`color: red;` }; + +const I = styled( + Button +)` + color: red; +`; +const J = styled + .div` + color: red; +`; + +const K = styled(Button, { + shouldForwardProp: (p) => p.length < 3 && p !== "x", +})` + color: red; +`; + +const L = styled.div.attrs((p) => ({ + a: p?.b ?? 1, + c: [1, 2].map((x) => x < 2), +}))` + color: red; +`; + +const M = styled.div.attrs({ + re: /[(`]/g, +})` + color: red; +`; + +const N = styled.div.attrs({ + s: "(", + t: ")))", +})` + color: red; +`; + +const O = styled.div.attrs({ + title: `a ${b} (`, +})` + color: red; +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/injectGlobal.js b/src/tests/suite/colorize-fixtures/injectGlobal.js index 742a254..9dcf4ca 100644 --- a/src/tests/suite/colorize-fixtures/injectGlobal.js +++ b/src/tests/suite/colorize-fixtures/injectGlobal.js @@ -8,3 +8,4 @@ injectGlobal` margin: 0; } `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/inside-function.js b/src/tests/suite/colorize-fixtures/inside-function.js index cda42ff..8e9fc76 100644 --- a/src/tests/suite/colorize-fixtures/inside-function.js +++ b/src/tests/suite/colorize-fixtures/inside-function.js @@ -3,3 +3,4 @@ function insideFunction() { height: 15px; `; } +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/inside-method.js b/src/tests/suite/colorize-fixtures/inside-method.js index bed8867..6667e21 100644 --- a/src/tests/suite/colorize-fixtures/inside-method.js +++ b/src/tests/suite/colorize-fixtures/inside-method.js @@ -5,3 +5,4 @@ class InsideMethod extends React.Component { `; } } +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/interpolation-in-function.js b/src/tests/suite/colorize-fixtures/interpolation-in-function.js new file mode 100644 index 0000000..55f25e7 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/interpolation-in-function.js @@ -0,0 +1,10 @@ +const A = styled.div` + background: url(${img}); + background: url(${(p) => p.src}) no-repeat; + background: url("${img}"); + background: url(img-${n}.png); + background: url('${img}'); + font-family: var(--a, "${font}"); + content: attr(data-a "${text}"); +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/jsx-in-head.js b/src/tests/suite/colorize-fixtures/jsx-in-head.js new file mode 100644 index 0000000..3332ba5 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/jsx-in-head.js @@ -0,0 +1,12 @@ +// A Material-UI wrapper: JSX inside the head keeps its JSX scopes +const StyledButton = styled(({ color, ...other }) => ( +