var.ts 2.1 KB

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