Skip to content

Commit

Permalink
fix: don't fail on possible invalid script (microsoft#1156)
Browse files Browse the repository at this point in the history
* Don't fail on possible invalid script

* fix

* Fix extension
  • Loading branch information
kblok authored Feb 24, 2021
1 parent e59ff60 commit f01af99
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
8 changes: 8 additions & 0 deletions src/PlaywrightSharp.Tests/PageEvaluateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,14 @@ public async Task ShouldRoundtripDate()
Assert.Equal(date, result);
}

[Fact(Skip = "The driver doesn't support this yet")]
public async Task ShouldTreatEcma2020AsFunctions()
=> Assert.Equal("dario", await Page.EvaluateAsync<string>(
@"() => {
const person = { name: 'dario' };
return person?.name;
}"));

[PlaywrightTest("page-evaluate.spec.ts", "should roundtrip regex")]
[Fact(Skip = "Regex is not native as in javascript")]
public void ShouldRoundtripRegex()
Expand Down
21 changes: 9 additions & 12 deletions src/PlaywrightSharp/Helpers/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -651,8 +651,10 @@ public static Dictionary<string, string> ParseQueryString(this string query)
/// Determine if the script is a javascript function and not an expression.
/// </summary>
/// <param name="script">Script to evaluate.</param>
/// <param name="retry">Whether it should retry by wrapping the code in parenthesis.</param>
/// <param name="checkExpression">Checks whether the function could be a function expression.</param>
/// <returns>Whether the script is a function or not.</returns>
public static bool IsJavascriptFunction(this string script)
public static bool IsJavascriptFunction(this string script, bool retry = true, bool checkExpression = false)
{
try
{
Expand All @@ -662,27 +664,22 @@ public static bool IsJavascriptFunction(this string script)
if (program.Body.Count > 0)
{
return
(program.Body[0] is ExpressionStatement expression && expression.Expression.Type == Nodes.ArrowFunctionExpression) ||
(program.Body[0] is ExpressionStatement expression && (
expression.Expression.Type == Nodes.ArrowFunctionExpression ||
(checkExpression && expression.Expression.Type == Nodes.FunctionExpression))) ||
program.Body[0] is FunctionDeclaration;
}

return false;
}
catch (ParserException)
{
// Retry using parenthesis
var parser = new JavaScriptParser($"({script})");
var program = parser.ParseScript();

if (program.Body.Count > 0)
if (retry)
{
return
program.Body.Count > 0 &&
program.Body[0] is ExpressionStatement expression &&
expression.Expression.Type == Nodes.FunctionExpression;
return IsJavascriptFunction($"({script})", false, true);
}

return false;
return true;
}
}

Expand Down

0 comments on commit f01af99

Please sign in to comment.