Validate return
This commit is contained in:
parent
fba5663e66
commit
1a4abb7630
|
@ -1,7 +1,6 @@
|
||||||
import { Parser } from "acorn"
|
import { Parser } from "acorn"
|
||||||
import { simple as walk } from "acorn-walk"
|
import * as walk from "acorn-walk"
|
||||||
|
|
||||||
import { iifeWrapper } from "@budibase/string-templates"
|
|
||||||
import type { Diagnostic } from "@codemirror/lint"
|
import type { Diagnostic } from "@codemirror/lint"
|
||||||
import { CodeValidator } from "@/types"
|
import { CodeValidator } from "@/types"
|
||||||
|
|
||||||
|
@ -12,13 +11,13 @@ export function validateJsTemplate(
|
||||||
const diagnostics: Diagnostic[] = []
|
const diagnostics: Diagnostic[] = []
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// const helperUsages = new RegExp(/\bhelpers\.(\w)+\b/).exec(code)
|
const ast = Parser.parse(code, {
|
||||||
const ast = Parser.parse(iifeWrapper(code), {
|
|
||||||
ecmaVersion: "latest",
|
ecmaVersion: "latest",
|
||||||
locations: true,
|
locations: true,
|
||||||
|
allowReturnOutsideFunction: true,
|
||||||
})
|
})
|
||||||
|
|
||||||
const lineOffsets: number[] = [0]
|
const lineOffsets: number[] = []
|
||||||
let offset = 0
|
let offset = 0
|
||||||
for (const line of code.split("\n")) {
|
for (const line of code.split("\n")) {
|
||||||
lineOffsets.push(offset)
|
lineOffsets.push(offset)
|
||||||
|
@ -26,9 +25,18 @@ export function validateJsTemplate(
|
||||||
}
|
}
|
||||||
|
|
||||||
let hasReturnStatement = false
|
let hasReturnStatement = false
|
||||||
walk(ast, {
|
walk.ancestor(ast, {
|
||||||
ReturnStatement(node) {
|
ReturnStatement(node, _state, ancestors) {
|
||||||
hasReturnStatement = !!node.argument
|
if (
|
||||||
|
// it returns a value
|
||||||
|
node.argument &&
|
||||||
|
// and it is top level
|
||||||
|
ancestors.length === 2 &&
|
||||||
|
ancestors[0].type === "Program" &&
|
||||||
|
ancestors[1].type === "ReturnStatement"
|
||||||
|
) {
|
||||||
|
hasReturnStatement = true
|
||||||
|
}
|
||||||
},
|
},
|
||||||
CallExpression(node) {
|
CallExpression(node) {
|
||||||
const callee: any = node.callee
|
const callee: any = node.callee
|
||||||
|
|
|
@ -49,6 +49,24 @@ describe("js validator", () => {
|
||||||
])
|
])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it("checks that returns are at top level", () => {
|
||||||
|
const text = `
|
||||||
|
function call(){
|
||||||
|
return 1
|
||||||
|
}`
|
||||||
|
const validators = {}
|
||||||
|
|
||||||
|
const result = validateJsTemplate(text, validators)
|
||||||
|
expect(result).toEqual([
|
||||||
|
{
|
||||||
|
from: 0,
|
||||||
|
message: "Your code must return a value.",
|
||||||
|
severity: "error",
|
||||||
|
to: text.length,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
describe("helpers", () => {
|
describe("helpers", () => {
|
||||||
const validators: CodeValidator = {
|
const validators: CodeValidator = {
|
||||||
helperFunction: {
|
helperFunction: {
|
||||||
|
|
Loading…
Reference in New Issue