diff --git a/CHANGELOG.md b/CHANGELOG.md index ed40fea..9457695 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +## [Unreleased] + +### Fixed + +* Advanced filters stay within what Strapi accepts: at most 100 values for "is one of" / "is none of" and at most 100 conditions with "Any condition" (the `arrayLimit` of Strapi's `strapi::query` middleware; Strapi 5.63 answers a longer list with 400), and at most 20 conditions with "All conditions" (with more, the Content Manager list view does not render on Strapi 5.62 and 5.63). The editor says so next to the fields, in all five admin languages, instead of applying a filter that fails. +* Opening a bookmark whose filters exceed these limits shows a notice that explains how to fix it, instead of a list view that fails. Magic Mark 4.x already refuses to save more than 100 items in one list; older bookmarks can still hold more. +* The Advanced filters dialog no longer logs the Radix "Missing `Description`" warning: its title is its only label (`aria-describedby={undefined}`). + ## [4.0.2](https://github.com/Schero94/Magicmark/compare/v4.0.1...v4.0.2) (2026-11-17) diff --git a/README.md b/README.md index ced7234..a789b48 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,14 @@ appear as filter tags and can be removed one by one. With **Any condition** the correctly, but Strapi does not show those conditions as tags; open Advanced filters to change or clear them. +A filter can have at most 100 values for "is one of" / "is none of" and at most 100 conditions +with **Any condition**: that is the `arrayLimit` of Strapi's `strapi::query` middleware, and from +Strapi 5.63 a longer list is answered with 400. With **All conditions** the limit is 20, because +the Content Manager list view does not open with more `$and` conditions in the URL (Strapi 5.62 +and 5.63). Advanced filters shows these limits next to the fields, and a bookmark with a longer +list is not opened: a notice asks you to narrow the filters and save the current view into the +bookmark again. + ## Configuration Magic Mark has no configuration options and reads no environment variables. Access is controlled @@ -364,6 +372,7 @@ you deploy the upgrade. | Users are listed without email | Email is shown only to admins who can read admin users. | | Advanced filters show only some fields | The role can read only those fields of the content type in the Content Manager. | | "This bookmark does not point to a list view" | A 3.x bookmark had an unusual path. Delete it and save the view again. | +| "This bookmark was not opened: a filter in it has more than 100 values or conditions" | Strapi accepts at most 100 items in one filter list. Open the list, narrow that filter, then save the current view into the bookmark. | | After an upgrade with several instances, some processes stopped with "already exists" | Strapi's schema sync ran in several processes at once. Restart them; see [Running several instances](#running-several-instances-railway-replicas-pm2-cluster). | | The plugin does not show up after installing | Rebuild the admin panel (`npm run build`) and restart Strapi. | diff --git a/admin/src/components/AdvancedFiltersModal.tsx b/admin/src/components/AdvancedFiltersModal.tsx index 16eea0d..d1b5c81 100644 --- a/admin/src/components/AdvancedFiltersModal.tsx +++ b/admin/src/components/AdvancedFiltersModal.tsx @@ -24,6 +24,7 @@ import { SingleSelectOption, TextButton, TextInput, + Typography, } from '@strapi/design-system'; import { Plus, Trash } from '@strapi/icons'; import { deepEncodeQueryValues, useQueryParams, withEncodedUserParams } from '@strapi/strapi/admin'; @@ -32,7 +33,9 @@ import { useIntl } from 'react-intl'; import { useFilterFields } from '../hooks/useSchemas'; import { LIST_OPERATORS, + MAX_LIST_ITEMS, NO_VALUE_OPERATORS, + maxConditions, RANGE_OPERATORS, type FieldOption, type FilterRow, @@ -40,6 +43,7 @@ import { buildFilters, datetimeToInput, fitsAdminQueryDepth, + hasTooManyValues, inputToDatetime, isDateOnly, nextRowId, @@ -100,7 +104,12 @@ export const AdvancedFiltersModal = ({ open, onOpenChange, uid }: AdvancedFilter const activeRows = rows.filter((row) => row.field || row.value); const rowErrors = new Map(activeRows.map((row) => [row.id, validateRow(row, fieldMap)])); - const hasErrors = [...rowErrors.values()].some(Boolean); + // Strapi accepts at most 100 conditions in one $or list (400 above that); with "all" the + // Content Manager list renders at most 20 (see maxConditions). + const rowLimit = maxConditions(match); + const tooManyRows = activeRows.length > rowLimit; + const atRowLimit = rows.length >= rowLimit; + const hasErrors = tooManyRows || [...rowErrors.values()].some(Boolean); const apply = () => { setShowErrors(true); @@ -133,6 +142,16 @@ export const AdvancedFiltersModal = ({ open, onOpenChange, uid }: AdvancedFilter }; const errorText = (row: FilterRow, part: string) => { + // A list that is too long is shown while typing, so the limit is clear before applying. + if (part === 'value' && hasTooManyValues(row)) { + return formatMessage( + msg( + 'filters.errorTooManyValues', + 'Enter at most {max} values. Strapi does not accept longer lists.' + ), + { max: MAX_LIST_ITEMS } + ); + } if (!showErrors || rowErrors.get(row.id) !== part) return undefined; if (part === 'field') return formatMessage(msg('filters.errorField', 'Choose a field.')); if (part === 'operator') @@ -142,7 +161,7 @@ export const AdvancedFiltersModal = ({ open, onOpenChange, uid }: AdvancedFilter return ( - + {formatMessage(msg('filters.title', 'Advanced filters'))} @@ -239,15 +258,48 @@ export const AdvancedFiltersModal = ({ open, onOpenChange, uid }: AdvancedFilter ))} - + } {...TEXT_BUTTON_TARGET} + disabled={atRowLimit} + aria-describedby={atRowLimit ? 'magic-mark-filters-row-limit' : undefined} onClick={() => setRows((prev) => [...prev, emptyRow()])} > {formatMessage(msg('filters.add', 'Add condition'))} - + {atRowLimit ? ( + + {formatMessage( + match === 'all' + ? tooManyRows + ? msg( + 'filters.errorTooManyConditionsAll', + 'With All conditions, keep at most {max} conditions: the Content Manager list does not open with more. Remove conditions or choose Any condition.' + ) + : msg( + 'filters.maxConditionsAll', + 'With All conditions, a filter can have at most {max} conditions. The Content Manager list does not open with more.' + ) + : tooManyRows + ? msg( + 'filters.errorTooManyConditions', + 'Remove conditions until at most {max} are left. Strapi does not accept more.' + ) + : msg( + 'filters.maxConditions', + 'A filter can have at most {max} conditions, the most Strapi accepts.' + ), + { max: rowLimit } + )} + + ) : null} + )} diff --git a/admin/src/hooks/useOpenBookmark.ts b/admin/src/hooks/useOpenBookmark.ts index 0d79e11..f33f1c4 100644 --- a/admin/src/hooks/useOpenBookmark.ts +++ b/admin/src/hooks/useOpenBookmark.ts @@ -5,7 +5,10 @@ * stored value can never send the user to another admin page or off-site. Before navigating, * boolean filter values are normalised for Strapi 5.62 (see `utils/booleanFilters`), and the * Content Manager's remembered list settings for that content type are replaced by the - * bookmark's own, so remembered filters do not mix into the bookmark. + * bookmark's own, so remembered filters do not mix into the bookmark. A bookmark with a list + * longer than Strapi accepts (more than 100 `$in` values or `$or` conditions, which Strapi 5.63 + * answers with 400, or more than 20 `$and` conditions, which the Content Manager list cannot + * render) is not opened: the user gets a notice that says how to fix it instead of an error. */ import { useFetchClient, useNotification } from '@strapi/strapi/admin'; import { useCallback } from 'react'; @@ -13,6 +16,7 @@ import { useIntl } from 'react-intl'; import { useNavigate } from 'react-router-dom'; import type { Bookmark } from '../types'; import { createAttributeResolver, sanitizeBooleanFilters } from '../utils/booleanFilters'; +import { exceedsListLimit } from '../utils/filters'; import type { InitData } from '../utils/fieldOptions'; import { parseListViewPath, syncPersistedListSettings } from '../utils/listView'; import { parseQuery, stringifyQuery } from '../utils/query'; @@ -74,6 +78,19 @@ export const useOpenBookmark = () => { return; } const parsed = parseQuery(bookmark.query); + if (exceedsListLimit(parsed)) { + toggleNotification({ + type: 'warning', + timeout: 15000, + message: formatMessage( + msg( + 'notification.listTooLong', + 'This bookmark was not opened: its filters have more values or conditions than Strapi accepts. Open the list, narrow the filters, then save the current view in this bookmark.' + ) + ), + }); + return; + } let saved = parsed; try { saved = normalizeSavedQuery(parsed, await loadInit(get), location.uid); diff --git a/admin/src/translations/de.json b/admin/src/translations/de.json index b286c42..a3e6482 100644 --- a/admin/src/translations/de.json +++ b/admin/src/translations/de.json @@ -18,6 +18,9 @@ "filters.conditions": "Bedingungen", "filters.errorField": "Feld auswählen.", "filters.errorOperator": "Bedingung auswählen.", + "filters.errorTooManyConditions": "Bedingungen entfernen, bis höchstens {max} übrig sind. Mehr nimmt Strapi nicht an.", + "filters.errorTooManyConditionsAll": "Bei „Alle Bedingungen“ höchstens {max} Bedingungen verwenden: Mit mehr öffnet sich die Liste im Content Manager nicht. Bedingungen entfernen oder „Eine der Bedingungen“ wählen.", + "filters.errorTooManyValues": "Höchstens {max} Werte eingeben. Längere Listen nimmt Strapi nicht an.", "filters.errorValue": "Wert eingeben.", "filters.false": "falsch", "filters.field": "Feld", @@ -30,6 +33,8 @@ "filters.matchAll": "Alle Bedingungen", "filters.matchAny": "Eine der Bedingungen", "filters.matchAnyHint": "Diese Bedingungen erscheinen nicht als Filter-Tags über der Liste.", + "filters.maxConditions": "Ein Filter kann höchstens {max} Bedingungen haben, mehr nimmt Strapi nicht an.", + "filters.maxConditionsAll": "Bei „Alle Bedingungen“ kann ein Filter höchstens {max} Bedingungen haben. Mit mehr öffnet sich die Liste im Content Manager nicht.", "filters.noFields": "Keine passenden Felder", "filters.operator": "Bedingung", "filters.remove": "Bedingung {number} entfernen", @@ -106,6 +111,7 @@ "notification.invalidPath": "Dieses Lesezeichen verweist auf keine Listenansicht.", "notification.linkCopied": "Link kopiert.", "notification.linkCopyError": "Der Link konnte nicht kopiert werden.", + "notification.listTooLong": "Dieses Lesezeichen wurde nicht geöffnet: Seine Filter haben mehr Werte oder Bedingungen, als Strapi annimmt. Die Liste öffnen, die Filter eingrenzen und dann die aktuelle Ansicht in diesem Lesezeichen speichern.", "notification.pinError": "Das Lesezeichen konnte nicht angeheftet werden.", "notification.pinned": "Lesezeichen angeheftet.", "notification.saveError": "Das Lesezeichen konnte nicht gespeichert werden. Die Änderungen sind noch im Formular.", diff --git a/admin/src/translations/en.json b/admin/src/translations/en.json index 16e73aa..97b5696 100644 --- a/admin/src/translations/en.json +++ b/admin/src/translations/en.json @@ -18,6 +18,9 @@ "filters.conditions": "Conditions", "filters.errorField": "Choose a field.", "filters.errorOperator": "Choose a condition.", + "filters.errorTooManyConditions": "Remove conditions until at most {max} are left. Strapi does not accept more.", + "filters.errorTooManyConditionsAll": "With All conditions, keep at most {max} conditions: the Content Manager list does not open with more. Remove conditions or choose Any condition.", + "filters.errorTooManyValues": "Enter at most {max} values. Strapi does not accept longer lists.", "filters.errorValue": "Enter a value.", "filters.false": "false", "filters.field": "Field", @@ -30,6 +33,8 @@ "filters.matchAll": "All conditions", "filters.matchAny": "Any condition", "filters.matchAnyHint": "These conditions are not shown as filter tags above the list.", + "filters.maxConditions": "A filter can have at most {max} conditions, the most Strapi accepts.", + "filters.maxConditionsAll": "With All conditions, a filter can have at most {max} conditions. The Content Manager list does not open with more.", "filters.noFields": "No matching fields", "filters.operator": "Condition", "filters.remove": "Remove condition {number}", @@ -106,6 +111,7 @@ "notification.invalidPath": "This bookmark does not point to a list view.", "notification.linkCopied": "Link copied.", "notification.linkCopyError": "The link could not be copied.", + "notification.listTooLong": "This bookmark was not opened: its filters have more values or conditions than Strapi accepts. Open the list, narrow the filters, then save the current view in this bookmark.", "notification.pinError": "The bookmark could not be pinned.", "notification.pinned": "Bookmark pinned.", "notification.saveError": "The bookmark could not be saved. Your changes are still in the form.", diff --git a/admin/src/translations/es.json b/admin/src/translations/es.json index b151d90..6905e9f 100644 --- a/admin/src/translations/es.json +++ b/admin/src/translations/es.json @@ -18,6 +18,9 @@ "filters.conditions": "Condiciones", "filters.errorField": "Elija un campo.", "filters.errorOperator": "Elija una condición.", + "filters.errorTooManyConditions": "Elimina condiciones hasta que queden como máximo {max}. Strapi no acepta más.", + "filters.errorTooManyConditionsAll": "Con «Todas las condiciones», usa como máximo {max} condiciones: la lista del Content Manager no se abre con más. Elimina condiciones o elige «Alguna condición».", + "filters.errorTooManyValues": "Introduce como máximo {max} valores. Strapi no acepta listas más largas.", "filters.errorValue": "Introduzca un valor.", "filters.false": "falso", "filters.field": "Campo", @@ -30,6 +33,8 @@ "filters.matchAll": "Todas las condiciones", "filters.matchAny": "Alguna condición", "filters.matchAnyHint": "Estas condiciones no aparecen como etiquetas de filtro sobre la lista.", + "filters.maxConditions": "Un filtro puede tener como máximo {max} condiciones, el máximo que acepta Strapi.", + "filters.maxConditionsAll": "Con «Todas las condiciones», un filtro puede tener como máximo {max} condiciones. La lista del Content Manager no se abre con más.", "filters.noFields": "No hay campos coincidentes", "filters.operator": "Condición", "filters.remove": "Quitar la condición {number}", @@ -106,6 +111,7 @@ "notification.invalidPath": "Este marcador no apunta a una vista de lista.", "notification.linkCopied": "Enlace copiado.", "notification.linkCopyError": "No se pudo copiar el enlace.", + "notification.listTooLong": "Este marcador no se abrió: sus filtros tienen más valores o condiciones de los que acepta Strapi. Abre la lista, reduce los filtros y guarda la vista actual en este marcador.", "notification.pinError": "No se pudo fijar el marcador.", "notification.pinned": "Marcador fijado.", "notification.saveError": "No se pudo guardar el marcador. Los cambios siguen en el formulario.", diff --git a/admin/src/translations/fr.json b/admin/src/translations/fr.json index dd621ce..3f59482 100644 --- a/admin/src/translations/fr.json +++ b/admin/src/translations/fr.json @@ -18,6 +18,9 @@ "filters.conditions": "Conditions", "filters.errorField": "Choisissez un champ.", "filters.errorOperator": "Choisissez une condition.", + "filters.errorTooManyConditions": "Supprimez des conditions pour n'en garder que {max} au plus. Strapi n'en accepte pas davantage.", + "filters.errorTooManyConditionsAll": "Avec « Toutes les conditions », gardez au plus {max} conditions : la liste du Content Manager ne s'ouvre pas avec davantage. Supprimez des conditions ou choisissez « Au moins une condition ».", + "filters.errorTooManyValues": "Saisissez au plus {max} valeurs. Strapi n'accepte pas de listes plus longues.", "filters.errorValue": "Saisissez une valeur.", "filters.false": "faux", "filters.field": "Champ", @@ -30,6 +33,8 @@ "filters.matchAll": "Toutes les conditions", "filters.matchAny": "Au moins une condition", "filters.matchAnyHint": "Ces conditions ne s'affichent pas comme étiquettes de filtre au-dessus de la liste.", + "filters.maxConditions": "Un filtre peut avoir au plus {max} conditions, le maximum accepté par Strapi.", + "filters.maxConditionsAll": "Avec « Toutes les conditions », un filtre peut avoir au plus {max} conditions. La liste du Content Manager ne s'ouvre pas avec davantage.", "filters.noFields": "Aucun champ correspondant", "filters.operator": "Condition", "filters.remove": "Supprimer la condition {number}", @@ -106,6 +111,7 @@ "notification.invalidPath": "Ce favori ne pointe vers aucune vue de liste.", "notification.linkCopied": "Lien copié.", "notification.linkCopyError": "Le lien n'a pas pu être copié.", + "notification.listTooLong": "Ce favori n'a pas été ouvert : ses filtres ont plus de valeurs ou de conditions que Strapi n'en accepte. Ouvrez la liste, restreignez les filtres, puis enregistrez la vue actuelle dans ce favori.", "notification.pinError": "Le favori n'a pas pu être épinglé.", "notification.pinned": "Favori épinglé.", "notification.saveError": "Le favori n'a pas pu être enregistré. Vos modifications sont toujours dans le formulaire.", diff --git a/admin/src/translations/pt.json b/admin/src/translations/pt.json index 9c1f3ca..77aff0f 100644 --- a/admin/src/translations/pt.json +++ b/admin/src/translations/pt.json @@ -18,6 +18,9 @@ "filters.conditions": "Condições", "filters.errorField": "Escolha um campo.", "filters.errorOperator": "Escolha uma condição.", + "filters.errorTooManyConditions": "Remova condições até restarem no máximo {max}. O Strapi não aceita mais.", + "filters.errorTooManyConditionsAll": "Com \"Todas as condições\", use no máximo {max} condições: a lista do Content Manager não abre com mais. Remova condições ou escolha \"Qualquer condição\".", + "filters.errorTooManyValues": "Insira no máximo {max} valores. O Strapi não aceita listas mais longas.", "filters.errorValue": "Informe um valor.", "filters.false": "falso", "filters.field": "Campo", @@ -30,6 +33,8 @@ "filters.matchAll": "Todas as condições", "filters.matchAny": "Qualquer condição", "filters.matchAnyHint": "Estas condições não aparecem como etiquetas de filtro acima da lista.", + "filters.maxConditions": "Um filtro pode ter no máximo {max} condições, o máximo que o Strapi aceita.", + "filters.maxConditionsAll": "Com \"Todas as condições\", um filtro pode ter no máximo {max} condições. A lista do Content Manager não abre com mais.", "filters.noFields": "Nenhum campo correspondente", "filters.operator": "Condição", "filters.remove": "Remover a condição {number}", @@ -106,6 +111,7 @@ "notification.invalidPath": "Este favorito não aponta para uma visualização de lista.", "notification.linkCopied": "Link copiado.", "notification.linkCopyError": "Não foi possível copiar o link.", + "notification.listTooLong": "Este favorito não foi aberto: os filtros têm mais valores ou condições do que o Strapi aceita. Abra a lista, restrinja os filtros e salve a visualização atual neste favorito.", "notification.pinError": "Não foi possível fixar o favorito.", "notification.pinned": "Favorito fixado.", "notification.saveError": "Não foi possível salvar o favorito. Suas alterações continuam no formulário.", diff --git a/admin/src/utils/filters.ts b/admin/src/utils/filters.ts index 9720e14..b13ca8d 100644 --- a/admin/src/utils/filters.ts +++ b/admin/src/utils/filters.ts @@ -53,6 +53,29 @@ export const NO_VALUE_OPERATORS = ['$null', '$notNull']; export const LIST_OPERATORS = ['$in', '$notIn']; export const RANGE_OPERATORS = ['$between']; +/** + * Most items Strapi accepts in one list of the query string. The `strapi::query` middleware + * parses with qs `arrayLimit: 100`; a longer list arrives as an object keyed by index, and from + * Strapi 5.63 the Content API and Content Manager answer it with 400. It applies to the values + * of `$in` / `$notIn` and to the conditions of `$and` / `$or`. + */ +export const MAX_LIST_ITEMS = 100; + +/** + * Most conditions for match "all". The admin parses the URL with qs defaults (`arrayLimit: 20`), + * so a longer `$and` list becomes an object keyed by index, and the Content Manager list view + * (`Filters` reads `query.filters.$and` with `.reduce`, Strapi 5.62 and 5.63) fails to render. + * `$or` lists are not read that way and keep {@link MAX_LIST_ITEMS}. + */ +export const MAX_ALL_CONDITIONS = 20; + +/** + * Most conditions a filter can have for a match mode. + * @param match - "all" or "any". + */ +export const maxConditions = (match: MatchMode): number => + match === 'all' ? MAX_ALL_CONDITIONS : MAX_LIST_ITEMS; + const BASE = ['$eq', '$ne', '$null', '$notNull']; const NUMERIC = ['$gt', '$gte', '$lt', '$lte']; const SENSITIVE = ['$eqi', '$nei']; @@ -161,6 +184,13 @@ export const splitList = (value: string): string[] => .map((item) => item.trim()) .filter(Boolean); +/** + * True when a `$in` / `$notIn` row has more values than Strapi accepts ({@link MAX_LIST_ITEMS}). + * @param row - The row. + */ +export const hasTooManyValues = (row: Pick): boolean => + LIST_OPERATORS.includes(row.operator) && splitList(row.value).length > MAX_LIST_ITEMS; + /** * Validates one row against the available fields. * @param row - The row. @@ -179,7 +209,10 @@ export const validateRow = ( if (NO_VALUE_OPERATORS.includes(row.operator)) return null; // Strapi 5.62 answers 400 for any other boolean value (empty, "1", "yes", padded, ...). if (field.type === 'boolean') return BOOLEAN_VALUES.includes(row.value) ? null : 'value'; - if (LIST_OPERATORS.includes(row.operator)) return splitList(row.value).length ? null : 'value'; + if (LIST_OPERATORS.includes(row.operator)) { + const count = splitList(row.value).length; + return count && count <= MAX_LIST_ITEMS ? null : 'value'; + } if (!row.value.trim()) return 'value'; if (RANGE_OPERATORS.includes(row.operator) && !(row.valueTo ?? '').trim()) return 'valueTo'; return null; @@ -346,3 +379,45 @@ export const countConditions = (filters: unknown): number => { } return count; }; + +const INDEX_KEY = /^\d+$/; + +/** Number of items in a parsed list: an array, or an object keyed only by indexes. */ +const listLength = (value: unknown): number => { + if (Array.isArray(value)) return value.length; + if (!value || typeof value !== 'object') return 0; + const keys = Object.keys(value); + return keys.length && keys.every((key) => INDEX_KEY.test(key)) + ? Math.max(...keys.map(Number)) + 1 + : 0; +}; + +/** True when an array or index-keyed object at any depth has more than {@link MAX_LIST_ITEMS} items. */ +const exceedsItemLimit = (value: unknown): boolean => { + if (Array.isArray(value)) { + return value.length > MAX_LIST_ITEMS || value.some(exceedsItemLimit); + } + if (!value || typeof value !== 'object') return false; + const keys = Object.keys(value); + if (keys.length && keys.every((key) => INDEX_KEY.test(key))) { + if (keys.some((key) => Number(key) >= MAX_LIST_ITEMS)) return true; + } + return Object.values(value as Record).some(exceedsItemLimit); +}; + +/** + * True when a parsed query holds a list that Strapi 5.63 rejects with 400: an array with more + * than {@link MAX_LIST_ITEMS} items, or an object keyed only by indexes with an index of + * {@link MAX_LIST_ITEMS} or more (what qs makes of such a list with `arrayLimit: 100`). Also true + * for a root `$and` with more than {@link MAX_ALL_CONDITIONS} conditions, which the Content + * Manager list view cannot render. + * @param value - Parsed query, or any part of it. + * @returns True when a list is too long. + */ +export const exceedsListLimit = (value: unknown): boolean => { + const filters = (value as { filters?: unknown } | null)?.filters; + if (filters && typeof filters === 'object') { + if (listLength((filters as Record).$and) > MAX_ALL_CONDITIONS) return true; + } + return exceedsItemLimit(value); +}; diff --git a/tests/admin-filters-563.test.cjs b/tests/admin-filters-563.test.cjs new file mode 100644 index 0000000..a7047ad --- /dev/null +++ b/tests/admin-filters-563.test.cjs @@ -0,0 +1,120 @@ +'use strict'; + +/** + * Strapi 5.63 list limit: the `strapi::query` middleware parses the query string with qs + * `arrayLimit: 100`. A longer list (more than 100 `$in` / `$notIn` values or `$and` / `$or` + * conditions) arrives as an object keyed by index, and from 5.63 `@strapi/utils` answers it with + * 400 ("the list has more items than the query parser's arrayLimit"). The filter editor caps + * both at 100, and a stored bookmark over the limit is not opened. + * + * The admin parses the URL with qs defaults (arrayLimit 20): a root `$and` with more than 20 + * conditions becomes an object and the Content Manager list view (`Filters`, `$and.reduce`) + * fails to render, so match "all" is capped at 20 conditions. + */ +require('./helpers/register-ts.cjs'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const test = require('node:test'); +const qs = require('qs'); + +const f = require('../admin/src/utils/filters.ts'); +const { parseQuery, stringifyQuery } = require('../admin/src/utils/query.ts'); + +/** The options of Strapi's `strapi::query` middleware (`@strapi/core` 5.63.0 `middlewares/query`). */ +const STRAPI_QUERY = { strictNullHandling: true, arrayLimit: 100, depth: 20 }; + +const fields = new Map( + [ + { path: 'title', label: 'Title', type: 'string' }, + { path: 'views', label: 'Views', type: 'integer' }, + ].map((field) => [field.path, field]) +); +const values = (n) => Array.from({ length: n }, (_, i) => `v${i}`); +const row = (field, operator, value = '') => ({ id: f.nextRowId(), field, operator, value }); +const read = (file) => fs.readFileSync(path.join(__dirname, '..', file), 'utf8'); + +test('the limit is the arrayLimit of the strapi::query middleware', () => { + assert.equal(f.MAX_LIST_ITEMS, 100); + const at = qs.parse(stringifyQuery({ filters: { title: { $in: values(100) } } }), STRAPI_QUERY); + assert.ok(Array.isArray(at.filters.title.$in), '100 values stay a list'); + const over = qs.parse(stringifyQuery({ filters: { title: { $in: values(101) } } }), STRAPI_QUERY); + assert.ok(!Array.isArray(over.filters.title.$in), '101 values become an object (400 on 5.63)'); +}); + +test('$in / $notIn rows accept up to 100 values and reject more', () => { + for (const operator of ['$in', '$notIn']) { + const ok = row('title', operator, values(100).join(', ')); + assert.equal(f.validateRow(ok, fields), null, `${operator} 100`); + assert.equal(f.hasTooManyValues(ok), false); + const tooMany = row('title', operator, values(101).join(', ')); + assert.equal(f.validateRow(tooMany, fields), 'value', `${operator} 101`); + assert.equal(f.hasTooManyValues(tooMany), true); + } + // Empty items do not count: "a,,b" is two values. + assert.equal(f.hasTooManyValues(row('title', '$in', `${values(100).join(',')},,,`)), false); + // Other operators never count list items. + assert.equal(f.hasTooManyValues(row('title', '$eq', values(101).join(', '))), false); +}); + +test('exceedsListLimit finds long lists in a parsed bookmark query', () => { + const stored = (filters) => parseQuery(stringifyQuery({ page: '1', filters })); + assert.equal(f.exceedsListLimit(stored({ $and: [{ title: { $in: values(100) } }] })), false); + assert.equal(f.exceedsListLimit(stored({ $and: [{ title: { $in: values(101) } }] })), true); + assert.equal(f.exceedsListLimit(stored({ $and: [{ title: { $notIn: values(150) } }] })), true); + + const rows = (n) => Array.from({ length: n }, (_, i) => ({ views: { $eq: String(i) } })); + assert.equal(f.exceedsListLimit(stored({ $or: rows(100) })), false, '$or 100'); + assert.equal(f.exceedsListLimit(stored({ $or: rows(101) })), true, '$or 101'); + assert.equal(f.exceedsListLimit(stored({ $and: rows(20) })), false, '$and 20'); + assert.equal(f.exceedsListLimit(stored({ $and: rows(21) })), true, '$and 21'); + // The admin's own parse (qs defaults) turns 21 $and conditions into an index-keyed object. + const adminParsed = qs.parse(stringifyQuery({ filters: { $and: rows(21) } })); + assert.ok(!Array.isArray(adminParsed.filters.$and)); + assert.equal(f.exceedsListLimit(adminParsed), true); + // A plain array (not parsed) longer than the limit counts too. + assert.equal(f.exceedsListLimit({ filters: { $or: rows(101) } }), true); + // Ordinary queries and values are untouched. + assert.equal(f.exceedsListLimit(parseQuery('page=1&pageSize=10&sort=title:ASC')), false); + assert.equal(f.exceedsListLimit({}), false); + assert.equal(f.exceedsListLimit(null), false); + assert.equal(f.exceedsListLimit('x'.repeat(500)), false); +}); + +test('buildFilters output within the limits stays a list for Strapi', () => { + const filters = f.buildFilters( + 'any', + Array.from({ length: 100 }, (_, i) => row('views', '$eq', String(i))) + ); + const parsed = qs.parse(stringifyQuery({ filters }), STRAPI_QUERY); + assert.ok(Array.isArray(parsed.filters.$or)); + assert.equal(parsed.filters.$or.length, 100); + assert.equal(f.exceedsListLimit(parseQuery(stringifyQuery({ filters }))), false); +}); + +test('match "all" allows 20 conditions, "any" 100', () => { + assert.equal(f.MAX_ALL_CONDITIONS, 20); + assert.equal(f.maxConditions('all'), 20); + assert.equal(f.maxConditions('any'), 100); + const parsed = qs.parse( + stringifyQuery({ + filters: { $and: Array.from({ length: 20 }, (_, i) => ({ views: { $eq: String(i) } })) }, + }) + ); + assert.ok(Array.isArray(parsed.filters.$and), '20 stay a list in the admin parse'); +}); + +test('the editor caps conditions and the opener checks the limit before navigating', () => { + const modal = read('admin/src/components/AdvancedFiltersModal.tsx'); + assert.match(modal, /maxConditions\(match\)/); + assert.match(modal, /activeRows\.length > rowLimit/); + assert.match(modal, /rows\.length >= rowLimit/); + assert.match(modal, /disabled=\{atRowLimit\}/); + assert.match(modal, /hasTooManyValues\(row\)/); + + const opener = read('admin/src/hooks/useOpenBookmark.ts'); + const check = opener.indexOf('exceedsListLimit(parsed)'); + assert.ok(check > 0, 'useOpenBookmark checks the list limit'); + assert.ok(check < opener.indexOf('navigate({'), 'the check runs before navigating'); + assert.match(opener.slice(check, opener.indexOf('navigate({')), /notification\.listTooLong/); +});