forked from cujojs/curl
-
Notifications
You must be signed in to change notification settings - Fork 12
/
curl.js
1087 lines (921 loc) · 31.5 KB
/
curl.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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @license MIT License (c) copyright B Cavalier & J Hann */
/**
* curl (cujo resource loader)
* An AMD-compliant javascript module and resource loader
*
* curl is part of the cujo.js family of libraries (http://cujojs.com/)
*
* Licensed under the MIT License at:
* http://www.opensource.org/licenses/mit-license.php
*
* @version 0.6.3
*/
(function (global) {
"use strict";
var
version = '0.6.3',
userCfg = global['curl'],
prevCurl,
prevDefine,
doc = global.document,
head = doc && (doc['head'] || doc.getElementsByTagName('head')[0]),
// // constants / flags
msgUsingExports = {},
msgFactoryExecuted = {},
interactive = {},
// this is the list of scripts that IE is loading. one of these will
// be the "interactive" script. too bad IE doesn't send a readystatechange
// event to tell us exactly which one.
activeScripts = {},
// these are always handy :)
cleanPrototype = {},
toString = cleanPrototype.toString,
undef,
// script ready states that signify it's loaded
readyStates = { 'loaded': 1, 'interactive': interactive, 'complete': 1 },
// local cache of resource definitions (lightweight promises)
cache = {},
// preload are files that must be loaded before any others
preload = false,
// net to catch anonymous define calls' arguments (non-IE browsers)
argsNet,
// RegExp's used later, "cached" here
dontAddExtRx = /\?/,
absUrlRx = /^\/|^[^:]+:\/\//,
findLeadingDotsRx = /(\.)(\.?)(?:$|\/([^\.\/]+.*)?)/g, // /(?:^|\/)(\.)(\.?)\/?/g,
removeCommentsRx = /\/\*[\s\S]*?\*\/|(?:[^\\])\/\/.*?[\n\r]/g,
findRValueRequiresRx = /require\s*\(\s*["']([^"']+)["']\s*\)|(?:[^\\]?)(["'])/g,
cjsGetters,
core;
function noop () {}
function isType (obj, type) {
return toString.call(obj).indexOf('[object ' + type) == 0;
}
function normalizePkgDescriptor (descriptor) {
var main;
descriptor.path = removeEndSlash(descriptor['path'] || descriptor['location'] || '');
main = removeEndSlash(descriptor['main']) || 'main';
if (main.charAt(0) != '.') main = './' + main;
// trailing slashes trick reduceLeadingDots to see them as base ids
descriptor.main = reduceLeadingDots(main, descriptor.name + '/');
descriptor.mainPath = reduceLeadingDots(main, descriptor.path + '/');
descriptor.config = descriptor['config'];
return descriptor;
}
function joinPath (path, file) {
return removeEndSlash(path) + '/' + file;
}
function removeEndSlash (path) {
return path && path.charAt(path.length - 1) == '/' ? path.substr(0, path.length - 1) : path;
}
function reduceLeadingDots (childId, baseId) {
// this algorithm is similar to dojo's compactPath, which interprets
// module ids of "." and ".." as meaning "grab the module whose name is
// the same as my folder or parent folder". These special module ids
// are not included in the AMD spec but seem to work in node.js, too.
var levels, removeLevels, isRelative;
removeLevels = 1;
childId = childId.replace(findLeadingDotsRx, function (m, dot, doubleDot, remainder) {
if (doubleDot) removeLevels++;
isRelative = true;
return remainder || '';
});
// TODO: throw if removeLevels > baseId levels in debug module
if (isRelative) {
levels = baseId.split('/');
levels.splice(levels.length - removeLevels, removeLevels);
// childId || [] is a trick to not concat if no childId
return levels.concat(childId || []).join('/');
}
else {
return childId;
}
}
function pluginParts (id) {
var delPos = id.indexOf('!');
return {
resourceId: id.substr(delPos + 1),
// resourceId can be zero length
pluginId: delPos >= 0 && id.substr(0, delPos)
};
}
function Begetter () {}
function beget (parent) {
Begetter.prototype = parent;
var child = new Begetter();
Begetter.prototype = cleanPrototype;
return child;
}
function Promise () {
var self, thens, complete;
self = this;
thens = [];
function then (resolved, rejected, progressed) {
// capture calls to callbacks
thens.push([resolved, rejected, progressed]);
}
function notify (which, arg) {
// complete all callbacks
var aThen, cb, i = 0;
while ((aThen = thens[i++])) {
cb = aThen[which];
if (cb) cb(arg);
}
}
complete = function promiseComplete (success, arg) {
// switch over to sync then()
then = success ?
function (resolved, rejected) { resolved && resolved(arg); } :
function (resolved, rejected) { rejected && rejected(arg); };
// we no longer throw during multiple calls to resolve or reject
// since we don't really provide useful information anyways.
complete = noop;
// complete all callbacks
notify(success ? 0 : 1, arg);
// no more notifications
notify = noop;
// release memory
thens = undef;
};
this.then = function (resolved, rejected, progressed) {
then(resolved, rejected, progressed);
return self;
};
this.resolve = function (val) {
self.resolved = val;
complete(true, val);
};
this.reject = function (ex) {
self.rejected = ex;
complete(false, ex);
};
this.progress = function (msg) {
notify(2, msg);
}
}
function isPromise (o) {
return o instanceof Promise;
}
function when (promiseOrValue, callback, errback, progback) {
// we can't just sniff for then(). if we do, resources that have a
// then() method will make dependencies wait!
if (isPromise(promiseOrValue)) {
return promiseOrValue.then(callback, errback, progback);
}
else {
return callback(promiseOrValue);
}
}
/**
* Returns a function that when executed, executes a lambda function,
* but only executes it the number of times stated by howMany.
* When done executing, it executes the completed function. Each callback
* function receives the same parameters that are supplied to the
* returned function each time it executes. In other words, they
* are passed through.
* @private
* @param howMany {Number} must be greater than zero
* @param lambda {Function} executed each time
* @param completed {Function} only executes once when the counter
* reaches zero
* @returns {Function}
*/
function countdown (howMany, lambda, completed) {
var result;
return function () {
if (--howMany >= 0 && lambda) result = lambda.apply(undef, arguments);
// we want ==, not <=, since some callers expect call-once functionality
if (howMany == 0 && completed) completed(result);
return result;
}
}
core = {
createContext: function (cfg, baseId, depNames, isPreload) {
var def;
def = new Promise();
def.ctxId = def.id = baseId || ''; // '' == global
def.isPreload = isPreload;
def.depNames = depNames;
// functions that dependencies will use:
function toAbsId (childId) {
return reduceLeadingDots(childId, def.ctxId);
}
function toUrl (n) {
// even though internally, we don't seem to need to do
// toAbsId, the AMD spec says we need to do this for plugins.
// also, the spec states that we should not append an extension
// in this function.
return core.resolvePathInfo(toAbsId(n), cfg).url;
}
function localRequire (ids, callback) {
var cb, rvid, childDef, earlyExport;
// this is public, so send pure function
// also fixes issue #41
cb = callback && function () { callback.apply(undef, arguments[0]); };
// RValue require (CommonJS)
if (isType(ids, 'String')) {
// return resource
rvid = toAbsId(ids);
childDef = cache[rvid];
earlyExport = isPromise(childDef) && childDef.exports;
if (!(rvid in cache)) {
// this should only happen when devs attempt their own
// manual wrapping of cjs modules or get confused with
// the callback syntax:
throw new Error('Module not resolved: ' + rvid);
}
if (cb) {
throw new Error('require(id, callback) not allowed');
}
return earlyExport || childDef;
}
else {
// use same id so that relative modules are normalized correctly
when(core.getDeps(core.createContext(cfg, def.ctxId, ids, isPreload)), cb);
}
}
def.require = localRequire;
localRequire['toUrl'] = toUrl;
def.toAbsId = toAbsId;
return def;
},
createResourceDef: function (cfg, id, isPreload, optCtxId) {
var def, origResolve, execute;
def = core.createContext(cfg, id, undef, isPreload);
def.ctxId = optCtxId == undef ? id : optCtxId;
origResolve = def.resolve;
// using countdown to only execute definition function once
execute = countdown(1, function (deps) {
def.deps = deps;
try {
return core.executeDefFunc(def);
}
catch (ex) {
def.reject(ex);
}
});
// intercept resolve function to execute definition function
// before resolving
def.resolve = function resolve (deps) {
when(isPreload || preload, function () {
origResolve((cache[def.id] = execute(deps)));
});
};
// track exports
def.exportsReady = function executeFactory (deps) {
when(isPreload || preload, function () {
// only resolve early if we also use exports (to avoid
// circular dependencies). def.exports will have already
// been set by the getDeps loop before we get here.
if (def.exports) {
execute(deps);
def.progress(msgFactoryExecuted);
}
});
};
return def;
},
createPluginDef: function (cfg, id, isPreload, ctxId) {
var def;
def = core.createContext(cfg, id, undef, isPreload);
def.ctxId = ctxId;
return def;
},
getCjsRequire: function (def) {
return def.require;
},
getCjsExports: function (def) {
return def.exports || (def.exports = {});
},
getCjsModule: function (def) {
var module = def.module;
if (!module) {
module = def.module = {
'id': def.id,
'uri': core.getDefUrl(def),
'exports': core.getCjsExports(def)
};
module.exports = module['exports']; // oh closure compiler!
}
return module;
},
getDefUrl: function (def) {
// note: don't look up an anon module's id from it's own toUrl cuz
// the parent's config was used to find this module
// the toUrl fallback is for named modules in built files
// which must have absolute ids.
return def.url || (def.url = core.checkToAddJsExt(def.require['toUrl'](def.id)));
},
config: function (cfg) {
var hasCfg,
apiName, apiObj, defineName, defineObj, define;
/*
* !cfg && !prevCurl: define global curl
* !cfg && prevCurl: define global curl (fix at next config call)
* cfg && !prevCurl: define apiObj[apiName] || global curl
* cfg && prevCurl: define apiObj[apiName] && restore prevCurl || throw
* (clear prevCurl if apiObj[apiName])
*/
hasCfg = cfg;
if (!cfg) cfg = {};
// allow dev to rename/relocate curl() to another object
apiName = cfg['apiName'];
apiObj = cfg['apiContext'];
// if the dev is overwriting an existing curl()
if (apiObj || apiName ? apiObj[apiName] : prevCurl && hasCfg) {
throw new Error((apiName || 'curl') + ' already exists');
}
(apiObj || global)[apiName || 'curl'] = _curl;
// allow dev to rename/relocate define() to another object
defineName = cfg['defineName'];
defineObj = cfg['defineContext'];
if (defineObj || defineName ? defineObj[defineName] : prevDefine) {
throw new Error((defineName|| 'define') + 'already exists');
}
(defineObj || global)[defineName || 'define'] = define = function () {
// wrap inner _define so it can be replaced without losing define.amd
var args = core.fixArgs(arguments);
_define(args);
};
// indicate our capabilities:
define['amd'] = { 'plugins': true, 'jQuery': true, 'curl': version };
// switch to re-runnable config
if (hasCfg) core.config = core.moreConfig;
return core.moreConfig(cfg);
},
moreConfig: function (cfg) {
var pluginCfgs, apiName, apiContext, defineName, defineContext;
// set defaults and convert from closure-safe names
cfg.baseUrl = cfg['baseUrl'] || '';
cfg.pluginPath = 'pluginPath' in cfg ? cfg['pluginPath'] : 'curl/plugin';
// create object to hold path map.
// each plugin and package will have its own pathMap, too.
cfg.pathMap = {};
pluginCfgs = cfg.plugins = cfg['plugins'] || {};
// temporary arrays of paths. this will be converted to
// a regexp for fast path parsing.
cfg.pathList = [];
// normalizes path/package info and places info on either
// the global cfg.pathMap or on a plugin-specific altCfg.pathMap.
// also populates a pathList on cfg or plugin configs.
function fixAndPushPaths (coll, isPkg) {
var id, pluginId, data, parts, currCfg, info;
for (var name in coll) {
data = coll[name];
// grab the package id, if specified. default to
// property name.
data.name = data['id'] || data['name'] || name;
currCfg = cfg;
// don't remove `|| name` since data may be a string, not an object
parts = pluginParts(removeEndSlash(data.name || name));
id = parts.resourceId;
pluginId = parts.pluginId;
if (pluginId) {
// plugin-specific path
currCfg = pluginCfgs[pluginId];
if (!currCfg) {
currCfg = pluginCfgs[pluginId] = beget(cfg);
currCfg.pathMap = beget(cfg.pathMap);
currCfg.pathList = [];
}
// remove plugin-specific path from coll
delete coll[name];
}
if (isPkg) {
info = normalizePkgDescriptor(data);
}
else {
info = { path: removeEndSlash(data) };
}
info.specificity = id.split('/').length;
if (id) {
currCfg.pathMap[id] = info;
currCfg.pathList.push(id);
}
else {
// naked plugin name signifies baseUrl for plugin
// resources. baseUrl could be relative to global
// baseUrl.
currCfg.baseUrl = core.resolveUrl(data, cfg);
}
}
}
// adds the path matching regexp onto the cfg or plugin cfgs.
function convertPathMatcher (cfg) {
var pathMap = cfg.pathMap;
cfg.pathRx = new RegExp('^(' +
cfg.pathList.sort(function (a, b) { return pathMap[a].specificity < pathMap[b].specificity; } )
.join('|')
.replace(/\/|\./g, '\\$&') +
')(?=\\/|$)'
);
delete cfg.pathList;
}
// fix all paths and packages
fixAndPushPaths(cfg['paths'], false);
fixAndPushPaths(cfg['packages'], true);
// create search regex for each path map
for (var p in pluginCfgs) {
var pathList = pluginCfgs[p].pathList;
if (pathList) {
pluginCfgs[p].pathList = pathList.concat(cfg.pathList);
convertPathMatcher(pluginCfgs[p]);
}
}
convertPathMatcher(cfg);
core.checkPreloads(cfg);
return cfg;
},
checkPreloads: function (cfg) {
var preloads;
preloads = cfg && cfg['preloads'];
if (preloads && preloads.length > 0) {
// chain from previous preload, if any.
// TODO: revisit when doing package-specific configs.
when(preload, function () {
preload = core.getDeps(core.createContext(cfg, undef, preloads, true));
});
}
},
resolvePathInfo: function (absId, cfg, forPlugin) {
// searches through the configured path mappings and packages
var pathMap, pathInfo, ctxId, path, pkgCfg, found;
pathMap = cfg.pathMap;
if (forPlugin && cfg.pluginPath && absId.indexOf('/') < 0 && !(absId in pathMap)) {
// prepend plugin folder path, if it's missing and path isn't in pathMap
// Note: this munges the concepts of ids and paths for plugins,
// but is generally safe since it's only for non-namespaced
// plugins (plugins without path or package info).
ctxId = absId = joinPath(cfg.pluginPath, absId);
}
if (!absUrlRx.test(absId)) {
path = absId.replace(cfg.pathRx, function (match) {
pathInfo = pathMap[match] || {};
found = true;
pkgCfg = pathInfo.config;
// if pathInfo.main and match == absId, this is a main module
if (pathInfo.main && match == absId) {
ctxId = pathInfo.main;
return pathInfo.mainPath;
}
// if pathInfo.path return pathInfo.path
else {
return pathInfo.path || '';
}
});
}
else {
path = absId;
}
return {
ctxId: ctxId || absId,
config: pkgCfg || userCfg,
url: core.resolveUrl(path, cfg)
};
},
resolveUrl: function (path, cfg) {
var baseUrl = cfg.baseUrl;
return baseUrl && !absUrlRx.test(path) ? joinPath(baseUrl, path) : path;
},
checkToAddJsExt: function (url) {
// don't add extension if a ? is found in the url (query params)
// i'd like to move this feature to a moduleLoader
return url + (dontAddExtRx.test(url) ? '' : '.js');
},
loadScript: function (def, success, failure) {
// script processing rules learned from RequireJS
// insert script
var el = doc.createElement('script');
// initial script processing
function process (ev) {
ev = ev || global.event;
// detect when it's done loading
if (ev.type == 'load' || readyStates[el.readyState]) {
delete activeScripts[def.id];
// release event listeners
el.onload = el.onreadystatechange = el.onerror = ''; // ie cries if we use undefined
success();
}
}
function fail (e) {
// some browsers send an event, others send a string,
// but none of them send anything useful, so just say we failed:
failure(new Error('Syntax or http error: ' + def.url));
}
// set type first since setting other properties could
// prevent us from setting this later
// actually, we don't even need to set this at all
//el.type = 'text/javascript';
// using dom0 event handlers instead of wordy w3c/ms
el.onload = el.onreadystatechange = process;
el.onerror = fail;
// js! plugin uses alternate mimetypes
el.type = def.mimetype || 'text/javascript';
// TODO: support other charsets?
el.charset = 'utf-8';
el.async = !def.order;
el.src = def.url;
// loading will start when the script is inserted into the dom.
// IE will load the script sync if it's in the cache, so
// indicate the current resource definition if this happens.
activeScripts[def.id] = el;
// use insertBefore to keep IE from throwing Operation Aborted (thx Bryan Forbes!)
head.insertBefore(el, head.firstChild);
},
extractCjsDeps: function (defFunc) {
// Note: ignores require() inside strings and comments
var source, ids = [], currQuote;
// prefer toSource (FF) since it strips comments
source = typeof defFunc == 'string' ?
defFunc :
defFunc.toSource ? defFunc.toSource() : defFunc.toString();
// remove comments, then look for require() or quotes
source.replace(removeCommentsRx, '').replace(findRValueRequiresRx, function (m, id, qq) {
// if we encounter a quote
if (qq) {
currQuote = currQuote == qq ? undef : currQuote;
}
// if we're not inside a quoted string
else if (!currQuote) {
ids.push(id);
}
return m; // uses least RAM/CPU
});
return ids;
},
fixArgs: function (args) {
// resolve args
// valid combinations for define:
// (string, array, object|function) sax|saf
// (array, object|function) ax|af
// (string, object|function) sx|sf
// (object|function) x|f
var id, deps, defFunc, defFuncArity, len, cjs;
len = args.length;
defFunc = args[len - 1];
defFuncArity = isType(defFunc, 'Function') ? defFunc.length : -1;
if (len == 2) {
if (isType(args[0], 'Array')) {
deps = args[0];
}
else {
id = args[0];
}
}
else if (len == 3) {
id = args[0];
deps = args[1];
}
// Hybrid format: assume that a definition function with zero
// dependencies and non-zero arity is a wrapped CommonJS module
if (!deps && defFuncArity > 0) {
cjs = true;
deps = ['require', 'exports', 'module'].slice(0, defFuncArity).concat(core.extractCjsDeps(defFunc));
}
return {
id: id,
deps: deps || [],
res: defFuncArity >= 0 ? defFunc : function () { return defFunc; },
cjs: cjs
};
},
executeDefFunc: function (def) {
var resource, moduleThis;
// the force of AMD is strong so anything returned
// overrides exports.
// node.js assumes `this` === `exports` so we do that
// for all cjs-wrapped modules, just in case.
// also, use module.exports if that was set
// (node.js convention).
// note: if .module exists, .exports exists.
moduleThis = def.cjs ? def.exports : undef;
resource = def.res.apply(moduleThis, def.deps);
if (resource === undef && def.exports) {
// note: exports will equal module.exports unless
// module.exports was reassigned inside module.
resource = def.module ? (def.exports = def.module.exports) : def.exports;
}
return resource;
},
defineResource: function (def, args) {
def.res = args.res;
def.cjs = args.cjs;
def.depNames = args.deps;
core.getDeps(def);
},
getDeps: function (parentDef) {
var i, names, deps, len, dep, completed, name,
exportCollector, resolveCollector;
deps = [];
names = parentDef.depNames;
len = names.length;
if (names.length == 0) allResolved();
function collect (dep, index, alsoExport) {
deps[index] = dep;
if (alsoExport) exportCollector(dep, index);
}
// reducer-collectors
exportCollector = countdown(len, collect, allExportsReady);
resolveCollector = countdown(len, collect, allResolved);
// initiate the resolution of all dependencies
// Note: the correct handling of early exports relies on the
// fact that the exports pseudo-dependency is always listed
// before other module dependencies.
for (i = 0; i < len; i++) {
name = names[i];
// is this "require", "exports", or "module"?
if (name in cjsGetters) {
// a side-effect of cjsGetters is that the cjs
// property is also set on the def.
resolveCollector(cjsGetters[name](parentDef), i, true);
// if we are using the `module` or `exports` cjs variables,
// signal any waiters/parents that we can export
// early (see progress callback in getDep below).
// note: this may fire for `require` as well, if it
// is listed after `module` or `exports` in teh deps list,
// but that is okay since all waiters will only record
// it once.
if (parentDef.exports) {
parentDef.progress(msgUsingExports);
}
}
// check for blanks. fixes #32.
// this helps support yepnope.js, has.js, and the has! plugin
else if (!name) {
resolveCollector(undef, i, true);
}
// normal module or plugin resource
else {
getDep(name, i);
}
}
return parentDef;
function getDep (name, index) {
var resolveOnce, exportOnce, childDef, earlyExport;
resolveOnce = countdown(1, function (dep) {
exportOnce(dep);
resolveCollector(dep, index);
});
exportOnce = countdown(1, function (dep) {
exportCollector(dep, index);
});
// get child def / dep
childDef = core.fetchDep(name, parentDef);
// check if childDef can export. if it can, then
// we missed the notification and it will never fire in the
// when() below.
earlyExport = isPromise(childDef) && childDef.exports;
if (earlyExport) {
exportOnce(earlyExport);
}
when(childDef,
resolveOnce,
parentDef.reject,
parentDef.exports && function (msg) {
// messages are only sent from childDefs that support
// exports, and we only notify parents that understand
// exports too.
if (childDef.exports) {
if (msg == msgUsingExports) {
// if we're using exports cjs variable on both sides
exportOnce(childDef.exports);
}
else if (msg == msgFactoryExecuted) {
resolveOnce(childDef.exports);
}
}
}
);
}
function allResolved () {
parentDef.resolve(deps);
}
function allExportsReady () {
parentDef.exportsReady && parentDef.exportsReady(deps);
}
},
fetchResDef: function (def) {
// ensure url is computed
core.getDefUrl(def);
core.loadScript(def,
function () {
var args = argsNet;
argsNet = undef; // reset it before we get deps
// if our resource was not explicitly defined with an id (anonymous)
// Note: if it did have an id, it will be resolved in the define()
if (def.useNet !== false) {
// if !args, nothing was added to the argsNet
if (!args || args.ex) {
def.reject(new Error(((args && args.ex) || 'define() missing or duplicated: ' + def.url)));
}
else {
core.defineResource(def, args);
}
}
},
def.reject
);
return def;
},
fetchDep: function (depName, parentDef) {
var toAbsId, isPreload, parts, mainId, loaderId, pluginId,
resId, pathInfo, def, tempDef, resCfg;
toAbsId = parentDef.toAbsId;
isPreload = parentDef.isPreload;
// check for plugin loaderId
parts = pluginParts(depName);
// resId is not normalized since the plugin may need to do it
resId = parts.resourceId;
// get id of first resource to load (which could be a plugin)
mainId = toAbsId(parts.pluginId || resId);
pathInfo = core.resolvePathInfo(mainId, userCfg, !!parts.pluginId);
// get custom module loader from package config if not a plugin
// TODO: figure out how to make module loaders work with plugins
if (parts.pluginId) {
loaderId = mainId;
}
else {
loaderId = pathInfo.config['moduleLoader'];
if (loaderId) {
// since we're not using toAbsId, transformers must be absolute
resId = mainId;
mainId = loaderId;
pathInfo = core.resolvePathInfo(loaderId, userCfg);
}
}
// find resource definition. ALWAYS check via (id in cache) b/c
// falsey values could be in there.
def = cache[mainId];
if (!(mainId in cache)) {
def = cache[mainId] = core.createResourceDef(pathInfo.config, mainId, isPreload, pathInfo.ctxId);
def.url = core.checkToAddJsExt(pathInfo.url);
core.fetchResDef(def);
}
// plugin or transformer
if (mainId == loaderId) {
// we need to use depName until plugin tells us normalized id.
// if the plugin changes the id, we need to consolidate
// def promises below. Note: exports objects will be different
// between pre-normalized and post-normalized defs! does this matter?
// don't put this resource def in the cache because if the
// resId doesn't change, the check if this is a new
// normalizedDef (below) will think it's already being loaded.
tempDef = /*cache[depName] =*/ new Promise();
// note: this means moduleLoaders can store config info in the
// plugins config, too.
resCfg = userCfg.plugins[loaderId] || userCfg;
// wait for plugin resource def
when(def, function(plugin) {
var normalizedDef, fullId, dynamic;
dynamic = plugin['dynamic'];
// check if plugin supports the normalize method
if ('normalize' in plugin) {
// dojo/has may return falsey values (0, actually)
resId = plugin['normalize'](resId, toAbsId, resCfg) || '';
}
else {
resId = toAbsId(resId);
}
// use the full id (loaderId + id) to id plugin resources
// so multiple plugins may each process the same resource
// resId could be blank if the plugin doesn't require any (e.g. "domReady!")
fullId = loaderId + '!' + resId;
normalizedDef = cache[fullId];
// if this is our first time fetching this (normalized) def
if (!(fullId in cache)) {
// because we're using resId, plugins, such as wire!,
// can use paths relative to the resource
normalizedDef = core.createPluginDef(resCfg, fullId, isPreload, resId);
// don't cache non-determinate "dynamic" resources (or non-existent resources)
if (!dynamic) {
cache[fullId] = normalizedDef;
}
// curl's plugins prefer to receive a deferred,
// but to be compatible with AMD spec, we have to
// piggy-back on the callback function parameter:
var loaded = function (res) {
normalizedDef.resolve(res);
if (!dynamic) cache[fullId] = res;
};
loaded['resolve'] = loaded;
loaded['reject'] = normalizedDef.reject;
// load the resource!
plugin.load(resId, normalizedDef.require, loaded, resCfg);
}
// chain defs (resolve when plugin.load executes)
if (tempDef != normalizedDef) {
when(normalizedDef, tempDef.resolve, tempDef.reject, tempDef.progress);
}
}, tempDef.reject);
}
// return tempDef if this is a plugin-based resource
return tempDef || def;
},
getCurrentDefName: function () {
// IE marks the currently executing thread as "interactive"
// Note: Opera lies about which scripts are "interactive", so we
// just have to test for it. Opera provides a true browser test, not
// a UA sniff, thankfully.
// learned this trick from James Burke's RequireJS
var def;
if (!isType(global.opera, 'Opera')) {
for (var d in activeScripts) {
if (readyStates[activeScripts[d].readyState] == interactive) {
def = d;
break;
}
}
}
return def;
}
};
// hook-up cjs free variable getters
cjsGetters = {'require': core.getCjsRequire, 'exports': core.getCjsExports, 'module': core.getCjsModule};
function _curl (/* various */) {
var args = [].slice.call(arguments);
// extract config, if it's specified
if (isType(args[0], 'Object')) {
userCfg = core.config(args.shift());
}
// thanks to Joop Ringelberg for helping troubleshoot the API
function CurlApi (ids, callback, waitFor) {
var then, ctx;
ctx = core.createContext(userCfg, undef, [].concat(ids));
this['then'] = then = function (resolved, rejected) {
when(ctx,
// return the dependencies as arguments, not an array