Class: Dommy::Js::ImportMap

Inherits:
Object
  • Object
show all
Defined in:
lib/dommy/js/import_map.rb

Overview

A parsed <script type="importmap">: resolves bare specifiers to URLs per the import-maps proposal (the subset Rails' importmap-rails and most apps use — imports with exact and trailing-slash-prefix matches, plus basic scopes). Relative/absolute specifiers are not the import map's job; the ModuleLoader resolves those against the importer.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = {}) ⇒ ImportMap

Returns a new instance of ImportMap.



21
22
23
24
# File 'lib/dommy/js/import_map.rb', line 21

def initialize(data = {})
  @imports = data["imports"].is_a?(Hash) ? data["imports"] : {}
  @scopes = data["scopes"].is_a?(Hash) ? data["scopes"] : {}
end

Class Method Details

.parse(json) ⇒ Object

Build from the importmap JSON text (a <script type=importmap> body). An empty/invalid map resolves nothing.



16
17
18
19
# File 'lib/dommy/js/import_map.rb', line 16

def self.parse(json)
  data = json.to_s.strip.empty? ? {} : (JSON.parse(json) rescue {})
  new(data.is_a?(Hash) ? data : {})
end

Instance Method Details

#empty?Boolean

Returns:

  • (Boolean)


26
# File 'lib/dommy/js/import_map.rb', line 26

def empty? = @imports.empty? && @scopes.empty?

#resolve(specifier, importer = nil) ⇒ Object

Resolve a bare specifier to a URL string, or nil when unmapped. A scope whose prefix matches the importer wins over the top-level imports; within each map, an exact key wins over the longest trailing-slash prefix.



32
33
34
# File 'lib/dommy/js/import_map.rb', line 32

def resolve(specifier, importer = nil)
  scope_map(importer)&.then { |m| match(m, specifier) } || match(@imports, specifier)
end