Allow it to work on edge (e.g. cloudflare workers)
Currently AJV can't run on cloudflare workers, vercel-edge and other edge environments. When trying to run it, the worker throws an error:
Code generation from strings disallowed for this context
Most likely this is because they restrict certain JavaScript functions like eval(), new Function(), setTimeout([string]), and setInterval([string]), which can execute code generated from strings.
I'm not sure why these functions are needed but it would be better to avoid them so that it could run everywhere without issues.
Up !
Up! Also a question, is it possible to use ajv in web worker?
I use this library https://github.com/cfworker/cfworker/tree/main/packages/json-schema alternative
Currently AJV can't run on cloudflare workers, vercel-edge and other edge environments. When trying to run it, the worker throws an error:
Code generation from strings disallowed for this contextMost likely this is because they restrict certain JavaScript functions like
eval(), new Function(), setTimeout([string]), andsetInterval([string]), which can execute code generated from strings.I'm not sure why these functions are needed but it would be better to avoid them so that it could run everywhere without issues.
Thanks for the extra info @cosbgn. I have looked into it and I can only see that of the disallowed functions, AJV only uses new Function(), all within the compile functionality. This makes sense as in order to produce highly performant code, the compile logic does a lot of magic and basically creates optimised validation functions using this technique.
So I am curious, can you use AJV in cloudflare if you avoid the compile method. For example can you do this:
const Ajv = require("ajv");
const ajv = new Ajv();
const schema = {
type: "object",
properties: {
foo: {type: "integer"},
},
};
const data = {
foo: 1,
};
const valid = ajv.validate(schema, data);
Otherwise I can only suggest prebuilding your validation functions in CI using ajv-cli like this:
ajv compile -s schema.json -o validate_schema.js
Then within your application code you can require the validation functions.
const validate = require('./validate_schema.js');
const data = { /* your data */ };
if (validate(data)) {
console.log('Validation successful');
} else {
console.error('Validation failed', validate.errors);
}
I think pre-compiling functions is a good option here so will close unless someone strongly disagrees.
const valid = ajv.validate(schema, data);
Using validate worked for me. Thanks!
Could you share a bit more about the precompile option? Conceivably, this could be done with a script as part of the build process? Would the precompile option be better than simply using validate in any way?
ajv.validate fails because it still compiles and use new Function