rspack_loader_runner 0.102.1

rspack loader runner
Documentation
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
use std::{borrow::Cow, sync::Arc};

use derive_more::Debug;
use rspack_cacheable::cacheable;
use rspack_error::Diagnostic;
use rspack_paths::{InternedPath, InternedPathSet, Utf8Path};
use rspack_sources::SourceMap;

use crate::{
  AdditionalData, Content, LoaderItem, LoaderRunnerPlugin, ParseMeta, ResourceData,
  loader::LoaderItemList,
};

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum State {
  Init,
  Pitching,
  ProcessResource,
  Normal,
  Finished,
}

impl State {
  pub(crate) fn transition(&mut self, next: State) {
    *self = match (*self, next) {
      (State::Init, State::Pitching) => State::Pitching,
      (State::Pitching, State::ProcessResource) => State::ProcessResource,
      (State::Pitching, State::Normal) => State::Normal, // if pitching loader modifies the content
      (State::ProcessResource, State::Normal) => State::Normal,
      (State::Normal, State::Finished) => State::Finished,
      _ => panic!("Unexpected loader runner state (current: {self:?}, next: {next:?})"),
    };
  }
}

#[cacheable]
#[derive(Clone, Debug, Default)]
pub struct LoaderDependencies {
  pub file: InternedPathSet,
  pub context: InternedPathSet,
  pub missing: InternedPathSet,
  pub build: InternedPathSet,
}

impl LoaderDependencies {
  pub fn is_empty(&self) -> bool {
    self.file.is_empty()
      && self.context.is_empty()
      && self.missing.is_empty()
      && self.build.is_empty()
  }
}

#[derive(Debug)]
pub struct LoaderContext<Context: Send> {
  pub hot: bool,
  pub resource_data: Arc<ResourceData>,
  #[debug(skip)]
  pub context: Context,
  pub parse_meta: ParseMeta,

  pub(crate) content: Option<Content>,
  pub(crate) source_map: Option<Box<SourceMap<'static>>>,
  pub(crate) additional_data: Option<AdditionalData>,

  pub cacheable: bool,
  /// Dependencies committed by resource processing and preceding loaders.
  pub(crate) dependencies: LoaderDependencies,
  /// Dependencies added by the current native loader. A dependency remains
  /// here even when it was already present in `dependencies`.
  pub(crate) added_dependencies: LoaderDependencies,
  /// Dependencies removed by the current native loader.
  pub(crate) removed_dependencies: LoaderDependencies,

  pub diagnostics: Vec<Diagnostic>,

  /// Loader States
  pub(crate) state: State,
  pub loader_index: i32,
  pub loader_items: Vec<LoaderItem<Context>>,
  #[debug(skip)]
  pub plugin: Option<Arc<dyn LoaderRunnerPlugin<Context = Context>>>,
}

