-
Notifications
You must be signed in to change notification settings - Fork 29.6k
/
module_wrap.cc
1338 lines (1174 loc) Β· 44.5 KB
/
module_wrap.cc
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
#include "module_wrap.h"
#include "env.h"
#include "memory_tracker-inl.h"
#include "node_errors.h"
#include "node_url.h"
#include "util-inl.h"
#include "node_contextify.h"
#include "node_watchdog.h"
#include <sys/stat.h> // S_IFDIR
#include <algorithm>
#include <climits> // PATH_MAX
namespace node {
namespace loader {
using errors::TryCatchScope;
using node::contextify::ContextifyContext;
using node::url::URL;
using node::url::URL_FLAGS_FAILED;
using v8::Array;
using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Global;
using v8::HandleScope;
using v8::Integer;
using v8::IntegrityLevel;
using v8::Isolate;
using v8::Just;
using v8::Local;
using v8::Maybe;
using v8::MaybeLocal;
using v8::Module;
using v8::Nothing;
using v8::Number;
using v8::Object;
using v8::PrimitiveArray;
using v8::Promise;
using v8::ScriptCompiler;
using v8::ScriptOrigin;
using v8::String;
using v8::Undefined;
using v8::Value;
static const char* const EXTENSIONS[] = {
".mjs",
".cjs",
".js",
".json",
".node"
};
ModuleWrap::ModuleWrap(Environment* env,
Local<Object> object,
Local<Module> module,
Local<String> url) :
BaseObject(env, object),
id_(env->get_next_module_id()) {
module_.Reset(env->isolate(), module);
url_.Reset(env->isolate(), url);
env->id_to_module_map.emplace(id_, this);
}
ModuleWrap::~ModuleWrap() {
HandleScope scope(env()->isolate());
Local<Module> module = module_.Get(env()->isolate());
env()->id_to_module_map.erase(id_);
auto range = env()->hash_to_module_map.equal_range(module->GetIdentityHash());
for (auto it = range.first; it != range.second; ++it) {
if (it->second == this) {
env()->hash_to_module_map.erase(it);
break;
}
}
}
ModuleWrap* ModuleWrap::GetFromModule(Environment* env,
Local<Module> module) {
auto range = env->hash_to_module_map.equal_range(module->GetIdentityHash());
for (auto it = range.first; it != range.second; ++it) {
if (it->second->module_ == module) {
return it->second;
}
}
return nullptr;
}
ModuleWrap* ModuleWrap::GetFromID(Environment* env, uint32_t id) {
auto module_wrap_it = env->id_to_module_map.find(id);
if (module_wrap_it == env->id_to_module_map.end()) {
return nullptr;
}
return module_wrap_it->second;
}
void ModuleWrap::New(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = env->isolate();
CHECK(args.IsConstructCall());
Local<Object> that = args.This();
const int argc = args.Length();
CHECK_GE(argc, 2);
CHECK(args[0]->IsString());
Local<String> source_text = args[0].As<String>();
CHECK(args[1]->IsString());
Local<String> url = args[1].As<String>();
Local<Context> context;
Local<Integer> line_offset;
Local<Integer> column_offset;
if (argc == 5) {
// new ModuleWrap(source, url, context?, lineOffset, columnOffset)
if (args[2]->IsUndefined()) {
context = that->CreationContext();
} else {
CHECK(args[2]->IsObject());
ContextifyContext* sandbox =
ContextifyContext::ContextFromContextifiedSandbox(
env, args[2].As<Object>());
CHECK_NOT_NULL(sandbox);
context = sandbox->context();
}
CHECK(args[3]->IsNumber());
line_offset = args[3].As<Integer>();
CHECK(args[4]->IsNumber());
column_offset = args[4].As<Integer>();
} else {
// new ModuleWrap(source, url)
context = that->CreationContext();
line_offset = Integer::New(isolate, 0);
column_offset = Integer::New(isolate, 0);
}
ShouldNotAbortOnUncaughtScope no_abort_scope(env);
TryCatchScope try_catch(env);
Local<Module> module;
Local<PrimitiveArray> host_defined_options =
PrimitiveArray::New(isolate, HostDefinedOptions::kLength);
host_defined_options->Set(isolate, HostDefinedOptions::kType,
Number::New(isolate, ScriptType::kModule));
// compile
{
ScriptOrigin origin(url,
line_offset, // line offset
column_offset, // column offset
True(isolate), // is cross origin
Local<Integer>(), // script id
Local<Value>(), // source map URL
False(isolate), // is opaque (?)
False(isolate), // is WASM
True(isolate), // is ES Module
host_defined_options);
Context::Scope context_scope(context);
ScriptCompiler::Source source(source_text, origin);
if (!ScriptCompiler::CompileModule(isolate, &source).ToLocal(&module)) {
if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
CHECK(!try_catch.Message().IsEmpty());
CHECK(!try_catch.Exception().IsEmpty());
AppendExceptionLine(env, try_catch.Exception(), try_catch.Message(),
ErrorHandlingMode::MODULE_ERROR);
try_catch.ReThrow();
}
return;
}
}
if (!that->Set(context, env->url_string(), url).FromMaybe(false)) {
return;
}
ModuleWrap* obj = new ModuleWrap(env, that, module, url);
obj->context_.Reset(isolate, context);
env->hash_to_module_map.emplace(module->GetIdentityHash(), obj);
host_defined_options->Set(isolate, HostDefinedOptions::kID,
Number::New(isolate, obj->id()));
that->SetIntegrityLevel(context, IntegrityLevel::kFrozen);
args.GetReturnValue().Set(that);
}
void ModuleWrap::Link(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = args.GetIsolate();
CHECK_EQ(args.Length(), 1);
CHECK(args[0]->IsFunction());
Local<Object> that = args.This();
ModuleWrap* obj;
ASSIGN_OR_RETURN_UNWRAP(&obj, that);
if (obj->linked_)
return;
obj->linked_ = true;
Local<Function> resolver_arg = args[0].As<Function>();
Local<Context> mod_context = obj->context_.Get(isolate);
Local<Module> module = obj->module_.Get(isolate);
Local<Array> promises = Array::New(isolate,
module->GetModuleRequestsLength());
// call the dependency resolve callbacks
for (int i = 0; i < module->GetModuleRequestsLength(); i++) {
Local<String> specifier = module->GetModuleRequest(i);
Utf8Value specifier_utf8(env->isolate(), specifier);
std::string specifier_std(*specifier_utf8, specifier_utf8.length());
Local<Value> argv[] = {
specifier
};
MaybeLocal<Value> maybe_resolve_return_value =
resolver_arg->Call(mod_context, that, 1, argv);
if (maybe_resolve_return_value.IsEmpty()) {
return;
}
Local<Value> resolve_return_value =
maybe_resolve_return_value.ToLocalChecked();
if (!resolve_return_value->IsPromise()) {
env->ThrowError("linking error, expected resolver to return a promise");
}
Local<Promise> resolve_promise = resolve_return_value.As<Promise>();
obj->resolve_cache_[specifier_std].Reset(env->isolate(), resolve_promise);
promises->Set(mod_context, i, resolve_promise).Check();
}
args.GetReturnValue().Set(promises);
}
void ModuleWrap::Instantiate(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = args.GetIsolate();
ModuleWrap* obj;
ASSIGN_OR_RETURN_UNWRAP(&obj, args.This());
Local<Context> context = obj->context_.Get(isolate);
Local<Module> module = obj->module_.Get(isolate);
TryCatchScope try_catch(env);
USE(module->InstantiateModule(context, ResolveCallback));
// clear resolve cache on instantiate
obj->resolve_cache_.clear();
if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
CHECK(!try_catch.Message().IsEmpty());
CHECK(!try_catch.Exception().IsEmpty());
AppendExceptionLine(env, try_catch.Exception(), try_catch.Message(),
ErrorHandlingMode::MODULE_ERROR);
try_catch.ReThrow();
return;
}
}
void ModuleWrap::Evaluate(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = env->isolate();
ModuleWrap* obj;
ASSIGN_OR_RETURN_UNWRAP(&obj, args.This());
Local<Context> context = obj->context_.Get(isolate);
Local<Module> module = obj->module_.Get(isolate);
// module.evaluate(timeout, breakOnSigint)
CHECK_EQ(args.Length(), 2);
CHECK(args[0]->IsNumber());
int64_t timeout = args[0]->IntegerValue(env->context()).FromJust();
CHECK(args[1]->IsBoolean());
bool break_on_sigint = args[1]->IsTrue();
ShouldNotAbortOnUncaughtScope no_abort_scope(env);
TryCatchScope try_catch(env);
bool timed_out = false;
bool received_signal = false;
MaybeLocal<Value> result;
if (break_on_sigint && timeout != -1) {
Watchdog wd(isolate, timeout, &timed_out);
SigintWatchdog swd(isolate, &received_signal);
result = module->Evaluate(context);
} else if (break_on_sigint) {
SigintWatchdog swd(isolate, &received_signal);
result = module->Evaluate(context);
} else if (timeout != -1) {
Watchdog wd(isolate, timeout, &timed_out);
result = module->Evaluate(context);
} else {
result = module->Evaluate(context);
}
// Convert the termination exception into a regular exception.
if (timed_out || received_signal) {
if (!env->is_main_thread() && env->is_stopping())
return;
env->isolate()->CancelTerminateExecution();
// It is possible that execution was terminated by another timeout in
// which this timeout is nested, so check whether one of the watchdogs
// from this invocation is responsible for termination.
if (timed_out) {
THROW_ERR_SCRIPT_EXECUTION_TIMEOUT(env, timeout);
} else if (received_signal) {
THROW_ERR_SCRIPT_EXECUTION_INTERRUPTED(env);
}
}
if (try_catch.HasCaught()) {
if (!try_catch.HasTerminated())
try_catch.ReThrow();
return;
}
args.GetReturnValue().Set(result.ToLocalChecked());
}
void ModuleWrap::Namespace(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = args.GetIsolate();
ModuleWrap* obj;
ASSIGN_OR_RETURN_UNWRAP(&obj, args.This());
Local<Module> module = obj->module_.Get(isolate);
switch (module->GetStatus()) {
default:
return env->ThrowError(
"cannot get namespace, Module has not been instantiated");
case v8::Module::Status::kInstantiated:
case v8::Module::Status::kEvaluating:
case v8::Module::Status::kEvaluated:
break;
}
Local<Value> result = module->GetModuleNamespace();
args.GetReturnValue().Set(result);
}
void ModuleWrap::GetStatus(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
ModuleWrap* obj;
ASSIGN_OR_RETURN_UNWRAP(&obj, args.This());
Local<Module> module = obj->module_.Get(isolate);
args.GetReturnValue().Set(module->GetStatus());
}
void ModuleWrap::GetStaticDependencySpecifiers(
const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
ModuleWrap* obj;
ASSIGN_OR_RETURN_UNWRAP(&obj, args.This());
Local<Module> module = obj->module_.Get(env->isolate());
int count = module->GetModuleRequestsLength();
Local<Array> specifiers = Array::New(env->isolate(), count);
for (int i = 0; i < count; i++)
specifiers->Set(env->context(), i, module->GetModuleRequest(i)).Check();
args.GetReturnValue().Set(specifiers);
}
void ModuleWrap::GetError(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
ModuleWrap* obj;
ASSIGN_OR_RETURN_UNWRAP(&obj, args.This());
Local<Module> module = obj->module_.Get(isolate);
args.GetReturnValue().Set(module->GetException());
}
MaybeLocal<Module> ModuleWrap::ResolveCallback(Local<Context> context,
Local<String> specifier,
Local<Module> referrer) {
Environment* env = Environment::GetCurrent(context);
CHECK_NOT_NULL(env); // TODO(addaleax): Handle nullptr here.
Isolate* isolate = env->isolate();
ModuleWrap* dependent = GetFromModule(env, referrer);
if (dependent == nullptr) {
env->ThrowError("linking error, null dep");
return MaybeLocal<Module>();
}
Utf8Value specifier_utf8(isolate, specifier);
std::string specifier_std(*specifier_utf8, specifier_utf8.length());
if (dependent->resolve_cache_.count(specifier_std) != 1) {
env->ThrowError("linking error, not in local cache");
return MaybeLocal<Module>();
}
Local<Promise> resolve_promise =
dependent->resolve_cache_[specifier_std].Get(isolate);
if (resolve_promise->State() != Promise::kFulfilled) {
env->ThrowError("linking error, dependency promises must be resolved on "
"instantiate");
return MaybeLocal<Module>();
}
Local<Object> module_object = resolve_promise->Result().As<Object>();
if (module_object.IsEmpty() || !module_object->IsObject()) {
env->ThrowError("linking error, expected a valid module object from "
"resolver");
return MaybeLocal<Module>();
}
ModuleWrap* module;
ASSIGN_OR_RETURN_UNWRAP(&module, module_object, MaybeLocal<Module>());
return module->module_.Get(isolate);
}
namespace {
// Tests whether a path starts with /, ./ or ../
// In WhatWG terminology, the alternative case is called a "bare" specifier
// (e.g. in `import "jquery"`).
inline bool ShouldBeTreatedAsRelativeOrAbsolutePath(
const std::string& specifier) {
size_t len = specifier.length();
if (len == 0)
return false;
if (specifier[0] == '/') {
return true;
} else if (specifier[0] == '.') {
if (len == 1 || specifier[1] == '/')
return true;
if (specifier[1] == '.') {
if (len == 2 || specifier[2] == '/')
return true;
}
}
return false;
}
std::string ReadFile(uv_file file) {
std::string contents;
uv_fs_t req;
char buffer_memory[4096];
uv_buf_t buf = uv_buf_init(buffer_memory, sizeof(buffer_memory));
do {
const int r = uv_fs_read(uv_default_loop(),
&req,
file,
&buf,
1,
contents.length(), // offset
nullptr);
uv_fs_req_cleanup(&req);
if (r <= 0)
break;
contents.append(buf.base, r);
} while (true);
return contents;
}
enum DescriptorType {
FILE,
DIRECTORY,
NONE
};
// When DescriptorType cache is added, this can also return
// Nothing for the "null" cache entries.
inline Maybe<uv_file> OpenDescriptor(const std::string& path) {
uv_fs_t fs_req;
uv_file fd = uv_fs_open(nullptr, &fs_req, path.c_str(), O_RDONLY, 0, nullptr);
uv_fs_req_cleanup(&fs_req);
if (fd < 0) return Nothing<uv_file>();
return Just(fd);
}
inline void CloseDescriptor(uv_file fd) {
uv_fs_t fs_req;
CHECK_EQ(0, uv_fs_close(nullptr, &fs_req, fd, nullptr));
uv_fs_req_cleanup(&fs_req);
}
inline DescriptorType CheckDescriptorAtFile(uv_file fd) {
uv_fs_t fs_req;
int rc = uv_fs_fstat(nullptr, &fs_req, fd, nullptr);
if (rc == 0) {
uint64_t is_directory = fs_req.statbuf.st_mode & S_IFDIR;
uv_fs_req_cleanup(&fs_req);
return is_directory ? DIRECTORY : FILE;
}
uv_fs_req_cleanup(&fs_req);
return NONE;
}
// TODO(@guybedford): Add a DescriptorType cache layer here.
// Should be directory based -> if path/to/dir doesn't exist
// then the cache should early-fail any path/to/dir/file check.
DescriptorType CheckDescriptorAtPath(const std::string& path) {
Maybe<uv_file> fd = OpenDescriptor(path);
if (fd.IsNothing()) return NONE;
DescriptorType type = CheckDescriptorAtFile(fd.FromJust());
CloseDescriptor(fd.FromJust());
return type;
}
Maybe<std::string> ReadIfFile(const std::string& path) {
Maybe<uv_file> fd = OpenDescriptor(path);
if (fd.IsNothing()) return Nothing<std::string>();
DescriptorType type = CheckDescriptorAtFile(fd.FromJust());
if (type != FILE) return Nothing<std::string>();
std::string source = ReadFile(fd.FromJust());
CloseDescriptor(fd.FromJust());
return Just(source);
}
using Exists = PackageConfig::Exists;
using IsValid = PackageConfig::IsValid;
using HasMain = PackageConfig::HasMain;
using PackageType = PackageConfig::PackageType;
Maybe<const PackageConfig*> GetPackageConfig(Environment* env,
const std::string& path,
const URL& base) {
auto existing = env->package_json_cache.find(path);
if (existing != env->package_json_cache.end()) {
const PackageConfig* pcfg = &existing->second;
if (pcfg->is_valid == IsValid::No) {
std::string msg = "Invalid JSON in " + path +
" imported from " + base.ToFilePath();
node::THROW_ERR_INVALID_PACKAGE_CONFIG(env, msg.c_str());
return Nothing<const PackageConfig*>();
}
return Just(pcfg);
}
Maybe<std::string> source = ReadIfFile(path);
if (source.IsNothing()) {
auto entry = env->package_json_cache.emplace(path,
PackageConfig { Exists::No, IsValid::Yes, HasMain::No, "",
PackageType::None, Global<Value>() });
return Just(&entry.first->second);
}
std::string pkg_src = source.FromJust();
Isolate* isolate = env->isolate();
v8::HandleScope handle_scope(isolate);
Local<Object> pkg_json;
{
Local<Value> src;
Local<Value> pkg_json_v;
Local<Context> context = env->context();
if (!ToV8Value(context, pkg_src).ToLocal(&src) ||
!v8::JSON::Parse(context, src.As<String>()).ToLocal(&pkg_json_v) ||
!pkg_json_v->ToObject(context).ToLocal(&pkg_json)) {
env->package_json_cache.emplace(path,
PackageConfig { Exists::Yes, IsValid::No, HasMain::No, "",
PackageType::None, Global<Value>() });
std::string msg = "Invalid JSON in " + path +
" imported from " + base.ToFilePath();
node::THROW_ERR_INVALID_PACKAGE_CONFIG(env, msg.c_str());
return Nothing<const PackageConfig*>();
}
}
Local<Value> pkg_main;
HasMain has_main = HasMain::No;
std::string main_std;
if (pkg_json->Get(env->context(), env->main_string()).ToLocal(&pkg_main)) {
if (pkg_main->IsString()) {
has_main = HasMain::Yes;
}
Utf8Value main_utf8(isolate, pkg_main);
main_std.assign(std::string(*main_utf8, main_utf8.length()));
}
PackageType pkg_type = PackageType::None;
Local<Value> type_v;
if (pkg_json->Get(env->context(), env->type_string()).ToLocal(&type_v)) {
if (type_v->StrictEquals(env->module_string())) {
pkg_type = PackageType::Module;
} else if (type_v->StrictEquals(env->commonjs_string())) {
pkg_type = PackageType::CommonJS;
}
// ignore unknown types for forwards compatibility
}
Local<Value> exports_v;
if (env->options()->experimental_exports &&
pkg_json->Get(env->context(),
env->exports_string()).ToLocal(&exports_v) &&
!exports_v->IsNullOrUndefined()) {
Global<Value> exports;
exports.Reset(env->isolate(), exports_v);
auto entry = env->package_json_cache.emplace(path,
PackageConfig { Exists::Yes, IsValid::Yes, has_main, main_std,
pkg_type, std::move(exports) });
return Just(&entry.first->second);
}
auto entry = env->package_json_cache.emplace(path,
PackageConfig { Exists::Yes, IsValid::Yes, has_main, main_std,
pkg_type, Global<Value>() });
return Just(&entry.first->second);
}
Maybe<const PackageConfig*> GetPackageScopeConfig(Environment* env,
const URL& resolved,
const URL& base) {
URL pjson_url("./package.json", &resolved);
while (true) {
std::string pjson_url_path = pjson_url.path();
if (pjson_url_path.length() > 25 &&
pjson_url_path.substr(pjson_url_path.length() - 25, 25) ==
"node_modules/package.json") {
break;
}
Maybe<const PackageConfig*> pkg_cfg =
GetPackageConfig(env, pjson_url.ToFilePath(), base);
if (pkg_cfg.IsNothing()) return pkg_cfg;
if (pkg_cfg.FromJust()->exists == Exists::Yes) return pkg_cfg;
URL last_pjson_url = pjson_url;
pjson_url = URL("../package.json", pjson_url);
// Terminates at root where ../package.json equals ../../package.json
// (can't just check "/package.json" for Windows support).
if (pjson_url.path() == last_pjson_url.path()) break;
}
auto entry = env->package_json_cache.emplace(pjson_url.ToFilePath(),
PackageConfig { Exists::No, IsValid::Yes, HasMain::No, "",
PackageType::None, Global<Value>() });
const PackageConfig* pcfg = &entry.first->second;
return Just(pcfg);
}
/*
* Legacy CommonJS main resolution:
* 1. let M = pkg_url + (json main field)
* 2. TRY(M, M.js, M.json, M.node)
* 3. TRY(M/index.js, M/index.json, M/index.node)
* 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
* 5. NOT_FOUND
*/
inline bool FileExists(const URL& url) {
return CheckDescriptorAtPath(url.ToFilePath()) == FILE;
}
Maybe<URL> LegacyMainResolve(const URL& pjson_url,
const PackageConfig& pcfg) {
URL guess;
if (pcfg.has_main == HasMain::Yes) {
// Note: fs check redundances will be handled by Descriptor cache here.
if (FileExists(guess = URL("./" + pcfg.main, pjson_url))) {
return Just(guess);
}
if (FileExists(guess = URL("./" + pcfg.main + ".js", pjson_url))) {
return Just(guess);
}
if (FileExists(guess = URL("./" + pcfg.main + ".json", pjson_url))) {
return Just(guess);
}
if (FileExists(guess = URL("./" + pcfg.main + ".node", pjson_url))) {
return Just(guess);
}
if (FileExists(guess = URL("./" + pcfg.main + "/index.js", pjson_url))) {
return Just(guess);
}
// Such stat.
if (FileExists(guess = URL("./" + pcfg.main + "/index.json", pjson_url))) {
return Just(guess);
}
if (FileExists(guess = URL("./" + pcfg.main + "/index.node", pjson_url))) {
return Just(guess);
}
// Fallthrough.
}
if (FileExists(guess = URL("./index.js", pjson_url))) {
return Just(guess);
}
// So fs.
if (FileExists(guess = URL("./index.json", pjson_url))) {
return Just(guess);
}
if (FileExists(guess = URL("./index.node", pjson_url))) {
return Just(guess);
}
// Not found.
return Nothing<URL>();
}
enum ResolveExtensionsOptions {
TRY_EXACT_NAME,
ONLY_VIA_EXTENSIONS
};
template <ResolveExtensionsOptions options>
Maybe<URL> ResolveExtensions(const URL& search) {
if (options == TRY_EXACT_NAME) {
if (FileExists(search)) {
return Just(search);
}
}
for (const char* extension : EXTENSIONS) {
URL guess(search.path() + extension, &search);
if (FileExists(guess)) {
return Just(guess);
}
}
return Nothing<URL>();
}
inline Maybe<URL> ResolveIndex(const URL& search) {
return ResolveExtensions<ONLY_VIA_EXTENSIONS>(URL("index", search));
}
Maybe<URL> FinalizeResolution(Environment* env,
const URL& resolved,
const URL& base) {
if (env->options()->es_module_specifier_resolution == "node") {
Maybe<URL> file = ResolveExtensions<TRY_EXACT_NAME>(resolved);
if (!file.IsNothing()) {
return file;
}
if (resolved.path().back() != '/') {
file = ResolveIndex(URL(resolved.path() + "/", &base));
} else {
file = ResolveIndex(resolved);
}
if (!file.IsNothing()) {
return file;
}
std::string msg = "Cannot find module " + resolved.path() +
" imported from " + base.ToFilePath();
node::THROW_ERR_MODULE_NOT_FOUND(env, msg.c_str());
return Nothing<URL>();
}
const std::string& path = resolved.ToFilePath();
if (CheckDescriptorAtPath(path) != FILE) {
std::string msg = "Cannot find module " +
(path.length() != 0 ? path : resolved.path()) +
" imported from " + base.ToFilePath();
node::THROW_ERR_MODULE_NOT_FOUND(env, msg.c_str());
return Nothing<URL>();
}
return Just(resolved);
}
Maybe<URL> PackageMainResolve(Environment* env,
const URL& pjson_url,
const PackageConfig& pcfg,
const URL& base) {
if (pcfg.exists == Exists::Yes) {
if (pcfg.has_main == HasMain::Yes) {
URL resolved(pcfg.main, pjson_url);
const std::string& path = resolved.ToFilePath();
if (CheckDescriptorAtPath(path) == FILE) {
return Just(resolved);
}
}
if (env->options()->es_module_specifier_resolution == "node") {
if (pcfg.has_main == HasMain::Yes) {
return FinalizeResolution(env, URL(pcfg.main, pjson_url), base);
} else {
return FinalizeResolution(env, URL("index", pjson_url), base);
}
}
if (pcfg.type != PackageType::Module) {
Maybe<URL> resolved = LegacyMainResolve(pjson_url, pcfg);
if (!resolved.IsNothing()) {
return resolved;
}
}
}
std::string msg = "Cannot find main entry point for " +
URL(".", pjson_url).ToFilePath() + " imported from " +
base.ToFilePath();
node::THROW_ERR_MODULE_NOT_FOUND(env, msg.c_str());
return Nothing<URL>();
}
void ThrowExportsNotFound(Environment* env,
const std::string& subpath,
const URL& pjson_url,
const URL& base) {
const std::string msg = "Package exports for " +
pjson_url.ToFilePath() + " do not define a '" + subpath +
"' subpath, imported from " + base.ToFilePath();
node::THROW_ERR_MODULE_NOT_FOUND(env, msg.c_str());
}
void ThrowExportsInvalid(Environment* env,
const std::string& subpath,
const std::string& target,
const URL& pjson_url,
const URL& base) {
const std::string msg = "Cannot resolve package exports target '" + target +
"' matched for '" + subpath + "' in " + pjson_url.ToFilePath() +
", imported from " + base.ToFilePath();
node::THROW_ERR_MODULE_NOT_FOUND(env, msg.c_str());
}
void ThrowExportsInvalid(Environment* env,
const std::string& subpath,
Local<Value> target,
const URL& pjson_url,
const URL& base) {
Local<String> target_string;
if (target->ToString(env->context()).ToLocal(&target_string)) {
Utf8Value target_utf8(env->isolate(), target_string);
std::string target_str(*target_utf8, target_utf8.length());
if (target->IsArray()) {
target_str = '[' + target_str + ']';
}
ThrowExportsInvalid(env, subpath, target_str, pjson_url, base);
}
}
Maybe<URL> ResolveExportsTarget(Environment* env,
const std::string& target,
const std::string& subpath,
const std::string& match,
const URL& pjson_url,
const URL& base,
bool throw_invalid = true) {
if (target.substr(0, 2) != "./") {
if (throw_invalid) {
ThrowExportsInvalid(env, match, target, pjson_url, base);
}
return Nothing<URL>();
}
if (subpath.length() > 0 && target.back() != '/') {
if (throw_invalid) {
ThrowExportsInvalid(env, match, target, pjson_url, base);
}
return Nothing<URL>();
}
URL resolved(target, pjson_url);
std::string resolved_path = resolved.path();
std::string pkg_path = URL(".", pjson_url).path();
if (resolved_path.find(pkg_path) != 0 ||
resolved_path.find("/node_modules/", pkg_path.length() - 1) !=
std::string::npos) {
if (throw_invalid) {
ThrowExportsInvalid(env, match, target, pjson_url, base);
}
return Nothing<URL>();
}
if (subpath.length() == 0) return Just(resolved);
URL subpath_resolved(subpath, resolved);
std::string subpath_resolved_path = subpath_resolved.path();
if (subpath_resolved_path.find(resolved_path) != 0 ||
subpath_resolved_path.find("/node_modules/", pkg_path.length() - 1)
!= std::string::npos) {
if (throw_invalid) {
ThrowExportsInvalid(env, match, target + subpath, pjson_url, base);
}
return Nothing<URL>();
}
return Just(subpath_resolved);
}
Maybe<URL> PackageExportsResolve(Environment* env,
const URL& pjson_url,
const std::string& pkg_subpath,
const PackageConfig& pcfg,
const URL& base) {
CHECK(env->options()->experimental_exports);
Isolate* isolate = env->isolate();
Local<Context> context = env->context();
Local<Value> exports = pcfg.exports.Get(isolate);
if (!exports->IsObject()) {
ThrowExportsNotFound(env, pkg_subpath, pjson_url, base);
return Nothing<URL>();
}
Local<Object> exports_obj = exports.As<Object>();
Local<String> subpath = String::NewFromUtf8(isolate,
pkg_subpath.c_str(), v8::NewStringType::kNormal).ToLocalChecked();
if (exports_obj->HasOwnProperty(context, subpath).FromJust()) {
Local<Value> target = exports_obj->Get(context, subpath).ToLocalChecked();
if (target->IsString()) {
Utf8Value target_utf8(isolate, target.As<v8::String>());
std::string target_str(*target_utf8, target_utf8.length());
Maybe<URL> resolved = ResolveExportsTarget(env, target_str, "",
pkg_subpath, pjson_url, base);
if (resolved.IsNothing()) {
ThrowExportsInvalid(env, pkg_subpath, target, pjson_url, base);
return Nothing<URL>();
}
return FinalizeResolution(env, resolved.FromJust(), base);
} else if (target->IsArray()) {
Local<Array> target_arr = target.As<Array>();
const uint32_t length = target_arr->Length();
if (length == 0) {
ThrowExportsInvalid(env, pkg_subpath, target, pjson_url, base);
return Nothing<URL>();
}
for (uint32_t i = 0; i < length; i++) {
auto target_item = target_arr->Get(context, i).ToLocalChecked();
if (target_item->IsString()) {
Utf8Value target_utf8(isolate, target_item.As<v8::String>());
std::string target(*target_utf8, target_utf8.length());
Maybe<URL> resolved = ResolveExportsTarget(env, target, "",
pkg_subpath, pjson_url, base, false);
if (resolved.IsNothing()) continue;
return FinalizeResolution(env, resolved.FromJust(), base);
}
}
auto invalid = target_arr->Get(context, length - 1).ToLocalChecked();
if (!invalid->IsString()) {
ThrowExportsInvalid(env, pkg_subpath, invalid, pjson_url, base);
return Nothing<URL>();
}
Utf8Value invalid_utf8(isolate, invalid.As<v8::String>());
std::string invalid_str(*invalid_utf8, invalid_utf8.length());
Maybe<URL> resolved = ResolveExportsTarget(env, invalid_str, "",
pkg_subpath, pjson_url, base);
CHECK(resolved.IsNothing());
return Nothing<URL>();
} else {
ThrowExportsInvalid(env, pkg_subpath, target, pjson_url, base);
return Nothing<URL>();
}
}
Local<String> best_match;
std::string best_match_str = "";
Local<Array> keys =
exports_obj->GetOwnPropertyNames(context).ToLocalChecked();
for (uint32_t i = 0; i < keys->Length(); ++i) {
Local<String> key = keys->Get(context, i).ToLocalChecked().As<String>();
Utf8Value key_utf8(isolate, key);
std::string key_str(*key_utf8, key_utf8.length());
if (key_str.back() != '/') continue;
if (pkg_subpath.substr(0, key_str.length()) == key_str &&
key_str.length() > best_match_str.length()) {
best_match = key;
best_match_str = key_str;
}
}
if (best_match_str.length() > 0) {
auto target = exports_obj->Get(context, best_match).ToLocalChecked();
std::string subpath = pkg_subpath.substr(best_match_str.length());
if (target->IsString()) {
Utf8Value target_utf8(isolate, target.As<v8::String>());
std::string target(*target_utf8, target_utf8.length());
Maybe<URL> resolved = ResolveExportsTarget(env, target, subpath,
pkg_subpath, pjson_url, base);
if (resolved.IsNothing()) {
ThrowExportsInvalid(env, pkg_subpath, target, pjson_url, base);
return Nothing<URL>();
}
return FinalizeResolution(env, URL(subpath, resolved.FromJust()), base);
} else if (target->IsArray()) {
Local<Array> target_arr = target.As<Array>();
const uint32_t length = target_arr->Length();
if (length == 0) {
ThrowExportsInvalid(env, pkg_subpath, target, pjson_url, base);
return Nothing<URL>();
}
for (uint32_t i = 0; i < length; i++) {
auto target_item = target_arr->Get(context, i).ToLocalChecked();
if (target_item->IsString()) {
Utf8Value target_utf8(isolate, target_item.As<v8::String>());
std::string target_str(*target_utf8, target_utf8.length());
Maybe<URL> resolved = ResolveExportsTarget(env, target_str, subpath,
pkg_subpath, pjson_url, base, false);
if (resolved.IsNothing()) continue;
return FinalizeResolution(env, resolved.FromJust(), base);
}
}