-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKModule.js
1385 lines (1115 loc) · 28.9 KB
/
KModule.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
var eval1= function(str){
return eval(str)
}
var Next= require("./NextJavascript")
var fs= require("fs")
var Os= require("os")
var Path= require("path")
var Module = require("module").Module
var Url= require('url')
var httpr={}
var Mod= exports.Module= function(){
}
Mod._cache = {}
Mod._cacherequire = {}
Mod._cacheresolve= {}
Mod._virtualfile= {}
Mod._npmcache= {}
Mod.cachetime= 5000
var createDefault=function(options){
var defoptions= Mod.defaultOptions || exports.defaultOptions
options= options || {}
for(var id in defoptions){
if(options[id] === undefined)
options[id]= defoptions[id]
}
return options
}
Module._originalResolveFilename = Module._resolveFilename
var getKModule= function(filename){
var nmod={
filename: filename,
require : Mod.require,
import : Mod.import,
addVirtualFile : Mod.addVirtualFile,
extensions : Mod.extensions,
replaceSyncRequire : Mod.replaceSyncRequire,
removeCached : Mod.removeCached
}
return nmod
}
var _getCachedFilename= function(uri, options){
options= options || {}
if(!uri.protocol){
uri.protocol= "file:"
uri.pathname= Path.normalize(uri.pathname)
}
var name= (options.mask || uri.format()).replace(/\:|\?/g, '').replace(/\\/g, '/')
if(uri.search){
name += uri.search.replace(/\:|\?|\\/g, '')
}
var parts= name.split("/")
parts= parts.filter(function(a){
return !!a
})
if(options.virtual){
parts.shift()
}
var full= parts.join(Path.sep)
var kawi_dir= Path.join(Os.homedir(), ".kawi")
var file_dir= Path.join(kawi_dir, full)
var cache_dir= Path.dirname(file_dir)
return {
kawi_dir: kawi_dir,
file_dir: file_dir,
cache_dir: cache_dir ,
parts: parts,
full: full
}
}
var getCachedFilenameSync= function(uri, options){
var result= _getCachedFilename(uri, options)
var kawi_dir= result.kawi_dir
var cache_dir= result.cache_dir
var file_dir= result.file_dir
var parts= result.parts
var full= result.full
var part
try{
if(fs.accessSync(cache_dir, fs.constants.F_OK)){
return file_dir
}
}catch(e){}
var path= kawi_dir
try{
fs.accessSync(path, fs.constants.F_OK)
}catch(e){
fs.mkdirSync(path)
}
for(var i=0;i<parts.length-1;i++){
part= parts[i]
path= Path.join(path, part)
try{
fs.accessSync(path, fs.constants.F_OK)
}catch(e){
fs.mkdirSync(path)
}
}
return file_dir
}
var getCachedFilename= function(uri, options){
var result= _getCachedFilename(uri, options)
var kawi_dir= result.kawi_dir
var cache_dir= result.cache_dir
var file_dir= result.file_dir
var parts= result.parts
var full= result.full
return new Promise(function(resolve, reject){
var i= 0, part
var createTree= function(path){
try{
if(!path){
path= kawi_dir
}
fs.access(path, fs.constants.F_OK, function(err){
if(err){
fs.mkdir(path, function(err){
if(err) return reject(err)
part= parts[i]
if(i == parts.length - 1)
return resolve(file_dir)
i++
return createTree(Path.join(path, part))
})
}else{
part= parts[i]
if(i == parts.length - 1)
return resolve(file_dir)
i++
return createTree(Path.join(path, part))
}
})
}catch(e){
reject(e)
}
}
fs.access(cache_dir, fs.constants.F_OK, function(err){
if(err) return createTree()
return resolve(file_dir)
})
})
}
var builtinModules = require("module").builtinModules
Module._resolveFilename= function(name,parent){
//console.info(Mod._virtualfile)
if(name.startsWith("___kawi__internal__")){
return name
}
else if(Mod._virtualfile[name]){
return name
}
else if(builtinModules.indexOf(name) >= 0){
return name
}
else{
if(parent && parent.filename && parent.filename.startsWith("/virtual")){
// Allow resolve
result= Mod.resolveVirtual(name,parent)
if(!result){
return Module._originalResolveFilename.apply(Module, arguments)
}
return result
}
}
return Module._originalResolveFilename.apply(Module, arguments)
}
Mod.resolveVirtual= function(name, parent){
var possibles=[]
var path,dirname, path1
if(name.startsWith("/virtual")){
possibles.push(name)
}
else{
dirname= Path.dirname(parent.filename)
if(name.startsWith("./") || name.startsWith("../")){
path= Path.normalize(Path.join(dirname, name))
possibles.push(path)
}
else{
path= Path.join(dirname, "node_modules", name)
possibles.push(path)
path1= dirname
while(path1 && path1 != "/virtual" && path1 != "/"){
path1= Path.dirname(path1)
path= Path.join(path1, "node_modules", name)
possibles.push(path)
}
}
}
var possiblesFromFile= function(name){
var possibles=[]
for(var ext in Mod.extensions){
possibles.push(name+ext)
}
return possibles
}
var possiblesFromFolder= function(name){
var possibles={}, path, data, pjson, rpossibles=[]
// package json?
path= Path.join(name,"package.json")
data= Mod._virtualfile[path]
if(data){
if(typeof data == "function")
data= data()
pjson= data.content
pjson= JSON.parse(data.content)
if(pjson.main){
path= Path.normalize(Path.join(name, pjson.main))
possibles[path]= true
for(var ext in Mod.extensions){
possibles[path+ext]= true
}
}
}
possibles[Path.join(name,"index.js")]= true
for(var ext in Mod.extensions){
possibles[Path.join(name,"index"+ext)]= true
}
for(var id in possibles){
rpossibles.push(id)
}
return rpossibles
}
var processPossibles= function(possibles, deep=0){
var possible, vfile, result, possibles1
for(var i=0;i<possibles.length;i++){
possible= possibles[i]
vfile= Mod._virtualfile[possible]
if(vfile){
if(typeof vfile == "function")
vfile= vfile()
if(vfile.stat.isdirectory){
possibles1= possiblesFromFolder(possible)
result= processPossibles(possibles1, deep+1)
if(result)
return result
}
else{
if(vfile.content){
return possible
}
}
}
else{
if(deep==0){
possibles1= possiblesFromFile(possible)
result= processPossibles(possibles1, deep+1)
if(result)
return result
}
}
}
}
path= processPossibles(possibles)
//if(!path)
// throw new Error("Failed resolve " + name + " from " + parent.filename)
return path
}
var validateFileUrl= function(file){
var uri = Url.parse(file)
if (uri.protocol) {
if (uri.protocol != "http:" && uri.protocol != "npm:" && uri.protocol != "npmi:" && uri.protocol != "https:" && uri.protocol != "file:") {
throw new Error("Protocol " + uri.protocol + " not supported")
}
}
return uri
}
Mod.replaceSyncRequire= function(originalrequire, parent){
return function(name){
if(builtinModules.indexOf(name) >= 0)
return originalrequire(name)
var file= Module._resolveFilename(name, parent)
if(file.startsWith("/virtual/")){
return Mod.requireVirtualSync(file)
}else{
return originalrequire(name,parent)
}
}
}
Mod.requireVirtualSync= function(file){
var module= Mod._cacherequire[file]
if(module){
return module.exports
}
var ast= Mod.compileSync(file)
var nmod= getKModule(file)
module = new Module(file)
module.exports = {}
module.filename= file
module.KModule= nmod
Module._cache[file] = module
var code= "exports.__kawi= function(KModule){\n" +
"\trequire= KModule.replaceSyncRequire(require,module);\n"
+ ast.code + "\n}"
module._compile(code, file)
module.exports.__kawi(nmod)
Mod._cacherequire[file] = module
return module.exports
}
Mod.compileSync= function(file, options){
var vfile= Mod._virtualfile[file]
if(typeof vfile == "function"){
vfile= vfile()
}
var ext= Path.extname(file)
var cached2, stat1, stat2, compile , transpilerOptions, ast
var uri = validateFileUrl(file)
if(ext == ".json"){
ast={
"code": "module.exports=" + vfile.content
}
return ast
}
else{
cached2= getCachedFilenameSync(uri,{
virtual: true
})
try{
stat1= fs.statSync(cached2)
}catch(e){
if(e.code != "ENOENT"){
throw e
}
stat1= null
}
if(stat1){
stat2= vfile.stat
if(!(stat2.mtime instanceof Date))
stat2.mtime= new Date(stat2.mtime)
if(stat1.mtime.getTime() < stat2.mtime.getTime())
compile= true
}else{
compile= true
}
if(compile){
for(var ext in Mod.extensions){
if(file.endsWith(ext)){
if( typeof Mod.extensions[ext] == "function"){
ast= Mod.extensions[ext](vfile.content, file, options)
//value= ast.code
}
}
}
if(ast && ast.transpilerOptions){
transpilerOptions= ast.transpilerOptions
}else{
transpilerOptions = {
presets: ['es2015', 'es2016', 'es2017'],
sourceMaps: true,
comments: true,
filename: file
}
if(file.endsWith(".ts")){
transpilerOptions.presets=['typescript']
}
}
if(!ast || ast.transpile !== false)
ast= Next.transpile(ast ? ast.code : vfile.content, transpilerOptions)
if(ast){
str= JSON.stringify(ast)
fs.writeFileSync(cached2, str)
delete ast.options
ast.time= Date.now()
Mod._cache[file]= ast
}
return ast
}
else{
ast= JSON.parse(fs.readFileSync(cached2, 'utf8'))
return ast
}
}
}
/** resolve a file in current module, and require */
exports.import= Mod.import= function(file, options){
var uri2 , promise, original, filename
original= file
options= createDefault(options)
if(builtinModules.indexOf(file) >= 0){
return require(file)
}
var uri = validateFileUrl(file)
filename = this.filename || "current"
var getBetter= function(){
if(file.startsWith("/virtual")){
file= Mod.resolveVirtual(file,{
filename: options.parent
})
if(!file){
throw new Error("Cannot resolve " + original + " from " + filename)
}
return Mod.require(file,options)
}
promise = new Promise(function (resolve, reject) {
var ids = Object.keys(Mod.extensions)
var i = -1
var f = function (file, ext) {
var cfile = file
if (ext) {
cfile = file + ext
}
fs.access(cfile, fs.constants.F_OK, function (err) {
if (err) {
// test next
i++
ext = ids[i]
if (!ext)
return reject(new Error("Cannot resolve " + original + " from " + filename))
return f(file, ext)
}
return resolve(Mod.require(cfile, options))
})
}
f(file)
})
return promise
}
if(uri.protocol || Path.isAbsolute(file)){
if(uri.protocol && uri.protocol != "file:"){
return Mod.require(file, options)
}
else{
if(uri.protocol)
file= Url.fileURLToPath(file)
file= Path.normalize(file)
}
return getBetter()
}
else{
// create a path from parent
if(!this.filename){
// is good get from cwd?
this.filename= options.parent
if(!this.filename)
throw new Error("Cannot resolve file or URL: " + file)
}
if (file.startsWith("./") || file.startsWith("../")) {
uri2 = Url.parse(this.filename)
if (uri2.protocol) {
if(file.startsWith("./"))
file= file.substring(2)
file = Url.resolve(this.filename, file)
return Mod.require(file, options)
}
else{
// find this or with extensions
file= Path.join(Path.dirname(this.filename), file)
return getBetter()
}
}
else {
file= require.resolve(file)
return Mod.require(file, options)
}
}
}
/** Allow create more extensions */
Mod.extensions= {
".json": null,
".js": null,
".es6": null
}
/** Allow importing modules in KModule way by default, with import keyword */
exports.injectImport= Mod.injectImport= function(){
Mod.__injected= true
}
Mod.__num= 0
var changeSource= function(source){
// this method works with transpiled code
// that is known the generated style, can determine the modules imported with `import`
var lines= source.split(/\r\n|\r|\n/g)
var line
var maybeRequire= []
var reg= /\=?\s?(_interopRequire.*\()?require\((.*)\)\)?/
var esm = false , req, required=[]
for(var i=0;i<lines.length;i++){
line= lines[i]
if(reg.test(line)){
maybeRequire.push({
line: line,
index: i
})
}
else if(line.startsWith("function _interopRequire")){
// good, is a ESM module
esm= true
break
}
}
var num,json,code
num= Mod.__num++
if(esm){
for(var i=0;i<maybeRequire.length;i++){
req= maybeRequire[i]
mod= null
req.line= req.line.replace(reg,function(a,_, c){
var b= c
if(c.endsWith(")"))
c= c.substring(0,c.length-1)
c= c.substring(1, c.length-1)
mod= c
return a.replace(b, b.replace(c, "___kawi__internal__" + num + "MOD_" + c + "_" + i))
})
if(mod){
if(builtinModules.indexOf(mod) < 0){
required.push(mod)
lines[req.index]= req.line
}
}
}
}
if(required.length){
source= lines.join("\n")
// create a preloader function
json= JSON.stringify(required)
code= "function(KModule){\n"
code+= " var resolve, reject\n"
code+= " var required= " + json + "\n"
code+= " var num=" + num +"\n"
code+= " var i=-1\n"
code+= " var __load= " + (function(){
i++
var mod= required[i]
if(!mod) return resolve()
var unq = "___kawi__internal__" + num + "MOD_" + mod + "_" + i
var promise= KModule.import(mod, {
uid: unq
})
promise.then(__load).catch(reject)
}).toString() + "\n"
code+= " var promise= new Promise(function(a,b){ resolve=a; reject=b; })\n"
code+= " __load()\n"
code+= " return promise\n"
code+= "}"
}
var imports={}
imports.mods= required
imports.inject= code
imports.source= source + (code ? ("\nvar ___kawi__async = " + code) : "")
return imports
}
// this method is not good
var __bad__changeSource= function(source){
var reg = /import\s+.+\s+from\s+(\"|\')(.+)(\"|\')(\;|\r|\n)/g
var num= Mod.__num++
var mod, op
var unq = "___kawi__internal__" + Date.now().toString(28) + num
var cid= -1
var imports= {
unq:unq,
mods:[]
}
source= source.replace(reg, function (a, b, c, d) {
try{
var name = eval(b + c + d)
if(builtinModules.indexOf(name) >= 0)
return a
imports.mods.push(name)
cid++
return a.replace(b+c+d, "'"+ unq + "." + cid + ".js'")
}catch(e){
return a
}
})
if(imports.mods && imports.mods.length){
var morecode= ['var ___kawi__async= async function(KModule){']
for(var i=0;i<imports.mods.length;i++){
mod= imports.mods[i]
op= {
uid: unq + "." + i + ".js"
}
morecode.push("\tawait KModule.import("+JSON.stringify(mod)+", "+ JSON.stringify(op) +")")
}
morecode.push("}")
imports.inject= morecode.join("\n")
imports.source= source + "\n" + imports.inject
}
else{
imports.source= source
//console.info("Source: ", source)
}
return imports
}
var asynchelper = "function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\n\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }"
var loadInjectImportFunc= function(ast){
var code, injectCode, ucode
if(!ast.injectCode){
var i= ast.code.indexOf("var ___kawi__async =")
if(i >= 0){
code= ast.code.substring(0,i)
injectCode= ast.code.substring(i+20)
ast.code = code
ast.injectCode= injectCode.trim()
i= ast.injectCode.indexOf("function")
ast.injectCode= ast.injectCode.substring(i)
}
}
if(ast.injectCode && !ast.inject){
if(ast.injectCode.indexOf("regeneratorRuntime") >= 0){
ucode= "(function(){" + asynchelper + "\n\nreturn " + ast.injectCode + ";\n})()"
ast.inject= eval(ucode)
}else{
ucode= "(" + ast.injectCode + ")"
ast.inject= eval(ucode)
}
}
}
/** Remove a module from cache */
exports.removeCached= Mod.removeCached= function(file){
var cached = Mod._cacherequire[file]
if(cached){
if (cached.__kawi_uid && cached.__kawi_uid.length){
for (var i = 0; i < cached.__kawi_uid.length;i++){
delete Module._cache[cached.__kawi_uid[i]]
}
}
delete Module._cache[file]
delete Mod._cacherequire[file]
}
delete Mod._cache[file]
}
exports.addVirtualFile= Mod.addVirtualFile= function(file, data){
var path= Path.join("/virtual", file)
Mod._virtualfile[path]= data
data.time= Date.now()
}
var getMask= function(url, value){
if(value.mask){
return value.mask
}
var name= Path.basename(value.redirect)
if(url.endsWith(value)){
return url
}
else{
return url + "/" + name
}
}
/** require a module (file or url) */
exports.require= Mod.require= function(file, options){
options=options || {}
var cached = Mod._cacherequire[file]
var promise, promise2 , generate, module
var generate= function(ast, resolve, reject){
module = new Module(file)
module.exports = {}
module.filename= file
var nmod = getKModule(file)
module.KModule = nmod
module.__kawi_time= Date.now()
var continue1 = function () {
//console.info("exports.__kawi= function(KModule){" + ast.code + "}")
module._compile("exports.__kawi= function(KModule){\n" +
"\trequire= KModule.replaceSyncRequire(require,module);\n"
+ ast.code + "\n}", file)
// custom mod for each file
Module._cache[file] = module
Mod._cacherequire[file] = module
module.__kawi_uid = {}
if (options.uid)
module.__kawi_uid[options.uid] = true
var maybePromise = module.exports.__kawi(nmod)
if(module.exports && module.exports.then){
module.exports.then(function(result){
module.exports= result
Module._cache[options.uid || "_internal_kawi_last.js"] = module
resolve(module.exports)
}).catch(reject)
}
else{
Module._cache[options.uid || "_internal_kawi_last.js"] = module
return resolve(module.exports)
}
}
if (ast.injectCode && !ast.inject) {
// inject the code
loadInjectImportFunc(ast)
}
if (ast.inject) {
ast.inject(nmod).then(function () {
continue1()
}).catch(reject)
} else {
continue1()
}
}
if(cached){
var returnData= function(){
Module._cache[file] = cached
if (options.uid)
cached.__kawi_uid[options.uid] = true
Module._cache[options.uid || "_internal_kawi_last.js"] = cached
return cached.exports
}
if (cached.exports.kawixDynamic && ((Date.now() - cached.__kawi_time) >
(cached.exports.kawixDynamic.time || Mod.cachetime))){
// exported as dynamicMethod
// get if changed ...
options.ignoreonunchanged= true
promise = Mod.compile(file, options)
promise2 = new Promise(function (resolve, reject) {
promise.then(function(ast){
if(!ast){
return resolve(returnData())
}else{
if(ast.redirect){
options.mask= getMask(file, ast)
return resolve(require(ast.redirect, options))
}
Mod.removeCached(file)
return generate(ast, function(){
// this allow hot reloading modules
if(typeof module.exports.kawixDynamic.reload == "function"){
return resolve(module.exports.kawixDynamic.reload(cached.exports, module.exports))
}
return resolve(module.exports)
}, reject)
}
})
})
return promise2
}else{
return returnData()
}
}
promise= Mod.compile(file,options)
promise2= new Promise(function(resolve, reject){
promise.then(function(ast){
if(ast && ast.redirect){
options.mask= getMask(file, ast)
return resolve(Mod.require(ast.redirect,options))
}
return generate(ast,resolve,reject)
}).catch(reject)
})
return promise2
}
var readNpm= function(url){
//var uri= Url.parse(url)
var module= url.substring(url.indexOf("://") + 3)
var parts= module.split("/")
var oparts= [].concat(parts)
var subpath= ""
while(parts.length > 2){
parts.pop()
}
if(parts.length > 1){
if(parts[0].startsWith("@")){
// valid
}
else{
parts.pop()
}
}
subpath= oparts.slice(parts.length)
subpath= subpath.join("/")
module= parts.join("/")
var moduledesc= Mod._npmcache[module]
var continue3= function(moduledesc){
if(moduledesc){
Mod._npmcache[module]= moduledesc
// return
if(subpath){
return {
redirect: Path.join(moduledesc.folder, subpath),
mask: "npm://" + moduledesc.name + "$v$" + moduledesc.version + "/" + subpath
}
}else{
return {
redirect: moduledesc.main ,
mask: "npm://" + moduledesc.name + "$v$" + moduledesc.version + "/" + (Path.relative(moduledesc.folder,moduledesc.main))
}
}
}
}
if(moduledesc){
return continue3(moduledesc)
}
return new Promise(function(resolve,reject){
var continue2= function(moduledesc){
return resolve(continue3(moduledesc))
}
var continue1= function(){
if (!process.env.DISABLE_COMPILATION_INFO) {
console.info("Caching npm module: " + url + " ...")
}
Mod._npmImport.resolve(module).then(continue2).catch(reject)
}
if(!Mod._npmImport){
Mod.import(Path.join(__dirname,"src","npm-import")).then(function(loader){
Mod._npmImport= loader
continue1()
}).catch(reject)
}
})