Merge "LOG SQL dump files getting installed"
[sdnc/oam.git] / dgbuilder / dgeflows / node_modules / serve-index / node_modules / accepts / node_modules / negotiator / lib / charset.js
1 module.exports = preferredCharsets;
2 preferredCharsets.preferredCharsets = preferredCharsets;
3
4 function parseAcceptCharset(accept) {
5   var accepts = accept.split(',');
6
7   for (var i = 0, j = 0; i < accepts.length; i++) {
8     var charset = parseCharset(accepts[i].trim(), i);
9
10     if (charset) {
11       accepts[j++] = charset;
12     }
13   }
14
15   // trim accepts
16   accepts.length = j;
17
18   return accepts;
19 }
20
21 function parseCharset(s, i) {
22   var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/);
23   if (!match) return null;
24
25   var charset = match[1];
26   var q = 1;
27   if (match[2]) {
28     var params = match[2].split(';')
29     for (var i = 0; i < params.length; i ++) {
30       var p = params[i].trim().split('=');
31       if (p[0] === 'q') {
32         q = parseFloat(p[1]);
33         break;
34       }
35     }
36   }
37
38   return {
39     charset: charset,
40     q: q,
41     i: i
42   };
43 }
44
45 function getCharsetPriority(charset, accepted, index) {
46   var priority = {o: -1, q: 0, s: 0};
47
48   for (var i = 0; i < accepted.length; i++) {
49     var spec = specify(charset, accepted[i], index);
50
51     if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
52       priority = spec;
53     }
54   }
55
56   return priority;
57 }
58
59 function specify(charset, spec, index) {
60   var s = 0;
61   if(spec.charset.toLowerCase() === charset.toLowerCase()){
62     s |= 1;
63   } else if (spec.charset !== '*' ) {
64     return null
65   }
66
67   return {
68     i: index,
69     o: spec.i,
70     q: spec.q,
71     s: s
72   }
73 }
74
75 function preferredCharsets(accept, provided) {
76   // RFC 2616 sec 14.2: no header = *
77   var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || '');
78
79   if (!provided) {
80     // sorted list of all charsets
81     return accepts.filter(isQuality).sort(compareSpecs).map(function getCharset(spec) {
82       return spec.charset;
83     });
84   }
85
86   var priorities = provided.map(function getPriority(type, index) {
87     return getCharsetPriority(type, accepts, index);
88   });
89
90   // sorted list of accepted charsets
91   return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) {
92     return provided[priorities.indexOf(priority)];
93   });
94 }
95
96 function compareSpecs(a, b) {
97   return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
98 }
99
100 function isQuality(spec) {
101   return spec.q > 0;
102 }