rspack_plugin_javascript 0.101.6

rspack javascript plugin
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
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
use std::sync::LazyLock;

use rspack_core::{
  ChunkKind, ChunkUkey, Compilation, RuntimeCodeTemplate, RuntimeGlobals, RuntimeGlobalsRenderMode,
  RuntimeProxyMetadata, RuntimeVariable, SourceType, property_access, render_lexical_declarations,
  rspack_sources::{BoxSource, ConcatSource, RawStringSource, SourceExt},
  runtime_module_owned_define_fields,
};
use rspack_error::Result;

use crate::runtime::{RuntimeModuleSourceItem, render_runtime_module_sources};

static HMR_RUNTIME_STATE_GLOBALS: LazyLock<RuntimeGlobals> = LazyLock::new(|| {
  RuntimeGlobals::HMR_DOWNLOAD_UPDATE_HANDLERS
    | RuntimeGlobals::HMR_INVALIDATE_MODULE_HANDLERS
    | RuntimeGlobals::HMR_MODULE_DATA
    | RuntimeGlobals::HMR_RUNTIME_STATE_PREFIX
});

static LIVE_BINDING_CONTEXT_GLOBALS: LazyLock<RuntimeGlobals> = LazyLock::new(|| {
  RuntimeGlobals::PUBLIC_PATH
    | RuntimeGlobals::SCRIPT_NONCE
    | RuntimeGlobals::GET_CHUNK_SCRIPT_FILENAME
    | RuntimeGlobals::SHARE_SCOPE_MAP
    | RuntimeGlobals::INITIALIZE_SHARING
    | RuntimeGlobals::CURRENT_REMOTE_GET_SCOPE
});

static BOOTSTRAP_EXPORT_GLOBALS: LazyLock<RuntimeGlobals> = LazyLock::new(|| {
  RuntimeGlobals::REQUIRE
    | RuntimeGlobals::REQUIRE_SCOPE
    | RuntimeGlobals::MODULE_FACTORIES
    | RuntimeGlobals::MODULE_CACHE
    | RuntimeGlobals::INTERCEPT_MODULE_EXECUTION
});

pub fn should_export_rspack_runtime_globals(
  compilation: &Compilation,
  chunk_ukey: &ChunkUkey,
) -> bool {
  let chunk_graph = &compilation.build_chunk_graph_artifact.chunk_graph;
  if chunk_graph.get_chunk_entry_modules(chunk_ukey).is_empty() {
    return true;
  }

  let chunk = compilation
    .build_chunk_graph_artifact
    .chunk_by_ukey
    .expect_get(chunk_ukey);
  let module_graph = compilation.get_module_graph();
  chunk
    .get_all_referenced_chunks(&compilation.build_chunk_graph_artifact.chunk_group_by_ukey)
    .into_iter()
    .any(|referenced_chunk| {
      referenced_chunk != *chunk_ukey
        && chunk_graph.has_chunk_module_by_source_type(
          &referenced_chunk,
          SourceType::JavaScript,
          module_graph,
        )
    })
}

fn filter_unused_module_runtime_bindings(
  mut fields: RuntimeGlobals,
  tree_runtime_requirements: RuntimeGlobals,
  bootstrap_runtime_requirements: RuntimeGlobals,
) -> RuntimeGlobals {
  fields = fields.renderable_require_scope();

  let use_require = bootstrap_runtime_requirements.intersects(
    RuntimeGlobals::REQUIRE | RuntimeGlobals::INTERCEPT_MODULE_EXECUTION | RuntimeGlobals::MODULE,
  );
  let module_cache = tree_runtime_requirements.contains(RuntimeGlobals::MODULE_CACHE);
  let render_module_cache =
    use_require || bootstrap_runtime_requirements.contains(RuntimeGlobals::MODULE_CACHE);
  if !module_cache || !render_module_cache {
    fields.remove(RuntimeGlobals::MODULE_CACHE);
  }

  let uses_module_factories = tree_runtime_requirements
    .intersects(RuntimeGlobals::MODULE_FACTORIES | RuntimeGlobals::MODULE_FACTORIES_ADD_ONLY);
  let renders_module_factories = bootstrap_runtime_requirements.intersects(
    RuntimeGlobals::MODULE_FACTORIES
      | RuntimeGlobals::MODULE_FACTORIES_ADD_ONLY
      | RuntimeGlobals::REQUIRE,
  );
  if !uses_module_factories || !renders_module_factories {
    fields.remove(RuntimeGlobals::MODULE_FACTORIES);
  } else if tree_runtime_requirements.contains(RuntimeGlobals::MODULE_FACTORIES_ADD_ONLY) {
    fields.insert(RuntimeGlobals::MODULE_FACTORIES);
  }

  fields
}

