tern.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import tern from "tern"
  2. import { registerTernLinter } from "./ternlint"
  3. import ECMA_DEF from "~/helpers/terndoc/ecma.json"
  4. import PW_PRE_DEF from "~/helpers/terndoc/pw-pre.json"
  5. import PW_TEST_DEF from "~/helpers/terndoc/pw-test.json"
  6. import PW_EXTRAS_DEF from "~/helpers/terndoc/pw-extras.json"
  7. const server = new tern.Server({
  8. defs: [ECMA_DEF, PW_EXTRAS_DEF],
  9. plugins: {
  10. lint: {
  11. rules: [],
  12. },
  13. },
  14. })
  15. registerTernLinter()
  16. function performLinting(code) {
  17. return new Promise((resolve, reject) => {
  18. server.request(
  19. {
  20. query: {
  21. type: "lint",
  22. file: "doc",
  23. lineCharPositions: true,
  24. },
  25. files: [
  26. {
  27. type: "full",
  28. name: "doc",
  29. text: code,
  30. },
  31. ],
  32. },
  33. (err, res) => {
  34. if (!err) resolve(res.messages)
  35. else reject(err)
  36. }
  37. )
  38. })
  39. }
  40. export function performPreRequestLinting(code) {
  41. server.deleteDefs("pw-test")
  42. server.deleteDefs("pw-pre")
  43. server.addDefs(PW_PRE_DEF)
  44. return performLinting(code)
  45. }
  46. export function performTestLinting(code) {
  47. server.deleteDefs("pw-test")
  48. server.deleteDefs("pw-pre")
  49. server.addDefs(PW_TEST_DEF)
  50. return performLinting(code)
  51. }
  52. function postProcessCompletionResult(res) {
  53. if (res.completions) {
  54. const index = res.completions.findIndex((el) => el.name === "pw")
  55. if (index !== -1) {
  56. const result = res.completions[index]
  57. res.completions.splice(index, 1)
  58. res.completions.splice(0, 0, result)
  59. }
  60. }
  61. return res
  62. }
  63. function performCompletion(code, row, col) {
  64. return new Promise((resolve, reject) => {
  65. server.request(
  66. {
  67. query: {
  68. type: "completions",
  69. file: "doc",
  70. end: {
  71. line: row,
  72. ch: col,
  73. },
  74. guess: false,
  75. types: true,
  76. includeKeywords: true,
  77. inLiteral: false,
  78. },
  79. files: [
  80. {
  81. type: "full",
  82. name: "doc",
  83. text: code,
  84. },
  85. ],
  86. },
  87. (err, res) => {
  88. if (err) reject(err)
  89. else resolve(postProcessCompletionResult(res))
  90. }
  91. )
  92. })
  93. }
  94. export function getPreRequestScriptCompletions(code, row, col) {
  95. server.deleteDefs("pw-test")
  96. server.deleteDefs("pw-pre")
  97. server.addDefs(PW_PRE_DEF)
  98. return performCompletion(code, row, col)
  99. }
  100. export function getTestScriptCompletions(code, row, col) {
  101. server.deleteDefs("pw-test")
  102. server.deleteDefs("pw-pre")
  103. server.addDefs(PW_TEST_DEF)
  104. return performCompletion(code, row, col)
  105. }