UNPKG

2.42 kBJavaScriptView Raw
1/**
2 * Adds the capability to load SeaJS modules in node environment.
3 * @author lifesinger@gmail.com
4 */
5
6var Module = module.constructor
7var helper = require('./helper')
8var vm = require('vm')
9
10
11var _compile = Module.prototype._compile
12var _resolveFilename = Module._resolveFilename
13var moduleStack = []
14
15Module._resolveFilename = function(request, parent) {
16 request = request.replace(/\?.*$/, '') // remove timestamp etc.
17 request = helper.parseAlias(request)
18 return _resolveFilename(request, parent)
19}
20
21Module.prototype._compile = function(content, filename) {
22 moduleStack.push(this)
23 try {
24 return _compile.call(this, content, filename)
25 }
26 finally {
27 moduleStack.pop()
28 }
29}
30
31
32global.seajs = {
33 config: helper.configFn,
34 use: createAsync(module),
35 cache: require.cache,
36 log: console.log,
37 version: require('../package.json').version
38}
39
40global.define = function(factory) {
41 var ret = factory
42 var module = moduleStack[moduleStack.length - 1] || require.main
43
44 // define(function(require, exports, module) { ... })
45 if (typeof factory === 'function') {
46 module.uri = module.id
47
48 var req = function(id) {
49 return module.require(id)
50 }
51 req.async = createAsync(module)
52
53 ret = factory.call(
54 global,
55 req,
56 module.exports,
57 module)
58
59 if (ret !== undefined) {
60 module.exports = ret
61 }
62 }
63 // define(object)
64 else {
65 module.exports = factory
66 }
67}
68
69function createAsync(module) {
70
71 return function(ids, callback) {
72 if (typeof ids === 'string') ids = [ids]
73
74 var args = []
75 var remain = ids.length
76
77 ids.forEach(function(id, index) {
78
79 // http or https file
80 if (/^https?:\/\//.test(id)) {
81 helper.readFile(id, function(data) {
82 var m = {
83 id: id,
84 exports: {}
85 }
86
87 moduleStack.push(m)
88 vm.runInThisContext(data, id)
89 moduleStack.pop()
90
91 done(m.exports, index)
92 })
93 }
94 // local file
95 else {
96 done(module.require(id), index)
97 }
98 })
99
100 function done(data, index) {
101 args[index] = data
102 if (--remain === 0 && callback) {
103 callback.apply(null, args)
104 }
105 }
106 }
107
108}
109
110
111module.exports = global.seajs
112
113/**
114 * Thanks to
115 * - https://github.com/joyent/node/blob/master/lib/module.js
116 * - https://github.com/ajaxorg/node-amd-loader/blob/master/lib/amd-loader.js
117 */