fn render_rspack_runtime_exports(
  fields: RuntimeGlobals,
  setter_fields: RuntimeGlobals,
  should_export: bool,
  runtime_template: &RuntimeCodeTemplate,
  emitted_fields: &mut RuntimeGlobals,
  emitted_setters: &mut RuntimeGlobals,
) -> String {
  let mut source = String::new();

  if should_export {
    for (_, runtime_global) in fields
      .renderable_require_scope()
      .difference(*BOOTSTRAP_EXPORT_GLOBALS)
      .iter_names()
    {
      if emitted_fields.contains(runtime_global) {
        continue;
      }
      emitted_fields.insert(runtime_global);
      let specifier = runtime_template.render_runtime_globals(&runtime_global);
      source.push_str(&format!("export {{ {specifier} }};\n"));
    }
  }

  for (_, runtime_global) in setter_fields.renderable_require_scope().iter_names() {
    if emitted_setters.contains(runtime_global) {
      continue;
    }
    let Some(setter_name) = runtime_global.to_rspack_export_setter_name() else {
      continue;
    };
    emitted_setters.insert(runtime_global);
    let lexical_name = runtime_template.render_runtime_globals(&runtime_global);
    source.push_str(&format!(
      "function {setter_name}(value) {{ return {lexical_name} = value; }}\n"
    ));
    if should_export {
      source.push_str(&format!("export {{ {setter_name} }};\n"));
    }
  }

  source
}

fn render_runtime_context_accessors(
  fields: RuntimeGlobals,
  runtime_context: &str,
  runtime_template: &RuntimeCodeTemplate,
) -> String {
  let mut source = String::new();
  for (_, runtime_global) in fields.renderable_require_scope().iter_names() {
    let Some(key) = runtime_global.rspack_context_property_name() else {
      continue;
    };
    let lexical_name = runtime_template.render_runtime_globals(&runtime_global);
    source.push_str(&format!(
      "Object.defineProperty({runtime_context}, {}, {{ configurable: true, get: function() {{ return {lexical_name}; }}, set: function(value) {{ {lexical_name} = value; }} }});\n",
      rspack_util::json_stringify(key),
    ));
  }
  source
}

pub fn render_runtime_context_declaration(runtime_template: &RuntimeCodeTemplate) -> String {
  let runtime_context = runtime_template.render_runtime_variable(&RuntimeVariable::Context);
  format!("var {runtime_context}={{}};\n")
}

pub fn render_runtime_context_require_assignment(runtime_template: &RuntimeCodeTemplate) -> String {
  format!(
    "{} = {};\n",
    runtime_template.render_runtime_globals(&RuntimeGlobals::REQUIRE),
    runtime_template.render_runtime_variable(&RuntimeVariable::Require)
  )
}

pub async fn render_runtime_chunk_runtime_modules(
  compilation: &Compilation,
  chunk_ukey: &ChunkUkey,
  runtime_template: &RuntimeCodeTemplate,
) -> Result<BoxSource> {
  let runtime_module_sources = render_runtime_module_sources(compilation, chunk_ukey, true).await?;
  Ok(render_runtime_chunk_runtime_modules_sync(
    compilation,
    chunk_ukey,
    runtime_template,
    runtime_module_sources,
  ))
}

