|
| 1 | +import { FakerError } from '../../errors/faker-error'; |
| 2 | +import type { Faker } from '../../faker'; |
| 3 | + |
| 4 | +const REGEX_DOT_OR_BRACKET = /\.|\(/; |
| 5 | + |
| 6 | +/** |
| 7 | + * Resolves the given expression and returns its result. This method should only be used when using serialized expressions. |
| 8 | + * |
| 9 | + * This method is useful if you have to build a random string from a static, non-executable source |
| 10 | + * (e.g. string coming from a developer, stored in a database or a file). |
| 11 | + * |
| 12 | + * It tries to resolve the expression on the given/default entrypoints: |
| 13 | + * |
| 14 | + * ```js |
| 15 | + * const firstName = fakeEval('person.firstName', faker); |
| 16 | + * const firstName2 = fakeEval('person.first_name', faker); |
| 17 | + * ``` |
| 18 | + * |
| 19 | + * Is equivalent to: |
| 20 | + * |
| 21 | + * ```js |
| 22 | + * const firstName = faker.person.firstName(); |
| 23 | + * const firstName2 = faker.helpers.arrayElement(faker.rawDefinitions.person.first_name); |
| 24 | + * ``` |
| 25 | + * |
| 26 | + * You can provide parameters as well. At first, they will be parsed as json, |
| 27 | + * and if that isn't possible, it will fall back to string: |
| 28 | + * |
| 29 | + * ```js |
| 30 | + * const message = fakeEval('phone.number(+!# !## #### #####!)', faker); |
| 31 | + * ``` |
| 32 | + * |
| 33 | + * It is also possible to use multiple parameters (comma separated). |
| 34 | + * |
| 35 | + * ```js |
| 36 | + * const pin = fakeEval('string.numeric(4, {"allowLeadingZeros": true})', faker); |
| 37 | + * ``` |
| 38 | + * |
| 39 | + * This method can resolve expressions with varying depths (dot separated parts). |
| 40 | + * |
| 41 | + * ```ts |
| 42 | + * const airlineModule = fakeEval('airline', faker); // AirlineModule |
| 43 | + * const airlineObject = fakeEval('airline.airline', faker); // { name: 'Etihad Airways', iataCode: 'EY' } |
| 44 | + * const airlineCode = fakeEval('airline.airline.iataCode', faker); // 'EY' |
| 45 | + * const airlineName = fakeEval('airline.airline().name', faker); // 'Etihad Airways' |
| 46 | + * const airlineMethodName = fakeEval('airline.airline.name', faker); // 'bound airline' |
| 47 | + * ``` |
| 48 | + * |
| 49 | + * It is NOT possible to access any values not passed as entrypoints. |
| 50 | + * |
| 51 | + * This method will never return arrays, as it will pick a random element from them instead. |
| 52 | + * |
| 53 | + * @param expression The expression to evaluate on the entrypoints. |
| 54 | + * @param faker The faker instance to resolve array elements. |
| 55 | + * @param entrypoints The entrypoints to use when evaluating the expression. |
| 56 | + * |
| 57 | + * @see faker.helpers.fake() If you wish to have a string with multiple expressions. |
| 58 | + * |
| 59 | + * @example |
| 60 | + * fakeEval('person.lastName', faker) // 'Barrows' |
| 61 | + * fakeEval('helpers.arrayElement(["heads", "tails"])', faker) // 'tails' |
| 62 | + * fakeEval('number.int(9999)', faker) // 4834 |
| 63 | + * |
| 64 | + * @since 8.4.0 |
| 65 | + */ |
| 66 | +export function fakeEval( |
| 67 | + expression: string, |
| 68 | + faker: Faker, |
| 69 | + entrypoints: ReadonlyArray<unknown> = [faker, faker.rawDefinitions] |
| 70 | +): unknown { |
| 71 | + if (expression.length === 0) { |
| 72 | + throw new FakerError('Eval expression cannot be empty.'); |
| 73 | + } |
| 74 | + |
| 75 | + if (entrypoints.length === 0) { |
| 76 | + throw new FakerError('Eval entrypoints cannot be empty.'); |
| 77 | + } |
| 78 | + |
| 79 | + let current = entrypoints; |
| 80 | + let remaining = expression; |
| 81 | + do { |
| 82 | + let index: number; |
| 83 | + if (remaining.startsWith('(')) { |
| 84 | + [index, current] = evalProcessFunction(remaining, current); |
| 85 | + } else { |
| 86 | + [index, current] = evalProcessExpression(remaining, current); |
| 87 | + } |
| 88 | + |
| 89 | + remaining = remaining.substring(index); |
| 90 | + |
| 91 | + // Remove garbage and resolve array values |
| 92 | + current = current |
| 93 | + .filter((value) => value != null) |
| 94 | + .map((value): unknown => |
| 95 | + Array.isArray(value) ? faker.helpers.arrayElement(value) : value |
| 96 | + ); |
| 97 | + } while (remaining.length > 0 && current.length > 0); |
| 98 | + |
| 99 | + if (current.length === 0) { |
| 100 | + throw new FakerError(`Cannot resolve expression '${expression}'`); |
| 101 | + } |
| 102 | + |
| 103 | + const value = current[0]; |
| 104 | + return typeof value === 'function' ? value() : value; |
| 105 | +} |
| 106 | + |
| 107 | +/** |
| 108 | + * Evaluates a function call and returns the new read index and the mapped results. |
| 109 | + * |
| 110 | + * @param input The input string to parse. |
| 111 | + * @param entrypoints The entrypoints to attempt the call on. |
| 112 | + */ |
| 113 | +function evalProcessFunction( |
| 114 | + input: string, |
| 115 | + entrypoints: ReadonlyArray<unknown> |
| 116 | +): [continueIndex: number, mapped: unknown[]] { |
| 117 | + const [index, params] = findParams(input); |
| 118 | + const nextChar = input[index + 1]; |
| 119 | + switch (nextChar) { |
| 120 | + case '.': |
| 121 | + case '(': |
| 122 | + case undefined: |
| 123 | + break; // valid |
| 124 | + default: |
| 125 | + throw new FakerError( |
| 126 | + `Expected dot ('.'), open parenthesis ('('), or nothing after function call but got '${nextChar}'` |
| 127 | + ); |
| 128 | + } |
| 129 | + |
| 130 | + return [ |
| 131 | + index + (nextChar === '.' ? 2 : 1), // one for the closing bracket, one for the dot |
| 132 | + entrypoints.map((entrypoint): unknown => |
| 133 | + // TODO @ST-DDT 2023-12-11: Replace in v9 |
| 134 | + // typeof entrypoint === 'function' ? entrypoint(...params) : undefined |
| 135 | + typeof entrypoint === 'function' ? entrypoint(...params) : entrypoint |
| 136 | + ), |
| 137 | + ]; |
| 138 | +} |
| 139 | + |
| 140 | +/** |
| 141 | + * Tries to find the parameters of a function call. |
| 142 | + * |
| 143 | + * @param input The input string to parse. |
| 144 | + */ |
| 145 | +function findParams(input: string): [continueIndex: number, params: unknown[]] { |
| 146 | + let index = input.indexOf(')', 1); |
| 147 | + if (index === -1) { |
| 148 | + throw new FakerError(`Missing closing parenthesis in '${input}'`); |
| 149 | + } |
| 150 | + |
| 151 | + while (index !== -1) { |
| 152 | + const params = input.substring(1, index); |
| 153 | + try { |
| 154 | + // assuming that the params are valid JSON |
| 155 | + return [index, JSON.parse(`[${params}]`) as unknown[]]; |
| 156 | + } catch { |
| 157 | + if (!params.includes("'") && !params.includes('"')) { |
| 158 | + try { |
| 159 | + // assuming that the params are a single unquoted string |
| 160 | + return [index, JSON.parse(`["${params}"]`) as unknown[]]; |
| 161 | + } catch { |
| 162 | + // try again with the next index |
| 163 | + } |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + index = input.indexOf(')', index + 1); |
| 168 | + } |
| 169 | + |
| 170 | + index = input.lastIndexOf(')'); |
| 171 | + const params = input.substring(1, index); |
| 172 | + return [index, [params]]; |
| 173 | +} |
| 174 | + |
| 175 | +/** |
| 176 | + * Processes one expression part and returns the new read index and the mapped results. |
| 177 | + * |
| 178 | + * @param input The input string to parse. |
| 179 | + * @param entrypoints The entrypoints to resolve on. |
| 180 | + */ |
| 181 | +function evalProcessExpression( |
| 182 | + input: string, |
| 183 | + entrypoints: ReadonlyArray<unknown> |
| 184 | +): [continueIndex: number, mapped: unknown[]] { |
| 185 | + const result = REGEX_DOT_OR_BRACKET.exec(input); |
| 186 | + const dotMatch = (result?.[0] ?? '') === '.'; |
| 187 | + const index = result?.index ?? input.length; |
| 188 | + const key = input.substring(0, index); |
| 189 | + if (key.length === 0) { |
| 190 | + throw new FakerError(`Expression parts cannot be empty in '${input}'`); |
| 191 | + } |
| 192 | + |
| 193 | + const next = input[index + 1]; |
| 194 | + if (dotMatch && (next == null || next === '.' || next === '(')) { |
| 195 | + throw new FakerError(`Found dot without property name in '${input}'`); |
| 196 | + } |
| 197 | + |
| 198 | + return [ |
| 199 | + index + (dotMatch ? 1 : 0), |
| 200 | + entrypoints.map((entrypoint) => resolveProperty(entrypoint, key)), |
| 201 | + ]; |
| 202 | +} |
| 203 | + |
| 204 | +/** |
| 205 | + * Resolves the given property on the given entrypoint. |
| 206 | + * |
| 207 | + * @param entrypoint The entrypoint to resolve the property on. |
| 208 | + * @param key The property name to resolve. |
| 209 | + */ |
| 210 | +function resolveProperty(entrypoint: unknown, key: string): unknown { |
| 211 | + switch (typeof entrypoint) { |
| 212 | + case 'function': { |
| 213 | + try { |
| 214 | + entrypoint = entrypoint(); |
| 215 | + } catch { |
| 216 | + return undefined; |
| 217 | + } |
| 218 | + |
| 219 | + return entrypoint?.[key as keyof typeof entrypoint]; |
| 220 | + } |
| 221 | + |
| 222 | + case 'object': { |
| 223 | + return entrypoint?.[key as keyof typeof entrypoint]; |
| 224 | + } |
| 225 | + |
| 226 | + default: |
| 227 | + return undefined; |
| 228 | + } |
| 229 | +} |
0 commit comments