impl<Context: Send> LoaderContext<Context> {
  fn effective_dependency_set<'a>(
    existing: &'a InternedPathSet,
    added: &InternedPathSet,
    removed: &InternedPathSet,
  ) -> Cow<'a, InternedPathSet> {
    if added.is_empty() && removed.is_empty() {
      return Cow::Borrowed(existing);
    }
    let mut dependencies = existing.clone();
    for dependency in removed {
      dependencies.remove(dependency);
    }
    dependencies.extend(added.iter().cloned());
    Cow::Owned(dependencies)
  }

  /// Dependencies visible to the current loader, with its pending additions and removals applied.
  pub fn dependencies(&self) -> Cow<'_, LoaderDependencies> {
    if self.added_dependencies.is_empty() && self.removed_dependencies.is_empty() {
      return Cow::Borrowed(&self.dependencies);
    }
    Cow::Owned(LoaderDependencies {
      file: self.file_dependencies().into_owned(),
      context: self.context_dependencies().into_owned(),
      missing: self.missing_dependencies().into_owned(),
      build: self.build_dependencies().into_owned(),
    })
  }

  /// Dependencies committed before the current loader started.
  #[doc(hidden)]
  pub fn existing_dependencies(&self) -> &LoaderDependencies {
    &self.dependencies
  }

  pub fn file_dependencies(&self) -> Cow<'_, InternedPathSet> {
    Self::effective_dependency_set(
      &self.dependencies.file,
      &self.added_dependencies.file,
      &self.removed_dependencies.file,
    )
  }

  pub fn context_dependencies(&self) -> Cow<'_, InternedPathSet> {
    Self::effective_dependency_set(
      &self.dependencies.context,
      &self.added_dependencies.context,
      &self.removed_dependencies.context,
    )
  }

  pub fn missing_dependencies(&self) -> Cow<'_, InternedPathSet> {
    Self::effective_dependency_set(
      &self.dependencies.missing,
      &self.added_dependencies.missing,
      &self.removed_dependencies.missing,
    )
  }

  pub fn build_dependencies(&self) -> Cow<'_, InternedPathSet> {
    Self::effective_dependency_set(
      &self.dependencies.build,
      &self.added_dependencies.build,
      &self.removed_dependencies.build,
    )
  }

  #[doc(hidden)]
  pub fn added_dependencies(&self) -> &LoaderDependencies {
    &self.added_dependencies
  }

  #[doc(hidden)]
  pub fn removed_dependencies(&self) -> &LoaderDependencies {
    &self.removed_dependencies
  }

  #[doc(hidden)]
  pub fn reset_dependency_changes(&mut self) {
    self.added_dependencies = Default::default();
    self.removed_dependencies = Default::default();
  }

  #[doc(hidden)]
  pub fn merge_dependency_changes(&mut self) {
    macro_rules! merge_dependencies {
      ($field:ident) => {{
        for dependency in self.removed_dependencies.$field.drain() {
          self.dependencies.$field.remove(&dependency);
        }
        self
          .dependencies
          .$field
          .extend(self.added_dependencies.$field.drain());
      }};
    }

    merge_dependencies!(file);
    merge_dependencies!(context);
    merge_dependencies!(missing);
    merge_dependencies!(build);
  }

  #[doc(hidden)]
  pub fn replace_dependencies(&mut self, dependencies: LoaderDependencies) {
    self.dependencies = dependencies;
    self.reset_dependency_changes();
  }

  #[doc(hidden)]
  pub fn add_dependencies(&mut self, dependencies: &LoaderDependencies) {
    for dependency in &dependencies.file {
      self.add_file_dependency(dependency.clone());
    }
    for dependency in &dependencies.context {
      self.add_context_dependency(dependency.clone());
    }
    for dependency in &dependencies.missing {
      self.add_missing_dependency(dependency.clone());
    }
    for dependency in &dependencies.build {
      self.add_build_dependency(dependency.clone());
    }
  }

  pub fn add_file_dependency(&mut self, dependency: impl Into<InternedPath>) {
    let dependency = dependency.into();
    self.removed_dependencies.file.remove(&dependency);
    self.added_dependencies.file.insert(dependency);
  }

  pub fn add_context_dependency(&mut self, dependency: impl Into<InternedPath>) {
    let dependency = dependency.into();
    self.removed_dependencies.context.remove(&dependency);
    self.added_dependencies.context.insert(dependency);
  }

  pub fn add_missing_dependency(&mut self, dependency: impl Into<InternedPath>) {
    let dependency = dependency.into();
    self.removed_dependencies.missing.remove(&dependency);
    self.added_dependencies.missing.insert(dependency);
  }

  pub fn add_build_dependency(&mut self, dependency: impl Into<InternedPath>) {
    let dependency = dependency.into();
    self.removed_dependencies.build.remove(&dependency);
    self.added_dependencies.build.insert(dependency);
  }

  pub fn remove_file_dependency(&mut self, dependency: impl Into<InternedPath>) {
    let dependency = dependency.into();
    self.added_dependencies.file.remove(&dependency);
    if self.dependencies.file.contains(&dependency) {
      self.removed_dependencies.file.insert(dependency);
    }
  }

  pub fn remove_context_dependency(&mut self, dependency: impl Into<InternedPath>) {
    let dependency = dependency.into();
    self.added_dependencies.context.remove(&dependency);
    if self.dependencies.context.contains(&dependency) {
      self.removed_dependencies.context.insert(dependency);
    }
  }

  pub fn remove_missing_dependency(&mut self, dependency: impl Into<InternedPath>) {
    let dependency = dependency.into();
    self.added_dependencies.missing.remove(&dependency);
    if self.dependencies.missing.contains(&dependency) {
      self.removed_dependencies.missing.insert(dependency);
    }
  }

  pub fn remove_build_dependency(&mut self, dependency: impl Into<InternedPath>) {
    let dependency = dependency.into();
    self.added_dependencies.build.remove(&dependency);
    if self.dependencies.build.contains(&dependency) {
      self.removed_dependencies.build.insert(dependency);
    }
  }

  pub fn clear_dependencies(&mut self) {
    self
      .removed_dependencies
      .file
      .extend(self.dependencies.file.iter().cloned());
    self
      .removed_dependencies
      .context
      .extend(self.dependencies.context.iter().cloned());
    self
      .removed_dependencies
      .missing
      .extend(self.dependencies.missing.iter().cloned());
    self.added_dependencies.file.clear();
    self.added_dependencies.context.clear();
    self.added_dependencies.missing.clear();
  }

  pub fn remaining_request(&self) -> LoaderItemList<'_, Context> {
    if self.loader_index >= self.loader_items.len() as i32 - 1 {
      return Default::default();
    }
    LoaderItemList(&self.loader_items[self.loader_index as usize + 1..])
  }

  pub fn previous_request(&self) -> LoaderItemList<'_, Context> {
    LoaderItemList(&self.loader_items[..self.loader_index as usize])
  }

  #[inline]
  pub fn current_loader(&self) -> &LoaderItem<Context> {
    &self.loader_items[self.loader_index as usize]
  }

  /// Emit a diagnostic, it can be a `warning` or `error`.
  pub fn emit_diagnostic(&mut self, diagnostic: Diagnostic) {
    self.diagnostics.push(diagnostic)
  }

  /// The resource part of the request, including query and fragment.
  /// E.g. /abc/resource.js?query=1#some-fragment
  pub fn resource(&self) -> &str {
    self.resource_data.resource()
  }

  /// The resource part of the request.
  /// E.g. /abc/resource.js
  pub fn resource_path(&self) -> Option<&Utf8Path> {
    self.resource_data.path()
  }

  /// The query of the request
  /// E.g. query=1
  pub fn resource_query(&self) -> Option<&str> {
    self.resource_data.query()
  }

  pub fn content(&self) -> Option<&Content> {
    self.content.as_ref()
  }

  pub fn source_map(&self) -> Option<&SourceMap<'static>> {
    self.source_map.as_deref()
  }

  pub fn additional_data(&self) -> Option<&AdditionalData> {
    self.additional_data.as_ref()
  }

  pub fn take_content(&mut self) -> Option<Content> {
    self.content.take()
  }

  pub fn take_source_map(&mut self) -> Option<SourceMap<'static>> {
    self.source_map.take().map(|source_map| *source_map)
  }

  pub fn take_additional_data(&mut self) -> Option<AdditionalData> {
    self.additional_data.take()
  }

  pub fn take_all(
    &mut self,
  ) -> (
    Option<Content>,
    Option<SourceMap<'static>>,
    Option<AdditionalData>,
  ) {
    (
      self.content.take(),
      self.take_source_map(),
      self.additional_data.take(),
    )
  }

  pub fn finish_with(&mut self, patch: impl Into<LoaderPatch>) {
    self.__finish_with(patch);
    self.current_loader().set_finish_called();
  }

  pub fn finish_with_empty(&mut self) {
    self.content = None;
    self.source_map = None;
    self.additional_data = None;
    self.current_loader().set_finish_called();
  }

  #[inline]
  pub fn state(&self) -> State {
    self.state
  }

  #[doc(hidden)]
  pub fn __finish_with(&mut self, patch: impl Into<LoaderPatch>) {
    let patch = patch.into();
    self.content = patch.content;
    self.source_map = patch.source_map.map(Box::new);
    self.additional_data = patch.additional_data;
  }
}