#[inline(never)]
fn render_runtime_chunk_runtime_modules_sync(
  compilation: &Compilation,
  chunk_ukey: &ChunkUkey,
  runtime_template: &RuntimeCodeTemplate,
  runtime_module_sources: Vec<RuntimeModuleSourceItem>,
) -> BoxSource {
  let mut sources = ConcatSource::default();
  if runtime_module_sources.is_empty() {
    return sources.boxed();
  }
  let metadata = compilation
    .runtime_proxy_metadata_artifact
    .get(chunk_ukey)
    .expect("should generate runtime metadata");
  let runtime_context = runtime_template.render_runtime_variable(&RuntimeVariable::Context);
  let module_graph = compilation.get_module_graph();
  let has_modules = !compilation
    .build_chunk_graph_artifact
    .chunk_graph
    .get_chunk_modules_identifier_by_source_type(chunk_ukey, SourceType::JavaScript, module_graph)
    .is_empty();
  let is_hmr_runtime = metadata
    .tree_runtime_requirements
    .contains(RuntimeGlobals::HMR_DOWNLOAD_MANIFEST);
  let should_export_runtime_globals = should_export_rspack_runtime_globals(compilation, chunk_ukey);
  let mut hmr_state_keys = Vec::new();
  for runtime_module_id in compilation
    .build_chunk_graph_artifact
    .chunk_graph
    .get_chunk_runtime_modules_iterable(chunk_ukey)
  {
    let runtime_module = compilation
      .runtime_modules
      .get(runtime_module_id)
      .expect("should have runtime module");
    let Some(key) = (match runtime_module.get_constructor_name().as_str() {
      "JsonpChunkLoadingRuntimeModule" => Some("jsonp"),
      "ModuleChunkLoadingRuntimeModule" => Some("module"),
      "ImportScriptsChunkLoadingRuntimeModule" => Some("importScripts"),
      "ReadFileChunkLoadingRuntimeModule" => Some("readFileVm"),
      "RequireChunkLoadingRuntimeModule" => Some("require"),
      _ => None,
    }) else {
      continue;
    };
    hmr_state_keys.push(key);
  }

  let isolate = has_modules;
  let render_runtime_global = |runtime_global: RuntimeGlobals| {
    if runtime_global == RuntimeGlobals::REQUIRE {
      Some(runtime_template.render_runtime_variable(&RuntimeVariable::Require))
    } else if runtime_global == RuntimeGlobals::MODULE_FACTORIES {
      Some(runtime_template.render_runtime_variable(&RuntimeVariable::Modules))
    } else if runtime_global == RuntimeGlobals::MODULE_CACHE {
      let module_cache = runtime_template.render_runtime_variable(&RuntimeVariable::ModuleCache);
      Some(format!(
        "typeof {module_cache} !== \"undefined\" ? {module_cache} : {{}}"
      ))
    } else if runtime_template.render_mode() == RuntimeGlobalsRenderMode::RspackContext
      && runtime_global.intersects(RuntimeGlobals::STARTUP | RuntimeGlobals::STARTUP_ENTRYPOINT)
    {
      runtime_global
        .rspack_context_property_name()
        .map(|property_name| format!("{runtime_context}{}", property_access([property_name], 0)))
    } else {
      None
    }
  };
  let mut wrapped_sources = ConcatSource::default();
  let bootstrap_runtime_requirements = compilation
    .cgc_runtime_requirements_artifact
    .get(chunk_ukey)
    .copied()
    .unwrap_or_default();
  let lexical_fields = filter_unused_module_runtime_bindings(
    metadata.lexical_fields() | metadata.context_setter_fields(),
    metadata.tree_runtime_requirements,
    bootstrap_runtime_requirements,
  );
  if runtime_template.render_mode() == RuntimeGlobalsRenderMode::RspackExport {
    sources.add(RawStringSource::from(render_lexical_declarations(
      lexical_fields
        .difference(runtime_module_owned_define_fields(compilation, chunk_ukey))
        .difference(*BOOTSTRAP_EXPORT_GLOBALS),
      Some(&render_runtime_global),
    )));
    if is_hmr_runtime {
      let require = runtime_template.render_runtime_variable(&RuntimeVariable::Require);
      let modules = runtime_template.render_runtime_globals(&RuntimeGlobals::MODULE_FACTORIES);
      let module_cache = runtime_template.render_runtime_variable(&RuntimeVariable::ModuleCache);
      sources.add(RawStringSource::from(format!(
        "var {runtime_context}={require};{runtime_context}.r={require};{runtime_context}.m={modules};{runtime_context}.c={module_cache};\n"
      )));
      sources.add(RawStringSource::from(render_runtime_context_accessors(
        (metadata.context_fields() | metadata.context_setter_fields()).difference(
          RuntimeGlobals::REQUIRE
            | RuntimeGlobals::REQUIRE_SCOPE
            | RuntimeGlobals::MODULE_FACTORIES
            | RuntimeGlobals::MODULE_CACHE,
        ),
        &runtime_context,
        runtime_template,
      )));
    }
    if metadata
      .lexical_fields()
      .intersects(*HMR_RUNTIME_STATE_GLOBALS)
    {
      for key in &hmr_state_keys {
        let state_expression = runtime_template.render_hmr_runtime_state_expression(key);
        sources.add(RawStringSource::from(format!("var {state_expression};\n")));
      }
    }

    let mut emitted_fields = RuntimeGlobals::default();
    let mut emitted_setters = RuntimeGlobals::default();
    let setters = metadata.context_setter_fields();
    let mut remaining_setters = setters;
    for (runtime_module_source, generated_requirements, context_requirements, _) in
      runtime_module_sources
    {
      sources.add(runtime_module_source);
      let mut context_fields = metadata.context_fields().intersection(context_requirements);
      if is_hmr_runtime {
        context_fields.insert(generated_requirements.renderable_require_scope());
        context_fields.remove(RuntimeGlobals::REQUIRE | RuntimeGlobals::REQUIRE_SCOPE);
      }
      let context_setters = context_fields.intersection(setters);
      remaining_setters.remove(context_setters);
      sources.add(RawStringSource::from(render_rspack_runtime_exports(
        context_fields,
        context_setters,
        should_export_runtime_globals,
        runtime_template,
        &mut emitted_fields,
        &mut emitted_setters,
      )));
    }
    sources.add(RawStringSource::from(render_rspack_runtime_exports(
      remaining_setters,
      remaining_setters,
      should_export_runtime_globals,
      runtime_template,
      &mut emitted_fields,
      &mut emitted_setters,
    )));

    return sources.boxed();
  }
  wrapped_sources.add(RawStringSource::from(render_lexical_declarations(
    lexical_fields.difference(runtime_module_owned_define_fields(compilation, chunk_ukey)),
    Some(&render_runtime_global),
  )));
  if metadata
    .lexical_fields()
    .intersects(*HMR_RUNTIME_STATE_GLOBALS)
  {
    for key in &hmr_state_keys {
      wrapped_sources.add(RawStringSource::from(format!("var hmrS_{key};\n")));
    }
  }
  for (runtime_module_source, generated_requirements, context_requirements, needs_top_level) in
    runtime_module_sources
  {
    if isolate && needs_top_level {
      sources.add(runtime_module_source);
    } else {
      wrapped_sources.add(runtime_module_source);
    }
    let mut context_fields = metadata.context_fields().intersection(context_requirements);
    if is_hmr_runtime {
      context_fields.insert(generated_requirements.renderable_require_scope());
      context_fields.remove(RuntimeGlobals::REQUIRE | RuntimeGlobals::REQUIRE_SCOPE);
    }
    let setters = metadata.context_setter_fields();
    if context_fields.is_empty() {
      continue;
    }
    for (_, runtime_global) in context_fields.iter_names() {
      let (Some(key), Some(lexical_name)) = (
        runtime_global.rspack_context_property_name(),
        runtime_global.to_lexical_name(),
      ) else {
        continue;
      };
      if setters.contains(runtime_global)
        && (is_hmr_runtime || LIVE_BINDING_CONTEXT_GLOBALS.contains(runtime_global))
      {
        wrapped_sources.add(RawStringSource::from(format!(
          "Object.defineProperty({}, {}, {{ configurable: true, get: function() {{ return {}; }}, set: function(value) {{ {} = value; }} }});\n",
          runtime_context,
          rspack_util::json_stringify(key),
          lexical_name,
          lexical_name
        )));
      } else {
        wrapped_sources.add(RawStringSource::from(format!(
          "{}{} = {};\n",
          runtime_context,
          property_access([key], 0),
          lexical_name
        )));
      }
    }
  }
  if isolate {
    sources.add(RawStringSource::from("(function() {\n".to_string()));
    sources.add(wrapped_sources);
    sources.add(RawStringSource::from("\n}).call(this);\n".to_string()));
  } else {
    sources.add(wrapped_sources);
  }

  sources.boxed()
}

