var.ts 1.9 KB

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