From 448512685974b029a658be1c2232fffe54ea3332 Mon Sep 17 00:00:00 2001 From: valentinab25 Date: Wed, 24 Jun 2026 22:28:52 +0300 Subject: [PATCH 1/5] chore: [JENKINSFILE] sanitize sonarqube command Refs #305084 --- Jenkinsfile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 06e372b..18af911 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -240,15 +240,15 @@ pipeline { def scannerHome = tool 'SonarQubeScanner' def nodeJS = tool 'NodeJS' if (env.CHANGE_ID) { - env.sonarParams = " -Dsonar.pullrequest.base=${env.CHANGE_TARGET} -Dsonar.pullrequest.branch=${env.CHANGE_BRANCH} -Dsonar.pullrequest.key=${env.CHANGE_ID} " + env.sonarParams = " -Dsonar.pullrequest.base='${env.CHANGE_TARGET}' -Dsonar.pullrequest.branch='${env.CHANGE_BRANCH}' -Dsonar.pullrequest.key='${env.CHANGE_ID}' " } else { - env.sonarParams = " -Dsonar.branch.name=${env.BRANCH_NAME}" + env.sonarParams = " -Dsonar.branch.name='${env.BRANCH_NAME}'" } withSonarQubeEnv('Sonarqube') { sh '''sed -i "s#/app/src/addons/${GIT_NAME}/##g" xunit-reports-current/coverage/lcov.info''' sh '''sed -i "s#src/addons/${GIT_NAME}/##g" xunit-reports-current/coverage/lcov.info''' - sh "export PATH=${scannerHome}/bin:${nodeJS}/bin:$PATH; sonar-scanner -Dsonar.javascript.lcov.reportPaths=./xunit-reports-current/coverage/lcov.info,./cypress-coverage-current/coverage/lcov.info -Dsonar.sources=./src -Dsonar.projectKey=$GIT_NAME -Dsonar.projectName=$GIT_NAME -Dsonar.projectVersion=\$(jq -r '.version' package.json) ${env.sonarParams}" + sh "export PATH=${scannerHome}/bin:${nodeJS}/bin:$PATH; sonar-scanner -Dsonar.javascript.lcov.reportPaths=./xunit-reports-current/coverage/lcov.info,./cypress-coverage-current/coverage/lcov.info -Dsonar.sources=./src -Dsonar.projectKey=\"${GIT_NAME}\" -Dsonar.projectName=\"${GIT_NAME}\" -Dsonar.projectVersion=\$(jq '.version' package.json) ${env.sonarParams}" sh '''try=5; while [ \$try -gt 0 ]; do curl -s -XPOST -u "${SONAR_AUTH_TOKEN}:" "${SONAR_HOST_URL}api/project_tags/set?project=${GIT_NAME}&tags=${SONARQUBE_TAGS}" > set_tags_result; if [ \$(grep -ic error set_tags_result ) -eq 0 ]; then try=0; else cat set_tags_result; echo "... Will retry"; sleep 15; try=\$(( \$try - 1 )); fi; done''' } } From d4548baced643a9bb58a1ac2e2b672ef2f3af639 Mon Sep 17 00:00:00 2001 From: valentinab25 Date: Mon, 6 Jul 2026 19:31:40 +0300 Subject: [PATCH 2/5] test: pin Chromium version 149 to work with Cypress --- Dockerfile | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 5745d68..77da85e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,13 +4,38 @@ FROM plone/frontend-builder:${VOLTO_VERSION} ARG ADDON_NAME ARG ADDON_PATH +ARG CHROMIUM_VERSION=149.0.7827.196-1~deb12u1 + + ENV HOST="0.0.0.0" +ENV CHROME_BIN="/usr/bin/chromium" +ENV CHROMIUM_BIN="/usr/bin/chromium" +ENV CYPRESS_BROWSER_PATH="/usr/bin/chromium" +# Install Cypress dependencies (matching eeacms/frontend-builder) USER root RUN apt-get update -q \ && apt-get install -qy --no-install-recommends \ - chromium libgtk2.0-0 libgtk-3-0 libgbm-dev libnotify-dev libgconf-2-4 libnss3 libxss1 libasound2 libxtst6 xauth xvfb \ + libgtk2.0-0 libgtk-3-0 libgbm-dev libnotify-dev libgconf-2-4 libnss3 libxss1 libasound2 libxtst6 xauth xvfb \ && rm -rf /var/lib/apt/lists/* + +RUN set -eux; \ + mkdir -p /etc/apt/sources.list.d /etc/apt/preferences.d /etc/apt/apt.conf.d; \ + printf '%s\n' \ + 'Acquire::Check-Valid-Until "false";' \ + > /etc/apt/apt.conf.d/99snapshot-no-check-valid-until; \ + printf '%s\n' \ + 'deb [check-valid-until=no] http://snapshot.debian.org/archive/debian-security/20260630T000000Z bookworm-security main' \ + 'deb [check-valid-until=no] http://snapshot.debian.org/archive/debian/20260630T000000Z bookworm main' \ + > /etc/apt/sources.list.d/bookworm-chromium149-snapshot.list; \ + apt-get update -q; \ + apt-get install -qy --no-install-recommends \ + "chromium=${CHROMIUM_VERSION}" \ + "chromium-common=${CHROMIUM_VERSION}" \ + ; \ + apt-mark hold chromium chromium-common ; \ + rm -rf /var/lib/apt/lists/* + USER node COPY --chown=node:node ./ /app/src/addons/${ADDON_PATH}/ From dd7345fa06c05c6b31db6445a4a0764721597eca Mon Sep 17 00:00:00 2001 From: dobri1408 <50819975+dobri1408@users.noreply.github.com> Date: Tue, 14 Jul 2026 12:07:49 +0300 Subject: [PATCH 3/5] fix: Add betterleaks github action - refs #304517 --- .env | 4 +- .github/workflows/betterleaks.yml | 133 ++++++++++++++++++++++++++++++ .gitleaks.toml | 89 ++++++++++++++++++++ README.md | 59 +++++++++++++ RELEASE.md | 2 +- cypress/support/commands.js | 4 +- 6 files changed, 285 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/betterleaks.yml create mode 100644 .gitleaks.toml diff --git a/.env b/.env index ef282fa..7afcd38 100644 --- a/.env +++ b/.env @@ -1,3 +1 @@ -# Jest configuration variables -# - possible values: ON, OFF -JEST_USE_SETUP=OFF \ No newline at end of file +JEST_USE_SETUP=OFF # Jest configuration variables: ON, OFF diff --git a/.github/workflows/betterleaks.yml b/.github/workflows/betterleaks.yml new file mode 100644 index 0000000..e3ee2df --- /dev/null +++ b/.github/workflows/betterleaks.yml @@ -0,0 +1,133 @@ +name: Betterleaks + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + scan: + name: Scan for secrets + runs-on: ubuntu-latest + env: + SMTP_URL: ${{ secrets.SMTP_URL }} + SMTP_PORT: ${{ secrets.SMTP_PORT || '25' }} + SMTP_EMAIL: ${{ secrets.SMTP_EMAIL }} + SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 1 + ref: ${{ github.event.pull_request.head.sha || github.sha }} + + - name: Run Betterleaks + id: betterleaks + continue-on-error: true + uses: dortort/betterleaks-action@v0.1.0 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + scan-mode: dir + scan-path: . + config: .gitleaks.toml + report-format: json + report-path: betterleaks-report.json + redact: "true" + no-color: "true" + no-banner: "true" + fail-on-leak: "true" + + - name: Upload Betterleaks report + if: always() + uses: actions/upload-artifact@v4 + with: + name: betterleaks-report + path: betterleaks-report.json + if-no-files-found: ignore + + - name: Build Betterleaks email summary + id: leak_summary + if: steps.betterleaks.outcome == 'failure' + shell: bash + run: | + if [[ -s betterleaks-report.json ]]; then + jq -r ' + def one_line: + tostring + | gsub("[\r\n]+"; " ") + | if length > 240 then .[0:240] + "..." else . end; + + .[:20][] + | "- " + (.RuleID // "unknown-rule") + + " at " + (.File // "unknown-file") + + ":" + ((.StartLine // 0) | tostring) + + "\n match: " + ((.Match // .Secret // "REDACTED") | one_line) + ' betterleaks-report.json > betterleaks-email-summary.txt + + count="$(jq 'length' betterleaks-report.json)" + if (( count > 20 )); then + { + echo "" + echo "... and $((count - 20)) more finding(s). Download the artifact for full details." + } >> betterleaks-email-summary.txt + fi + else + echo "No JSON report was generated. Download the workflow logs for details." > betterleaks-email-summary.txt + fi + + { + echo "text<> "$GITHUB_OUTPUT" + + - name: Resolve committer email + id: committer + if: steps.betterleaks.outcome == 'failure' + shell: bash + run: | + committer_email="$(git log -1 --format='%ce')" + author_email="$(git log -1 --format='%ae')" + email="$committer_email" + if [[ -z "$email" || "$email" == *"noreply.github.com"* ]]; then + email="$author_email" + fi + if [[ "$email" =~ ^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$ && "$email" != *"noreply.github.com"* ]]; then + echo "email=$email" >> "$GITHUB_OUTPUT" + else + echo "No deliverable committer email found; skipping Betterleaks email notification." + echo "email=" >> "$GITHUB_OUTPUT" + fi + + - name: Email committer on Betterleaks failure + if: steps.betterleaks.outcome == 'failure' && steps.committer.outputs.email != '' && env.SMTP_URL != '' && env.SMTP_EMAIL != '' + uses: dawidd6/action-send-mail@v18 + with: + server_address: ${{ env.SMTP_URL }} + server_port: ${{ env.SMTP_PORT }} + secure: ${{ env.SMTP_PORT == '465' }} + username: ${{ env.SMTP_EMAIL }} + password: ${{ env.SMTP_PASSWORD }} + from: ${{ env.SMTP_EMAIL }} + to: ${{ steps.committer.outputs.email }} + subject: "[Betterleaks] Secret scan failed in ${{ github.repository }}" + body: | + Betterleaks detected one or more potential secrets. + + Repository: ${{ github.repository }} + Branch: ${{ github.ref_name }} + Commit: ${{ github.sha }} + Workflow run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + + Findings: + ${{ steps.leak_summary.outputs.text }} + + Download the betterleaks-report artifact from the workflow run for details. + + - name: Fail if Betterleaks found leaks + if: steps.betterleaks.outcome == 'failure' + run: | + echo "Betterleaks detected one or more secrets. Download the betterleaks-report artifact from this workflow run for details." + exit 1 diff --git a/.gitleaks.toml b/.gitleaks.toml new file mode 100644 index 0000000..d26a674 --- /dev/null +++ b/.gitleaks.toml @@ -0,0 +1,89 @@ +title = "Betterleaks config" + +[extend] +useDefault = true + +[[rules]] +id = "secret-literal-assignment" +description = "Secret-like literal assignment in source, YAML, env and config files" +regex = '''(?i)([A-Za-z0-9_.-]*(?:password|passwd|pwd|api[_-]?key|apikey|access[_-]?key|secret[_-]?access[_-]?key|private[_-]?key|client[_-]?secret|consumer[_-]?key|consumer[_-]?secret|(?:auth|access|refresh|session|api|bearer|id|jwt|csrf|xsrf|oauth)[_-]?token|translate[_-]?auth|translation[_-]?auth|auth[_-]?password|auth[_-]?key|auth[_-]?credentials|database[_-]?url|connection[_-]?string)[A-Za-z0-9_.-]*)[ \t]*[:=][ \t]*["'']?([^"''[:space:]#{}$.][^"''\n#{}]{2,})["'']?''' +secretGroup = 2 +keywords = [ + "password", + "passwd", + "pwd", + "api_key", + "apikey", + "access_key", + "private_key", + "client_secret", + "consumer_key", + "consumer_secret", + "auth_token", + "access_token", + "refresh_token", + "session_token", + "api_token", + "bearer_token", + "id_token", + "jwt_token", + "csrf_token", + "xsrf_token", + "oauth_token", + "translate_auth", + "translation_auth", + "auth_password", + "auth_key", + "auth_credentials", + "database_url", + "connection_string" +] +tags = ["literal-secret"] + +[[rules]] +id = "env-short-secret-assignment" +description = "Uppercase env-style PASS/TOKEN/SECRET assignment" +regex = '''\b((?:PASS|TOKEN|SECRET|[A-Z0-9_]*(?:_PASS|_TOKEN|_SECRET|PASS_|TOKEN_|SECRET_)[A-Z0-9_]*))[ \t]*[:=][ \t]*["'']?([^"''[:space:]#{}$.][^"''\n#{}]{2,})["'']?''' +secretGroup = 2 +keywords = [ + "PASS", + "TOKEN", + "SECRET" +] +tags = ["env", "literal-secret"] + +[[rules]] +id = "standalone-sk-token" +description = "Standalone sk-* token not attached to a secret-like variable name" +regex = '''(?i)\b(sk-[A-Za-z0-9][A-Za-z0-9_-]{20,})\b''' +secretGroup = 1 +entropy = 2.5 +keywords = ["sk-"] +tags = ["standalone-token", "generic"] + +[[rules]] +id = "dotenv-only-jest-setup" +description = ".env may only contain the committed Jest setup lines" +path = '''(?i)(^|/)\.env$''' +regex = '''(?m)^(.+)$''' +secretGroup = 1 +tags = ["file", "dotenv"] +[[rules.allowlists]] +regexTarget = "match" +regexes = [ + '''^JEST_USE_SETUP=OFF # Jest configuration variables: ON, OFF\r?$''', +] + +[[rules]] +id = "forbidden-secret-file" +description = "Forbidden secret-bearing file committed to repository" +path = '''(?i)(^|/)(\.env\..*|\.npmrc|\.pypirc|id_rsa|id_ed25519|.*\.(pem|key|p12|pfx|jks|kubeconfig))$''' +regex = '''(?s).{1,}''' +tags = ["file", "secret-file"] + +[[allowlists]] +description = "Allow Jenkins SonarQube token environment variable reference" +regexTarget = "match" +regexes = [ + '''SONAR_AUTH_TOKEN''', +] diff --git a/README.md b/README.md index 32775ef..d8365df 100644 --- a/README.md +++ b/README.md @@ -234,6 +234,65 @@ See [RELEASE.md](https://github.com/eea/volto-object-widget/blob/master/RELEASE. See [DEVELOP.md](https://github.com/eea/volto-object-widget/blob/master/DEVELOP.md). +## Secret Scanning + +This repository uses the Betterleaks GitHub Action to scan the current +repository content on every push and pull request. The scan uses the rules in +`.gitleaks.toml` and uploads a `betterleaks-report` artifact when a finding is +detected. + +If the optional SMTP secrets are configured, failed scans also send an email to +the last commit committer. The workflow expects these repository or +organization secrets: + +- `SMTP_URL` +- `SMTP_PORT` (optional, defaults to `25`) +- `SMTP_EMAIL` +- `SMTP_PASSWORD` (optional if the SMTP server does not require authentication) + +Port `465` is sent with direct TLS; other ports use the default SMTP handshake. +The email includes a short finding summary from the redacted Betterleaks report, +including the redacted matched line from each finding. + +There are three common outcomes: + +1. **Everything is OK.** The `Betterleaks / Scan for secrets` check is green and + no action is needed. Regular references to runtime values are OK, for example: + + ```js + const tokenFromCookie = req.universalCookies.get('auth_token'); + ``` + +2. **A real secret was found.** The check is red and the workflow log asks you to + download the `betterleaks-report` artifact. Open the artifact from the GitHub + Actions run and check the reported file, line and rule. Remove the committed + value, move it to the proper secret store, and rotate it if it was exposed. + A report entry looks like this: + + ```json + { + "RuleID": "secret-literal-assignment", + "File": "src/config.js", + "StartLine": 12, + "Secret": "[REDACTED]" + } + ``` + +3. **The finding is a false positive.** Keep the value only if it is clearly not + sensitive, such as a test fixture, placeholder, or public example. Add + `betterleaks:allow` on the same line and include a short explanation in the + pull request. + + ```js + const testPassword = 'admin'; //betterleaks:allow + ``` + + ```yaml + password: "admin" #betterleaks:allow + ``` + +Do not add `betterleaks:allow` to real credentials. + ## Copyright and license The Initial Owner of the Original Code is European Environment Agency (EEA). diff --git a/RELEASE.md b/RELEASE.md index 4e311a0..27baae1 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -33,7 +33,7 @@ Release-it is a tool that automates 4 important steps in the release process: To configure the authentification, you need to export GITHUB_TOKEN for [GitHub](https://github.com/settings/tokens) ``` - export GITHUB_TOKEN=XXX-XXXXXXXXXXXXXXXXXXXXXX + export GITHUB_TOKEN="${GITHUB_TOKEN}" ``` To configure npm, you can use the `npm login` command or use a configuration file with a TOKEN : diff --git a/cypress/support/commands.js b/cypress/support/commands.js index 8b091db..13c1161 100644 --- a/cypress/support/commands.js +++ b/cypress/support/commands.js @@ -8,14 +8,14 @@ Cypress.Commands.add('autologin', () => { let api_url, user, password; api_url = Cypress.env('API_PATH') || 'http://localhost:8080/Plone'; user = 'admin'; - password = 'admin'; + password = 'admin'; //betterleaks:allow return cy .request({ method: 'POST', url: `${api_url}/@login`, headers: { Accept: 'application/json' }, - body: { login: user, password: password }, + body: { login: user, password: password }, //betterleaks:allow }) .then((response) => cy.setCookie('auth_token', response.body.token)); }); From 954b35f80537b4fc40cd01aa6789fa3f0ebd7808 Mon Sep 17 00:00:00 2001 From: dobri1408 <50819975+dobri1408@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:45:34 +0200 Subject: [PATCH 4/5] feat: Volto 19 support - refs #297832 * Volto 19 compatibility: use @plone/volto/babel preset * chore: migrate add-on to Volto 19 structure * style: Automated code fix * fix: satisfy Betterleaks scan * fix: sonarqube coverage on Volto 19 Restore the Cypress end-to-end coverage instrumentation: babel-plugin-istanbul plus a coverage babel config that instruments only the add-on sources. Unit tests now use the Istanbul coverage provider so the unit and e2e lcov reports share the same line model and can be merged by SonarQube. * fix: load the edit route directly in slateBeforeEach The appHistory push can race with the client hydration, which then settles back on the server-rendered view URL and the title editor never mounts. * chore: update Volto to 19.5.0 * fix: restore RAZZLE_CI for the CI frontend build The Volto 19 migration dropped RAZZLE_CI from start-ci, but packages/volto-object-widget/src/index.js only registers the demo block when it is set: the integration test asserting the '.button.ObjectWidgetDemo' chooser entry failed and left the '/Plone/cypress' fixture behind, which cascaded into the 11 remaining specs failing with a duplicate content id. develop set it for both the build and the start command; do the same. * fix: return an object from the css vi.mock factories Vitest 3.2.7 rejects a mock factory that returns undefined: 'vi.mock("jsoneditor/dist/jsoneditor.min.css", factory) is not returning an object'. The whole JsonWidget suite errored before running (volto19 unit stage exit 1). Return an empty object for both style imports. * test: resolve Volto and the nested add-ons from the frontend project in vitest Look up the Volto checkout in any parent folder, resolve the core packages through Volto and alias the add-ons kept in each repository's packages/ folder, so the tests also run from the eea-website-frontend workspace. * ci: re-run the Jenkins builds aborted on 2026-10-28 * docs: ship the package readme and license npm reads README/LICENSE only from the package directory. The package readme keeps the add-on documentation, the repository readme becomes a landing page, the secret scanning notes move to DEVELOP.md. * chore(release): 10.0.0 Drop Volto 17: the package requires @plone/volto >=18 <20 and Node.js >=22. * ci(betterleaks): adopt the shared scan and its history audit * docs: document the 10.x upgrade --------- Co-authored-by: Alin Voinea Co-authored-by: eea-jenkins --- .betterleaks-history-baseline.json | 216 + .cookieplone.json | 7 + .coverage.babel.config.js | 30 +- .dockerignore | 10 + .env | 1 - .eslintrc.js | 66 +- .github/workflows/betterleaks-audit.yml | 29 + .github/workflows/betterleaks.yml | 131 +- .gitignore | 9 + .gitleaks.toml | 22 +- .husky/pre-commit | 2 +- .npmignore | 106 +- .npmrc | 6 + .pnpmfile.cjs | 23 + .prettierignore | 3 + .prettierrc | 12 + .storybook/main.js | 192 + .storybook/preview.jsx | 26 + .stylelintrc | 32 + DEVELOP.md | 59 + Dockerfile | 50 +- Jenkinsfile | 118 +- Makefile | 169 +- README.md | 293 +- babel.config.js | 17 - bootstrap | 41 - cypress.config.js | 17 +- cypress/support/e2e.js | 8 +- ...1-attached-image-widget-external-url.cy.js | 0 ...2-attached-image-widget-internal-url.cy.js | 0 .../03-attached-image-widget-clear-url.cy.js | 0 ...ttached-image-widget-submit-disabled.cy.js | 0 ...attached-image-widget-object-browser.cy.js | 0 ...-attached-image-widget-preview-clear.cy.js | 0 ...attached-image-widget-upload-loading.cy.js | 0 ...attached-image-widget-dragging-state.cy.js | 0 ...ttached-image-widget-conflict-dialog.cy.js | 0 ...tached-image-widget-replace-existing.cy.js | 0 ...1-attached-image-widget-use-existing.cy.js | 0 ...-attached-image-widget-cancel-upload.cy.js | 0 cypress/tsconfig.json | 8 + docker-compose.yml | 31 +- jest-addon.config.js | 469 - jest.setup.js | 65 - mrs.developer.json | 10 + package.json | 101 +- packages/volto-object-widget/.env | 1 + packages/volto-object-widget/.npmignore | 96 + .../volto-object-widget/.release-it.json | 0 .../volto-object-widget/CHANGELOG.md | 0 packages/volto-object-widget/LICENSE.md | 9 + packages/volto-object-widget/README.md | 232 + packages/volto-object-widget/babel.config.js | 1 + .../locales}/de/LC_MESSAGES/volto.po | 0 .../locales}/en/LC_MESSAGES/volto.po | 0 .../locales}/it/LC_MESSAGES/volto.po | 0 .../locales}/ro/LC_MESSAGES/volto.po | 0 .../volto-object-widget/locales}/volto.pot | 0 packages/volto-object-widget/package.json | 93 + .../src}/Widget/AttachedFileWidget.jsx | 0 .../src}/Widget/AttachedFileWidget.test.jsx | 17 +- .../src}/Widget/AttachedImageWidget.jsx | 0 .../src}/Widget/InternalUrlWidget.jsx | 0 .../src}/Widget/JsonWidget/JsonWidget.jsx | 0 .../Widget/JsonWidget/JsonWidget.test.jsx | 37 +- .../src}/Widget/JsonWidget/helpers.js | 0 .../src}/Widget/JsonWidget/helpers.test.js | 17 +- .../src}/Widget/JsonWidget/json-widget.css | 0 .../src}/Widget/MappingWidget.jsx | 0 .../src}/Widget/MappingWidget.test.jsx | 25 +- .../src}/Widget/ObjectByTypeWidget.jsx | 0 .../src}/Widget/ObjectByTypeWidget.test.jsx | 27 +- .../src}/Widget/ObjectListInlineWidget.jsx | 0 .../Widget/ObjectListInlineWidget.test.jsx | 112 +- .../src}/Widget/ObjectListWidget.jsx | 0 .../src}/Widget/ObjectListWidget.test.jsx | 117 +- .../src}/Widget/ObjectTypesWidget.jsx | 0 .../src}/Widget/ObjectTypesWidget.test.jsx | 9 +- .../src}/Widget/UrlWidget.jsx | 0 .../volto-object-widget/src}/Widget/index.js | 0 .../volto-object-widget/src}/Widget/style.css | 0 .../src}/demo/BlockEdit.jsx | 0 .../src}/demo/BlockEdit.test.jsx | 43 +- .../src}/demo/BlockView.jsx | 0 .../volto-object-widget/src}/demo/index.js | 0 .../src}/demo/index.test.js | 0 .../volto-object-widget/src}/demo/schema.js | 0 .../volto-object-widget/src}/helpers/index.js | 0 .../src}/helpers/index.test.js | 7 +- .../volto-object-widget/src}/index.js | 0 packages/volto-object-widget/tsconfig.json | 43 + .../volto-object-widget/vitest.config.mjs | 283 + packages/volto-object-widget/vitest.setup.jsx | 64 + pnpm-lock.yaml | 23543 ++++++++++++++++ pnpm-workspace.yaml | 5 + volto.config.js | 7 + 96 files changed, 25551 insertions(+), 1616 deletions(-) create mode 100644 .betterleaks-history-baseline.json create mode 100644 .cookieplone.json create mode 100644 .dockerignore delete mode 100644 .env create mode 100644 .github/workflows/betterleaks-audit.yml create mode 100644 .npmrc create mode 100644 .pnpmfile.cjs create mode 100644 .prettierignore create mode 100644 .prettierrc create mode 100644 .storybook/main.js create mode 100644 .storybook/preview.jsx create mode 100644 .stylelintrc delete mode 100644 babel.config.js delete mode 100644 bootstrap rename cypress/{e2e => tests}/01-attached-image-widget-external-url.cy.js (100%) rename cypress/{e2e => tests}/02-attached-image-widget-internal-url.cy.js (100%) rename cypress/{e2e => tests}/03-attached-image-widget-clear-url.cy.js (100%) rename cypress/{e2e => tests}/04-attached-image-widget-submit-disabled.cy.js (100%) rename cypress/{e2e => tests}/05-attached-image-widget-object-browser.cy.js (100%) rename cypress/{e2e => tests}/06-attached-image-widget-preview-clear.cy.js (100%) rename cypress/{e2e => tests}/07-attached-image-widget-upload-loading.cy.js (100%) rename cypress/{e2e => tests}/08-attached-image-widget-dragging-state.cy.js (100%) rename cypress/{e2e => tests}/09-attached-image-widget-conflict-dialog.cy.js (100%) rename cypress/{e2e => tests}/10-attached-image-widget-replace-existing.cy.js (100%) rename cypress/{e2e => tests}/11-attached-image-widget-use-existing.cy.js (100%) rename cypress/{e2e => tests}/12-attached-image-widget-cancel-upload.cy.js (100%) create mode 100644 cypress/tsconfig.json delete mode 100644 jest-addon.config.js delete mode 100644 jest.setup.js create mode 100644 mrs.developer.json create mode 100644 packages/volto-object-widget/.env create mode 100644 packages/volto-object-widget/.npmignore rename .release-it.json => packages/volto-object-widget/.release-it.json (100%) rename CHANGELOG.md => packages/volto-object-widget/CHANGELOG.md (100%) create mode 100644 packages/volto-object-widget/LICENSE.md create mode 100644 packages/volto-object-widget/README.md create mode 100644 packages/volto-object-widget/babel.config.js rename {locales => packages/volto-object-widget/locales}/de/LC_MESSAGES/volto.po (100%) rename {locales => packages/volto-object-widget/locales}/en/LC_MESSAGES/volto.po (100%) rename {locales => packages/volto-object-widget/locales}/it/LC_MESSAGES/volto.po (100%) rename {locales => packages/volto-object-widget/locales}/ro/LC_MESSAGES/volto.po (100%) rename {locales => packages/volto-object-widget/locales}/volto.pot (100%) create mode 100644 packages/volto-object-widget/package.json rename {src => packages/volto-object-widget/src}/Widget/AttachedFileWidget.jsx (100%) rename {src => packages/volto-object-widget/src}/Widget/AttachedFileWidget.test.jsx (90%) rename {src => packages/volto-object-widget/src}/Widget/AttachedImageWidget.jsx (100%) rename {src => packages/volto-object-widget/src}/Widget/InternalUrlWidget.jsx (100%) rename {src => packages/volto-object-widget/src}/Widget/JsonWidget/JsonWidget.jsx (100%) rename {src => packages/volto-object-widget/src}/Widget/JsonWidget/JsonWidget.test.jsx (78%) rename {src => packages/volto-object-widget/src}/Widget/JsonWidget/helpers.js (100%) rename {src => packages/volto-object-widget/src}/Widget/JsonWidget/helpers.test.js (87%) rename {src => packages/volto-object-widget/src}/Widget/JsonWidget/json-widget.css (100%) rename {src => packages/volto-object-widget/src}/Widget/MappingWidget.jsx (100%) rename {src => packages/volto-object-widget/src}/Widget/MappingWidget.test.jsx (75%) rename {src => packages/volto-object-widget/src}/Widget/ObjectByTypeWidget.jsx (100%) rename {src => packages/volto-object-widget/src}/Widget/ObjectByTypeWidget.test.jsx (77%) rename {src => packages/volto-object-widget/src}/Widget/ObjectListInlineWidget.jsx (100%) rename {src => packages/volto-object-widget/src}/Widget/ObjectListInlineWidget.test.jsx (62%) rename {src => packages/volto-object-widget/src}/Widget/ObjectListWidget.jsx (100%) rename {src => packages/volto-object-widget/src}/Widget/ObjectListWidget.test.jsx (91%) rename {src => packages/volto-object-widget/src}/Widget/ObjectTypesWidget.jsx (100%) rename {src => packages/volto-object-widget/src}/Widget/ObjectTypesWidget.test.jsx (93%) rename {src => packages/volto-object-widget/src}/Widget/UrlWidget.jsx (100%) rename {src => packages/volto-object-widget/src}/Widget/index.js (100%) rename {src => packages/volto-object-widget/src}/Widget/style.css (100%) rename {src => packages/volto-object-widget/src}/demo/BlockEdit.jsx (100%) rename {src => packages/volto-object-widget/src}/demo/BlockEdit.test.jsx (73%) rename {src => packages/volto-object-widget/src}/demo/BlockView.jsx (100%) rename {src => packages/volto-object-widget/src}/demo/index.js (100%) rename {src => packages/volto-object-widget/src}/demo/index.test.js (100%) rename {src => packages/volto-object-widget/src}/demo/schema.js (100%) rename {src => packages/volto-object-widget/src}/helpers/index.js (100%) rename {src => packages/volto-object-widget/src}/helpers/index.test.js (98%) rename {src => packages/volto-object-widget/src}/index.js (100%) create mode 100644 packages/volto-object-widget/tsconfig.json create mode 100644 packages/volto-object-widget/vitest.config.mjs create mode 100644 packages/volto-object-widget/vitest.setup.jsx create mode 100644 pnpm-lock.yaml create mode 100644 pnpm-workspace.yaml create mode 100644 volto.config.js diff --git a/.betterleaks-history-baseline.json b/.betterleaks-history-baseline.json new file mode 100644 index 0000000..9830a16 --- /dev/null +++ b/.betterleaks-history-baseline.json @@ -0,0 +1,216 @@ +[ + { + "RuleID": "secret-literal-assignment", + "Description": "Secret-like literal assignment in source, YAML, env and config files", + "StartLine": 8, + "EndLine": 8, + "StartColumn": 3, + "EndColumn": 20, + "Match": "password = 'REDACTED'", + "Secret": "REDACTED", + "Attributes": { + "git.author_email": "valentinab25", + "git.author_name": "valentinab25", + "git.date": "2021-05-25T17:18:22Z", + "git.message": "Cypress coverage", + "git.platform": "github", + "git.remote_url": "https://github.com/eea/volto-object-widget", + "git.sha": "d274f575bc425483bcf1bb84e1762bdf22462ec1", + "path": "cypress/support/commands.js", + "resource": "git.patch_content", + "url": "https://github.com/eea/volto-object-widget/blob/d274f575bc425483bcf1bb84e1762bdf22462ec1/cypress/support/commands.js#L8" + }, + "Tags": [ + "literal-secret", + "literal-secret" + ], + "Fingerprint": "d274f575bc425483bcf1bb84e1762bdf22462ec1:cypress/support/commands.js:secret-literal-assignment:8", + "File": "cypress/support/commands.js", + "SymlinkFile": "", + "Commit": "d274f575bc425483bcf1bb84e1762bdf22462ec1", + "Entropy": 2.321928, + "Author": "valentinab25", + "Email": "valentinab25", + "Date": "2021-05-25T17:18:22Z", + "Message": "Cypress coverage" + }, + { + "RuleID": "secret-literal-assignment", + "Description": "Secret-like literal assignment in source, YAML, env and config files", + "StartLine": 15, + "EndLine": 15, + "StartColumn": 28, + "EndColumn": 46, + "Match": "password: REDACTED", + "Secret": "REDACTED", + "Attributes": { + "git.author_email": "valentinab25", + "git.author_name": "valentinab25", + "git.date": "2021-05-25T17:18:22Z", + "git.message": "Cypress coverage", + "git.platform": "github", + "git.remote_url": "https://github.com/eea/volto-object-widget", + "git.sha": "d274f575bc425483bcf1bb84e1762bdf22462ec1", + "path": "cypress/support/commands.js", + "resource": "git.patch_content", + "url": "https://github.com/eea/volto-object-widget/blob/d274f575bc425483bcf1bb84e1762bdf22462ec1/cypress/support/commands.js#L15" + }, + "Tags": [ + "literal-secret", + "literal-secret" + ], + "Fingerprint": "d274f575bc425483bcf1bb84e1762bdf22462ec1:cypress/support/commands.js:secret-literal-assignment:15", + "File": "cypress/support/commands.js", + "SymlinkFile": "", + "Commit": "d274f575bc425483bcf1bb84e1762bdf22462ec1", + "Entropy": 2.947703, + "Author": "valentinab25", + "Email": "valentinab25", + "Date": "2021-05-25T17:18:22Z", + "Message": "Cypress coverage" + }, + { + "RuleID": "secret-literal-assignment", + "Description": "Secret-like literal assignment in source, YAML, env and config files", + "StartLine": 8, + "EndLine": 8, + "StartColumn": 3, + "EndColumn": 20, + "Match": "password = 'REDACTED'", + "Secret": "REDACTED", + "Attributes": { + "git.author_email": "alin.voinea@eaudeweb.ro", + "git.author_name": "Alin Voinea", + "git.date": "2021-06-04T14:07:58Z", + "git.message": "Cypress coverage (#8)\n\n* Cypress coverage\n\n* Automated release 2.2.2\n\nCo-authored-by: valentinab25 \u003cvalentinab25\u003e\nCo-authored-by: EEA Jenkins \u003c@users.noreply.github.com\u003e", + "git.platform": "github", + "git.remote_url": "https://github.com/eea/volto-object-widget", + "git.sha": "883e419076e90ec9b21cfb31961c01310f2ad68a", + "path": "cypress/support/commands.js", + "resource": "git.patch_content", + "url": "https://github.com/eea/volto-object-widget/blob/883e419076e90ec9b21cfb31961c01310f2ad68a/cypress/support/commands.js#L8" + }, + "Tags": [ + "literal-secret", + "literal-secret" + ], + "Fingerprint": "883e419076e90ec9b21cfb31961c01310f2ad68a:cypress/support/commands.js:secret-literal-assignment:8", + "File": "cypress/support/commands.js", + "SymlinkFile": "", + "Commit": "883e419076e90ec9b21cfb31961c01310f2ad68a", + "Entropy": 2.321928, + "Author": "Alin Voinea", + "Email": "alin.voinea@eaudeweb.ro", + "Date": "2021-06-04T14:07:58Z", + "Message": "Cypress coverage (#8)\n\n* Cypress coverage\n\n* Automated release 2.2.2\n\nCo-authored-by: valentinab25 \u003cvalentinab25\u003e\nCo-authored-by: EEA Jenkins \u003c@users.noreply.github.com\u003e" + }, + { + "RuleID": "secret-literal-assignment", + "Description": "Secret-like literal assignment in source, YAML, env and config files", + "StartLine": 15, + "EndLine": 15, + "StartColumn": 28, + "EndColumn": 46, + "Match": "password: REDACTED", + "Secret": "REDACTED", + "Attributes": { + "git.author_email": "alin.voinea@eaudeweb.ro", + "git.author_name": "Alin Voinea", + "git.date": "2021-06-04T14:07:58Z", + "git.message": "Cypress coverage (#8)\n\n* Cypress coverage\n\n* Automated release 2.2.2\n\nCo-authored-by: valentinab25 \u003cvalentinab25\u003e\nCo-authored-by: EEA Jenkins \u003c@users.noreply.github.com\u003e", + "git.platform": "github", + "git.remote_url": "https://github.com/eea/volto-object-widget", + "git.sha": "883e419076e90ec9b21cfb31961c01310f2ad68a", + "path": "cypress/support/commands.js", + "resource": "git.patch_content", + "url": "https://github.com/eea/volto-object-widget/blob/883e419076e90ec9b21cfb31961c01310f2ad68a/cypress/support/commands.js#L15" + }, + "Tags": [ + "literal-secret", + "literal-secret" + ], + "Fingerprint": "883e419076e90ec9b21cfb31961c01310f2ad68a:cypress/support/commands.js:secret-literal-assignment:15", + "File": "cypress/support/commands.js", + "SymlinkFile": "", + "Commit": "883e419076e90ec9b21cfb31961c01310f2ad68a", + "Entropy": 2.947703, + "Author": "Alin Voinea", + "Email": "alin.voinea@eaudeweb.ro", + "Date": "2021-06-04T14:07:58Z", + "Message": "Cypress coverage (#8)\n\n* Cypress coverage\n\n* Automated release 2.2.2\n\nCo-authored-by: valentinab25 \u003cvalentinab25\u003e\nCo-authored-by: EEA Jenkins \u003c@users.noreply.github.com\u003e" + }, + { + "RuleID": "env-short-secret-assignment", + "Description": "Uppercase env-style PASS/TOKEN/SECRET assignment", + "StartLine": 36, + "EndLine": 36, + "StartColumn": 11, + "EndColumn": 49, + "Match": "GITHUB_TOKEN=REDACTED", + "Secret": "REDACTED", + "Attributes": { + "git.author_email": "miu.razvan28@gmail.com", + "git.author_name": "Miu Razvan", + "git.date": "2022-10-25T10:29:27Z", + "git.message": "Use latest cypress + bring add-on up to date", + "git.platform": "github", + "git.remote_url": "https://github.com/eea/volto-object-widget", + "git.sha": "f1c4c50797ea25365d4bc28839f5bb10013ad423", + "path": "RELEASE.md", + "resource": "git.patch_content", + "url": "https://github.com/eea/volto-object-widget/blob/f1c4c50797ea25365d4bc28839f5bb10013ad423/RELEASE.md?plain=1#L36" + }, + "Tags": [ + "env", + "literal-secret", + "env", + "literal-secret" + ], + "Fingerprint": "f1c4c50797ea25365d4bc28839f5bb10013ad423:RELEASE.md:env-short-secret-assignment:36", + "File": "RELEASE.md", + "SymlinkFile": "", + "Commit": "f1c4c50797ea25365d4bc28839f5bb10013ad423", + "Entropy": 0.23519339, + "Author": "Miu Razvan", + "Email": "miu.razvan28@gmail.com", + "Date": "2022-10-25T10:29:27Z", + "Message": "Use latest cypress + bring add-on up to date" + }, + { + "RuleID": "env-short-secret-assignment", + "Description": "Uppercase env-style PASS/TOKEN/SECRET assignment", + "StartLine": 235, + "EndLine": 235, + "StartColumn": 11, + "EndColumn": 49, + "Match": "GITHUB_TOKEN=REDACTED", + "Secret": "REDACTED", + "Attributes": { + "git.author_email": "valentinab25", + "git.author_name": "valentinab25", + "git.date": "2021-12-16T17:01:46Z", + "git.message": "[JENKINS] Refs #142742 - Add release documentation", + "git.platform": "github", + "git.remote_url": "https://github.com/eea/volto-object-widget", + "git.sha": "9e888e25f098d4d1e556472eb1d1d85419050466", + "path": "README.md", + "resource": "git.patch_content", + "url": "https://github.com/eea/volto-object-widget/blob/9e888e25f098d4d1e556472eb1d1d85419050466/README.md?plain=1#L235" + }, + "Tags": [ + "env", + "literal-secret", + "env", + "literal-secret" + ], + "Fingerprint": "9e888e25f098d4d1e556472eb1d1d85419050466:README.md:env-short-secret-assignment:235", + "File": "README.md", + "SymlinkFile": "", + "Commit": "9e888e25f098d4d1e556472eb1d1d85419050466", + "Entropy": 0.23519339, + "Author": "valentinab25", + "Email": "valentinab25", + "Date": "2021-12-16T17:01:46Z", + "Message": "[JENKINS] Refs #142742 - Add release documentation" + } +] diff --git a/.cookieplone.json b/.cookieplone.json new file mode 100644 index 0000000..382620a --- /dev/null +++ b/.cookieplone.json @@ -0,0 +1,7 @@ +{ + "title": "Object Widget", + "frontend_addon_name": "volto-object-widget", + "description": "volto-object-widget: Volto add-on", + "volto_version": "19.3.0", + "__template__": "frontend_addon" +} diff --git a/.coverage.babel.config.js b/.coverage.babel.config.js index 37219fd..c1a8b42 100644 --- a/.coverage.babel.config.js +++ b/.coverage.babel.config.js @@ -1,9 +1,27 @@ -const defaultBabel = require('@plone/volto/babel'); +// Coverage-enabled variant of the Volto babel config. `make start-ci` copies +// this file over core/packages/volto/babel.config.js so that +// babel-plugin-istanbul instruments the app and Cypress can collect +// end-to-end coverage. +// +// Instrumenting the whole workspace breaks the client build (webpack 5 pulls +// server-only code in once tree-shaking is disabled), so only the add-on +// sources are instrumented: they are the only ones SonarQube analyses. +// `cwd` must be the workspace root (/app), otherwise test-exclude would +// ignore the add-on files, which live outside the Volto core package. +const path = require('path'); -function applyDefault(api) { +const defaultBabel = require('./babel'); + +const workspaceRoot = path.resolve(__dirname, '../../..'); + +module.exports = function (api) { const voltoBabel = defaultBabel(api); - voltoBabel.plugins.push('istanbul'); + voltoBabel.plugins.push([ + 'istanbul', + { + cwd: workspaceRoot, + include: ['packages/*/src/**'], + }, + ]); return voltoBabel; -} - -module.exports = applyDefault; +}; diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b9a4d6e --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +.git +node_modules +core +build +coverage +*.log +.DS_Store +cypress/screenshots +cypress/videos +cypress/reports \ No newline at end of file diff --git a/.env b/.env deleted file mode 100644 index 7afcd38..0000000 --- a/.env +++ /dev/null @@ -1 +0,0 @@ -JEST_USE_SETUP=OFF # Jest configuration variables: ON, OFF diff --git a/.eslintrc.js b/.eslintrc.js index c3c4cc1..be1ba7c 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,23 +1,14 @@ const fs = require('fs'); -const path = require('path'); -const projectRootPath = fs.realpathSync(__dirname + '/../../../'); - -let voltoPath = path.join(projectRootPath, 'node_modules/@plone/volto'); -let configFile; -if (fs.existsSync(`${projectRootPath}/tsconfig.json`)) - configFile = `${projectRootPath}/tsconfig.json`; -else if (fs.existsSync(`${projectRootPath}/jsconfig.json`)) - configFile = `${projectRootPath}/jsconfig.json`; +const projectRootPath = __dirname; +const { AddonRegistry } = require('@plone/registry/addon-registry'); -if (configFile) { - const jsConfig = require(configFile).compilerOptions; - const pathsConfig = jsConfig.paths; - if (pathsConfig['@plone/volto']) - voltoPath = `./${jsConfig.baseUrl}/${pathsConfig['@plone/volto'][0]}`; -} +let coreLocation; +if (fs.existsSync(`${projectRootPath}/core`)) + coreLocation = `${projectRootPath}/core`; +else if (fs.existsSync(`${projectRootPath}/../../core`)) + coreLocation = `${projectRootPath}/../../core`; -const { AddonRegistry } = require('@plone/registry/addon-registry'); -const { registry } = AddonRegistry.init(projectRootPath); +const { registry } = AddonRegistry.init(`${coreLocation}/packages/volto`); // Extends ESlint configuration for adding the aliases to `src` directories in Volto addons const addonAliases = Object.keys(registry.packages).map((o) => [ @@ -25,41 +16,26 @@ const addonAliases = Object.keys(registry.packages).map((o) => [ registry.packages[o].modulePath, ]); -const addonExtenders = registry.getEslintExtenders().map((m) => require(m)); - -const defaultConfig = { - extends: `${voltoPath}/.eslintrc`, +module.exports = { + extends: `${coreLocation}/packages/volto/.eslintrc`, + rules: { + 'import/no-unresolved': 1, + }, settings: { 'import/resolver': { alias: { map: [ - ['@plone/volto', '@plone/volto/src'], - ['@plone/volto-slate', '@plone/volto-slate/src'], + ['@plone/volto', `${coreLocation}/packages/volto/src`], + ['@plone/volto-slate', `${coreLocation}/packages/volto-slate/src`], + ['@plone/registry', `${coreLocation}/packages/registry/src`], + [ + '@eeacms/volto-object-widget', + './packages/volto-object-widget/src', + ], ...addonAliases, - ['@package', `${__dirname}/src`], - ['@root', `${__dirname}/src`], - ['~', `${__dirname}/src`], ], - extensions: ['.js', '.jsx', '.json'], - }, - 'babel-plugin-root-import': { - rootPathSuffix: 'src', + extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'], }, }, }, - rules: { - 'react/jsx-no-target-blank': [ - 'error', - { - allowReferrer: true, - }, - ], - } }; - -const config = addonExtenders.reduce( - (acc, extender) => extender.modify(acc), - defaultConfig, -); - -module.exports = config; diff --git a/.github/workflows/betterleaks-audit.yml b/.github/workflows/betterleaks-audit.yml new file mode 100644 index 0000000..d68f013 --- /dev/null +++ b/.github/workflows/betterleaks-audit.yml @@ -0,0 +1,29 @@ +name: Betterleaks history audit + +on: + schedule: + - cron: "0 3 * * 1" # Mondays 03:00 UTC + workflow_dispatch: + +permissions: + contents: read + +jobs: + audit: + name: Scan all commits for secrets + runs-on: ubuntu-latest + timeout-minutes: 70 # outer guard; the scan itself stops after timeout-minutes below + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 # all commits of all branches + + # Shared EEA secret scan: https://github.com/eea/github-actions/tree/main/betterleaks#weekly-full-history-audit + # Findings already handled are listed in .betterleaks-history-baseline.json. + - uses: eea/github-actions/betterleaks@v1 + with: + mode: git + log-opts: --all + baseline: .betterleaks-history-baseline.json + timeout-minutes: 60 diff --git a/.github/workflows/betterleaks.yml b/.github/workflows/betterleaks.yml index e3ee2df..e916b59 100644 --- a/.github/workflows/betterleaks.yml +++ b/.github/workflows/betterleaks.yml @@ -5,129 +5,30 @@ on: pull_request: permissions: - contents: read + contents: write jobs: scan: name: Scan for secrets + # push covers branches in this repo; pull_request is only needed for forks + if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.repository runs-on: ubuntu-latest - env: - SMTP_URL: ${{ secrets.SMTP_URL }} - SMTP_PORT: ${{ secrets.SMTP_PORT || '25' }} - SMTP_EMAIL: ${{ secrets.SMTP_EMAIL }} - SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }} + timeout-minutes: 20 # outer guard; the scan itself stops after timeout-minutes below steps: - - name: Checkout repository - uses: actions/checkout@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: + persist-credentials: false fetch-depth: 1 ref: ${{ github.event.pull_request.head.sha || github.sha }} - - name: Run Betterleaks - id: betterleaks - continue-on-error: true - uses: dortort/betterleaks-action@v0.1.0 + # Shared EEA secret scan: https://github.com/eea/github-actions/tree/main/betterleaks + # Findings show as annotations on this check (file and line), with a job summary. + - uses: eea/github-actions/betterleaks@v1 with: - github-token: ${{ secrets.GITHUB_TOKEN }} - scan-mode: dir - scan-path: . - config: .gitleaks.toml - report-format: json - report-path: betterleaks-report.json - redact: "true" - no-color: "true" - no-banner: "true" - fail-on-leak: "true" - - - name: Upload Betterleaks report - if: always() - uses: actions/upload-artifact@v4 - with: - name: betterleaks-report - path: betterleaks-report.json - if-no-files-found: ignore - - - name: Build Betterleaks email summary - id: leak_summary - if: steps.betterleaks.outcome == 'failure' - shell: bash - run: | - if [[ -s betterleaks-report.json ]]; then - jq -r ' - def one_line: - tostring - | gsub("[\r\n]+"; " ") - | if length > 240 then .[0:240] + "..." else . end; - - .[:20][] - | "- " + (.RuleID // "unknown-rule") - + " at " + (.File // "unknown-file") - + ":" + ((.StartLine // 0) | tostring) - + "\n match: " + ((.Match // .Secret // "REDACTED") | one_line) - ' betterleaks-report.json > betterleaks-email-summary.txt - - count="$(jq 'length' betterleaks-report.json)" - if (( count > 20 )); then - { - echo "" - echo "... and $((count - 20)) more finding(s). Download the artifact for full details." - } >> betterleaks-email-summary.txt - fi - else - echo "No JSON report was generated. Download the workflow logs for details." > betterleaks-email-summary.txt - fi - - { - echo "text<> "$GITHUB_OUTPUT" - - - name: Resolve committer email - id: committer - if: steps.betterleaks.outcome == 'failure' - shell: bash - run: | - committer_email="$(git log -1 --format='%ce')" - author_email="$(git log -1 --format='%ae')" - email="$committer_email" - if [[ -z "$email" || "$email" == *"noreply.github.com"* ]]; then - email="$author_email" - fi - if [[ "$email" =~ ^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$ && "$email" != *"noreply.github.com"* ]]; then - echo "email=$email" >> "$GITHUB_OUTPUT" - else - echo "No deliverable committer email found; skipping Betterleaks email notification." - echo "email=" >> "$GITHUB_OUTPUT" - fi - - - name: Email committer on Betterleaks failure - if: steps.betterleaks.outcome == 'failure' && steps.committer.outputs.email != '' && env.SMTP_URL != '' && env.SMTP_EMAIL != '' - uses: dawidd6/action-send-mail@v18 - with: - server_address: ${{ env.SMTP_URL }} - server_port: ${{ env.SMTP_PORT }} - secure: ${{ env.SMTP_PORT == '465' }} - username: ${{ env.SMTP_EMAIL }} - password: ${{ env.SMTP_PASSWORD }} - from: ${{ env.SMTP_EMAIL }} - to: ${{ steps.committer.outputs.email }} - subject: "[Betterleaks] Secret scan failed in ${{ github.repository }}" - body: | - Betterleaks detected one or more potential secrets. - - Repository: ${{ github.repository }} - Branch: ${{ github.ref_name }} - Commit: ${{ github.sha }} - Workflow run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - - Findings: - ${{ steps.leak_summary.outputs.text }} - - Download the betterleaks-report artifact from the workflow run for details. - - - name: Fail if Betterleaks found leaks - if: steps.betterleaks.outcome == 'failure' - run: | - echo "Betterleaks detected one or more secrets. Download the betterleaks-report artifact from this workflow run for details." - exit 1 + timeout-minutes: 15 + mention-author: "true" + smtp-url: ${{ secrets.SMTP_URL }} + smtp-port: ${{ secrets.SMTP_PORT || '25' }} + smtp-email: ${{ secrets.SMTP_EMAIL }} + smtp-password: ${{ secrets.SMTP_PASSWORD }} + fallback-email: ${{ vars.BETTERLEAKS_FALLBACK_EMAIL }} diff --git a/.gitignore b/.gitignore index f1be4ff..321c66e 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,12 @@ videos .env.test.local .env.production.local *~ +.*project +.settings/ +.vscode +acceptance/cypress/videos/ +acceptance/node_modules +.storybook-build +/core +results +/public diff --git a/.gitleaks.toml b/.gitleaks.toml index d26a674..2b75f29 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -61,23 +61,10 @@ entropy = 2.5 keywords = ["sk-"] tags = ["standalone-token", "generic"] -[[rules]] -id = "dotenv-only-jest-setup" -description = ".env may only contain the committed Jest setup lines" -path = '''(?i)(^|/)\.env$''' -regex = '''(?m)^(.+)$''' -secretGroup = 1 -tags = ["file", "dotenv"] -[[rules.allowlists]] -regexTarget = "match" -regexes = [ - '''^JEST_USE_SETUP=OFF # Jest configuration variables: ON, OFF\r?$''', -] - [[rules]] id = "forbidden-secret-file" description = "Forbidden secret-bearing file committed to repository" -path = '''(?i)(^|/)(\.env\..*|\.npmrc|\.pypirc|id_rsa|id_ed25519|.*\.(pem|key|p12|pfx|jks|kubeconfig))$''' +path = '''(?i)(^|/)(\.env\..*|\.pypirc|id_rsa|id_ed25519|.*\.(pem|key|p12|pfx|jks|kubeconfig))$''' regex = '''(?s).{1,}''' tags = ["file", "secret-file"] @@ -87,3 +74,10 @@ regexTarget = "match" regexes = [ '''SONAR_AUTH_TOKEN''', ] + +[[allowlists]] +description = "Ignore generated development workspace dependencies" +paths = [ + '''(^|/)core/''', + '''(^|/)node_modules/''', +] diff --git a/.husky/pre-commit b/.husky/pre-commit index 9183f9d..17092dc 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,2 +1,2 @@ [ -n "$CI" ] && exit 0 -yarn lint-staged +pnpm lint-staged diff --git a/.npmignore b/.npmignore index 080322a..eb6fa94 100644 --- a/.npmignore +++ b/.npmignore @@ -1,96 +1,16 @@ -# https://docs.npmjs.com/using-npm/developers.html#keeping-files-out-of-your-package - -# Directories -api/ -bin/ -build/ -lib/ -g-api/ -tests/ - -# Docs -docs/ - -# Cypress -cypress/ - -# Tests -__tests__/ -*.snap - -# Files -.travis.yml -requirements-docs.txt -requirements-tests.txt -yarn.lock -.dockerignore -.gitattributes -.yarnrc -.nvmrc -changelogupdater.js -pip-selfcheck.json -Dockerfile -CNAME -entrypoint.sh -Jenkinsfile -Makefile - -# Logs +.vscode/ +.history logs *.log npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# nyc test coverage -.nyc_output - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (https://nodejs.org/api/addons.html) -build/Release - -# Dependency directories -node_modules/ -jspm_packages/ - -# TypeScript v1 declaration files -typings/ - -# Optional npm cache directory -.npm - -# Optional eslint cache -.eslintcache - -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# Yarn Integrity file -.yarn-integrity - -# dotenv environment variables file -.env - -# next.js build output -.next - -styleguide.config -.vscode -packages +.DS_Store +*.swp +yarn-error.log + +node_modules +dockerfiles +acceptance +build +dist +yarn.lock +.storybook diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..a770dea --- /dev/null +++ b/.npmrc @@ -0,0 +1,6 @@ +public-hoist-pattern[]=*eslint* +public-hoist-pattern[]=*prettier* +public-hoist-pattern[]=*stylelint* +public-hoist-pattern[]=*cypress* +public-hoist-pattern[]=babel-plugin-react-intl +public-hoist-pattern[]=*babel-preset-razzle diff --git a/.pnpmfile.cjs b/.pnpmfile.cjs new file mode 100644 index 0000000..7e9c7b2 --- /dev/null +++ b/.pnpmfile.cjs @@ -0,0 +1,23 @@ +/* eslint-disable */ +const fs = require('fs'); +const path = require('path'); + +const catalogPath = path.resolve(__dirname, 'core/catalog.json'); +let catalog = {}; +if (fs.existsSync(catalogPath)) { + const catalogData = fs.readFileSync(catalogPath, 'utf-8'); + catalog = JSON.parse(catalogData); +} else { + console.error('Catalog file does not exist at:', catalogPath); +} + +module.exports = { + hooks: { + updateConfig(config) { + if (config.catalogs) { + config.catalogs.default ??= catalog; + } + return config; + }, + }, +}; diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..16f05c7 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,3 @@ +.storybook +CHANGELOG.md +README.md diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..c56f626 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,12 @@ +{ + "trailingComma": "all", + "singleQuote": true, + "overrides": [ + { + "files": "*.overrides", + "options": { + "parser": "less" + } + } + ] + } diff --git a/.storybook/main.js b/.storybook/main.js new file mode 100644 index 0000000..a645419 --- /dev/null +++ b/.storybook/main.js @@ -0,0 +1,192 @@ +const webpack = require('webpack'); +const fs = require('fs'); +const path = require('path'); + +const projectRootPath = path.resolve('.'); +const lessPlugin = require('@plone/volto/webpack-plugins/webpack-less-plugin'); +const RelativeResolverPlugin = require('@plone/volto/webpack-plugins/webpack-relative-resolver'); +const scssPlugin = require('@plone/volto/webpack-plugins/webpack-scss-plugin'); +const createConfig = require('@plone/razzle/config/createConfigAsync.js'); +const razzleConfig = require(path.join(projectRootPath, 'razzle.config.js')); + +const SVGLOADER = { + test: /icons\/.*\.svg$/, + use: [ + { + loader: 'svg-loader', + }, + { + loader: 'svgo-loader', + options: { + plugins: [ + { + name: 'preset-default', + params: { + overrides: { + convertPathData: false, + removeViewBox: false, + }, + }, + }, + 'removeTitle', + 'removeUselessStrokeAndFill', + ], + }, + }, + ], +}; + +const defaultRazzleOptions = { + verbose: false, + debug: {}, + buildType: 'iso', + cssPrefix: 'static/css', + jsPrefix: 'static/js', + enableSourceMaps: true, + enableReactRefresh: true, + enableTargetBabelrc: false, + enableBabelCache: true, + forceRuntimeEnvVars: [], + mediaPrefix: 'static/media', + staticCssInDev: false, + emitOnErrors: false, + disableWebpackbar: false, + browserslist: [ + '>1%', + 'last 4 versions', + 'Firefox ESR', + 'not ie 11', + 'not dead', + ], +}; + +module.exports = { + stories: [ + '../packages/**/*.mdx', + '../packages/**/*.stories.@(js|jsx|ts|tsx)', + ], + addons: [ + '@storybook/addon-links', + '@storybook/addon-essentials', + '@storybook/addon-webpack5-compiler-babel', + ], + framework: { + name: '@storybook/react-webpack5', + options: { builder: { useSWC: true } }, + }, + typescript: { + check: false, + checkOptions: {}, + reactDocgen: 'react-docgen-typescript', + reactDocgenTypescriptOptions: { + compilerOptions: { + allowSyntheticDefaultImports: false, + esModuleInterop: false, + }, + propFilter: () => true, + }, + }, + webpackFinal: async (config, { configType }) => { + // `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION' + // You can change the configuration based on that. + // 'PRODUCTION' is used when building the static version of storybook. + + // Make whatever fine-grained changes you need + let baseConfig; + baseConfig = await createConfig( + 'web', + 'dev', + { + // clearConsole: false, + modifyWebpackConfig: razzleConfig.modifyWebpackConfig, + plugins: razzleConfig.plugins, + }, + webpack, + false, + undefined, + [], + defaultRazzleOptions, + ); + const { AddonRegistry } = require('@plone/registry/addon-registry'); + + const { registry } = AddonRegistry.init(projectRootPath); + + config = lessPlugin({ registry }).modifyWebpackConfig({ + env: { target: 'web', dev: 'dev' }, + webpackConfig: config, + webpackObject: webpack, + options: {}, + }); + + config = scssPlugin.modifyWebpackConfig({ + env: { target: 'web', dev: 'dev' }, + webpackConfig: config, + webpackObject: webpack, + options: { razzleOptions: {} }, + }); + + // Put the SVG loader on top and prevent the asset/resource rule + // from processing the app's SVGs + config.module.rules.unshift(SVGLOADER); + const fileLoaderRule = config.module.rules.find((rule) => + rule.test.test('.svg'), + ); + fileLoaderRule.exclude = /icons\/.*\.svg$/; + + config.plugins.unshift( + new webpack.DefinePlugin({ + __DEVELOPMENT__: true, + __CLIENT__: true, + __SERVER__: false, + }), + ); + + const resultConfig = { + ...config, + resolve: { + ...config.resolve, + alias: { ...config.resolve.alias, ...baseConfig.resolve.alias }, + fallback: { ...config.resolve.fallback, zlib: false }, + plugins: [ + ...(config.resolve.plugins || []), + new RelativeResolverPlugin(registry), + ], + }, + }; + + // Add-ons have to be loaded with babel + const addonPaths = registry + .getAddons() + .map((addon) => fs.realpathSync(addon.modulePath)); + + resultConfig.module.rules[13].exclude = (input) => + // exclude every input from node_modules except from @plone/volto + /node_modules\/(?!(@plone\/volto)\/)/.test(input) && + // Storybook default exclusions + /storybook-config-entry\.js$/.test(input) && + /storybook-stories\.js$/.test(input) && + // If input is in an addon, DON'T exclude it + !addonPaths.some((p) => input.includes(p)); + + resultConfig.module.rules[13].include = [ + /preview\.jsx/, + ...resultConfig.module.rules[13].include, + ...addonPaths, + ]; + + const addonExtenders = registry.getAddonExtenders().map((m) => require(m)); + + const extendedConfig = addonExtenders.reduce( + (acc, extender) => + extender.modify(acc, { target: 'web', dev: 'dev' }, config), + resultConfig, + ); + + // Note: we don't actually support razzle plugins, which are also a feature + // of the razzle.extend.js addons file. Those features are probably + // provided in a different manner by Storybook plugins (for example scss + // loaders). + + return extendedConfig; + }, +}; diff --git a/.storybook/preview.jsx b/.storybook/preview.jsx new file mode 100644 index 0000000..1d2ac84 --- /dev/null +++ b/.storybook/preview.jsx @@ -0,0 +1,26 @@ +import '@plone/volto/config'; // This is the bootstrap for the global config - client side +import React from 'react'; +import { StaticRouter } from 'react-router-dom'; +import { IntlProvider } from 'react-intl'; +import enMessages from '@root/../locales/en.json'; + +import '@root/theme'; + +export const parameters = { + controls: { + matchers: { + color: /(background|color)$/i, + date: /Date$/, + }, + }, +}; + +export const decorators = [ + (Story) => ( + + + + + + ), +]; diff --git a/.stylelintrc b/.stylelintrc new file mode 100644 index 0000000..09d4a27 --- /dev/null +++ b/.stylelintrc @@ -0,0 +1,32 @@ +{ + "extends": [ + "stylelint-config-idiomatic-order" + ], + "plugins": [ + "stylelint-prettier" + ], + "overrides": [ + { + "files": [ + "**/*.less" + ], + "customSyntax": "postcss-less" + }, + { + "files": [ + "**/*.overrides" + ], + "customSyntax": "postcss-less" + }, + { + "files": [ + "**/*.scss" + ], + "customSyntax": "postcss-scss" + } + ], + "rules": { + "prettier/prettier": true, + "order/properties-alphabetical-order": null + } +} diff --git a/DEVELOP.md b/DEVELOP.md index 61530df..362b745 100644 --- a/DEVELOP.md +++ b/DEVELOP.md @@ -106,3 +106,62 @@ Or run it: ```Bash make cypress-run ``` + +## Secret Scanning + +This repository uses the Betterleaks GitHub Action to scan the current +repository content on every push and pull request. The scan uses the rules in +`.gitleaks.toml` and uploads a `betterleaks-report` artifact when a finding is +detected. + +If the optional SMTP secrets are configured, failed scans also send an email to +the last commit committer. The workflow expects these repository or +organization secrets: + +- `SMTP_URL` +- `SMTP_PORT` (optional, defaults to `25`) +- `SMTP_EMAIL` +- `SMTP_PASSWORD` (optional if the SMTP server does not require authentication) + +Port `465` is sent with direct TLS; other ports use the default SMTP handshake. +The email includes a short finding summary from the redacted Betterleaks report, +including the redacted matched line from each finding. + +There are three common outcomes: + +1. **Everything is OK.** The `Betterleaks / Scan for secrets` check is green and + no action is needed. Regular references to runtime values are OK, for example: + + ```js + const tokenFromCookie = req.universalCookies.get('auth_token'); + ``` + +2. **A real secret was found.** The check is red and the workflow log asks you to + download the `betterleaks-report` artifact. Open the artifact from the GitHub + Actions run and check the reported file, line and rule. Remove the committed + value, move it to the proper secret store, and rotate it if it was exposed. + A report entry looks like this: + + ```json + { + "RuleID": "secret-literal-assignment", + "File": "src/config.js", + "StartLine": 12, + "Secret": "[REDACTED]" + } + ``` + +3. **The finding is a false positive.** Keep the value only if it is clearly not + sensitive, such as a test fixture, placeholder, or public example. Add + `betterleaks:allow` on the same line and include a short explanation in the + pull request. + + ```js + const testPassword = 'admin'; //betterleaks:allow + ``` + + ```yaml + password: "admin" #betterleaks:allow + ``` + +Do not add `betterleaks:allow` to real credentials. diff --git a/Dockerfile b/Dockerfile index 77da85e..e941e56 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,48 +1,14 @@ # syntax=docker/dockerfile:1 +# Add-on overlay onto eeacms/frontend-builder (Volto + Chromium base). ARG VOLTO_VERSION -FROM plone/frontend-builder:${VOLTO_VERSION} +FROM eeacms/frontend-builder:${VOLTO_VERSION} -ARG ADDON_NAME ARG ADDON_PATH -ARG CHROMIUM_VERSION=149.0.7827.196-1~deb12u1 - - -ENV HOST="0.0.0.0" -ENV CHROME_BIN="/usr/bin/chromium" -ENV CHROMIUM_BIN="/usr/bin/chromium" -ENV CYPRESS_BROWSER_PATH="/usr/bin/chromium" - -# Install Cypress dependencies (matching eeacms/frontend-builder) -USER root -RUN apt-get update -q \ - && apt-get install -qy --no-install-recommends \ - libgtk2.0-0 libgtk-3-0 libgbm-dev libnotify-dev libgconf-2-4 libnss3 libxss1 libasound2 libxtst6 xauth xvfb \ - && rm -rf /var/lib/apt/lists/* - -RUN set -eux; \ - mkdir -p /etc/apt/sources.list.d /etc/apt/preferences.d /etc/apt/apt.conf.d; \ - printf '%s\n' \ - 'Acquire::Check-Valid-Until "false";' \ - > /etc/apt/apt.conf.d/99snapshot-no-check-valid-until; \ - printf '%s\n' \ - 'deb [check-valid-until=no] http://snapshot.debian.org/archive/debian-security/20260630T000000Z bookworm-security main' \ - 'deb [check-valid-until=no] http://snapshot.debian.org/archive/debian/20260630T000000Z bookworm main' \ - > /etc/apt/sources.list.d/bookworm-chromium149-snapshot.list; \ - apt-get update -q; \ - apt-get install -qy --no-install-recommends \ - "chromium=${CHROMIUM_VERSION}" \ - "chromium-common=${CHROMIUM_VERSION}" \ - ; \ - apt-mark hold chromium chromium-common ; \ - rm -rf /var/lib/apt/lists/* - -USER node +# Overlay the add-on onto the base; rm -rf /app/cypress so the add-on's EEA +# cypress replaces the base's upstream Volto one. COPY --chown=node:node ./ /app/src/addons/${ADDON_PATH}/ - -RUN /setupAddon -RUN yarn add jest-junit -RUN yarn install - -ENTRYPOINT ["yarn"] -CMD ["start"] +RUN rm -rf /app/cypress \ + && cp -r /app/src/addons/${ADDON_PATH}/. /app/ \ + && pnpm install \ + && make build-deps \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile index 18af911..123be6c 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -2,6 +2,7 @@ pipeline { agent { node { label 'docker-host' } } + environment { GIT_NAME = "volto-object-widget" NAMESPACE = "@eeacms" @@ -9,8 +10,8 @@ pipeline { DEPENDENCIES = "" BACKEND_PROFILES = "eea.kitkat:testing" BACKEND_ADDONS = "" - CURRENT_VOLTO = "18-yarn" - PREVIOUS_VOLTO = "17" + CURRENT_VOLTO = "19" + PREVIOUS_VOLTO = "18" IMAGE_NAME = BUILD_TAG.toLowerCase() } @@ -71,13 +72,13 @@ pipeline { } parallel { - // Declarative stage names must stay string literals. - stage('Volto 18-yarn') { + // Volto 19 (current) — full testing with EEA Makefile targets + stage('Volto 19') { agent { node { label 'docker-1.13'} } stages { - stage('Build test image') { + stage('Build test image') { steps { - sh '''docker build --pull --build-arg="VOLTO_VERSION=$CURRENT_VOLTO" --build-arg="ADDON_NAME=$NAMESPACE/$GIT_NAME" --build-arg="ADDON_PATH=$GIT_NAME" . -t $IMAGE_NAME-frontend-current''' + sh '''docker build --pull --build-arg="VOLTO_VERSION=$CURRENT_VOLTO" --build-arg="ADDON_PATH=$GIT_NAME" . -t $IMAGE_NAME-frontend-current''' } } @@ -88,8 +89,8 @@ pipeline { } steps { script { - fix_result = sh(script: '''docker run --name="$IMAGE_NAME-fix-current" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-current ci-fix''', returnStatus: true) - sh '''docker cp $IMAGE_NAME-fix-current:/app/src/addons/$GIT_NAME/src .''' + fix_result = sh(script: '''docker run --name="$IMAGE_NAME-fix-current" --entrypoint=make --workdir=/app $IMAGE_NAME-frontend-current ci-fix''', returnStatus: true) + sh '''docker cp $IMAGE_NAME-fix-current:/app/packages/$GIT_NAME/src ./packages/$GIT_NAME/''' sh '''docker rm -v $IMAGE_NAME-fix-current''' FOUND_FIX = sh(script: '''git diff | wc -l''', returnStdout: true).trim() @@ -99,7 +100,7 @@ pipeline { } sh '''git fetch origin $GIT_BRANCH:$GIT_BRANCH''' sh '''git checkout $GIT_BRANCH''' - sh '''git add src/''' + sh '''git add packages/$GIT_NAME/src/''' sh '''git commit -m "style: Automated code fix" ''' sh '''git push --set-upstream origin $GIT_BRANCH''' sh '''exit 1''' @@ -111,35 +112,36 @@ pipeline { stage('ES lint') { when { environment name: 'SKIP_TESTS', value: '' } steps { - sh '''docker run --rm --name="$IMAGE_NAME-eslint-current" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-current lint''' + sh '''docker run --rm --name="$IMAGE_NAME-eslint-current" --entrypoint=make --workdir=/app $IMAGE_NAME-frontend-current lint''' } } stage('Style lint') { when { environment name: 'SKIP_TESTS', value: '' } steps { - sh '''docker run --rm --name="$IMAGE_NAME-stylelint-current" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-current stylelint''' + sh '''docker run --rm --name="$IMAGE_NAME-stylelint-current" --entrypoint=make --workdir=/app $IMAGE_NAME-frontend-current stylelint''' } } stage('Prettier') { when { environment name: 'SKIP_TESTS', value: '' } steps { - sh '''docker run --rm --name="$IMAGE_NAME-prettier-current" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-current prettier''' + sh '''docker run --rm --name="$IMAGE_NAME-prettier-current" --entrypoint=make --workdir=/app $IMAGE_NAME-frontend-current prettier''' } } + stage('Unit tests') { when { environment name: 'SKIP_TESTS', value: '' } steps { script { try { - sh '''docker run --name="$IMAGE_NAME-volto-current" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-current test-ci''' + sh '''docker run --name="$IMAGE_NAME-volto-current" --entrypoint=make --workdir=/app $IMAGE_NAME-frontend-current test-ci''' sh '''rm -rf xunit-reports-current''' sh '''mkdir -p xunit-reports-current''' - sh '''docker cp $IMAGE_NAME-volto-current:/app/coverage xunit-reports-current/''' - sh '''docker cp $IMAGE_NAME-volto-current:/app/junit.xml xunit-reports-current/''' + sh '''docker cp $IMAGE_NAME-volto-current:/app/packages/$GIT_NAME/coverage xunit-reports-current/ 2>/dev/null || true''' + sh '''docker cp $IMAGE_NAME-volto-current:/app/packages/$GIT_NAME/junit.xml xunit-reports-current/ 2>/dev/null || true''' publishHTML(target : [ - allowMissing: false, + allowMissing: true, alwaysLinkToLastBuild: true, keepAll: true, reportDir: 'xunit-reports-current/coverage/lcov-report', @@ -156,35 +158,35 @@ pipeline { } } } - + stage('Integration tests') { when { environment name: 'SKIP_TESTS', value: '' } steps { script { try { sh '''docker run --pull always --rm -d --name="$IMAGE_NAME-plone-current" -e SITE="Plone" -e PROFILES="$BACKEND_PROFILES" -e ADDONS="$BACKEND_ADDONS" eeacms/plone-backend''' - sh '''docker run -d --shm-size=4g --link $IMAGE_NAME-plone-current:plone --name="$IMAGE_NAME-cypress-current" -e "RAZZLE_INTERNAL_API_PATH=http://plone:8080/Plone" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-current start-ci''' - frontend = sh script:'''docker exec --workdir=/app/src/addons/${GIT_NAME} $IMAGE_NAME-cypress-current make check-ci''', returnStatus: true + sh '''docker run -d --shm-size=4g --link $IMAGE_NAME-plone-current:plone --name="$IMAGE_NAME-cypress-current" -e "RAZZLE_INTERNAL_API_PATH=http://plone:8080/Plone" --entrypoint=make --workdir=/app $IMAGE_NAME-frontend-current start-ci''' + frontend = sh script:'''docker exec --workdir=/app $IMAGE_NAME-cypress-current make check-ci''', returnStatus: true if ( frontend != 0 ) { sh '''docker logs $IMAGE_NAME-cypress-current; exit 1''' } - sh '''timeout -s 9 1800 docker exec --workdir=/app/src/addons/${GIT_NAME} $IMAGE_NAME-cypress-current make cypress-ci''' + sh '''timeout -s 9 1800 docker exec --workdir=/app $IMAGE_NAME-cypress-current make cypress-ci''' } finally { try { if ( frontend == 0 ) { sh '''rm -rf cypress-videos-current cypress-results-current cypress-coverage-current cypress-screenshots-current''' sh '''mkdir -p cypress-videos-current cypress-results-current cypress-coverage-current cypress-screenshots-current''' - videos = sh script: '''docker cp $IMAGE_NAME-cypress-current:/app/src/addons/$GIT_NAME/cypress/videos cypress-videos-current/''', returnStatus: true - sh '''docker cp $IMAGE_NAME-cypress-current:/app/src/addons/$GIT_NAME/cypress/reports cypress-results-current/''' - screenshots = sh script: '''docker cp $IMAGE_NAME-cypress-current:/app/src/addons/$GIT_NAME/cypress/screenshots cypress-screenshots-current''', returnStatus: true + videos = sh script: '''docker cp $IMAGE_NAME-cypress-current:/app/cypress/videos cypress-videos-current/''', returnStatus: true + sh '''docker cp $IMAGE_NAME-cypress-current:/app/cypress/reports cypress-results-current/''' + screenshots = sh script: '''docker cp $IMAGE_NAME-cypress-current:/app/cypress/screenshots cypress-screenshots-current''', returnStatus: true archiveArtifacts artifacts: 'cypress-screenshots-current/**', fingerprint: true, allowEmptyArchive: true - coverage = sh script: '''docker cp $IMAGE_NAME-cypress-current:/app/src/addons/$GIT_NAME/coverage cypress-coverage-current''', returnStatus: true + coverage = sh script: '''docker cp $IMAGE_NAME-cypress-current:/app/coverage cypress-coverage-current''', returnStatus: true if ( coverage == 0 ) { - publishHTML(target : [allowMissing: false, + publishHTML(target : [allowMissing: true, alwaysLinkToLastBuild: true, keepAll: true, reportDir: 'cypress-coverage-current/coverage/lcov-report', @@ -246,9 +248,9 @@ pipeline { env.sonarParams = " -Dsonar.branch.name='${env.BRANCH_NAME}'" } withSonarQubeEnv('Sonarqube') { - sh '''sed -i "s#/app/src/addons/${GIT_NAME}/##g" xunit-reports-current/coverage/lcov.info''' - sh '''sed -i "s#src/addons/${GIT_NAME}/##g" xunit-reports-current/coverage/lcov.info''' - sh "export PATH=${scannerHome}/bin:${nodeJS}/bin:$PATH; sonar-scanner -Dsonar.javascript.lcov.reportPaths=./xunit-reports-current/coverage/lcov.info,./cypress-coverage-current/coverage/lcov.info -Dsonar.sources=./src -Dsonar.projectKey=\"${GIT_NAME}\" -Dsonar.projectName=\"${GIT_NAME}\" -Dsonar.projectVersion=\$(jq '.version' package.json) ${env.sonarParams}" + sh '''sed -i "s#/app/packages/${GIT_NAME}/##g" xunit-reports-current/coverage/lcov.info 2>/dev/null || true''' + sh '''sed -i "s#packages/${GIT_NAME}/##g" xunit-reports-current/coverage/lcov.info 2>/dev/null || true''' + sh "export PATH=${scannerHome}/bin:${nodeJS}/bin:$PATH; sonar-scanner -Dsonar.javascript.lcov.reportPaths=./xunit-reports-current/coverage/lcov.info,./cypress-coverage-current/coverage/lcov.info -Dsonar.sources=./packages/$GIT_NAME/src -Dsonar.projectKey=\"${GIT_NAME}\" -Dsonar.projectName=\"${GIT_NAME}\" -Dsonar.projectVersion=\$(jq '.version' packages/$GIT_NAME/package.json) ${env.sonarParams}" sh '''try=5; while [ \$try -gt 0 ]; do curl -s -XPOST -u "${SONAR_AUTH_TOKEN}:" "${SONAR_HOST_URL}api/project_tags/set?project=${GIT_NAME}&tags=${SONARQUBE_TAGS}" > set_tags_result; if [ \$(grep -ic error set_tags_result ) -eq 0 ]; then try=0; else cat set_tags_result; echo "... Will retry"; sleep 15; try=\$(( \$try - 1 )); fi; done''' } } @@ -259,7 +261,8 @@ pipeline { } } - stage('Volto 17') { + // Volto 18 (previous) — pnpm, same EEA Makefile flow as Volto 19 + stage('Volto 18') { agent { node { label 'integration'} } when { allOf { @@ -268,51 +271,51 @@ pipeline { } } stages { - stage('Build test image') { + stage('Build test image') { steps { - sh '''docker build --pull --build-arg="VOLTO_VERSION=$PREVIOUS_VOLTO" --build-arg="ADDON_NAME=$NAMESPACE/$GIT_NAME" --build-arg="ADDON_PATH=$GIT_NAME" . -t $IMAGE_NAME-frontend-previous''' + sh '''docker build --pull --build-arg="VOLTO_VERSION=$PREVIOUS_VOLTO" --build-arg="ADDON_PATH=$GIT_NAME" . -t $IMAGE_NAME-frontend-previous''' } } - stage('Unit tests') { + stage('Integration tests') { steps { script { try { - sh '''docker run --name="$IMAGE_NAME-volto-previous" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-previous test-ci''' - sh '''rm -rf xunit-reports-previous''' - sh '''mkdir -p xunit-reports-previous''' - sh '''docker cp $IMAGE_NAME-volto-previous:/app/junit.xml xunit-reports-previous/''' - } finally { - catchError(buildResult: 'SUCCESS', stageResult: 'SUCCESS') { - junit testResults: 'xunit-reports-previous/junit.xml', allowEmptyResults: true + sh '''docker run --pull always --rm -d --name="$IMAGE_NAME-plone-previous" -e SITE="Plone" -e PROFILES="$BACKEND_PROFILES" -e ADDONS="$BACKEND_ADDONS" eeacms/plone-backend''' + sh '''docker run -d --shm-size=4g --link $IMAGE_NAME-plone-previous:plone --name="$IMAGE_NAME-cypress-previous" -e "RAZZLE_INTERNAL_API_PATH=http://plone:8080/Plone" --entrypoint=make --workdir=/app $IMAGE_NAME-frontend-previous start-ci''' + frontend = sh script:'''docker exec --workdir=/app $IMAGE_NAME-cypress-previous make check-ci''', returnStatus: true + if ( frontend != 0 ) { + sh '''docker logs $IMAGE_NAME-cypress-previous; exit 1''' } - sh script: '''docker rm -v $IMAGE_NAME-volto-previous''', returnStatus: true - } - } - } - } - stage('Integration tests') { - steps { - script { - try { - sh '''docker run --pull always --rm -d --name="$IMAGE_NAME-plone-previous" -e SITE="Plone" -e PROFILES="$BACKEND_PROFILES" -e ADDONS="$BACKEND_ADDONS" eeacms/plone-backend''' - sh '''docker run -d --shm-size=4g --link $IMAGE_NAME-plone-previous:plone --name="$IMAGE_NAME-cypress-previous" -e "RAZZLE_INTERNAL_API_PATH=http://plone:8080/Plone" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-previous start-ci''' - sh '''timeout -s 9 1800 docker exec --workdir=/app/src/addons/${GIT_NAME} $IMAGE_NAME-cypress-previous make cypress-ci''' + sh '''timeout -s 9 1800 docker exec --workdir=/app $IMAGE_NAME-cypress-previous make cypress-ci''' } finally { try { + if ( frontend == 0 ) { sh '''rm -rf cypress-videos-previous cypress-results-previous cypress-coverage-previous cypress-screenshots-previous''' sh '''mkdir -p cypress-videos-previous cypress-results-previous cypress-coverage-previous cypress-screenshots-previous''' - videos = sh script: '''docker cp $IMAGE_NAME-cypress-previous:/app/src/addons/$GIT_NAME/cypress/videos cypress-videos-previous/''', returnStatus: true - sh '''docker cp $IMAGE_NAME-cypress-previous:/app/src/addons/$GIT_NAME/cypress/reports cypress-results-previous/''' - screenshots = sh script: '''docker cp $IMAGE_NAME-cypress-previous:/app/src/addons/$GIT_NAME/cypress/screenshots cypress-screenshots-previous''', returnStatus: true + videos = sh script: '''docker cp $IMAGE_NAME-cypress-previous:/app/cypress/videos cypress-videos-previous/''', returnStatus: true + sh '''docker cp $IMAGE_NAME-cypress-previous:/app/cypress/reports cypress-results-previous/''' + screenshots = sh script: '''docker cp $IMAGE_NAME-cypress-previous:/app/cypress/screenshots cypress-screenshots-previous''', returnStatus: true archiveArtifacts artifacts: 'cypress-screenshots-previous/**', fingerprint: true, allowEmptyArchive: true + coverage = sh script: '''docker cp $IMAGE_NAME-cypress-previous:/app/coverage cypress-coverage-previous''', returnStatus: true + + if ( coverage == 0 ) { + publishHTML(target : [allowMissing: true, + alwaysLinkToLastBuild: true, + keepAll: true, + reportDir: 'cypress-coverage-previous/coverage/lcov-report', + reportFiles: 'index.html', + reportName: 'CypressCoverage (Volto 18)', + reportTitles: 'Integration Tests Code Coverage']) + } if ( videos == 0 ) { sh '''for file in $(find cypress-results-previous -name *.xml); do if [ $(grep -E 'failures="[1-9].*"' $file | wc -l) -eq 0 ]; then testname=$(grep -E 'file=.*failures="0"' $file | sed 's#.* file=".*\\/\\(.*\\.[jsxt]\\+\\)" time.*#\\1#' ); rm -f cypress-videos-previous/videos/$testname.mp4; fi; done''' archiveArtifacts artifacts: 'cypress-videos-previous/**/*.mp4', fingerprint: true, allowEmptyArchive: true } + } } finally { catchError(buildResult: 'SUCCESS', stageResult: 'SUCCESS') { junit testResults: 'cypress-results-previous/**/*.xml', allowEmptyResults: true @@ -328,7 +331,7 @@ pipeline { } } } - } + } } } @@ -348,10 +351,10 @@ pipeline { allOf { not { environment name: 'CHANGE_ID', value: '' } environment name: 'CHANGE_TARGET', value: 'develop' - environment name: 'SKIP_TESTS', value: '' + environment name: 'SKIP_TESTS', value: '' } allOf { - environment name: 'SKIP_TESTS', value: '' + environment name: 'SKIP_TESTS', value: '' environment name: 'CHANGE_ID', value: '' branch 'develop' not { changelog '.*^Automated release [0-9\\.]+$' } @@ -412,4 +415,3 @@ pipeline { } } } - diff --git a/Makefile b/Makefile index 2537fb4..26e935f 100644 --- a/Makefile +++ b/Makefile @@ -1,12 +1,16 @@ ############################################################################## # Run: -# make +# make install # make start # # Go to: # # http://localhost:3000 # +# Backend: +# +# make backend-docker-start +# # Cypress: # # make cypress-open @@ -43,123 +47,120 @@ endif ############################################################################## # SETTINGS AND VARIABLE -DIR=$(shell basename $$(pwd)) -NODE_MODULES?="../../../node_modules" -PLONE_VERSION?=6 -VOLTO_VERSION?=18-yarn -ADDON_PATH="${DIR}" -ADDON_NAME="@eeacms/${ADDON_PATH}" -DOCKER_COMPOSE=PLONE_VERSION=${PLONE_VERSION} VOLTO_VERSION=${VOLTO_VERSION} ADDON_NAME=${ADDON_NAME} ADDON_PATH=${ADDON_PATH} docker compose -RAZZLE_INTERNAL_API_PATH?="http://localhost:8080/Plone" -RAZZLE_DEV_PROXY_API_PATH?="${RAZZLE_INTERNAL_API_PATH}" -CYPRESS_API_PATH="${RAZZLE_DEV_PROXY_API_PATH}" - +CURRENT_DIR:=$(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))) +RAZZLE_INTERNAL_API_PATH?=http://localhost:8080/Plone +export RAZZLE_INTERNAL_API_PATH # Top-level targets .PHONY: all -all: clean install +all: help .PHONY: clean clean: ## Cleanup development environment - ${DOCKER_COMPOSE} down --volumes --remove-orphans + docker compose down --volumes --remove-orphans + rm -rf core node_modules .PHONY: install -install: ## Build and install development environment - echo "Running: ${DOCKER_COMPOSE} build" - ${DOCKER_COMPOSE} pull - ${DOCKER_COMPOSE} build +install: ## Install development environment + pnpm dlx mrs-developer missdev --no-config --fetch-https + pnpm i + make build-deps .PHONY: start -start: ## Start development environment - echo "Running: ${DOCKER_COMPOSE} up" - ${DOCKER_COMPOSE} up +start: ## Start backend and Volto frontend + docker compose up -d backend + pnpm start + +.PHONY: backend-docker-start +backend-docker-start: ## Start Plone backend on port 8080 + docker compose up backend -.PHONY: shell -shell: ## Start a shell in the frontend container - echo "Running: ${DOCKER_COMPOSE} run frontend bash" - ${DOCKER_COMPOSE} run --entrypoint=bash frontend +.PHONY: build +build: ## Build production bundle + pnpm build + +.PHONY: build-deps +build-deps: ## Build Volto dependencies + pnpm --filter @plone/registry --filter @plone/components build .PHONY: cypress-open -cypress-open: ## Open cypress integration tests - CYPRESS_API_PATH="${RAZZLE_DEV_PROXY_API_PATH}" NODE_ENV=development CYPRESS_COVERAGE=true $(NODE_MODULES)/cypress/bin/cypress open +CYPRESS_SPEC_PATTERN=$(CURRENT_DIR)/cypress/tests/**/*.{js,jsx,ts,tsx} + +cypress-open: ## Open Cypress interactive runner + pnpm --filter @plone/volto exec cypress open --project $(CURRENT_DIR) --config-file $(CURRENT_DIR)/cypress.config.js --config specPattern='$(CYPRESS_SPEC_PATTERN)' --env API_PATH="$(RAZZLE_INTERNAL_API_PATH)" .PHONY: cypress-run -cypress-run: ## Run cypress integration tests - CYPRESS_API_PATH="${RAZZLE_DEV_PROXY_API_PATH}" NODE_ENV=development CYPRESS_COVERAGE=true $(NODE_MODULES)/cypress/bin/cypress run --env coverage=true +cypress-run: ## Run Cypress tests headless + pnpm --filter @plone/volto exec cypress run --project $(CURRENT_DIR) --config-file $(CURRENT_DIR)/cypress.config.js --config specPattern='$(CYPRESS_SPEC_PATTERN)' --env API_PATH="$(RAZZLE_INTERNAL_API_PATH)" -.PHONY: test -test: ## Run jest tests - ${DOCKER_COMPOSE} run --no-deps -e CI=1 frontend test +.PHONY: cypress +cypress: cypress-run ## Run Cypress tests headless -.PHONY: test-update -test-update: ## Update jest tests snapshots - ${DOCKER_COMPOSE} run --no-deps -e CI=1 frontend test -u +.PHONY: test +test: ## Run unit tests + pnpm test -.PHONY: stylelint -stylelint: ## Stylelint - $(NODE_MODULES)/.bin/stylelint --allow-empty-input 'src/**/*.{css,less}' +.PHONY: i18n +i18n: ## Extract and compile translations + pnpm i18n -.PHONY: stylelint-overrides -stylelint-overrides: - $(NODE_MODULES)/.bin/stylelint --custom-syntax less --allow-empty-input 'theme/**/*.overrides' 'src/**/*.overrides' +.PHONY: lint +lint: ## ESLint check + pnpm lint -.PHONY: stylelint-fix -stylelint-fix: ## Fix stylelint - $(NODE_MODULES)/.bin/stylelint --allow-empty-input 'src/**/*.{css,less}' --fix - $(NODE_MODULES)/.bin/stylelint --custom-syntax less --allow-empty-input 'theme/**/*.overrides' 'src/**/*.overrides' --fix +.PHONY: lint-fix +lint-fix: ## ESLint fix + pnpm lint:fix .PHONY: prettier -prettier: ## Prettier - $(NODE_MODULES)/.bin/prettier --single-quote --check 'src/**/*.{js,jsx,json,css,less,md}' +prettier: ## Prettier check + pnpm prettier .PHONY: prettier-fix -prettier-fix: ## Fix prettier - $(NODE_MODULES)/.bin/prettier --single-quote --write 'src/**/*.{js,jsx,json,css,less,md}' +prettier-fix: ## Prettier fix + pnpm prettier:fix -.PHONY: lint -lint: ## ES Lint - $(NODE_MODULES)/.bin/eslint --max-warnings=0 'src/**/*.{js,jsx}' - -.PHONY: lint-fix -lint-fix: ## Fix ES Lint - $(NODE_MODULES)/.bin/eslint --fix 'src/**/*.{js,jsx}' - -.PHONY: i18n -i18n: ## i18n - rm -rf build/messages - NODE_ENV=development $(NODE_MODULES)/.bin/i18n --addon +.PHONY: stylelint +stylelint: ## Stylelint check + pnpm stylelint -.PHONY: help -help: ## Show this help. - @echo -e "$$(grep -hE '^\S+:.*##' $(MAKEFILE_LIST) | sed -e 's/:.*##\s*/:/' -e 's/^\(.\+\):\(.*\)/\\x1b[36m\1\\x1b[m:\2/' | column -c2 -t -s :)" - head -n 14 Makefile +.PHONY: stylelint-fix +stylelint-fix: ## Stylelint fix + pnpm stylelint:fix .PHONY: ci-fix -ci-fix: - echo "Running lint-fix" - make lint-fix - echo "Running prettier-fix" - make prettier-fix - echo "Running stylelint-fix" - make stylelint-fix +ci-fix: ## Fix code style (used by CI) + pnpm lint:fix + pnpm prettier:fix + pnpm stylelint:fix .PHONY: test-ci -test-ci: - cd /app - RAZZLE_JEST_CONFIG=src/addons/${ADDON_PATH}/jest-addon.config.js CI=true yarn test src/addons/${ADDON_PATH}/src --watchAll=false --reporters=default --reporters=jest-junit --collectCoverage --coverageReporters lcov cobertura text +test-ci: ## Run unit tests in CI + VOLTOCONFIG=$(CURRENT_DIR)/volto.config.js pnpm --filter @plone/volto i18n + CI=1 pnpm run test --passWithNoTests --coverage --coverage.reporter=lcov --coverage.reporter=text --reporter=junit --outputFile=junit.xml .PHONY: start-ci -start-ci: - cp .coverage.babel.config.js /app/babel.config.js - cd ../.. - RAZZLE_CI=true yarn start +start-ci: ## Start frontend in production mode (used by CI) + # Instrument the build (babel-plugin-istanbul) so Cypress can collect + # end-to-end coverage; the original babel config is restored on exit. + # RAZZLE_CI gates the demo block registration in packages/volto-object-widget/src/index.js, + # which the integration tests rely on. + cp core/packages/volto/babel.config.js core/packages/volto/babel.config.js.orig + trap 'mv -f core/packages/volto/babel.config.js.orig core/packages/volto/babel.config.js' EXIT + cp .coverage.babel.config.js core/packages/volto/babel.config.js + RAZZLE_CI=true pnpm build + RAZZLE_CI=true pnpm start:prod .PHONY: check-ci -check-ci: - $(NODE_MODULES)/.bin/wait-on -t 240000 http://localhost:3000 +check-ci: ## Wait for frontend to be ready + @timeout 600 bash -c 'until (echo > /dev/tcp/localhost/3000) 2>/dev/null; do sleep 2; done' .PHONY: cypress-ci -cypress-ci: - $(NODE_MODULES)/.bin/wait-on -t 240000 http://localhost:3000 - CYPRESS_API_PATH="${RAZZLE_DEV_PROXY_API_PATH}" NODE_ENV=development RAZZLE_CI=true $(NODE_MODULES)/cypress/bin/cypress run --browser electron +cypress-ci: ## Run Cypress tests headless (used by CI) + pnpm --filter @plone/volto exec cypress run --project $(CURRENT_DIR) --config-file $(CURRENT_DIR)/cypress.config.js --config specPattern='$(CYPRESS_SPEC_PATTERN)' --env API_PATH="$(RAZZLE_INTERNAL_API_PATH)" --browser chromium + +.PHONY: help +help: ## Show this help. + @echo -e "$$(grep -hE '^\S+:.*##' $(MAKEFILE_LIST) | sed -e 's/:.*##\s*/:/' -e 's/^\(.\+\):\(.*\)/\\x1b[36m\1\\x1b[m:\2/' | column -c2 -t -s :)" + @head -n 18 Makefile diff --git a/README.md b/README.md index d8365df..67fa32b 100644 --- a/README.md +++ b/README.md @@ -1,304 +1,25 @@ # volto-object-widget [![Releases](https://img.shields.io/github/v/release/eea/volto-object-widget)](https://github.com/eea/volto-object-widget/releases) - [![Pipeline](https://ci.eionet.europa.eu/buildStatus/icon?job=volto-addons%2Fvolto-object-widget%2Fmaster&subject=master)](https://ci.eionet.europa.eu/view/Github/job/volto-addons/job/volto-object-widget/job/master/display/redirect) -[![Lines of Code](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&metric=ncloc)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget) [![Coverage](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&metric=coverage)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget) -[![Bugs](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&metric=bugs)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget) -[![Duplicated Lines (%)](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&metric=duplicated_lines_density)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget) - -[![Pipeline](https://ci.eionet.europa.eu/buildStatus/icon?job=volto-addons%2Fvolto-object-widget%2Fdevelop&subject=develop)](https://ci.eionet.europa.eu/view/Github/job/volto-addons/job/volto-object-widget/job/develop/display/redirect) -[![Lines of Code](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&branch=develop&metric=ncloc)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget&branch=develop) -[![Coverage](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&branch=develop&metric=coverage)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget&branch=develop) -[![Bugs](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&branch=develop&metric=bugs)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget&branch=develop) -[![Duplicated Lines (%)](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&branch=develop&metric=duplicated_lines_density)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget&branch=develop) [Volto](https://github.com/plone/volto) add-on: Various Volto schema-based widgets. -## Features - -This Volto addon provides several "abstract" widgets, to allow complex -information to be editable by the schema-based forms. It centers around the -concept: "we can create a form to edit a JSON object by using a schema" and so -it provides, right now, widgets to edit "list of JSON objects", a "mapping of -JSON objects" and a single "JSON object, but I choose the schema for it". - -### FlatListObject - -![Flat List object](https://raw.githubusercontent.com/eea/volto-object-widget/master/img/flat-list-widget.png) - -This widget allows you to edit a list of objects by creating, editing and -deleting instances of objects editable with the provided `schema` parameter. -The list is sortable with drag&drop. You can also provide a schema extender, -a function with signature `(schema, data) => schema`, which will adjust, per -instance of object, its schema. To use this widget, in the schema, set the -`widget` field to `object_list_inline`. - -Example of how the data could look like for a block: - -``` -"a55c5053-ba81-4f73-ab29-7cdea74df20f": { - "@type": "dataTable", - "columns": [ - { - "@id": "f899ca76-68be-4ded-aa0b-669c04c27309", - "column": " PERC_HA_07\n(in %)", - "renderer": "progress", - "title": "21" - }, - { - "@id": "94315c5a-e031-4b7e-acb2-93887878a252", - "column": " PERC_HA_07\n(in %)", - "title": "12" - } - ], -} -``` - -The `columns` field, in this case, is data generated by the `FlatListObject`. -The schema for this field could look like (`ColumnSchema()` just generates -another instance of a schema, suitable for the `column` definition of our -specific use case): - -``` -columns: { - title: 'Columns', - description: 'Leave empty to show all columns', - schema: ColumnSchema(), - widget: 'object_list_inline', -}, -``` - -### Mapping Widget - -![Mapping widget](https://raw.githubusercontent.com/eea/volto-object-widget/master/img/mapping-widget.png) - -This widget allows editing the properties of an object. For example, in the -following block data, the `row_colors` value is generated by an instance of the -`MappingWidget`. - -``` -"4430a32a-a266-497b-88e7-72fead5ab718": { - "@type": "dottedTableChart", - "column_data": "habitat_group", - "row_colors": { - "Bad": "#ed1834", - "F - Heathland, scrub and tundra": "#88c24f", - "Good": "#3c8000", - "Poor": "#f2a70e", - "Unknown": "#8d8d8d" - }, - "row_data": "assessment", - "size_data": "quantity" -}, -``` - -You need to provide the `options`, which is a list of objects with `{id, title}` and the `field_props`, which are parameters for the actual field that -will be used to edit the values. In our case the schema definition that was -used to edit the above value is (note, the options are empty, we're populating -them in the edit component, before passing the schema to the form): - -``` -row_colors: { - title: 'Colors', - widget: 'option_mapping', - field_props: { - widget: 'simple_color', - available_colors: settings.available_colors, - }, - options: [], -} -``` - -To use this widget, in the schema, set the `widget` field to `option_mapping`. - -### Object by type - -![Object by type](https://raw.githubusercontent.com/eea/volto-object-widget/master/img/object-by-type-widget.png) - -With this widget you can choose the type of value that will be used, from -a predefined list of schemas. A schema that would use this type of widget could -look like: - -``` -const LinkEditSchema = { - title: 'Link', - fieldsets: [ - { - id: 'default', - title: 'Default', - fields: ['link'], - }, - ], - properties: { - link: { - title: 'Link', - widget: 'object_by_type', - schemas: [ - { - id: 'internal', - icon: internalSVG, - schema: InternalLinkSchema, - }, - { - id: 'external', - icon: externalSVG, - schema: ExternalLinkSchema, - }, - { - id: 'email', - icon: emailSVG, - schema: EmailLinkSchema, - }, - ], - }, - }, - required: [], -}; -``` - -To use this widget, in the schema, set the `widget` field to `object_by_type`. - -## Getting started - -### Try volto-object-widget with Docker - - git clone https://github.com/eea/volto-object-widget.git - cd volto-object-widget - make - make start - -Go to http://localhost:3000 - -`make start` now defaults to Volto 18. To run the same setup against Volto 17, use: - - VOLTO_VERSION=17 make - VOLTO_VERSION=17 make start - -### Add volto-object-widget to your Volto project - -1. Make sure you have a [Plone backend](https://plone.org/download) up-and-running at http://localhost:8080/Plone +The add-on package lives in [`packages/volto-object-widget`](packages/volto-object-widget), +its [README](packages/volto-object-widget/README.md) documents installation and usage. - ```Bash - docker compose up backend - ``` +## Development -1. Start Volto frontend - -* If you already have a volto project, just update `package.json`: - - ```JSON - "dependencies": { - "@eeacms/volto-object-widget": "*" - } - ``` - - and `volto.config.js`: - - ```JavaScript - const addons = ['@eeacms/volto-object-widget']; - ``` - -* If not, create one with Cookieplone, as recommended by the official Plone documentation for Volto 18+: - - ``` - uvx cookieplone project - cd project-title - ``` - -1. Install or update dependencies, then start the project: - - ``` - make install - ``` - - For a Cookieplone project, start the backend and frontend in separate terminals: - - ``` - make backend-start - make frontend-start - ``` - - For a legacy Volto 17 project, install the package with `yarn` and restart the frontend as usual. - -1. Go to http://localhost:3000 - -1. Happy editing! +See [DEVELOP.md](DEVELOP.md). ## Release -See [RELEASE.md](https://github.com/eea/volto-object-widget/blob/master/RELEASE.md). - -## How to contribute - -See [DEVELOP.md](https://github.com/eea/volto-object-widget/blob/master/DEVELOP.md). - -## Secret Scanning - -This repository uses the Betterleaks GitHub Action to scan the current -repository content on every push and pull request. The scan uses the rules in -`.gitleaks.toml` and uploads a `betterleaks-report` artifact when a finding is -detected. - -If the optional SMTP secrets are configured, failed scans also send an email to -the last commit committer. The workflow expects these repository or -organization secrets: - -- `SMTP_URL` -- `SMTP_PORT` (optional, defaults to `25`) -- `SMTP_EMAIL` -- `SMTP_PASSWORD` (optional if the SMTP server does not require authentication) - -Port `465` is sent with direct TLS; other ports use the default SMTP handshake. -The email includes a short finding summary from the redacted Betterleaks report, -including the redacted matched line from each finding. - -There are three common outcomes: - -1. **Everything is OK.** The `Betterleaks / Scan for secrets` check is green and - no action is needed. Regular references to runtime values are OK, for example: - - ```js - const tokenFromCookie = req.universalCookies.get('auth_token'); - ``` - -2. **A real secret was found.** The check is red and the workflow log asks you to - download the `betterleaks-report` artifact. Open the artifact from the GitHub - Actions run and check the reported file, line and rule. Remove the committed - value, move it to the proper secret store, and rotate it if it was exposed. - A report entry looks like this: - - ```json - { - "RuleID": "secret-literal-assignment", - "File": "src/config.js", - "StartLine": 12, - "Secret": "[REDACTED]" - } - ``` - -3. **The finding is a false positive.** Keep the value only if it is clearly not - sensitive, such as a test fixture, placeholder, or public example. Add - `betterleaks:allow` on the same line and include a short explanation in the - pull request. - - ```js - const testPassword = 'admin'; //betterleaks:allow - ``` - - ```yaml - password: "admin" #betterleaks:allow - ``` - -Do not add `betterleaks:allow` to real credentials. - -## Copyright and license +See [RELEASE.md](RELEASE.md). -The Initial Owner of the Original Code is European Environment Agency (EEA). -All Rights Reserved. +## License -See [LICENSE.md](https://github.com/eea/volto-object-widget/blob/master/LICENSE.md) for details. +See [LICENSE.md](LICENSE.md) for details. ## Funding diff --git a/babel.config.js b/babel.config.js deleted file mode 100644 index 51bd52b..0000000 --- a/babel.config.js +++ /dev/null @@ -1,17 +0,0 @@ -module.exports = function (api) { - api.cache(true); - const presets = ['razzle']; - const plugins = [ - [ - 'react-intl', // React Intl extractor, required for the whole i18n infrastructure to work - { - messagesDir: './build/messages/', - }, - ], - ]; - - return { - plugins, - presets, - }; -}; diff --git a/bootstrap b/bootstrap deleted file mode 100644 index 8613750..0000000 --- a/bootstrap +++ /dev/null @@ -1,41 +0,0 @@ -const path = require('path'); -const fs = require('fs'); -const ejs = require('ejs'); - -const currentDir = path.basename(process.cwd()); - -const bootstrap = function (ofile) { - fs.readFile(ofile, 'utf8', function (err, data) { - if (err) { - return console.log(err); - } - const result = ejs.render(data, { - addonName: `@eeacms/${currentDir}`, - name: currentDir - }); - const output = ofile.replace('.tpl', ''); - fs.writeFile(output, result, 'utf8', function (err) { - if (err) { - return console.log(err); - } - }); - if (ofile.includes('.tpl')) { - fs.unlink(ofile, (err) => { - if (err) { - return console.error(err); - } - }); - } - }); -} - -fs.readdir(".", { withFileTypes: true }, (err, dirents) => { - const files = dirents - .filter(dirent => dirent.isFile()) - .map(dirent => dirent.name); - files.forEach(function (file) { - if (file != 'bootstrap') { - bootstrap(file); - } - }); -}); diff --git a/cypress.config.js b/cypress.config.js index 7a9e0be..3fd03ff 100644 --- a/cypress.config.js +++ b/cypress.config.js @@ -2,25 +2,28 @@ const { defineConfig } = require('cypress'); module.exports = defineConfig({ viewportWidth: 1280, - defaultCommandTimeout: 8888, - chromeWebSecurity: false, - reporter: 'junit', - video: false, + viewportHeight: 1280, retries: { - runMode: 2, - openMode: 0, + runMode: 3, }, + // JUnit reporter so the EEA Jenkinsfile can publish Cypress results + // (it copies cypress/reports/*.xml via `junit testResults: 'cypress-results-current/**/*.xml'`). + reporter: 'junit', reporterOptions: { mochaFile: 'cypress/reports/cypress-[hash].xml', jenkinsMode: true, toConsole: true, }, e2e: { + // Register the code-coverage task so cypress/support/e2e.js's + // `@cypress/code-coverage/support` has somewhere to send coverage to. + // Coverage is only collected when the frontend is built/started with + // babel-plugin-istanbul instrumentation (see Makefile `start-ci`). setupNodeEvents(on, config) { - // e2e testing node events setup code require('@cypress/code-coverage/task')(on, config); return config; }, baseUrl: 'http://localhost:3000', + specPattern: 'cypress/tests/**/*.cy.{js,jsx,ts,tsx}', }, }); diff --git a/cypress/support/e2e.js b/cypress/support/e2e.js index bc4138a..0c05bcf 100644 --- a/cypress/support/e2e.js +++ b/cypress/support/e2e.js @@ -40,9 +40,11 @@ export const slateBeforeEach = (contentType = 'Document') => { contentTitle: 'My Image', path: 'cypress/my-page', }); - cy.visit('/cypress/my-page'); - cy.waitForResourceToLoad('my-page'); - cy.navigate('/cypress/my-page/edit'); + // Load the edit route directly instead of pushing it through the SPA + // history: an appHistory push can race with the client hydration, which + // then settles back on the server-rendered view URL and the edit UI + // (including the title editor) never mounts. + cy.visit('/cypress/my-page/edit'); }; export const slateAfterEach = () => { diff --git a/cypress/e2e/01-attached-image-widget-external-url.cy.js b/cypress/tests/01-attached-image-widget-external-url.cy.js similarity index 100% rename from cypress/e2e/01-attached-image-widget-external-url.cy.js rename to cypress/tests/01-attached-image-widget-external-url.cy.js diff --git a/cypress/e2e/02-attached-image-widget-internal-url.cy.js b/cypress/tests/02-attached-image-widget-internal-url.cy.js similarity index 100% rename from cypress/e2e/02-attached-image-widget-internal-url.cy.js rename to cypress/tests/02-attached-image-widget-internal-url.cy.js diff --git a/cypress/e2e/03-attached-image-widget-clear-url.cy.js b/cypress/tests/03-attached-image-widget-clear-url.cy.js similarity index 100% rename from cypress/e2e/03-attached-image-widget-clear-url.cy.js rename to cypress/tests/03-attached-image-widget-clear-url.cy.js diff --git a/cypress/e2e/04-attached-image-widget-submit-disabled.cy.js b/cypress/tests/04-attached-image-widget-submit-disabled.cy.js similarity index 100% rename from cypress/e2e/04-attached-image-widget-submit-disabled.cy.js rename to cypress/tests/04-attached-image-widget-submit-disabled.cy.js diff --git a/cypress/e2e/05-attached-image-widget-object-browser.cy.js b/cypress/tests/05-attached-image-widget-object-browser.cy.js similarity index 100% rename from cypress/e2e/05-attached-image-widget-object-browser.cy.js rename to cypress/tests/05-attached-image-widget-object-browser.cy.js diff --git a/cypress/e2e/06-attached-image-widget-preview-clear.cy.js b/cypress/tests/06-attached-image-widget-preview-clear.cy.js similarity index 100% rename from cypress/e2e/06-attached-image-widget-preview-clear.cy.js rename to cypress/tests/06-attached-image-widget-preview-clear.cy.js diff --git a/cypress/e2e/07-attached-image-widget-upload-loading.cy.js b/cypress/tests/07-attached-image-widget-upload-loading.cy.js similarity index 100% rename from cypress/e2e/07-attached-image-widget-upload-loading.cy.js rename to cypress/tests/07-attached-image-widget-upload-loading.cy.js diff --git a/cypress/e2e/08-attached-image-widget-dragging-state.cy.js b/cypress/tests/08-attached-image-widget-dragging-state.cy.js similarity index 100% rename from cypress/e2e/08-attached-image-widget-dragging-state.cy.js rename to cypress/tests/08-attached-image-widget-dragging-state.cy.js diff --git a/cypress/e2e/09-attached-image-widget-conflict-dialog.cy.js b/cypress/tests/09-attached-image-widget-conflict-dialog.cy.js similarity index 100% rename from cypress/e2e/09-attached-image-widget-conflict-dialog.cy.js rename to cypress/tests/09-attached-image-widget-conflict-dialog.cy.js diff --git a/cypress/e2e/10-attached-image-widget-replace-existing.cy.js b/cypress/tests/10-attached-image-widget-replace-existing.cy.js similarity index 100% rename from cypress/e2e/10-attached-image-widget-replace-existing.cy.js rename to cypress/tests/10-attached-image-widget-replace-existing.cy.js diff --git a/cypress/e2e/11-attached-image-widget-use-existing.cy.js b/cypress/tests/11-attached-image-widget-use-existing.cy.js similarity index 100% rename from cypress/e2e/11-attached-image-widget-use-existing.cy.js rename to cypress/tests/11-attached-image-widget-use-existing.cy.js diff --git a/cypress/e2e/12-attached-image-widget-cancel-upload.cy.js b/cypress/tests/12-attached-image-widget-cancel-upload.cy.js similarity index 100% rename from cypress/e2e/12-attached-image-widget-cancel-upload.cy.js rename to cypress/tests/12-attached-image-widget-cancel-upload.cy.js diff --git a/cypress/tsconfig.json b/cypress/tsconfig.json new file mode 100644 index 0000000..74b7cb3 --- /dev/null +++ b/cypress/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "target": "es5", + "lib": ["es5", "dom"], + "types": ["cypress", "@testing-library/cypress", "node"] + }, + "include": ["**/*.ts"] +} diff --git a/docker-compose.yml b/docker-compose.yml index 18afc2e..9ebce08 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,33 +1,8 @@ -version: '3' services: backend: image: eeacms/plone-backend ports: - - '8080:8080' + - "8080:8080" environment: - SITE: 'Plone' - PROFILES: 'eea.kitkat:testing' - - frontend: - build: - context: ./ - dockerfile: ./Dockerfile - args: - ADDON_NAME: '${ADDON_NAME}' - ADDON_PATH: '${ADDON_PATH}' - VOLTO_VERSION: ${VOLTO_VERSION:-18-yarn} - ports: - - '3000:3000' - - '3001:3001' - depends_on: - - backend - volumes: - - ./:/app/src/addons/${ADDON_PATH} - environment: - RAZZLE_CI: 'true' - CI: 'true' - NODE_ENV: 'development' - RAZZLE_JEST_CONFIG: 'src/addons/${ADDON_PATH}/jest-addon.config.js' - RAZZLE_INTERNAL_API_PATH: 'http://backend:8080/Plone' - RAZZLE_DEV_PROXY_API_PATH: 'http://backend:8080/Plone' - HOST: '0.0.0.0' + SITE: "Plone" + PROFILES: "eea.kitkat:testing" diff --git a/jest-addon.config.js b/jest-addon.config.js deleted file mode 100644 index 477a6a9..0000000 --- a/jest-addon.config.js +++ /dev/null @@ -1,469 +0,0 @@ -/** - * Generic Jest configuration for Volto addons - * - * This configuration automatically: - * - Detects the addon name from the config file path - * - Configures test coverage to focus on the specific test path - * - Handles different ways of specifying test paths: - * - Full paths like src/addons/addon-name/src/components - * - Just filenames like Component.test.jsx - * - Just directory names like components - * - * Usage: - * RAZZLE_JEST_CONFIG=src/addons/addon-name/jest-addon.config.js CI=true yarn test [test-path] --collectCoverage - */ - -require('dotenv').config({ path: __dirname + '/.env' }); - -const path = require('path'); -const fs = require('fs'); -const fg = require('fast-glob'); - -const voltoSlatePath = fs.existsSync( - path.join(__dirname, '../../../node_modules/@plone/volto-slate/src'), -) - ? '/node_modules/@plone/volto-slate/src' - : '/node_modules/@plone/volto/packages/volto-slate/src'; - -// Get the addon name from the current file path -const pathParts = __filename.split(path.sep); -const addonsIdx = pathParts.lastIndexOf('addons'); -const addonName = - addonsIdx !== -1 && addonsIdx < pathParts.length - 1 - ? pathParts[addonsIdx + 1] - : path.basename(path.dirname(__filename)); // Fallback to folder name -const addonBasePath = `src/addons/${addonName}/src`; - -// --- Performance caches --- -const fileSearchCache = new Map(); -const dirSearchCache = new Map(); -const dirListingCache = new Map(); -const statCache = new Map(); -const implementationCache = new Map(); - -/** - * Cached fs.statSync wrapper to avoid redundant filesystem calls - * @param {string} p - * @returns {fs.Stats|null} - */ -const getStatSync = (p) => { - if (statCache.has(p)) return statCache.get(p); - try { - const s = fs.statSync(p); - statCache.set(p, s); - return s; - } catch { - statCache.set(p, null); - return null; - } -}; - -/** - * Find files that match a specific pattern using fast-glob - * @param {string} baseDir - The base directory to search in - * @param {string} fileName - The name of the file to find - * @param {string} [pathPattern=''] - Optional path pattern to filter results - * @returns {string[]} - Array of matching file paths - */ -const findFilesWithPattern = (baseDir, fileName, pathPattern = '') => { - const cacheKey = `${baseDir}|${fileName}|${pathPattern}`; - if (fileSearchCache.has(cacheKey)) { - return fileSearchCache.get(cacheKey); - } - - let files = []; - try { - const patterns = fileName - ? [`${baseDir}/**/${fileName}`] - : [`${baseDir}/**/*.{js,jsx,ts,tsx}`]; - - files = fg.sync(patterns, { onlyFiles: true }); - - if (pathPattern) { - files = files.filter((file) => file.includes(pathPattern)); - } - } catch { - files = []; - } - - fileSearchCache.set(cacheKey, files); - return files; -}; - -/** - * Find directories that match a specific pattern using fast-glob - * @param {string} baseDir - The base directory to search in - * @param {string} dirName - The name of the directory to find - * @param {string} [pathPattern=''] - Optional path pattern to filter results - * @returns {string[]} - Array of matching directory paths - */ -const findDirsWithPattern = (baseDir, dirName, pathPattern = '') => { - const cacheKey = `${baseDir}|${dirName}|${pathPattern}`; - if (dirSearchCache.has(cacheKey)) { - return dirSearchCache.get(cacheKey); - } - - let dirs = []; - try { - const patterns = dirName - ? [`${baseDir}/**/${dirName}`] - : [`${baseDir}/**/`]; - - dirs = fg.sync(patterns, { onlyDirectories: true }); - - if (pathPattern) { - dirs = dirs.filter((dir) => dir.includes(pathPattern)); - } - } catch { - dirs = []; - } - - dirSearchCache.set(cacheKey, dirs); - return dirs; -}; - -/** - * Find files or directories in the addon using fast-glob - * @param {string} name - The name to search for - * @param {string} type - The type of item to find ('f' for files, 'd' for directories) - * @param {string} [additionalOptions=''] - Additional options for flexible path matching - * @returns {string|null} - The path of the found item or null if not found - */ -const findInAddon = (name, type, additionalOptions = '') => { - const isFile = type === 'f'; - const isDirectory = type === 'd'; - const isFlexiblePathMatch = additionalOptions.includes('-path'); - - let pathPattern = ''; - if (isFlexiblePathMatch) { - const match = additionalOptions.match(/-path "([^"]+)"/); - if (match && match[1]) { - pathPattern = match[1].replace(/\*/g, ''); - } - } - - try { - let results = []; - if (isFile) { - results = findFilesWithPattern(addonBasePath, name, pathPattern); - } else if (isDirectory) { - results = findDirsWithPattern(addonBasePath, name, pathPattern); - } - return results.length > 0 ? results[0] : null; - } catch (error) { - return null; - } -}; - -/** - * Find the implementation file for a test file - * @param {string} testPath - Path to the test file - * @returns {string|null} - Path to the implementation file or null if not found - */ -const findImplementationFile = (testPath) => { - if (implementationCache.has(testPath)) { - return implementationCache.get(testPath); - } - - if (!fs.existsSync(testPath)) { - implementationCache.set(testPath, null); - return null; - } - - const dirPath = path.dirname(testPath); - const fileName = path.basename(testPath); - - // Regex for common test file patterns (e.g., .test.js, .spec.ts) - const TEST_OR_SPEC_FILE_REGEX = /\.(test|spec)\.[jt]sx?$/; - - if (!TEST_OR_SPEC_FILE_REGEX.test(fileName)) { - implementationCache.set(testPath, null); - return null; - } - - const baseFileName = path - .basename(fileName, path.extname(fileName)) - .replace(/\.(test|spec)$/, ''); // Remove .test or .spec - - let dirFiles = dirListingCache.get(dirPath); - if (!dirFiles) { - dirFiles = fs.readdirSync(dirPath); - dirListingCache.set(dirPath, dirFiles); - } - - const exactMatch = dirFiles.find((file) => { - const fileBaseName = path.basename(file, path.extname(file)); - return ( - fileBaseName === baseFileName && !TEST_OR_SPEC_FILE_REGEX.test(file) // Ensure it's not another test/spec file - ); - }); - - if (exactMatch) { - const result = `${dirPath}/${exactMatch}`; - implementationCache.set(testPath, result); - return result; - } - - const similarMatch = dirFiles.find((file) => { - if ( - TEST_OR_SPEC_FILE_REGEX.test(file) || - (getStatSync(`${dirPath}/${file}`)?.isDirectory() ?? false) - ) { - return false; - } - const fileBaseName = path.basename(file, path.extname(file)); - return ( - fileBaseName.toLowerCase().includes(baseFileName.toLowerCase()) || - baseFileName.toLowerCase().includes(fileBaseName.toLowerCase()) - ); - }); - - if (similarMatch) { - const result = `${dirPath}/${similarMatch}`; - implementationCache.set(testPath, result); - return result; - } - - implementationCache.set(testPath, null); - return null; -}; - -/** - * Get the test path from command line arguments - * @returns {string|null} - The resolved test path or null if not found - */ -const getTestPath = () => { - const args = process.argv; - let testPath = null; - const TEST_FILE_REGEX = /\.test\.[jt]sx?$/; // Matches .test.js, .test.jsx, .test.ts, .test.tsx - - testPath = args.find( - (arg) => - arg.includes(addonName) && - !arg.startsWith('--') && - arg !== 'test' && - arg !== 'node', - ); - - if (!testPath) { - const testIndex = args.findIndex((arg) => arg === 'test'); - if (testIndex !== -1 && testIndex < args.length - 1) { - const nextArg = args[testIndex + 1]; - if (!nextArg.startsWith('--')) { - testPath = nextArg; - } - } - } - - if (!testPath) { - testPath = args.find((arg) => TEST_FILE_REGEX.test(arg)); - } - - if (!testPath) { - return null; - } - - if (!testPath.includes(path.sep)) { - if (TEST_FILE_REGEX.test(testPath)) { - const foundTestFile = findInAddon(testPath, 'f'); - if (foundTestFile) { - return foundTestFile; - } - } else { - const foundDir = findInAddon(testPath, 'd'); - if (foundDir) { - return foundDir; - } - const flexibleDir = findInAddon(testPath, 'd', `-path "*${testPath}*"`); - if (flexibleDir) { - return flexibleDir; - } - } - } else if ( - TEST_FILE_REGEX.test(testPath) && // Check if it looks like a test file path - !testPath.startsWith('src/addons/') - ) { - const testFileName = path.basename(testPath); - const foundTestFile = findInAddon(testFileName, 'f'); - if (foundTestFile) { - const relativePath = path.dirname(testPath); - if (foundTestFile.includes(relativePath)) { - return foundTestFile; - } - const similarFiles = findFilesWithPattern( - addonBasePath, - testFileName, - relativePath, - ); - if (similarFiles && similarFiles.length > 0) { - return similarFiles[0]; - } - } - } - - if ( - !path - .normalize(testPath) - .startsWith(path.join('src', 'addons', addonName, 'src')) && - !path.isAbsolute(testPath) // Use path.isAbsolute for robust check - ) { - testPath = path.join(addonBasePath, testPath); // Use path.join for OS-agnostic paths - } - - if (fs.existsSync(testPath)) { - return testPath; - } - - const pathWithoutTrailingSlash = testPath.endsWith(path.sep) - ? testPath.slice(0, -1) - : null; - if (pathWithoutTrailingSlash && fs.existsSync(pathWithoutTrailingSlash)) { - return pathWithoutTrailingSlash; - } - - const pathWithTrailingSlash = !testPath.endsWith(path.sep) - ? testPath + path.sep - : null; - if (pathWithTrailingSlash && fs.existsSync(pathWithTrailingSlash)) { - // Generally, return paths without trailing slashes for consistency, - // unless it's specifically needed for a directory that only exists with it (rare). - return testPath; - } - return testPath; // Return the original path if no variations exist -}; - -/** - * Determine collectCoverageFrom patterns based on test path - * @returns {string[]} - Array of coverage patterns - */ -const getCoveragePatterns = () => { - const excludePatterns = [ - '!src/**/*.d.ts', - '!**/*.test.{js,jsx,ts,tsx}', - '!**/*.spec.{js,jsx,ts,tsx}', - ]; - - const defaultPatterns = [ - `${addonBasePath}/**/*.{js,jsx,ts,tsx}`, - ...excludePatterns, - ]; - - const ANY_SCRIPT_FILE_REGEX = /\.[jt]sx?$/; - - const directoryArg = process.argv.find( - (arg) => - !arg.includes(path.sep) && - !arg.startsWith('--') && - arg !== 'test' && - arg !== 'node' && - !ANY_SCRIPT_FILE_REGEX.test(arg) && - ![ - 'yarn', - 'npm', - 'npx', - 'collectCoverage', - 'CI', - 'RAZZLE_JEST_CONFIG', - ].some( - (reserved) => - arg === reserved || arg.startsWith(reserved.split('=')[0] + '='), - ) && - process.argv.indexOf(arg) > - process.argv.findIndex((item) => item === 'test'), - ); - - if (directoryArg) { - const foundDir = findInAddon(directoryArg, 'd'); - if (foundDir) { - return [`${foundDir}/**/*.{js,jsx,ts,tsx}`, ...excludePatterns]; - } - } - - let testPath = getTestPath(); - - if (!testPath) { - return defaultPatterns; - } - - if (testPath.endsWith(path.sep)) { - testPath = testPath.slice(0, -1); - } - - const stats = getStatSync(testPath); - - if (stats && stats.isFile()) { - const implFile = findImplementationFile(testPath); - if (implFile) { - return [implFile, '!src/**/*.d.ts']; - } - const dirPath = path.dirname(testPath); - return [`${dirPath}/**/*.{js,jsx,ts,tsx}`, ...excludePatterns]; - } else if (stats && stats.isDirectory()) { - return [`${testPath}/**/*.{js,jsx,ts,tsx}`, ...excludePatterns]; - } - - return defaultPatterns; -}; - -const coverageConfig = getCoveragePatterns(); - -module.exports = { - testMatch: ['**/src/addons/**/?(*.)+(spec|test).[jt]s?(x)'], - collectCoverageFrom: coverageConfig, - coveragePathIgnorePatterns: [ - '/node_modules/', - 'schema\\.[jt]s?$', - 'index\\.[jt]s?$', - 'config\\.[jt]sx?$', - ], - moduleNameMapper: { - '\\.(css|less|scss|sass)$': 'identity-obj-proxy', - '@plone/volto/cypress': '/node_modules/@plone/volto/cypress', - '@plone/volto/babel': '/node_modules/@plone/volto/babel', - '@plone/volto/(.*)$': '/node_modules/@plone/volto/src/$1', - '@package/(.*)$': '/node_modules/@plone/volto/src/$1', - '@root/(.*)$': '/node_modules/@plone/volto/src/$1', - '@plone/volto-quanta/(.*)$': '/src/addons/volto-quanta/src/$1', - '@eeacms/search/(.*)$': '/src/addons/volto-searchlib/searchlib/$1', - '@eeacms/search': '/src/addons/volto-searchlib/searchlib', - '@eeacms/(.*?)/(.*)$': '/node_modules/@eeacms/$1/src/$2', - '@plone/volto-slate$': voltoSlatePath, - '@plone/volto-slate/(.*)$': `${voltoSlatePath}/$1`, - '~/(.*)$': '/src/$1', - 'load-volto-addons': - '/node_modules/@plone/volto/jest-addons-loader.js', - }, - transformIgnorePatterns: [ - '/node_modules/(?!(@plone|@root|@package|@eeacms)/).*/', - ], - transform: { - '^.+\\.js(x)?$': 'babel-jest', - '^.+\\.ts(x)?$': 'babel-jest', - '^.+\\.(png)$': 'jest-file', - '^.+\\.(jpg)$': 'jest-file', - '^.+\\.(svg)$': './node_modules/@plone/volto/jest-svgsystem-transform.js', - }, - coverageThreshold: { - global: { - branches: 5, - functions: 5, - lines: 5, - statements: 5, - }, - }, - ...(process.env.JEST_USE_SETUP === 'ON' && { - setupFilesAfterEnv: [ - fs.existsSync( - path.join( - __dirname, - 'node_modules', - '@eeacms', - addonName, - 'jest.setup.js', - ), - ) - ? `/node_modules/@eeacms/${addonName}/jest.setup.js` - : `/src/addons/${addonName}/jest.setup.js`, - ], - }), -}; diff --git a/jest.setup.js b/jest.setup.js deleted file mode 100644 index 85b16f7..0000000 --- a/jest.setup.js +++ /dev/null @@ -1,65 +0,0 @@ -import { jest } from '@jest/globals'; -import configureStore from 'redux-mock-store'; -import thunk from 'redux-thunk'; -import { blocksConfig } from '@plone/volto/config/Blocks'; -import installSlate from '@plone/volto-slate/index'; - -var mockSemanticComponents = jest.requireActual('semantic-ui-react'); -var mockComponents = jest.requireActual('@plone/volto/components'); -var config = jest.requireActual('@plone/volto/registry').default; - -config.blocks.blocksConfig = { - ...blocksConfig, - ...config.blocks.blocksConfig, -}; - -jest.doMock('semantic-ui-react', () => ({ - __esModule: true, - ...mockSemanticComponents, - Popup: ({ content, trigger }) => { - return ( -
-
{trigger}
-
{content}
-
- ); - }, -})); - -jest.doMock('@plone/volto/components', () => { - return { - __esModule: true, - ...mockComponents, - SidebarPortal: ({ children }) => , - }; -}); - -jest.doMock('@plone/volto/registry', () => - [installSlate].reduce((acc, apply) => apply(acc), config), -); - -const mockStore = configureStore([thunk]); - -global.fetch = jest.fn(() => - Promise.resolve({ - json: () => Promise.resolve({}), - }), -); - -global.store = mockStore({ - intl: { - locale: 'en', - messages: {}, - formatMessage: jest.fn(), - }, - content: { - create: {}, - subrequests: [], - }, - connected_data_parameters: {}, - screen: { - page: { - width: 768, - }, - }, -}); diff --git a/mrs.developer.json b/mrs.developer.json new file mode 100644 index 0000000..19fe64c --- /dev/null +++ b/mrs.developer.json @@ -0,0 +1,10 @@ +{ + "core": { + "output": "./", + "package": "@plone/volto", + "url": "git@github.com:plone/volto.git", + "https": "https://github.com/plone/volto.git", + "tag": "19.5.0", + "filterBlobs": true + } +} diff --git a/package.json b/package.json index 239532f..3c29b9a 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,11 @@ { - "name": "@eeacms/volto-object-widget", - "version": "9.1.1", + "name": "@eeacms/volto-object-widget-dev", + "private": true, + "version": "10.0.0", "description": "volto-object-widget: Volto add-on", - "main": "src/index.js", "author": "European Environment Agency: IDM2 A-Team", - "license": "MIT", "homepage": "https://github.com/eea/volto-object-widget", + "license": "MIT", "keywords": [ "volto-addon", "volto-widget", @@ -13,63 +13,54 @@ "plone", "react" ], - "repository": { - "type": "git", - "url": "git@github.com:eea/volto-object-widget.git" + "scripts": { + "preinstall": "npx only-allow pnpm", + "start": "VOLTOCONFIG=$(pwd)/volto.config.js pnpm --filter @plone/volto start", + "start:prod": "pnpm --filter @plone/volto start:prod", + "build": "VOLTOCONFIG=$(pwd)/volto.config.js pnpm --filter @plone/volto build", + "build:deps": "pnpm --filter @plone/registry --filter @plone/components build", + "i18n": "pnpm --filter @eeacms/volto-object-widget i18n && VOLTOCONFIG=$(pwd)/volto.config.js pnpm --filter @plone/volto i18n", + "test": "pnpm --filter @eeacms/volto-object-widget exec vitest", + "lint": "VOLTOCONFIG=$(pwd)/volto.config.js eslint --max-warnings=0 'packages/**/src/**/*.{js,jsx,ts,tsx}'", + "lint:fix": "VOLTOCONFIG=$(pwd)/volto.config.js eslint --fix 'packages/**/src/**/*.{js,jsx,ts,tsx}'", + "prettier": "prettier --check 'packages/**/src/**/*.{js,jsx,ts,tsx}'", + "prettier:fix": "prettier --write 'packages/**/src/**/*.{js,jsx,ts,tsx}' ", + "stylelint": "stylelint 'packages/**/src/**/*.{css,scss,less}' --allow-empty-input", + "stylelint:fix": "stylelint 'packages/**/src/**/*.{css,scss,less}' --fix --allow-empty-input", + "dry-release": "pnpm --filter @eeacms/volto-object-widget dry-release", + "release": "pnpm --filter @eeacms/volto-object-widget release", + "release-major-alpha": "pnpm --filter @eeacms/volto-object-widget release-major-alpha", + "release-alpha": "pnpm --filter @eeacms/volto-object-widget release-alpha", + "storybook": "VOLTOCONFIG=$(pwd)/volto.config.js pnpm --filter @plone/volto storybook dev -p 6006 -c $(pwd)/.storybook", + "storybook-build": "VOLTOCONFIG=$(pwd)/volto.config.js pnpm --filter @plone/volto build-storybook -c $(pwd)/.storybook" }, "dependencies": { - "jsoneditor": "10.2.0" + "@plone/volto": "workspace:*", + "@plone/registry": "workspace:*", + "@eeacms/volto-object-widget": "workspace:*" }, "devDependencies": { - "@cypress/code-coverage": "^3.10.0", - "@plone/scripts": "^3.6.2", - "babel-plugin-transform-class-properties": "^6.24.1", - "cypress": "13.1.0", - "cypress-file-upload": "^5.0.8", - "dotenv": "^16.3.2", - "husky": "^8.0.3", - "lint-staged": "^14.0.1", - "md5": "^2.3.0" + "babel-plugin-istanbul": "^6.1.1", + "mrs-developer": "^2.2.0" }, - "lint-staged": { - "src/**/*.{js,jsx,ts,tsx,json}": [ - "make lint-fix", - "make prettier-fix" - ], - "src/**/*.{jsx}": [ - "make i18n" + "pnpm": { + "overrides": { + "@pmmmwh/react-refresh-webpack-plugin": "^0.5.15", + "react-refresh": "^0.14.2" + }, + "ignoredBuiltDependencies": [ + "@parcel/watcher" ], - "theme/**/*.{css,less}": [ - "make stylelint-fix" - ], - "src/**/*.{css,less}": [ - "make stylelint-fix" - ], - "theme/**/*.overrides": [ - "make stylelint-fix" - ], - "src/**/*.overrides": [ - "make stylelint-fix" + "onlyBuiltDependencies": [ + "core-js", + "core-js-pure", + "cypress", + "es5-ext", + "esbuild", + "full-icu", + "lightningcss-cli", + "unrs-resolver" ] }, - "scripts": { - "release": "release-it", - "release-major-beta": "release-it major --preRelease=beta", - "release-beta": "release-it --preRelease=beta", - "bootstrap": "npm install -g ejs; npm link ejs; node bootstrap", - "test": "make test", - "test:fix": "make test-update", - "pre-commit": "yarn stylelint:fix && yarn prettier:fix && yarn lint:fix", - "stylelint": "make stylelint", - "stylelint:overrides": "make stylelint-overrides", - "stylelint:fix": "make stylelint-fix", - "prettier": "make prettier", - "prettier:fix": "make prettier-fix", - "lint": "make lint", - "lint:fix": "make lint-fix", - "i18n": "make i18n", - "cypress:run": "make cypress-run", - "cypress:open": "make cypress-open", - "prepare": "husky install" - } + "packageManager": "pnpm@10.20.0" } diff --git a/packages/volto-object-widget/.env b/packages/volto-object-widget/.env new file mode 100644 index 0000000..1762bf3 --- /dev/null +++ b/packages/volto-object-widget/.env @@ -0,0 +1 @@ +VITEST_USE_SETUP=ON # Vitest configuration variables: ON, OFF diff --git a/packages/volto-object-widget/.npmignore b/packages/volto-object-widget/.npmignore new file mode 100644 index 0000000..080322a --- /dev/null +++ b/packages/volto-object-widget/.npmignore @@ -0,0 +1,96 @@ +# https://docs.npmjs.com/using-npm/developers.html#keeping-files-out-of-your-package + +# Directories +api/ +bin/ +build/ +lib/ +g-api/ +tests/ + +# Docs +docs/ + +# Cypress +cypress/ + +# Tests +__tests__/ +*.snap + +# Files +.travis.yml +requirements-docs.txt +requirements-tests.txt +yarn.lock +.dockerignore +.gitattributes +.yarnrc +.nvmrc +changelogupdater.js +pip-selfcheck.json +Dockerfile +CNAME +entrypoint.sh +Jenkinsfile +Makefile + +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# TypeScript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env + +# next.js build output +.next + +styleguide.config +.vscode +packages diff --git a/.release-it.json b/packages/volto-object-widget/.release-it.json similarity index 100% rename from .release-it.json rename to packages/volto-object-widget/.release-it.json diff --git a/CHANGELOG.md b/packages/volto-object-widget/CHANGELOG.md similarity index 100% rename from CHANGELOG.md rename to packages/volto-object-widget/CHANGELOG.md diff --git a/packages/volto-object-widget/LICENSE.md b/packages/volto-object-widget/LICENSE.md new file mode 100644 index 0000000..0992c00 --- /dev/null +++ b/packages/volto-object-widget/LICENSE.md @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2020 European Environment Agency + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/volto-object-widget/README.md b/packages/volto-object-widget/README.md new file mode 100644 index 0000000..a285516 --- /dev/null +++ b/packages/volto-object-widget/README.md @@ -0,0 +1,232 @@ +# @eeacms/volto-object-widget + +[![Releases](https://img.shields.io/github/v/release/eea/volto-object-widget)](https://github.com/eea/volto-object-widget/releases) +[![Pipeline](https://ci.eionet.europa.eu/buildStatus/icon?job=volto-addons%2Fvolto-object-widget%2Fmaster&subject=master)](https://ci.eionet.europa.eu/view/Github/job/volto-addons/job/volto-object-widget/job/master/display/redirect) +[![Coverage](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&metric=coverage)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget) + +[Volto](https://github.com/plone/volto) add-on: Various Volto schema-based widgets. + +## Features + +This Volto addon provides several "abstract" widgets, to allow complex +information to be editable by the schema-based forms. It centers around the +concept: "we can create a form to edit a JSON object by using a schema" and so +it provides, right now, widgets to edit "list of JSON objects", a "mapping of +JSON objects" and a single "JSON object, but I choose the schema for it". + +### FlatListObject + +![Flat List object](https://raw.githubusercontent.com/eea/volto-object-widget/master/img/flat-list-widget.png) + +This widget allows you to edit a list of objects by creating, editing and +deleting instances of objects editable with the provided `schema` parameter. +The list is sortable with drag&drop. You can also provide a schema extender, +a function with signature `(schema, data) => schema`, which will adjust, per +instance of object, its schema. To use this widget, in the schema, set the +`widget` field to `object_list_inline`. + +Example of how the data could look like for a block: + +``` +"a55c5053-ba81-4f73-ab29-7cdea74df20f": { + "@type": "dataTable", + "columns": [ + { + "@id": "f899ca76-68be-4ded-aa0b-669c04c27309", + "column": " PERC_HA_07\n(in %)", + "renderer": "progress", + "title": "21" + }, + { + "@id": "94315c5a-e031-4b7e-acb2-93887878a252", + "column": " PERC_HA_07\n(in %)", + "title": "12" + } + ], +} +``` + +The `columns` field, in this case, is data generated by the `FlatListObject`. +The schema for this field could look like (`ColumnSchema()` just generates +another instance of a schema, suitable for the `column` definition of our +specific use case): + +``` +columns: { + title: 'Columns', + description: 'Leave empty to show all columns', + schema: ColumnSchema(), + widget: 'object_list_inline', +}, +``` + +### Mapping Widget + +![Mapping widget](https://raw.githubusercontent.com/eea/volto-object-widget/master/img/mapping-widget.png) + +This widget allows editing the properties of an object. For example, in the +following block data, the `row_colors` value is generated by an instance of the +`MappingWidget`. + +``` +"4430a32a-a266-497b-88e7-72fead5ab718": { + "@type": "dottedTableChart", + "column_data": "habitat_group", + "row_colors": { + "Bad": "#ed1834", + "F - Heathland, scrub and tundra": "#88c24f", + "Good": "#3c8000", + "Poor": "#f2a70e", + "Unknown": "#8d8d8d" + }, + "row_data": "assessment", + "size_data": "quantity" +}, +``` + +You need to provide the `options`, which is a list of objects with `{id, title}` and the `field_props`, which are parameters for the actual field that +will be used to edit the values. In our case the schema definition that was +used to edit the above value is (note, the options are empty, we're populating +them in the edit component, before passing the schema to the form): + +``` +row_colors: { + title: 'Colors', + widget: 'option_mapping', + field_props: { + widget: 'simple_color', + available_colors: settings.available_colors, + }, + options: [], +} +``` + +To use this widget, in the schema, set the `widget` field to `option_mapping`. + +### Object by type + +![Object by type](https://raw.githubusercontent.com/eea/volto-object-widget/master/img/object-by-type-widget.png) + +With this widget you can choose the type of value that will be used, from +a predefined list of schemas. A schema that would use this type of widget could +look like: + +``` +const LinkEditSchema = { + title: 'Link', + fieldsets: [ + { + id: 'default', + title: 'Default', + fields: ['link'], + }, + ], + properties: { + link: { + title: 'Link', + widget: 'object_by_type', + schemas: [ + { + id: 'internal', + icon: internalSVG, + schema: InternalLinkSchema, + }, + { + id: 'external', + icon: externalSVG, + schema: ExternalLinkSchema, + }, + { + id: 'email', + icon: emailSVG, + schema: EmailLinkSchema, + }, + ], + }, + }, + required: [], +}; +``` + +To use this widget, in the schema, set the `widget` field to `object_by_type`. + +## Upgrade + +### Upgrading to 10.x + +> This version requires `Volto 18` or `Volto 19` and Node.js 22. + +Every widget it registers (`object_list_popup`, `object_list_inline`, `object_by_type`, `option_mapping`, `attachedimage`, `attachedfile`, `object_types_widget`, `url`, `internal_url`, `json`) and every export other add-ons import keeps the same name and behaviour, so upgrading from 9.x on Volto 18 needs no content changes. The release adds Volto 19 support and moves the repository to the Volto 19 layout, where the published package lives in `packages/volto-object-widget`. + +#### Breaking changes + +- **Node.js 22 or newer is required** (`engines.node >= 22`), 9.x declared no engine. +- **React 18 is required.** The package declares `react` and `react-dom` as `^18.2.0` peers, 9.x declared no peers. +- **The package no longer ships the Jest setup.** `jest-addon.config.js` and `jest.setup.js` were removed in favour of Vitest, so a Volto 18 project that still runs the Jest harness has to keep its own copy. + +## Requirements + +### Backend + +- [Plone](https://plone.org/download) +- [plone.restapi](https://pypi.org/project/plone.restapi/) + +### Frontend + +- Node.js: `>=22.0.0` + +## Installation + +1. Make sure you have a [Plone backend](https://plone.org/download) up-and-running at http://localhost:8080/Plone + + ```Bash + docker compose up backend + ``` + +1. Start Volto frontend + +* If you already have a volto project, just update `package.json`: + + ```JSON + "dependencies": { + "@eeacms/volto-object-widget": "*" + } + ``` + + and `volto.config.js`: + + ```JavaScript + const addons = ['@eeacms/volto-object-widget']; + ``` + +* If not, create one with Cookieplone, as recommended by the official Plone documentation for Volto 18+: + + ``` + uvx cookieplone project + cd project-title + ``` + +1. Install or update dependencies, then start the project: + + ``` + make install + ``` + + For a Cookieplone project, start the backend and frontend in separate terminals: + + ``` + make backend-start + make frontend-start + ``` + +1. Go to http://localhost:3000 + +1. Happy editing! + +## License + +See [LICENSE.md](LICENSE.md) for details. + +## Funding + +[European Environment Agency (EU)](http://eea.europa.eu) diff --git a/packages/volto-object-widget/babel.config.js b/packages/volto-object-widget/babel.config.js new file mode 100644 index 0000000..a900a75 --- /dev/null +++ b/packages/volto-object-widget/babel.config.js @@ -0,0 +1 @@ +module.exports = require('@plone/volto/babel'); diff --git a/locales/de/LC_MESSAGES/volto.po b/packages/volto-object-widget/locales/de/LC_MESSAGES/volto.po similarity index 100% rename from locales/de/LC_MESSAGES/volto.po rename to packages/volto-object-widget/locales/de/LC_MESSAGES/volto.po diff --git a/locales/en/LC_MESSAGES/volto.po b/packages/volto-object-widget/locales/en/LC_MESSAGES/volto.po similarity index 100% rename from locales/en/LC_MESSAGES/volto.po rename to packages/volto-object-widget/locales/en/LC_MESSAGES/volto.po diff --git a/locales/it/LC_MESSAGES/volto.po b/packages/volto-object-widget/locales/it/LC_MESSAGES/volto.po similarity index 100% rename from locales/it/LC_MESSAGES/volto.po rename to packages/volto-object-widget/locales/it/LC_MESSAGES/volto.po diff --git a/locales/ro/LC_MESSAGES/volto.po b/packages/volto-object-widget/locales/ro/LC_MESSAGES/volto.po similarity index 100% rename from locales/ro/LC_MESSAGES/volto.po rename to packages/volto-object-widget/locales/ro/LC_MESSAGES/volto.po diff --git a/locales/volto.pot b/packages/volto-object-widget/locales/volto.pot similarity index 100% rename from locales/volto.pot rename to packages/volto-object-widget/locales/volto.pot diff --git a/packages/volto-object-widget/package.json b/packages/volto-object-widget/package.json new file mode 100644 index 0000000..732dbc8 --- /dev/null +++ b/packages/volto-object-widget/package.json @@ -0,0 +1,93 @@ +{ + "name": "@eeacms/volto-object-widget", + "version": "10.0.0", + "description": "volto-object-widget: Volto add-on", + "main": "src/index.js", + "author": "European Environment Agency: IDM2 A-Team", + "license": "MIT", + "homepage": "https://github.com/eea/volto-object-widget", + "keywords": [ + "volto-addon", + "volto-widget", + "volto", + "plone", + "react" + ], + "repository": { + "type": "git", + "url": "git@github.com:eea/volto-object-widget.git" + }, + "dependencies": { + "jsoneditor": "10.2.0" + }, + "devDependencies": { + "@cypress/code-coverage": "^3.10.0", + "@plone/scripts": "workspace:*", + "babel-plugin-transform-class-properties": "^6.24.1", + "cypress": "13.1.0", + "cypress-file-upload": "^5.0.8", + "dotenv": "^16.3.2", + "husky": "^8.0.3", + "lint-staged": "^14.0.1", + "md5": "^2.3.0", + "@plone/registry": "workspace:*", + "@plone/types": "workspace:*", + "@testing-library/jest-dom": "6.9.1", + "@testing-library/react": "^16.3.2", + "@types/react": "^18.3.1", + "@types/react-dom": "^18.3.1", + "@vitejs/plugin-react": "4.7.0", + "@vitest/coverage-istanbul": "3.2.7", + "jsdom": "23.0.0", + "redux-mock-store": "1.5.4", + "redux-thunk": "^2.4.2", + "release-it": "^19.0.5", + "typescript": "^5.7.3", + "vite": "6.4.3", + "vitest": "3.2.7" + }, + "lint-staged": { + "src/**/*.{js,jsx,ts,tsx,json}": [ + "make lint-fix", + "make prettier-fix" + ], + "src/**/*.{jsx}": [ + "make i18n" + ], + "theme/**/*.{css,less}": [ + "make stylelint-fix" + ], + "src/**/*.{css,less}": [ + "make stylelint-fix" + ], + "theme/**/*.overrides": [ + "make stylelint-fix" + ], + "src/**/*.overrides": [ + "make stylelint-fix" + ] + }, + "scripts": { + "release": "release-it", + "release-major-beta": "release-it major --preRelease=beta", + "release-beta": "release-it --preRelease=beta", + "test": "vitest --config ./vitest.config.mjs run --passWithNoTests", + "test:fix": "vitest --config ./vitest.config.mjs run --passWithNoTests --update", + "i18n": "rm -rf build/messages && NODE_ENV=production i18n --addon", + "prepare": "cd ../.. && husky install || true", + "dry-release": "release-it --dry-run", + "release-major-alpha": "release-it major --preRelease=alpha", + "release-alpha": "release-it --preRelease=alpha" + }, + "packageManager": "pnpm@10.20.0", + "engines": { + "node": ">=22.0.0" + }, + "publishConfig": { + "access": "public" + }, + "peerDependencies": { + "react": "^18.2.0", + "react-dom": "^18.2.0" + } +} diff --git a/src/Widget/AttachedFileWidget.jsx b/packages/volto-object-widget/src/Widget/AttachedFileWidget.jsx similarity index 100% rename from src/Widget/AttachedFileWidget.jsx rename to packages/volto-object-widget/src/Widget/AttachedFileWidget.jsx diff --git a/src/Widget/AttachedFileWidget.test.jsx b/packages/volto-object-widget/src/Widget/AttachedFileWidget.test.jsx similarity index 90% rename from src/Widget/AttachedFileWidget.test.jsx rename to packages/volto-object-widget/src/Widget/AttachedFileWidget.test.jsx index a9e9e90..f0e42cd 100644 --- a/src/Widget/AttachedFileWidget.test.jsx +++ b/packages/volto-object-widget/src/Widget/AttachedFileWidget.test.jsx @@ -1,3 +1,4 @@ +import { vi } from 'vitest'; import React from 'react'; import { render, fireEvent, screen, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; @@ -5,12 +6,12 @@ import AttachedFileWidget from './AttachedFileWidget'; import { Provider } from 'react-intl-redux'; import configureStore from 'redux-mock-store'; -jest.mock('@plone/volto/components/manage/Sidebar/ObjectBrowser', () => { - return (Component) => Component; +vi.mock('@plone/volto/components/manage/Sidebar/ObjectBrowser', () => { + return { default: (Component) => Component }; }); -jest.mock('promise-file-reader', () => ({ - readAsDataURL: jest.fn(() => +vi.mock('promise-file-reader', () => ({ + readAsDataURL: vi.fn(() => Promise.resolve('data:text/plain;base64,SGVsbG8sIFdvcmxkIQ=='), ), })); @@ -20,7 +21,7 @@ const store = mockStore({ intl: { locale: 'en', messages: {}, - formatMessage: jest.fn(), + formatMessage: vi.fn(), subrequests: {}, }, router: { @@ -30,11 +31,11 @@ const store = mockStore({ }); describe('AttachedFileWidget', () => { - const mockOnChange = jest.fn(); - const mockOpenObjectBrowser = jest.fn(); + const mockOnChange = vi.fn(); + const mockOpenObjectBrowser = vi.fn(); beforeEach(() => { - jest.clearAllMocks(); + vi.clearAllMocks(); }); it('renders without crashing', () => { diff --git a/src/Widget/AttachedImageWidget.jsx b/packages/volto-object-widget/src/Widget/AttachedImageWidget.jsx similarity index 100% rename from src/Widget/AttachedImageWidget.jsx rename to packages/volto-object-widget/src/Widget/AttachedImageWidget.jsx diff --git a/src/Widget/InternalUrlWidget.jsx b/packages/volto-object-widget/src/Widget/InternalUrlWidget.jsx similarity index 100% rename from src/Widget/InternalUrlWidget.jsx rename to packages/volto-object-widget/src/Widget/InternalUrlWidget.jsx diff --git a/src/Widget/JsonWidget/JsonWidget.jsx b/packages/volto-object-widget/src/Widget/JsonWidget/JsonWidget.jsx similarity index 100% rename from src/Widget/JsonWidget/JsonWidget.jsx rename to packages/volto-object-widget/src/Widget/JsonWidget/JsonWidget.jsx diff --git a/src/Widget/JsonWidget/JsonWidget.test.jsx b/packages/volto-object-widget/src/Widget/JsonWidget/JsonWidget.test.jsx similarity index 78% rename from src/Widget/JsonWidget/JsonWidget.test.jsx rename to packages/volto-object-widget/src/Widget/JsonWidget/JsonWidget.test.jsx index 5cd7ed4..5733f31 100644 --- a/src/Widget/JsonWidget/JsonWidget.test.jsx +++ b/packages/volto-object-widget/src/Widget/JsonWidget/JsonWidget.test.jsx @@ -1,14 +1,15 @@ +import { vi } from 'vitest'; import React from 'react'; import { Provider } from 'react-intl-redux'; import { render, fireEvent, screen, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; import configureStore from 'redux-mock-store'; import JsonWidget from './JsonWidget'; -jest.mock('jsoneditor/dist/jsoneditor.min.css', () => {}); -jest.mock('./json-widget.css', () => {}); +vi.mock('jsoneditor/dist/jsoneditor.min.css', () => ({})); +vi.mock('./json-widget.css', () => ({})); // Mock semantic-ui-react components to simple HTML elements -jest.mock('semantic-ui-react', () => { +vi.mock('semantic-ui-react', () => { const Button = (props) => ; const Segment = (props) =>
{props.children}
; const TextArea = (props) =>