data-primals-engine 1.7.0 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/filter.js CHANGED
@@ -1,343 +1,348 @@
1
-
2
- let safeRegex = null; // Par défaut, aucune fonction de validation n'est définie.
3
-
4
- /**
5
- * Permet d'injecter une fonction de validation de regex (côté serveur).
6
- * @param {function} validator - La fonction qui valide une regex, ex: la fonction du module 'safe-regex'.
7
- */
8
- export function setSafeRegex(validator) {
9
- safeRegex = validator;
10
- }
11
-
12
- /**
13
- * Évalue une comparaison entre une valeur cible et une valeur de condition.
14
- * @param {string} operator - L'opérateur de comparaison (ex: '$eq', '$lt').
15
- * @param {*} targetValue - La valeur actuelle du champ dans les données.
16
- * @param {*} processedConditionValue - La valeur de la condition à comparer.
17
- * @param {object} condition - La condition complète pour le contexte de logging.
18
- * @returns {boolean} - Le résultat de la comparaison.
19
- */
20
- function evaluateComparison(operator, targetValue, processedConditionValue, condition) {
21
- const logClientEvalWarning = (message, details) => {
22
- console.warn(`[Client Eval] ${message}:`, details);
23
- };
24
-
25
- try {
26
- switch (operator) {
27
- case '$eq': return targetValue == processedConditionValue; // Utilise '==' pour une comparaison plus souple
28
- case '$ne': return targetValue != processedConditionValue;
29
- case '$gt': return targetValue > processedConditionValue;
30
- case '$lt': return targetValue < processedConditionValue;
31
- case '$gte': return targetValue >= processedConditionValue;
32
- case '$lte': return targetValue <= processedConditionValue;
33
- case '$regex':
34
- if (typeof targetValue !== 'string' || !processedConditionValue || typeof processedConditionValue !== 'string') return false;
35
- try {
36
- if (safeRegex && !safeRegex(processedConditionValue)) return false;
37
- const regex = new RegExp(processedConditionValue, 'i');
38
- return regex.test(targetValue);
39
- } catch (e) {
40
- logClientEvalWarning(`Invalid regex pattern: ${processedConditionValue}`, condition);
41
- return false;
42
- }
43
- case '$in': return Array.isArray(processedConditionValue) && processedConditionValue.includes(targetValue);
44
- case '$nin': return !Array.isArray(processedConditionValue) || !processedConditionValue.includes(targetValue);
45
- default: return true; // Permissif par défaut pour les opérateurs non gérés
46
- }
47
- } catch (evalError) {
48
- logClientEvalWarning(`Error during condition evaluation: ${operator}, targetValue=${targetValue}, processedConditionValue=${processedConditionValue}`, condition);
49
- return false;
50
- }
51
- }
52
-
53
- /**
54
- * Récupère une valeur imbriquée dans un objet en utilisant une chaîne de chemin.
55
- * Gère les tableaux et les objets. Retourne undefined si le chemin n'est pas trouvé.
56
- * Exemple: getNestedValue({ a: { b: [ { c: 1 } ] } }, 'a.b.0.c') -> 1
57
- *
58
- * @param {object} obj L'objet source.
59
- * @param {string} path La chaîne de chemin (ex: 'user.address.city').
60
- * @returns {*} La valeur trouvée ou undefined.
61
- */
62
- function getNestedValue(obj, path) {
63
- // Vérifie si l'objet ou le chemin est invalide
64
- if (!obj || typeof path !== 'string') {
65
- return undefined;
66
- }
67
- // Sépare le chemin en clés individuelles (ex: 'a.b.0.c' -> ['a', 'b', '0', 'c'])
68
- const keys = path.split('.');
69
- let current = obj; // Commence à la racine de l'objet
70
-
71
- // Parcourt chaque clé dans le chemin
72
- for (const key of keys) {
73
- // Si à un moment donné on atteint null ou undefined, le chemin est invalide
74
- if (current === null || current === undefined) {
75
- return undefined;
76
- }
77
- // Récupère la valeur pour la clé actuelle
78
- const value = current[key];
79
- // Si la valeur est undefined, le chemin est invalide
80
- if (value === undefined) {
81
- return undefined;
82
- }
83
- // Passe au niveau suivant de l'objet/tableau
84
- current = value;
85
- }
86
- // Retourne la valeur finale trouvée
87
- return current;
88
- }
89
- /**
90
- * Evaluates a single condition against form data.
91
- * @param {object} currentModelDef - The definition of the current model.
92
- * @param {object} condition - The condition to evaluate.
93
- * @param {object} formData - The form data.
94
- * @param {object[]} allModels - An array of all model definitions.
95
- * @param {object} user - The current user.
96
- * @returns {boolean} - True if the condition is met, false otherwise.
97
- */
98
- const evaluateSingleCondition = (currentModelDef, condition, formData, allModels, user, checkRegex =true) => {
99
- // Condition est directement un filtre MongoDB, donc on l'applique
100
- // en utilisant les opérateurs et les valeurs qu'il contient.
101
-
102
- if (!condition || typeof condition !== 'object') {
103
- console.warn("[Client Eval] Condition is not an object:", condition);
104
- return true; // Permissive default
105
- }
106
-
107
- // If the condition is a standard query operator like { amount: { $lt: 1000 } }
108
- const fieldNameFromCondition = Object.keys(condition)[0];
109
- const conditionValueObject = condition[fieldNameFromCondition];
110
-
111
- if (typeof conditionValueObject === 'object' && conditionValueObject !== null && !Array.isArray(conditionValueObject)) {
112
- const operator = Object.keys(conditionValueObject)[0];
113
- if (operator.startsWith('$')) {
114
- return evaluateComparison(operator, formData[fieldNameFromCondition], conditionValueObject[operator], condition, checkRegex);
115
- }
116
- }
117
-
118
- // Si la condition est de la forme {field: value}, on la transforme en {$eq: value}
119
- if (!Object.keys(condition)[0].startsWith('$') && typeof condition[Object.keys(condition)[0]] !== 'object') {
120
- const fieldName = Object.keys(condition)[0];
121
- const value = condition[fieldName];
122
- return evaluateSingleCondition(currentModelDef, {[fieldName]: {$eq: value}}, formData, allModels, user);
123
- }
124
-
125
- // Gestion des opérateurs d'agrégation (commencent par $)
126
- const operator = Object.keys(condition)[0];
127
- if ((operator === '$eq' || operator === '$ne') && Array.isArray(condition[operator])) {
128
- // Cas spécial pour {$op: ['$field', value]}
129
- const [fieldPath, expectedValue] = condition[operator];
130
- if (typeof fieldPath === 'string' && fieldPath.startsWith('$')) {
131
- const fieldName = fieldPath.substring(1); // Enlève le $ devant
132
- const actualValue = getNestedValue(formData, fieldName);
133
- return evaluateComparison(operator, actualValue, expectedValue, condition, checkRegex);
134
- }
135
- }
136
-
137
-
138
- // Si la condition contient des opérateurs logiques, on les gère ici
139
- if (condition.$and || condition.$or || condition.$not || condition.$nor) {
140
- console.warn("[Client Eval] Condition logique détectée dans evaluateSingleCondition, ce n'est pas attendu. Devrait être géré par isConditionMet.");
141
- return true; // Permissive default
142
- }
143
-
144
- if (condition.$find) {
145
- const fieldName = Object.keys(condition)[0];
146
- const fieldValue = formData[fieldName];
147
- const findCondition = condition.$find;
148
-
149
- if (!Array.isArray(fieldValue)) return false;
150
-
151
- return fieldValue.some(item => {
152
- // Gestion spéciale pour la syntaxe $eq: ["$$this.field", value]
153
- if (findCondition.$eq && Array.isArray(findCondition.$eq)) {
154
- const [fieldPath, value] = findCondition.$eq;
155
- if (fieldPath.startsWith("$$this.")) {
156
- const fieldToCheck = fieldPath.replace("$$this.", "");
157
- return item[fieldToCheck] == value;
158
- }
159
- }
160
-
161
- // Sinon, évaluation normale
162
- const tempData = { ...item };
163
- return evaluateSingleCondition(currentModelDef, findCondition, tempData, allModels, user);
164
- });
165
- }
166
-
167
- // Si la condition contient un opérateur $exists, on le gère ici
168
- if (condition.$exists !== undefined) {
169
- const fieldName = Object.keys(condition)[0]; // Récupérer le nom du champ
170
- const shouldExist = condition.$exists; // Récupérer la valeur de $exists (true ou false)
171
- const exists = Object.prototype.hasOwnProperty.call(formData, fieldName) && formData[fieldName] !== undefined && formData[fieldName] !== null;
172
- return exists === shouldExist;
173
- }
174
-
175
- // Si la condition contient un opérateur $find, on le gère ici
176
- if (condition.$find) {
177
- // Récupérer le nom du champ
178
- const fieldName = Object.keys(condition)[0];
179
- const fieldValue = formData[fieldName];
180
- try {
181
- // Assuming evaluateSingleCondition handles $find
182
- return evaluateSingleCondition(currentModelDef, condition.$find, formData, allModels, user);
183
- } catch (error) {
184
- console.error("Error evaluating $find condition:", condition, error);
185
- return false;
186
- }
187
- }
188
-
189
- // Récupérer le nom du champ et la condition
190
- const fieldName = Object.keys(condition)[0];
191
- const fieldValue = condition[fieldName];
192
-
193
- // Récupérer la définition du champ
194
- const fieldDef = currentModelDef?.fields.find(f => f.name === fieldName);
195
-
196
- // Si la définition du champ n'est pas trouvée, on retourne true
197
- if (!fieldDef) {
198
- console.warn(`[Client Eval] Field definition not found for field: ${fieldName}`);
199
- return true; // Permissive default
200
- }
201
-
202
- let targetValue = formData[fieldName];
203
- let processedConditionValue = fieldValue;
204
-
205
- // 1. Handle $exists (on the first field)
206
- // 2. Convert condition value based on operator's expected input type
207
- const fieldType = fieldDef?.type; // Type of the first field
208
-
209
- try {
210
- processedConditionValue = convertValueType(fieldValue, fieldType);
211
- } catch (e) {
212
- logClientEvalWarning(`Error converting value type: ${e.message}`, condition);
213
- return false;
214
- }
215
-
216
- return evaluateComparison('$eq', targetValue, processedConditionValue, condition);
217
-
218
- function logClientEvalWarning(message, details) {
219
- console.warn(`[Client Eval] ${message}:`, details);
220
- }
221
-
222
- function convertValueType(value, inputType) {
223
- switch (inputType) {
224
- case 'number':
225
- const numValue = parseFloat(value);
226
- if (isNaN(numValue)) {
227
- throw new Error(`Invalid number value: ${value}`);
228
- }
229
- return numValue;
230
- case 'boolean':
231
- return String(value).toLowerCase() === 'true';
232
- case 'csv':
233
- return String(value).split(',').map(item => item.trim()).filter(Boolean);
234
- case 'text':
235
- default:
236
- return String(value);
237
- }
238
- }
239
-
240
- };
241
-
242
- export const isConditionMet = (model, cond, formData, allModels, user,checkRegex=true) => {
243
- const condition = cond;
244
-
245
- if (!condition) return true;
246
-
247
- if (typeof condition !== 'object' || condition === null) {
248
- return true;
249
- }
250
-
251
- // --- NOUVELLE LOGIQUE ---
252
- // Gère les conditions de type expression d'agrégation comme { "$lt": ["$amount", 1000] }
253
- const operatorKeys = Object.keys(condition).filter(k => k.startsWith('$'));
254
- if (operatorKeys.length === 1) {
255
- const operator = operatorKeys[0];
256
- const operands = condition[operator];
257
-
258
- if (Array.isArray(operands) && operands.length === 2 && typeof operands[0] === 'string' && operands[0].startsWith('$')) {
259
- const fieldName = operands[0].substring(1); // Extrait 'amount' de '$amount'
260
- const expectedValue = operands[1];
261
- const actualValue = getNestedValue(formData, fieldName);
262
-
263
- return evaluateComparison(operator, actualValue, expectedValue, condition, checkRegex);
264
- }
265
- }
266
-
267
- // Cas spécial: Évaluation sans modèle (ex: pour les webhooks où la condition est déjà résolue)
268
- // Dans ce mode, la condition doit être un objet avec un seul opérateur.
269
- if (!model) {
270
- const keys = Object.keys(condition);
271
- if (keys.length !== 1 || !keys[0].startsWith('$')) {
272
- console.warn('[isConditionMet] Condition invalide pour une évaluation sans modèle. Attendu : { "$opérateur": [...] }. Reçu :', condition);
273
- return false; // Plus sûr que true pour éviter les faux positifs
274
- }
275
-
276
- const operator = keys[0];
277
- const operands = condition[operator];
278
-
279
- switch (operator) {
280
- // Opérateurs logiques (récursifs)
281
- case '$and':
282
- return Array.isArray(operands) && operands.every(sub => isConditionMet(null, sub, formData, allModels, user,checkRegex));
283
- case '$or':
284
- return Array.isArray(operands) && operands.some(sub => isConditionMet(null, sub, formData, allModels, user,checkRegex));
285
- case '$not':
286
- return !isConditionMet(null, operands, formData, allModels, user);
287
- case '$nor':
288
- return Array.isArray(operands) && !operands.some(sub => isConditionMet(null, sub, formData, allModels, user,checkRegex));
289
-
290
- // Opérateurs de comparaison (terminaux)
291
- case '$eq':
292
- return Array.isArray(operands) && operands[0] === operands[1];
293
- case '$ne':
294
- return Array.isArray(operands) && operands[0] !== operands[1];
295
- case '$in':
296
- return Array.isArray(operands) && Array.isArray(operands[1]) && operands[1].includes(operands[0]);
297
- case '$nin':
298
- return Array.isArray(operands) && Array.isArray(operands[1]) && !operands[1].includes(operands[0]);
299
- case '$gt':
300
- return Array.isArray(operands) && operands[0] > operands[1];
301
- case '$gte':
302
- return Array.isArray(operands) && operands[0] >= operands[1];
303
- case '$lt':
304
- return Array.isArray(operands) && operands[0] < operands[1];
305
- case '$lte':
306
- return Array.isArray(operands) && operands[0] <= operands[1];
307
-
308
- default:
309
- console.warn(`[isConditionMet] Opérateur non supporté '${operator}' pour une évaluation sans modèle.`);
310
- return false;
311
- }
312
- }
313
-
314
- // --- Logique existante pour l'évaluation AVEC modèle ---
315
-
316
- if (condition.$and && Array.isArray(condition.$and)) {
317
- if (condition.$and.length === 0) return true;
318
- return condition.$and.every(sub => isConditionMet(model, sub, formData, allModels, user,checkRegex));
319
- }
320
- if (condition.$or && Array.isArray(condition.$or)) {
321
- if (condition.$or.length === 0) return false;
322
- return condition.$or.some(sub => isConditionMet(model, sub, formData, allModels, user,checkRegex));
323
- }
324
- if (condition.$not) {
325
- return !isConditionMet(model, condition.$not, formData, allModels, user,checkRegex);
326
- }
327
- if (condition.$nor && Array.isArray(condition.$nor)) {
328
- if (condition.$nor.length === 0) return true;
329
- return !condition.$nor.some(sub => isConditionMet(model, sub, formData, allModels, user,checkRegex));
330
- }
331
-
332
- // Cas 3: Syntaxe d'agrégation {$eq: ['$field', value]}
333
- if (Object.keys(condition).length === 1) {
334
- const operator = Object.keys(condition)[0];
335
- if (operator.startsWith('$') && operator !== '$find' &&
336
- Array.isArray(condition[operator])) {
337
- return evaluateSingleCondition(model, condition, formData, allModels, user,checkRegex);
338
- }
339
- }
340
-
341
- return evaluateSingleCondition(model, condition, formData, allModels, user, checkRegex);
342
- };
343
-
1
+
2
+ let safeRegex = null; // Par défaut, aucune fonction de validation n'est définie.
3
+
4
+ /**
5
+ * Permet d'injecter une fonction de validation de regex (côté serveur).
6
+ * @param {function} validator - La fonction qui valide une regex, ex: la fonction du module 'safe-regex'.
7
+ */
8
+ export function setSafeRegex(validator) {
9
+ safeRegex = validator;
10
+ }
11
+
12
+ /**
13
+ * Évalue une comparaison entre une valeur cible et une valeur de condition.
14
+ * @param {string} operator - L'opérateur de comparaison (ex: '$eq', '$lt').
15
+ * @param {*} targetValue - La valeur actuelle du champ dans les données.
16
+ * @param {*} processedConditionValue - La valeur de la condition à comparer.
17
+ * @param {object} condition - La condition complète pour le contexte de logging.
18
+ * @returns {boolean} - Le résultat de la comparaison.
19
+ */
20
+ function evaluateComparison(operator, targetValue, processedConditionValue, condition) {
21
+ const logClientEvalWarning = (message, details) => {
22
+ console.warn(`[Client Eval] ${message}:`, details);
23
+ };
24
+
25
+ try {
26
+ switch (operator) {
27
+ case '$eq': return targetValue == processedConditionValue; // Utilise '==' pour une comparaison plus souple
28
+ case '$ne': return targetValue != processedConditionValue;
29
+ case '$gt': return targetValue > processedConditionValue;
30
+ case '$lt': return targetValue < processedConditionValue;
31
+ case '$gte': return targetValue >= processedConditionValue;
32
+ case '$lte': return targetValue <= processedConditionValue;
33
+ case '$regex':
34
+ if (typeof targetValue !== 'string' || !processedConditionValue || typeof processedConditionValue !== 'string') return false;
35
+ try {
36
+ if (safeRegex && !safeRegex(processedConditionValue)) return false;
37
+ const regex = new RegExp(processedConditionValue, 'i');
38
+ return regex.test(targetValue);
39
+ } catch (e) {
40
+ logClientEvalWarning(`Invalid regex pattern: ${processedConditionValue}`, condition);
41
+ return false;
42
+ }
43
+ case '$in': return Array.isArray(processedConditionValue) && processedConditionValue.includes(targetValue);
44
+ case '$nin': return !Array.isArray(processedConditionValue) || !processedConditionValue.includes(targetValue);
45
+ default: return true; // Permissif par défaut pour les opérateurs non gérés
46
+ }
47
+ } catch (evalError) {
48
+ logClientEvalWarning(`Error during condition evaluation: ${operator}, targetValue=${targetValue}, processedConditionValue=${processedConditionValue}`, condition);
49
+ return false;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Récupère une valeur imbriquée dans un objet en utilisant une chaîne de chemin.
55
+ * Gère les tableaux et les objets. Retourne undefined si le chemin n'est pas trouvé.
56
+ * Exemple: getNestedValue({ a: { b: [ { c: 1 } ] } }, 'a.b.0.c') -> 1
57
+ *
58
+ * @param {object} obj L'objet source.
59
+ * @param {string} path La chaîne de chemin (ex: 'user.address.city').
60
+ * @returns {*} La valeur trouvée ou undefined.
61
+ */
62
+ function getNestedValue(obj, path) {
63
+ // Vérifie si l'objet ou le chemin est invalide
64
+ if (!obj || typeof path !== 'string') {
65
+ return undefined;
66
+ }
67
+ // Sépare le chemin en clés individuelles (ex: 'a.b.0.c' -> ['a', 'b', '0', 'c'])
68
+ const keys = path.split('.');
69
+ let current = obj; // Commence à la racine de l'objet
70
+
71
+ // Parcourt chaque clé dans le chemin
72
+ for (const key of keys) {
73
+ // --- SÉCURITÉ : Ajout de la validation de la clé ---
74
+ // Empêche la pollution de prototype en refusant les clés dangereuses.
75
+ if (["__proto__", "constructor", "prototype"].includes(key)) {
76
+ return undefined;
77
+ }
78
+
79
+ // Si à un moment donné on atteint null ou undefined, le chemin est invalide
80
+ if (current === null || current === undefined) {
81
+ return undefined;
82
+ }
83
+ // Récupère la valeur pour la clé actuelle
84
+ const value = current[key];
85
+ // Si la valeur est undefined, le chemin est invalide
86
+ if (value === undefined) {
87
+ return undefined;
88
+ }
89
+ // Passe au niveau suivant de l'objet/tableau
90
+ current = value;
91
+ }
92
+ // Retourne la valeur finale trouvée
93
+ return current;
94
+ }
95
+ /**
96
+ * Evaluates a single condition against form data.
97
+ * @param {object} currentModelDef - The definition of the current model.
98
+ * @param {object} condition - The condition to evaluate.
99
+ * @param {object} formData - The form data.
100
+ * @param {object[]} allModels - An array of all model definitions.
101
+ * @param {object} user - The current user.
102
+ * @returns {boolean} - True if the condition is met, false otherwise.
103
+ */
104
+ const evaluateSingleCondition = (currentModelDef, condition, formData, allModels, user, checkRegex =true) => {
105
+ // Condition est directement un filtre MongoDB, donc on l'applique
106
+ // en utilisant les opérateurs et les valeurs qu'il contient.
107
+
108
+ if (!condition || typeof condition !== 'object') {
109
+ console.warn("[Client Eval] Condition is not an object:", condition);
110
+ return true; // Permissive default
111
+ }
112
+
113
+ // If the condition is a standard query operator like { amount: { $lt: 1000 } }
114
+ const fieldNameFromCondition = Object.keys(condition)[0];
115
+ const conditionValueObject = condition[fieldNameFromCondition];
116
+
117
+ if (typeof conditionValueObject === 'object' && conditionValueObject !== null && !Array.isArray(conditionValueObject)) {
118
+ const operator = Object.keys(conditionValueObject)[0];
119
+ if (operator.startsWith('$')) {
120
+ return evaluateComparison(operator, formData[fieldNameFromCondition], conditionValueObject[operator], condition, checkRegex);
121
+ }
122
+ }
123
+
124
+ // Si la condition est de la forme {field: value}, on la transforme en {$eq: value}
125
+ if (!Object.keys(condition)[0].startsWith('$') && typeof condition[Object.keys(condition)[0]] !== 'object') {
126
+ const fieldName = Object.keys(condition)[0];
127
+ const value = condition[fieldName];
128
+ return evaluateSingleCondition(currentModelDef, {[fieldName]: {$eq: value}}, formData, allModels, user);
129
+ }
130
+
131
+ // Gestion des opérateurs d'agrégation (commencent par $)
132
+ const operator = Object.keys(condition)[0];
133
+ if ((operator === '$eq' || operator === '$ne') && Array.isArray(condition[operator])) {
134
+ // Cas spécial pour {$op: ['$field', value]}
135
+ const [fieldPath, expectedValue] = condition[operator];
136
+ if (typeof fieldPath === 'string' && fieldPath.startsWith('$')) {
137
+ const fieldName = fieldPath.substring(1); // Enlève le $ devant
138
+ const actualValue = getNestedValue(formData, fieldName);
139
+ return evaluateComparison(operator, actualValue, expectedValue, condition, checkRegex);
140
+ }
141
+ }
142
+
143
+
144
+ // Si la condition contient des opérateurs logiques, on les gère ici
145
+ if (condition.$and || condition.$or || condition.$not || condition.$nor) {
146
+ console.warn("[Client Eval] Condition logique détectée dans evaluateSingleCondition, ce n'est pas attendu. Devrait être géré par isConditionMet.");
147
+ return true; // Permissive default
148
+ }
149
+
150
+ if (condition.$find) {
151
+ const fieldName = Object.keys(condition)[0];
152
+ const fieldValue = formData[fieldName];
153
+ const findCondition = condition.$find;
154
+
155
+ if (!Array.isArray(fieldValue)) return false;
156
+
157
+ return fieldValue.some(item => {
158
+ // Gestion spéciale pour la syntaxe $eq: ["$$this.field", value]
159
+ if (findCondition.$eq && Array.isArray(findCondition.$eq)) {
160
+ const [fieldPath, value] = findCondition.$eq;
161
+ if (fieldPath.startsWith("$$this.")) {
162
+ const fieldToCheck = fieldPath.replace("$$this.", "");
163
+ return item[fieldToCheck] == value;
164
+ }
165
+ }
166
+
167
+ // Sinon, évaluation normale
168
+ const tempData = { ...item };
169
+ return evaluateSingleCondition(currentModelDef, findCondition, tempData, allModels, user);
170
+ });
171
+ }
172
+
173
+ // Si la condition contient un opérateur $exists, on le gère ici
174
+ if (condition.$exists !== undefined) {
175
+ const fieldName = Object.keys(condition)[0]; // Récupérer le nom du champ
176
+ const shouldExist = condition.$exists; // Récupérer la valeur de $exists (true ou false)
177
+ const exists = Object.prototype.hasOwnProperty.call(formData, fieldName) && formData[fieldName] !== undefined && formData[fieldName] !== null;
178
+ return exists === shouldExist;
179
+ }
180
+
181
+ // Si la condition contient un opérateur $find, on le gère ici
182
+ if (condition.$find) {
183
+ // Récupérer le nom du champ
184
+ const fieldName = Object.keys(condition)[0];
185
+ const fieldValue = formData[fieldName];
186
+ try {
187
+ // Assuming evaluateSingleCondition handles $find
188
+ return evaluateSingleCondition(currentModelDef, condition.$find, formData, allModels, user);
189
+ } catch (error) {
190
+ console.error("Error evaluating $find condition:", condition, error);
191
+ return false;
192
+ }
193
+ }
194
+
195
+ // Récupérer le nom du champ et la condition
196
+ const fieldName = Object.keys(condition)[0];
197
+ const fieldValue = condition[fieldName];
198
+
199
+ // Récupérer la définition du champ
200
+ const fieldDef = currentModelDef?.fields.find(f => f.name === fieldName);
201
+
202
+ // Si la définition du champ n'est pas trouvée, on retourne true
203
+ if (!fieldDef) {
204
+ console.warn(`[Client Eval] Field definition not found for field: ${fieldName}`);
205
+ return true; // Permissive default
206
+ }
207
+
208
+ let targetValue = formData[fieldName];
209
+ let processedConditionValue = fieldValue;
210
+
211
+ // 1. Handle $exists (on the first field)
212
+ // 2. Convert condition value based on operator's expected input type
213
+ const fieldType = fieldDef?.type; // Type of the first field
214
+
215
+ try {
216
+ processedConditionValue = convertValueType(fieldValue, fieldType);
217
+ } catch (e) {
218
+ logClientEvalWarning(`Error converting value type: ${e.message}`, condition);
219
+ return false;
220
+ }
221
+
222
+ return evaluateComparison('$eq', targetValue, processedConditionValue, condition);
223
+
224
+ function logClientEvalWarning(message, details) {
225
+ console.warn(`[Client Eval] ${message}:`, details);
226
+ }
227
+
228
+ function convertValueType(value, inputType) {
229
+ switch (inputType) {
230
+ case 'number':
231
+ const numValue = parseFloat(value);
232
+ if (isNaN(numValue)) {
233
+ throw new Error(`Invalid number value: ${value}`);
234
+ }
235
+ return numValue;
236
+ case 'boolean':
237
+ return String(value).toLowerCase() === 'true';
238
+ case 'csv':
239
+ return String(value).split(',').map(item => item.trim()).filter(Boolean);
240
+ case 'text':
241
+ default:
242
+ return String(value);
243
+ }
244
+ }
245
+
246
+ };
247
+
248
+ export const isConditionMet = (model, cond, formData, allModels, user,checkRegex=true) => {
249
+ const condition = cond;
250
+
251
+ if (!condition) return true;
252
+
253
+ if (typeof condition !== 'object' || condition === null) {
254
+ return true;
255
+ }
256
+
257
+ // --- NOUVELLE LOGIQUE ---
258
+ // Gère les conditions de type expression d'agrégation comme { "$lt": ["$amount", 1000] }
259
+ const operatorKeys = Object.keys(condition).filter(k => k.startsWith('$'));
260
+ if (operatorKeys.length === 1) {
261
+ const operator = operatorKeys[0];
262
+ const operands = condition[operator];
263
+
264
+ if (Array.isArray(operands) && operands.length === 2 && typeof operands[0] === 'string' && operands[0].startsWith('$')) {
265
+ const fieldName = operands[0].substring(1); // Extrait 'amount' de '$amount'
266
+ const expectedValue = operands[1];
267
+ const actualValue = getNestedValue(formData, fieldName);
268
+
269
+ return evaluateComparison(operator, actualValue, expectedValue, condition, checkRegex);
270
+ }
271
+ }
272
+
273
+ // Cas spécial: Évaluation sans modèle (ex: pour les webhooks où la condition est déjà résolue)
274
+ // Dans ce mode, la condition doit être un objet avec un seul opérateur.
275
+ if (!model) {
276
+ const keys = Object.keys(condition);
277
+ if (keys.length !== 1 || !keys[0].startsWith('$')) {
278
+ console.warn('[isConditionMet] Condition invalide pour une évaluation sans modèle. Attendu : { "$opérateur": [...] }. Reçu :', condition);
279
+ return false; // Plus sûr que true pour éviter les faux positifs
280
+ }
281
+
282
+ const operator = keys[0];
283
+ const operands = condition[operator];
284
+
285
+ switch (operator) {
286
+ // Opérateurs logiques (récursifs)
287
+ case '$and':
288
+ return Array.isArray(operands) && operands.every(sub => isConditionMet(null, sub, formData, allModels, user,checkRegex));
289
+ case '$or':
290
+ return Array.isArray(operands) && operands.some(sub => isConditionMet(null, sub, formData, allModels, user,checkRegex));
291
+ case '$not':
292
+ return !isConditionMet(null, operands, formData, allModels, user);
293
+ case '$nor':
294
+ return Array.isArray(operands) && !operands.some(sub => isConditionMet(null, sub, formData, allModels, user,checkRegex));
295
+
296
+ // Opérateurs de comparaison (terminaux)
297
+ case '$eq':
298
+ return Array.isArray(operands) && operands[0] === operands[1];
299
+ case '$ne':
300
+ return Array.isArray(operands) && operands[0] !== operands[1];
301
+ case '$in':
302
+ return Array.isArray(operands) && Array.isArray(operands[1]) && operands[1].includes(operands[0]);
303
+ case '$nin':
304
+ return Array.isArray(operands) && Array.isArray(operands[1]) && !operands[1].includes(operands[0]);
305
+ case '$gt':
306
+ return Array.isArray(operands) && operands[0] > operands[1];
307
+ case '$gte':
308
+ return Array.isArray(operands) && operands[0] >= operands[1];
309
+ case '$lt':
310
+ return Array.isArray(operands) && operands[0] < operands[1];
311
+ case '$lte':
312
+ return Array.isArray(operands) && operands[0] <= operands[1];
313
+
314
+ default:
315
+ console.warn(`[isConditionMet] Opérateur non supporté '${operator}' pour une évaluation sans modèle.`);
316
+ return false;
317
+ }
318
+ }
319
+
320
+ // --- Logique existante pour l'évaluation AVEC modèle ---
321
+
322
+ if (condition.$and && Array.isArray(condition.$and)) {
323
+ if (condition.$and.length === 0) return true;
324
+ return condition.$and.every(sub => isConditionMet(model, sub, formData, allModels, user,checkRegex));
325
+ }
326
+ if (condition.$or && Array.isArray(condition.$or)) {
327
+ if (condition.$or.length === 0) return false;
328
+ return condition.$or.some(sub => isConditionMet(model, sub, formData, allModels, user,checkRegex));
329
+ }
330
+ if (condition.$not) {
331
+ return !isConditionMet(model, condition.$not, formData, allModels, user,checkRegex);
332
+ }
333
+ if (condition.$nor && Array.isArray(condition.$nor)) {
334
+ if (condition.$nor.length === 0) return true;
335
+ return !condition.$nor.some(sub => isConditionMet(model, sub, formData, allModels, user,checkRegex));
336
+ }
337
+
338
+ // Cas 3: Syntaxe d'agrégation {$eq: ['$field', value]}
339
+ if (Object.keys(condition).length === 1) {
340
+ const operator = Object.keys(condition)[0];
341
+ if (operator.startsWith('$') && operator !== '$find' &&
342
+ Array.isArray(condition[operator])) {
343
+ return evaluateSingleCondition(model, condition, formData, allModels, user,checkRegex);
344
+ }
345
+ }
346
+
347
+ return evaluateSingleCondition(model, condition, formData, allModels, user, checkRegex);
348
+ };