UNPKG

2.52 kBJavaScriptView Raw
1
2
3/*! litejs.com/MIT-LICENSE.txt */
4
5this.accept = function(choices, priority) {
6 'use strict'
7 var group = 0
8 , ruleSeq = 0
9 , rules = choices.constructor == Object ? Object.keys(choices) : choices
10 , escapeRe = /[.+?^!:${}()|\[\]\/\\]/g
11 , fnStr = 'return function(i){for(var m,t,l={q:null};(m=r.exec(i))&&(m='
12
13 return Function(
14 'c,R,D',
15 'var r=/(?:^|,\\s*)(?:(' +
16 ('' + rules).replace(/[^,;]+|\s*;\s*(\w+)=("([^"]*)"|[^,;\s]*)|,/ig, function add(rule, key, token, qstr, offset, all) {
17 if (key) {
18 // Parse Parameters
19 //
20 // Non-extended notation, using "quoted-string" RFC-8187
21 // foo: bar; title="US-$ rates"
22 // Extended notation, using the Unicode character U+00A3 ("£", POUND SIGN):
23 // foo: bar; title*=utf-8'en'%C2%A3%20rates
24
25 fnStr += ',' + key + ':D(m[' + (++group) + '],m[' + (++group + 1) + ']==null?m[' + (group++) + ']||'
26 + JSON.stringify(qstr == null ? token : qstr)
27 + ':m[' + group + '])'
28 return '(?=(?:"[^"]*"|[^,])*;\\s*' + key + '(=|\\*=utf-8\'\\w*\')("([^"]*)"|[^\\s,;]+)|)'
29 }
30 if (rule == ',') {
31 return ')|('
32 }
33 fnStr += (offset ? '}:m[' : 'm[') + (++group) + ']?{rule:"' + rule + '",match:m[' + group + ']'
34 if (choices !== rules) {
35 fnStr += ',o:c[R[' + (ruleSeq++) + ']]'
36 }
37
38 key = rule.match(/^(.+?)\/(.+?)(?:\+(.+))?$/)
39 rule = rule.replace(escapeRe, '\\$&')
40 if (key) {
41 // type / [ tree. ] subtype [ +suffix ] [ ; parameters ]
42 fnStr += ',type:' + capture(1, /(.*)\\\//, '($1)\\/')
43 + ',subtype:' + capture(2, /\/(.+?)(?=\\\+|$)/, '/($1)')
44 + ',suffix:' + capture(3, /\+(.+)/, '+($1)')
45 } else if (key = priority == "lang" && rule.match(/^..(?=\-)/i)) {
46 // Basic Filtering
47 // https://tools.ietf.org/html/rfc4647#section-3.3.1
48 if (!RegExp(key + "(?!-)", "i").test(all)) {
49 rule = "(?:" + rule + "|" + key + "(?!.+" + rule + "))"
50 }
51 }
52 rule = rule.replace(/\*/g, '[^,;\\s\\/+]+?')
53
54 return (offset ? rule : '(?:' + rule + '|[*\\/]+)') + add(0, 'q', 1)
55
56 function capture(j, re, to) {
57 return /\*/.test(key[j]) ?
58 ((rule = rule.replace(re, to)), 'm[' + (++group) + ']') :
59 '"' + (key[j] || '') + '"'
60 }
61 }) +
62 '))\\s*(?=,|;|$)(?:"[^"]*"|[^,])*/gi;' +
63 fnStr.replace(/m\[\d+\]\?(?!.*m\[\d+\]\?)/, '') +
64 '});){t=1*m.q;if((m.q=t>=0&&t<1?t:1)>l.q' +
65 (priority && priority !== "lang" ? priority : '') +
66 ')l=m}return l}'
67 )(choices, rules, function(op, str) {
68 if (op !== "=") try {
69 str = decodeURIComponent(str)
70 } catch (e) {}
71 return str
72 })
73}
74