BuilderModuleRecord.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System.Collections.Generic;
  2. using Esprima.Ast;
  3. using Jint.Native;
  4. namespace Jint.Runtime.Modules;
  5. /// <summary>
  6. /// This is a custom ModuleRecord implementation for dynamically built modules using <see cref="ModuleBuilder"/>
  7. /// </summary>
  8. internal sealed class BuilderModuleRecord : SourceTextModuleRecord
  9. {
  10. private List<KeyValuePair<string, JsValue>> _exportBuilderDeclarations = new();
  11. internal BuilderModuleRecord(Engine engine, Realm realm, Module source, string location, bool async)
  12. : base(engine, realm, source, location, async)
  13. {
  14. }
  15. internal void BindExportedValue(string name, JsValue value)
  16. {
  17. if (_environment != null)
  18. {
  19. ExceptionHelper.ThrowInvalidOperationException("Cannot bind exported values after the environment has been initialized");
  20. }
  21. _exportBuilderDeclarations ??= new();
  22. _exportBuilderDeclarations.Add(new KeyValuePair<string, JsValue>(name, value));
  23. }
  24. protected override void InitializeEnvironment()
  25. {
  26. base.InitializeEnvironment();
  27. if (_exportBuilderDeclarations != null)
  28. {
  29. for (var i = 0; i < _exportBuilderDeclarations.Count; i++)
  30. {
  31. var d = _exportBuilderDeclarations[i];
  32. _environment.CreateImmutableBindingAndInitialize(d.Key, true, d.Value);
  33. _localExportEntries.Add(new ExportEntry(d.Key, null, null, d.Key));
  34. }
  35. _exportBuilderDeclarations.Clear();
  36. }
  37. }
  38. }