importmap-rails 0.6.3 → 0.7.3

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e83ed6ee74e2b39acc314afedb47331aa6499f73cefd377813d35042c5edef99
4
- data.tar.gz: 2892356151da356c2ca221d9cdb34742c7f258641481079f32c7e3a65b92155b
3
+ metadata.gz: a6bef1930a7817f62361604877196991706c6dd6ac589d41fb615bb3cd21cdb6
4
+ data.tar.gz: 7cd5da364f95e8ea04104e57d22c42e9fe1351451a51d22fa1247456dda6fa10
5
5
  SHA512:
6
- metadata.gz: a31bde4420db119b939f660310262b2ce56bf9dc2dba8c6a255c565ce99d127361584917e378445b6a500675295a502912e49e772aec37a95d32b1d51d9def85
7
- data.tar.gz: 79dbc56c9c96dd85ef65d9d0cca3baee1c1e0c8e80e25f99b3823dd1828a20297261ea7fb21f13c7dea980c13358c9872cb09b2217704c293f260b17d11a510f
6
+ metadata.gz: e3e7e6e12f99afc8d69756142f5c1fa8945d541489d5950cdf36adeb8b7f6dcf5c8b7924b64b8a4d003bcef16bf2522fb435da54b3c74afdd4d2db88c838c54e
7
+ data.tar.gz: b8c8b2ab0472abb4c7eac50ad4c2a858d4210939438e095b367608323ae72b08e514075e12846282020ae98f1664d61e2e826c214441d442cecfda9b6c10b765
data/README.md CHANGED
@@ -20,7 +20,7 @@ Note: In order to use JavaScript from Rails frameworks like Action Cable, Action
20
20
 
21
21
  ## Usage
22
22
 
23
- The import map is setup through `Rails.application.config.importmap` via the configuration in `config/importmap.rb`. This file is automatically reloaded in development upon changes, but note that you must restart the server if you remove pins and need them gone from the rendered importmap or list of preloads.
23
+ The import map is setup through `Rails.application.importmap` via the configuration in `config/importmap.rb`. This file is automatically reloaded in development upon changes, but note that you must restart the server if you remove pins and need them gone from the rendered importmap or list of preloads.
24
24
 
