Gathering detailed insights and metrics for devalue
Approximately 800 new packages are uploaded to the npm registry every day. This number can vary, but it reflects the active and growing nature of the JavaScript development community.
Gathering detailed insights and metrics for devalue
Approximately 800 new packages are uploaded to the npm registry every day. This number can vary, but it reflects the active and growing nature of the JavaScript development community.
npm install devalue
99.5
Supply Chain
99.5
Quality
82.8
Maintenance
100
Vulnerability
2,179 Stars
174 Commits
59 Forks
14 Watching
1 Branches
12 Contributors
Updated on 12 Nov 2024
Minified
Minified + Gzipped
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
1.4%
261,686
Compared to previous day
Last week
3.6%
1,404,473
Compared to previous week
Last month
10.5%
6,135,666
Compared to previous month
Last year
75.1%
57,908,444
Compared to previous year
4
Like JSON.stringify
, but handles
obj.self = obj
)[value, value]
)undefined
, Infinity
, NaN
, -0
Map
and Set
BigInt
ArrayBuffer
and Typed ArraysTry it out here.
There are two ways to use devalue
:
uneval
This function takes a JavaScript value and returns the JavaScript code to create an equivalent value — sort of like eval
in reverse:
1import * as devalue from 'devalue'; 2 3let obj = { message: 'hello' }; 4devalue.uneval(obj); // '{message:"hello"}' 5 6obj.self = obj; 7devalue.uneval(obj); // '(function(a){a.message="hello";a.self=a;return a}({}))'
Use uneval
when you want the most compact possible output and don't want to include any code for parsing the serialized value.
stringify
and parse
These two functions are analogous to JSON.stringify
and JSON.parse
:
1import * as devalue from 'devalue'; 2 3let obj = { message: 'hello' }; 4 5let stringified = devalue.stringify(obj); // '[{"message":1},"hello"]' 6devalue.parse(stringified); // { message: 'hello' } 7 8obj.self = obj; 9 10stringified = devalue.stringify(obj); // '[{"message":1,"self":0},"hello"]' 11devalue.parse(stringified); // { message: 'hello', self: [Circular] }
Use stringify
and parse
when evaluating JavaScript isn't an option.
unflatten
In the case where devalued data is one part of a larger JSON string, unflatten
allows you to revive just the bit you need:
1import * as devalue from 'devalue'; 2 3const json = `{ 4 "type": "data", 5 "data": ${devalue.stringify(data)} 6}`; 7 8const data = devalue.unflatten(JSON.parse(json).data);
You can serialize and deserialize custom types by passing a second argument to stringify
containing an object of types and their reducers, and a second argument to parse
or unflatten
containing an object of types and their revivers:
1class Vector { 2 constructor(x, y) { 3 this.x = x; 4 this.y = y; 5 } 6 7 magnitude() { 8 return Math.sqrt(this.x * this.x + this.y * this.y); 9 } 10} 11 12const stringified = devalue.stringify(new Vector(30, 40), { 13 Vector: (value) => value instanceof Vector && [value.x, value.y] 14}); 15 16console.log(stringified); // [["Vector",1],[2,3],30,40] 17 18const vector = devalue.parse(stringified, { 19 Vector: ([x, y]) => new Vector(x, y) 20}); 21 22console.log(vector.magnitude()); // 50
If a function passed to stringify
returns a truthy value, it's treated as a match.
You can also use custom types with uneval
by specifying a custom replacer:
1devalue.uneval(vector, (value, uneval) => { 2 if (value instanceof Vector) { 3 return `new Vector(${value.x},${value.y})`; 4 } 5}); // `new Vector(30,40)`
Note that any variables referenced in the resulting JavaScript (like Vector
in the example above) must be in scope when it runs.
If uneval
or stringify
encounters a function or a non-POJO that isn't handled by a custom replacer/reducer, it will throw an error. You can find where in the input data the offending value lives by inspecting error.path
:
1try { 2 const map = new Map(); 3 map.set('key', function invalid() {}); 4 5 uneval({ 6 object: { 7 array: [map] 8 } 9 }); 10} catch (e) { 11 console.log(e.path); // '.object.array[0].get("key")' 12}
Say you're server-rendering a page and want to serialize some state, which could include user input. JSON.stringify
doesn't protect against XSS attacks:
1const state = { 2 userinput: `</script><script src='https://evil.com/mwahaha.js'>` 3}; 4 5const template = ` 6<script> 7 // NEVER DO THIS 8 var preloaded = ${JSON.stringify(state)}; 9</script>`;
Which would result in this:
1<script> 2 // NEVER DO THIS 3 var preloaded = {"userinput":" 4</script> 5<script src="https://evil.com/mwahaha.js"> 6 "}; 7</script>
Using uneval
or stringify
, we're protected against that attack:
1const template = ` 2<script> 3 var preloaded = ${uneval(state)}; 4</script>`;
1<script>
2 var preloaded = {
3 userinput:
4 "\\u003C\\u002Fscript\\u003E\\u003Cscript src='https:\\u002F\\u002Fevil.com\\u002Fmwahaha.js'\\u003E"
5 };
6</script>
This, along with the fact that uneval
and stringify
bail on functions and non-POJOs, stops attackers from executing arbitrary code. Strings generated by uneval
can be safely deserialized with eval
or new Function
:
1const value = (0, eval)('(' + str + ')');
While uneval
prevents the XSS vulnerability shown above, meaning you can use it to send data from server to client, you should not send user data from client to server using the same method. Since it has to be evaluated, an attacker that successfully submitted data that bypassed uneval
would have access to your system.
When using eval
, ensure that you call it indirectly so that the evaluated code doesn't have access to the surrounding scope:
1{ 2 const sensitiveData = 'Setec Astronomy'; 3 eval('sendToEvilServer(sensitiveData)'); // pwned :( 4 (0, eval)('sendToEvilServer(sensitiveData)'); // nice try, evildoer! 5}
Using new Function(code)
is akin to using indirect eval.
stringify
/parse
approach in devalue
was inspired by arson
No vulnerabilities found.
Reason
13 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10
Reason
license file detected
Details
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
0 existing vulnerabilities detected
Reason
Found 6/14 approved changesets -- score normalized to 4
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-11
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn Moreturbo-stream
A streaming data transport format that aims to support built-in features such as Promises, Dates, RegExps, Maps, Sets and more.
@nuxt/devalue
Gets the job done when JSON.stringify can't
@nuxtjs/devalue
Gets the job done when JSON.stringify can't
@socket.io/devalue-parser
Socket.IO parser based on devalue