Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80538 views
1
'use strict';
2
3
4
var templateSTR = "(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}defineNamespace()}})(function(){source()});";
5
6
function template(moduleName, options) {
7
if (typeof options === 'boolean') {
8
options = {commonJS: options};
9
} else if (!options) {
10
options = {};
11
}
12
var str = templateSTR.replace(/defineNamespace\(\)/g, compileNamespace(moduleName))
13
.split('source()')
14
str[0] = str[0].trim();
15
//make sure these are undefined so as to not get confused if modules have inner UMD systems
16
str[0] += 'var define,module,exports;';
17
if (options.commonJS) str[0] += 'module={exports:(exports={})};';
18
str[0] += '\n';
19
if (options.commonJS) str[1] = 'return module.exports;' + str[1];
20
str[1] = '\n' + str[1];
21
return str;
22
}
23
24
exports = module.exports = function (name, src, options) {
25
if (typeof options === 'string' && typeof src === 'object') {
26
var tmp = options;
27
options = src;
28
src = tmp;
29
}
30
return exports.prelude(name, options) + src + exports.postlude(name, options);
31
};
32
33
exports.prelude = function (moduleName, options) {
34
return template(moduleName, options)[0];
35
};
36
exports.postlude = function (moduleName, options) {
37
return template(moduleName, options)[1];
38
};
39
40
41
function camelCase(name) {
42
name = name.replace(/\-([a-z])/g, function (_, char) { return char.toUpperCase(); });
43
if (!/^[a-zA-Z_$]$/.test(name[0])) {
44
name = name.substr(1);
45
}
46
var result = name.replace(/[^\w$]+/g, '')
47
if (!result) {
48
throw new Error('Invalid JavaScript identifier resulted from camel-casing');
49
}
50
return result
51
}
52
53
54
function compileNamespace(name) {
55
var names = name.split('.')
56
57
// No namespaces, yield the best case 'global.NAME = VALUE'
58
if (names.length === 1) {
59
return 'g.' + camelCase(name) + ' = f()';
60
61
// Acceptable case, with reasonable compilation
62
} else if (names.length === 2) {
63
names = names.map(camelCase);
64
return '(g.' + names[0] + ' || (g.' + names[0] + ' = {})).' + names[1] + ' = f()';
65
66
// Worst case, too many namespaces to care about
67
} else {
68
var valueContainer = names.pop()
69
return names.map(compileNamespaceStep)
70
.concat(['g.' + camelCase(valueContainer) + ' = f()'])
71
.join(';');
72
}
73
}
74
75
function compileNamespaceStep(name) {
76
name = camelCase(name);
77
return 'g=(g.' + name + '||(g.' + name + ' = {}))';
78
}
79
80