From 6194d3a28f80f5cf152c61d85713a2de1f9b6d67 Mon Sep 17 00:00:00 2001 From: "Schero D." Date: Thu, 19 Nov 2026 00:11:20 +0100 Subject: [PATCH 1/3] test(admin): add a StrictMode and React 19 harness for every entry point npm run test:admin renders the bookmark page, the homepage widget, the Content Manager list view toolbar (popover, advanced filters) and the bookmark dialog inside React.StrictMode with the provider tree of the Strapi 5.62 admin test utils, in jsdom (31) with a fake network. It fails on a mutation sent twice, a GET repeated without aborting the first copy, any interval, listener, connection or observer left after unmount, and any console error or warning. CI runs it on React 18 and, informational only (peers stay React ^18), on React 19. Docs read: react.dev/reference/react/StrictMode, React 19 upgrade guide, @strapi/admin 5.62 dist/admin/admin/tests/utils.mjs and useFetchClient.mjs, Node 22 module customization hooks, esbuild 0.28 transform API, jsdom 31. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 35 ++ README.md | 9 + eslint.config.mjs | 13 + package-lock.json | 335 ++++++++++++++++++ package.json | 3 + tests/admin/harness/fake-socket.mjs | 120 +++++++ tests/admin/harness/index.jsx | 523 ++++++++++++++++++++++++++++ tests/admin/harness/loader.mjs | 297 ++++++++++++++++ tests/admin/harness/network.mjs | 178 ++++++++++ tests/admin/harness/setup.mjs | 350 +++++++++++++++++++ tests/admin/strict-mode.test.jsx | 197 +++++++++++ tests/package.test.cjs | 9 +- 12 files changed, 2068 insertions(+), 1 deletion(-) create mode 100644 tests/admin/harness/fake-socket.mjs create mode 100644 tests/admin/harness/index.jsx create mode 100644 tests/admin/harness/loader.mjs create mode 100644 tests/admin/harness/network.mjs create mode 100644 tests/admin/harness/setup.mjs create mode 100644 tests/admin/strict-mode.test.jsx diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6c80847..f7a906f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -51,6 +51,9 @@ jobs: - name: Run regression test suite run: npm test + - name: Admin StrictMode tests (React 18) + run: npm run test:admin + - name: Type checks run: | npm run test:ts:front @@ -81,6 +84,38 @@ jobs: test -f README.md test -f LICENSE + react-19: + # Informational: the peer range is React ^18, like the Strapi 5 admin, and stays so. This job + # runs the admin StrictMode tests against React 19 (RFC strapi/strapi#25739) to see problems + # before Strapi moves; a failure here does not block a pull request. + name: Admin StrictMode tests on React 19 (informational) + runs-on: ubuntu-latest + timeout-minutes: 20 + continue-on-error: true + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '22' + cache: npm + + - name: Install dependencies + run: npm ci --legacy-peer-deps + + - name: Install React 19 (not saved) + run: npm install --no-save --legacy-peer-deps --ignore-scripts react@19 react-dom@19 + + - name: Show installed React version + run: node -p "'react ' + require('react/package.json').version + ', react-dom ' + require('react-dom/package.json').version" + + - name: Admin StrictMode tests (React 19) + run: npm run test:admin + peer-floor: # peerDependencies say @strapi/strapi ^5.57.0: prove the lowest supported version, not only # the acceptance version in the lockfile. diff --git a/README.md b/README.md index a789b48..1e3fe73 100644 --- a/README.md +++ b/README.md @@ -413,6 +413,7 @@ npm ci --legacy-peer-deps npm run lint npm run format:check npm test +npm run test:admin npm run test:ts:front npm run test:ts:back npm run build @@ -427,6 +428,14 @@ view helpers, translation completeness and package rules. CI runs every command and 24, and type-checks, tests and builds once more against the lowest supported Strapi version (5.57.0). +`npm run test:admin` renders every admin entry point (the bookmark page, the homepage widget, the +list view toolbar with its popover and filter dialog, the bookmark dialog) inside +`React.StrictMode` with the providers of the Strapi admin, in jsdom with a fake network. It fails +on a mutation sent twice, a read repeated without aborting the first one, an interval, listener, +connection or observer left after unmount, and any console error or warning. A separate CI job +runs the same tests against React 19 for information only: the plugin's peer range is React 18, +like the Strapi 5 admin. + ## Contributing and support - Bugs and feature requests: [open an issue](https://github.com/Schero94/Magicmark/issues/new/choose). diff --git a/eslint.config.mjs b/eslint.config.mjs index 258f27d..2e03df0 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -6,6 +6,7 @@ * - Admin panel: browser globals, JSX, React Hooks recommended rules. * - Server: Node globals, `strapi` as a readonly global. * - Tests and scripts: Node globals, module type per file extension. + * - Admin StrictMode harness (tests/admin): JSX, Node and browser (jsdom) globals, React Hooks. * - `eslint-config-prettier` last, so formatting stays with Prettier. * * eslint-plugin-jsx-a11y is not used: its latest release (6.10.2) declares @@ -81,6 +82,18 @@ export default defineConfig([ globals: { ...globals.node }, }, }, + // Admin StrictMode harness and tests: Node test runner with a jsdom window + { + files: ['tests/admin/**/*.{mjs,jsx}'], + extends: [js.configs.recommended, reactHooks.configs.flat.recommended], + languageOptions: { + ecmaVersion: 'latest', + sourceType: 'module', + parserOptions: { ecmaFeatures: { jsx: true } }, + globals: { ...globals.node, ...globals.browser }, + }, + rules: { 'no-unused-vars': unusedVars }, + }, // Playwright evaluate callbacks run in the browser { files: ['scripts/acceptance/**/*.cjs'], diff --git a/package-lock.json b/package-lock.json index 6ec285d..21ca66a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -29,10 +29,12 @@ "@types/qs": "^6.15.1", "@types/react": "^18.3.31", "@types/react-dom": "^18.3.7", + "esbuild": "^0.28.2", "eslint": "^10.14.0", "eslint-config-prettier": "^10.1.8", "eslint-plugin-react-hooks": "^7.1.1", "globals": "^17.14.0", + "jsdom": "^31.0.1", "prettier": "^3.9.10", "react": "^18.3.1", "react-dom": "^18.3.1", @@ -1968,6 +1970,24 @@ "node": "^20.19.0 || ^22.13.0 || >=24" } }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, "node_modules/@floating-ui/core": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", @@ -14552,6 +14572,33 @@ "node": ">=6.0.0" } }, + "node_modules/bcp-47": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/bcp-47/-/bcp-47-2.1.2.tgz", + "integrity": "sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/bcp-47-match": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-2.0.3.tgz", + "integrity": "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/bcryptjs": { "version": "2.4.3", "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", @@ -16264,6 +16311,20 @@ "dev": true, "license": "MIT" }, + "node_modules/data-urls": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", + "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.1.2" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/date-fns": { "version": "2.30.0", "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.30.0.tgz", @@ -16315,6 +16376,13 @@ } } }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, "node_modules/decode-named-character-reference": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz", @@ -19092,6 +19160,19 @@ "node": "20 || >=22" } }, + "node_modules/html-encoding-sniffer": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", + "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.15.1" + }, + "engines": { + "node": "^22.13.0 || >=24.0.0" + } + }, "node_modules/html-entities": { "version": "2.6.0", "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-2.6.0.tgz", @@ -20124,6 +20205,13 @@ "node": ">=0.10.0" } }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, "node_modules/is-regex": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", @@ -20483,6 +20571,90 @@ "node": "^14.17.0 || ^16.13.0 || >=18.0.0" } }, + "node_modules/jsdom": { + "version": "31.0.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-31.0.1.tgz", + "integrity": "sha512-CbhJL8ZQg3eKswxSZth4QO9tW0jPIhmR0vtSXQSbKSfWbwIT6hoRc17wdHIVTQ43KI0mdV5iTJr3281IDgVZ5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "bcp-47": "^2.1.2", + "bcp-47-match": "^2.0.3", + "data-urls": "^8.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^7.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3", + "parse5": "^8.1.0", + "parse5-parser-stream": "^8.1.0", + "saxes": "^6.0.0", + "tough-cookie": "^6.0.2", + "undici": "^8.12.3", + "w3c-xmlserializer": "^6.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.3.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "@napi-rs/canvas": "^1.0.13" + }, + "peerDependenciesMeta": { + "@napi-rs/canvas": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/entities": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/jsdom/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/jsdom/node_modules/parse5": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", + "integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^9.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/jsdom/node_modules/undici": { + "version": "8.12.4", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.4.tgz", + "integrity": "sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, "node_modules/jsesc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", @@ -26095,6 +26267,45 @@ "dev": true, "license": "MIT" }, + "node_modules/parse5-parser-stream": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-8.1.1.tgz", + "integrity": "sha512-hMcVbbUJcQmP8rURWUdYrT1flRiBiBVjq/RYGguJpDUgIXSqdYKlE0CxthmdMWoSlBAuL5bUBa73g0pttSy7Hw==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse5": "^8.1.1" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-parser-stream/node_modules/entities": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/parse5-parser-stream/node_modules/parse5": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", + "integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^9.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -28463,6 +28674,19 @@ "dev": true, "license": "MIT" }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, "node_modules/scheduler": { "version": "0.23.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.0.tgz", @@ -30101,6 +30325,26 @@ "dev": true, "license": "MIT" }, + "node_modules/tldts": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.5.4.tgz", + "integrity": "sha512-Rn2ABgjHZrA+jzqom5zhxA0hLohzYrIgfCPyhpTUxqsUrcsBYuab49LseR9waB9Jr8/MxdodvMHA91oRiGLO3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.5.4" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.5.4.tgz", + "integrity": "sha512-9+4zWtKEDZ3V3FoZ1B97rv+5z5oqp7yeXGVze3CxgQ+CJro9do9DCPD00wxstYZDXDMXsurkBerFfiB6GYtPbA==", + "dev": true, + "license": "MIT" + }, "node_modules/tmp": { "version": "0.2.7", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", @@ -30177,6 +30421,32 @@ "nodetouch": "bin/nodetouch.js" } }, + "node_modules/tough-cookie": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.1.0.tgz", + "integrity": "sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", + "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/traverse": { "version": "0.6.8", "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.6.8.tgz", @@ -31483,6 +31753,19 @@ "dev": true, "license": "MIT" }, + "node_modules/w3c-xmlserializer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", + "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, "node_modules/watchpack": { "version": "2.6.1", "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.6.1.tgz", @@ -31513,6 +31796,16 @@ "dev": true, "license": "Apache-2.0" }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, "node_modules/webpack": { "version": "5.109.2", "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.109.2.tgz", @@ -31691,6 +31984,31 @@ "node": ">=10.13.0" } }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "17.3.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz", + "integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "tr46": "^7.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -32021,6 +32339,23 @@ "fsevents": "*" } }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, "node_modules/xtend": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", diff --git a/package.json b/package.json index 2d49b55..04fed3b 100644 --- a/package.json +++ b/package.json @@ -52,6 +52,7 @@ "scripts": { "clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"", "test": "node --test tests/*.test.cjs", + "test:admin": "node --import ./tests/admin/harness/setup.mjs --test \"tests/admin/*.test.jsx\"", "test:ts:front": "tsc --noEmit -p admin/tsconfig.json", "test:ts:back": "tsc --noEmit -p server/tsconfig.json", "lint": "eslint .", @@ -86,10 +87,12 @@ "@types/qs": "^6.15.1", "@types/react": "^18.3.31", "@types/react-dom": "^18.3.7", + "esbuild": "^0.28.2", "eslint": "^10.14.0", "eslint-config-prettier": "^10.1.8", "eslint-plugin-react-hooks": "^7.1.1", "globals": "^17.14.0", + "jsdom": "^31.0.1", "prettier": "^3.9.10", "react": "^18.3.1", "react-dom": "^18.3.1", diff --git a/tests/admin/harness/fake-socket.mjs b/tests/admin/harness/fake-socket.mjs new file mode 100644 index 0000000..038b312 --- /dev/null +++ b/tests/admin/harness/fake-socket.mjs @@ -0,0 +1,120 @@ +/** + * Counting fake of `socket.io-client` 4.8 (`io(url, options)` returns a Socket with on/off/emit, + * connect/disconnect/close and `io` the Manager). Every socket that is created and not + * disconnected stays in `__strictHarness.resources.sockets`, so a test sees a leaked connection. + * Docs: https://socket.io/docs/v4/client-api/ + */ +const resources = () => globalThis.__strictHarness.resources; + +class FakeSocket { + /** + * @param {string} url - Server URL. + * @param {object} [options] - Client options. + */ + constructor(url, options = {}) { + this.kind = 'socket.io'; + this.url = String(url ?? ''); + this.options = options; + this.connected = false; + this.disconnected = true; + this.id = undefined; + this.handlers = new Map(); + this.emitted = []; + this.io = { + on: () => this.io, + off: () => this.io, + opts: options, + engine: { on() {}, off() {} }, + }; + this.origin = (new Error().stack || '').split('\n').slice(2, 6).join(' <- '); + if (options.autoConnect !== false) this.connect(); + } + connect() { + if (this.connected) return this; + this.connected = true; + this.disconnected = false; + resources().sockets.add(this); + return this; + } + open() { + return this.connect(); + } + disconnect() { + this.connected = false; + this.disconnected = true; + resources().sockets.delete(this); + return this; + } + close() { + return this.disconnect(); + } + on(event, handler) { + if (!this.handlers.has(event)) this.handlers.set(event, new Set()); + this.handlers.get(event).add(handler); + return this; + } + once(event, handler) { + const wrapped = (...args) => { + this.off(event, wrapped); + handler(...args); + }; + return this.on(event, wrapped); + } + off(event, handler) { + if (!event) this.handlers.clear(); + else if (!handler) this.handlers.delete(event); + else this.handlers.get(event)?.delete(handler); + return this; + } + removeAllListeners(event) { + return this.off(event); + } + onAny() { + return this; + } + offAny() { + return this; + } + emit(event, ...args) { + this.emitted.push({ event, args }); + return this; + } + timeout() { + return this; + } + emitWithAck(event, ...args) { + this.emitted.push({ event, args }); + return Promise.resolve(undefined); + } + /** + * Test helper: delivers a server event to the registered handlers. + * @param {string} event - Event name. + * @param {...unknown} args - Payload. + */ + receive(event, ...args) { + for (const handler of [...(this.handlers.get(event) || [])]) handler(...args); + } +} + +/** Every socket created in this test file, open or closed. */ +export const createdSockets = []; + +/** + * `io()` of socket.io-client. + * @param {string | object} [url] - Server URL or options. + * @param {object} [options] - Options. + * @returns {FakeSocket} Socket. + */ +export function io(url, options) { + const socket = typeof url === 'object' ? new FakeSocket('', url) : new FakeSocket(url, options); + createdSockets.push(socket); + return socket; +} +export const connect = io; +export const Socket = FakeSocket; +export class Manager { + socket(namespace, options) { + return io(namespace, options); + } +} +export default io; diff --git a/tests/admin/harness/index.jsx b/tests/admin/harness/index.jsx new file mode 100644 index 0000000..55476fe --- /dev/null +++ b/tests/admin/harness/index.jsx @@ -0,0 +1,523 @@ +/** + * React StrictMode harness for the plugin's admin entry points (RFC strapi/strapi#27897 StrictMode, + * #25739 React 19). + * + * `renderStrict(ui)` mounts `ui` inside `` and the provider tree Strapi 5.62 + * uses for its own admin tests (`@strapi/admin/dist/admin/admin/tests/utils.mjs`, `Providers`): + * data router (createMemoryRouter), StrapiAppProvider, Redux store with `adminApi`, + * LanguageProvider, Theme (Design System light/dark), NotificationsProvider, AuthProvider, + * react-query QueryClientProvider, react-dnd DndProvider, GuidedTourContext, + * ConfigurationProvider and AppInfoProvider. These providers are not in the package's `exports` + * map, so they are imported by file path; Strapi's own test utils need jest and msw, which this + * repository does not use. Every `@strapi/strapi/admin` component and hook the plugin imports is + * the real one: the package loads unchanged through loader.mjs. + * + * In StrictMode React mounts every component, runs each effect's cleanup, and mounts again + * (react.dev/reference/react/StrictMode). Assertions: + * - `expectNoDuplicateRequests`: no mutation (POST/PUT/PATCH/DELETE) twice, no GET twice unless the + * first copy was aborted by the effect cleanup or the test lists it with a reason. + * - `unmount()` + `expectNoLeaks`: no interval, animation frame, window/document/body listener, + * WebSocket/EventSource/BroadcastChannel/socket.io connection or Resize/Intersection observer + * left behind, and no pending plugin timeout. Resources Strapi's own providers leave behind + * (measured once per file with an empty tree) are not counted. + * - `expectNoConsole`: no console.error/console.warn and no uncaught error, apart from messages the + * providers alone print (measured in the same calibration run). + */ +import path from 'node:path'; +import { createRequire } from 'node:module'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import * as React from 'react'; +import { createRoot } from 'react-dom/client'; +import { configureStore } from '@reduxjs/toolkit'; +import { darkTheme, lightTheme } from '@strapi/design-system'; +import { DndProvider } from 'react-dnd'; +import { HTML5Backend } from 'react-dnd-html5-backend'; +import { QueryClient, QueryClientProvider, setLogger } from 'react-query'; +import { Provider as ReduxProvider } from 'react-redux'; +import { createMemoryRouter, RouterProvider } from 'react-router-dom'; +import { installNetwork, network } from './network.mjs'; + +export { network }; +export { createdSockets } from './fake-socket.mjs'; + +const harnessDir = path.dirname(fileURLToPath(import.meta.url)); +const repoRoot = path.resolve(harnessDir, '../../..'); +const requireFromRepo = createRequire(path.join(repoRoot, 'package.json')); +const adminDist = path.join( + path.dirname(requireFromRepo.resolve('@strapi/admin/package.json')), + 'dist/admin/admin/src' +); +/** + * Imports a module of the installed @strapi/admin by file path (same URL as the package's own + * relative imports, so the same module instance and React contexts). + * @param {string} file - Path below dist/admin/admin/src. + * @returns {Promise} Module namespace. + */ +const adminModule = (file) => import(pathToFileURL(path.join(adminDist, file)).href); + +const [ + { GuidedTourContext }, + { LanguageProvider }, + { Theme }, + { RBAC }, + { AppInfoProvider }, + { AuthProvider }, + { _internalConfigurationContextProvider: ConfigurationContextProvider }, + { NotificationsProvider }, + { StrapiAppProvider }, + { reducer }, + { adminApi }, +] = await Promise.all( + [ + adminModule('components/GuidedTour/Context.mjs'), + adminModule('components/LanguageProvider.mjs'), + adminModule('components/Theme.mjs'), + adminModule('core/apis/rbac.mjs'), + adminModule('features/AppInfo.mjs'), + adminModule('features/Auth.mjs'), + adminModule('features/Configuration.mjs'), + adminModule('features/Notifications.mjs'), + adminModule('features/StrapiApp.mjs'), + 'reducer.mjs', + 'services/api.mjs', + ].map((entry) => (typeof entry === 'string' ? adminModule(entry) : entry)) +); + +setLogger({ log: () => {}, warn: () => {}, error: () => {} }); +installNetwork(repoRoot); + +const { resources, window } = globalThis.__strictHarness; +const nativeAddListener = window.EventTarget.prototype.addEventListener; + +// Console and uncaught errors. +const consoleMessages = []; +for (const level of ['error', 'warn']) { + const original = console[level].bind(console); + console[level] = (...args) => { + const text = args + .map((arg) => + arg instanceof Error + ? arg.stack || arg.message + : typeof arg === 'string' + ? arg + : safeJson(arg) + ) + .join(' '); + consoleMessages.push({ level, text }); + if (process.env.STRICT_HARNESS_VERBOSE) original(...args); + }; +} +nativeAddListener.call(window, 'error', (event) => { + consoleMessages.push({ level: 'uncaught', text: String(event.error?.stack || event.message) }); +}); +process.on('unhandledRejection', (reason) => { + consoleMessages.push({ level: 'unhandledRejection', text: String(reason?.stack || reason) }); +}); + +/** + * JSON for console arguments, tolerant of cycles. + * @param {unknown} value - Value. + * @returns {string} Text. + */ +function safeJson(value) { + try { + return JSON.stringify(value); + } catch { + return String(value); + } +} + +const ADMIN_USER = { + id: 1, + documentId: 'admin-user-1', + firstname: 'Ada', + lastname: 'Example', + username: null, + email: 'ada@example.test', + isActive: true, + blocked: false, + preferedLanguage: 'en', + roles: [{ id: 1, name: 'Super Admin', code: 'strapi-super-admin' }], +}; + +/** + * Answers the requests Strapi's own providers make (AuthProvider: users/me and permissions). + * @param {object[]} permissions - Permissions of the signed-in admin. + */ +const installCoreRoutes = (permissions) => { + network.on('GET', '/admin/users/me', { data: ADMIN_USER }); + network.on('GET', '/admin/users/me/permissions', { data: permissions }); + network.on('POST', '/admin/permissions/check', (call) => ({ + data: (call.json()?.permissions || []).map(() => true), + })); +}; + +/** + * Builds a permission entry as the admin API returns it. + * @param {string} action - Action uid. + * @param {string | null} [subject] - Subject uid. + * @returns {object} Permission. + */ +export const permission = (action, subject = null) => ({ + id: Math.floor(Math.random() * 1e6), + action, + subject, + properties: {}, + conditions: [], + actionParameters: {}, +}); + +/** + * Lets effects, fetch promises and short timers run inside `act`. + * @param {number} [rounds] - Number of macrotask rounds. + * @param {number} [ms] - Delay per round. + */ +export const settle = async (rounds = 6, ms = 5) => { + for (let index = 0; index < rounds; index += 1) { + await React.act(async () => { + await new Promise((resolve) => setTimeout(resolve, ms)); + }); + } +}; + +/** + * Copies the live resource sets. + * @returns {object} Snapshot of resource identities. + */ +export const snapshotResources = () => ({ + intervals: new Set(resources.intervals.keys()), + timeouts: new Set(resources.timeouts.keys()), + frames: new Set(resources.frames.keys()), + listeners: new Set(resources.listeners.keys()), + sockets: new Set(resources.sockets), + observers: new Set(resources.observers), +}); + +/** + * Resources created after `before` that still exist. + * @param {object} before - Snapshot taken before mounting. + * @returns {Array<{ kind: string, label: string, origin: string }>} Leftovers. + */ +const leftoversSince = (before) => { + const out = []; + for (const [id, entry] of resources.intervals) + if (!before.intervals.has(id)) + out.push({ kind: 'interval', label: `${entry.delay}ms`, origin: entry.origin }); + for (const [id, entry] of resources.timeouts) + if (!before.timeouts.has(id)) + out.push({ kind: 'timeout', label: `${entry.delay}ms`, origin: entry.origin }); + for (const [id, entry] of resources.frames) + if (!before.frames.has(id)) + out.push({ kind: 'animationFrame', label: '', origin: entry.origin }); + for (const [id, entry] of resources.listeners) + if (!before.listeners.has(id)) + out.push({ kind: 'listener', label: `${entry.target}:${entry.type}`, origin: entry.origin }); + for (const socket of resources.sockets) + if (!before.sockets.has(socket)) + out.push({ kind: socket.kind, label: socket.url, origin: socket.origin }); + for (const observer of resources.observers) + if (!before.observers.has(observer)) + out.push({ kind: observer.kind, label: '', origin: observer.origin }); + return out; +}; + +const signature = (entry) => `${entry.kind}|${entry.label}|${entry.origin}`; + +let calibration = null; + +/** + * Mounts the providers alone once per file and records what they leave behind and print, so the + * plugin assertions only count the plugin's own resources and messages. + * @returns {Promise<{ leftovers: Set, messages: Set }>} Baseline. + */ +const calibrate = async () => { + if (calibration) return calibration; + calibration = { leftovers: new Set(), messages: new Set() }; + const startMessages = consoleMessages.length; + const before = snapshotResources(); + const handle = await mount(null, { permissions: [] }); + await handle.unmount(); + for (const entry of leftoversSince(before)) calibration.leftovers.add(signature(entry)); + for (const message of consoleMessages.slice(startMessages)) + calibration.messages.add(message.text); + return calibration; +}; + +/** + * Mounts a tree in StrictMode with Strapi's admin providers. + * @param {React.ReactNode} ui - Tree to render. + * @param {object} options - See renderStrict. + * @returns {Promise} Mounted handle. + */ +async function mount(ui, options) { + const { + path: initialPath = '/', + routePath = '/*', + permissions = [], + strict = true, + plugins = {}, + getPlugin, + locale = 'en', + messages = {}, + } = options; + installCoreRoutes(permissions); + window.strapi = { + backendURL: 'http://localhost:1337', + isEE: false, + features: { isEnabled: () => false, SSO: 'sso', AUDIT: 'audit-logs' }, + featureFlags: { isEnabled: () => false }, + future: { isEnabled: () => false }, + flags: { nps: false, promoteEE: false, docLinks: false }, + projectType: 'Community', + telemetryDisabled: true, + }; + window.localStorage.setItem('jwtToken', JSON.stringify('harness-token')); + + const store = configureStore({ + preloadedState: { + admin_app: { + language: { locale, localeNames: { en: 'English' } }, + permissions: {}, + theme: { availableThemes: [], currentTheme: 'light' }, + token: 'harness-token', + }, + }, + reducer: { [adminApi.reducerPath]: adminApi.reducer, admin_app: reducer }, + middleware: (getDefaultMiddleware) => + getDefaultMiddleware({ immutableCheck: false, serializableCheck: false }).concat( + adminApi.middleware + ), + }); + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const noop = () => {}; + const element = ( + [], register: noop }} + customFields={{ customFields: {}, get: () => undefined, getAll: () => ({}), register: noop }} + fields={{}} + menu={[]} + getAdminInjectedComponents={() => []} + getPlugin={getPlugin || ((id) => plugins[id])} + plugins={plugins} + runHookParallel={noop} + runHookWaterfall={(_name, initialValue) => initialValue} + runHookSeries={noop} + settings={{}} + > + + + + + + + + + + + {ui} + + + + + + + + + + + + ); + const router = createMemoryRouter([{ path: routePath, element }], { + initialEntries: [initialPath], + }); + const container = document.createElement('div'); + document.body.appendChild(container); + const root = createRoot(container, { + onRecoverableError: (error) => + consoleMessages.push({ level: 'recoverable', text: String(error?.stack || error) }), + }); + const tree = ; + await React.act(async () => { + root.render(strict ? {tree} : tree); + }); + await settle(); + let mounted = true; + return { + container, + router, + store, + queryClient, + /** Unmounts the tree, tears the harness router/store down and lets cleanups run. */ + async unmount() { + if (!mounted) return; + mounted = false; + await React.act(async () => root.unmount()); + router.dispose(); + queryClient.clear(); + store.dispatch(adminApi.util.resetApiState()); + container.remove(); + window.localStorage.clear(); + await settle(4, 10); + }, + }; +} + +/** + * Renders a plugin entry point in StrictMode with Strapi's admin providers and records what it + * does while mounting. + * @param {React.ReactNode} ui - Element to render (page, widget, injected component, side panel). + * @param {object} [options] - Options. + * @param {string} [options.path] - Initial router location. + * @param {string} [options.routePath] - Route pattern the tree renders under (default `/*`), for + * components that read route params (`/content-manager/:collectionType/:slug/:id`). + * @param {object[]} [options.permissions] - Permissions of the admin (see `permission()`). + * @param {Record} [options.plugins] - Plugins for `useStrapiApp().getPlugin`. + * @param {Record} [options.messages] - Translations. + * @returns {Promise} Handle: container, unmount, mountCalls, before (resource snapshot). + */ +export async function renderStrict(ui, options = {}) { + await calibrate(); + network.clearCalls(); + const before = snapshotResources(); + const startMessages = consoleMessages.length; + const handle = await mount(ui, options); + return { + ...handle, + /** Unmounts and forgets the test's network routes. */ + async unmount() { + await handle.unmount(); + network.reset(); + }, + before, + startMessages, + /** Requests made while mounting (StrictMode mount, cleanup, mount). */ + mountCalls: [...network.calls], + }; +} + +/** + * Fails when plugin code sent the same mutation twice, or the same GET twice without aborting the + * first copy and without an explicit allowance. + * @param {Array} calls - Recorded calls (handle.mountCalls or network.calls). + * @param {object} [options] - Options. + * @param {Array<{ path: string | RegExp, reason: string }>} [options.allowDuplicateGets] - GETs the + * plugin may repeat (idempotent reads), each with the reason. + */ +export function expectNoDuplicateRequests(calls, { allowDuplicateGets = [] } = {}) { + const groups = new Map(); + for (const call of calls.filter((entry) => entry.fromPlugin)) { + const key = `${call.method} ${call.path} ${call.method === 'GET' ? '' : (call.body ?? '')}`; + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(call); + } + const problems = []; + for (const [key, group] of groups) { + if (group.length < 2) continue; + const [first] = group; + if (first.method !== 'GET') { + problems.push(`${group.length}x ${key.trim()} (mutation sent more than once)`); + continue; + } + const live = group.filter((call) => !call.aborted); + if (live.length <= 1) continue; + const allowed = allowDuplicateGets.find((entry) => + entry.path instanceof RegExp ? entry.path.test(first.path) : entry.path === first.pathname + ); + if (allowed) { + if (!allowed.reason) problems.push(`allowance for ${first.path} has no reason`); + continue; + } + problems.push(`${live.length}x GET ${first.path} (not aborted by the effect cleanup)`); + } + if (problems.length) + throw new Error(`Duplicate requests in StrictMode:\n ${problems.join('\n ')}`); +} + +/** + * Fails when the unmounted tree left resources behind (see module docs). + * @param {object} handle - Handle from renderStrict (after `await handle.unmount()`). + * @param {object} [options] - Options. + * @param {Array<{ match: RegExp, reason: string }>} [options.allow] - Leftovers that are expected, + * matched against `kind label origin`, each with a reason. + */ +export function expectNoLeaks(handle, { allow = [] } = {}) { + const leftovers = leftoversSince(handle.before).filter((entry) => { + if (calibration.leftovers.has(signature(entry))) return false; + // A pending timeout is a leak only when plugin code set it (library caches expire on their own). + if (entry.kind === 'timeout' && entry.origin.startsWith('lib:')) return false; + // React DOM delegates events on every root and portal container (document.body for + // dialogs and popovers) and never removes those listeners, by design. + if (entry.kind === 'listener' && entry.origin.startsWith('lib:react-dom/')) return false; + const text = `${entry.kind} ${entry.label} ${entry.origin}`; + return !allow.some((rule) => rule.match.test(text)); + }); + if (leftovers.length) { + throw new Error( + `Resources left after unmount:\n ${leftovers + .map((entry) => `${entry.kind} ${entry.label} from ${entry.origin}`) + .join('\n ')}` + ); + } +} + +/** + * Fails on console errors/warnings and uncaught errors since the handle was mounted. + * @param {object} handle - Handle from renderStrict. + * @param {object} [options] - Options. + * @param {Array<{ match: RegExp, reason: string }>} [options.allow] - Third-party messages that are + * expected, each with a reason. + */ +export function expectNoConsole(handle, { allow = [] } = {}) { + const messages = consoleMessages + .slice(handle.startMessages) + .filter((message) => !calibration.messages.has(message.text)) + .filter((message) => !allow.some((rule) => rule.match.test(message.text))); + if (messages.length) { + throw new Error( + `Console output while mounted:\n ${messages + .map( + (message) => `[${message.level}] ${message.text.split('\n').slice(0, 6).join('\n ')}` + ) + .join('\n ')}` + ); + } +} + +/** + * Renders, unmounts and runs all three assertions: the standard StrictMode check of one entry + * point. + * @param {React.ReactNode} ui - Element. + * @param {object} [options] - renderStrict options plus `allowDuplicateGets`, `allowLeaks`, + * `allowConsole` and `whileMounted(handle)` (interactions before unmount). + * @returns {Promise} The unmounted handle (calls, container snapshot). + */ +export async function checkStrictEntry(ui, options = {}) { + const handle = await renderStrict(ui, options); + let html; + let calls; + try { + if (options.whileMounted) await options.whileMounted(handle); + } finally { + // Unmount also after a failed interaction, so live intervals do not keep the process alive. + html = handle.container.innerHTML; + calls = [...network.calls]; + await handle.unmount(); + } + expectNoConsole(handle, { allow: options.allowConsole }); + expectNoDuplicateRequests(handle.mountCalls, { allowDuplicateGets: options.allowDuplicateGets }); + expectNoLeaks(handle, { allow: options.allowLeaks }); + return { ...handle, html, calls }; +} diff --git a/tests/admin/harness/loader.mjs b/tests/admin/harness/loader.mjs new file mode 100644 index 0000000..0791135 --- /dev/null +++ b/tests/admin/harness/loader.mjs @@ -0,0 +1,297 @@ +/** + * Node module customization hooks for the admin StrictMode harness. + * + * Runs in the loader thread (`module.register`, Node >= 20.6). It lets `node --test` import the + * plugin's admin sources the way the Strapi admin bundler (Vite) does: + * + * - JSX/TSX/TS under the repository (outside node_modules) is transpiled with esbuild + * (`jsx: 'automatic'`) and loaded as ES modules, even in a `"type": "commonjs"` package. + * - Extensionless and directory specifiers resolve like a bundler (`./Foo` -> `./Foo.tsx`, + * `./dir` -> `./dir/index.jsx`), also inside node_modules packages that ship bundler-style ESM. + * - JSON imports without import attributes become `export default `; CSS and image imports + * become empty or string modules. + * - `aliases` (passed from setup.mjs) swap modules, for example `socket.io-client` for a counting + * fake. + * - CommonJS dependencies imported from ESM get a wrapper with every runtime export, and a bare + * package import prefers the package's `module` entry, as Vite does for the Strapi admin. + * + * Docs: https://nodejs.org/docs/latest-v22.x/api/module.html#customization-hooks and + * https://esbuild.github.io/api/#transform (esbuild 0.28). + */ +import { readFile, stat } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { createRequire } from 'node:module'; +import { transform } from 'esbuild'; + +const CJS_INTEROP = 'strict-harness-cjs'; + +/** @type {{ root: string, aliases: Record }} */ +let config = { root: process.cwd(), aliases: {} }; + +const SOURCE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mjs']; +const RESOLVE_EXTENSIONS = [...SOURCE_EXTENSIONS, '.json', '.cjs']; +const ASSET_EXTENSIONS = new Set([ + '.css', + '.svg', + '.png', + '.jpg', + '.jpeg', + '.gif', + '.webp', + '.woff', + '.woff2', +]); + +/** + * Receives the harness configuration from `module.register(..., { data })`. + * @param {{ root: string, aliases: Record }} data - Repository root and aliases. + */ +export function initialize(data) { + if (data) config = { ...config, ...data }; +} + +/** + * Whether a file belongs to the repository sources the harness transpiles. + * @param {string} filePath - Absolute path. + * @returns {boolean} True for repository files outside node_modules. + */ +const isRepoSource = (filePath) => + filePath.startsWith(config.root + path.sep) && + !filePath.includes(`${path.sep}node_modules${path.sep}`); + +/** + * Checks that a path is an existing file. + * @param {string} candidate - Absolute path. + * @returns {Promise} True for a file. + */ +const isFile = async (candidate) => { + try { + return (await stat(candidate)).isFile(); + } catch { + return false; + } +}; + +/** + * Bundler-style lookup: the path itself, the path plus an extension, then `index.*`. + * @param {string} base - Absolute path without or with extension. + * @returns {Promise} Resolved file or null. + */ +const bundlerLookup = async (base) => { + if (await isFile(base)) return base; + // A directory with its own package.json (`@reduxjs/toolkit/query/react`): its ESM entry. + try { + const manifest = JSON.parse(await readFile(path.join(base, 'package.json'), 'utf8')); + const entry = manifest.module || manifest.main; + if (entry && (await isFile(path.join(base, entry)))) return path.join(base, entry); + } catch { + // no nested package.json + } + for (const extension of RESOLVE_EXTENSIONS) + if (await isFile(base + extension)) return base + extension; + for (const extension of RESOLVE_EXTENSIONS) { + const index = path.join(base, `index${extension}`); + if (await isFile(index)) return index; + } + return null; +}; + +const esmCache = new Map(); + +/** + * Whether a file is evaluated as an ES module: `.mjs`, a transpiled repository source, or `.js` + * with ESM syntax (Node 22 detects module syntax in ambiguous `.js` files, as in + * `@reduxjs/toolkit/dist/query/rtk-query.esm.js`). + * @param {string} filePath - Absolute path. + * @returns {Promise} True for ESM. + */ +const isEsmFile = async (filePath) => { + if (filePath.endsWith('.mjs') || isRepoSource(filePath)) return true; + if (!filePath.endsWith('.js')) return false; + if (!esmCache.has(filePath)) { + const code = await readFile(filePath, 'utf8').catch(() => ''); + esmCache.set(filePath, /^\s*(import\s[\s\S]*?from\s|import\s*['"{*]|export\s)/m.test(code)); + } + return esmCache.get(filePath); +}; + +/** + * Finds the directory of an installed package the way Node does (nearest node_modules upwards). + * @param {string} packageName - Package name. + * @param {string} fromPath - Importing file. + * @returns {Promise} Package directory. + */ +const findPackageRoot = async (packageName, fromPath) => { + let directory = path.dirname(fromPath); + while (directory !== path.dirname(directory)) { + const packageRoot = path.join(directory, 'node_modules', packageName); + if (await isFile(path.join(packageRoot, 'package.json'))) return packageRoot; + directory = path.dirname(directory); + } + return null; +}; + +/** + * Vite's `mainFields` (module before main): a bare package import without an `exports` map + * resolves to the package's `module` (ESM) entry, as in the Strapi admin build. + * @param {string} specifier - Bare specifier. + * @param {string} parentPath - Importing file. + * @returns {Promise} ESM entry or null. + */ +const packageModuleEntry = async (specifier, parentPath) => { + if (specifier.startsWith('.') || specifier.startsWith('node:') || path.isAbsolute(specifier)) + return null; + const parts = specifier.split('/'); + const isScoped = specifier.startsWith('@'); + if (parts.length !== (isScoped ? 2 : 1)) return null; + const packageRoot = await findPackageRoot(specifier, parentPath); + if (!packageRoot) return null; + const manifest = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8')); + if (manifest.exports || typeof manifest.module !== 'string') return null; + const entry = path.join(packageRoot, manifest.module); + if (!(await isFile(entry))) return null; + if (entry.endsWith('.mjs') || manifest.type === 'module') return entry; + // A Babel-style `module` build (`.js` with ESM syntax, no `"type"`) loads as ESM too, as in Vite; + // Node detects module syntax in its other files. Loading the CommonJS `main` instead would + // require() a second copy of ESM-first dependencies (`@uiw/react-codemirror` -> + // `@codemirror/state` in the Design System's JSONInput). An explicit `"type": "commonjs"` stays. + return manifest.type === undefined && (await isEsmFile(entry)) ? entry : null; +}; + +/** + * Whether a resolved module is CommonJS: `.cjs`, or `.js` whose nearest package.json is not + * `"type": "module"`. + * @param {{ url: string, format?: string | null }} resolved - Result of the next resolver. + * @returns {Promise} True for CommonJS. + */ +const isCommonJs = async (resolved) => { + if (resolved.format === 'commonjs') return true; + if (resolved.format || !resolved.url.startsWith('file:')) return false; + const filePath = fileURLToPath(resolved.url); + if (filePath.endsWith('.cjs')) return true; + if (!filePath.endsWith('.js')) return false; + let directory = path.dirname(filePath); + while (directory !== path.dirname(directory)) { + try { + const manifest = JSON.parse(await readFile(path.join(directory, 'package.json'), 'utf8')); + return manifest.type !== 'module'; + } catch { + directory = path.dirname(directory); + } + } + return true; +}; + +/** + * Resolve hook: aliases first, then Node's resolver, then bundler-style fallback. + * @param {string} specifier - Import specifier. + * @param {object} context - Resolve context. + * @param {Function} nextResolve - Next hook. + * @returns {Promise} Resolution. + */ +export async function resolve(specifier, context, nextResolve) { + const alias = config.aliases[specifier]; + if (alias && context.parentURL !== pathToFileURL(alias).href) { + return { url: pathToFileURL(alias).href, shortCircuit: true }; + } + const parentPath = context.parentURL?.startsWith('file:') + ? fileURLToPath(context.parentURL) + : null; + if (parentPath && (specifier.startsWith('./') || specifier.startsWith('../'))) { + const found = await bundlerLookup(path.resolve(path.dirname(parentPath), specifier)); + if (found) return { url: pathToFileURL(found).href, shortCircuit: true }; + } + const moduleEntry = parentPath ? await packageModuleEntry(specifier, parentPath) : null; + if (moduleEntry) + return { url: pathToFileURL(moduleEntry).href, format: 'module', shortCircuit: true }; + try { + const resolved = await nextResolve(specifier, context); + // Vite pre-bundles CommonJS dependencies so ESM code can use their named exports + // (`import { assignWith } from 'lodash'` in the Design System). Node's static CJS analysis + // misses many of them, so ESM importers get a generated wrapper with every runtime key. + const parentIsEsm = parentPath && (await isEsmFile(parentPath)); + if (parentIsEsm && (await isCommonJs(resolved))) { + return { ...resolved, url: `${resolved.url}?${CJS_INTEROP}`, format: 'module' }; + } + return resolved; + } catch (error) { + // Bundler-style deep imports inside packages (`lodash/get`, `date-fns/locale`). + if ( + !['ERR_MODULE_NOT_FOUND', 'ERR_UNSUPPORTED_DIR_IMPORT'].includes(error?.code) || + specifier.startsWith('.') || + !parentPath + ) + throw error; + const parts = specifier.split('/'); + const packageName = specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]; + const rest = parts.slice(specifier.startsWith('@') ? 2 : 1).join('/'); + let directory = path.dirname(parentPath); + while (directory !== path.dirname(directory)) { + const packageRoot = path.join(directory, 'node_modules', packageName); + if (await isFile(path.join(packageRoot, 'package.json'))) { + const found = await bundlerLookup(path.join(packageRoot, rest)); + if (found) return { url: pathToFileURL(found).href, shortCircuit: true }; + break; + } + directory = path.dirname(directory); + } + throw error; + } +} + +/** + * Load hook: transpile repository sources, turn JSON and assets into ES modules. + * @param {string} url - Module URL. + * @param {object} context - Load context. + * @param {Function} nextLoad - Next hook. + * @returns {Promise} Module source. + */ +export async function load(url, context, nextLoad) { + if (!url.startsWith('file:')) return nextLoad(url, context); + if (url.endsWith(`?${CJS_INTEROP}`)) { + const filePath = fileURLToPath(url.slice(0, -CJS_INTEROP.length - 1)); + let keys = []; + try { + keys = Object.keys(createRequire(filePath)(filePath)).filter((key) => + /^[A-Za-z_$][\w$]*$/.test(key) + ); + } catch { + // A module that needs the DOM to evaluate: only the default export. + } + const named = keys.filter((key) => key !== 'default'); + const source = [ + `import { createRequire } from 'node:module';`, + `const mod = createRequire(${JSON.stringify(filePath)})(${JSON.stringify(filePath)});`, + // Like Vite/esbuild interop: a transpiled ES module (`__esModule`) exposes its own default. + `export default mod && mod.__esModule && 'default' in mod ? mod.default : mod;`, + ...named.map((key) => `export const ${key} = mod[${JSON.stringify(key)}];`), + ].join('\n'); + return { format: 'module', source, shortCircuit: true }; + } + const filePath = fileURLToPath(url); + const extension = path.extname(filePath); + if (ASSET_EXTENSIONS.has(extension)) { + const source = + extension === '.css' ? 'export default {};' : `export default ${JSON.stringify(filePath)};`; + return { format: 'module', source, shortCircuit: true }; + } + if (extension === '.json' && !context.importAttributes?.type) { + const json = await readFile(filePath, 'utf8'); + return { format: 'module', source: `export default ${json};`, shortCircuit: true }; + } + if (isRepoSource(filePath) && SOURCE_EXTENSIONS.includes(extension)) { + const code = await readFile(filePath, 'utf8'); + const loader = extension === '.ts' ? 'ts' : extension === '.tsx' ? 'tsx' : 'jsx'; + const result = await transform(code, { + loader, + format: 'esm', + jsx: 'automatic', + target: 'node22', + sourcefile: filePath, + sourcemap: 'inline', + }); + return { format: 'module', source: result.code, shortCircuit: true }; + } + return nextLoad(url, context); +} diff --git a/tests/admin/harness/network.mjs b/tests/admin/harness/network.mjs new file mode 100644 index 0000000..fb4f0bd --- /dev/null +++ b/tests/admin/harness/network.mjs @@ -0,0 +1,178 @@ +/** + * Fake network for the harness: replaces `fetch`, records every request with its initiator and + * whether it was aborted, and answers from route handlers. Strapi's `useFetchClient` + * (`getFetchClient` in @strapi/admin 5.62) and RTK Query both end in `window.fetch`, so this is + * the only network boundary of the admin. + */ + +const BACKEND = 'http://localhost:1337'; + +/** + * @typedef {object} RecordedCall + * @property {string} method - Upper-case HTTP method. + * @property {string} path - Path and query relative to the backend. + * @property {string} pathname - Path without query. + * @property {string | null} body - Request body as text. + * @property {boolean} aborted - The request's signal was aborted. + * @property {boolean} fromPlugin - Initiated by code in this repository (stack attribution). + * @property {boolean} handled - A route handler answered it. + * @property {boolean} [completed] - A response was delivered (a later abort no longer counts). + */ + +/** @type {RecordedCall[]} */ +const calls = []; +/** @type {Array<{ method: string, match: string | RegExp | ((path: string) => boolean), reply: Function }>} */ +let routes = []; +let repoRoot = ''; + +/** + * Whether the current stack contains a frame from the repository (not node_modules, not harness). + * @returns {boolean} True when plugin code initiated the call. + */ +const initiatedByPlugin = () => + (new Error().stack || '') + .split('\n') + .map((line) => decodeURIComponent(line)) + .some( + (line) => + repoRoot && + line.includes(repoRoot) && + !line.includes('node_modules') && + !line.includes('/tests/admin/') + ); + +/** + * Matches a route against method and path. + * @param {{ method: string, match: string | RegExp | Function }} route - Route. + * @param {string} method - Method. + * @param {string} path - Path with query. + * @param {string} pathname - Path without query. + * @returns {boolean} Match. + */ +const matches = (route, method, path, pathname) => { + if (route.method !== '*' && route.method !== method) return false; + if (typeof route.match === 'string') return route.match === pathname || route.match === path; + if (route.match instanceof RegExp) return route.match.test(path); + return Boolean(route.match(path, method)); +}; + +/** + * The fake `fetch`. + * @param {string | URL | Request} input - URL or request. + * @param {RequestInit} [init] - Options. + * @returns {Promise} Response. + */ +async function fakeFetch(input, init = {}) { + const url = new URL(typeof input === 'string' ? input : input.url || String(input), BACKEND); + const method = String( + init.method || (typeof input === 'object' && input.method) || 'GET' + ).toUpperCase(); + let body = init.body ?? null; + if (body && typeof body !== 'string') + body = body instanceof FormData ? '[FormData]' : String(body); + /** @type {RecordedCall} */ + const call = { + method, + path: url.pathname + url.search, + pathname: url.pathname, + body, + aborted: false, + fromPlugin: initiatedByPlugin(), + handled: false, + }; + calls.push(call); + const signal = init.signal || (typeof input === 'object' ? input.signal : undefined); + const abortError = () => new DOMException('The operation was aborted.', 'AbortError'); + if (signal?.aborted) { + call.aborted = true; + throw abortError(); + } + const route = [...routes] + .reverse() + .find((entry) => matches(entry, method, call.path, call.pathname)); + call.handled = Boolean(route); + const answer = route + ? Promise.resolve( + route.reply({ + ...call, + json: () => (typeof body === 'string' ? JSON.parse(body) : body), + }) + ) + : Promise.resolve({ + status: 404, + body: { data: null, error: { status: 404, name: 'NotFoundError', message: 'Not Found' } }, + }); + // Like a browser, an abort rejects at once, even while the server is still answering. + let onAbort = () => {}; + const aborted = new Promise((_, reject) => { + onAbort = () => { + call.aborted = true; + reject(abortError()); + }; + }); + signal?.addEventListener('abort', onAbort, { once: true }); + let result; + try { + result = await Promise.race([answer, aborted]); + } finally { + signal?.removeEventListener('abort', onAbort); + } + const { status = 200, body: payload = null } = + result && typeof result === 'object' && 'status' in result && 'body' in result + ? result + : { body: result }; + // Answer on a later task so abort-on-unmount can win the race, as in a browser. + await new Promise((resolve) => queueMicrotask(resolve)); + if (signal?.aborted) { + call.aborted = true; + throw abortError(); + } + call.completed = true; + return new Response(payload === null ? null : JSON.stringify(payload), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +} + +/** + * Installs the fake fetch on window and the global object. + * @param {string} root - Repository root, for initiator attribution. + */ +export const installNetwork = (root) => { + repoRoot = root; + globalThis.fetch = fakeFetch; + globalThis.window.fetch = fakeFetch; +}; + +export const network = { + /** @returns {RecordedCall[]} Every request since the last reset. */ + get calls() { + return calls; + }, + /** + * Adds a route; later routes win. + * @param {string} method - HTTP method or '*'. + * @param {string | RegExp | Function} match - Path (without or with query), RegExp or predicate. + * @param {Function | object} reply - Body, `{ status, body }`, or a function returning either. + */ + on(method, match, reply) { + routes.push({ + method: method.toUpperCase(), + match, + reply: typeof reply === 'function' ? reply : () => reply, + }); + }, + /** Forgets recorded calls; routes stay. */ + clearCalls() { + calls.length = 0; + }, + /** Removes all routes and recorded calls. */ + reset() { + calls.length = 0; + routes = []; + }, + /** @returns {RecordedCall[]} Requests started by plugin code. */ + pluginCalls() { + return calls.filter((call) => call.fromPlugin); + }, +}; diff --git a/tests/admin/harness/setup.mjs b/tests/admin/harness/setup.mjs new file mode 100644 index 0000000..85d6b1a --- /dev/null +++ b/tests/admin/harness/setup.mjs @@ -0,0 +1,350 @@ +/** + * Preloaded with `node --import ./tests/admin/harness/setup.mjs --test ...`. + * + * 1. Creates a jsdom browser environment on the globals (window, document, navigator, DOM classes) + * before React, styled-components or the Design System are imported. + * 2. Instruments every resource a plugin component can leak and counts it: intervals, pending + * timeouts, animation frames, window/document listeners, WebSocket, EventSource, + * BroadcastChannel, ResizeObserver, IntersectionObserver, MutationObserver and fetch. + * 3. Registers the module hooks in loader.mjs (JSX/TS transpile, bundler-style resolution) with + * the module aliases below. + * + * Docs: jsdom 31 README (https://github.com/jsdom/jsdom#readme), React "act" testing + * (https://react.dev/reference/react/act: `IS_REACT_ACT_ENVIRONMENT`), Node customization hooks. + */ +import { existsSync } from 'node:fs'; +import { register } from 'node:module'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { JSDOM } from 'jsdom'; + +const harnessDir = path.dirname(fileURLToPath(import.meta.url)); +const root = path.resolve(harnessDir, '../../..'); + +/** + * Optional per-repository fakes: `tests/admin/harness.config.mjs` may export + * `aliases` (`{ specifier: 'path/relative/to/repo/root.mjs' }`). An alias file can import the + * real module under the same specifier (the loader does not alias the alias file itself). + */ +const localConfigFile = path.join(root, 'tests/admin/harness.config.mjs'); +const localConfig = existsSync(localConfigFile) + ? await import(pathToFileURL(localConfigFile).href) + : {}; + +/** Modules the plugin imports that the harness replaces with counting fakes. */ +const ALIASES = { + 'socket.io-client': path.join(harnessDir, 'fake-socket.mjs'), + ...Object.fromEntries( + Object.entries(localConfig.aliases || {}).map(([specifier, file]) => [ + specifier, + path.resolve(root, file), + ]) + ), +}; + +register(pathToFileURL(path.join(harnessDir, 'loader.mjs')), import.meta.url, { + data: { root, aliases: ALIASES }, +}); + +const dom = new JSDOM('', { + url: 'http://localhost:1337/admin/', + pretendToBeVisual: true, +}); +const { window } = dom; + +// Node's own globals (timers, fetch, AbortController, Event, URL, ...) stay; DOM classes come +// from jsdom. Timers are unified so `window.setTimeout` and `setTimeout` are the same instrumented +// functions. +for (const key of Object.getOwnPropertyNames(window)) { + if (key in globalThis || key.startsWith('_')) continue; + try { + globalThis[key] = window[key]; + } catch { + // read-only jsdom internals + } +} +// Node 25+ has its own Web Storage globals (`localStorage` is undefined without +// --localstorage-file), so the loop above skips them: use jsdom's storage. +for (const key of ['localStorage', 'sessionStorage']) { + Object.defineProperty(globalThis, key, { + value: window[key], + configurable: true, + writable: true, + }); +} +globalThis.window = window; +globalThis.document = window.document; +Object.defineProperty(globalThis, 'navigator', { value: window.navigator, configurable: true }); +// React DOM expects the jsdom event classes on `window` and on the global object to match. +// Abort signals must be jsdom's: components pass them to DOM `addEventListener({ signal })`. +for (const key of [ + 'Event', + 'CustomEvent', + 'EventTarget', + 'KeyboardEvent', + 'MouseEvent', + 'FocusEvent', + 'AbortController', + 'AbortSignal', +]) { + globalThis[key] = window[key]; +} +globalThis.IS_REACT_ACT_ENVIRONMENT = true; + +/** Live resource counters, read by index.jsx (`snapshotResources`). */ +const resources = { + intervals: new Map(), + timeouts: new Map(), + frames: new Map(), + listeners: new Map(), + sockets: new Set(), + observers: new Set(), +}; +globalThis.__strictHarness = { resources, window }; + +/** + * Records where a resource was created, to name the owner in a failure message. + * @returns {string} Stack lines of the caller in the repository (no node_modules). + */ +const origin = () => { + const frames = (new Error().stack || '') + .split('\n') + .slice(3) + .map((line) => decodeURIComponent(line).replace('file://', '')); + const own = frames + .filter( + (line) => line.includes(root) && !line.includes('node_modules') && !line.includes(harnessDir) + ) + .slice(0, 3) + .map((line) => + line + .trim() + .replace(/\?.*?(?=:\d+:\d+)/, '') + .replace(root, '.') + .replace(/^at /, '') + ); + if (own.length) return own.join(' <- '); + const library = frames.find((line) => line.includes('node_modules')); + if (!library) return 'lib:runtime'; + // Package path without line numbers, so the same call site matches across runs. + return `lib:${library.slice(library.lastIndexOf('node_modules/') + 13).replace(/:\d+:\d+\)?$/, '')}`; +}; + +const nodeSetTimeout = globalThis.setTimeout; +const nodeClearTimeout = globalThis.clearTimeout; +const nodeSetInterval = globalThis.setInterval; +const nodeClearInterval = globalThis.clearInterval; + +/** + * setTimeout that tracks pending timeouts until they run or are cleared. + * @param {Function} callback - Callback. + * @param {number} [delay] - Delay in ms. + * @param {...unknown} args - Arguments. + * @returns {ReturnType} Handle. + */ +function trackedSetTimeout(callback, delay, ...args) { + const handle = nodeSetTimeout( + (...callArgs) => { + resources.timeouts.delete(handle); + if (typeof callback === 'function') callback(...callArgs); + }, + delay, + ...args + ); + resources.timeouts.set(handle, { delay: Number(delay) || 0, origin: origin() }); + return handle; +} +function trackedClearTimeout(handle) { + resources.timeouts.delete(handle); + nodeClearTimeout(handle); +} +function trackedSetInterval(callback, delay, ...args) { + const handle = nodeSetInterval(callback, delay, ...args); + resources.intervals.set(handle, { delay: Number(delay) || 0, origin: origin() }); + return handle; +} +function trackedClearInterval(handle) { + resources.intervals.delete(handle); + nodeClearInterval(handle); +} +for (const target of [globalThis, window]) { + target.setTimeout = trackedSetTimeout; + target.clearTimeout = trackedClearTimeout; + target.setInterval = trackedSetInterval; + target.clearInterval = trackedClearInterval; +} + +let frameId = 0; +window.requestAnimationFrame = globalThis.requestAnimationFrame = (callback) => { + frameId += 1; + const id = frameId; + const handle = nodeSetTimeout(() => { + resources.frames.delete(id); + callback(performance.now()); + }, 16); + resources.frames.set(id, { handle, origin: origin() }); + return id; +}; +window.cancelAnimationFrame = globalThis.cancelAnimationFrame = (id) => { + const frame = resources.frames.get(id); + if (frame) nodeClearTimeout(frame.handle); + resources.frames.delete(id); +}; + +/** + * Counts listeners on long-lived targets (window, document, document.body). Listeners on + * elements inside the rendered tree go away with the tree and are not counted. + * @param {EventTarget} target - Target to instrument. + * @param {string} name - Name used in reports. + */ +const trackListeners = (target, name) => { + const add = target.addEventListener.bind(target); + const remove = target.removeEventListener.bind(target); + const keyOf = (type, listener, options) => { + const capture = typeof options === 'boolean' ? options : Boolean(options && options.capture); + return { type, listener, capture }; + }; + target.addEventListener = (type, listener, options) => { + if (listener) { + const key = keyOf(type, listener, options); + const exists = [...resources.listeners.values()].some( + (entry) => + entry.target === name && + entry.type === key.type && + entry.listener === listener && + entry.capture === key.capture + ); + if (!exists) { + const id = Symbol(type); + resources.listeners.set(id, { target: name, ...key, origin: origin() }); + const signal = options && typeof options === 'object' ? options.signal : undefined; + if (signal) + signal.addEventListener('abort', () => resources.listeners.delete(id), { once: true }); + // A `once` listener is gone after its first event. + if (options && typeof options === 'object' && options.once) { + add(type, () => resources.listeners.delete(id), { once: true, capture: key.capture }); + } + } + } + add(type, listener, options); + }; + target.removeEventListener = (type, listener, options) => { + const key = keyOf(type, listener, options); + for (const [id, entry] of resources.listeners) { + if ( + entry.target === name && + entry.type === key.type && + entry.listener === listener && + entry.capture === key.capture + ) { + resources.listeners.delete(id); + break; + } + } + remove(type, listener, options); + }; +}; +trackListeners(window, 'window'); +trackListeners(window.document, 'document'); +trackListeners(window.document.body, 'body'); + +/** + * Base class for counted connection-like fakes (WebSocket, EventSource, BroadcastChannel). + */ +class CountedConnection extends window.EventTarget { + /** + * @param {string} kind - Constructor name. + * @param {string} [url] - URL or channel name. + */ + constructor(kind, url) { + super(); + this.kind = kind; + this.url = String(url ?? ''); + this.readyState = 0; + this.origin = origin(); + resources.sockets.add(this); + } + close() { + this.readyState = 3; + resources.sockets.delete(this); + } + send() {} + postMessage() {} +} +globalThis.WebSocket = window.WebSocket = class WebSocket extends CountedConnection { + constructor(url) { + super('WebSocket', url); + } +}; +globalThis.EventSource = window.EventSource = class EventSource extends CountedConnection { + constructor(url) { + super('EventSource', url); + } +}; +globalThis.BroadcastChannel = window.BroadcastChannel = class BroadcastChannel extends ( + CountedConnection +) { + constructor(name) { + super('BroadcastChannel', name); + } +}; + +/** + * Counted observer fake for ResizeObserver and IntersectionObserver (jsdom has neither). + * @param {string} kind - Constructor name. + * @returns {Function} Observer class. + */ +const countedObserver = (kind) => + class { + constructor(callback) { + this.kind = kind; + this.callback = callback; + this.targets = new Set(); + this.origin = origin(); + } + observe(target) { + this.targets.add(target); + resources.observers.add(this); + } + unobserve(target) { + this.targets.delete(target); + if (this.targets.size === 0) resources.observers.delete(this); + } + disconnect() { + this.targets.clear(); + resources.observers.delete(this); + } + takeRecords() { + return []; + } + }; +globalThis.ResizeObserver = window.ResizeObserver = countedObserver('ResizeObserver'); +globalThis.IntersectionObserver = window.IntersectionObserver = + countedObserver('IntersectionObserver'); + +window.matchMedia = globalThis.matchMedia = (query) => ({ + matches: false, + media: query, + onchange: null, + addListener() {}, + removeListener() {}, + addEventListener() {}, + removeEventListener() {}, + dispatchEvent: () => false, +}); +window.scrollTo = () => {}; +// jsdom has no layout: Range geometry (CodeMirror in the Design System's JSONInput measures text). +for (const name of ['getClientRects', 'getBoundingClientRect']) { + if (!window.Range.prototype[name]) { + window.Range.prototype[name] = + name === 'getClientRects' + ? () => [] + : () => window.DOMRect.fromRect({ x: 0, y: 0, width: 0, height: 0 }); + } +} +window.HTMLElement.prototype.scrollIntoView = function scrollIntoView() {}; +if (!window.HTMLElement.prototype.hasPointerCapture) { + window.HTMLElement.prototype.hasPointerCapture = () => false; + window.HTMLElement.prototype.releasePointerCapture = () => {}; + window.HTMLElement.prototype.setPointerCapture = () => {}; +} diff --git a/tests/admin/strict-mode.test.jsx b/tests/admin/strict-mode.test.jsx new file mode 100644 index 0000000..8db24f5 --- /dev/null +++ b/tests/admin/strict-mode.test.jsx @@ -0,0 +1,197 @@ +/** + * StrictMode checks of every Magic Mark admin entry point (menu page, homepage widget, Content + * Manager list view injection) and the dialogs they open. See harness/index.jsx for what each + * assertion counts. + */ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { act } from 'react'; +import { checkStrictEntry, network, permission } from './harness/index.jsx'; +import App from '../../admin/src/pages/App'; +import PinnedBookmarksWidget from '../../admin/src/widgets/PinnedBookmarksWidget'; +import { ListViewActions } from '../../admin/src/components/ListViewActions'; +import { BookmarkFormModal } from '../../admin/src/components/BookmarkFormModal'; + +const ALL = ['read', 'create', 'update', 'delete', 'share', 'manage'].map((name) => + permission(`plugin::magic-mark.bookmarks.${name}`) +); +const ARTICLE = 'api::article.article'; + +const bookmark = (overrides = {}) => ({ + documentId: 'bm-1', + name: 'Drafts', + description: '', + icon: 'bookmark', + path: `/content-manager/collection-types/${ARTICLE}`, + contentType: ARTICLE, + query: 'filters[$and][0][title][$contains]=draft', + visibility: 'private', + owner: { name: 'Ada Example', isDeleted: false }, + isOwner: true, + isPinned: true, + canEdit: true, + sharing: { roles: [], users: [] }, + ...overrides, +}); + +const list = (items) => ({ + data: items, + meta: { + pagination: { page: 1, pageSize: 10, pageCount: items.length ? 1 : 0, total: items.length }, + permissions: { canShare: true, canManage: true }, + }, +}); + +/** Content Manager schema routes the plugin reads (synthetic article type). */ +const contentManagerRoutes = () => { + network.on('GET', '/content-manager/init', { + data: { + contentTypes: [ + { + uid: ARTICLE, + isDisplayed: true, + kind: 'collectionType', + info: { displayName: 'Article', singularName: 'article', pluralName: 'articles' }, + attributes: { title: { type: 'string' }, published: { type: 'boolean' } }, + }, + ], + components: [], + fieldSizes: {}, + }, + }); + network.on('GET', `/content-manager/content-types/${ARTICLE}/configuration`, { + data: { + contentType: { + uid: ARTICLE, + metadatas: { + title: { list: { label: 'Title', searchable: true, sortable: true } }, + published: { list: { label: 'Published', searchable: true, sortable: true } }, + }, + }, + components: {}, + }, + }); +}; + +/** + * Clicks an element inside `act` (Design System buttons and Radix triggers handle `click`; + * Radix menus also need pointerdown). + * @param {Element | null} element - Element. + */ +const click = async (element) => { + assert.ok(element, 'element to click exists'); + await act(async () => { + element.dispatchEvent(new window.PointerEvent('pointerdown', { bubbles: true, button: 0 })); + element.click(); + }); + await act(async () => new Promise((resolve) => setTimeout(resolve, 20))); +}; + +/** + * Finds a button by its accessible label or text anywhere in the document (dialogs and popovers + * render in portals). + * @param {string} label - Label or text. + * @returns {HTMLElement | null} Button. + */ +const button = (label) => + document.querySelector(`[aria-label="${label}"]`) || + [...document.querySelectorAll('button')].find((node) => node.textContent.trim() === label) || + null; + +test('menu page (bookmark list): StrictMode mount, one live list request, clean unmount', async () => { + contentManagerRoutes(); + network.on('GET', '/magic-mark/bookmarks', list([bookmark()])); + const result = await checkStrictEntry(, { path: '/', permissions: ALL }); + assert.match(result.html, /Drafts/); + const live = result.mountCalls.filter( + (call) => call.pathname === '/magic-mark/bookmarks' && !call.aborted + ); + assert.equal(live.length, 1, 'one list request survives the StrictMode remount'); +}); + +test('menu page: unknown sub-path shows the not-found state without plugin requests', async () => { + const result = await checkStrictEntry(, { path: '/unknown', permissions: ALL }); + assert.equal(result.mountCalls.filter((call) => call.fromPlugin).length, 0); +}); + +test('homepage widget: StrictMode mount shows pinned bookmarks with content type names', async () => { + contentManagerRoutes(); + network.on('GET', '/magic-mark/bookmarks', list([bookmark()])); + const result = await checkStrictEntry(, { permissions: ALL }); + assert.match(result.html, /Drafts/); + // The name comes from the shared /content-manager/init cache. StrictMode aborts the first + // mount's request (useFetchClient aborts on unmount); the remount must still get the names. + assert.match(result.html, />Articleapi::article\.article { + contentManagerRoutes(); + network.on('GET', '/magic-mark/bookmarks', list([])); + const empty = await checkStrictEntry(, { permissions: ALL }); + assert.match(empty.html, /Pin bookmarks to see them here/); + + contentManagerRoutes(); + network.on('GET', '/magic-mark/bookmarks', { status: 500, body: { error: { status: 500 } } }); + const failed = await checkStrictEntry(, { permissions: ALL }); + assert.match(failed.html, /could not be loaded/); +}); + +test('list view injection: StrictMode mount, popover and filters dialog open cleanly', async () => { + contentManagerRoutes(); + network.on('GET', '/magic-mark/bookmarks', list([bookmark()])); + const result = await checkStrictEntry(, { + path: `/content-manager/collection-types/${ARTICLE}?page=1`, + permissions: ALL, + async whileMounted() { + await click(button('Bookmarks')); + assert.match(document.body.textContent, /Bookmarks for Article/); + await click(button('Advanced filters')); + assert.match(document.body.textContent, /Show entries that match/); + }, + }); + assert.equal(result.calls.filter((call) => call.method !== 'GET').length, 0, 'no mutation'); + const configuration = result.calls.filter((call) => call.pathname.endsWith('/configuration')); + assert.equal(configuration.length, 1, 'field metadata is loaded once and not aborted'); + assert.equal(configuration[0].aborted, false); +}); + +test('list view injection: renders nothing outside collection-type list views', async () => { + const result = await checkStrictEntry(, { + path: '/content-manager/single-types/api::home.home', + permissions: ALL, + }); + assert.equal(result.mountCalls.filter((call) => call.fromPlugin).length, 0); +}); + +test('bookmark dialog (edit, shared): StrictMode mount and clean unmount', async () => { + network.on('GET', '/magic-mark/bookmarks/bm-1', { data: bookmark({ visibility: 'shared' }) }); + network.on('GET', '/magic-mark/sharing/roles', { + data: [{ documentId: 'role-1', name: 'Editor' }], + }); + network.on('GET', '/magic-mark/sharing/users', { + data: [], + meta: { pagination: { page: 1, pageSize: 10, pageCount: 0, total: 0 } }, + }); + const result = await checkStrictEntry( + {}} + onSaved={() => {}} + />, + { + permissions: ALL, + // The user search is debounced by 250 ms; wait for it so its request is part of the check. + whileMounted: () => act(async () => new Promise((resolve) => setTimeout(resolve, 300))), + } + ); + assert.ok( + result.calls.some((call) => call.pathname === '/magic-mark/bookmarks/bm-1' && !call.aborted) + ); + assert.ok( + result.calls.some((call) => call.pathname === '/magic-mark/sharing/users' && !call.aborted) + ); + assert.equal(result.calls.filter((call) => call.method !== 'GET').length, 0); +}); diff --git a/tests/package.test.cjs b/tests/package.test.cjs index 86b9b4e..8e58b83 100644 --- a/tests/package.test.cjs +++ b/tests/package.test.cjs @@ -115,6 +115,7 @@ test('CI and Dependabot are set up like the other plugins (CI-1, REL-2)', () => 'npm run lint', 'npm run format:check', 'npm test', + 'npm run test:admin', 'npm run test:ts:front', 'npm run test:ts:back', 'npm run build', @@ -123,7 +124,13 @@ test('CI and Dependabot are set up like the other plugins (CI-1, REL-2)', () => ]) { assert.ok(ci.includes(step), step); } - assert.doesNotMatch(ci, /continue-on-error/); + // Only the informational React 19 job may fail without blocking (peers stay React ^18). + const react19 = ci.match(/\n react-19:\n[\s\S]*?(?=\n [a-z][\w-]*:\n|$)/); + assert.ok(react19, 'react-19 job'); + assert.match(react19[0], /continue-on-error: true/); + assert.match(react19[0], /react@19 react-dom@19/); + assert.match(react19[0], /npm run test:admin/); + assert.doesNotMatch(ci.replace(react19[0], ''), /continue-on-error/); for (const file of [ '.github/workflows/test.yml', '.github/workflows/release.yml', From 6b992dfa8b6ac3d37f530af4d46db37cc7571448 Mon Sep 17 00:00:00 2001 From: "Schero D." Date: Thu, 19 Nov 2026 00:11:20 +0100 Subject: [PATCH 2/3] fix(admin): keep the shared schema cache alive when a component unmounts The /content-manager/init and list view configuration caches are shared by the toolbar, popover, widget and page, but their requests used the abort signal of the component that started them (useFetchClient aborts on unmount). In StrictMode, and whenever that component unmounted first, every other consumer got the aborted promise and showed raw content type ids or "Fields could not be loaded". The caches now use getFetchClient(). The bookmark dialog states that its title is its only label, so Radix no longer warns about a missing description. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 ++++++++ admin/src/components/BookmarkFormModal.tsx | 6 ++++- admin/src/hooks/useOpenBookmark.ts | 7 +++-- admin/src/hooks/useSchemas.ts | 31 +++++++++++++--------- 4 files changed, 37 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d34c60..f463d2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,14 @@ +## [Unreleased] + +### Fixed + +* Content type names and filter fields load again after a component that started loading them unmounts. The schema cache (`/content-manager/init` and the list view configuration) is shared by the list view toolbar, the bookmark popover, the homepage widget and the bookmark page, but its requests ran on the abort signal of the first component; when that component unmounted (React StrictMode does this once on every mount), every other component got the aborted request and showed raw content type ids or "Fields could not be loaded". The cache now uses a fetch client that is not bound to one component. +* The bookmark dialog no longer logs the Radix "Missing `Description`" warning: its title is its only label (`aria-describedby={undefined}`), as in the Advanced filters dialog since 4.0.3. + +### Tests + +* `npm run test:admin`: StrictMode tests for every admin entry point (no duplicate requests, no leaked timers, listeners, connections or observers after unmount, no console errors or warnings), also run against React 19 in an informational CI job. + ## [4.0.3](https://github.com/Schero94/Magicmark/compare/v4.0.2...v4.0.3) (2026-11-18) diff --git a/admin/src/components/BookmarkFormModal.tsx b/admin/src/components/BookmarkFormModal.tsx index d502628..0845fc5 100644 --- a/admin/src/components/BookmarkFormModal.tsx +++ b/admin/src/components/BookmarkFormModal.tsx @@ -253,7 +253,11 @@ export const BookmarkFormModal = ({ return ( <> - + {title} diff --git a/admin/src/hooks/useOpenBookmark.ts b/admin/src/hooks/useOpenBookmark.ts index f33f1c4..d66c01b 100644 --- a/admin/src/hooks/useOpenBookmark.ts +++ b/admin/src/hooks/useOpenBookmark.ts @@ -10,7 +10,7 @@ * answers with 400, or more than 20 `$and` conditions, which the Content Manager list cannot * render) is not opened: the user gets a notice that says how to fix it instead of an error. */ -import { useFetchClient, useNotification } from '@strapi/strapi/admin'; +import { useNotification } from '@strapi/strapi/admin'; import { useCallback } from 'react'; import { useIntl } from 'react-intl'; import { useNavigate } from 'react-router-dom'; @@ -61,7 +61,6 @@ export const normalizeSavedQuery = ( */ export const useOpenBookmark = () => { const navigate = useNavigate(); - const { get } = useFetchClient(); const { toggleNotification } = useNotification(); const { formatMessage } = useIntl(); @@ -93,7 +92,7 @@ export const useOpenBookmark = () => { } let saved = parsed; try { - saved = normalizeSavedQuery(parsed, await loadInit(get), location.uid); + saved = normalizeSavedQuery(parsed, await loadInit(), location.uid); } catch { // Schemas unavailable: open the bookmark as it was saved. } @@ -105,6 +104,6 @@ export const useOpenBookmark = () => { } navigate({ pathname: location.path, search: search ? `?${search}` : '' }); }, - [get, navigate, toggleNotification, formatMessage] + [navigate, toggleNotification, formatMessage] ); }; diff --git a/admin/src/hooks/useSchemas.ts b/admin/src/hooks/useSchemas.ts index 49bd686..76ad2f4 100644 --- a/admin/src/hooks/useSchemas.ts +++ b/admin/src/hooks/useSchemas.ts @@ -4,7 +4,7 @@ * Every admin who can use the Content Manager may call both, unlike the Content-Type * Builder API, which needs builder permissions. */ -import { useAuth, useFetchClient } from '@strapi/strapi/admin'; +import { getFetchClient, useAuth } from '@strapi/strapi/admin'; import { useEffect, useMemo, useState } from 'react'; import type { FieldOption } from '../utils/filters'; import { buildFieldOptions, type InitData, type Metadata } from '../utils/fieldOptions'; @@ -12,15 +12,22 @@ import { buildFieldOptions, type InitData, type Metadata } from '../utils/fieldO let initCache: Promise | null = null; const configCache = new Map>>(); -type Get = ReturnType['get']; +/** + * GET for the session-wide caches below. They are shared by every component, so their requests + * must not belong to one component: `useFetchClient` aborts its requests when its component + * unmounts (React StrictMode unmounts once on mount), which would reject the cached promise for + * every other consumer. `getFetchClient()` has no component-bound abort signal. + * @param url - Admin API path. + * @returns The fetch client response. + */ +const sessionGet = (url: string) => getFetchClient().get(url); /** * Schemas from `/content-manager/init`, loaded once per admin session. - * @param get - `useFetchClient().get`. */ -export const loadInit = (get: Get): Promise => { +export const loadInit = (): Promise => { if (!initCache) { - initCache = get<{ data: InitData }>('/content-manager/init') + initCache = sessionGet<{ data: InitData }>('/content-manager/init') .then(({ data }) => data.data) .catch((error) => { initCache = null; @@ -30,10 +37,10 @@ export const loadInit = (get: Get): Promise => { return initCache; }; -const loadMetadatas = (get: Get, uid: string): Promise> => { +const loadMetadatas = (uid: string): Promise> => { let promise = configCache.get(uid); if (!promise) { - promise = get<{ data: { contentType: { metadatas: Record } } }>( + promise = sessionGet<{ data: { contentType: { metadatas: Record } } }>( `/content-manager/content-types/${uid}/configuration` ) .then(({ data }) => data.data.contentType.metadatas ?? {}) @@ -51,7 +58,6 @@ const loadMetadatas = (get: Get, uid: string): Promise> * @returns `{ names, isLoading, error }`. */ export const useContentTypeNames = () => { - const { get } = useFetchClient(); const [state, setState] = useState<{ names: Map; isLoading: boolean; @@ -63,7 +69,7 @@ export const useContentTypeNames = () => { }); useEffect(() => { let active = true; - loadInit(get) + loadInit() .then((init) => { if (!active) return; setState({ @@ -76,7 +82,7 @@ export const useContentTypeNames = () => { return () => { active = false; }; - }, [get]); + }, []); return state; }; @@ -86,7 +92,6 @@ export const useContentTypeNames = () => { * @returns `{ fields, isLoading, error, retry }`. */ export const useFilterFields = (uid: string | null) => { - const { get } = useFetchClient(); const permissions = useAuth('MagicMarkFilters', (state) => state.permissions); const [attempt, setAttempt] = useState(0); // Results are stored with the request key, so a new uid or a retry shows "loading" @@ -110,7 +115,7 @@ export const useFilterFields = (uid: string | null) => { useEffect(() => { if (!uid) return undefined; let active = true; - Promise.all([loadInit(get), loadMetadatas(get, uid)]) + Promise.all([loadInit(), loadMetadatas(uid)]) .then(([init, metadatas]) => { if (active) { setState({ key, fields: buildFieldOptions(uid, init, metadatas, readable), error: null }); @@ -120,7 +125,7 @@ export const useFilterFields = (uid: string | null) => { return () => { active = false; }; - }, [get, uid, readable, key]); + }, [uid, readable, key]); const current = state.key === key; return { From 736f1150b6af418dded14f76a1365f237185f69b Mon Sep 17 00:00:00 2001 From: "Schero D." Date: Thu, 19 Nov 2026 00:14:53 +0100 Subject: [PATCH 3/3] test: count the indentation in the React 19 job pattern Co-Authored-By: Claude Opus 5.5 --- tests/package.test.cjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/package.test.cjs b/tests/package.test.cjs index 8e58b83..c6d4f15 100644 --- a/tests/package.test.cjs +++ b/tests/package.test.cjs @@ -125,7 +125,7 @@ test('CI and Dependabot are set up like the other plugins (CI-1, REL-2)', () => assert.ok(ci.includes(step), step); } // Only the informational React 19 job may fail without blocking (peers stay React ^18). - const react19 = ci.match(/\n react-19:\n[\s\S]*?(?=\n [a-z][\w-]*:\n|$)/); + const react19 = ci.match(/\n {2}react-19:\n[\s\S]*?(?=\n {2}[a-z][\w-]*:\n|$)/); assert.ok(react19, 'react-19 job'); assert.match(react19[0], /continue-on-error: true/); assert.match(react19[0], /react@19 react-dom@19/);