From 848bae1fdfe18dbaa55a99bce725c5a7ad391786 Mon Sep 17 00:00:00 2001 From: Ludovico Fischer Date: Sat, 7 Nov 2026 13:22:55 +0100 Subject: [PATCH 1/3] chore: update pnpm to 12.18.0 --- package.json | 2 +- pnpm-lock.yaml | 122 ++++++++++++++++++++++++------------------------- 2 files changed, 62 insertions(+), 62 deletions(-) diff --git a/package.json b/package.json index a788718..632dfd6 100644 --- a/package.json +++ b/package.json @@ -52,7 +52,7 @@ "devEngines": { "packageManager": { "name": "pnpm", - "version": "12.16.1" + "version": "12.18.0" } }, "devDependencies": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 33f403e..36d590e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7,153 +7,153 @@ importers: configDependencies: {} packageManagerDependencies: pnpm: - specifier: 12.16.1 - version: 12.16.1 + specifier: 12.18.0 + version: 12.18.0 packages: - '@pnpm/exe.android-arm64@12.16.1': - resolution: {integrity: sha512-PKf78Ew+i0CBYf0Xc+eMcqQiqyBT+u8XCVg1F5roc98/6wWfdYlWhrUMmEBiKWaJ3JqHxrtt8l1NwZ7qfJt2/Q==} + '@pnpm/exe.android-arm64@12.18.0': + resolution: {integrity: sha512-fOF6IwgvnUKEmVedGqiAsNPfN2Ry8GvaqzSQOiF3RJFbpBfPKO/6YT54s1GjToyYinRxw9preHHPe4y2N3SzhA==} cpu: [arm64] os: [android] - '@pnpm/exe.android-x64@12.16.1': - resolution: {integrity: sha512-xdu7gMbB98pdvhwMeA6612Of515FDlRUtfA/1f7nWPZfPLnEdSRBO2u+1N0XBtQ/ennhPH/lrxB1gC6gnR/cdg==} + '@pnpm/exe.android-x64@12.18.0': + resolution: {integrity: sha512-6OiolnaCsB3/GcJ9XNrenbUH3zFHRJ+5QynrMUUEyThbgnnCzWxa199hpQlOmxN4rAXuYQ0IYgWFNUZxyzg31Q==} cpu: [x64] os: [android] - '@pnpm/exe.darwin-arm64@12.16.1': - resolution: {integrity: sha512-pVbmIIbhixiLvADLu1WA3TaW8FZy/D72R1De27WbbFx8/2mxvnsTyFVm4fO9kjpjMY7RzJd48CiQ96p8fO3ebQ==} + '@pnpm/exe.darwin-arm64@12.18.0': + resolution: {integrity: sha512-zkq+4YzVIX39ETYLyC3W7LY7MpHEU/J3nRhHl4i2yPld2Cf2+rEKRh3ejJ4AmaQ77HHJLCktY4Z3jq0fpcxFXg==} cpu: [arm64] os: [darwin] - '@pnpm/exe.darwin-x64@12.16.1': - resolution: {integrity: sha512-xZvQBFqcZjO7vFKTK3XsJpqY6lnBL9EWSLCzVUPq3kZ94+D96gwJCa76xxGNK8Cj32f4eeM91Qg+yNRR4sRpDw==} + '@pnpm/exe.darwin-x64@12.18.0': + resolution: {integrity: sha512-qMsL9qx92unOTa6hgkfiTJv8ceZaTx0IQg7InhYDVX2ZrTECujaVEEVypnJK5m3eGUsP1KD7Y4qIgleCwfRsYw==} cpu: [x64] os: [darwin] - '@pnpm/exe.freebsd-x64@12.16.1': - resolution: {integrity: sha512-zTtunfi9mBhRXiXEJYfwiJj0tk7MgTSfqDSRh+Az9FZ9THazVIiQiVNS8jpcsftDOqu7LKNffQdjmgwHDThfUg==} + '@pnpm/exe.freebsd-x64@12.18.0': + resolution: {integrity: sha512-/9vy/4ms52cU4MjZ5NhHd6N2d9L9W0kARf5/ff2tweAHu0VeUzs/0qp/7ZHFuddm2Wa/m0AKQoPum9AVUCqKsw==} cpu: [x64] os: [freebsd] - '@pnpm/exe.linux-arm64-musl@12.16.1': - resolution: {integrity: sha512-BJ3mOmcmQgcUo92Ee/WfEOt1pRiv3y2MMAkhEiYHd85UiPpHTfFhv+SpCbALmfExzXk3UlaRtMYwHlkQymc4VA==} + '@pnpm/exe.linux-arm64-musl@12.18.0': + resolution: {integrity: sha512-Vp+TIMPPyackVCXkOdEKH/RmAn/r07EcIyrgZYQK7VrkksqZOie0GnWIx+85mPqeFEYCRtXIZAFJ9L4ceTndDg==} cpu: [arm64] os: [linux] libc: [musl] - '@pnpm/exe.linux-arm64@12.16.1': - resolution: {integrity: sha512-JaRd5gNxwdNGBBkrZFt8bknrK4YmHVJBW0JMhUQ0fJ0dEYp6C2GT9ExaCqOO8EwYEyqM+jpKgJIK+8WFaJy3ew==} + '@pnpm/exe.linux-arm64@12.18.0': + resolution: {integrity: sha512-2dpyVBCHT+FfpuQh9i+7MXAqNWYLCvD5vYr5p6Eimxoga8USLnjbUgyj72AOrO0hjc5ri3TEFP3jiyBHjkSZpQ==} cpu: [arm64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-ppc64@12.16.1': - resolution: {integrity: sha512-FnSV0Jv40S1cMv7vFNWwvu0X567Lec4L4HCRead3CFcD6zQDNbGw81s8N5bcKPahtPD9ApVuhsbmFCx4rw6RMw==} + '@pnpm/exe.linux-ppc64@12.18.0': + resolution: {integrity: sha512-BBOOOfNJ2QwIIya3eKqOjiN4WNTszfRz7HCvw9XggcT7+ftMjNP8XJ/GfW+ltCBeUFR9d8WBVsr2m/NLjX2CZQ==} cpu: [ppc64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-riscv64@12.16.1': - resolution: {integrity: sha512-C1Sww4FN5IttD4atRRhAKmQtSGWVp04ZAKNxO8pfu2bkRPwOW+7v+2DH1Xs1W+kZYYpO86BYDvUcadefF+AgaQ==} + '@pnpm/exe.linux-riscv64@12.18.0': + resolution: {integrity: sha512-7kMN77xSOYJX8GPSH5RbNAc5oM61LMmcSUukDDUwllnZPXm8GRPskCNsTWy8SCw01Kr1FB+5SwGNMiTdiziLNQ==} cpu: [riscv64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-s390x@12.16.1': - resolution: {integrity: sha512-kn2fautsTcxIMODoovQVqZyfpDRdNgGkoeVqNdrKqbeBBvrEl+fXLkmZiq5xDht1LMr4sYiCNcsMfNMT6JPFmg==} + '@pnpm/exe.linux-s390x@12.18.0': + resolution: {integrity: sha512-htuSCpEcmDzhKoJqXbPkvfr176dBHU0QIF5mWcRiqxRXAB/1JoYiMYotfjWpk+ztgpB9qlx4XnWlLFAf7gzc6g==} cpu: [s390x] os: [linux] libc: [glibc] - '@pnpm/exe.linux-x64-musl@12.16.1': - resolution: {integrity: sha512-PM6ccHCOe/O9SsTflTJTYWfwogJZa6EmUvpnwZgiPguJBddh20wDQKgxUPXf48rDsPm9vMsIij0uHswwwbXL8g==} + '@pnpm/exe.linux-x64-musl@12.18.0': + resolution: {integrity: sha512-Uj+vzfIQ62kDP10x36yHZIXVs5ohdNtiPYwn5FhCLlNScHPo0OAI+ShGDtLofiBXKE7umu71Jmjm7N8a8zVcDw==} cpu: [x64] os: [linux] libc: [musl] - '@pnpm/exe.linux-x64@12.16.1': - resolution: {integrity: sha512-RK//8ZLcXGW8A2k8bQOXZDBN1Qu92zN4dYnG1bzj1zoQ1fkZ6jNzZ1AvXtsfGVma795CJtvoaF5bLXf4l/FIUw==} + '@pnpm/exe.linux-x64@12.18.0': + resolution: {integrity: sha512-OJ+X2wcraldCwj75pCIerWARQSRpdfj0eBTs/2ODyhfeW46ylOnjTIE/GKra6Mn6E72/gBmXS8igrUioa+F9fQ==} cpu: [x64] os: [linux] libc: [glibc] - '@pnpm/exe.win32-arm64@12.16.1': - resolution: {integrity: sha512-Ox3kNNVxtGw6pK7SVejmeOUgHhUTZgAM7NQQ6cU7frPw3ix9+j7d2MGbRg3fyEFAaKWq8ZAZLTQGcDyLnAu+qA==} + '@pnpm/exe.win32-arm64@12.18.0': + resolution: {integrity: sha512-wEY6jiACGcbhhi5yD59doHqNTndS7AaujaPmtWAu1DKkHru2hy5fJ9yUGecW72Ypaw2/I3BEprfMOopap2NQtw==} cpu: [arm64] os: [win32] - '@pnpm/exe.win32-x64@12.16.1': - resolution: {integrity: sha512-k+FhRJ0ttphFoFIVB1Sk4v76YJAulafmA/Ly57cysesUhhIzVlApeOShUz0jXubKx317TThlEfpQrukldnqORA==} + '@pnpm/exe.win32-x64@12.18.0': + resolution: {integrity: sha512-5FJkghO7RLRkQpWxeVEygW9XsmnNuxzPfXbgwFWCHsFyFhpDn/vOdL88ToQEM0Kt5igdW5s6U0/IDH8Dvkt3pg==} cpu: [x64] os: [win32] - pnpm@12.16.1: - resolution: {integrity: sha512-CR0d7nknV1Zhsl2rPCrjHK/BxU1rce1qZgDPDByxBDSkR+rhQBXxsj4ua+3u1535SpMuIWTSgyKA3OP7MvZW0Q==} + pnpm@12.18.0: + resolution: {integrity: sha512-nXiC1dyCFH7PxOBiqjSDTgrQKWcQoYN6ERWuASEn02txCeMhrBWYod0KZVl2gbHpmRfhLtDXSerpEYeUM2O+sw==} engines: {node: '>=18'} hasBin: true snapshots: - '@pnpm/exe.android-arm64@12.16.1': + '@pnpm/exe.android-arm64@12.18.0': optional: true - '@pnpm/exe.android-x64@12.16.1': + '@pnpm/exe.android-x64@12.18.0': optional: true - '@pnpm/exe.darwin-arm64@12.16.1': + '@pnpm/exe.darwin-arm64@12.18.0': optional: true - '@pnpm/exe.darwin-x64@12.16.1': + '@pnpm/exe.darwin-x64@12.18.0': optional: true - '@pnpm/exe.freebsd-x64@12.16.1': + '@pnpm/exe.freebsd-x64@12.18.0': optional: true - '@pnpm/exe.linux-arm64-musl@12.16.1': + '@pnpm/exe.linux-arm64-musl@12.18.0': optional: true - '@pnpm/exe.linux-arm64@12.16.1': + '@pnpm/exe.linux-arm64@12.18.0': optional: true - '@pnpm/exe.linux-ppc64@12.16.1': + '@pnpm/exe.linux-ppc64@12.18.0': optional: true - '@pnpm/exe.linux-riscv64@12.16.1': + '@pnpm/exe.linux-riscv64@12.18.0': optional: true - '@pnpm/exe.linux-s390x@12.16.1': + '@pnpm/exe.linux-s390x@12.18.0': optional: true - '@pnpm/exe.linux-x64-musl@12.16.1': + '@pnpm/exe.linux-x64-musl@12.18.0': optional: true - '@pnpm/exe.linux-x64@12.16.1': + '@pnpm/exe.linux-x64@12.18.0': optional: true - '@pnpm/exe.win32-arm64@12.16.1': + '@pnpm/exe.win32-arm64@12.18.0': optional: true - '@pnpm/exe.win32-x64@12.16.1': + '@pnpm/exe.win32-x64@12.18.0': optional: true - pnpm@12.16.1: + pnpm@12.18.0: optionalDependencies: - '@pnpm/exe.android-arm64': 12.16.1 - '@pnpm/exe.android-x64': 12.16.1 - '@pnpm/exe.darwin-arm64': 12.16.1 - '@pnpm/exe.darwin-x64': 12.16.1 - '@pnpm/exe.freebsd-x64': 12.16.1 - '@pnpm/exe.linux-arm64': 12.16.1 - '@pnpm/exe.linux-arm64-musl': 12.16.1 - '@pnpm/exe.linux-ppc64': 12.16.1 - '@pnpm/exe.linux-riscv64': 12.16.1 - '@pnpm/exe.linux-s390x': 12.16.1 - '@pnpm/exe.linux-x64': 12.16.1 - '@pnpm/exe.linux-x64-musl': 12.16.1 - '@pnpm/exe.win32-arm64': 12.16.1 - '@pnpm/exe.win32-x64': 12.16.1 + '@pnpm/exe.android-arm64': 12.18.0 + '@pnpm/exe.android-x64': 12.18.0 + '@pnpm/exe.darwin-arm64': 12.18.0 + '@pnpm/exe.darwin-x64': 12.18.0 + '@pnpm/exe.freebsd-x64': 12.18.0 + '@pnpm/exe.linux-arm64': 12.18.0 + '@pnpm/exe.linux-arm64-musl': 12.18.0 + '@pnpm/exe.linux-ppc64': 12.18.0 + '@pnpm/exe.linux-riscv64': 12.18.0 + '@pnpm/exe.linux-s390x': 12.18.0 + '@pnpm/exe.linux-x64': 12.18.0 + '@pnpm/exe.linux-x64-musl': 12.18.0 + '@pnpm/exe.win32-arm64': 12.18.0 + '@pnpm/exe.win32-x64': 12.18.0 --- lockfileVersion: '9.0' From 60f70eca1b347b0f5331245391c844907e300636 Mon Sep 17 00:00:00 2001 From: Ludovico Fischer Date: Sat, 7 Nov 2026 13:44:44 +0100 Subject: [PATCH 2/3] fix: update linters and fix lint error --- package.json | 4 +- pnpm-lock.yaml | 326 +++++++++---------- scripts/benchmark/parser-benchmark-worker.js | 4 +- 3 files changed, 167 insertions(+), 167 deletions(-) diff --git a/package.json b/package.json index 632dfd6..de03e47 100644 --- a/package.json +++ b/package.json @@ -59,8 +59,8 @@ "@csstools/css-calc": "^3.4.3", "@types/node": "^26.6.6", "fast-check": "^4.10.2", - "oxfmt": "^0.76.0", - "oxlint": "^1.91.0", + "oxfmt": "^0.77.0", + "oxlint": "^1.92.0", "postcss": "^8.5.32", "typescript": "~7.0.2" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 36d590e..d11f462 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -180,11 +180,11 @@ importers: specifier: ^4.10.2 version: 4.10.2 oxfmt: - specifier: ^0.76.0 - version: 0.76.0 + specifier: ^0.77.0 + version: 0.77.0 oxlint: - specifier: ^1.91.0 - version: 1.91.0 + specifier: ^1.92.0 + version: 1.92.0 postcss: specifier: ^8.5.32 version: 8.5.32 @@ -211,246 +211,246 @@ packages: resolution: {integrity: sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==} engines: {node: '>=20.19.0'} - '@oxfmt/binding-android-arm-eabi@0.76.0': - resolution: {integrity: sha512-z8x4kittQLPsrJWmfoIJyYqs2gNwceGShoUqAJdFRPw3K4kkkKCFHh3Cr4NFRvZb7DPfDS3+JfBjSm3OIyQaJQ==} + '@oxfmt/binding-android-arm-eabi@0.77.0': + resolution: {integrity: sha512-zmPiuOvkuu0csMx4U3gdMunIFWNcWulzikFMdAPBzLazVAA3LhdHzv9yzgUgAckv/zje5vz4XJcseNQKdSsWMw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [android] - '@oxfmt/binding-android-arm64@0.76.0': - resolution: {integrity: sha512-Zj9fEQhQSKGj8ZTB+X4q4ho4545xWf7qsvJpwREWnBz5BATEFYtStKRgiwYOZvxQ7ORlBEgSj7pmDzuljfV1mQ==} + '@oxfmt/binding-android-arm64@0.77.0': + resolution: {integrity: sha512-shXOIK9sj3bvt4H6K47qFWNKaYBwEhzj97iUwoLGyyRDrXt1OdAAuCiupCinG1i7ETL81knjEKeB+JmhOOfPew==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] - '@oxfmt/binding-darwin-arm64@0.76.0': - resolution: {integrity: sha512-jZy8GpUXaWpic5JPMAvLmaBz95Sx0naZl6hptBPLOMiYmZYiME7jAt6pv8o/tjQqPNWKb+7jKzZhrYx6UqM5MQ==} + '@oxfmt/binding-darwin-arm64@0.77.0': + resolution: {integrity: sha512-lrTX0I54buv9CW2leEWchWLdfcrblZ5Rj8uAilKzBEyWif8CTN6zBHdFc12K1b6U2cnlvOFBd1LxdLdqLKX2EA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@oxfmt/binding-darwin-x64@0.76.0': - resolution: {integrity: sha512-U59+a9lVpoRp9enRhTE9GssL3qB1k09CYagRzTfs3dfknopMYV0x0xHZv7Pls3SNMqHlyHR+ufmY76CYafQoLw==} + '@oxfmt/binding-darwin-x64@0.77.0': + resolution: {integrity: sha512-SD44K3x/Im8EsOtdHxjVmTBi0cafAaunRpCeq+w91tkD2keqYagR8oAvxkJHUK+KPg5NQk7JZqQnzGHnVEBrDw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@oxfmt/binding-freebsd-x64@0.76.0': - resolution: {integrity: sha512-J1R3YJHPdQJ2RQvzMdTVDWyizhihGiRGGAeEZxtGp629j5pcT5ypSLSiBflopD7o7tmiMD+xlNfhIVmjcHKMVQ==} + '@oxfmt/binding-freebsd-x64@0.77.0': + resolution: {integrity: sha512-N+gUflsCx3FAVkxi5sxGlL5LwO+7pv5NexHJufBqPyl3BcPv1rXpfwqhL/Vj+XfshfoxMFTBbzrbJgGVaPVkAw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] - '@oxfmt/binding-linux-arm-gnueabihf@0.76.0': - resolution: {integrity: sha512-x9qTg6zHoqeyzmFVlIjSb9WlhZdoXaayMTeQeDeUEfKA484AgPJz7f9chLjDMONA6wUUX0FJxnVHsYgX5Zv0+g==} + '@oxfmt/binding-linux-arm-gnueabihf@0.77.0': + resolution: {integrity: sha512-DXGwP8818IUZ4cxcfugg9PXqnI6fVCWIqgCgBoUKdl/QhJF4Po+lucJBrnrX/b5BNKwVMc3xSrvbI9rl8+RrBA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@oxfmt/binding-linux-arm-musleabihf@0.76.0': - resolution: {integrity: sha512-303gbamm7NDllTtkeaX+8F5Da+KcSBr64mqELQEFg9XgnjfLX3YBCHUcOfgIlVTSybesy43eoeKai8oGr0P6UA==} + '@oxfmt/binding-linux-arm-musleabihf@0.77.0': + resolution: {integrity: sha512-HUiJTgdV10PkCW41nHqVYYlW8Uc+39YBOoluZLfJE2MBPKVTNElhL+vpdSEuVaCGhGkzOGR6XyxM37gu31L1Qw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@oxfmt/binding-linux-arm64-gnu@0.76.0': - resolution: {integrity: sha512-j3UAXzCJoWX9bZLaICj6DfwkI/2fzja9RpiCIbIN+2CQAcKoY+5SH5pQUcECvn32mQm17NSPE9YqTAwYx1seZg==} + '@oxfmt/binding-linux-arm64-gnu@0.77.0': + resolution: {integrity: sha512-+w3V07y6yy8FdACnGtzgDsG/CHgA0Y/W2/bzZuPYgvBAa23Lap/nmvyNQmCiGKkSaChTPlY7QpIShGGAC7IGEQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [glibc] - '@oxfmt/binding-linux-arm64-musl@0.76.0': - resolution: {integrity: sha512-qFZqWVkEzuxWMtUkCtHxsnohXHnUMBQr/ZIxF0KmlCSt8de/bc1lbpVgpqjb3QxCADQHG/O1s3JcowcBF2sqdw==} + '@oxfmt/binding-linux-arm64-musl@0.77.0': + resolution: {integrity: sha512-FASxWQAuLW4WXFViDa77ybd3Y1lbkBx5DTtL4OGl+pL64/ymtydTFvJM0xz/0vnCirNzPUDAI6TiTBDGsFbEVg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [musl] - '@oxfmt/binding-linux-ppc64-gnu@0.76.0': - resolution: {integrity: sha512-ROiAid0UH2GN5lMMX2JTgKlOKx1rN+6a1WxIuBsU3j5A3MuB9U5XkREMW76XBbAImnH45mfOCFcSIwb+drcVYg==} + '@oxfmt/binding-linux-ppc64-gnu@0.77.0': + resolution: {integrity: sha512-WRdlgZahG35zCieq7Po7QU8mBgkFAIdEpgS5p3vVZrHt0FXTbFgzqC7xeBCceh9gpFGgr4VWblULNnU8gdw0DA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] libc: [glibc] - '@oxfmt/binding-linux-riscv64-gnu@0.76.0': - resolution: {integrity: sha512-Oyd/9ObdM2RYkZ7yzF/GyvVdbNgJcRG8BFVwnAVo3ooqzaem4E2p5eTIGB09FecQD+Q5HQEANOTEnIZTO6rBAQ==} + '@oxfmt/binding-linux-riscv64-gnu@0.77.0': + resolution: {integrity: sha512-CVzNO94x/UzQe/INVUu9qt5X1MjLEooqwc/5VcQ88eyLXiEIIsjubpPQgwEMKwfWtAA5hnpFL2GF74zSdCg07Q==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] libc: [glibc] - '@oxfmt/binding-linux-riscv64-musl@0.76.0': - resolution: {integrity: sha512-86DOpmPDR5UzHSOB8y5HlOpYAIBtMx+6L72IyousNx54q1Kz61aykB4ScovFYivZUak+7Ww6tPBUjarluzYKLw==} + '@oxfmt/binding-linux-riscv64-musl@0.77.0': + resolution: {integrity: sha512-NrCcVheqL0kRUi9gptqjkQhxSFayotM+zycC3lSOSrsf5SroZq49u66ShyuZkHCCzKPHB0AT0pL/s+ET9R3qQQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] libc: [musl] - '@oxfmt/binding-linux-s390x-gnu@0.76.0': - resolution: {integrity: sha512-u6omjjFooKfnHLBI+3UtBVInAeuEhoM/RAIw/OiFop2QQgOan5zDfqPR6guMaylt68L60kV+by07Ibp87KDjrw==} + '@oxfmt/binding-linux-s390x-gnu@0.77.0': + resolution: {integrity: sha512-LWDQ9T/Bo/kt/q223j9fYLiNTkUYyuMkk7ZrIsIAV7l19MmuKxgd/1tZ8xhoUuVIdsyET7sJrQ6X/vRG6V+bZQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] libc: [glibc] - '@oxfmt/binding-linux-x64-gnu@0.76.0': - resolution: {integrity: sha512-L0/hW1MdMrgsvuLGp9YEQOYOGj5xPHa8wVRtybdd5av03PV4qSpAq3pyfC7sn7UCA8ynRhMRTAa9Kr9nV4LGZg==} + '@oxfmt/binding-linux-x64-gnu@0.77.0': + resolution: {integrity: sha512-5JbOT3ucC/2kROUjyyOW06FjXO8trPjYb+kE7E7cLxmpGAnw0jjeU4Tjg4C8H9JR1MZ2oH4fXE1NqLNZ89ISnw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [glibc] - '@oxfmt/binding-linux-x64-musl@0.76.0': - resolution: {integrity: sha512-JNk/7HaPDJjy5kih3vq6b71Qif3tHx1ZFACGBzeHeNzyKaIpar4eFGya89GR398K2rwX0eEVmEq1npBPlEkkmg==} + '@oxfmt/binding-linux-x64-musl@0.77.0': + resolution: {integrity: sha512-/q9p495bmmKtxqWlIrNiJ15hoddgk/jPvJwMW6Nh796UgVRMTCKD7yI+AAL7/7xWlC3+2ls5l1RPywuV4lOdlw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [musl] - '@oxfmt/binding-openharmony-arm64@0.76.0': - resolution: {integrity: sha512-MDLrOQPXDuPKvPUCvpP3hC6kO72dsYxfpYiR08Nf5DiM75M0d8+D26JwT4uHDf0bcflvlGHcd58Hn2HpxkHUUQ==} + '@oxfmt/binding-openharmony-arm64@0.77.0': + resolution: {integrity: sha512-tmN3OEI38xXr48UeAkQMAX1jMHszVHv4I9lzh44DKrMlIFxEU0aBYl3Zs7PzRBuJOLR7h77m6bUlCh0E06MVXw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] - '@oxfmt/binding-win32-arm64-msvc@0.76.0': - resolution: {integrity: sha512-2CcICDrQKqMAOFuzmts/8Ov5iKb+DW/QrW4MFsl2bnRg86uoiUvtqUkHqNSY19Shegc8pBHiXMSEHDjIg94o0A==} + '@oxfmt/binding-win32-arm64-msvc@0.77.0': + resolution: {integrity: sha512-v//nJMk72xRT+/9QB9mJWEPV3/5XncMvxtYQAYbAsv5VcxLlRcbj2n2srQSERglVcTft4jI3MK30ceCoRcDTJg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] - '@oxfmt/binding-win32-ia32-msvc@0.76.0': - resolution: {integrity: sha512-NjZLJg+tQpMWVSyeWBBKCpib7H/uLq84ZzxCvY5eqHzSaItuzCECGA9MBiZwmW8fnkBIfppg49Ib//LSCGAp8Q==} + '@oxfmt/binding-win32-ia32-msvc@0.77.0': + resolution: {integrity: sha512-D3SMXWBkVogzAlzd3RfMaFuHOTdPpRDFT+jVbtXszWwck9PCK4hYoRoncjuAjWZuWzRFND3/Mk91qFvJyoJbLA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ia32] os: [win32] - '@oxfmt/binding-win32-x64-msvc@0.76.0': - resolution: {integrity: sha512-0vCMaX/qloc7uaKBDRh+62SBW8EqmhS7c8/al+PxD594ao4lyEWdcoEmVoBgnCNVW07GDpg+9uPV7x6ta9mljw==} + '@oxfmt/binding-win32-x64-msvc@0.77.0': + resolution: {integrity: sha512-2vyyODjP1Sb830rTVgfFqZoIUYF8uYdGx9S/Usih+Av6gQ9QyxXzwEGXS7poxfsxxQftZW1IbcFlhvQkeDRekQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] - '@oxlint/binding-android-arm-eabi@1.91.0': - resolution: {integrity: sha512-eOqJUUS1MCqIoUUxMIkuwaqIdKaHr1SXYA0CQI95UUrF8jwQylQH33bBmnqhZfvWXKlRB2Ylx/+Sbk/ctEqzZQ==} + '@oxlint/binding-android-arm-eabi@1.92.0': + resolution: {integrity: sha512-k3Sd4ixQfiOrybv1gT+AMI81HSdtAFsiCFx+xXxWdFkmKW2HNrSiOfwn20o5nl/ggwbzU1oNLDeU/fRPinTVZQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [android] - '@oxlint/binding-android-arm64@1.91.0': - resolution: {integrity: sha512-vIJU4lRxK0EhbBt+iR3rkq3pio4I+V5Gshwjei3plNjN+CIq0WxWHzYVI06J9KN8Ar3hyNSFtzJAjVRLZOYpjg==} + '@oxlint/binding-android-arm64@1.92.0': + resolution: {integrity: sha512-OZzgEuiTSG11QkBWdXEguiLOT6lL09KtfcC/BmvUQWBAjU5eVyBxIAsmWAXv8L85/eT6RE0GBEWTEFBAbYE74g==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] - '@oxlint/binding-darwin-arm64@1.91.0': - resolution: {integrity: sha512-tLy76MurwAOpQt5QVMkJUgexBSWhB7qdvAYb14bc0xntZS6f55aKicbZoxZ/QlmAbnrdlXeD5+IjwY8EZ9RWTg==} + '@oxlint/binding-darwin-arm64@1.92.0': + resolution: {integrity: sha512-We6XS7tIqxgUoany6uyGjj7mNsh/mwf4Gt9gUzhxG65NKo2Ow9s6tDfrVuI0FVg8n3YmpW5PBx80qFxiLwAfsA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@oxlint/binding-darwin-x64@1.91.0': - resolution: {integrity: sha512-zPeMmjAqm5vXxbTp/JqYuc9gGSbUuEaeCAkFHB4TCRLTlfJGD//Fkx03YvZHCHZJ7ideLiiLcae+3f2I27qnaA==} + '@oxlint/binding-darwin-x64@1.92.0': + resolution: {integrity: sha512-jKJWijmi6AxAZcXXWA6R/NLVZHxoRTbIMnV8znsHzeiVfuEefYcyR8SJGfbBPmkG+kveLFRcBGw0fBrjLqtGmQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@oxlint/binding-freebsd-x64@1.91.0': - resolution: {integrity: sha512-psOR9+xGMXn0hj4KY5M2kjSQ1n0TCMdYbPOraoV0iQyl7mw2oBBYGUM2+ma40m1YLVrktTBOta4FjrmcOHDhrg==} + '@oxlint/binding-freebsd-x64@1.92.0': + resolution: {integrity: sha512-wkw01wvJPM8/4jh+MV3cp11859VuBc94N2q5uOzcBgdGIRAqMCg1O0W/+xsZ1fsInvuUcv2Xo4nd1nzcKhi9kg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] - '@oxlint/binding-linux-arm-gnueabihf@1.91.0': - resolution: {integrity: sha512-1PNA1j4ETxawvxfz6ueDxWgQgWkXPbv44DWZmC7LR07GqojGFDOwWbosOT6/AYiJr7zMXEhn2dPWMkyFFOFpUQ==} + '@oxlint/binding-linux-arm-gnueabihf@1.92.0': + resolution: {integrity: sha512-Elm6nW308MzmR8knvk0tPqQ4XE+PGKztjXv7kVZTRLkhBQZRXHUQoBLc4E30fiIuF6gkZO5f3EpJtQc4Ok/fXw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@oxlint/binding-linux-arm-musleabihf@1.91.0': - resolution: {integrity: sha512-jcNePVpca37lTbHmiPMnVbPAAW0rH9kAoDjsDv6vESEX9pzazIR1q5SyYuc1rQzdjHtc2VVCDN9jDh6tHcOHyA==} + '@oxlint/binding-linux-arm-musleabihf@1.92.0': + resolution: {integrity: sha512-oylpBAoeogddjhTlSPsXrzGq/aeJsvaULz/hYXvWtGn/Wt8LPLC7gFhucCicbRnzEKsShrZxIA0KyHmtFNnijQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@oxlint/binding-linux-arm64-gnu@1.91.0': - resolution: {integrity: sha512-TJi78UX6R+9qZ23ZKtzN6adfW83bjY0NXsCRMBRH6H7IizaMXmZbdRAtjedMkx77bT46YQH0csawsY9lwha8MA==} + '@oxlint/binding-linux-arm64-gnu@1.92.0': + resolution: {integrity: sha512-/EWOI0wwY+74UGvC93TldpoNP8moIcidVUPbUSoX16/SEdF7ah209yxSQia4+9JdCRWYA3+yQMofXMgWKk/16Q==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [glibc] - '@oxlint/binding-linux-arm64-musl@1.91.0': - resolution: {integrity: sha512-OowlLroUTzKq5OBvbu6iegch8SJ2DivXFCukzPWURwvcJhMj7/P0CUGH5qrDlxT1Kh48dcxqYqrvE8qK6xTLKQ==} + '@oxlint/binding-linux-arm64-musl@1.92.0': + resolution: {integrity: sha512-9Se7Zuazr104yc2PaluriJW2rqvtaN6FSi9MSjQgZGeYb6LKvEcJ586tpjek0l7hNQNoir8MID7OENPH6juN1w==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [musl] - '@oxlint/binding-linux-ppc64-gnu@1.91.0': - resolution: {integrity: sha512-QF/5Ge8yGpWg5s4awMNHfVKh1WOmk591Qg082i6CHenXYBa+W1E5RwWZXaKUOw4Ko7CCjqg3TfBc0AzhnqblYg==} + '@oxlint/binding-linux-ppc64-gnu@1.92.0': + resolution: {integrity: sha512-88IAchs204I/xxAbAo3NRyz1m/29tn8jUAPvc4tK4FzrT2PLwZertd93ANF6231vwbAhYiD5gl0cX8Po5xsjWQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] libc: [glibc] - '@oxlint/binding-linux-riscv64-gnu@1.91.0': - resolution: {integrity: sha512-dXlsKlNhzJQX1nageGKnvWe1D7uTng249hQM80CG/YPZ8F/VZHbxVLhImgurdWBOmu86XOemValLjrW6QIOM/Q==} + '@oxlint/binding-linux-riscv64-gnu@1.92.0': + resolution: {integrity: sha512-KtFdVdkfvBGcsrmnbjYJ9/XTDABnaniiwnptAcAm0pkaR2zhZ3sr/Xy+N1Xbz1Yq5Jegu7SoeNv9caTP0b5OTA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] libc: [glibc] - '@oxlint/binding-linux-riscv64-musl@1.91.0': - resolution: {integrity: sha512-tznkj5VrWNRUfymkaLcJetgMLbP9suL5ob/m7j0Fdbnm5u3Li/Ezo/YcBixiuwdL1sg0oGpyTe86It0J6T+Lxg==} + '@oxlint/binding-linux-riscv64-musl@1.92.0': + resolution: {integrity: sha512-V43CO5FPgHtwHup4H5+dIdwzZX2FhREQGsSBZx8V1UyFEAul0Q13qviKqZfSMM6G41CGtCekVpJGGOxW5v1y8Q==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] libc: [musl] - '@oxlint/binding-linux-s390x-gnu@1.91.0': - resolution: {integrity: sha512-sNvfLiUYQkVsLNUgIW24AEYTHSd2zZ1vAxXssPdjuQHTtCpRvQihYri6d5z5FY7w/QrcnB5+g9E+/sqmZq8tfA==} + '@oxlint/binding-linux-s390x-gnu@1.92.0': + resolution: {integrity: sha512-WooxeACzGH5q34olo7JgAk7XbVkTUNfwhR/TzmhwVs/y1p2R7ZWJo14hiyxiGcoYZR1iBnbBFHectADqb/KSog==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] libc: [glibc] - '@oxlint/binding-linux-x64-gnu@1.91.0': - resolution: {integrity: sha512-eA25ETvimhUZ89y5BcunNY7yv7qwG2I7V7dFQAU+mIEqZ57gBCXdIERl0yXOEt43zjsw0yK2gRKTc+twF706wQ==} + '@oxlint/binding-linux-x64-gnu@1.92.0': + resolution: {integrity: sha512-lW2pLF1oFvNN780YUCtDyoUm8oFzZGJNcOFe9RtLMX5v5+FcWfAQvHUMMPF8H8kJB0HAi3dFmWDWLa5VPuY9mw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [glibc] - '@oxlint/binding-linux-x64-musl@1.91.0': - resolution: {integrity: sha512-4hZ4Z9K+OkcTpAHDoUTMg/8MModbM0aocrl9KnGzp9h5iKqjrXraEUZorYoVCT7xoK93CAHXgTndxRBrOjH/fA==} + '@oxlint/binding-linux-x64-musl@1.92.0': + resolution: {integrity: sha512-2BJAAB/eqPn7iD7mFVfs+1ZVUogAYOMCTaUgjAvbtNGg2ppCDE7gcv/9VSO6GCDybdFUqlcyeyjn9hRpl1ZHog==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [musl] - '@oxlint/binding-openharmony-arm64@1.91.0': - resolution: {integrity: sha512-gtqn4b0kLpGe46Qh7NHiR86wZpd+TLaesO106s7V3RG33r63VB94LW5qPKEDJX64osh3xfjnPFn1M0484bC7wQ==} + '@oxlint/binding-openharmony-arm64@1.92.0': + resolution: {integrity: sha512-iLtjNqqa/2IV5qu/3rrkpVd42Ia3yeCn4fSZoEr+m5FoGHtZvAV6J6YuU3lewg5Rg5ORGvwhdgN+7gNzwkl7tA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] - '@oxlint/binding-win32-arm64-msvc@1.91.0': - resolution: {integrity: sha512-KQItBdsyHN28U3z/bEek6h9pvG3Uqv564QYO8K1bE/V7YRZgpHlRnfNKVPHkk4sfYKyPzEjCgW80QkImOLvJog==} + '@oxlint/binding-win32-arm64-msvc@1.92.0': + resolution: {integrity: sha512-ryxiR3ZqB0OJzydMu+bVC3R7ZtoU7X1rI8sEgTBCCvQvgVwoCwqSFlfmhgiZ+9wZ4IdTsFeu9tdiF9KtRCbSHQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] - '@oxlint/binding-win32-ia32-msvc@1.91.0': - resolution: {integrity: sha512-XFKqbbsQVmTgw+CyBKuzSZtAa45viom1naFfulKmkTFdDyDaBQaBqEz5J61TI8iwBynU+F8q7qPD+9mplZRhEg==} + '@oxlint/binding-win32-ia32-msvc@1.92.0': + resolution: {integrity: sha512-DaE9OChj4nsdEST32BP7saGu8WtjOinTy/eS88dZ0TvTfDV26ebRDhsI1rL9OKXfO+DgehzhAQMqdPr2jgfcFw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ia32] os: [win32] - '@oxlint/binding-win32-x64-msvc@1.91.0': - resolution: {integrity: sha512-DmpK0PthG66Bcz5Y4JqNbzXltzyLQtg3ofYpd25+ejm7kQYUM78VL1uIP/ZFct2781mwUyBX37LatFPCTVp35A==} + '@oxlint/binding-win32-x64-msvc@1.92.0': + resolution: {integrity: sha512-0AyhqX0ciFuEnHIL+B4PIMMX3s/IpGHNEbbUqwsNhSrzWUSlEOPw/q7qFnRsEJfiKedcqVfUE/aXYuSMtpiFyw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] @@ -587,8 +587,8 @@ packages: engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true - oxfmt@0.76.0: - resolution: {integrity: sha512-Yo9RIn9lRWTm/U8obHbXUWc39lCpEFXlEggFoPx01zS18OCFi7mAwMmL05+p1AunuJgSkONffWyBHJzpMMCRuQ==} + oxfmt@0.77.0: + resolution: {integrity: sha512-3bPDJwLZf4i6dOaQS+6GOI/YUFTHNif7qw4nknbZyzdB0uws57tD8jA/GLGC9J7kjyf6d/eVWm73b43VeMUqGw==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true peerDependencies: @@ -603,8 +603,8 @@ packages: vite-plus: optional: true - oxlint@1.91.0: - resolution: {integrity: sha512-vjy/cBZcEFcYh3dbxUoQK+bjc+QaY3ZWo86aJkZ5YAwp/HyiqP7dTdNgbvcIVJafhAH5sZbTqBp4sZcicEZngA==} + oxlint@1.92.0: + resolution: {integrity: sha512-y9iRiRwVjVFqzKNXZJ9bT/GYRdf+F9Gy+a1Yju2Aq3xqqa4FJYXHI8VrxlpzxKDvkYRohvJX42m/eH+qkQPOFw==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true peerDependencies: @@ -655,118 +655,118 @@ snapshots: '@csstools/css-tokenizer@4.0.2': {} - '@oxfmt/binding-android-arm-eabi@0.76.0': + '@oxfmt/binding-android-arm-eabi@0.77.0': optional: true - '@oxfmt/binding-android-arm64@0.76.0': + '@oxfmt/binding-android-arm64@0.77.0': optional: true - '@oxfmt/binding-darwin-arm64@0.76.0': + '@oxfmt/binding-darwin-arm64@0.77.0': optional: true - '@oxfmt/binding-darwin-x64@0.76.0': + '@oxfmt/binding-darwin-x64@0.77.0': optional: true - '@oxfmt/binding-freebsd-x64@0.76.0': + '@oxfmt/binding-freebsd-x64@0.77.0': optional: true - '@oxfmt/binding-linux-arm-gnueabihf@0.76.0': + '@oxfmt/binding-linux-arm-gnueabihf@0.77.0': optional: true - '@oxfmt/binding-linux-arm-musleabihf@0.76.0': + '@oxfmt/binding-linux-arm-musleabihf@0.77.0': optional: true - '@oxfmt/binding-linux-arm64-gnu@0.76.0': + '@oxfmt/binding-linux-arm64-gnu@0.77.0': optional: true - '@oxfmt/binding-linux-arm64-musl@0.76.0': + '@oxfmt/binding-linux-arm64-musl@0.77.0': optional: true - '@oxfmt/binding-linux-ppc64-gnu@0.76.0': + '@oxfmt/binding-linux-ppc64-gnu@0.77.0': optional: true - '@oxfmt/binding-linux-riscv64-gnu@0.76.0': + '@oxfmt/binding-linux-riscv64-gnu@0.77.0': optional: true - '@oxfmt/binding-linux-riscv64-musl@0.76.0': + '@oxfmt/binding-linux-riscv64-musl@0.77.0': optional: true - '@oxfmt/binding-linux-s390x-gnu@0.76.0': + '@oxfmt/binding-linux-s390x-gnu@0.77.0': optional: true - '@oxfmt/binding-linux-x64-gnu@0.76.0': + '@oxfmt/binding-linux-x64-gnu@0.77.0': optional: true - '@oxfmt/binding-linux-x64-musl@0.76.0': + '@oxfmt/binding-linux-x64-musl@0.77.0': optional: true - '@oxfmt/binding-openharmony-arm64@0.76.0': + '@oxfmt/binding-openharmony-arm64@0.77.0': optional: true - '@oxfmt/binding-win32-arm64-msvc@0.76.0': + '@oxfmt/binding-win32-arm64-msvc@0.77.0': optional: true - '@oxfmt/binding-win32-ia32-msvc@0.76.0': + '@oxfmt/binding-win32-ia32-msvc@0.77.0': optional: true - '@oxfmt/binding-win32-x64-msvc@0.76.0': + '@oxfmt/binding-win32-x64-msvc@0.77.0': optional: true - '@oxlint/binding-android-arm-eabi@1.91.0': + '@oxlint/binding-android-arm-eabi@1.92.0': optional: true - '@oxlint/binding-android-arm64@1.91.0': + '@oxlint/binding-android-arm64@1.92.0': optional: true - '@oxlint/binding-darwin-arm64@1.91.0': + '@oxlint/binding-darwin-arm64@1.92.0': optional: true - '@oxlint/binding-darwin-x64@1.91.0': + '@oxlint/binding-darwin-x64@1.92.0': optional: true - '@oxlint/binding-freebsd-x64@1.91.0': + '@oxlint/binding-freebsd-x64@1.92.0': optional: true - '@oxlint/binding-linux-arm-gnueabihf@1.91.0': + '@oxlint/binding-linux-arm-gnueabihf@1.92.0': optional: true - '@oxlint/binding-linux-arm-musleabihf@1.91.0': + '@oxlint/binding-linux-arm-musleabihf@1.92.0': optional: true - '@oxlint/binding-linux-arm64-gnu@1.91.0': + '@oxlint/binding-linux-arm64-gnu@1.92.0': optional: true - '@oxlint/binding-linux-arm64-musl@1.91.0': + '@oxlint/binding-linux-arm64-musl@1.92.0': optional: true - '@oxlint/binding-linux-ppc64-gnu@1.91.0': + '@oxlint/binding-linux-ppc64-gnu@1.92.0': optional: true - '@oxlint/binding-linux-riscv64-gnu@1.91.0': + '@oxlint/binding-linux-riscv64-gnu@1.92.0': optional: true - '@oxlint/binding-linux-riscv64-musl@1.91.0': + '@oxlint/binding-linux-riscv64-musl@1.92.0': optional: true - '@oxlint/binding-linux-s390x-gnu@1.91.0': + '@oxlint/binding-linux-s390x-gnu@1.92.0': optional: true - '@oxlint/binding-linux-x64-gnu@1.91.0': + '@oxlint/binding-linux-x64-gnu@1.92.0': optional: true - '@oxlint/binding-linux-x64-musl@1.91.0': + '@oxlint/binding-linux-x64-musl@1.92.0': optional: true - '@oxlint/binding-openharmony-arm64@1.91.0': + '@oxlint/binding-openharmony-arm64@1.92.0': optional: true - '@oxlint/binding-win32-arm64-msvc@1.91.0': + '@oxlint/binding-win32-arm64-msvc@1.92.0': optional: true - '@oxlint/binding-win32-ia32-msvc@1.91.0': + '@oxlint/binding-win32-ia32-msvc@1.92.0': optional: true - '@oxlint/binding-win32-x64-msvc@1.91.0': + '@oxlint/binding-win32-x64-msvc@1.92.0': optional: true '@types/node@26.6.6': @@ -839,51 +839,51 @@ snapshots: nanoid@3.3.20: {} - oxfmt@0.76.0: + oxfmt@0.77.0: dependencies: tinypool: 2.2.0 optionalDependencies: - '@oxfmt/binding-android-arm-eabi': 0.76.0 - '@oxfmt/binding-android-arm64': 0.76.0 - '@oxfmt/binding-darwin-arm64': 0.76.0 - '@oxfmt/binding-darwin-x64': 0.76.0 - '@oxfmt/binding-freebsd-x64': 0.76.0 - '@oxfmt/binding-linux-arm-gnueabihf': 0.76.0 - '@oxfmt/binding-linux-arm-musleabihf': 0.76.0 - '@oxfmt/binding-linux-arm64-gnu': 0.76.0 - '@oxfmt/binding-linux-arm64-musl': 0.76.0 - '@oxfmt/binding-linux-ppc64-gnu': 0.76.0 - '@oxfmt/binding-linux-riscv64-gnu': 0.76.0 - '@oxfmt/binding-linux-riscv64-musl': 0.76.0 - '@oxfmt/binding-linux-s390x-gnu': 0.76.0 - '@oxfmt/binding-linux-x64-gnu': 0.76.0 - '@oxfmt/binding-linux-x64-musl': 0.76.0 - '@oxfmt/binding-openharmony-arm64': 0.76.0 - '@oxfmt/binding-win32-arm64-msvc': 0.76.0 - '@oxfmt/binding-win32-ia32-msvc': 0.76.0 - '@oxfmt/binding-win32-x64-msvc': 0.76.0 - - oxlint@1.91.0: + '@oxfmt/binding-android-arm-eabi': 0.77.0 + '@oxfmt/binding-android-arm64': 0.77.0 + '@oxfmt/binding-darwin-arm64': 0.77.0 + '@oxfmt/binding-darwin-x64': 0.77.0 + '@oxfmt/binding-freebsd-x64': 0.77.0 + '@oxfmt/binding-linux-arm-gnueabihf': 0.77.0 + '@oxfmt/binding-linux-arm-musleabihf': 0.77.0 + '@oxfmt/binding-linux-arm64-gnu': 0.77.0 + '@oxfmt/binding-linux-arm64-musl': 0.77.0 + '@oxfmt/binding-linux-ppc64-gnu': 0.77.0 + '@oxfmt/binding-linux-riscv64-gnu': 0.77.0 + '@oxfmt/binding-linux-riscv64-musl': 0.77.0 + '@oxfmt/binding-linux-s390x-gnu': 0.77.0 + '@oxfmt/binding-linux-x64-gnu': 0.77.0 + '@oxfmt/binding-linux-x64-musl': 0.77.0 + '@oxfmt/binding-openharmony-arm64': 0.77.0 + '@oxfmt/binding-win32-arm64-msvc': 0.77.0 + '@oxfmt/binding-win32-ia32-msvc': 0.77.0 + '@oxfmt/binding-win32-x64-msvc': 0.77.0 + + oxlint@1.92.0: optionalDependencies: - '@oxlint/binding-android-arm-eabi': 1.91.0 - '@oxlint/binding-android-arm64': 1.91.0 - '@oxlint/binding-darwin-arm64': 1.91.0 - '@oxlint/binding-darwin-x64': 1.91.0 - '@oxlint/binding-freebsd-x64': 1.91.0 - '@oxlint/binding-linux-arm-gnueabihf': 1.91.0 - '@oxlint/binding-linux-arm-musleabihf': 1.91.0 - '@oxlint/binding-linux-arm64-gnu': 1.91.0 - '@oxlint/binding-linux-arm64-musl': 1.91.0 - '@oxlint/binding-linux-ppc64-gnu': 1.91.0 - '@oxlint/binding-linux-riscv64-gnu': 1.91.0 - '@oxlint/binding-linux-riscv64-musl': 1.91.0 - '@oxlint/binding-linux-s390x-gnu': 1.91.0 - '@oxlint/binding-linux-x64-gnu': 1.91.0 - '@oxlint/binding-linux-x64-musl': 1.91.0 - '@oxlint/binding-openharmony-arm64': 1.91.0 - '@oxlint/binding-win32-arm64-msvc': 1.91.0 - '@oxlint/binding-win32-ia32-msvc': 1.91.0 - '@oxlint/binding-win32-x64-msvc': 1.91.0 + '@oxlint/binding-android-arm-eabi': 1.92.0 + '@oxlint/binding-android-arm64': 1.92.0 + '@oxlint/binding-darwin-arm64': 1.92.0 + '@oxlint/binding-darwin-x64': 1.92.0 + '@oxlint/binding-freebsd-x64': 1.92.0 + '@oxlint/binding-linux-arm-gnueabihf': 1.92.0 + '@oxlint/binding-linux-arm-musleabihf': 1.92.0 + '@oxlint/binding-linux-arm64-gnu': 1.92.0 + '@oxlint/binding-linux-arm64-musl': 1.92.0 + '@oxlint/binding-linux-ppc64-gnu': 1.92.0 + '@oxlint/binding-linux-riscv64-gnu': 1.92.0 + '@oxlint/binding-linux-riscv64-musl': 1.92.0 + '@oxlint/binding-linux-s390x-gnu': 1.92.0 + '@oxlint/binding-linux-x64-gnu': 1.92.0 + '@oxlint/binding-linux-x64-musl': 1.92.0 + '@oxlint/binding-openharmony-arm64': 1.92.0 + '@oxlint/binding-win32-arm64-msvc': 1.92.0 + '@oxlint/binding-win32-ia32-msvc': 1.92.0 + '@oxlint/binding-win32-x64-msvc': 1.92.0 picocolors@1.1.1: {} diff --git a/scripts/benchmark/parser-benchmark-worker.js b/scripts/benchmark/parser-benchmark-worker.js index bb47b8a..a0529b0 100644 --- a/scripts/benchmark/parser-benchmark-worker.js +++ b/scripts/benchmark/parser-benchmark-worker.js @@ -11,7 +11,7 @@ const payload = JSON.parse( ); const sourceRoot = payload.sourceRoot; if (typeof sourceRoot !== 'string') - throw new Error('missing parser source root'); + throw new TypeError('missing parser source root'); const parser = await import(pathToFileURL(`${sourceRoot}/lib/parser.js`).href); const { matchBlocks } = await import( @@ -19,7 +19,7 @@ const { matchBlocks } = await import( ); const buildCloser = (tokens) => matchBlocks(tokens).close; if (typeof parser.parse !== 'function' || typeof matchBlocks !== 'function') - throw new Error('incompatible baseline parser API'); + throw new TypeError('incompatible baseline parser API'); const TARGET_MS = payload.targetBatchMs ?? 25; const MIN_WARMUPS = payload.warmupMinimum ?? 5; From c012beb9ce5386585b12a6c2d3cb6eeb6d040486 Mon Sep 17 00:00:00 2001 From: Ludovico Fischer Date: Sat, 7 Nov 2026 14:07:55 +0100 Subject: [PATCH 3/3] refactor: port latest changes from refactor-token-core --- CHANGELOG.md | 3 + scripts/benchmark/benchmark-serialization.js | 17 +- scripts/benchmark/parser-benchmark-worker.js | 7 +- src/lib/blocks.js | 64 +++- src/lib/core.js | 171 ++++++--- src/lib/functions.js | 7 +- src/lib/limits.js | 3 +- src/lib/node.js | 36 +- src/lib/offsets.js | 22 +- src/lib/opaque.js | 17 +- src/lib/parser.js | 29 +- src/lib/parser/opaque.js | 61 +++- src/lib/parser/state.js | 13 +- src/lib/serialize.js | 63 ++-- src/lib/serialize/expression.js | 115 +++--- src/lib/serialize/precision.js | 78 ++-- src/lib/serialize/sink.js | 366 +++++++++++++++++++ src/lib/serialize/text-sink.js | 197 ++++++++++ src/lib/simplify.js | 3 +- src/lib/simplify/sum.js | 4 +- src/reduce.js | 6 +- test/helpers/sexpr.js | 9 +- test/integration/math-operations.test.js | 36 ++ test/property/immutability.test.js | 79 ++++ test/property/opaque-grouping.test.js | 26 ++ test/unit/node.test.js | 20 +- test/unit/parser-opaque.test.js | 15 +- test/unit/serialize-core.test.js | 9 + test/unit/serialize-result.test.js | 70 ++-- types/lib/blocks.d.ts | 42 ++- types/lib/core.d.ts | 26 +- types/lib/functions.d.ts | 4 +- types/lib/node.d.ts | 13 +- types/lib/offsets.d.ts | 12 +- types/lib/opaque.d.ts | 9 +- types/lib/parser.d.ts | 13 +- types/lib/parser/state.d.ts | 8 +- types/lib/serialize.d.ts | 26 +- types/lib/serialize/expression.d.ts | 17 +- types/lib/serialize/precision.d.ts | 30 +- types/lib/serialize/sink.d.ts | 152 ++++++++ types/lib/serialize/text-sink.d.ts | 100 +++++ 42 files changed, 1644 insertions(+), 354 deletions(-) create mode 100644 src/lib/serialize/sink.js create mode 100644 src/lib/serialize/text-sink.js create mode 100644 test/property/immutability.test.js create mode 100644 types/lib/serialize/sink.d.ts create mode 100644 types/lib/serialize/text-sink.d.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ad1d9f..7b3fd60 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ All notable changes to this project will be documented in this file. See [commit ### Bug fixes +- A reduced value that would merge with a neighbouring token is now kept apart + by a space. For example, `foo(calc(1px + 1px)b)` becomes `foo(2px b)` instead + of `foo(2pxb)`, which reads as a different unit. - `reduceCalc` and the plugin no longer report the nesting-limit error for a value nested more than 1024 levels deep that has no supported math function outside `url()`, a string or a comment, such as `url(calc(1+2))((((…`. The diff --git a/scripts/benchmark/benchmark-serialization.js b/scripts/benchmark/benchmark-serialization.js index 0a99464..d1e3781 100644 --- a/scripts/benchmark/benchmark-serialization.js +++ b/scripts/benchmark/benchmark-serialization.js @@ -6,6 +6,7 @@ import assert from 'node:assert/strict'; import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; +import { tokenize } from '@csstools/css-tokenizer'; import { serialize as serializeWorktree } from '../../src/lib/serialize.js'; import { num, @@ -63,10 +64,22 @@ function nestedCalls(size) { /** @param {number} size @return {import('../../src/lib/node.js').Node} */ function nestedOpaqueFallbacks(size) { - let node = opaqueCall('var', [ident('--x'), ', ', dim(1, 'px')]); + // The separator is the range `[0, 2)` of the source tokens `, `. + const source = tokenize({ css: ', ' }); + let node = opaqueCall( + 'var', + [ident('--x'), [0, 2], dim(1, 'px')], + undefined, + source + ); const depth = Math.max(2, Math.ceil(size / 4)); for (let i = 0; i < depth; i++) { - node = opaqueCall('var', [ident(`--x${i}`), ', ', node]); + node = opaqueCall( + 'var', + [ident(`--x${i}`), [0, 2], node], + undefined, + source + ); } return node; } diff --git a/scripts/benchmark/parser-benchmark-worker.js b/scripts/benchmark/parser-benchmark-worker.js index a0529b0..c2aef70 100644 --- a/scripts/benchmark/parser-benchmark-worker.js +++ b/scripts/benchmark/parser-benchmark-worker.js @@ -17,7 +17,12 @@ const parser = await import(pathToFileURL(`${sourceRoot}/lib/parser.js`).href); const { matchBlocks } = await import( pathToFileURL(`${sourceRoot}/lib/blocks.js`).href ); -const buildCloser = (tokens) => matchBlocks(tokens).close; +// The baseline revision returns its closer array as `close`; newer revisions +// return a `Blocks` value as `blocks`. Either is what `parse()` takes. +const buildCloser = (tokens) => { + const matched = matchBlocks(tokens); + return matched.blocks ?? matched.close; +}; if (typeof parser.parse !== 'function' || typeof matchBlocks !== 'function') throw new TypeError('incompatible baseline parser API'); diff --git a/src/lib/blocks.js b/src/lib/blocks.js index 15fc4f2..274c426 100644 --- a/src/lib/blocks.js +++ b/src/lib/blocks.js @@ -5,6 +5,17 @@ import { TokenType as CssType } from '@csstools/css-tokenizer'; /** @typedef {import('@csstools/css-tokenizer').CSSToken} CSSToken */ +/** + * The closer of each opener in one matched range. `close[i - base]` is the + * absolute index of the closer for the opener at token index `i`, or -1. + * `base` is the first token index the matching covered, so a range far into a + * long list allocates only its own length. + * + * @typedef {object} Blocks + * @property {Int32Array} close + * @property {number} base + */ + /** * Closing token type for each opening token type. * @@ -25,24 +36,27 @@ function closerOf(type) { } /** - * Match every block opener in the list to its closer. Matching is LIFO: a - * closer that does not match the innermost open block is ignored, so the - * open stack survives the mismatch. Openers with no closer map to -1. + * Match every block opener in `[start, end)` to its closer. Matching is LIFO: + * a closer that does not match the innermost open block is ignored, so the + * open stack survives the mismatch. Openers with no closer before `end` map + * to -1, as if the range were the whole list. * * `maxDepth` is the largest number of blocks open at once. The caller decides * whether that exceeds the nesting limit. * * @param {CSSToken[]} tokens - * @return {{close: Int32Array, maxDepth: number}} `close[i]` is the closer index for opener `i`, or -1. + * @param {number} [start] + * @param {number} [end] + * @return {{blocks: Blocks, maxDepth: number}} */ -function matchBlocks(tokens) { - const close = new Int32Array(tokens.length).fill(-1); +function matchBlocks(tokens, start = 0, end = tokens.length) { + const close = new Int32Array(Math.max(0, end - start)).fill(-1); /** @type {number[]} */ const openers = []; /** @type {CssType[]} */ const expected = []; let maxDepth = 0; - for (let i = 0; i < tokens.length; i++) { + for (let i = start; i < end; i++) { const type = tokens[i][0]; const closer = closerOf(type); if (closer !== undefined) { @@ -52,23 +66,35 @@ function matchBlocks(tokens) { continue; } if (expected.at(-1) !== type) continue; - close[/** @type {number} */ (openers.pop())] = i; + close[/** @type {number} */ (openers.pop()) - start] = i; expected.pop(); } - return { close, maxDepth }; + return { blocks: { close, base: start }, maxDepth }; +} + +/** + * The closer of the opener at `index`, or -1 when it has no closer or the + * matching does not cover `index`. The result is an absolute token index. + * + * @param {Blocks} blocks + * @param {number} index + * @return {number} + */ +function closerAt(blocks, index) { + return blocks.close[index - blocks.base] ?? -1; } /** * The closer of the opener at `index`, or -1 when it has none inside * `[index, end)`. * - * @param {Int32Array} close + * @param {Blocks} blocks * @param {number} index * @param {number} end * @return {number} */ -function closeIn(close, index, end) { - const closer = close[index]; +function closeIn(blocks, index, end) { + const closer = closerAt(blocks, index); return closer !== -1 && closer < end ? closer : -1; } @@ -76,13 +102,13 @@ function closeIn(close, index, end) { * Index after the component (a token, or a whole block) that starts at `index`, * never past `end`. * - * @param {Int32Array} close + * @param {Blocks} blocks * @param {number} index * @param {number} end * @return {number} */ -function nextComponent(close, index, end) { - const closer = closeIn(close, index, end); +function nextComponent(blocks, index, end) { + const closer = closeIn(blocks, index, end); return closer === -1 ? index + 1 : closer + 1; } @@ -90,16 +116,16 @@ function nextComponent(close, index, end) { * First comma outside every block in `[start, end)`, or -1. * * @param {CSSToken[]} tokens - * @param {Int32Array} close + * @param {Blocks} blocks * @param {number} start * @param {number} end * @return {number} */ -function firstTopLevelComma(tokens, close, start, end) { - for (let i = start; i < end; i = nextComponent(close, i, end)) { +function firstTopLevelComma(tokens, blocks, start, end) { + for (let i = start; i < end; i = nextComponent(blocks, i, end)) { if (tokens[i][0] === CssType.Comma) return i; } return -1; } -export { closeIn, firstTopLevelComma, matchBlocks, nextComponent }; +export { closerAt, closeIn, firstTopLevelComma, matchBlocks, nextComponent }; diff --git a/src/lib/core.js b/src/lib/core.js index 1bcda4e..d36e835 100644 --- a/src/lib/core.js +++ b/src/lib/core.js @@ -1,28 +1,37 @@ // The reducer core: scan a token list for supported math functions, compile -// each one, and report every changed range. The string reducer owns -// tokenizing and splicing; this module owns nothing else. +// each one, and report every changed range. The string and token wrappers +// own tokenizing and splicing; this module owns nothing else. import { parseRange } from './parser.js'; import { ParseError, positionedError } from './parser/state.js'; import { simplify } from './simplify.js'; import { analyze } from './analyze.js'; -import { serializeResult } from './serialize.js'; -import { matchBlocks } from './blocks.js'; +import { printResult, serializeResult } from './serialize.js'; +import { TokenSink } from './serialize/sink.js'; +import { + FUSE_SEPARATOR, + firstCharOf, + lastCharBefore, + wouldFuse, +} from './serialize/text-sink.js'; +import { closerAt, matchBlocks } from './blocks.js'; import { assertDepth } from './limits.js'; import { hasMathFunctionToken, mathFunctionAt } from './functions.js'; import { joinTokens, offsetLookup } from './offsets.js'; /** @typedef {import('../reduce.js').ResolvedReduceCalcOptions} ResolvedReduceCalcOptions */ /** @typedef {import('@csstools/css-tokenizer').CSSToken} CSSToken */ +/** @typedef {import('./blocks.js').Blocks} Blocks */ /** @typedef {import('./functions.js').MathFunction} MathFunction */ /** * Receives one replaced range. `start` and `end` are token indices, `end` - * exclusive. + * exclusive. `printed` is the replacement text, or the token sink holding the + * replacement tokens when the caller asked for tokens. * * @callback EmitReplacement * @param {number} start * @param {number} end - * @param {string} text + * @param {string | TokenSink} printed * @return {void} */ @@ -40,29 +49,37 @@ function asError(error) { * A throw from serialization is reported and yields no replacement text. * * @param {CSSToken[]} tokens - * @param {Int32Array} close + * @param {Blocks} blocks * @param {number} start Index of the function token. - * @param {number} end Index after its closer, or `tokens.length` when unclosed. + * @param {number} end Index after its closer, or the end of the range when unclosed. * @param {{normalizedName: string, definition: MathFunction}} lookup * @param {ResolvedReduceCalcOptions} options - * @return {{text: string | undefined, unresolved: boolean}} + * @param {boolean} printTokens Print into a token sink instead of a string. + * @return {{text: string | TokenSink | undefined, unresolved: boolean}} */ -function compileCandidate(tokens, close, start, end, lookup, options) { +function compileCandidate( + tokens, + blocks, + start, + end, + lookup, + options, + printTokens +) { const name = /** @type {{value: string}} */ (tokens[start][4]).value; const isCalc = lookup.definition.calculation === true; - if (close[start] === -1) throw new ParseError(`Unclosed ${name}(`, start); + const closer = closerAt(blocks, start); + if (closer === -1) throw new ParseError(`Unclosed ${name}(`, start); // Unpositioned parse errors: the caller positions them with a shared lookup. const parsed = isCalc - ? parseRange(tokens, close, start + 1, close[start]) - : parseRange(tokens, close, start, end); + ? parseRange(tokens, blocks, start + 1, closer) + : parseRange(tokens, blocks, start, end); const analysis = analyze(parsed); if (!analysis.valid) { throw new Error('Invalid CSS calculation type'); } const tree = simplify(parsed, options.precision); const unresolved = analysis.unresolved; - const original = - unresolved && !isCalc ? joinTokens(tokens, start, end) : undefined; /** @type {'resolved' | 'unresolved'} */ const status = unresolved ? 'unresolved' : 'resolved'; const result = { @@ -71,17 +88,19 @@ function compileCandidate(tokens, close, start, end, lookup, options) { rootName: lookup.normalizedName, rootSpelling: tokens[start][1].slice(0, -1), calculation: isCalc, - original, + }; + const printOptions = { + precision: options.precision, + unwrapSingleNegativeNumber: options.unwrapSingleNegativeNumber, + unwrapSingleValue: options.unwrapSingleValue, }; try { - return { - text: serializeResult(result, { - precision: options.precision, - unwrapSingleNegativeNumber: options.unwrapSingleNegativeNumber, - unwrapSingleValue: options.unwrapSingleValue, - }), - unresolved, - }; + if (printTokens) { + const sink = new TokenSink(tokens, start, end); + const printed = printResult(result, printOptions, sink); + return { text: printed ? sink : undefined, unresolved }; + } + return { text: serializeResult(result, printOptions), unresolved }; } catch (error) { options.onParseError?.(asError(error), joinTokens(tokens, start, end)); return { text: undefined, unresolved }; @@ -89,57 +108,119 @@ function compileCandidate(tokens, close, start, end, lookup, options) { } /** - * Reduce every supported math function in a token list. Each function is one - * candidate, so a nested function is never reduced on its own, and an invalid - * outer function is reported without partial output. + * The printed replacement for `tokens[from, to)`, with a space on each side + * where it would otherwise merge into the token beside it, as in + * `calc(1px + 1px)b` becoming `2pxb`. * + * The neighbours are the tokens just outside the range, skipping EOF tokens, + * because the replacement is spliced in between them. + * + * @template {string | TokenSink} T + * @param {T} printed + * @param {CSSToken[]} tokens + * @param {number} from + * @param {number} to + * @return {T | string} + */ +function fitted(printed, tokens, from, to) { + const before = lastCharBefore(tokens, from); + const after = firstCharOf(tokens, to, tokens.length); + if (typeof printed !== 'string') { + printed.fit(before, after); + return printed; + } + return ( + (wouldFuse(before, printed[0]) ? FUSE_SEPARATOR : '') + + printed + + (wouldFuse(printed.at(-1), after) ? FUSE_SEPARATOR : '') + ); +} +/** + * Reduce every supported math function in `tokens[start, end)`. Each function + * is one candidate, so a nested function is never reduced on its own, and an + * invalid outer function is reported without partial output. Blocks and + * error offsets read the range as the list it names would: a block open at + * `end` is unclosed, and error offsets count from `start`. The one exception + * is the token on each side of a replacement, which may lie outside the range: + * a replacement gets a space when it would fuse with it. + * + * Reads each token's type, raw text and parsed value (`token[4]`), never its + * source offsets (`token[2]`, `token[3]`), so the list may have been edited + * since it was tokenized. Emitted indices are indices into `tokens`. + * * @param {CSSToken[]} tokens * @param {ResolvedReduceCalcOptions} options * @param {EmitReplacement} emit - * @param {string} source The joined token text. + * @param {number} start + * @param {number} end + * @param {string} [source] The joined text of the range, when the caller already has it. + * @param {boolean} [printTokens] Emit token sinks instead of text. * @return {void} */ -function reduceTokenList(tokens, options, emit, source) { - if (!hasMathFunctionToken(tokens)) return; +function reduceTokenList( + tokens, + options, + emit, + start, + end, + source, + printTokens = false +) { + if (!hasMathFunctionToken(tokens, start, end)) return; - /** @type {ReturnType} */ + /** @type {Blocks} */ let blocks; try { - blocks = matchBlocks(tokens); - assertDepth(blocks.maxDepth); + const matched = matchBlocks(tokens, start, end); + assertDepth(matched.maxDepth); + blocks = matched.blocks; } catch (error) { - options.onParseError?.(asError(error), source); + options.onParseError?.( + asError(error), + source ?? joinTokens(tokens, start, end) + ); return; } - const { close } = blocks; - - const offsetOf = offsetLookup(tokens); - for (let i = 0; i < tokens.length; i++) { + const offsetOf = offsetLookup(tokens, start, end); + let wholeText = source; + for (let i = start; i < end; i++) { const lookup = mathFunctionAt(tokens, i); if (lookup === undefined) continue; - const end = close[i] === -1 ? tokens.length : close[i] + 1; + const closer = closerAt(blocks, i); + const candidateEnd = closer === -1 ? end : closer + 1; /** @type {ReturnType | undefined} */ let result; try { - result = compileCandidate(tokens, close, i, end, lookup, options); + result = compileCandidate( + tokens, + blocks, + i, + candidateEnd, + lookup, + options, + printTokens + ); } catch (error) { options.onParseError?.( positionedError(asError(error), offsetOf), - joinTokens(tokens, i, end) + joinTokens(tokens, i, candidateEnd) ); } if (result !== undefined) { if (options.warnWhenCannotResolve && result.unresolved) { - options.onWarn?.('Could not reduce expression: ' + source); + wholeText ??= joinTokens(tokens, start, end); + options.onWarn?.('Could not reduce expression: ' + wholeText); + } + if (result.text !== undefined) { + emit(i, candidateEnd, fitted(result.text, tokens, i, candidateEnd)); } - if (result.text !== undefined) emit(i, end, result.text); } // A supported function is one candidate, so its nested calls are skipped. // An unclosed one runs to the end of the list. - if (close[i] === -1) break; - i = close[i]; + if (closer === -1) break; + i = closer; } } diff --git a/src/lib/functions.js b/src/lib/functions.js index 12b58e3..c084c01 100644 --- a/src/lib/functions.js +++ b/src/lib/functions.js @@ -228,10 +228,13 @@ function hasPotentialMathFunction(value) { * functions inside `url()` and similar are part of another token. * * @param {import('@csstools/css-tokenizer').CSSToken[]} tokens + * @param {number} [start] First token to inspect. + * @param {number} [end] One past the last token to inspect (half-open). * @return {boolean} */ -function hasMathFunctionToken(tokens) { - for (const token of tokens) { +function hasMathFunctionToken(tokens, start = 0, end = tokens.length) { + for (let i = start; i < end; i++) { + const token = tokens[i]; if (token[0] === CssType.Function && lookupMathFunction(token[4].value)) { return true; } diff --git a/src/lib/limits.js b/src/lib/limits.js index 8c5b32c..0660246 100644 --- a/src/lib/limits.js +++ b/src/lib/limits.js @@ -34,7 +34,8 @@ function checkCalculationDepth(node, depth = 0) { // components were nested arrays. for (const part of node.components) { assertDepth(depth + 1); - if (typeof part !== 'string') checkCalculationDepth(part, depth + 2); + if (typeof part === 'object' && !Array.isArray(part)) + checkCalculationDepth(part, depth + 2); } } } diff --git a/src/lib/node.js b/src/lib/node.js index b046664..0cb4e14 100644 --- a/src/lib/node.js +++ b/src/lib/node.js @@ -21,14 +21,32 @@ // evaluation has finished, because it is an IEEE-754 value with observable // math-function behavior. // Zero-valued Dims are kept — the unit carries type info. +// +// Ownership rule (no runtime checks; test/property/immutability.test.js +// enforces it on frozen trees): +// +// - Nodes are immutable once construction finishes. No stage assigns to +// node fields, and no code writes to a range array after creating it. +// - Constructors may keep their arguments (children, factor and term +// objects) without copying, so subtrees can be shared between an input +// tree and the simplified output. +// - Code must not read or reuse a tree on the assumption that it owns it +// exclusively. In Rust, a constructor takes its children by value, and the +// simplifier consumes its input tree and returns a new one. +// - `OpaqueCall` range components are `[start, end)` indices into the +// `source` token list. They are token indices, not byte offsets, because +// the token list may be edited after tokenization (see the +// `reduceTokenList` doc comment in `src/lib/core.js`). /** + * @typedef {import('@csstools/css-tokenizer').CSSToken} CSSToken * @typedef {{type: 'Num', value: number}} Num * @typedef {{type: 'Dim', value: number, unit: string, rawUnit?: string}} Dim * @typedef {{type: 'Ident', name: string, rawName?: string}} Ident * @typedef {{type: 'Call', name: string, args: Node[], rawName?: string}} Call - * @typedef {string | Node} OpaqueComponent - * @typedef {{type: 'OpaqueCall', name: string, components: OpaqueComponent[], rawName?: string}} OpaqueCall + * @typedef {[number, number] | Node} OpaqueComponent A `[start, end)` range + * reads the call's `source` tokens. + * @typedef {{type: 'OpaqueCall', name: string, components: OpaqueComponent[], rawName?: string, source?: CSSToken[]}} OpaqueCall * @typedef {{sign: 1 | -1, node: Node}} SumTerm Sign is always +1 when node is Num or Dim. * @typedef {{type: 'Sum', terms: SumTerm[], grouped?: boolean}} Sum * @typedef {{exponent: 1 | -1, node: Node}} ProductFactor exponent +1 = numerator, -1 = denominator. @@ -83,12 +101,18 @@ function call(name, args, rawName) { * @param {string} name * @param {OpaqueComponent[]} components * @param {string} [rawName] + * @param {CSSToken[]} [source] The token list that the range components index. * @return {OpaqueCall} */ -function opaqueCall(name, components, rawName) { - return rawName === undefined - ? { type: 'OpaqueCall', name, components } - : { type: 'OpaqueCall', name, components, rawName }; +function opaqueCall(name, components, rawName, source) { + if (source === undefined && components.some(Array.isArray)) { + throw new TypeError('An OpaqueCall with range components needs a source'); + } + /** @type {OpaqueCall} */ + const node = { type: 'OpaqueCall', name, components }; + if (rawName !== undefined) node.rawName = rawName; + if (source !== undefined) node.source = source; + return node; } /** diff --git a/src/lib/offsets.js b/src/lib/offsets.js index 1638a92..315f961 100644 --- a/src/lib/offsets.js +++ b/src/lib/offsets.js @@ -1,28 +1,30 @@ /** @typedef {import('@csstools/css-tokenizer').CSSToken} CSSToken */ /** - * Maps a token index to the offset in the joined raw text of `tokens` where - * that token starts, or the total length past the end. Only diagnostics need - * offsets, and a fallback can report many of them, so the table is built on - * the first call and each lookup after that is constant time. + * Maps a token index in `[start, end)` to the offset in the joined raw text of + * that range where the token starts, or the range's total length past its end. + * Only diagnostics need offsets, and a fallback can report many of them, so the + * table is built on the first call and each lookup after that is constant time. * * @param {CSSToken[]} tokens + * @param {number} [start] + * @param {number} [end] * @return {(index: number) => number} */ -function offsetLookup(tokens) { +function offsetLookup(tokens, start = 0, end = tokens.length) { /** @type {Int32Array | undefined} */ let starts; return (index) => { if (starts === undefined) { - starts = new Int32Array(tokens.length + 1); + starts = new Int32Array(end - start + 1); let offset = 0; - for (let i = 0; i < tokens.length; i++) { - starts[i] = offset; + for (let i = start; i < end; i++) { + starts[i - start] = offset; offset += tokens[i][1].length; } - starts[tokens.length] = offset; + starts[end - start] = offset; } - return starts[Math.min(index, tokens.length)]; + return starts[Math.min(index, end) - start]; }; } diff --git a/src/lib/opaque.js b/src/lib/opaque.js index 4a2cdb8..afbafc2 100644 --- a/src/lib/opaque.js +++ b/src/lib/opaque.js @@ -8,21 +8,8 @@ */ function simplifyComponents(components, simplify) { return components.map((part) => - typeof part === 'string' ? part : simplify(part) + Array.isArray(part) ? part : simplify(part) ); } -/** - * @param {OpaqueComponent[]} components - * @param {string[]} buffer - * @param {(node: Node, buffer: string[]) => void} serialize - * @return {void} - */ -function serializeComponents(components, buffer, serialize) { - for (const part of components) { - if (typeof part === 'string') buffer.push(part); - else serialize(part, buffer); - } -} - -export { simplifyComponents, serializeComponents }; +export { simplifyComponents }; diff --git a/src/lib/parser.js b/src/lib/parser.js index 07c7ad4..22a6114 100644 --- a/src/lib/parser.js +++ b/src/lib/parser.js @@ -38,11 +38,12 @@ import { /** @typedef {import('./node.js').Node} Node */ /** @typedef {import('./node.js').SumTerm} SumTerm */ /** @typedef {import('./node.js').ProductFactor} ProductFactor */ +/** @typedef {import('./blocks.js').Blocks} Blocks */ /** * @callback ParseRange * @param {CSSToken[]} tokens - * @param {Int32Array} close + * @param {Blocks} blocks * @param {number} start * @param {number} end * @return {Node} @@ -214,7 +215,7 @@ function dimension(token) { * @return {Node} */ function parseGroup(state, open, depth) { - const closer = closeIn(state.close, open, state.end); + const closer = closeIn(state.blocks, open, state.end); const sub = subRange(state, open, closer); const expression = parseSum(sub, depth + 1); expectCloser(sub, closer); @@ -230,7 +231,7 @@ function parseGroup(state, open, depth) { */ function subRange(state, open, closer) { const end = closer === -1 ? state.end : closer + 1; - return newState(state.tokens, state.close, open + 1, end); + return newState(state.tokens, state.blocks, open + 1, end); } /** @@ -271,7 +272,7 @@ function parseCall(state, index, depth) { return parseVar(state, index, name, rawName, parseRange); if (lookupMathFunction(name) === undefined) return parseOpaqueCall(state, index, name, rawName, parseRange); - const closer = closeIn(state.close, index, state.end); + const closer = closeIn(state.blocks, index, state.end); const sub = subRange(state, index, closer); /** @type {Node[]} */ const args = []; @@ -295,13 +296,13 @@ function parseCall(state, index, depth) { * Parse `[start, end)` as one complete expression. * * @param {CSSToken[]} tokens - * @param {Int32Array} close + * @param {Blocks} blocks * @param {number} start * @param {number} end * @return {Node} */ -function parseRange(tokens, close, start, end) { - const state = newState(tokens, close, start, end); +function parseRange(tokens, blocks, start, end) { + const state = newState(tokens, blocks, start, end); const ast = parseSum(state, 0); const trailing = peek(state); if (trailing < end) { @@ -315,28 +316,28 @@ function parseRange(tokens, close, start, end) { * `parse()` uses it when its caller supplies no closer array. * * @param {CSSToken[]} tokens - * @return {Int32Array} + * @return {Blocks} */ function closersWithinLimit(tokens) { - const { close, maxDepth } = matchBlocks(tokens); + const { blocks, maxDepth } = matchBlocks(tokens); assertDepth(maxDepth); - return close; + return blocks; } /** * Parse the token range `[start, end)` of `tokens` as one calculation. - * `close` is the closer array from `matchBlocks(tokens)`; when omitted, it is + * `blocks` is the matching from `matchBlocks(tokens)`; when omitted, it is * built and depth-checked from `tokens`. * * @param {CSSToken[]} tokens * @param {number} start * @param {number} end - * @param {Int32Array} [close] + * @param {Blocks} [blocks] * @return {Node} */ -function parse(tokens, start, end, close = closersWithinLimit(tokens)) { +function parse(tokens, start, end, blocks = closersWithinLimit(tokens)) { try { - return parseRange(tokens, close, start, end); + return parseRange(tokens, blocks, start, end); } catch (error) { if (error instanceof ParseError) { throw positionedError(error, offsetLookup(tokens)); diff --git a/src/lib/parser/opaque.js b/src/lib/parser/opaque.js index b554e94..9348efb 100644 --- a/src/lib/parser/opaque.js +++ b/src/lib/parser/opaque.js @@ -3,7 +3,6 @@ import { TokenType as CssType } from '@csstools/css-tokenizer'; import { ident, opaqueCall } from '../node.js'; import { lookupMathFunction } from '../functions.js'; import { closeIn, firstTopLevelComma } from '../blocks.js'; -import { joinTokens } from '../offsets.js'; import { ParseError, isTrivia } from './state.js'; import { sourceSpelling } from './tokens.js'; @@ -13,13 +12,32 @@ import { sourceSpelling } from './tokens.js'; /** @typedef {import('./state.js').ParseState} ParseState */ /** @typedef {import('../parser.js').ParseRange} ParseRange */ -/** @param {OpaqueComponent[]} target @param {OpaqueComponent} part */ +/** + * Append `part`, merging it into the preceding range when the two are + * contiguous. The merged range is a new array: range arrays are never written + * after they are created, because the simplified output shares them. + * + * @param {OpaqueComponent[]} target + * @param {OpaqueComponent} part + */ function pushComponent(target, part) { - if (typeof part === 'string' && typeof target.at(-1) === 'string') - target[target.length - 1] += part; + const last = target.at(-1); + if (Array.isArray(part) && Array.isArray(last) && last[1] === part[0]) + target[target.length - 1] = [last[0], part[1]]; else target.push(part); } +/** + * Append the source tokens `[start, end)` as one range, when there are any. + * + * @param {OpaqueComponent[]} target + * @param {number} start + * @param {number} end + */ +function pushRange(target, start, end) { + if (start < end) pushComponent(target, [start, end]); +} + /** * The closer of the call whose function token is `index`. The state has * already moved past that token, so the position names the token after it. @@ -30,7 +48,7 @@ function pushComponent(target, part) { * @return {number} */ function closeOfCall(state, index, name) { - const close = closeIn(state.close, index, state.end); + const close = closeIn(state.blocks, index, state.end); if (close === -1) throw new ParseError(`Unclosed ${name}(`, state.pos); return close; } @@ -49,7 +67,8 @@ function parseOpaqueCall(state, index, name, rawName, parseRange) { return opaqueCall( name, componentTree(state, index + 1, close, parseRange, []), - sourceSpelling(rawName, name) + sourceSpelling(rawName, name), + state.tokens ); } @@ -79,10 +98,10 @@ function customProperty(tokens, start, end) { /** * Append the components of `[start, rangeEnd)` to `root` and return it. Raw - * token text is merged into the preceding string. A supported math function - * becomes a parsed node, or raw text when it does not parse, and the scan - * resumes after its closer. Other blocks are plain text, so their contents - * are scanned as ordinary tokens. + * tokens become a range of the source list, merged with the preceding range. + * A supported math function becomes a parsed node, or a range when it does + * not parse, and the scan resumes after its closer. Other blocks are plain + * text, so their contents are scanned as ordinary tokens. * * @param {ParseState} state * @param {number} start @@ -92,27 +111,30 @@ function customProperty(tokens, start, end) { * @return {OpaqueComponent[]} */ function componentTree(state, start, rangeEnd, parseRange, root) { - const { tokens, close: closers } = state; + const { tokens, blocks } = state; + let runStart = start; let i = start; while (i < rangeEnd) { const token = tokens[i]; - const close = closeIn(closers, i, rangeEnd); + const close = closeIn(blocks, i, rangeEnd); if ( close !== -1 && token[0] === CssType.Function && lookupMathFunction(token[4].value) !== undefined ) { + pushRange(root, runStart, i); try { - pushComponent(root, parseRange(tokens, closers, i, close + 1)); + pushComponent(root, parseRange(tokens, blocks, i, close + 1)); } catch { - pushComponent(root, joinTokens(tokens, i, close + 1)); + pushRange(root, i, close + 1); } i = close + 1; + runStart = i; continue; } - pushComponent(root, token[1]); i++; } + pushRange(root, runStart, rangeEnd); return root; } @@ -128,7 +150,7 @@ function parseVar(state, index, name, rawName, parseRange) { const { tokens } = state; const start = index + 1; const close = closeOfCall(state, index, name); - const comma = firstTopLevelComma(tokens, state.close, start, close); + const comma = firstTopLevelComma(tokens, state.blocks, start, close); const property = customProperty(tokens, start, comma === -1 ? close : comma); if (!property) throw new ParseError(`Invalid custom property in ${name}()`, start); @@ -139,7 +161,12 @@ function parseVar(state, index, name, rawName, parseRange) { ]; if (comma !== -1) componentTree(state, property.index + 1, close, parseRange, components); - return opaqueCall(name, components, sourceSpelling(rawName, name)); + return opaqueCall( + name, + components, + sourceSpelling(rawName, name), + state.tokens + ); } export { parseOpaqueCall, parseVar }; diff --git a/src/lib/parser/state.js b/src/lib/parser/state.js index 5ddd6f2..4f31abd 100644 --- a/src/lib/parser/state.js +++ b/src/lib/parser/state.js @@ -4,6 +4,7 @@ import { TokenType as CssType } from '@csstools/css-tokenizer'; /** @typedef {import('@csstools/css-tokenizer').CSSToken} CSSToken */ +/** @typedef {import('../blocks.js').Blocks} Blocks */ /** * A syntax error at a token. The position is not formatted here: a fallback @@ -49,12 +50,12 @@ function isTrivia(type) { } /** - * One parse range. `pos` is the next token to read. `close` is the closer - * array for the whole list, shared by every range. + * One parse range. `pos` is the next token to read. `blocks` is the closer + * matching for the whole list, shared by every range. * * @typedef {object} ParseState * @property {CSSToken[]} tokens - * @property {Int32Array} close + * @property {Blocks} blocks * @property {number} start First token of the range, for the leading-whitespace rule. * @property {number} end Exclusive bound. * @property {number} pos @@ -107,15 +108,15 @@ function peek(state) { /** * @param {CSSToken[]} tokens - * @param {Int32Array} close + * @param {Blocks} blocks * @param {number} start * @param {number} end * @return {ParseState} */ -function newState(tokens, close, start, end) { +function newState(tokens, blocks, start, end) { return { tokens, - close, + blocks, start, end, pos: start, diff --git a/src/lib/serialize.js b/src/lib/serialize.js index 61fa332..5be2781 100644 --- a/src/lib/serialize.js +++ b/src/lib/serialize.js @@ -5,12 +5,12 @@ import { checkCalculationDepth } from './limits.js'; import { isCalculationFunction } from './functions.js'; import { isScalar } from './serialize/precision.js'; +import { TextSink } from './serialize/sink.js'; import { emitCall, - emitLeadingNeg, emitOpaqueCall, emitMathResult, - emitNode, + emitWrappedRoot, } from './serialize/expression.js'; /** @@ -34,25 +34,17 @@ function normalizeScalarPolicy(opts) { /** * @param {SerializeOptions} opts + * @param {import('./serialize/sink.js').Sink} out * @return {import('./serialize/precision.js').SerializeSession} */ -function makeSession(opts) { +function makeSession(opts, out) { return { - buffer: [], + out, precision: opts.precision ?? 5, scalarPolicy: normalizeScalarPolicy(opts), }; } -/** @param {Node} node @param {import('./serialize/precision.js').SerializeSession} session @return {void} */ -function emitRootExpr(node, session) { - if (node.type === 'Sum' && node.terms.length === 1) { - emitLeadingNeg(node.terms[0].node, session); - return; - } - emitNode(node, session); -} - /** * @param {Node} node * @param {SerializeOptions} [opts] @@ -60,21 +52,25 @@ function emitRootExpr(node, session) { */ function serialize(node, opts = {}) { checkCalculationDepth(node); - const session = makeSession(opts); - emitMathResult(node, session, opts.calcName ?? 'calc'); - return session.buffer.join(''); + const out = new TextSink(); + emitMathResult(node, makeSession(opts, out), opts.calcName ?? 'calc'); + return out.join(); } /** - * @param {{tree: Node, status: 'resolved' | 'unresolved', rootName: string, rootSpelling: string, calculation?: boolean, original?: string}} result - * @param {SerializeOptions} [opts] - * @return {string} + * Print a result into `out`. An unresolved root that is not a calculation and + * does not match its own name prints nothing. + * + * @param {{tree: Node, status: 'resolved' | 'unresolved', rootName: string, rootSpelling: string, calculation?: boolean}} result + * @param {SerializeOptions} opts + * @param {import('./serialize/sink.js').Sink} out + * @return {boolean} Whether anything was printed. */ -function serializeResult(result, opts = {}) { +function printResult(result, opts, out) { const node = result.tree; checkCalculationDepth(node); const isCalc = result.calculation ?? isCalculationFunction(result.rootName); - const session = makeSession(opts); + const session = makeSession(opts, out); if (!isCalc && result.status === 'unresolved') { const rootName = @@ -87,9 +83,9 @@ function serializeResult(result, opts = {}) { ) { if (node.type === 'Call') emitCall(node, session, result.rootSpelling); else emitOpaqueCall(node, session, result.rootSpelling); - return session.buffer.join(''); + return true; } - return result.original ?? ''; + return false; } const wrapper = isCalc @@ -97,13 +93,24 @@ function serializeResult(result, opts = {}) { : 'calc'; // Under the standard policy a bare Ident/Call result still needs calc(). if (session.scalarPolicy === 'standard' && !isScalar(node)) { - session.buffer.push(wrapper, '('); - emitRootExpr(node, session); - session.buffer.push(')'); + emitWrappedRoot(node, session, wrapper); } else { emitMathResult(node, session, wrapper); } - return session.buffer.join(''); + return true; +} + +/** + * Returns `undefined` for an unresolved root that is not a calculation and + * does not match its own name: the caller keeps the source text as it is. + * + * @param {Parameters[0]} result + * @param {SerializeOptions} [opts] + * @return {string | undefined} + */ +function serializeResult(result, opts = {}) { + const out = new TextSink(); + return printResult(result, opts, out) ? out.join() : undefined; } -export { serialize, serializeResult }; +export { printResult, serialize, serializeResult }; diff --git a/src/lib/serialize/expression.js b/src/lib/serialize/expression.js index 8c342ba..3fb4b38 100644 --- a/src/lib/serialize/expression.js +++ b/src/lib/serialize/expression.js @@ -4,10 +4,9 @@ // share one module; precision and precedence rules live in sibling modules. import { num } from '../node.js'; -import { serializeComponents } from '../opaque.js'; import { - degenerateKeyword, emitBareSignedZero, + emitDegenerate, emitRoundedScalar, emitScalar, emitSignedZero, @@ -29,6 +28,7 @@ import { * @typedef {import('../node.js').SumTerm} SumTerm * @typedef {import('../node.js').ProductFactor} ProductFactor * @typedef {import('./precision.js').SerializeSession} SerializeSession + * @typedef {import('@csstools/css-tokenizer').CSSToken} CSSToken */ /** @@ -49,9 +49,9 @@ function emitNode( parentPrecedence, groupedRequired ); - if (parenthesized) session.buffer.push('('); + if (parenthesized) session.out.open(); emitNodeBody(node, session); - if (parenthesized) session.buffer.push(')'); + if (parenthesized) session.out.close(); } /** @@ -60,14 +60,13 @@ function emitNode( * @return {void} */ function emitNodeBody(node, session) { - const buffer = session.buffer; switch (node.type) { case 'Num': case 'Dim': emitScalar(node, session); return; case 'Ident': - buffer.push(node.rawName ?? node.name); + session.out.ident(node.rawName ?? node.name); return; case 'Call': emitCall(node, session); @@ -92,32 +91,33 @@ function emitNodeBody(node, session) { * @return {void} */ function emitScalarSumTerm(termNode, sign, leading, session) { - const buffer = session.buffer; + const out = session.out; const effectiveVal = sign * termNode.value; if (Object.is(effectiveVal, -0)) { // `x - 0` reparses as x + -(0), so subtraction round-trips negative zero. // A leading term starts a , so `-1 * 0` needs no calc(). if (leading) { - emitBareSignedZero(buffer, termNode); + emitBareSignedZero(out, termNode); } else { - buffer.push(' - '); - emitRoundedScalar(termNode, buffer, 0); + out.op('-'); + emitRoundedScalar(termNode, out, 0); } return; } if (isDegenerate(effectiveVal)) { - if (!leading) buffer.push(sign === 1 ? ' + ' : ' - '); - else if (sign === -1) buffer.push('-'); + if (!leading) out.op(sign === 1 ? '+' : '-'); + else if (sign === -1) out.minus(); emitScalar(termNode, session); return; } const rounded = round(effectiveVal, session.precision); if (rounded < 0) { - buffer.push(leading ? '-' : ' - '); - emitRoundedScalar(termNode, buffer, -rounded); + if (leading) out.minus(); + else out.op('-'); + emitRoundedScalar(termNode, out, -rounded); } else { - if (!leading) buffer.push(' + '); - emitRoundedScalar(termNode, buffer, rounded); + if (!leading) out.op('+'); + emitRoundedScalar(termNode, out, rounded); } } @@ -134,7 +134,7 @@ function emitSumTerm(term, leading, session) { } else if (leading && term.sign === -1) { emitLeadingNeg(termNode, session); } else { - if (!leading) session.buffer.push(term.sign === 1 ? ' + ' : ' - '); + if (!leading) session.out.op(term.sign === 1 ? '+' : '-'); emitNode(termNode, session, SUM_PRECEDENCE, true); } } @@ -182,7 +182,9 @@ function emitLeadingNeg(node, session) { emitProductFactors(node.factors, session, 0, -1, num(-1)); return; } - session.buffer.push('-1 * '); + session.out.minus(); + session.out.number('1'); + session.out.op('*'); emitNode(node, session, UNARY_PRECEDENCE, false); } @@ -201,7 +203,7 @@ function emitProductFactors( coefficientValue, coefficientNode ) { - const buffer = session.buffer; + const out = session.out; // Only the product's first multiplied scalar may print negative zero as a // bare `-1 * 0`: reparsing folds the `-1` back into that same coefficient. // After any operator, the `-1` would bind to the preceding operand instead. @@ -217,8 +219,11 @@ function emitProductFactors( const factor = factors[i]; const factorNode = factor.node; const multiplied = factor.exponent === 1; - if (!leading) buffer.push(multiplied ? ' * ' : ' / '); - else if (!multiplied) buffer.push('1 / '); + if (!leading) out.op(multiplied ? '*' : '/'); + else if (!multiplied) { + out.number('1'); + out.op('/'); + } if (isScalar(factorNode)) { emitScalar(factorNode, session, undefined, leading && multiplied); } else { @@ -235,16 +240,16 @@ function emitProductFactors( * @return {void} */ function emitCall(node, session, callNameOverride) { - const buffer = session.buffer; - buffer.push(callNameOverride ?? node.rawName ?? node.name, '('); + const out = session.out; + out.fn(callNameOverride ?? node.rawName ?? node.name); for (let i = 0; i < node.args.length; i++) { - if (i > 0) buffer.push(', '); + if (i > 0) out.comma(); const arg = node.args[i]; // Every math-function argument is a , so it needs no calc() - if (isSignedZero(arg)) emitBareSignedZero(buffer, arg); + if (isSignedZero(arg)) emitBareSignedZero(out, arg); else emitNode(arg, session); } - buffer.push(')'); + out.close(); } /** @@ -254,12 +259,15 @@ function emitCall(node, session, callNameOverride) { * @return {void} */ function emitOpaqueCall(node, session, callNameOverride) { - const buffer = session.buffer; - buffer.push(callNameOverride ?? node.rawName ?? node.name, '('); - serializeComponents(node.components, buffer, (child, childBuffer) => { - emitNestedMathResult(child, session, childBuffer); - }); - buffer.push(')'); + const out = session.out; + out.fn(callNameOverride ?? node.rawName ?? node.name); + for (const part of node.components) { + if (Array.isArray(part)) { + // `opaqueCall` guarantees a source for range components. + out.source(/** @type {CSSToken[]} */ (node.source), part[0], part[1]); + } else emitNestedMathResult(part, session); + } + out.close(); } /** @@ -271,17 +279,15 @@ function emitOpaqueCall(node, session, callNameOverride) { function emitMathResult(node, session, wrapper) { if (isScalar(node)) { const scalarValue = round(node.value, session.precision); - const buffer = session.buffer; + const out = session.out; if (isDegenerate(scalarValue)) { - buffer.push(wrapper, '(', degenerateKeyword(scalarValue)); - if (node.type === 'Dim') buffer.push(' * 1', node.rawUnit ?? node.unit); - buffer.push(')'); + emitDegenerate(out, scalarValue, node, wrapper); } else if (session.scalarPolicy === 'standard') { - buffer.push(wrapper, '('); - emitRoundedScalar(node, buffer, scalarValue); - buffer.push(')'); + out.fn(wrapper); + emitRoundedScalar(node, out, scalarValue); + out.close(); } else { - emitRoundedScalar(node, buffer, scalarValue); + emitRoundedScalar(node, out, scalarValue); } return; } @@ -293,26 +299,36 @@ function emitMathResult(node, session, wrapper) { emitNode(node, session); return; } + emitWrappedRoot(node, session, wrapper); +} + +/** + * Emit a non-scalar root inside `wrapper(...)`. A single-term sum emits its + * term as a leading term, so the term's sign stays a leading sign. + * + * @param {Node} node + * @param {SerializeSession} session + * @param {string} wrapper + * @return {void} + */ +function emitWrappedRoot(node, session, wrapper) { + session.out.fn(wrapper); if (node.type === 'Sum' && node.terms.length === 1) { - session.buffer.push(wrapper, '('); emitLeadingNeg(node.terms[0].node, session); - session.buffer.push(')'); - return; + } else { + emitNode(node, session); } - session.buffer.push(wrapper, '('); - emitNode(node, session); - session.buffer.push(')'); + session.out.close(); } /** * @param {Node} node * @param {SerializeSession} session - * @param {string[]} [buffer] * @return {void} */ -function emitNestedMathResult(node, session, buffer = session.buffer) { +function emitNestedMathResult(node, session) { if (isSignedZero(node)) { - emitSignedZero(buffer, node); + emitSignedZero(session.out, node); return; } emitMathResult(node, session, 'calc'); @@ -325,4 +341,5 @@ export { emitOpaqueCall, emitMathResult, emitNestedMathResult, + emitWrappedRoot, }; diff --git a/src/lib/serialize/precision.js b/src/lib/serialize/precision.js index 292860d..5ddc7a5 100644 --- a/src/lib/serialize/precision.js +++ b/src/lib/serialize/precision.js @@ -7,7 +7,7 @@ * @typedef {import('../node.js').Num} Num * @typedef {import('../node.js').Dim} Dim * @typedef {object} SerializeSession - * @property {string[]} buffer + * @property {import('./sink.js').Sink} out * @property {number | false} precision * @property {'standard' | 'unwrap-all'} scalarPolicy */ @@ -131,15 +131,35 @@ function serializeNumber(v) { /** * @param {import('../node.js').Num | import('../node.js').Dim} node - * @param {string[]} buffer + * @param {SerializeSession['out']} out * @param {number} value * @return {void} */ -function emitRoundedScalar(node, buffer, value) { - buffer.push(serializeNumber(value)); +function emitRoundedScalar(node, out, value) { + const text = serializeNumber(value); + if (node.type === 'Dim') out.dimension(text, node.rawUnit ?? node.unit); + else out.number(text); +} + +/** + * A non-finite value as its keyword. A dimension keeps its unit as `* 1` + * so the keyword stays a valid calculation. `wrapper` names the function that + * wraps the keyword, or is omitted to emit the bare keyword. + * + * @param {SerializeSession['out']} out + * @param {number} value + * @param {import('../node.js').Num | import('../node.js').Dim} node + * @param {string} [wrapper] + * @return {void} + */ +function emitDegenerate(out, value, node, wrapper) { + if (wrapper !== undefined) out.fn(wrapper); + out.ident(degenerateKeyword(value)); if (node.type === 'Dim') { - buffer.push(node.rawUnit ?? node.unit); + out.op('*'); + out.dimension('1', node.rawUnit ?? node.unit); } + if (wrapper !== undefined) out.close(); } /** @@ -150,49 +170,48 @@ function emitRoundedScalar(node, buffer, value) { * @return {void} */ function emitScalar(node, session, value, bare = false) { - const buffer = session.buffer; + const out = session.out; const effective = value ?? node.value; if (Object.is(effective, -0)) { - if (bare) emitBareSignedZero(buffer, node); - else emitSignedZero(buffer, node); + if (bare) emitBareSignedZero(out, node); + else emitSignedZero(out, node); } else if (isDegenerate(effective)) { - if (node.type === 'Dim') { - buffer.push( - 'calc(', - degenerateKeyword(effective), - ' * 1', - node.rawUnit ?? node.unit, - ')' - ); - } else { - buffer.push(degenerateKeyword(effective)); - } + // A bare number keyword is valid in a sum or product, so only a dimension is wrapped. + emitDegenerate( + out, + effective, + node, + node.type === 'Dim' ? 'calc' : undefined + ); } else { - emitRoundedScalar(node, buffer, round(effective, session.precision)); + emitRoundedScalar(node, out, round(effective, session.precision)); } } /** - * @param {string[]} buffer + * @param {SerializeSession['out']} out * @param {import('../node.js').Num | import('../node.js').Dim} node * @return {void} */ -function emitSignedZero(buffer, node) { - buffer.push('calc('); - emitBareSignedZero(buffer, node); - buffer.push(')'); +function emitSignedZero(out, node) { + out.fn('calc'); + emitBareSignedZero(out, node); + out.close(); } /** * Negative zero as an unwrapped product, valid only where a `` * may appear without changing how the surrounding expression parses. - * @param {string[]} buffer + * @param {SerializeSession['out']} out * @param {import('../node.js').Num | import('../node.js').Dim} node * @return {void} */ -function emitBareSignedZero(buffer, node) { - const unit = node.type === 'Dim' ? (node.rawUnit ?? node.unit) : ''; - buffer.push('-1 * 0', unit); +function emitBareSignedZero(out, node) { + out.minus(); + out.number('1'); + out.op('*'); + if (node.type === 'Dim') out.dimension('0', node.rawUnit ?? node.unit); + else out.number('0'); } /** @param {Node} node @return {node is import('../node.js').Num | import('../node.js').Dim} */ @@ -213,6 +232,7 @@ export { isDegenerate, degenerateKeyword, serializeNumber, + emitDegenerate, emitRoundedScalar, emitScalar, emitSignedZero, diff --git a/src/lib/serialize/sink.js b/src/lib/serialize/sink.js new file mode 100644 index 0000000..2e69a64 --- /dev/null +++ b/src/lib/serialize/sink.js @@ -0,0 +1,366 @@ +// The printer's output. A text sink collects the printed strings. A token +// sink builds the tokens of the same text directly, so the printer does not +// tokenize its own output, and it reuses the source token whenever the printed +// token has the same type and raw text. +import { TokenType } from '@csstools/css-tokenizer'; + +import { + FUSE_SEPARATOR, + TextSink, + firstCharOf, + isEOF, + wouldFuse, +} from './text-sink.js'; + +/** @typedef {import('@csstools/css-tokenizer').CSSToken} CSSToken */ + +/** + * What the printer writes to. `TextSink` and `TokenSink` both implement it, so + * a method added to one must be added to the other. + * + * @typedef {TextSink | TokenSink} Sink + */ + +/** + * Whether `raw` is `prefix + first + last`, without building that string. + * + * @param {string} raw + * @param {string} prefix + * @param {string} first + * @param {string} last + * @return {boolean} + */ +function sameText(raw, prefix, first, last) { + return ( + raw.length === prefix.length + first.length + last.length && + raw.startsWith(prefix) && + raw.startsWith(first, prefix.length) && + raw.endsWith(last) + ); +} + +/** + * The value of a CSS identifier from its raw text: each escape is replaced by + * the code point it names, so `c\61 lc` reads `calc`. + * + * @param {string} raw + * @return {string} + */ +function decodeIdentifier(raw) { + if (!raw.includes('\\')) return raw; + let value = ''; + let i = 0; + while (i < raw.length) { + const char = raw[i]; + if (char !== '\\') { + value += char; + i++; + continue; + } + // A backslash at the end of the input is a parse error that reads U+FFFD. + if (i + 1 === raw.length) { + value += '\ufffd'; + break; + } + const hex = /^[0-9a-fA-F]{1,6}/.exec(raw.slice(i + 1, i + 7)); + if (hex === null) { + value += raw[i + 1]; + i += 2; + continue; + } + const codePoint = Number.parseInt(hex[0], 16); + const valid = + codePoint !== 0 && + codePoint <= 0x10ffff && + (codePoint < 0xd800 || codePoint > 0xdfff); + value += String.fromCodePoint(valid ? codePoint : 0xfffd); + i += 1 + hex[0].length; + // One whitespace after a hex escape belongs to it; CRLF counts as one. + if (raw.startsWith('\r\n', i)) i += 2; + else if (/[ \t\n\f\r]/.test(raw[i] ?? '')) i++; + } + return value; +} + +/** + * The detail object of a numeric token, as the tokenizer makes it. + * + * @param {TokenType} type + * @param {string} number The signed number text. + * @param {string} unit + * @return {object} + */ +function numericDetail(type, number, unit) { + /** @type {{value: number, signCharacter?: '-', type?: 'integer' | 'number', unit?: string}} */ + // The tokenizer always has the key, `undefined` when the number is unsigned. + const detail = { + value: Number(number), + signCharacter: number.startsWith('-') ? '-' : undefined, + }; + if (type !== TokenType.Percentage) { + detail.type = /^[+-]?\d+$/.test(number) ? 'integer' : 'number'; + } + if (type === TokenType.Dimension) detail.unit = decodeIdentifier(unit); + return detail; +} + +/** + * A printed token. Its offsets are unspecified. + * + * @param {TokenType} type + * @param {string} raw + * @param {object | null | undefined} detail + * @return {CSSToken} + */ +function newToken(type, raw, detail) { + return /** @type {CSSToken} */ ( + /** @type {unknown} */ ([type, raw, 0, 0, detail]) + ); +} + +/** + * The output of a printer that builds tokens. `source[start, end)` is the + * list the printed tokens are compared with: while the printed tokens match + * it in order, each one is the source token itself. Once one differs, the + * rest are new tokens with unspecified offsets. + */ +class TokenSink { + /** @type {CSSToken[]} */ + tokens = []; + /** @type {boolean} */ + minusPending = false; + /** @type {boolean} */ + matching = true; + /** @type {number} */ + cursor; + /** @type {CSSToken[]} */ sourceTokens; + /** @type {number} */ end; + + /** + * @param {CSSToken[]} source + * @param {number} start + * @param {number} end + */ + constructor(source, start, end) { + this.sourceTokens = source; + this.cursor = start; + this.end = end; + } + + /** + * Whether the printed tokens are the source range, token for token. + * + * @return {boolean} + */ + identical() { + return this.matching && !this.minusPending && this.cursor === this.end; + } + + /** + * Append the source token at the cursor when it has `type` and raw text + * `prefix + first + last`. Otherwise the output has diverged for good. + * + * @param {TokenType} type + * @param {string} prefix + * @param {string} first + * @param {string} last + * @return {boolean} + */ + reuse(type, prefix, first, last) { + if (this.matching && this.cursor < this.end) { + const token = this.sourceTokens[this.cursor]; + if (token[0] === type && sameText(token[1], prefix, first, last)) { + this.tokens.push(token); + this.cursor++; + return true; + } + } + this.matching = false; + return false; + } + + /** + * Write a space when a token starting with `first` would fuse with the + * token before it. + * + * @param {string} first + * @return {void} + */ + separate(first) { + if (wouldFuse(this.tokens.at(-1)?.[1].at(-1), first)) + this.push(TokenType.Whitespace, FUSE_SEPARATOR, undefined); + } + + /** + * Keep the printed tokens apart from the tokens around them: `before` and + * `after` are the neighbours' adjacent characters. The printed tokens no + * longer match the source range once a separator is added. + * + * @param {string | undefined} before + * @param {string | undefined} after + * @return {void} + */ + fit(before, after) { + const first = firstCharOf(this.tokens, 0, this.tokens.length); + const last = this.tokens.at(-1)?.[1].at(-1); + if (wouldFuse(before, first)) { + this.tokens.unshift( + newToken(TokenType.Whitespace, FUSE_SEPARATOR, undefined) + ); + this.matching = false; + } + if (wouldFuse(last, after)) { + this.tokens.push( + newToken(TokenType.Whitespace, FUSE_SEPARATOR, undefined) + ); + this.matching = false; + } + } + + /** @return {string} The pending sign, or `''`. */ + takeMinus() { + const prefix = this.minusPending ? '-' : ''; + this.minusPending = false; + return prefix; + } + + /** A pending sign that no token absorbed is a delimiter. @return {void} */ + flushMinus() { + if (this.minusPending) { + this.minusPending = false; + if (!this.reuse(TokenType.Delim, '', '-', '')) + this.tokens.push(newToken(TokenType.Delim, '-', { value: '-' })); + } + } + + /** + * @param {TokenType} type + * @param {string} raw + * @param {object | null | undefined} detail + * @return {void} + */ + push(type, raw, detail) { + if (!this.reuse(type, '', raw, '')) { + this.tokens.push(newToken(type, raw, detail)); + } + } + + /** @return {void} */ + open() { + this.flushMinus(); + this.push(TokenType.OpenParen, '(', undefined); + } + + /** @return {void} */ + close() { + this.flushMinus(); + this.push(TokenType.CloseParen, ')', undefined); + } + + /** @return {void} */ + comma() { + this.flushMinus(); + this.push(TokenType.Comma, ',', undefined); + this.push(TokenType.Whitespace, ' ', undefined); + } + + /** + * @param {'+' | '-' | '*' | '/'} operator + * @return {void} + */ + op(operator) { + this.flushMinus(); + this.push(TokenType.Whitespace, ' ', undefined); + this.push(TokenType.Delim, operator, { value: operator }); + this.push(TokenType.Whitespace, ' ', undefined); + } + + /** @return {void} */ + minus() { + this.minusPending = true; + } + + /** @param {string} name @return {void} */ + fn(name) { + const prefix = this.takeMinus(); + this.separate((prefix || name)[0]); + if (!this.reuse(TokenType.Function, prefix, name, '(')) { + this.tokens.push( + newToken(TokenType.Function, `${prefix}${name}(`, { + value: decodeIdentifier(`${prefix}${name}`), + }) + ); + } + } + + /** @param {string} raw @return {void} */ + ident(raw) { + const prefix = this.takeMinus(); + this.separate((prefix || raw)[0]); + if (!this.reuse(TokenType.Ident, prefix, raw, '')) { + this.tokens.push( + newToken(TokenType.Ident, `${prefix}${raw}`, { + value: decodeIdentifier(`${prefix}${raw}`), + }) + ); + } + } + + /** @param {string} text @return {void} */ + number(text) { + this.numeric(TokenType.Number, text, ''); + } + + /** + * @param {string} text + * @param {string} unit + * @return {void} + */ + dimension(text, unit) { + this.numeric( + unit === '%' ? TokenType.Percentage : TokenType.Dimension, + text, + unit + ); + } + + /** + * @param {TokenType} type + * @param {string} text + * @param {string} unit + * @return {void} + */ + numeric(type, text, unit) { + const prefix = this.takeMinus(); + this.separate((prefix || text)[0]); + if (this.reuse(type, prefix, text, unit)) return; + const number = `${prefix}${text}`; + this.tokens.push( + newToken(type, `${number}${unit}`, numericDetail(type, number, unit)) + ); + } + + /** + * The raw tokens `list[start, end)` of an opaque component. Source tokens + * are appended by reference, and they keep the cursor only when they start + * exactly where the printed tokens are. + * + * @param {CSSToken[]} list + * @param {number} start + * @param {number} end + * @return {void} + */ + source(list, start, end) { + this.flushMinus(); + const first = firstCharOf(list, start, end); + if (first !== undefined) this.separate(first); + if (this.matching && this.cursor === start) this.cursor = end; + else this.matching = false; + // An EOF token is not CSS, so it is never copied into a replacement. + for (let i = start; i < end; i++) { + if (!isEOF(list[i])) this.tokens.push(list[i]); + } + } +} + +export { TextSink, TokenSink, decodeIdentifier, numericDetail, sameText }; diff --git a/src/lib/serialize/text-sink.js b/src/lib/serialize/text-sink.js new file mode 100644 index 0000000..72d4156 --- /dev/null +++ b/src/lib/serialize/text-sink.js @@ -0,0 +1,197 @@ +// The text output of the printer: a sink that collects the printed strings. +// `sink.js` has the token-building counterpart. + +import { TokenType } from '@csstools/css-tokenizer'; + +/** @typedef {import('@csstools/css-tokenizer').CSSToken} CSSToken */ + +/** The printed text of each binary operator, with the spaces the printer uses. */ +const OPERATOR_TEXT = { '+': ' + ', '-': ' - ', '*': ' * ', '/': ' / ' }; + +/** A character that can continue or start an identifier, number or dimension. */ +const NAME_CHAR = /[\w\-.\u0080-\uffff]/; + +const DIGIT = /\d/; + +/** + * Whether a token ending in `last` and a token starting with `first` would + * read back as one token if written without a separator. The check is + * conservative: it may ask for a separator that is not strictly needed. + * + * @param {string | undefined} last + * @param {string | undefined} first + * @return {boolean} + */ +function wouldFuse(last, first) { + if (last === undefined || first === undefined) return false; + // A digit continues into `%`, and a backslash starts an escape that + // continues the name or unit before it. + if (first === '%') return DIGIT.test(last); + return ( + NAME_CHAR.test(last) && + (NAME_CHAR.test(first) || first === '(' || first === '\\') + ); +} + +/** + * What keeps a replacement apart from a neighbour it would fuse with. A space + * rather than the empty comment CSS Syntax 3 §9 allows, because tools that + * strip comments from values (such as minifiers run after this plugin) would + * fuse the tokens again. + */ +const FUSE_SEPARATOR = ' '; + +/** + * Whether `token` is an end-of-file token. It marks the end of a tokenized + * string, so one inside a list (for example from concatenated `tokenize` + * results) is not part of the CSS and is skipped. + * + * @param {CSSToken | undefined} token + * @return {boolean} + */ +function isEOF(token) { + return token?.[0] === TokenType.EOF; +} + +/** + * The first character of the first non-EOF token in `list[start, end)`. + * + * @param {CSSToken[]} list + * @param {number} start + * @param {number} end + * @return {string | undefined} + */ +function firstCharOf(list, start, end) { + for (let i = start; i < end; i++) { + if (!isEOF(list[i])) return list[i][1][0]; + } + return undefined; +} + +/** + * The last character of the last non-EOF token in `list[0, end)`. + * + * @param {CSSToken[]} list + * @param {number} end + * @return {string | undefined} + */ +function lastCharBefore(list, end) { + for (let i = end - 1; i >= 0; i--) { + if (!isEOF(list[i])) return list[i][1].at(-1); + } + return undefined; +} + +/** + * The output of a printer that keeps its printed text as strings. + */ +class TextSink { + /** @type {string[]} */ + parts = []; + /** @type {boolean} */ + signed = false; + + /** + * Write a space when a token starting with `first` would fuse with the + * text before it. A sign belongs to the token that follows it. + * + * @param {string} first + * @return {void} + */ + separate(first) { + if (this.signed) this.signed = false; + else if (wouldFuse(this.parts.at(-1)?.at(-1), first)) { + this.parts.push(FUSE_SEPARATOR); + } + } + + /** @return {void} */ + open() { + this.parts.push('('); + } + + /** @return {void} */ + close() { + this.parts.push(')'); + } + + /** @return {void} */ + comma() { + this.parts.push(', '); + } + + /** + * @param {'+' | '-' | '*' | '/'} operator + * @return {void} + */ + op(operator) { + this.parts.push(OPERATOR_TEXT[operator]); + } + + /** The sign of the next number, identifier or function. @return {void} */ + minus() { + this.separate('-'); + this.parts.push('-'); + this.signed = true; + } + + /** @param {string} name @return {void} */ + fn(name) { + this.separate(name[0]); + this.parts.push(name, '('); + } + + /** @param {string} raw @return {void} */ + ident(raw) { + this.separate(raw[0]); + this.parts.push(raw); + } + + /** @param {string} text @return {void} */ + number(text) { + this.separate(text[0]); + this.parts.push(text); + } + + /** + * @param {string} text + * @param {string} unit + * @return {void} + */ + dimension(text, unit) { + this.separate(text[0]); + this.parts.push(text, unit); + } + + /** + * The raw text of `list[start, end)`. EOF tokens are skipped, as the token + * sink skips them, so an empty part never hides the last character from + * the next separator check. + * + * @param {CSSToken[]} list + * @param {number} start + * @param {number} end + * @return {void} + */ + source(list, start, end) { + const first = firstCharOf(list, start, end); + if (first !== undefined) this.separate(first); + for (let i = start; i < end; i++) { + if (!isEOF(list[i])) this.parts.push(list[i][1]); + } + } + + /** @return {string} */ + join() { + return this.parts.join(''); + } +} + +export { + FUSE_SEPARATOR, + TextSink, + firstCharOf, + isEOF, + lastCharBefore, + wouldFuse, +}; diff --git a/src/lib/simplify.js b/src/lib/simplify.js index 449a831..b137d15 100644 --- a/src/lib/simplify.js +++ b/src/lib/simplify.js @@ -56,7 +56,8 @@ function simplify(node, precision = false, depth = 0) { return opaqueCall( node.name, simplifyComponents(node.components, child), - node.rawName + node.rawName, + node.source ); case 'Sum': return simplifySum(node, (value) => operand(value, child), precision); diff --git a/src/lib/simplify/sum.js b/src/lib/simplify/sum.js index 59e1fc0..21488d3 100644 --- a/src/lib/simplify/sum.js +++ b/src/lib/simplify/sum.js @@ -1,4 +1,4 @@ -import { mkSum, num, dim } from '../node.js'; +import { mkSum, mkGroup, num, dim } from '../node.js'; import { staticBaseOf } from '../convertUnits.js'; import { mergeConvertibleBuckets } from './bucket.js'; @@ -126,7 +126,7 @@ function simplifySum(sum, simplify, precision = false) { // Keep the source grouping available to an enclosing subtraction. Numeric // groups have already folded and therefore do not need the marker. if (sum.grouped && result.type === 'Sum' && opaque.length > 0) { - return { ...result, grouped: true }; + return mkGroup(result); } return result; } diff --git a/src/reduce.js b/src/reduce.js index dd6502a..e92cac2 100644 --- a/src/reduce.js +++ b/src/reduce.js @@ -51,7 +51,9 @@ function reduceCalc(value, opts) { reduceTokenList( tokens, options, - (start, end, text) => { + (start, end, printed) => { + // The string caller asks for text, so the printed value is a string. + const text = /** @type {string} */ (printed); const from = tokens[start][2]; const to = tokens[end - 1][3] + 1; if (to - from === text.length && value.startsWith(text, from)) return; @@ -59,6 +61,8 @@ function reduceCalc(value, opts) { lastIndex = to; changed = true; }, + 0, + tokens.length, value ); return changed ? output + value.slice(lastIndex) : value; diff --git a/test/helpers/sexpr.js b/test/helpers/sexpr.js index 561eff1..707aa47 100644 --- a/test/helpers/sexpr.js +++ b/test/helpers/sexpr.js @@ -31,11 +31,16 @@ export function sexpr(node) { ? `(${node.name})` : `(${node.name} ${node.args.map(sexpr).join(' ')})`; case 'OpaqueCall': - return `OpaqueCall(${node.name.toLowerCase()} [${node.components.map(opaqueComponentSexpr).join(' ')}])`; + return `OpaqueCall(${node.name.toLowerCase()} [${node.components.map((part) => opaqueComponentSexpr(part, node.source)).join(' ')}])`; } } -function opaqueComponentSexpr(component) { +function opaqueComponentSexpr(component, source) { if (typeof component === 'string') return JSON.stringify(component); + if (Array.isArray(component)) { + let text = ''; + for (let i = component[0]; i < component[1]; i++) text += source[i][1]; + return JSON.stringify(text); + } return sexpr(component); } diff --git a/test/integration/math-operations.test.js b/test/integration/math-operations.test.js index ec2fb72..11fa2f7 100644 --- a/test/integration/math-operations.test.js +++ b/test/integration/math-operations.test.js @@ -97,6 +97,16 @@ describe('Subtraction from zero', () => { ) ); + // Characterization: this passes on master too. It pins the current grouping + // behaviour; it does not guard the sum.js change. + test( + 'characterization: subtracting a simplified opaque group keeps its grouping', + testValue( + 'calc(1px - (var(--a) + 1px + 1px))', + 'calc(1px - (2px + var(--a)))' + ) + ); + test( 'should reduce nested expression', // zero bucket kept for type info. @@ -202,3 +212,29 @@ describe('Minus', () => { test('minus sign (#4)', testValue('calc(200px / -1)', 'calc(-200px)')); }); + +describe('Reduced value next to a neighbouring token', () => { + test( + 'keeps a unit apart from a following name', + testValue('foo(calc(1px + 1px)b)', 'foo(2px b)', { + unwrapSingleValue: true, + }) + ); + + test( + 'keeps a number apart from a preceding name', + testValue('foo(b calc(1 + 1))', 'foo(b 2)', { unwrapSingleValue: true }) + ); + + test( + 'keeps a number apart from a following percent sign', + testValue('foo(calc(1 + 1)%)', 'foo(2 %)', { unwrapSingleValue: true }) + ); + + test( + 'adds no space when the neighbour is separate already', + testValue('foo(calc(1px + 1px) b)', 'foo(2px b)', { + unwrapSingleValue: true, + }) + ); +}); diff --git a/test/property/immutability.test.js b/test/property/immutability.test.js new file mode 100644 index 0000000..840f55d --- /dev/null +++ b/test/property/immutability.test.js @@ -0,0 +1,79 @@ +// The ownership rule in src/lib/node.js: nodes are immutable once constructed, +// and subtrees may be shared between an input tree and the simplified output. +// Deep-freezing the input turns any write to a node into a TypeError (ES +// modules run in strict mode), so these properties catch in-place edits that +// would otherwise corrupt a shared subtree silently. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fc from 'fast-check'; +import { analyze } from '../../src/lib/analyze.js'; +import { simplify } from '../../src/lib/simplify.js'; +import { serialize } from '../../src/lib/serialize.js'; +import { parseSource } from '../helpers/parse-source.js'; +import { + astArbWithDegenerate, + cssMathSourceArb, + opaqueGroupedCalcArb, +} from '../helpers/arbitraries.js'; + +const NUM_RUNS = 300; + +/** @param {unknown} value */ +function deepFreeze(value, seen = new Set()) { + if (value === null || typeof value !== 'object' || seen.has(value)) { + return value; + } + seen.add(value); + for (const child of Object.values(value)) deepFreeze(child, seen); + return Object.freeze(value); +} + +/** Run every post-parse stage on a fresh tree from `make`. */ +function runStages(make, precision) { + const tree = make(); + const analysis = analyze(tree); + const simplified = simplify(tree, precision); + return { analysis, output: serialize(simplified, { precision }) }; +} + +function assertStagesDoNotMutate(make) { + for (const precision of [false, 5]) { + const expected = runStages(make, precision); + const frozen = runStages(() => deepFreeze(make()), precision); + assert.deepEqual(frozen, expected); + } +} + +test('property: post-parse stages never write to parsed source trees', () => { + fc.assert( + fc.property( + fc.oneof( + cssMathSourceArb, + opaqueGroupedCalcArb.map(({ input }) => input) + ), + (source) => { + if (parseSource(source) === null) return; + assertStagesDoNotMutate(() => parseSource(source)); + } + ), + { numRuns: NUM_RUNS } + ); +}); + +test('property: post-parse stages never write to canonical ASTs', () => { + fc.assert( + fc.property(astArbWithDegenerate(4), (ast) => { + assertStagesDoNotMutate(() => structuredClone(ast)); + }), + { numRuns: NUM_RUNS } + ); +}); + +test('simplified output shares no writable state with a frozen input', () => { + const source = 'calc(1px - (var(--a) + 1px + 1px))'; + const frozen = deepFreeze(parseSource(source)); + const once = simplify(frozen); + const again = simplify(deepFreeze(once)); + assert.equal(serialize(again), serialize(once)); + assert.equal(serialize(once), 'calc(1px - (2px + var(--a)))'); +}); diff --git a/test/property/opaque-grouping.test.js b/test/property/opaque-grouping.test.js index 483744d..0462597 100644 --- a/test/property/opaque-grouping.test.js +++ b/test/property/opaque-grouping.test.js @@ -8,13 +8,39 @@ import { tokenize } from '@csstools/css-tokenizer'; import { parse } from '../../src/lib/parser.js'; import { simplify } from '../../src/lib/simplify.js'; import { serialize } from '../../src/lib/serialize.js'; +import reduceCalc from 'postcss-calc/reduce'; import { out } from '../helpers/out.js'; import { cssMathSourceArb, opaqueGroupedCalcArb, } from '../helpers/arbitraries.js'; +// Sign-bearing groups around generated math: the sign must stay outside the +// group, so these are the inputs most likely to distribute it wrongly. +const signedGroupArb = fc + .tuple( + cssMathSourceArb, + fc.constantFrom( + (inner) => `calc(-1 * (${inner}))`, + (inner) => `calc((${inner}) * -1)`, + (inner) => `calc(${inner} - (${inner}))` + ) + ) + .map(([source, wrap]) => wrap(source)); + describe('opaque CSS math properties', () => { + test('property: reduceCalc output re-parses and reducing it again changes nothing', () => { + fc.assert( + fc.property(fc.oneof(cssMathSourceArb, signedGroupArb), (input) => { + const once = reduceCalc(input); + const tokens = tokenize({ css: once }); + parse(tokens, 0, tokens.length); + return reduceCalc(once) === once; + }), + { numRuns: 300 } + ); + }); + test('property: bounded CSS math grammar parses and round-trips', () => { fc.assert( fc.property(cssMathSourceArb, (input) => { diff --git a/test/unit/node.test.js b/test/unit/node.test.js index 397764e..78e4095 100644 --- a/test/unit/node.test.js +++ b/test/unit/node.test.js @@ -13,11 +13,21 @@ import { } from '../../src/lib/node.js'; test('opaqueCall: stores the component tree on the canonical node', () => { - assert.deepEqual(opaqueCall('var', [ident('--x'), ', 1px']), { - type: 'OpaqueCall', - name: 'var', - components: [{ type: 'Ident', name: '--x' }, ', 1px'], - }); + const source = []; + assert.deepEqual( + opaqueCall('var', [ident('--x'), [0, 0]], undefined, source), + { + type: 'OpaqueCall', + name: 'var', + components: [{ type: 'Ident', name: '--x' }, [0, 0]], + source, + } + ); +}); + +test('opaqueCall: rejects range components without a source', () => { + assert.throws(() => opaqueCall('var', [[0, 3]]), TypeError); + assert.doesNotThrow(() => opaqueCall('var', [[0, 3]], undefined, [])); }); // --- Leaf constructors ---------------------------------------------------- diff --git a/test/unit/parser-opaque.test.js b/test/unit/parser-opaque.test.js index 6cb062b..d1f976c 100644 --- a/test/unit/parser-opaque.test.js +++ b/test/unit/parser-opaque.test.js @@ -70,13 +70,15 @@ describe('parser: opaque expressions and invalid syntax', () => { assert.deepEqual(parse(varTokens, 0, varTokens.length), { type: 'OpaqueCall', name: 'var', - components: [{ type: 'Ident', name: '--x' }, ', 1px'], + components: [{ type: 'Ident', name: '--x' }, [2, 5]], + source: varTokens, }); const unknownTokens = tokenize({ css: 'unknown(1px + 2px)' }); assert.deepEqual(parse(unknownTokens, 0, unknownTokens.length), { type: 'OpaqueCall', name: 'unknown', - components: ['1px + 2px'], + components: [[1, 6]], + source: unknownTokens, }); }); @@ -97,13 +99,15 @@ describe('parser: opaque expressions and invalid syntax', () => { test('parser: opaque trees preserve raw and nested component structure', () => { const input = String.raw`f( /*lead*/ \66 oo\20 bar, raw([x, y], {z: q}), c\61 lc(1px + var(--x)), calc(1PX+2PX), calc(-(var(--x) + 1px)) )`; - const node = parseSource(input); + const tokens = tokenize({ css: input }); + const node = parse(tokens, 0, tokens.length); assert.deepEqual(node, { type: 'OpaqueCall', name: 'f', + source: tokens, components: [ - String.raw` /*lead*/ \66 oo\20 bar, raw([x, y], {z: q}), `, + [1, 25], { type: 'Call', name: 'calc', @@ -119,13 +123,14 @@ describe('parser: opaque expressions and invalid syntax', () => { type: 'OpaqueCall', name: 'var', components: [{ type: 'Ident', name: '--x' }], + source: tokens, }, }, ], }, ], }, - ', calc(1PX+2PX), calc(-(var(--x) + 1px)) ', + [34, 55], ], }); // `calc(-( ... ))` has no unary-minus production, so the nested calc() diff --git a/test/unit/serialize-core.test.js b/test/unit/serialize-core.test.js index e82f740..a69b1bf 100644 --- a/test/unit/serialize-core.test.js +++ b/test/unit/serialize-core.test.js @@ -1,5 +1,6 @@ import { describe, test } from 'node:test'; import assert from 'node:assert/strict'; +import { tokenize } from '@csstools/css-tokenizer'; import { serialize } from '../../src/lib/serialize.js'; import { num, @@ -281,3 +282,11 @@ describe('serialize: core syntax and expressions', () => { assert.equal(serialize(ast), 'calc(infinity * var(--x))'); }); }); + +test('serialize: an OpaqueCall with a range but no source fails with a TypeError', () => { + const node = { + ...opaqueCall('var', [[0, 1]], undefined, tokenize({ css: 'x' })), + }; + delete node.source; + assert.throws(() => serialize(node), TypeError); +}); diff --git a/test/unit/serialize-result.test.js b/test/unit/serialize-result.test.js index 11ca224..0502f9d 100644 --- a/test/unit/serialize-result.test.js +++ b/test/unit/serialize-result.test.js @@ -1,3 +1,4 @@ +import { tokenize } from '@csstools/css-tokenizer'; import { describe, test } from 'node:test'; import assert from 'node:assert/strict'; import { @@ -18,6 +19,10 @@ const serialize = (node, opts = {}) => serializeSource(node, opts); const serializeResult = (result, opts = {}) => serializeResultSource(result, opts); +/** The comma and space that separate a fallback, as a range of source tokens. */ +const commaSource = tokenize({ css: ', ' }); +const comma = /** @type {[number, number]} */ ([0, 2]); + /** @param {number} depth */ function nestedOpaque(depth) { let tree = ident('--x'); @@ -32,7 +37,6 @@ function serializeResultInput(tree) { status: /** @type {'resolved'} */ ('resolved'), rootName: 'calc', rootSpelling: 'calc', - original: 'calc(var(--x))', }; } @@ -116,16 +120,15 @@ describe('serialize: degenerate numeric', () => { }); describe('serializeResult: root planning', () => { - test('preserves the original unresolved non-root call', () => { + test('prints nothing for an unresolved non-root call', () => { assert.equal( serializeResult({ tree: opaqueCall('sin', [ident('--x')]), status: 'unresolved', rootName: 'custom', rootSpelling: 'CUSTOM', - original: 'CUSTOM(var(--x))', }), - 'CUSTOM(var(--x))' + undefined ); }); @@ -136,7 +139,6 @@ describe('serializeResult: root planning', () => { status: 'unresolved', rootName: 'sin', rootSpelling: 'SIN', - original: 'SIN(var(--x))', }), 'SIN(var(--x))' ); @@ -153,27 +155,30 @@ describe('serializeResult: root planning', () => { status: 'resolved', rootName: '-webkit-calc', rootSpelling: '-webkit-calc', - original: '-webkit-calc(1px + 2px)', }), '-webkit-calc(1px + 2px)' ); }); test('threads scalar policy through nested opaque fallbacks', () => { - const tree = opaqueCall('var', [ - ident('--x'), - ', ', - mkSum([ - { sign: 1, node: dim(1, 'px') }, - { sign: 1, node: dim(2, 'px') }, - ]), - ]); + const tree = opaqueCall( + 'var', + [ + ident('--x'), + comma, + mkSum([ + { sign: 1, node: dim(1, 'px') }, + { sign: 1, node: dim(2, 'px') }, + ]), + ], + undefined, + commaSource + ); const result = { tree, status: /** @type {'resolved'} */ ('resolved'), rootName: 'calc', rootSpelling: 'calc', - original: 'calc(var(--x, 1px + 2px))', }; assert.equal(serializeResult(result), 'calc(var(--x, calc(1px + 2px)))'); assert.equal( @@ -199,25 +204,34 @@ describe('serializeResult: root planning', () => { status: 'unresolved', rootName: 'sin', rootSpelling: 'SIN', - original: 'SIN(cos(--x))', }), 'SIN(cos(--x))' ); }); test('writes nested opaque fallbacks directly into the parent buffer', () => { - const ast = opaqueCall('var', [ - ident('--outer'), - ', ', - opaqueCall('var', [ - ident('--inner'), - ', ', - mkSum([ - { sign: 1, node: dim(1, 'px') }, - { sign: 1, node: dim(2, 'px') }, - ]), - ]), - ]); + const ast = opaqueCall( + 'var', + [ + ident('--outer'), + comma, + opaqueCall( + 'var', + [ + ident('--inner'), + comma, + mkSum([ + { sign: 1, node: dim(1, 'px') }, + { sign: 1, node: dim(2, 'px') }, + ]), + ], + undefined, + commaSource + ), + ], + undefined, + commaSource + ); assert.equal(serialize(ast), 'var(--outer, var(--inner, calc(1px + 2px)))'); }); }); diff --git a/types/lib/blocks.d.ts b/types/lib/blocks.d.ts index 2f08a55..a895de7 100644 --- a/types/lib/blocks.d.ts +++ b/types/lib/blocks.d.ts @@ -1,47 +1,63 @@ export type CSSToken = import('@csstools/css-tokenizer').CSSToken; +export type Blocks = { + close: Int32Array; + base: number; +}; /** - * Match every block opener in the list to its closer. Matching is LIFO: a - * closer that does not match the innermost open block is ignored, so the - * open stack survives the mismatch. Openers with no closer map to -1. + * Match every block opener in `[start, end)` to its closer. Matching is LIFO: + * a closer that does not match the innermost open block is ignored, so the + * open stack survives the mismatch. Openers with no closer before `end` map + * to -1, as if the range were the whole list. * * `maxDepth` is the largest number of blocks open at once. The caller decides * whether that exceeds the nesting limit. * * @param {CSSToken[]} tokens - * @return {{close: Int32Array, maxDepth: number}} `close[i]` is the closer index for opener `i`, or -1. + * @param {number} [start] + * @param {number} [end] + * @return {{blocks: Blocks, maxDepth: number}} */ -declare function matchBlocks(tokens: CSSToken[]): { - close: Int32Array; +declare function matchBlocks(tokens: CSSToken[], start?: number, end?: number): { + blocks: Blocks; maxDepth: number; }; +/** + * The closer of the opener at `index`, or -1 when it has no closer or the + * matching does not cover `index`. The result is an absolute token index. + * + * @param {Blocks} blocks + * @param {number} index + * @return {number} + */ +declare function closerAt(blocks: Blocks, index: number): number; /** * The closer of the opener at `index`, or -1 when it has none inside * `[index, end)`. * - * @param {Int32Array} close + * @param {Blocks} blocks * @param {number} index * @param {number} end * @return {number} */ -declare function closeIn(close: Int32Array, index: number, end: number): number; +declare function closeIn(blocks: Blocks, index: number, end: number): number; /** * Index after the component (a token, or a whole block) that starts at `index`, * never past `end`. * - * @param {Int32Array} close + * @param {Blocks} blocks * @param {number} index * @param {number} end * @return {number} */ -declare function nextComponent(close: Int32Array, index: number, end: number): number; +declare function nextComponent(blocks: Blocks, index: number, end: number): number; /** * First comma outside every block in `[start, end)`, or -1. * * @param {CSSToken[]} tokens - * @param {Int32Array} close + * @param {Blocks} blocks * @param {number} start * @param {number} end * @return {number} */ -declare function firstTopLevelComma(tokens: CSSToken[], close: Int32Array, start: number, end: number): number; -export { closeIn, firstTopLevelComma, matchBlocks, nextComponent }; +declare function firstTopLevelComma(tokens: CSSToken[], blocks: Blocks, start: number, end: number): number; +export { closerAt, closeIn, firstTopLevelComma, matchBlocks, nextComponent }; diff --git a/types/lib/core.d.ts b/types/lib/core.d.ts index f3f6cef..7889cfa 100644 --- a/types/lib/core.d.ts +++ b/types/lib/core.d.ts @@ -1,18 +1,30 @@ +import { TokenSink } from './serialize/sink.js'; export type ResolvedReduceCalcOptions = import('../reduce.js').ResolvedReduceCalcOptions; export type CSSToken = import('@csstools/css-tokenizer').CSSToken; +export type Blocks = import('./blocks.js').Blocks; export type MathFunction = import('./functions.js').MathFunction; -export type EmitReplacement = (start: number, end: number, text: string) => void; +export type EmitReplacement = (start: number, end: number, printed: string | TokenSink) => void; /** - * Reduce every supported math function in a token list. Each function is one - * candidate, so a nested function is never reduced on its own, and an invalid - * outer function is reported without partial output. + * Reduce every supported math function in `tokens[start, end)`. Each function + * is one candidate, so a nested function is never reduced on its own, and an + * invalid outer function is reported without partial output. Blocks and + * error offsets read the range as the list it names would: a block open at + * `end` is unclosed, and error offsets count from `start`. The one exception + * is the token on each side of a replacement, which may lie outside the range: + * a replacement gets a space when it would fuse with it. + * + * Reads each token's type, raw text and parsed value (`token[4]`), never its + * source offsets (`token[2]`, `token[3]`), so the list may have been edited + * since it was tokenized. Emitted indices are indices into `tokens`. * - * @param {CSSToken[]} tokens * @param {ResolvedReduceCalcOptions} options * @param {EmitReplacement} emit - * @param {string} source The joined token text. + * @param {number} start + * @param {number} end + * @param {string} [source] The joined text of the range, when the caller already has it. + * @param {boolean} [printTokens] Emit token sinks instead of text. * @return {void} */ -declare function reduceTokenList(tokens: CSSToken[], options: ResolvedReduceCalcOptions, emit: EmitReplacement, source: string): void; +declare function reduceTokenList(tokens: CSSToken[], options: ResolvedReduceCalcOptions, emit: EmitReplacement, start: number, end: number, source?: string, printTokens?: boolean): void; export { reduceTokenList }; diff --git a/types/lib/functions.d.ts b/types/lib/functions.d.ts index e34a606..3cb6739 100644 --- a/types/lib/functions.d.ts +++ b/types/lib/functions.d.ts @@ -34,9 +34,11 @@ declare function hasPotentialMathFunction(value: string): boolean; * functions inside `url()` and similar are part of another token. * * @param {import('@csstools/css-tokenizer').CSSToken[]} tokens + * @param {number} [start] First token to inspect. + * @param {number} [end] One past the last token to inspect (half-open). * @return {boolean} */ -declare function hasMathFunctionToken(tokens: import('@csstools/css-tokenizer').CSSToken[]): boolean; +declare function hasMathFunctionToken(tokens: import('@csstools/css-tokenizer').CSSToken[], start?: number, end?: number): boolean; /** * The supported math function named by the function token at `index`, or * `undefined` when that token is not a supported math function. diff --git a/types/lib/node.d.ts b/types/lib/node.d.ts index ef9f6b7..f6729eb 100644 --- a/types/lib/node.d.ts +++ b/types/lib/node.d.ts @@ -1,3 +1,4 @@ +export type CSSToken = import('@csstools/css-tokenizer').CSSToken; export type Num = { type: 'Num'; value: number; @@ -19,12 +20,13 @@ export type Call = { args: Node[]; rawName?: string; }; -export type OpaqueComponent = string | Node; +export type OpaqueComponent = [number, number] | Node; export type OpaqueCall = { type: 'OpaqueCall'; name: string; components: OpaqueComponent[]; rawName?: string; + source?: CSSToken[]; }; export type SumTerm = { sign: 1 | -1; @@ -46,12 +48,14 @@ export type Product = { }; export type Node = Num | Dim | Ident | Call | OpaqueCall | Sum | Product; /** + * @typedef {import('@csstools/css-tokenizer').CSSToken} CSSToken * @typedef {{type: 'Num', value: number}} Num * @typedef {{type: 'Dim', value: number, unit: string, rawUnit?: string}} Dim * @typedef {{type: 'Ident', name: string, rawName?: string}} Ident * @typedef {{type: 'Call', name: string, args: Node[], rawName?: string}} Call - * @typedef {string | Node} OpaqueComponent - * @typedef {{type: 'OpaqueCall', name: string, components: OpaqueComponent[], rawName?: string}} OpaqueCall + * @typedef {[number, number] | Node} OpaqueComponent A `[start, end)` range + * reads the call's `source` tokens. + * @typedef {{type: 'OpaqueCall', name: string, components: OpaqueComponent[], rawName?: string, source?: CSSToken[]}} OpaqueCall * @typedef {{sign: 1 | -1, node: Node}} SumTerm Sign is always +1 when node is Num or Dim. * @typedef {{type: 'Sum', terms: SumTerm[], grouped?: boolean}} Sum * @typedef {{exponent: 1 | -1, node: Node}} ProductFactor exponent +1 = numerator, -1 = denominator. @@ -87,9 +91,10 @@ declare function call(name: string, args: Node[], rawName?: string): Call; * @param {string} name * @param {OpaqueComponent[]} components * @param {string} [rawName] + * @param {CSSToken[]} [source] The token list that the range components index. * @return {OpaqueCall} */ -declare function opaqueCall(name: string, components: OpaqueComponent[], rawName?: string): OpaqueCall; +declare function opaqueCall(name: string, components: OpaqueComponent[], rawName?: string, source?: CSSToken[]): OpaqueCall; /** * @param {SumTerm[]} rawTerms * @return {Node} diff --git a/types/lib/offsets.d.ts b/types/lib/offsets.d.ts index c50e01e..43f638e 100644 --- a/types/lib/offsets.d.ts +++ b/types/lib/offsets.d.ts @@ -1,15 +1,17 @@ /** @typedef {import('@csstools/css-tokenizer').CSSToken} CSSToken */ export type CSSToken = import('@csstools/css-tokenizer').CSSToken; /** - * Maps a token index to the offset in the joined raw text of `tokens` where - * that token starts, or the total length past the end. Only diagnostics need - * offsets, and a fallback can report many of them, so the table is built on - * the first call and each lookup after that is constant time. + * Maps a token index in `[start, end)` to the offset in the joined raw text of + * that range where the token starts, or the range's total length past its end. + * Only diagnostics need offsets, and a fallback can report many of them, so the + * table is built on the first call and each lookup after that is constant time. * * @param {CSSToken[]} tokens + * @param {number} [start] + * @param {number} [end] * @return {(index: number) => number} */ -declare function offsetLookup(tokens: CSSToken[]): (index: number) => number; +declare function offsetLookup(tokens: CSSToken[], start?: number, end?: number): (index: number) => number; /** * @param {CSSToken[]} tokens * @param {number} start diff --git a/types/lib/opaque.d.ts b/types/lib/opaque.d.ts index d3e1712..3bf2035 100644 --- a/types/lib/opaque.d.ts +++ b/types/lib/opaque.d.ts @@ -8,11 +8,4 @@ export type OpaqueComponent = import('./node.js').OpaqueComponent; * @return {OpaqueComponent[]} */ declare function simplifyComponents(components: OpaqueComponent[], simplify: (node: Node) => Node): OpaqueComponent[]; -/** - * @param {OpaqueComponent[]} components - * @param {string[]} buffer - * @param {(node: Node, buffer: string[]) => void} serialize - * @return {void} - */ -declare function serializeComponents(components: OpaqueComponent[], buffer: string[], serialize: (node: Node, buffer: string[]) => void): void; -export { simplifyComponents, serializeComponents }; +export { simplifyComponents }; diff --git a/types/lib/parser.d.ts b/types/lib/parser.d.ts index 42d34fc..da6d1cc 100644 --- a/types/lib/parser.d.ts +++ b/types/lib/parser.d.ts @@ -3,27 +3,28 @@ export type CSSToken = import('@csstools/css-tokenizer').CSSToken; export type Node = import('./node.js').Node; export type SumTerm = import('./node.js').SumTerm; export type ProductFactor = import('./node.js').ProductFactor; -export type ParseRange = (tokens: CSSToken[], close: Int32Array, start: number, end: number) => Node; +export type Blocks = import('./blocks.js').Blocks; +export type ParseRange = (tokens: CSSToken[], blocks: Blocks, start: number, end: number) => Node; /** * Parse `[start, end)` as one complete expression. * * @param {CSSToken[]} tokens - * @param {Int32Array} close + * @param {Blocks} blocks * @param {number} start * @param {number} end * @return {Node} */ -declare function parseRange(tokens: CSSToken[], close: Int32Array, start: number, end: number): Node; +declare function parseRange(tokens: CSSToken[], blocks: Blocks, start: number, end: number): Node; /** * Parse the token range `[start, end)` of `tokens` as one calculation. - * `close` is the closer array from `matchBlocks(tokens)`; when omitted, it is + * `blocks` is the matching from `matchBlocks(tokens)`; when omitted, it is * built and depth-checked from `tokens`. * * @param {CSSToken[]} tokens * @param {number} start * @param {number} end - * @param {Int32Array} [close] + * @param {Blocks} [blocks] * @return {Node} */ -declare function parse(tokens: CSSToken[], start: number, end: number, close?: Int32Array): Node; +declare function parse(tokens: CSSToken[], start: number, end: number, blocks?: Blocks): Node; export { parse, parseRange }; diff --git a/types/lib/parser/state.d.ts b/types/lib/parser/state.d.ts index 3a4088d..3196bda 100644 --- a/types/lib/parser/state.d.ts +++ b/types/lib/parser/state.d.ts @@ -1,6 +1,8 @@ import { TokenType as CssType } from '@csstools/css-tokenizer'; export type CSSToken = import('@csstools/css-tokenizer').CSSToken; +export type Blocks = import('../blocks.js').Blocks; /** @typedef {import('@csstools/css-tokenizer').CSSToken} CSSToken */ +/** @typedef {import('../blocks.js').Blocks} Blocks */ /** * A syntax error at a token. The position is not formatted here: a fallback * that fails to parse is discarded, so formatting it would be wasted work. @@ -31,7 +33,7 @@ declare function positionedError(error: Error, offsetOf: (index: number) => numb declare function isTrivia(type: CssType): boolean; export type ParseState = { tokens: CSSToken[]; - close: Int32Array; + blocks: Blocks; /** * First token of the range, for the leading-whitespace rule. */ @@ -51,12 +53,12 @@ export type ParseState = { declare function peek(state: ParseState): number; /** * @param {CSSToken[]} tokens - * @param {Int32Array} close + * @param {Blocks} blocks * @param {number} start * @param {number} end * @return {ParseState} */ -declare function newState(tokens: CSSToken[], close: Int32Array, start: number, end: number): ParseState; +declare function newState(tokens: CSSToken[], blocks: Blocks, start: number, end: number): ParseState; /** * The text a parse error shows for an expression token, as * `Expected ) ... got "..."`. Numbers show their value without the unit, and diff --git a/types/lib/serialize.d.ts b/types/lib/serialize.d.ts index 29821fd..2fc066e 100644 --- a/types/lib/serialize.d.ts +++ b/types/lib/serialize.d.ts @@ -27,16 +27,28 @@ export type SerializeOptions = { */ declare function serialize(node: Node, opts?: SerializeOptions): string; /** - * @param {{tree: Node, status: 'resolved' | 'unresolved', rootName: string, rootSpelling: string, calculation?: boolean, original?: string}} result - * @param {SerializeOptions} [opts] - * @return {string} + * Print a result into `out`. An unresolved root that is not a calculation and + * does not match its own name prints nothing. + * + * @param {{tree: Node, status: 'resolved' | 'unresolved', rootName: string, rootSpelling: string, calculation?: boolean}} result + * @param {SerializeOptions} opts + * @param {import('./serialize/sink.js').Sink} out + * @return {boolean} Whether anything was printed. */ -declare function serializeResult(result: { +declare function printResult(result: { tree: Node; status: 'resolved' | 'unresolved'; rootName: string; rootSpelling: string; calculation?: boolean; - original?: string; -}, opts?: SerializeOptions): string; -export { serialize, serializeResult }; +}, opts: SerializeOptions, out: import('./serialize/sink.js').Sink): boolean; +/** + * Returns `undefined` for an unresolved root that is not a calculation and + * does not match its own name: the caller keeps the source text as it is. + * + * @param {Parameters[0]} result + * @param {SerializeOptions} [opts] + * @return {string | undefined} + */ +declare function serializeResult(result: Parameters[0], opts?: SerializeOptions): string | undefined; +export { printResult, serialize, serializeResult }; diff --git a/types/lib/serialize/expression.d.ts b/types/lib/serialize/expression.d.ts index f0f5dbc..d6c6293 100644 --- a/types/lib/serialize/expression.d.ts +++ b/types/lib/serialize/expression.d.ts @@ -3,12 +3,14 @@ export type Sum = import('../node.js').Sum; export type SumTerm = import('../node.js').SumTerm; export type ProductFactor = import('../node.js').ProductFactor; export type SerializeSession = import('./precision.js').SerializeSession; +export type CSSToken = import('@csstools/css-tokenizer').CSSToken; /** * @typedef {import('../node.js').Node} Node * @typedef {import('../node.js').Sum} Sum * @typedef {import('../node.js').SumTerm} SumTerm * @typedef {import('../node.js').ProductFactor} ProductFactor * @typedef {import('./precision.js').SerializeSession} SerializeSession + * @typedef {import('@csstools/css-tokenizer').CSSToken} CSSToken */ /** * @param {Node} node @@ -45,11 +47,20 @@ declare function emitOpaqueCall(node: import('../node.js').OpaqueCall, session: * @return {void} */ declare function emitMathResult(node: Node, session: SerializeSession, wrapper: string): void; +/** + * Emit a non-scalar root inside `wrapper(...)`. A single-term sum emits its + * term as a leading term, so the term's sign stays a leading sign. + * + * @param {Node} node + * @param {SerializeSession} session + * @param {string} wrapper + * @return {void} + */ +declare function emitWrappedRoot(node: Node, session: SerializeSession, wrapper: string): void; /** * @param {Node} node * @param {SerializeSession} session - * @param {string[]} [buffer] * @return {void} */ -declare function emitNestedMathResult(node: Node, session: SerializeSession, buffer?: string[]): void; -export { emitNode, emitLeadingNeg, emitCall, emitOpaqueCall, emitMathResult, emitNestedMathResult, }; +declare function emitNestedMathResult(node: Node, session: SerializeSession): void; +export { emitNode, emitLeadingNeg, emitCall, emitOpaqueCall, emitMathResult, emitNestedMathResult, emitWrappedRoot, }; diff --git a/types/lib/serialize/precision.d.ts b/types/lib/serialize/precision.d.ts index bf40670..be82fdb 100644 --- a/types/lib/serialize/precision.d.ts +++ b/types/lib/serialize/precision.d.ts @@ -2,7 +2,7 @@ export type Node = import('../node.js').Node; export type Num = import('../node.js').Num; export type Dim = import('../node.js').Dim; export type SerializeSession = { - buffer: string[]; + out: import('./sink.js').Sink; precision: number | false; scalarPolicy: 'standard' | 'unwrap-all'; }; @@ -11,7 +11,7 @@ export type SerializeSession = { * @typedef {import('../node.js').Num} Num * @typedef {import('../node.js').Dim} Dim * @typedef {object} SerializeSession - * @property {string[]} buffer + * @property {import('./sink.js').Sink} out * @property {number | false} precision * @property {'standard' | 'unwrap-all'} scalarPolicy */ @@ -54,11 +54,23 @@ declare function degenerateKeyword(v: number): string; declare function serializeNumber(v: number): string; /** * @param {import('../node.js').Num | import('../node.js').Dim} node - * @param {string[]} buffer + * @param {SerializeSession['out']} out * @param {number} value * @return {void} */ -declare function emitRoundedScalar(node: import('../node.js').Num | import('../node.js').Dim, buffer: string[], value: number): void; +declare function emitRoundedScalar(node: import('../node.js').Num | import('../node.js').Dim, out: SerializeSession['out'], value: number): void; +/** + * A non-finite value as its keyword. A dimension keeps its unit as `* 1` + * so the keyword stays a valid calculation. `wrapper` names the function that + * wraps the keyword, or is omitted to emit the bare keyword. + * + * @param {SerializeSession['out']} out + * @param {number} value + * @param {import('../node.js').Num | import('../node.js').Dim} node + * @param {string} [wrapper] + * @return {void} + */ +declare function emitDegenerate(out: SerializeSession['out'], value: number, node: import('../node.js').Num | import('../node.js').Dim, wrapper?: string): void; /** * @param {import('../node.js').Num | import('../node.js').Dim} node * @param {SerializeSession} session @@ -68,21 +80,21 @@ declare function emitRoundedScalar(node: import('../node.js').Num | import('../n */ declare function emitScalar(node: import('../node.js').Num | import('../node.js').Dim, session: SerializeSession, value?: number, bare?: boolean): void; /** - * @param {string[]} buffer + * @param {SerializeSession['out']} out * @param {import('../node.js').Num | import('../node.js').Dim} node * @return {void} */ -declare function emitSignedZero(buffer: string[], node: import('../node.js').Num | import('../node.js').Dim): void; +declare function emitSignedZero(out: SerializeSession['out'], node: import('../node.js').Num | import('../node.js').Dim): void; /** * Negative zero as an unwrapped product, valid only where a `` * may appear without changing how the surrounding expression parses. - * @param {string[]} buffer + * @param {SerializeSession['out']} out * @param {import('../node.js').Num | import('../node.js').Dim} node * @return {void} */ -declare function emitBareSignedZero(buffer: string[], node: import('../node.js').Num | import('../node.js').Dim): void; +declare function emitBareSignedZero(out: SerializeSession['out'], node: import('../node.js').Num | import('../node.js').Dim): void; /** @param {Node} node @return {node is import('../node.js').Num | import('../node.js').Dim} */ declare function isScalar(node: Node): node is import('../node.js').Num | import('../node.js').Dim; /** @param {Node} node @return {node is import('../node.js').Num | import('../node.js').Dim} */ declare function isSignedZero(node: Node): node is import('../node.js').Num | import('../node.js').Dim; -export { NOISE_FLOOR, divideByPowerOfTen, roundDecimal, round, isDegenerate, degenerateKeyword, serializeNumber, emitRoundedScalar, emitScalar, emitSignedZero, emitBareSignedZero, isScalar, isSignedZero, }; +export { NOISE_FLOOR, divideByPowerOfTen, roundDecimal, round, isDegenerate, degenerateKeyword, serializeNumber, emitDegenerate, emitRoundedScalar, emitScalar, emitSignedZero, emitBareSignedZero, isScalar, isSignedZero, }; diff --git a/types/lib/serialize/sink.d.ts b/types/lib/serialize/sink.d.ts new file mode 100644 index 0000000..28a7d1b --- /dev/null +++ b/types/lib/serialize/sink.d.ts @@ -0,0 +1,152 @@ +import { TokenType } from '@csstools/css-tokenizer'; +import { TextSink } from './text-sink.js'; +export type CSSToken = import('@csstools/css-tokenizer').CSSToken; +export type Sink = TextSink | TokenSink; +/** @typedef {import('@csstools/css-tokenizer').CSSToken} CSSToken */ +/** + * What the printer writes to. `TextSink` and `TokenSink` both implement it, so + * a method added to one must be added to the other. + * + * @typedef {TextSink | TokenSink} Sink + */ +/** + * Whether `raw` is `prefix + first + last`, without building that string. + * + * @param {string} raw + * @param {string} prefix + * @param {string} first + * @param {string} last + * @return {boolean} + */ +declare function sameText(raw: string, prefix: string, first: string, last: string): boolean; +/** + * The value of a CSS identifier from its raw text: each escape is replaced by + * the code point it names, so `c\61 lc` reads `calc`. + * + * @param {string} raw + * @return {string} + */ +declare function decodeIdentifier(raw: string): string; +/** + * The detail object of a numeric token, as the tokenizer makes it. + * + * @param {TokenType} type + * @param {string} number The signed number text. + * @param {string} unit + * @return {object} + */ +declare function numericDetail(type: TokenType, number: string, unit: string): object; +/** + * The output of a printer that builds tokens. `source[start, end)` is the + * list the printed tokens are compared with: while the printed tokens match + * it in order, each one is the source token itself. Once one differs, the + * rest are new tokens with unspecified offsets. + */ +declare class TokenSink { + /** @type {CSSToken[]} */ + tokens: CSSToken[]; + /** @type {boolean} */ + minusPending: boolean; + /** @type {boolean} */ + matching: boolean; + /** @type {number} */ + cursor: number; + /** @type {CSSToken[]} */ sourceTokens: CSSToken[]; + /** @type {number} */ end: number; + /** + * @param {CSSToken[]} source + * @param {number} start + * @param {number} end + */ + constructor(source: CSSToken[], start: number, end: number); + /** + * Whether the printed tokens are the source range, token for token. + * + * @return {boolean} + */ + identical(): boolean; + /** + * Append the source token at the cursor when it has `type` and raw text + * `prefix + first + last`. Otherwise the output has diverged for good. + * + * @param {TokenType} type + * @param {string} prefix + * @param {string} first + * @param {string} last + * @return {boolean} + */ + reuse(type: TokenType, prefix: string, first: string, last: string): boolean; + /** + * Write a space when a token starting with `first` would fuse with the + * token before it. + * + * @param {string} first + * @return {void} + */ + separate(first: string): void; + /** + * Keep the printed tokens apart from the tokens around them: `before` and + * `after` are the neighbours' adjacent characters. The printed tokens no + * longer match the source range once a separator is added. + * + * @param {string | undefined} before + * @param {string | undefined} after + * @return {void} + */ + fit(before: string | undefined, after: string | undefined): void; + /** @return {string} The pending sign, or `''`. */ + takeMinus(): string; + /** A pending sign that no token absorbed is a delimiter. @return {void} */ + flushMinus(): void; + /** + * @param {TokenType} type + * @param {string} raw + * @param {object | null | undefined} detail + * @return {void} + */ + push(type: TokenType, raw: string, detail: object | null | undefined): void; + /** @return {void} */ + open(): void; + /** @return {void} */ + close(): void; + /** @return {void} */ + comma(): void; + /** + * @param {'+' | '-' | '*' | '/'} operator + * @return {void} + */ + op(operator: '+' | '-' | '*' | '/'): void; + /** @return {void} */ + minus(): void; + /** @param {string} name @return {void} */ + fn(name: string): void; + /** @param {string} raw @return {void} */ + ident(raw: string): void; + /** @param {string} text @return {void} */ + number(text: string): void; + /** + * @param {string} text + * @param {string} unit + * @return {void} + */ + dimension(text: string, unit: string): void; + /** + * @param {TokenType} type + * @param {string} text + * @param {string} unit + * @return {void} + */ + numeric(type: TokenType, text: string, unit: string): void; + /** + * The raw tokens `list[start, end)` of an opaque component. Source tokens + * are appended by reference, and they keep the cursor only when they start + * exactly where the printed tokens are. + * + * @param {CSSToken[]} list + * @param {number} start + * @param {number} end + * @return {void} + */ + source(list: CSSToken[], start: number, end: number): void; +} +export { TextSink, TokenSink, decodeIdentifier, numericDetail, sameText }; diff --git a/types/lib/serialize/text-sink.d.ts b/types/lib/serialize/text-sink.d.ts new file mode 100644 index 0000000..d2e0d47 --- /dev/null +++ b/types/lib/serialize/text-sink.d.ts @@ -0,0 +1,100 @@ +export type CSSToken = import('@csstools/css-tokenizer').CSSToken; +/** + * Whether a token ending in `last` and a token starting with `first` would + * read back as one token if written without a separator. The check is + * conservative: it may ask for a separator that is not strictly needed. + * + * @param {string | undefined} last + * @param {string | undefined} first + * @return {boolean} + */ +declare function wouldFuse(last: string | undefined, first: string | undefined): boolean; +/** + * What keeps a replacement apart from a neighbour it would fuse with. A space + * rather than the empty comment CSS Syntax 3 §9 allows, because tools that + * strip comments from values (such as minifiers run after this plugin) would + * fuse the tokens again. + */ +declare const FUSE_SEPARATOR = " "; +/** + * Whether `token` is an end-of-file token. It marks the end of a tokenized + * string, so one inside a list (for example from concatenated `tokenize` + * results) is not part of the CSS and is skipped. + * + * @param {CSSToken | undefined} token + * @return {boolean} + */ +declare function isEOF(token: CSSToken | undefined): boolean; +/** + * The first character of the first non-EOF token in `list[start, end)`. + * + * @param {CSSToken[]} list + * @param {number} start + * @param {number} end + * @return {string | undefined} + */ +declare function firstCharOf(list: CSSToken[], start: number, end: number): string | undefined; +/** + * The last character of the last non-EOF token in `list[0, end)`. + * + * @param {CSSToken[]} list + * @param {number} end + * @return {string | undefined} + */ +declare function lastCharBefore(list: CSSToken[], end: number): string | undefined; +/** + * The output of a printer that keeps its printed text as strings. + */ +declare class TextSink { + /** @type {string[]} */ + parts: string[]; + /** @type {boolean} */ + signed: boolean; + /** + * Write a space when a token starting with `first` would fuse with the + * text before it. A sign belongs to the token that follows it. + * + * @param {string} first + * @return {void} + */ + separate(first: string): void; + /** @return {void} */ + open(): void; + /** @return {void} */ + close(): void; + /** @return {void} */ + comma(): void; + /** + * @param {'+' | '-' | '*' | '/'} operator + * @return {void} + */ + op(operator: '+' | '-' | '*' | '/'): void; + /** The sign of the next number, identifier or function. @return {void} */ + minus(): void; + /** @param {string} name @return {void} */ + fn(name: string): void; + /** @param {string} raw @return {void} */ + ident(raw: string): void; + /** @param {string} text @return {void} */ + number(text: string): void; + /** + * @param {string} text + * @param {string} unit + * @return {void} + */ + dimension(text: string, unit: string): void; + /** + * The raw text of `list[start, end)`. EOF tokens are skipped, as the token + * sink skips them, so an empty part never hides the last character from + * the next separator check. + * + * @param {CSSToken[]} list + * @param {number} start + * @param {number} end + * @return {void} + */ + source(list: CSSToken[], start: number, end: number): void; + /** @return {string} */ + join(): string; +} +export { FUSE_SEPARATOR, TextSink, firstCharOf, isEOF, lastCharBefore, wouldFuse, };