var.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { MAX_VAR_KEY_LENGHT, VAR_ITEM_TEMPLATE, getMaxVarNameLength } from '@/config'
  2. import { CONTEXT_PLACEHOLDER_TEXT, HISTORY_PLACEHOLDER_TEXT, PRE_PROMPT_PLACEHOLDER_TEXT, QUERY_PLACEHOLDER_TEXT } from '@/app/components/base/prompt-editor/constants'
  3. const otherAllowedRegex = /^[a-zA-Z0-9_]+$/
  4. export const getNewVar = (key: string) => {
  5. return {
  6. ...VAR_ITEM_TEMPLATE,
  7. key,
  8. name: key.slice(0, getMaxVarNameLength(key)),
  9. }
  10. }
  11. const checkKey = (key: string, canBeEmpty?: boolean) => {
  12. if (key.length === 0 && !canBeEmpty)
  13. return 'canNoBeEmpty'
  14. if (canBeEmpty && key === '')
  15. return true
  16. if (key.length > MAX_VAR_KEY_LENGHT)
  17. return 'tooLong'
  18. if (otherAllowedRegex.test(key)) {
  19. if (/[0-9]/.test(key[0]))
  20. return 'notStartWithNumber'
  21. return true
  22. }
  23. return 'notValid'
  24. }
  25. export const checkKeys = (keys: string[], canBeEmpty?: boolean) => {
  26. let isValid = true
  27. let errorKey = ''
  28. let errorMessageKey = ''
  29. keys.forEach((key) => {
  30. if (!isValid)
  31. return
  32. const res = checkKey(key, canBeEmpty)
  33. if (res !== true) {
  34. isValid = false
  35. errorKey = key
  36. errorMessageKey = res
  37. }
  38. })
  39. return { isValid, errorKey, errorMessageKey }
  40. }
  41. const varRegex = /\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g
  42. export const getVars = (value: string) => {
  43. const keys = value.match(varRegex)?.filter((item) => {
  44. return ![CONTEXT_PLACEHOLDER_TEXT, HISTORY_PLACEHOLDER_TEXT, QUERY_PLACEHOLDER_TEXT, PRE_PROMPT_PLACEHOLDER_TEXT].includes(item)
  45. }).map((item) => {
  46. return item.replace('{{', '').replace('}}', '')
  47. }).filter(key => key.length <= MAX_VAR_KEY_LENGHT) || []
  48. const keyObj: Record<string, boolean> = {}
  49. // remove duplicate keys
  50. const res: string[] = []
  51. keys.forEach((key) => {
  52. if (keyObj[key])
  53. return
  54. keyObj[key] = true
  55. res.push(key)
  56. })
  57. return res
  58. }