-
Notifications
You must be signed in to change notification settings - Fork 1
/
json.js
84 lines (70 loc) · 1.97 KB
/
json.js
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
/*
SystemJS JSON Format
Provides the JSON module format definition.
*/
function _SYSTEM_addJSON(loader) {
var jsonTest = /^[\s\n\r]*[\{\[]/;
var jsonExt = /\.json$/i;
var jsExt = /\.js$/i;
var inNode = typeof window === "undefined";
// Add the extension to _extensions so that it can be cloned.
loader._extensions.push(_SYSTEM_addJSON);
// if someone has a moduleName that is .json, make sure it loads a json file
// no matter what paths might do
var loaderLocate = loader.locate;
loader.locate = function(load){
return loaderLocate.apply(this, arguments).then(function(address){
if(jsonExt.test(load.name)) {
return address.replace(jsExt, "");
}
return address;
});
};
var transform = function(loader, load, data){
var fn = loader.jsonOptions && loader.jsonOptions.transform;
if(!fn) return data;
return fn.call(loader, load, data);
};
// If we are in a build we should convert to CommonJS instead.
if(inNode) {
var loaderTranslate = loader.translate;
loader.translate = function(load){
if(jsonExt.test(load.name)) {
var parsed = parse(load);
if(parsed) {
parsed = transform(this, load, parsed);
return "def" + "ine([], function(){\n" +
"\treturn " + JSON.stringify(parsed) + "\n});";
}
}
return loaderTranslate.call(this, load);
};
return;
}
var loaderInstantiate = loader.instantiate;
loader.instantiate = function(load) {
var loader = this,
parsed;
parsed = parse(load);
if(parsed) {
parsed = transform(loader, load, parsed);
load.metadata.format = 'json';
load.metadata.execute = function(){
return parsed;
};
}
return loaderInstantiate.call(loader, load);
};
return loader;
// Attempt to parse a load as json.
function parse(load){
if ( (load.metadata.format === 'json' || !load.metadata.format) && jsonTest.test(load.source) ) {
try {
return JSON.parse(load.source);
} catch(e) {}
}
}
}
if (typeof System !== "undefined") {
_SYSTEM_addJSON(System);
}