25
25
  This import map is inlined in the `<head>` of your application layout using `<%= javascript_importmap_tags %>`, which will setup the JSON configuration inside a `<script type="importmap">` tag. After that, the [es-module-shim](https://github.com/guybedford/es-module-shims) is loaded, and then finally the application entrypoint is imported via `<script type="module">import "application"</script>`. That logical entrypoint, `application`, is mapped in the importmap script tag to the file `app/javascript/application.js`.
26
26
 
@@ -143,9 +143,9 @@ pin "md5", to: "https://cdn.jsdelivr.net/npm/md5@2.3.0/md5.js", preload: false
143
143
 
144
144
  ## Composing import maps
145
145
 
146
- By default, Rails loads import map definition from the application's `config/importmap.rb` to the `Importmap::Map` object available at `Rails.application.config.importmap`.
146
+ By default, Rails loads import map definition from the application's `config/importmap.rb` to the `Importmap::Map` object available at `Rails.application.importmap`.
147
147
 
148
- You can combine multiple import maps by drawing their definitions onto the `Rails.application.config.importmap`. For example, appending import maps defined in Rails engines:
148
+ You can combine multiple import maps by drawing their definitions onto the `Rails.application.importmap`. For example, appending import maps defined in Rails engines:
149
149
 
150
150
  ```ruby
151
151
  # my_engine/lib/my_engine/engine.rb
@@ -175,10 +175,16 @@ If you're using etags generated by Rails helpers like `stale?` or `fresh_when`,
175
175
 
176
176
  ```ruby
177
177
  class ApplicationController < ActionController::Base
178
- etag { Rails.application.config.importmap.digest(resolver: helpers) if request.format&.html? }
178
+ etag { Rails.application.importmap.digest(resolver: helpers) if request.format&.html? }
179
179
  end
180
180
  ```
181
181
 
182
+
183
+ ## Sweeping the cache in development and test
184
+
185
+ Generating the import map json and modulepreloads may require resolving hundreds of assets. This can take a while, so these operations are cached, but in development and test, we watch for changes to both `config/importmap.rb` and files in `app/javascript` to clear this cache. This feature can be controlled in an environment configuration file via the boolean `config.importmap.sweep_cache`. If you're pinning local files from outside of `app/javascript`, you'll need to restart your development server upon changes.
186
+
187
+
182
188
  ## Expected errors from using the es-module-shim
183
189
 
184
190
  While import maps are native in Chrome and Edge, they need a shim in other browsers that'll produce a JavaScript console error like `TypeError: Module specifier, 'application' does not start with "/", "./", or "../".`. This error is normal and does not have any user-facing consequences.
@@ -188,10 +194,12 @@ While import maps are native in Chrome and Edge, they need a shim in other brows
188
194
 
189
195
  Under certain circumstances, like running system tests using chromedriver under CI (which may be resource constrained and trigger errors in certain cases), you may want to explicitly turn off including the shim. If can do this by calling the bulk tag helper with `javascript_importmap_tags("application", shim: false)`. Thus you can pass in something like `shim: !ENV["CI"]`. If you want, and are sure you're not doing any full-page caching, you can also connect this directive to a user agent check (using a gem like `useragent`) to check whether the browser is chrome/edge 89+. But you really shouldn't have to, as the shim is designed to gracefully work with natively compatible drivers.
190
196
 
197
+
191
198
  ## A note about browser extensions
192
199
 
193
200
  Certain extensions that also load Javascript modules may block import maps from being loaded (for instance, the Apollo Client Devtools extension). If you see a console message like `An import map is added after module script load was triggered`, browser extensions are likely the culprit.
194
201
 
202
+
195
203
  ## License
196
204
 
197
205
  Importmap for Rails is released under the [MIT License](https://opensource.org/licenses/MIT).
@@ -1,8 +1,6 @@
1
- /* ES Module Shims CSP 0.15.1 */
1
+ /* ES Module Shims 1.0.0 */
2
2
  (function () {
3
3
 
4
- Promise.resolve();
5
-
6
4
  const edge = navigator.userAgent.match(/Edge\/\d\d\.\d+$/);
7
5
 
8
6
  let baseUrl;
@@ -331,7 +329,7 @@
331
329
 
332
330
  let importMap = { imports: {}, scopes: {} };
333
331
  let importMapSrcOrLazy = false;
334
- let importMapPromise = featureDetectionPromise;
332
+ let importMapPromise = featureDetectionPromise.then(() => undefined);
335
333
 
336
334
  let acceptingImportMaps = true;
337
335
  let nativeAcceptingImportMaps = true;
@@ -346,21 +344,20 @@
346
344
  }
347
345
  await importMapPromise;
348
346
  // early analysis opt-out - no need to even fetch if we have feature support
349
- if (!shimMode && supportsDynamicImport && supportsImportMeta && supportsImportMaps && (!jsonModulesEnabled || supportsJsonAssertions) && (!cssModulesEnabled || supportsCssAssertions) && !importMapSrcOrLazy) {
347
+ if (!shimMode && supportsDynamicImport && supportsImportMeta && supportsImportMaps && (!jsonModulesEnabled || supportsJsonAssertions) && (!cssModulesEnabled || supportsCssAssertions) && !importMapSrcOrLazy && !false) {
350
348
  // for polyfill case, only dynamic import needs a return value here, and dynamic import will never pass nativelyLoaded
351
349
  if (nativelyLoaded)
352
350
  return null;
353
351
  await lastStaticLoadPromise;
354
352
  return dynamicImport(source ? createBlob(source) : url, { errUrl: url || source });
355
353
  }
356
- await undefined;
357
354
  const load = getOrCreateLoad(url, fetchOpts, source);
358
355
  const seen = {};
359
356
  await loadAll(load, seen);
360
357
  lastLoad = undefined;
361
358
  resolveDeps(load, seen);
362
359
  await lastStaticLoadPromise;
363
- if (source && !shimMode && !load.n) {
360
+ if (source && !shimMode && !load.n && !false) {
364
361
  const module = await dynamicImport(createBlob(source), { errUrl: source });
365
362
  if (revokeBlobURLs) revokeObjectURLs(Object.keys(seen));
366
363
  return module;
@@ -490,17 +487,11 @@
490
487
  resolvedSource += source.slice(lastIndex);
491
488
  }
492
489
 
493
- resolvedSource = resolvedSource.replace(/\/\/# sourceMappingURL=(.*)\s*$/, (match, url) => {
494
- return match.replace(url, new URL(url, load.r));
495
- });
490
+ resolvedSource = resolvedSource.replace(/\/\/# sourceMappingURL=(.*)\s*$/, (match, url) => match.replace(url, () => new URL(url, load.r)));
496
491
  let hasSourceURL = false;
497
- resolvedSource = resolvedSource.replace(/\/\/# sourceURL=(.*)\s*$/, (match, url) => {
498
- hasSourceURL = true;
499
- return match.replace(url, new URL(url, load.r));
500
- });
501
- if (!hasSourceURL) {
492
+ resolvedSource = resolvedSource.replace(/\/\/# sourceURL=(.*)\s*$/, (match, url) => (hasSourceURL = true, match.replace(url, () => new URL(url, load.r))));
493
+ if (!hasSourceURL)
502
494
  resolvedSource += '\n//# sourceURL=' + load.r;
503
- }
504
495
 
505
496
  load.b = lastLoad = createBlob(resolvedSource);
506
497
  load.S = undefined;
@@ -627,13 +618,10 @@
627
618
  return load;
628
619
  }
629
620
 
630
- const scriptQuery = 'script[type="module-shim"],script[type="importmap-shim"],script[type="module"],script[type="importmap"]';
631
- const preloadQuery = 'link[rel="modulepreload"]';
632
-
633
621
  function processScripts () {
634
- for (const link of document.querySelectorAll(preloadQuery))
622
+ for (const link of document.querySelectorAll('link[rel="modulepreload"]'))
635
623
  processPreload(link);
636
- const scripts = document.querySelectorAll(scriptQuery);
624
+ const scripts = document.querySelectorAll('script[type="module-shim"],script[type="importmap-shim"],script[type="module"],script[type="importmap"]');
637
625
  // early shim mode opt-in
638
626
  if (!shimMode) {
639
627
  for (const script of scripts) {
@@ -11,8 +11,8 @@ module Importmap::ImportmapTagsHelper
11
11
  end
12
12
 
13
13
  # Generate an inline importmap tag using the passed `importmap_json` JSON string.
14
- # By default, `Rails.application.config.importmap.to_json(resolver: self)` is used.
15
- def javascript_inline_importmap_tag(importmap_json = Rails.application.config.importmap.to_json(resolver: self))
14
+ # By default, `Rails.application.importmap.to_json(resolver: self)` is used.
15
+ def javascript_inline_importmap_tag(importmap_json = Rails.application.importmap.to_json(resolver: self))
16
16
  tag.script importmap_json.html_safe,
17
17
  type: "importmap", "data-turbo-track": "reload", nonce: content_security_policy_nonce
18
18
  end
@@ -39,9 +39,9 @@ module Importmap::ImportmapTagsHelper
39
39
  end
40
40
 
41
41
  # Link tags for preloading all modules marked as preload: true in the `importmap`
42
- # (defaults to Rails.application.config.importmap), such that they'll be fetched
42
+ # (defaults to Rails.application.importmap), such that they'll be fetched
43
43
  # in advance by browsers supporting this link type (https://caniuse.com/?search=modulepreload).
44
- def javascript_importmap_module_preload_tags(importmap = Rails.application.config.importmap)
44
+ def javascript_importmap_module_preload_tags(importmap = Rails.application.importmap)
45
45
  javascript_module_preload_tag(*importmap.preloaded_module_paths(resolver: self))
46
46
  end
47
47
 
@@ -43,7 +43,7 @@ class Importmap::Commands < Thor
43
43
 
44
44
  desc "json", "Show the full importmap in json"
45
45
  def json
46
- puts Rails.application.config.importmap.to_json(resolver: ActionController::Base.helpers)
46
+ puts Rails.application.importmap.to_json(resolver: ActionController::Base.helpers)
47
47
  end
48
48
 
49
49
  private
@@ -1,10 +1,19 @@
1
1
  require "importmap/map"
2
2
 
3
+ # Use Rails.application.importmap to access the map
4
+ Rails::Application.send(:attr_accessor, :importmap)
5
+
3
6
  module Importmap
4
7
  class Engine < ::Rails::Engine
5
- config.importmap = Importmap::Map.new.draw("config/importmap.rb")
8
+ config.importmap = ActiveSupport::OrderedOptions.new
9
+ config.importmap.sweep_cache = Rails.env.development? || Rails.env.test?
10
+
6
11
  config.autoload_once_paths = %W( #{root}/app/helpers )
7
12
 
13
+ initializer "importmap" do |app|
14
+ app.importmap = Importmap::Map.new.draw("config/importmap.rb")
15
+ end
16
+
8
17
  initializer "importmap.reloader" do |app|
9
18
  app.config.paths.add "config/importmap.rb"
10
19
 
@@ -15,6 +24,16 @@ module Importmap
15
24
  end
16
25
  end
17
26
 
27
+ initializer "importmap.cache_sweeper" do |app|
28
+ if app.config.importmap.sweep_cache
29
+ app.importmap.cache_sweeper watches: app.root.join("app/javascript")
30
+
31
+ ActiveSupport.on_load(:action_controller_base) do
32
+ before_action { Rails.application.importmap.cache_sweeper.execute_if_updated }
33
+ end
34
+ end
35
+ end
36
+
18
37
  initializer "importmap.assets" do
19
38
  if Rails.application.config.respond_to?(:assets)
20
39
  Rails.application.config.assets.precompile += %w( es-module-shims.js )
data/lib/importmap/map.rb CHANGED
@@ -50,12 +50,26 @@ class Importmap::Map
50
50
  # Example:
51
51
  #
52
52
  # class ApplicationController < ActionController::Base
53
- # etag { Rails.application.config.importmap.digest(resolver: helpers) if request.format&.html? }
53
+ # etag { Rails.application.importmap.digest(resolver: helpers) if request.format&.html? }
54
54
  # end
55
55
  def digest(resolver:)
56
56
  Digest::SHA1.hexdigest(to_json(resolver: resolver).to_s)
57
57
  end
58
58
 
59
+ # Returns an instance ActiveSupport::EventedFileUpdateChecker configured to clear the cache of the map
60
+ # when the directories passed on initialization via `watches:` have changes. This is used in development
61
+ # and test to ensure the map caches are reset when javascript files are changed.
62
+ def cache_sweeper(watches: nil)
63
+ if watches
64
+ @cache_sweeper =
65
+ Rails.application.config.file_watcher.new([], Array(watches).collect { |dir| [ dir.to_s, "js"] }.to_h) do
66
+ clear_cache
67
+ end
68
+ else
69
+ @cache_sweeper
70
+ end
71
+ end
72
+
59
73
  private
60
74
  MappedDir = Struct.new(:dir, :path, :under, :preload, keyword_init: true)
61
75
  MappedFile = Struct.new(:name, :path, :preload, keyword_init: true)
@@ -2,7 +2,7 @@ class Importmap::Reloader
2
2
  delegate :execute_if_updated, :execute, :updated?, to: :updater
3
3
 
4
4
  def reload!
5
- import_map_paths.each { |path| config.importmap.draw(path) }
5
+ import_map_paths.each { |path| Rails.application.importmap.draw(path) }
6
6
  end
7
7
 
8
8
  private
@@ -1,3 +1,3 @@
1
1
  module Importmap
2
- VERSION = "0.6.3"
2
+ VERSION = "0.7.3"
3
3
  end
@@ -7,6 +7,6 @@ namespace :importmap do
7
7
  desc "Show the importmap"
8
8
  task :pins do
9
9
  require Rails.root.join("config/environment")
10
- puts Rails.application.config.importmap.to_json(resolver: ActionController::Base.helpers)
10
+ puts Rails.application.importmap.to_json(resolver: ActionController::Base.helpers)
11
11
  end
12
12
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: importmap-rails
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.3
4
+ version: 0.7.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - David Heinemeier Hansson
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2021-09-19 00:00:00.000000000 Z
11
+ date: 2021-09-21 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rails