forked from seajs/seajs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.js
508 lines (394 loc) · 12 KB
/
module.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
/**
* The core of loader
*/
;(function(seajs, util, config) {
var cachedModules = {}
var cachedModifiers = {}
var compileStack = []
var STATUS = {
'FETCHING': 1, // The module file is fetching now.
'FETCHED': 2, // The module file has been fetched.
'SAVED': 3, // The module info has been saved.
'READY': 4, // All dependencies and self are ready to compile.
'COMPILING': 5, // The module is in compiling now.
'COMPILED': 6 // The module is compiled and module.exports is available.
}
function Module(uri, status) {
this.uri = uri
this.status = status || 0
// this.id is set when saving
// this.dependencies is set when saving
// this.factory is set when saving
// this.exports is set when compiling
// this.parent is set when compiling
// this.require is set when compiling
}
Module.prototype._use = function(ids, callback) {
util.isString(ids) && (ids = [ids])
var uris = resolve(ids, this.uri)
this._load(uris, function() {
var args = util.map(uris, function(uri) {
return uri ? cachedModules[uri]._compile() : null
})
if (callback) {
callback.apply(null, args)
}
})
}
Module.prototype._load = function(uris, callback) {
var unLoadedUris = util.filter(uris, function(uri) {
return uri && (!cachedModules[uri] ||
cachedModules[uri].status < STATUS.READY)
})
var length = unLoadedUris.length
if (length === 0) {
callback()
return
}
var remain = length
for (var i = 0; i < length; i++) {
(function(uri) {
var module = cachedModules[uri] ||
(cachedModules[uri] = new Module(uri, STATUS.FETCHING))
module.status >= STATUS.FETCHED ? onFetched() : fetch(uri, onFetched)
function onFetched() {
// cachedModules[uri] is changed in un-correspondence case
module = cachedModules[uri]
if (module.status >= STATUS.SAVED) {
var deps = getPureDependencies(module)
if (deps.length) {
Module.prototype._load(deps, function() {
cb(module)
})
}
else {
cb(module)
}
}
// Maybe failed to fetch successfully, such as 404 or non-module.
// In these cases, just call cb function directly.
else {
cb()
}
}
})(unLoadedUris[i])
}
function cb(module) {
(module || {}).status < STATUS.READY && (module.status = STATUS.READY)
--remain === 0 && callback()
}
}
Module.prototype._compile = function() {
var module = this
if (module.status === STATUS.COMPILED) {
return module.exports
}
// Just return null when:
// 1. the module file is 404.
// 2. the module file is not written with valid module format.
// 3. other error cases.
if (module.status < STATUS.READY && !hasModifiers(module)) {
return null
}
module.status = STATUS.COMPILING
function require(id) {
var uri = resolve(id, module.uri)
var child = cachedModules[uri]
// Just return null when uri is invalid.
if (!child) {
return null
}
// Avoids circular calls.
if (child.status === STATUS.COMPILING) {
return child.exports
}
child.parent = module
return child._compile()
}
require.async = function(ids, callback) {
module._use(ids, callback)
}
require.resolve = function(id) {
return resolve(id, module.uri)
}
require.cache = cachedModules
module.require = require
module.exports = {}
var factory = module.factory
if (util.isFunction(factory)) {
compileStack.push(module)
runInModuleContext(factory, module)
compileStack.pop()
}
else if (factory !== undefined) {
module.exports = factory
}
module.status = STATUS.COMPILED
execModifiers(module)
return module.exports
}
Module._define = function(id, deps, factory) {
var argsLength = arguments.length
// define(factory)
if (argsLength === 1) {
factory = id
id = undefined
}
// define(id || deps, factory)
else if (argsLength === 2) {
factory = deps
deps = undefined
// define(deps, factory)
if (util.isArray(id)) {
deps = id
id = undefined
}
}
// Parses dependencies.
if (!util.isArray(deps) && util.isFunction(factory)) {
deps = util.parseDependencies(factory.toString())
}
var meta = { id: id, dependencies: deps, factory: factory }
var derivedUri
// Try to derive uri in IE6-9 for anonymous modules.
if (document.attachEvent) {
// Try to get the current script.
var script = util.getCurrentScript()
if (script) {
derivedUri = util.unParseMap(util.getScriptAbsoluteSrc(script))
}
if (!derivedUri) {
util.log('Failed to derive URI from interactive script for:',
factory.toString(), 'warn')
// NOTE: If the id-deriving methods above is failed, then falls back
// to use onload event to get the uri.
}
}
// Gets uri directly for specific module.
var resolvedUri = id ? resolve(id) : derivedUri
if (resolvedUri) {
// For IE:
// If the first module in a package is not the cachedModules[derivedUri]
// self, it should assign to the correct module when found.
if (resolvedUri === derivedUri) {
var refModule = cachedModules[derivedUri]
if (refModule && refModule.realUri &&
refModule.status === STATUS.SAVED) {
cachedModules[derivedUri] = null
}
}
var module = save(resolvedUri, meta)
// For IE:
// Assigns the first module in package to cachedModules[derivedUrl]
if (derivedUri) {
// cachedModules[derivedUri] may be undefined in combo case.
if ((cachedModules[derivedUri] || {}).status === STATUS.FETCHING) {
cachedModules[derivedUri] = module
module.realUri = derivedUri
}
}
else {
firstModuleInPackage || (firstModuleInPackage = module)
}
}
else {
// Saves information for "memoizing" work in the onload event.
anonymousModuleMeta = meta
}
}
Module._getCompilingModule = function() {
return compileStack[compileStack.length - 1]
}
Module._find = function(selector) {
var matches = []
util.forEach(util.keys(cachedModules), function(uri) {
if (util.isString(selector) && uri.indexOf(selector) > -1 ||
util.isRegExp(selector) && selector.test(uri)) {
var module = cachedModules[uri]
module.exports && matches.push(module.exports)
}
})
return matches
}
Module._modify = function(id, modifier) {
var uri = resolve(id)
var module = cachedModules[uri]
if (module && module.status === STATUS.COMPILED) {
runInModuleContext(modifier, module)
}
else {
cachedModifiers[uri] || (cachedModifiers[uri] = [])
cachedModifiers[uri].push(modifier)
}
return seajs
}
// For plugin developers
Module.STATUS = STATUS
Module._resolve = util.id2Uri
Module._fetch = util.fetch
Module.cache = cachedModules
// Helpers
// -------
var fetchingList = {}
var fetchedList = {}
var callbackList = {}
var anonymousModuleMeta = null
var firstModuleInPackage = null
var circularCheckStack = []
function resolve(ids, refUri) {
if (util.isString(ids)) {
return Module._resolve(ids, refUri)
}
return util.map(ids, function(id) {
return resolve(id, refUri)
})
}
function fetch(uri, callback) {
var requestUri = util.parseMap(uri)
if (fetchedList[requestUri]) {
// See test/issues/debug-using-map
cachedModules[uri] = cachedModules[requestUri]
callback()
return
}
if (fetchingList[requestUri]) {
callbackList[requestUri].push(callback)
return
}
fetchingList[requestUri] = true
callbackList[requestUri] = [callback]
// Fetches it
Module._fetch(
requestUri,
function() {
fetchedList[requestUri] = true
// Updates module status
var module = cachedModules[uri]
if (module.status === STATUS.FETCHING) {
module.status = STATUS.FETCHED
}
// Saves anonymous module meta data
if (anonymousModuleMeta) {
save(uri, anonymousModuleMeta)
anonymousModuleMeta = null
}
// Assigns the first module in package to cachedModules[uri]
// See: test/issues/un-correspondence
if (firstModuleInPackage && module.status === STATUS.FETCHED) {
cachedModules[uri] = firstModuleInPackage
firstModuleInPackage.realUri = uri
}
firstModuleInPackage = null
// Clears
if (fetchingList[requestUri]) {
delete fetchingList[requestUri]
}
// Calls callbackList
if (callbackList[requestUri]) {
util.forEach(callbackList[requestUri], function(fn) {
fn()
})
delete callbackList[requestUri]
}
},
config.charset
)
}
function save(uri, meta) {
var module = cachedModules[uri] || (cachedModules[uri] = new Module(uri))
// Don't override already saved module
if (module.status < STATUS.SAVED) {
// Lets anonymous module id equal to its uri
module.id = meta.id || uri
module.dependencies = resolve(
util.filter(meta.dependencies || [], function(dep) {
return !!dep
}), uri)
module.factory = meta.factory
// Updates module status
module.status = STATUS.SAVED
}
return module
}
function runInModuleContext(fn, module) {
var ret = fn(module.require, module.exports, module)
if (ret !== undefined) {
module.exports = ret
}
}
function hasModifiers(module) {
return !!cachedModifiers[module.realUri || module.uri]
}
function execModifiers(module) {
var uri = module.realUri || module.uri
var modifiers = cachedModifiers[uri]
if (modifiers) {
util.forEach(modifiers, function(modifier) {
runInModuleContext(modifier, module)
})
delete cachedModifiers[uri]
}
}
function getPureDependencies(module) {
var uri = module.uri
return util.filter(module.dependencies, function(dep) {
circularCheckStack = [uri]
var isCircular = isCircularWaiting(cachedModules[dep], uri)
if (isCircular) {
circularCheckStack.push(uri)
printCircularLog(circularCheckStack)
}
return !isCircular
})
}
function isCircularWaiting(module, uri) {
if (!module || module.status !== STATUS.SAVED) {
return false
}
circularCheckStack.push(module.uri)
var deps = module.dependencies
if (deps.length) {
if (util.indexOf(deps, uri) > -1) {
return true
}
for (var i = 0; i < deps.length; i++) {
if (isCircularWaiting(cachedModules[deps[i]], uri)) {
return true
}
}
return false
}
return false
}
function printCircularLog(stack, type) {
util.log('Found circular dependencies:', stack.join(' --> '), type)
}
// Public API
// ----------
var globalModule = new Module(util.pageUri, STATUS.COMPILED)
seajs.use = function(ids, callback) {
var preloadMods = config.preload
if (preloadMods.length) {
// Loads preload modules before all other modules.
globalModule._use(preloadMods, function() {
config.preload = []
globalModule._use(ids, callback)
})
}
else {
globalModule._use(ids, callback)
}
return seajs
}
// For normal users
seajs.define = Module._define
seajs.cache = Module.cache
seajs.find = Module._find
seajs.modify = Module._modify
// For plugin developers
seajs.pluginSDK = {
Module: Module,
util: util,
config: config
}
})(seajs, seajs._util, seajs._config)