I have a business requirement where I need to execute dynamic arbitrary strings.
function executeScript(script){
if (!script) {
return;
}
try {
return new Function(script)();
}catch (err) {
console.log('Script execution error....');
}
}
console.log(executeScript(`if (document) {return true;}`));
According to Manifest V3 I cannot use eval() or New Function(). Are there any other libraries or solutions for this problem? I cannot package this as part of extension as user has ability to update this script any time. So bundling as part of extension would not solve my business use case. Your suggestions would be greatly appreciated.
Related
I am using the CrossDownManager plugin for Xamarin Forms
Here
When I run the method on Android it processes as expected. On iOS Debug.Writeline("Success!") isn't being hit like it was on Android.
Here is the code:
void ViewImage(string imageLink)
{
var downloadManager = CrossDownloadManager.Current;
downloadManager.PathNameForDownloadedFile = new System.Func<IDownloadFile, string>(file =>
{
string path = DependencyService.Get<IImageSaver>().Save("YHTS" + DateTime.Today.Ticks.ToString() + ".jpg");
Debug.WriteLine("Success!");
return path;
});
try
{
var file = downloadManager.CreateDownloadFile(imageLink);
Debug.WriteLine("file created");
downloadManager.Start(file);
Debug.WriteLine("downloadstarted");
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
}
For the life of me I can't figure out why the that code block isn't processed. Any ideas?
This is an interesting issue as technically your code should work as expected. I've done a little digging and found a reply to a similar question here.
your options are many... including:
DEBUG preprocessor as you show in your question.
Use System.Diagnostic.Debug.WriteLine: Any calls to Debug.* will be
removed by the compiler due to the [Conditional("DEBUG")] attribute
being applied.
Create your own "Logger" class as a wrapper to the stdout writers and
[Conditional("DEBUG")] it
Use Fody and re-weave the assemblies to remove/NOP/redirect the
WriteLine I do this to redirect the calls to in internal log and upon
crash or user stat requests, forward this log to our crash reporting
servers. etc, .....
So there are a few alternatives to consider, one of the common suggestions I've seen is to use the fully qualified reference for WriteLine(); as such:
System.Console.WriteLine("woop woop");
I would suggest giving the above a try first.
I'm starting to user Gate in Laravel 5.1, and I got this code from some where in the internet.
<?php
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
/**
* NOTE!!
* First time migration will fails, because permissions table doesn't exists.
*/
foreach($this->getPermissions() as $permission) {
$gate->define($permission->path, function($user) use ($permission) {
return $user->hasRole($permission->roles);
});
}
}
My question is, what is function($user) use ($permission) { in $gate->define($permission->path, function($user) use ($permission) { ??? Why is there use after function()?
If there're some references, I'd love to know/ read it.
It has been described in document of PHP.
Please refer to the example 3 of http://php.net/manual/en/functions.anonymous.php.
Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.
Your case is
$user->hasRole($permission->roles)
is necessary in order to use the variable of $permission.
I am trying to make a dart transformer that also runs on packages, but I cant figure out how I currently have the following
class MyTransformer extends Transformer implements LazyTransformer {
MyTransformer.asPlugin();
String get allowedExtensions => ".dart";
void declareOutputs(DeclaringTransform transform) {
// Just transforms a Dart file in place.
transform.declareOutput(transform.primaryId);
}
Future apply(Transform transform) {
//Only prints files that are in project how to include packages?
print(transform.primaryInput.id.path);
return //do work here
}
}
Thanks in advance I have know idea how to make it work
As far as I know this is not yet supported. See http://dartbug.com/18489 for more details (and http://dartbug.com/20267
I am using System.Web.Optimization v1.3 in what I believe is a standard configuration, to bundle and minify the JavaScript and CSS files in an MVC 5 web application. For the most part, this works very well, but I have discovered a case where JavaScript is corrupted by the minification process.
Here is a simplified version of what was originally an AngularJS input validation directive:
var myApp;
(function (myApp) {
myApp.module.directive("validator", [
function () {
return {
link: function (scope, element) {
var validators = [
{ signal: "required", message: "Please enter a value", value: null },
{ signal: "email", message: "Please enter a valid email address", value: null }
];
$("input", element).on("blur", function () {
for (var i in validators) {
var validator = validators[i];
if (scope.$parent.form[scope.modelName].$error[validator.signal]) {
element.removeClass("has-success");
scope.errorMessage = myApp.Utility.formatString(validator.message, eval(validator.value));
break;
}
}
});
}
};
}
]);
})(myApp || (myApp = {}));
Although the above code no longer does anything useful (because it has been trimmed), it does demonstrate the minification problem. When minified, the resulting JavaScript is as follows:
var myApp;
function(n){
n.module.directive("validator",[
function(){
return{
link:function(t,i){
var r=[
{signal:"required",message:"Please enter a value",value:null},
{signal:"email",message:"Please enter a valid email address",value:null}
];
$("input",i).on("blur",function(){
var i,
validator;
for(i in r)
if(validator=r[i],t.$parent.form[t.modelName].$error[validator.signal]){
i.removeClass("has-success");
t.errorMessage=n.Utility.formatString(validator.message,eval(validator.value));
break
}
})
}
}
}
])
})(myApp||(myApp={}))
Note how minification has assigned the parameter names t and i to the link function, despite the fact that a loop variable i is used in the original code.
Needless to say, this breaks the code. In this case I can fix it by renaming my loop variable, but I am concerned that there may be other adverse consequences to JsMinify's minification that I am not aware of.
So, I have 3 questions related to this issue:
Am I right to assume that this is a minification bug and, if so, is
there somewhere I should report it?
Is there any practical way of finding any other instances of this issue in my minified code?
Is it possible to replace the JavaScript minification engine used by
System.Web.Optimization and, if so, what would be a good
alternative?
Many thanks, in advance, for your ideas.
Tim
Update: After some further investigation, I have discovered that it is actually WebGrease that performs minification on behalf of System.Web.Optimization and this issue appears to be the one that I am seeing. This seems to answer my first question, but I would still appreciate advice regarding alternative minifiers.
In the past, I have successfully used YUI Compressor for .Net (now moved to GitHub), which is a .NET port from Java of YUI Compressor. The great thing about it is that it's based on Mozilla's Rhino JavaScript interpreter, meaning it actually understands the code, and not just runs regular expressions on it. As a result, it will fail your build if you have JavaScript syntax errors.
I found the Bundle Transformer (https://bundletransformer.codeplex.com/) to work well. It has a number of minifier options, such as YUI, JSMin, Microsoft Ajax Minifier, etc.
Example code in Global.asax.cs:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
var yuiMinifier = new BundleTransformer.Yui.Minifiers.YuiJsMinifier();
var customerTransformer = new BundleTransformer.Core.Transformers.ScriptTransformer(yuiMinifier);
var customBundle = new BundleTransformer.Core.Bundles.CustomScriptBundle("~/js/my-javascript.min.js");
customBundle.Include("~/js/script1.js");
customBundle.Include("~/js/script2.js");
customBundle.Transforms.Clear();
customBundle.Transforms.Add(customerTransformer);
BundleTable.Bundles.Add(customBundle);
}
}
Note: For me the minification only occurred if debug mode was set to false in the web.config.
Is there any way to conditionally import libraries / code based on environment flags or target platforms in Dart? I'm trying to switch out between dart:io's ZLibDecoder / ZLibEncoder classes and zlib.js based on the target platform.
There is an article that describes how to create a unified interface, but I'm unable to visualize that technique not creating duplicate code and redundant tests to test that duplicate code. game_loop employs this technique, but uses separate classes (GameLoopHtml and GameLoopIsolate) that don't seem to share anything.
My code looks a bit like this:
class Parser {
Layer parse(String data) {
List<int> rawBytes = /* ... */;
/* stuff you don't care about */
return new Layer(_inflateBytes(rawBytes));
}
String _inflateBytes(List<int> bytes) {
// Uses ZLibEncoder on dartvm, zlib.js in browser
}
}
I'd like to avoid duplicating code by having two separate classes -- ParserHtml and ParserServer -- that implement everything identically except for _inflateBytes.
EDIT: concrete example here: https://github.com/radicaled/citadel/blob/master/lib/tilemap/parser.dart. It's a TMX (Tile Map XML) parser.
You could use mirrors (reflection) to solve this problem. The pub package path is using reflection to access dart:io on the standalone VM or dart:html in the browser.
The source is located here. The good thing is, that they use #MirrorsUsed, so only the required classes are included for the mirrors api. In my opinion the code is documented very good, it should be easy to adopt the solution for your code.
Start at the getters _io and _html (stating at line 72), they show that you can load a library without that they are available on your type of the VM. Loading just returns false if the library it isn't available.
/// If we're running in the server-side Dart VM, this will return a
/// [LibraryMirror] that gives access to the `dart:io` library.
///
/// If `dart:io` is not available, this returns null.
LibraryMirror get _io => currentMirrorSystem().libraries[Uri.parse('dart:io')];
// TODO(nweiz): when issue 6490 or 6943 are fixed, make this work under dart2js.
/// If we're running in Dartium, this will return a [LibraryMirror] that gives
/// access to the `dart:html` library.
///
/// If `dart:html` is not available, this returns null.
LibraryMirror get _html =>
currentMirrorSystem().libraries[Uri.parse('dart:html')];
Later you can use mirrors to invoke methods or getters. See the getter current (starting at line 86) for an example implementation.
/// Gets the path to the current working directory.
///
/// In the browser, this means the current URL. When using dart2js, this
/// currently returns `.` due to technical constraints. In the future, it will
/// return the current URL.
String get current {
if (_io != null) {
return _io.classes[#Directory].getField(#current).reflectee.path;
} else if (_html != null) {
return _html.getField(#window).reflectee.location.href;
} else {
return '.';
}
}
As you see in the comments, this only works in the Dart VM at the moment. After issue 6490 is solved, it should work in Dart2Js, too. This may means that this solution isn't applicable for you at the moment, but would be a solution later.
The issue 6943 could also be helpful, but describes another solution that is not implemented yet.
Conditional imports are possible based on the presence of dart:html or dart:io, see for example the import statements of resource_loader.dart in package:resource.
I'm not yet sure how to do an import conditional on being on the Flutter platform.