File size: 2,528 Bytes
4cadbaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
(function () {
	var URI_NS = require("../uri"),
		URI = URI_NS.URI,
		pctEncChar = URI_NS.pctEncChar,
		NID$ = "(?:[0-9A-Za-z][0-9A-Za-z\\-]{1,31})",
		PCT_ENCODED$ = "(?:\\%[0-9A-Fa-f]{2})",
		TRANS$$ = "[0-9A-Za-z\\(\\)\\+\\,\\-\\.\\:\\=\\@\\;\\$\\_\\!\\*\\'\\/\\?\\#]",
		NSS$ = "(?:(?:" + PCT_ENCODED$ + "|" + TRANS$$ + ")+)",
		URN_SCHEME = new RegExp("^urn\\:(" + NID$ + ")$"),
		URN_PATH = new RegExp("^(" + NID$ + ")\\:(" + NSS$ + ")$"),
		URN_PARSE = /^([^\:]+)\:(.*)/,
		URN_EXCLUDED = /[\x00-\x20\\\"\&\<\>\[\]\^\`\{\|\}\~\x7F-\xFF]/g,
		UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;
	
	//RFC 2141
	URI.SCHEMES["urn"] = {
		parse : function (components, options) {
			var matches = components.path.match(URN_PATH),
				scheme, schemeHandler;
			
			if (!matches) {
				if (!options.tolerant) {
					components.errors.push("URN is not strictly valid.");
				}
				
				matches = components.path.match(URN_PARSE);
			}
			
			if (matches) {
				scheme = "urn:" + matches[1].toLowerCase();
				schemeHandler = URI.SCHEMES[scheme];
				
				//in order to serialize properly, 
				//every URN must have a serializer that calls the URN serializer 
				if (!schemeHandler) {
					schemeHandler = URI.SCHEMES[scheme] = {};
				}
				if (!schemeHandler.serialize) {
					schemeHandler.serialize = URI.SCHEMES["urn"].serialize;
				}
				
				components.scheme = scheme;
				components.path = matches[2];
				
				if (schemeHandler.parse) {
					schemeHandler.parse(components, options);
				}
			} else {
				components.errors.push("URN can not be parsed.");
			}
	
			return components;
		},
		
		serialize : function (components, options) {
			var scheme = components.scheme || options.scheme,
				matches;
			
			if (scheme && scheme !== "urn") {
				var matches = scheme.match(URN_SCHEME);
				
				if (!matches) {
					matches = ["urn:" + scheme, scheme];
				}
				
				components.scheme = "urn";
				components.path = matches[1] + ":" + (components.path ? components.path.replace(URN_EXCLUDED, pctEncChar) : "");
			}
			
			return components;
		}
	};
	
	//RFC 4122
	URI.SCHEMES["urn:uuid"] = {
		serialize : function (components, options) {
			//ensure UUID is valid
			if (!options.tolerant && (!components.path || !components.path.match(UUID))) {
				//invalid UUIDs can not have this scheme
				components.scheme = undefined;
			}
			
			return URI.SCHEMES["urn"].serialize(components, options);
		}
	};
}());