pub async fn render_chunk_runtime_modules(
  compilation: &Compilation,
  chunk_ukey: &ChunkUkey,
  runtime_template: &RuntimeCodeTemplate,
) -> Result<BoxSource> {
  let runtime_module_sources = render_runtime_module_sources(compilation, chunk_ukey, true).await?;
  let mut sources = ConcatSource::default();
  if runtime_module_sources.is_empty() {
    return Ok(sources.boxed());
  }
  let metadata = compilation
    .runtime_proxy_metadata_artifact
    .get(chunk_ukey)
    .expect("should generate runtime metadata");
  let runtime_context = runtime_template.render_runtime_variable(&RuntimeVariable::Context);
  let is_hmr_runtime = metadata
    .tree_runtime_requirements
    .contains(RuntimeGlobals::HMR_DOWNLOAD_MANIFEST);

  sources.add(RawStringSource::from("(function() {\n".to_string()));
  let render_context_field = |runtime_global: RuntimeGlobals| {
    runtime_global
      .rspack_context_property_name()
      .map(|property_name| {
        let value = format!("{runtime_context}{}", property_access([property_name], 0));
        if runtime_global.should_initialize_as_object() {
          format!("{value}||{{}}")
        } else if runtime_global.should_initialize_as_array() {
          format!("{value}||[]")
        } else {
          value
        }
      })
  };
  let render_runtime_global = |runtime_global: RuntimeGlobals| render_context_field(runtime_global);
  sources.add(RawStringSource::from(render_lexical_declarations(
    (metadata.lexical_fields() | metadata.context_setter_fields())
      .difference(runtime_module_owned_define_fields(compilation, chunk_ukey)),
    Some(&render_runtime_global),
  )));

  for (runtime_module_source, generated_requirements, context_requirements, _) in
    runtime_module_sources
  {
    sources.add(runtime_module_source);
    let mut context_fields = metadata.context_fields().intersection(context_requirements);
    if is_hmr_runtime {
      context_fields.insert(generated_requirements.renderable_require_scope());
      context_fields.remove(RuntimeGlobals::REQUIRE | RuntimeGlobals::REQUIRE_SCOPE);
    }

    let setters = metadata.context_setter_fields();
    for (_, runtime_global) in context_fields.iter_names() {
      let (Some(key), Some(lexical_name)) = (
        runtime_global.rspack_context_property_name(),
        runtime_global.to_lexical_name(),
      ) else {
        continue;
      };
      if setters.contains(runtime_global)
        && (is_hmr_runtime || LIVE_BINDING_CONTEXT_GLOBALS.contains(runtime_global))
      {
        sources.add(RawStringSource::from(format!(
          "Object.defineProperty({}, {}, {{ configurable: true, get: function() {{ return {}; }}, set: function(value) {{ {} = value; }} }});\n",
          runtime_context,
          rspack_util::json_stringify(key),
          lexical_name,
          lexical_name
        )));
      } else {
        sources.add(RawStringSource::from(format!(
          "{}{} = {};\n",
          runtime_context,
          property_access([key], 0),
          lexical_name
        )));
      }
    }
  }

  sources.add(RawStringSource::from("\n}).call(this);\n".to_string()));

  Ok(sources.boxed())
}