pub struct LoaderPatch {
  pub(crate) content: Option<Content>,
  pub(crate) source_map: Option<SourceMap<'static>>,
  pub(crate) additional_data: Option<AdditionalData>,
}

impl<T> From<T> for LoaderPatch
where
  T: Into<Content>,
{
  fn from(content: T) -> Self {
    Self {
      content: Some(content.into()),
      source_map: None,
      additional_data: None,
    }
  }
}

impl<T> From<(T, SourceMap<'static>)> for LoaderPatch
where
  T: Into<Content>,
{
  fn from(value: (T, SourceMap<'static>)) -> Self {
    Self {
      content: Some(value.0.into()),
      source_map: Some(value.1),
      additional_data: None,
    }
  }
}

impl<T> From<(T, Option<SourceMap<'static>>)> for LoaderPatch
where
  T: Into<Content>,
{
  fn from(value: (T, Option<SourceMap<'static>>)) -> Self {
    Self {
      content: Some(value.0.into()),
      source_map: value.1,
      additional_data: None,
    }
  }
}

impl<T> From<(T, SourceMap<'static>, AdditionalData)> for LoaderPatch
where
  T: Into<Content>,
{
  fn from(value: (T, SourceMap<'static>, AdditionalData)) -> Self {
    Self {
      content: Some(value.0.into()),
      source_map: Some(value.1),
      additional_data: Some(value.2),
    }
  }
}

impl<T> From<(T, Option<SourceMap<'static>>, Option<AdditionalData>)> for LoaderPatch
where
  T: Into<Content>,
{
  fn from(value: (T, Option<SourceMap<'static>>, Option<AdditionalData>)) -> Self {
    Self {
      content: Some(value.0.into()),
      source_map: value.1,
      additional_data: value.2,
    }
  }
}

impl<T> From<Option<T>> for LoaderPatch
where
  T: Into<Content>,
{
  fn from(content: Option<T>) -> Self {
    Self {
      content: content.map(|c| c.into()),
      source_map: None,
      additional_data: None,
    }
  }
}

impl<T> From<(Option<T>, SourceMap<'static>)> for LoaderPatch
where
  T: Into<Content>,
{
  fn from(value: (Option<T>, SourceMap<'static>)) -> Self {
    Self {
      content: value.0.map(|c| c.into()),
      source_map: Some(value.1),
      additional_data: None,
    }
  }
}

impl<T> From<(Option<T>, Option<SourceMap<'static>>)> for LoaderPatch
where
  T: Into<Content>,
{
  fn from(value: (Option<T>, Option<SourceMap<'static>>)) -> Self {
    Self {
      content: value.0.map(|c| c.into()),
      source_map: value.1,
      additional_data: None,
    }
  }
}

impl<T> From<(Option<T>, SourceMap<'static>, AdditionalData)> for LoaderPatch
where
  T: Into<Content>,
{
  fn from(value: (Option<T>, SourceMap<'static>, AdditionalData)) -> Self {
    Self {
      content: value.0.map(|c| c.into()),
      source_map: Some(value.1),
      additional_data: Some(value.2),
    }
  }
}

impl<T>
  From<(
    Option<T>,
    Option<SourceMap<'static>>,
    Option<AdditionalData>,
  )> for LoaderPatch
where
  T: Into<Content>,
{
  fn from(
    value: (
      Option<T>,
      Option<SourceMap<'static>>,
      Option<AdditionalData>,
    ),
  ) -> Self {
    Self {
      content: value.0.map(|c| c.into()),
      source_map: value.1,
      additional_data: value.2,
    }
  }
}