string.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import { setResponseValueAndErrors } from "../errorMessages.mjs";
  2. let emojiRegex;
  3. /**
  4. * Generated from the regular expressions found here as of 2024-05-22:
  5. * https://github.com/colinhacks/zod/blob/master/src/types.ts.
  6. *
  7. * Expressions with /i flag have been changed accordingly.
  8. */
  9. export const zodPatterns = {
  10. /**
  11. * `c` was changed to `[cC]` to replicate /i flag
  12. */
  13. cuid: /^[cC][^\s-]{8,}$/,
  14. cuid2: /^[0-9a-z]+$/,
  15. ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
  16. /**
  17. * `a-z` was added to replicate /i flag
  18. */
  19. email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
  20. /**
  21. * Constructed a valid Unicode RegExp
  22. *
  23. * Lazily instantiate since this type of regex isn't supported
  24. * in all envs (e.g. React Native).
  25. *
  26. * See:
  27. * https://github.com/colinhacks/zod/issues/2433
  28. * Fix in Zod:
  29. * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
  30. */
  31. emoji: () => {
  32. if (emojiRegex === undefined) {
  33. emojiRegex = RegExp('^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$', 'u');
  34. }
  35. return emojiRegex;
  36. },
  37. /**
  38. * Unused
  39. */
  40. uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
  41. /**
  42. * Unused
  43. */
  44. ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
  45. /**
  46. * Unused
  47. */
  48. ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
  49. base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
  50. nanoid: /^[a-zA-Z0-9_-]{21}$/,
  51. };
  52. export function parseStringDef(def, refs) {
  53. const res = {
  54. type: 'string',
  55. };
  56. function processPattern(value) {
  57. return refs.patternStrategy === 'escape' ? escapeNonAlphaNumeric(value) : value;
  58. }
  59. if (def.checks) {
  60. for (const check of def.checks) {
  61. switch (check.kind) {
  62. case 'min':
  63. setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
  64. break;
  65. case 'max':
  66. setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
  67. break;
  68. case 'email':
  69. switch (refs.emailStrategy) {
  70. case 'format:email':
  71. addFormat(res, 'email', check.message, refs);
  72. break;
  73. case 'format:idn-email':
  74. addFormat(res, 'idn-email', check.message, refs);
  75. break;
  76. case 'pattern:zod':
  77. addPattern(res, zodPatterns.email, check.message, refs);
  78. break;
  79. }
  80. break;
  81. case 'url':
  82. addFormat(res, 'uri', check.message, refs);
  83. break;
  84. case 'uuid':
  85. addFormat(res, 'uuid', check.message, refs);
  86. break;
  87. case 'regex':
  88. addPattern(res, check.regex, check.message, refs);
  89. break;
  90. case 'cuid':
  91. addPattern(res, zodPatterns.cuid, check.message, refs);
  92. break;
  93. case 'cuid2':
  94. addPattern(res, zodPatterns.cuid2, check.message, refs);
  95. break;
  96. case 'startsWith':
  97. addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs);
  98. break;
  99. case 'endsWith':
  100. addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs);
  101. break;
  102. case 'datetime':
  103. addFormat(res, 'date-time', check.message, refs);
  104. break;
  105. case 'date':
  106. addFormat(res, 'date', check.message, refs);
  107. break;
  108. case 'time':
  109. addFormat(res, 'time', check.message, refs);
  110. break;
  111. case 'duration':
  112. addFormat(res, 'duration', check.message, refs);
  113. break;
  114. case 'length':
  115. setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
  116. setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
  117. break;
  118. case 'includes': {
  119. addPattern(res, RegExp(processPattern(check.value)), check.message, refs);
  120. break;
  121. }
  122. case 'ip': {
  123. if (check.version !== 'v6') {
  124. addFormat(res, 'ipv4', check.message, refs);
  125. }
  126. if (check.version !== 'v4') {
  127. addFormat(res, 'ipv6', check.message, refs);
  128. }
  129. break;
  130. }
  131. case 'emoji':
  132. addPattern(res, zodPatterns.emoji, check.message, refs);
  133. break;
  134. case 'ulid': {
  135. addPattern(res, zodPatterns.ulid, check.message, refs);
  136. break;
  137. }
  138. case 'base64': {
  139. switch (refs.base64Strategy) {
  140. case 'format:binary': {
  141. addFormat(res, 'binary', check.message, refs);
  142. break;
  143. }
  144. case 'contentEncoding:base64': {
  145. setResponseValueAndErrors(res, 'contentEncoding', 'base64', check.message, refs);
  146. break;
  147. }
  148. case 'pattern:zod': {
  149. addPattern(res, zodPatterns.base64, check.message, refs);
  150. break;
  151. }
  152. }
  153. break;
  154. }
  155. case 'nanoid': {
  156. addPattern(res, zodPatterns.nanoid, check.message, refs);
  157. }
  158. case 'toLowerCase':
  159. case 'toUpperCase':
  160. case 'trim':
  161. break;
  162. default:
  163. ((_) => { })(check);
  164. }
  165. }
  166. }
  167. return res;
  168. }
  169. const escapeNonAlphaNumeric = (value) => Array.from(value)
  170. .map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\${c}`))
  171. .join('');
  172. const addFormat = (schema, value, message, refs) => {
  173. if (schema.format || schema.anyOf?.some((x) => x.format)) {
  174. if (!schema.anyOf) {
  175. schema.anyOf = [];
  176. }
  177. if (schema.format) {
  178. schema.anyOf.push({
  179. format: schema.format,
  180. ...(schema.errorMessage &&
  181. refs.errorMessages && {
  182. errorMessage: { format: schema.errorMessage.format },
  183. }),
  184. });
  185. delete schema.format;
  186. if (schema.errorMessage) {
  187. delete schema.errorMessage.format;
  188. if (Object.keys(schema.errorMessage).length === 0) {
  189. delete schema.errorMessage;
  190. }
  191. }
  192. }
  193. schema.anyOf.push({
  194. format: value,
  195. ...(message && refs.errorMessages && { errorMessage: { format: message } }),
  196. });
  197. }
  198. else {
  199. setResponseValueAndErrors(schema, 'format', value, message, refs);
  200. }
  201. };
  202. const addPattern = (schema, regex, message, refs) => {
  203. if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
  204. if (!schema.allOf) {
  205. schema.allOf = [];
  206. }
  207. if (schema.pattern) {
  208. schema.allOf.push({
  209. pattern: schema.pattern,
  210. ...(schema.errorMessage &&
  211. refs.errorMessages && {
  212. errorMessage: { pattern: schema.errorMessage.pattern },
  213. }),
  214. });
  215. delete schema.pattern;
  216. if (schema.errorMessage) {
  217. delete schema.errorMessage.pattern;
  218. if (Object.keys(schema.errorMessage).length === 0) {
  219. delete schema.errorMessage;
  220. }
  221. }
  222. }
  223. schema.allOf.push({
  224. pattern: processRegExp(regex, refs),
  225. ...(message && refs.errorMessages && { errorMessage: { pattern: message } }),
  226. });
  227. }
  228. else {
  229. setResponseValueAndErrors(schema, 'pattern', processRegExp(regex, refs), message, refs);
  230. }
  231. };
  232. // Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true
  233. const processRegExp = (regexOrFunction, refs) => {
  234. const regex = typeof regexOrFunction === 'function' ? regexOrFunction() : regexOrFunction;
  235. if (!refs.applyRegexFlags || !regex.flags)
  236. return regex.source;
  237. // Currently handled flags
  238. const flags = {
  239. i: regex.flags.includes('i'),
  240. m: regex.flags.includes('m'),
  241. s: regex.flags.includes('s'), // `.` matches newlines
  242. };
  243. // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!
  244. const source = flags.i ? regex.source.toLowerCase() : regex.source;
  245. let pattern = '';
  246. let isEscaped = false;
  247. let inCharGroup = false;
  248. let inCharRange = false;
  249. for (let i = 0; i < source.length; i++) {
  250. if (isEscaped) {
  251. pattern += source[i];
  252. isEscaped = false;
  253. continue;
  254. }
  255. if (flags.i) {
  256. if (inCharGroup) {
  257. if (source[i].match(/[a-z]/)) {
  258. if (inCharRange) {
  259. pattern += source[i];
  260. pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
  261. inCharRange = false;
  262. }
  263. else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) {
  264. pattern += source[i];
  265. inCharRange = true;
  266. }
  267. else {
  268. pattern += `${source[i]}${source[i].toUpperCase()}`;
  269. }
  270. continue;
  271. }
  272. }
  273. else if (source[i].match(/[a-z]/)) {
  274. pattern += `[${source[i]}${source[i].toUpperCase()}]`;
  275. continue;
  276. }
  277. }
  278. if (flags.m) {
  279. if (source[i] === '^') {
  280. pattern += `(^|(?<=[\r\n]))`;
  281. continue;
  282. }
  283. else if (source[i] === '$') {
  284. pattern += `($|(?=[\r\n]))`;
  285. continue;
  286. }
  287. }
  288. if (flags.s && source[i] === '.') {
  289. pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`;
  290. continue;
  291. }
  292. pattern += source[i];
  293. if (source[i] === '\\') {
  294. isEscaped = true;
  295. }
  296. else if (inCharGroup && source[i] === ']') {
  297. inCharGroup = false;
  298. }
  299. else if (!inCharGroup && source[i] === '[') {
  300. inCharGroup = true;
  301. }
  302. }
  303. try {
  304. const regexTest = new RegExp(pattern);
  305. }
  306. catch {
  307. console.warn(`Could not convert regex pattern at ${refs.currentPath.join('/')} to a flag-independent form! Falling back to the flag-ignorant source`);
  308. return regex.source;
  309. }
  310. return pattern;
  311. };
  312. //# sourceMappingURL=string.mjs.map