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
|
/*
* Copyright (C) 2015-2021 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ScriptModuleLoader.h"
#include "CachedModuleScriptLoader.h"
#include "CachedScript.h"
#include "CachedScriptFetcher.h"
#include "DocumentInlines.h"
#include "EventLoop.h"
#include "JSDOMBinding.h"
#include "JSDOMPromiseDeferred.h"
#include "LoadableModuleScript.h"
#include "LocalFrame.h"
#include "MIMETypeRegistry.h"
#include "ModuleFetchFailureKind.h"
#include "ModuleFetchParameters.h"
#include "ScriptController.h"
#include "ScriptSourceCode.h"
#include "ServiceWorkerGlobalScope.h"
#include "ShadowRealmGlobalScope.h"
#include "SubresourceIntegrity.h"
#include "WebAssemblyScriptSourceCode.h"
#include "WebCoreJSClientData.h"
#include "WorkerModuleScriptLoader.h"
#include "WorkerOrWorkletScriptController.h"
#include "WorkerScriptFetcher.h"
#include "WorkerScriptLoader.h"
#include "WorkletGlobalScope.h"
#include <JavaScriptCore/AbstractModuleRecord.h>
#include <JavaScriptCore/Completion.h>
#include <JavaScriptCore/ImportMap.h>
#include <JavaScriptCore/JSInternalPromise.h>
#include <JavaScriptCore/JSNativeStdFunction.h>
#include <JavaScriptCore/JSScriptFetchParameters.h>
#include <JavaScriptCore/JSScriptFetcher.h>
#include <JavaScriptCore/JSSourceCode.h>
#include <JavaScriptCore/JSString.h>
#include <JavaScriptCore/SourceProvider.h>
#include <JavaScriptCore/Symbol.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/MakeString.h>
namespace WebCore {
WTF_MAKE_TZONE_ALLOCATED_IMPL(ScriptModuleLoader);
ScriptModuleLoader::ScriptModuleLoader(ScriptExecutionContext* context, OwnerType ownerType)
: m_context(context)
, m_ownerType(ownerType)
{
}
ScriptModuleLoader::~ScriptModuleLoader()
{
for (auto& loader : m_loaders)
loader->clearClient();
}
UniqueRef<ScriptModuleLoader> ScriptModuleLoader::shadowRealmLoader(JSC::JSGlobalObject* realmGlobal) const
{
auto loader = makeUniqueRef<ScriptModuleLoader>(m_context.get(), m_ownerType);
loader->m_shadowRealmGlobal = realmGlobal;
return loader;
}
static bool isRootModule(JSC::JSValue importerModuleKey)
{
return importerModuleKey.isSymbol() || importerModuleKey.isUndefined();
}
static Expected<URL, String> resolveModuleSpecifier(ScriptExecutionContext& context, ScriptModuleLoader::OwnerType ownerType, JSC::ImportMap& importMap, const String& specifier, const URL& originalBaseURL)
{
// https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier
URL result = importMap.resolve(specifier, ownerType == ScriptModuleLoader::OwnerType::Document ? downcast<Document>(context).baseURLForComplete(originalBaseURL) : originalBaseURL);
if (result.isNull())
return makeUnexpected(makeString("Module name, '"_s, specifier, "' does not resolve to a valid URL."_s));
return result;
}
JSC::Identifier ScriptModuleLoader::resolve(JSC::JSGlobalObject* jsGlobalObject, JSC::JSModuleLoader*, JSC::JSValue moduleNameValue, JSC::JSValue importerModuleKey, JSC::JSValue)
{
JSC::VM& vm = jsGlobalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// We use a Symbol as a special purpose; It means this module is an inline module.
// So there is no correct URL to retrieve the module source code. If the module name
// value is a Symbol, it is used directly as a module key.
if (moduleNameValue.isSymbol())
return JSC::Identifier::fromUid(asSymbol(moduleNameValue)->privateName());
if (!moduleNameValue.isString()) {
JSC::throwTypeError(jsGlobalObject, scope, "Importer module key is not a Symbol or a String."_s);
return { };
}
String specifier = asString(moduleNameValue)->value(jsGlobalObject);
RETURN_IF_EXCEPTION(scope, { });
URL baseURL = responseURLFromRequestURL(*jsGlobalObject, importerModuleKey);
RETURN_IF_EXCEPTION(scope, { });
if (!m_context) {
JSC::throwTypeError(jsGlobalObject, scope, "No associated script execution context"_s);
return { };
}
auto result = resolveModuleSpecifier(*m_context, m_ownerType, jsGlobalObject->importMap(), specifier, baseURL);
if (!result) {
auto* error = JSC::createTypeError(jsGlobalObject, result.error());
ASSERT(error);
error->putDirect(vm, builtinNames(vm).failureKindPrivateName(), JSC::jsNumber(enumToUnderlyingType(ModuleFetchFailureKind::WasResolveError)));
JSC::throwException(jsGlobalObject, scope, error);
return { };
}
return JSC::Identifier::fromString(vm, result->string());
}
static void rejectToPropagateNetworkError(ScriptExecutionContext& context, Ref<DeferredPromise>&& deferred, ModuleFetchFailureKind failureKind, ASCIILiteral message)
{
context.eventLoop().queueTask(TaskSource::Networking, [deferred = WTFMove(deferred), failureKind, message]() {
deferred->rejectWithCallback([&] (JSDOMGlobalObject& jsGlobalObject) {
// We annotate exception with special private symbol. It allows us to distinguish these errors from the user thrown ones.
JSC::VM& vm = jsGlobalObject.vm();
// FIXME: Propagate more descriptive error.
// https://bugs.webkit.org/show_bug.cgi?id=167553
auto* error = JSC::createTypeError(&jsGlobalObject, message);
ASSERT(error);
error->putDirect(vm, builtinNames(vm).failureKindPrivateName(), JSC::jsNumber(enumToUnderlyingType(failureKind)));
return error;
});
});
}
static void rejectWithFetchError(ScriptExecutionContext& context, Ref<DeferredPromise>&& deferred, ExceptionCode ec, String&& message)
{
// Used to signal to the promise client that the failure was from a fetch, but not one that was propagated from another context.
context.eventLoop().queueTask(TaskSource::Networking, [deferred = WTFMove(deferred), ec, message = WTFMove(message)]() {
deferred->rejectWithCallback([&] (JSDOMGlobalObject& jsGlobalObject) {
JSC::VM& vm = jsGlobalObject.vm();
JSC::JSObject* error = JSC::jsCast<JSC::JSObject*>(createDOMException(&jsGlobalObject, ec, message));
ASSERT(error);
error->putDirect(vm, builtinNames(vm).failureKindPrivateName(), JSC::jsNumber(enumToUnderlyingType(ModuleFetchFailureKind::WasFetchError)));
return error;
});
});
}
JSC::JSInternalPromise* ScriptModuleLoader::fetch(JSC::JSGlobalObject* jsGlobalObject, JSC::JSModuleLoader*, JSC::JSValue moduleKeyValue, JSC::JSValue parametersValue, JSC::JSValue scriptFetcher)
{
JSC::VM& vm = jsGlobalObject->vm();
ASSERT(JSC::jsDynamicCast<JSC::JSScriptFetcher*>(scriptFetcher));
auto& globalObject = *JSC::jsCast<JSDOMGlobalObject*>(jsGlobalObject);
auto* jsPromise = JSC::JSInternalPromise::create(vm, globalObject.internalPromiseStructure());
RELEASE_ASSERT(jsPromise);
if (!m_context)
return jsPromise;
auto deferred = DeferredPromise::create(globalObject, *jsPromise);
if (moduleKeyValue.isSymbol()) {
rejectWithFetchError(*m_context, WTFMove(deferred), ExceptionCode::TypeError, "Symbol module key should be already fulfilled with the inlined resource."_s);
return jsPromise;
}
if (!moduleKeyValue.isString()) {
rejectWithFetchError(*m_context, WTFMove(deferred), ExceptionCode::TypeError, "Module key is not Symbol or String."_s);
return jsPromise;
}
// https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
URL completedURL { asString(moduleKeyValue)->value(jsGlobalObject) };
if (!completedURL.isValid()) {
rejectWithFetchError(*m_context, WTFMove(deferred), ExceptionCode::TypeError, "Module key is a valid URL."_s);
return jsPromise;
}
RefPtr<JSC::ScriptFetchParameters> parameters;
if (auto* scriptFetchParameters = JSC::jsDynamicCast<JSC::JSScriptFetchParameters*>(parametersValue))
parameters = &scriptFetchParameters->parameters();
if (m_ownerType == OwnerType::Document) {
auto loader = CachedModuleScriptLoader::create(*this, deferred.get(), *static_cast<CachedScriptFetcher*>(JSC::jsCast<JSC::JSScriptFetcher*>(scriptFetcher)->fetcher()), WTFMove(parameters));
m_loaders.add(loader.copyRef());
// Prevent non-normal worlds from loading with a service worker.
auto serviceWorkersMode = currentWorld(*jsGlobalObject).isNormal() ? ServiceWorkersMode::All : ServiceWorkersMode::None;
if (!loader->load(downcast<Document>(*m_context), WTFMove(completedURL), serviceWorkersMode)) {
loader->clearClient();
m_loaders.remove(WTFMove(loader));
rejectToPropagateNetworkError(*m_context, WTFMove(deferred), ModuleFetchFailureKind::WasPropagatedError, "Importing a module script failed."_s);
return jsPromise;
}
} else {
auto loader = WorkerModuleScriptLoader::create(*this, deferred.get(), *static_cast<WorkerScriptFetcher*>(JSC::jsCast<JSC::JSScriptFetcher*>(scriptFetcher)->fetcher()), WTFMove(parameters));
m_loaders.add(loader.copyRef());
loader->load(*m_context, WTFMove(completedURL));
}
return jsPromise;
}
URL ScriptModuleLoader::moduleURL(JSC::JSGlobalObject& jsGlobalObject, JSC::JSValue moduleKeyValue)
{
if (moduleKeyValue.isSymbol())
return m_context ? m_context->url() : URL();
ASSERT(moduleKeyValue.isString());
return URL { asString(moduleKeyValue)->value(&jsGlobalObject) };
}
URL ScriptModuleLoader::responseURLFromRequestURL(JSC::JSGlobalObject& jsGlobalObject, JSC::JSValue moduleKeyValue)
{
JSC::VM& vm = jsGlobalObject.vm();
auto scope = DECLARE_THROW_SCOPE(vm);
if (isRootModule(moduleKeyValue)) {
if (!m_context)
return URL();
if (m_ownerType == OwnerType::Document)
return downcast<Document>(*m_context).baseURL();
return m_context->url();
}
ASSERT(!isRootModule(moduleKeyValue));
ASSERT(moduleKeyValue.isString());
String requestURL = asString(moduleKeyValue)->value(&jsGlobalObject);
RETURN_IF_EXCEPTION(scope, { });
ASSERT_WITH_MESSAGE(URL(requestURL).isValid(), "Invalid module referrer never starts importing dependent modules.");
auto iterator = m_requestURLToResponseURLMap.find(requestURL);
if (iterator == m_requestURLToResponseURLMap.end())
return URL { requestURL }; // dynamic-import().
URL result = iterator->value;
ASSERT(result.isValid());
return result;
}
JSC::JSValue ScriptModuleLoader::evaluate(JSC::JSGlobalObject* jsGlobalObject, JSC::JSModuleLoader*, JSC::JSValue moduleKeyValue, JSC::JSValue moduleRecordValue, JSC::JSValue, JSC::JSValue awaitedValue, JSC::JSValue resumeMode)
{
JSC::VM& vm = jsGlobalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// FIXME: Currently, we only support JSModuleRecord and WebAssemblyModuleRecord.
// Once the reflective part of the module loader is supported, we will handle arbitrary values.
// https://whatwg.github.io/loader/#registry-prototype-provide
auto* moduleRecord = JSC::jsDynamicCast<JSC::AbstractModuleRecord*>(moduleRecordValue);
if (!moduleRecord)
return JSC::jsUndefined();
URL sourceURL = moduleURL(*jsGlobalObject, moduleKeyValue);
if (!sourceURL.isValid())
return JSC::throwTypeError(jsGlobalObject, scope, "Module key is an invalid URL."_s);
if (!m_context)
return JSC::jsUndefined();
if (m_shadowRealmGlobal)
RELEASE_AND_RETURN(scope, moduleRecord->evaluate(m_shadowRealmGlobal, awaitedValue, resumeMode));
else if (m_ownerType == OwnerType::Document) {
if (RefPtr frame = downcast<Document>(*m_context).frame())
RELEASE_AND_RETURN(scope, frame->script().evaluateModule(sourceURL, *moduleRecord, awaitedValue, resumeMode));
} else {
if (auto* script = downcast<WorkerOrWorkletGlobalScope>(*m_context).script())
RELEASE_AND_RETURN(scope, script->evaluateModule(sourceURL, *moduleRecord, awaitedValue, resumeMode));
}
return JSC::jsUndefined();
}
static JSC::JSInternalPromise* rejectPromise(ScriptExecutionContext& context, JSDOMGlobalObject& globalObject, ExceptionCode ec, String message)
{
auto* jsPromise = JSC::JSInternalPromise::create(globalObject.vm(), globalObject.internalPromiseStructure());
RELEASE_ASSERT(jsPromise);
rejectWithFetchError(context, DeferredPromise::create(globalObject, *jsPromise), ec, WTFMove(message));
return jsPromise;
}
JSC::JSInternalPromise* ScriptModuleLoader::importModule(JSC::JSGlobalObject* jsGlobalObject, JSC::JSModuleLoader*, JSC::JSString* moduleName, JSC::JSValue parametersValue, const JSC::SourceOrigin& sourceOrigin)
{
JSC::VM& vm = jsGlobalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
auto& globalObject = *JSC::jsCast<JSDOMGlobalObject*>(jsGlobalObject);
if (!m_context)
return nullptr;
// https://html.spec.whatwg.org/multipage/webappapis.html#hostimportmoduledynamically(referencingscriptormodule,-specifier,-promisecapability)
// If settings object's global object implements WorkletGlobalScope or ServiceWorkerGlobalScope, then:
if (is<WorkletGlobalScope>(*m_context) || is<ServiceWorkerGlobalScope>(*m_context)) {
scope.release();
return rejectPromise(*m_context, globalObject, ExceptionCode::TypeError, "Dynamic-import is not available in Worklets or ServiceWorkers"_s);
}
auto reject = [&](auto& scope) {
auto* promise = JSC::JSInternalPromise::create(vm, globalObject.internalPromiseStructure());
return promise->rejectWithCaughtException(&globalObject, scope);
};
auto getTypeFromAssertions = [&]() -> JSC::ScriptFetchParameters::Type {
auto scope = DECLARE_THROW_SCOPE(vm);
auto assertions = JSC::retrieveImportAttributesFromDynamicImportOptions(&globalObject, parametersValue, { vm.propertyNames->type.impl() });
RETURN_IF_EXCEPTION(scope, { });
auto type = JSC::retrieveTypeImportAttribute(&globalObject, assertions);
RETURN_IF_EXCEPTION(scope, { });
return type.value_or(JSC::ScriptFetchParameters::Type::JavaScript);
};
auto specifier = moduleName->value(jsGlobalObject);
// If SourceOrigin and/or CachedScriptFetcher is null, we import the module with the default fetcher.
// SourceOrigin can be null if the source code is not coupled with the script file.
// The examples,
// 1. The code evaluated by the inspector.
// 2. The other unusual code execution like the evaluation through the NPAPI.
// 3. The code from injected bundle's script.
// 4. The code from extension script.
URL baseURL;
RefPtr<JSC::ScriptFetcher> scriptFetcher;
RefPtr<ModuleFetchParameters> parameters;
if (sourceOrigin.isNull()) {
auto type = getTypeFromAssertions();
RETURN_IF_EXCEPTION(scope, reject(scope));
parameters = ModuleFetchParameters::create(type, emptyString(), /* isTopLevelModule */ true);
if (m_ownerType == OwnerType::Document) {
auto& document = downcast<Document>(*m_context);
baseURL = document.baseURL();
scriptFetcher = CachedScriptFetcher::create(document.charset());
} else {
// https://html.spec.whatwg.org/multipage/webappapis.html#default-classic-script-fetch-options
baseURL = m_context->url();
scriptFetcher = WorkerScriptFetcher::create(*parameters, FetchOptions::Credentials::SameOrigin, FetchOptions::Destination::Script, ReferrerPolicy::EmptyString);
}
} else {
baseURL = URL { sourceOrigin.string() };
if (!baseURL.isValid()) {
scope.release();
return rejectPromise(*m_context, globalObject, ExceptionCode::TypeError, "Importer module key is not a Symbol or a String."_s);
}
auto type = getTypeFromAssertions();
RETURN_IF_EXCEPTION(scope, reject(scope));
URL moduleURL = globalObject.importMap().resolve(specifier, baseURL);
parameters = ModuleFetchParameters::create(type, globalObject.importMap().integrityForURL(moduleURL), /* isTopLevelModule */ true);
if (sourceOrigin.fetcher()) {
scriptFetcher = sourceOrigin.fetcher();
// https://html.spec.whatwg.org/multipage/webappapis.html#fetch-an-import()-module-script-graph
// Destination should be "script" for dynamic-import.
if (m_ownerType == OwnerType::WorkerOrWorklet) {
auto& fetcher = static_cast<WorkerScriptFetcher&>(*scriptFetcher);
scriptFetcher = WorkerScriptFetcher::create(*parameters, fetcher.credentials(), FetchOptions::Destination::Script, fetcher.referrerPolicy());
}
}
if (!scriptFetcher) {
if (m_ownerType == OwnerType::Document)
scriptFetcher = CachedScriptFetcher::create(downcast<Document>(*m_context).charset());
else
scriptFetcher = WorkerScriptFetcher::create(*parameters, FetchOptions::Credentials::SameOrigin, FetchOptions::Destination::Script, ReferrerPolicy::EmptyString);
}
}
ASSERT(baseURL.isValid());
ASSERT(scriptFetcher);
ASSERT(parameters);
RETURN_IF_EXCEPTION(scope, reject(scope));
RELEASE_AND_RETURN(scope, JSC::importModule(jsGlobalObject, JSC::Identifier::fromString(vm, specifier), JSC::jsString(vm, baseURL.string()), JSC::JSScriptFetchParameters::create(vm, parameters.releaseNonNull()), JSC::JSScriptFetcher::create(vm, WTFMove(scriptFetcher))));
}
JSC::JSObject* ScriptModuleLoader::createImportMetaProperties(JSC::JSGlobalObject* jsGlobalObject, JSC::JSModuleLoader*, JSC::JSValue moduleKeyValue, JSC::JSModuleRecord*, JSC::JSValue)
{
// https://html.spec.whatwg.org/multipage/webappapis.html#hostgetimportmetaproperties
auto& vm = jsGlobalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
auto* metaProperties = JSC::constructEmptyObject(vm, jsGlobalObject->nullPrototypeObjectStructure());
RETURN_IF_EXCEPTION(scope, nullptr);
URL responseURL = responseURLFromRequestURL(*jsGlobalObject, moduleKeyValue);
RETURN_IF_EXCEPTION(scope, nullptr);
metaProperties->putDirect(vm, JSC::Identifier::fromString(vm, "url"_s), JSC::jsString(vm, responseURL.string()));
RETURN_IF_EXCEPTION(scope, nullptr);
String resolveName = "resolve"_s;
OwnerType ownerType = m_ownerType;
auto* function = JSC::JSNativeStdFunction::create(vm, jsGlobalObject, 1, resolveName, [ownerType, responseURL](JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame) -> JSC::EncodedJSValue {
JSC::VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
auto specifier = callFrame->argument(0).toWTFString(globalObject);
RETURN_IF_EXCEPTION(scope, { });
auto* domGlobalObject = jsDynamicCast<JSDOMGlobalObject*>(globalObject);
if (UNLIKELY(!domGlobalObject))
return JSC::throwVMTypeError(globalObject, scope);
auto* context = domGlobalObject->scriptExecutionContext();
if (UNLIKELY(!context))
return JSC::throwVMTypeError(globalObject, scope);
auto result = resolveModuleSpecifier(*context, ownerType, domGlobalObject->importMap(), specifier, responseURL);
if (UNLIKELY(!result))
return JSC::throwVMTypeError(globalObject, scope, result.error());
return JSC::JSValue::encode(JSC::jsString(vm, result->string()));
});
metaProperties->putDirect(vm, JSC::Identifier::fromString(vm, resolveName), function);
return metaProperties;
}
void ScriptModuleLoader::notifyFinished(ModuleScriptLoader& moduleScriptLoader, URL&& sourceURL, Ref<DeferredPromise> promise)
{
// https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
if (!m_loaders.remove(&moduleScriptLoader))
return;
moduleScriptLoader.clearClient();
RefPtr context = m_context.get();
if (!context)
return;
auto canonicalizeAndRegisterResponseURL = [&] (URL responseURL, bool hasRedirections, ResourceResponse::Source source) {
// If we do not have redirection, we must reserve the source URL's fragment explicitly here since ResourceResponse::url() is the one when we first cache it to MemoryCache.
// FIXME: We should track fragments through redirections.
// https://bugs.webkit.org/show_bug.cgi?id=158420
// https://bugs.webkit.org/show_bug.cgi?id=210490
if (!hasRedirections && source != ResourceResponse::Source::ServiceWorker) {
if (sourceURL.hasFragmentIdentifier())
responseURL.setFragmentIdentifier(sourceURL.fragmentIdentifier());
}
return responseURL;
};
JSC::SourceCode sourceCode;
if (m_ownerType == OwnerType::Document) {
auto& loader = static_cast<CachedModuleScriptLoader&>(moduleScriptLoader);
auto& cachedScript = *loader.cachedScript();
if (cachedScript.resourceError().isAccessControl()) {
rejectToPropagateNetworkError(*context, WTFMove(promise), ModuleFetchFailureKind::WasPropagatedError, "Cross-origin script load denied by Cross-Origin Resource Sharing policy."_s);
return;
}
if (cachedScript.errorOccurred()) {
rejectToPropagateNetworkError(*context, WTFMove(promise), ModuleFetchFailureKind::WasPropagatedError, "Importing a module script failed."_s);
return;
}
if (cachedScript.wasCanceled()) {
rejectToPropagateNetworkError(*context, WTFMove(promise), ModuleFetchFailureKind::WasCanceled, "Importing a module script is canceled."_s);
return;
}
ModuleType type = ModuleType::Invalid;
auto mimeType = cachedScript.response().mimeType();
if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(mimeType))
type = ModuleType::JavaScript;
#if ENABLE(WEBASSEMBLY)
else if (context->settingsValues().webAssemblyESMIntegrationEnabled && MIMETypeRegistry::isSupportedWebAssemblyMIMEType(mimeType))
type = ModuleType::WebAssembly;
#endif
else if (loader.parameters() && loader.parameters()->type() == JSC::ScriptFetchParameters::JSON && MIMETypeRegistry::isSupportedJSONMIMEType(mimeType))
type = ModuleType::JSON;
else {
// https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
// The result of extracting a MIME type from response's header list (ignoring parameters) is not a JavaScript MIME type.
// For historical reasons, fetching a classic script does not include MIME type checking. In contrast, module scripts will fail to load if they are not of a correct MIME type.
rejectWithFetchError(*context, WTFMove(promise), ExceptionCode::TypeError, makeString('\'', cachedScript.response().mimeType(), "' is not a valid JavaScript MIME type."_s));
return;
}
auto* globalObject = context->globalObject();
String integrity = globalObject ? globalObject->importMap().integrityForURL(sourceURL) : String();
if (auto* parameters = loader.parameters())
integrity = parameters->integrity();
if (!integrity.isEmpty()) {
if (!matchIntegrityMetadata(cachedScript, integrity)) {
context->addConsoleMessage(MessageSource::Security, MessageLevel::Error, makeString("Cannot load script "_s, integrityMismatchDescription(cachedScript, integrity)));
rejectWithFetchError(*context, WTFMove(promise), ExceptionCode::TypeError, "Cannot load script due to integrity mismatch"_s);
return;
}
}
URL responseURL = canonicalizeAndRegisterResponseURL(cachedScript.response().url(), cachedScript.hasRedirections(), cachedScript.response().source());
m_requestURLToResponseURLMap.add(sourceURL.string(), WTFMove(responseURL));
switch (type) {
case ModuleType::JavaScript:
sourceCode = JSC::SourceCode { ScriptSourceCode { &cachedScript, JSC::SourceProviderSourceType::Module, loader.scriptFetcher() }.jsSourceCode() };
break;
#if ENABLE(WEBASSEMBLY)
case ModuleType::WebAssembly:
sourceCode = JSC::SourceCode { WebAssemblyScriptSourceCode { &cachedScript, loader.scriptFetcher() }.jsSourceCode() };
break;
#endif
case ModuleType::JSON:
sourceCode = JSC::SourceCode { ScriptSourceCode { &cachedScript, JSC::SourceProviderSourceType::JSON, loader.scriptFetcher() }.jsSourceCode() };
break;
default:
RELEASE_ASSERT_NOT_REACHED();
}
} else {
auto& loader = static_cast<WorkerModuleScriptLoader&>(moduleScriptLoader);
if (loader.failed()) {
ASSERT(!loader.retrievedFromServiceWorkerCache());
auto& workerScriptLoader = loader.scriptLoader();
ASSERT(workerScriptLoader.failed());
if (workerScriptLoader.error().isAccessControl()) {
rejectToPropagateNetworkError(*context, WTFMove(promise), ModuleFetchFailureKind::WasPropagatedError, "Cross-origin script load denied by Cross-Origin Resource Sharing policy."_s);
return;
}
if (workerScriptLoader.error().isCancellation()) {
rejectToPropagateNetworkError(*context, WTFMove(promise), ModuleFetchFailureKind::WasCanceled, "Importing a module script is canceled."_s);
return;
}
rejectToPropagateNetworkError(*context, WTFMove(promise), ModuleFetchFailureKind::WasPropagatedError, "Importing a module script failed."_s);
return;
}
ModuleType type = ModuleType::Invalid;
auto mimeType = loader.responseMIMEType();
if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(mimeType))
type = ModuleType::JavaScript;
#if ENABLE(WEBASSEMBLY)
else if (context->settingsValues().webAssemblyESMIntegrationEnabled && MIMETypeRegistry::isSupportedWebAssemblyMIMEType(mimeType))
type = ModuleType::WebAssembly;
#endif
else if (loader.parameters() && loader.parameters()->type() == JSC::ScriptFetchParameters::JSON && MIMETypeRegistry::isSupportedJSONMIMEType(mimeType))
type = ModuleType::JSON;
else {
// https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
// The result of extracting a MIME type from response's header list (ignoring parameters) is not a JavaScript MIME type.
// For historical reasons, fetching a classic script does not include MIME type checking. In contrast, module scripts will fail to load if they are not of a correct MIME type.
rejectWithFetchError(*context, WTFMove(promise), ExceptionCode::TypeError, makeString('\'', loader.responseMIMEType(), "' is not a valid JavaScript MIME type."_s));
return;
}
URL responseURL = loader.responseURL();
if (!loader.retrievedFromServiceWorkerCache()) {
auto& workerScriptLoader = loader.scriptLoader();
if (auto* parameters = loader.parameters()) {
// If this is top-level-module, then we extract referrer-policy and apply to the dependent modules.
if (parameters->isTopLevelModule())
static_cast<WorkerScriptFetcher&>(loader.scriptFetcher()).setReferrerPolicy(loader.referrerPolicy());
}
responseURL = canonicalizeAndRegisterResponseURL(responseURL, workerScriptLoader.isRedirected(), workerScriptLoader.responseSource());
if (auto* globalScope = dynamicDowncast<ServiceWorkerGlobalScope>(*context))
globalScope->setScriptResource(sourceURL, ServiceWorkerContextData::ImportedScript { loader.script(), responseURL, loader.responseMIMEType() });
}
m_requestURLToResponseURLMap.add(sourceURL.string(), responseURL);
switch (type) {
case ModuleType::JavaScript:
sourceCode = JSC::SourceCode { ScriptSourceCode { loader.script(), WTFMove(responseURL), WTFMove(sourceURL), { }, JSC::SourceProviderSourceType::Module, loader.scriptFetcher() }.jsSourceCode() };
break;
#if ENABLE(WEBASSEMBLY)
case ModuleType::WebAssembly:
sourceCode = JSC::SourceCode { WebAssemblyScriptSourceCode { loader.script(), WTFMove(responseURL), loader.scriptFetcher() }.jsSourceCode() };
break;
#endif
case ModuleType::JSON:
sourceCode = JSC::SourceCode { ScriptSourceCode { loader.script(), WTFMove(responseURL), WTFMove(sourceURL), { }, JSC::SourceProviderSourceType::JSON, loader.scriptFetcher() }.jsSourceCode() };
break;
default:
RELEASE_ASSERT_NOT_REACHED();
}
}
context->checkedEventLoop()->queueTask(TaskSource::Networking, [promise = WTFMove(promise), sourceCode = WTFMove(sourceCode)]() {
promise->resolveWithCallback([&, sourceCode](JSDOMGlobalObject& jsGlobalObject) {
return JSC::JSSourceCode::create(jsGlobalObject.vm(), JSC::SourceCode { sourceCode });
});
});
}
}
|