pub async fn render_hot_update_chunk_runtime_modules(
  compilation: &Compilation,
  chunk_ukey: &ChunkUkey,
  runtime_template: &RuntimeCodeTemplate,
) -> Result<BoxSource> {
  let runtime_module_sources = render_runtime_module_sources(compilation, chunk_ukey, true).await?;
  let mut sources = ConcatSource::default();
  if runtime_module_sources.is_empty() {
    return Ok(sources.boxed());
  }
  let metadata = runtime_context_current_chunk_metadata(compilation, chunk_ukey);

  let runtime_context = runtime_template.render_runtime_argument();
  let mut hmr_state_keys = Vec::new();
  for runtime_module_id in compilation
    .build_chunk_graph_artifact
    .chunk_graph
    .get_chunk_runtime_modules_iterable(chunk_ukey)
  {
    let runtime_module = compilation
      .runtime_modules
      .get(runtime_module_id)
      .expect("should have runtime module");
    let Some(key) = (match runtime_module.get_constructor_name().as_str() {
      "JsonpChunkLoadingRuntimeModule" => Some("jsonp"),
      "ModuleChunkLoadingRuntimeModule" => Some("module"),
      "ImportScriptsChunkLoadingRuntimeModule" => Some("importScripts"),
      "ReadFileChunkLoadingRuntimeModule" => Some("readFileVm"),
      "RequireChunkLoadingRuntimeModule" => Some("require"),
      _ => None,
    }) else {
      continue;
    };
    hmr_state_keys.push(key);
  }

  let render_context_field = |runtime_global: RuntimeGlobals| {
    runtime_global
      .rspack_context_property_name()
      .map(|property_name| {
        let value = format!("{runtime_context}{}", property_access([property_name], 0));
        if runtime_global.should_initialize_as_object() {
          format!("{value}||{{}}")
        } else if runtime_global.should_initialize_as_array() {
          format!("{value}||[]")
        } else {
          value
        }
      })
  };
  sources.add(RawStringSource::from(render_lexical_declarations(
    (metadata.lexical_fields() | metadata.context_setter_fields())
      .difference(runtime_module_owned_define_fields(compilation, chunk_ukey)),
    Some(&render_context_field),
  )));
  if metadata
    .lexical_fields()
    .intersects(*HMR_RUNTIME_STATE_GLOBALS)
  {
    for key in &hmr_state_keys {
      let state_expression =
        if runtime_template.render_mode() == RuntimeGlobalsRenderMode::RspackExport {
          runtime_template.render_hmr_runtime_state_expression(key)
        } else {
          format!("hmrS_{key}")
        };
      sources.add(RawStringSource::from(format!("var {state_expression};\n")));
    }
  }

  let require = runtime_template.render_runtime_variable(&RuntimeVariable::Require);
  let modules = runtime_template.render_runtime_variable(&RuntimeVariable::Modules);
  let module_cache = runtime_template.render_runtime_variable(&RuntimeVariable::ModuleCache);
  sources.add(RawStringSource::from(format!(
    "var {require}={runtime_context}.r,{modules}={runtime_context}.m,{module_cache}={runtime_context}.c;\n"
  )));

  for (runtime_module_source, generated_requirements, _, _) in runtime_module_sources {
    sources.add(runtime_module_source);
    let mut context_fields = metadata
      .context_fields()
      .intersection(generated_requirements);
    context_fields.insert(generated_requirements.renderable_require_scope());
    context_fields.remove(RuntimeGlobals::REQUIRE | RuntimeGlobals::REQUIRE_SCOPE);
    if context_fields.is_empty() {
      continue;
    }
    for (_, runtime_global) in context_fields.iter_names() {
      let (Some(key), Some(lexical_name)) = (
        runtime_global.rspack_context_property_name(),
        runtime_global.to_lexical_name(),
      ) else {
        continue;
      };
      let json_key = rspack_util::json_stringify(key);
      let context_property = property_access([key], 0);
      sources.add(RawStringSource::from(format!(
        r#";(function() {{
var oldSetter = Object.getOwnPropertyDescriptor({runtime_context}, {json_key}) && Object.getOwnPropertyDescriptor({runtime_context}, {json_key}).set;
Object.defineProperty({runtime_context}, {json_key}, {{ configurable: true, get: function() {{ return {lexical_name}; }}, set: function(value) {{ {lexical_name} = value; if (oldSetter) oldSetter.call({runtime_context}, value); }} }});
{runtime_context}{context_property} = {lexical_name};
}})();
"#
      )));
    }
  }

  Ok(sources.boxed())
}

