1 | 'use strict';
|
---|
2 |
|
---|
3 | var JSON3 = require('json3');
|
---|
4 |
|
---|
5 | // Some extra characters that Chrome gets wrong, and substitutes with
|
---|
6 | // something else on the wire.
|
---|
7 | // eslint-disable-next-line no-control-regex, no-misleading-character-class
|
---|
8 | var extraEscapable = /[\x00-\x1f\ud800-\udfff\ufffe\uffff\u0300-\u0333\u033d-\u0346\u034a-\u034c\u0350-\u0352\u0357-\u0358\u035c-\u0362\u0374\u037e\u0387\u0591-\u05af\u05c4\u0610-\u0617\u0653-\u0654\u0657-\u065b\u065d-\u065e\u06df-\u06e2\u06eb-\u06ec\u0730\u0732-\u0733\u0735-\u0736\u073a\u073d\u073f-\u0741\u0743\u0745\u0747\u07eb-\u07f1\u0951\u0958-\u095f\u09dc-\u09dd\u09df\u0a33\u0a36\u0a59-\u0a5b\u0a5e\u0b5c-\u0b5d\u0e38-\u0e39\u0f43\u0f4d\u0f52\u0f57\u0f5c\u0f69\u0f72-\u0f76\u0f78\u0f80-\u0f83\u0f93\u0f9d\u0fa2\u0fa7\u0fac\u0fb9\u1939-\u193a\u1a17\u1b6b\u1cda-\u1cdb\u1dc0-\u1dcf\u1dfc\u1dfe\u1f71\u1f73\u1f75\u1f77\u1f79\u1f7b\u1f7d\u1fbb\u1fbe\u1fc9\u1fcb\u1fd3\u1fdb\u1fe3\u1feb\u1fee-\u1fef\u1ff9\u1ffb\u1ffd\u2000-\u2001\u20d0-\u20d1\u20d4-\u20d7\u20e7-\u20e9\u2126\u212a-\u212b\u2329-\u232a\u2adc\u302b-\u302c\uaab2-\uaab3\uf900-\ufa0d\ufa10\ufa12\ufa15-\ufa1e\ufa20\ufa22\ufa25-\ufa26\ufa2a-\ufa2d\ufa30-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4e\ufff0-\uffff]/g
|
---|
9 | , extraLookup;
|
---|
10 |
|
---|
11 | // This may be quite slow, so let's delay until user actually uses bad
|
---|
12 | // characters.
|
---|
13 | var unrollLookup = function(escapable) {
|
---|
14 | var i;
|
---|
15 | var unrolled = {};
|
---|
16 | var c = [];
|
---|
17 | for (i = 0; i < 65536; i++) {
|
---|
18 | c.push( String.fromCharCode(i) );
|
---|
19 | }
|
---|
20 | escapable.lastIndex = 0;
|
---|
21 | c.join('').replace(escapable, function(a) {
|
---|
22 | unrolled[ a ] = '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
|
---|
23 | return '';
|
---|
24 | });
|
---|
25 | escapable.lastIndex = 0;
|
---|
26 | return unrolled;
|
---|
27 | };
|
---|
28 |
|
---|
29 | // Quote string, also taking care of unicode characters that browsers
|
---|
30 | // often break. Especially, take care of unicode surrogates:
|
---|
31 | // http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Surrogates
|
---|
32 | module.exports = {
|
---|
33 | quote: function(string) {
|
---|
34 | var quoted = JSON3.stringify(string);
|
---|
35 |
|
---|
36 | // In most cases this should be very fast and good enough.
|
---|
37 | extraEscapable.lastIndex = 0;
|
---|
38 | if (!extraEscapable.test(quoted)) {
|
---|
39 | return quoted;
|
---|
40 | }
|
---|
41 |
|
---|
42 | if (!extraLookup) {
|
---|
43 | extraLookup = unrollLookup(extraEscapable);
|
---|
44 | }
|
---|
45 |
|
---|
46 | return quoted.replace(extraEscapable, function(a) {
|
---|
47 | return extraLookup[a];
|
---|
48 | });
|
---|
49 | }
|
---|
50 | };
|
---|