summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader.cc
blob: 32e05d15ca4cbc568e4a16ae317e5d40c6cc4594 (plain)
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
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/core/loader/modulescript/module_script_loader.h"

#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/loader/modulescript/module_script_fetcher.h"
#include "third_party/blink/renderer/core/loader/modulescript/module_script_loader_client.h"
#include "third_party/blink/renderer/core/loader/modulescript/module_script_loader_registry.h"
#include "third_party/blink/renderer/core/script/fetch_client_settings_object_snapshot.h"
#include "third_party/blink/renderer/core/script/modulator.h"
#include "third_party/blink/renderer/core/script/module_script.h"
#include "third_party/blink/renderer/core/workers/main_thread_worklet_global_scope.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loading_log.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"

namespace blink {

ModuleScriptLoader::ModuleScriptLoader(Modulator* modulator,
                                       const ScriptFetchOptions& options,
                                       ModuleScriptLoaderRegistry* registry,
                                       ModuleScriptLoaderClient* client)
    : modulator_(modulator),
      options_(options),
      registry_(registry),
      client_(client) {
  DCHECK(modulator);
  DCHECK(registry);
  DCHECK(client);
}

ModuleScriptLoader::~ModuleScriptLoader() = default;

#if DCHECK_IS_ON()
const char* ModuleScriptLoader::StateToString(ModuleScriptLoader::State state) {
  switch (state) {
    case State::kInitial:
      return "Initial";
    case State::kFetching:
      return "Fetching";
    case State::kFinished:
      return "Finished";
  }
  NOTREACHED();
  return "";
}
#endif

void ModuleScriptLoader::AdvanceState(ModuleScriptLoader::State new_state) {
  switch (state_) {
    case State::kInitial:
      DCHECK_EQ(new_state, State::kFetching);
      break;
    case State::kFetching:
      DCHECK_EQ(new_state, State::kFinished);
      break;
    case State::kFinished:
      NOTREACHED();
      break;
  }

#if DCHECK_IS_ON()
  RESOURCE_LOADING_DVLOG(1)
      << "ModuleLoader[" << url_.GetString() << "]::advanceState("
      << StateToString(state_) << " -> " << StateToString(new_state) << ")";
#endif
  state_ = new_state;

  if (state_ == State::kFinished) {
    registry_->ReleaseFinishedLoader(this);
    client_->NotifyNewSingleModuleFinished(module_script_);
  }
}

void ModuleScriptLoader::Fetch(
    const ModuleScriptFetchRequest& module_request,
    FetchClientSettingsObjectSnapshot* fetch_client_settings_object,
    ModuleGraphLevel level,
    Modulator* module_map_settings_object,
    ModuleScriptCustomFetchType custom_fetch_type,
    ModuleScriptLoaderRegistry* registry,
    ModuleScriptLoaderClient* client) {
  ModuleScriptLoader* loader = new ModuleScriptLoader(
      module_map_settings_object, module_request.Options(), registry, client);
  registry->AddLoader(loader);
  loader->FetchInternal(module_request, fetch_client_settings_object, level,
                        custom_fetch_type);
}

// https://html.spec.whatwg.org/#fetch-a-single-module-script
void ModuleScriptLoader::FetchInternal(
    const ModuleScriptFetchRequest& module_request,
    FetchClientSettingsObjectSnapshot* fetch_client_settings_object,
    ModuleGraphLevel level,
    ModuleScriptCustomFetchType custom_fetch_type) {
  // Step 4. "Set moduleMap[url] to "fetching"." [spec text]
  AdvanceState(State::kFetching);

  // Step 5. "Let request be a new request whose url is url, ..." [spec text]
  ResourceRequest resource_request(module_request.Url());
#if DCHECK_IS_ON()
  url_ = module_request.Url();
#endif

  // "destination is destination," [spec text]
  resource_request.SetRequestContext(module_request.Destination());

  ResourceLoaderOptions options;

  // Step 6. "Set up the module script request given request and options."
  // [spec text]
  // [SMSR]
  // https://html.spec.whatwg.org/multipage/webappapis.html#set-up-the-module-script-request

  // [SMSR] "... its parser metadata to options's parser metadata, ..."
  // [spec text]
  options.parser_disposition = options_.ParserState();

  // As initiator for module script fetch is not specified in HTML spec,
  // we specity "" as initiator per:
  // https://fetch.spec.whatwg.org/#concept-request-initiator
  options.initiator_info.name = g_empty_atom;

  if (level == ModuleGraphLevel::kDependentModuleFetch) {
    options.initiator_info.imported_module_referrer =
        module_request.GetReferrer().referrer;
    options.initiator_info.position = module_request.GetReferrerPosition();
  }

  // Note: |options| should not be modified after here.
  FetchParameters fetch_params(resource_request, options);

  // [SMSR] "... its integrity metadata to options's integrity metadata, ..."
  // [spec text]
  fetch_params.SetIntegrityMetadata(options_.GetIntegrityMetadata());
  fetch_params.MutableResourceRequest().SetFetchIntegrity(
      options_.GetIntegrityAttributeValue());

  // [SMSR] "Set request's cryptographic nonce metadata to options's
  // cryptographic nonce, ..." [spec text]
  fetch_params.SetContentSecurityPolicyNonce(options_.Nonce());

  // Step 5. "... mode is "cors", ..."
  // [SMSR] "... and its credentials mode to options's credentials mode."
  // [spec text]
  fetch_params.SetCrossOriginAccessControl(
      fetch_client_settings_object->GetSecurityOrigin(),
      options_.CredentialsMode());

  // <spec step="6">If destination is "worker" or "sharedworker" and the
  // top-level module fetch flag is set, then set request's mode to
  // "same-origin".</spec>
  //
  // `kServiceWorker` is included here for consistency, while it isn't mentioned
  // in the spec. This doesn't affect the behavior, because we already forbid
  // redirects and cross-origin response URLs in other places.
  if ((module_request.Destination() ==
           WebURLRequest::kRequestContextWorker ||
       module_request.Destination() ==
           WebURLRequest::kRequestContextSharedWorker ||
       module_request.Destination() ==
           WebURLRequest::kRequestContextServiceWorker) &&
      level == ModuleGraphLevel::kTopLevelModuleFetch) {
    // This should be done after SetCrossOriginAccessControl() that sets the
    // mode to kCors.
    fetch_params.MutableResourceRequest().SetMode(
        network::mojom::RequestMode::kSameOrigin);
  }

  // Step 5. "... referrer is referrer, ..." [spec text]
  fetch_params.MutableResourceRequest().SetHTTPReferrer(
      module_request.GetReferrer());

  // Step 5. "... and client is fetch client settings object." [spec text]
  // -> set by ResourceFetcher

  // Note: The fetch request's "origin" isn't specified in
  // https://html.spec.whatwg.org/#fetch-a-single-module-script
  // Thus, the "origin" is "client" per
  // https://fetch.spec.whatwg.org/#concept-request-origin

  // Module scripts are always defer.
  fetch_params.SetDefer(FetchParameters::kLazyLoad);
  // [nospec] Unlike defer/async classic scripts, module scripts are fetched at
  // High priority.
  fetch_params.MutableResourceRequest().SetPriority(
      ResourceLoadPriority::kHigh);

  // Use UTF-8, according to Step 9:
  // "Let source text be the result of UTF-8 decoding response's body."
  // [spec text]
  fetch_params.SetDecoderOptions(
      TextResourceDecoderOptions::CreateAlwaysUseUTF8ForText());

  // Step 7. "If the caller specified custom steps to perform the fetch,
  // perform them on request, setting the is top-level flag if the top-level
  // module fetch flag is set. Return from this algorithm, and when the custom
  // perform the fetch steps complete with response response, run the remaining
  // steps.
  // Otherwise, fetch request. Return from this algorithm, and run the remaining
  // steps as part of the fetch's process response for the response response."
  // [spec text]
  module_fetcher_ = modulator_->CreateModuleScriptFetcher(custom_fetch_type);
  module_fetcher_->Fetch(fetch_params, level, this);
}

void ModuleScriptLoader::NotifyFetchFinished(
    const base::Optional<ModuleScriptCreationParams>& params,
    const HeapVector<Member<ConsoleMessage>>& error_messages) {
  // [nospec] Abort the steps if the browsing context is discarded.
  if (!modulator_->HasValidContext()) {
    AdvanceState(State::kFinished);
    return;
  }

  // Note: "conditions" referred in Step 8 is implemented in
  // WasModuleLoadSuccessful() in module_script_fetcher.cc.
  // Step 8. "If any of the following conditions are met, set moduleMap[url] to
  // null, asynchronously complete this algorithm with null, and abort these
  // steps." [spec text]
  if (!params.has_value()) {
    for (ConsoleMessage* error_message : error_messages) {
      ExecutionContext::From(modulator_->GetScriptState())
          ->AddConsoleMessage(error_message);
    }
    AdvanceState(State::kFinished);
    return;
  }

  // Step 9. "Let source text be the result of UTF-8 decoding response's body."
  // [spec text]
  // Step 10. "Let module script be the result of creating a module script given
  // source text, module map settings object, response's url, and options."
  // [spec text]
  module_script_ = ModuleScript::Create(
      params->GetSourceText(), modulator_, params->GetResponseUrl(),
      params->GetResponseUrl(), options_, params->GetAccessControlStatus());

  AdvanceState(State::kFinished);
}

void ModuleScriptLoader::Trace(blink::Visitor* visitor) {
  visitor->Trace(modulator_);
  visitor->Trace(module_script_);
  visitor->Trace(registry_);
  visitor->Trace(client_);
  visitor->Trace(module_fetcher_);
}

}  // namespace blink