pub async fn render_rspack_runtime_modules(
  compilation: &Compilation,
  chunk_ukey: &ChunkUkey,
  runtime_template: &RuntimeCodeTemplate,
) -> Result<BoxSource> {
  let chunk = compilation
    .build_chunk_graph_artifact
    .chunk_by_ukey
    .expect_get(chunk_ukey);
  if matches!(chunk.kind(), ChunkKind::HotUpdate) {
    render_hot_update_chunk_runtime_modules(compilation, chunk_ukey, runtime_template).await
  } else if chunk.has_runtime(&compilation.build_chunk_graph_artifact.chunk_group_by_ukey) {
    render_runtime_chunk_runtime_modules(compilation, chunk_ukey, runtime_template).await
  } else {
    render_chunk_runtime_modules(compilation, chunk_ukey, runtime_template).await
  }
}

fn runtime_context_current_chunk_metadata(
  compilation: &Compilation,
  chunk_ukey: &ChunkUkey,
) -> RuntimeProxyMetadata {
  let mut metadata = compilation
    .runtime_proxy_metadata_artifact
    .get(chunk_ukey)
    .cloned()
    .unwrap_or_default();
  if let Some(chunk_runtime_requirements) = compilation
    .cgc_runtime_requirements_artifact
    .get(chunk_ukey)
  {
    metadata
      .tree_runtime_requirements
      .insert(*chunk_runtime_requirements);
    metadata
      .runtime_module_requirements
      .insert(*chunk_runtime_requirements);
  }
  for runtime_module_id in compilation
    .build_chunk_graph_artifact
    .chunk_graph
    .get_chunk_runtime_modules_iterable(chunk_ukey)
  {
    let runtime_module = compilation
      .runtime_modules
      .get(runtime_module_id)
      .expect("should have runtime module");
    let module_runtime_requirements = runtime_module.runtime_requirements(compilation);
    metadata
      .tree_runtime_requirements
      .insert(module_runtime_requirements.lexical_requirements());
    metadata
      .runtime_module_requirements
      .insert(module_runtime_requirements.dependencies);
    metadata
      .force_context_fields
      .insert(module_runtime_requirements.force_context);
  }

  metadata
}