importmap-plus 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -1,457 +1,71 @@
1
1
  # importmap-plus
2
2
 
3
- A drop-in replacement for [importmap-rails](https://github.com/rails/importmap-rails) with better vendoring: `bin/importmap pin --minify`, `--from esm.run` for jsDelivr's bundled builds, and a pin comment that remembers which CDN a package came from so later updates go back to it. Everything else is importmap-rails, constants included, so an app switches by changing one line in its `Gemfile`.
3
+ A drop-in replacement for [importmap-rails](https://github.com/rails/importmap-rails) with vendoring that keeps its promises: `bin/importmap pin --minify`, `--from esm.run` for jsDelivr's bundled builds, `--lock` to hold a package at a version, `update` by package name, and a pin comment that remembers where each package came from so later updates respect it. Everything else is importmap-rails, constants included, so an app switches by changing one line in its `Gemfile`.
4
4
 
5
- **Install this gem or importmap-rails, never both** — they define the same `Importmap::` constants and the same engine.
6
-
7
- See [what this adds](#loading-bundles-from-esmrun) below; the rest of this README is importmap-rails' own, which this gem tracks at the version in `Importmap::UPSTREAM_VERSION`.
8
-
9
- ---
10
-
11
- [Import maps](https://github.com/WICG/import-maps) let you import JavaScript modules using logical names that map to versioned/digested files – directly from the browser. So you can [build modern JavaScript applications using JavaScript libraries made for ES modules (ESM) without the need for transpiling or bundling](https://world.hey.com/dhh/modern-web-apps-without-javascript-bundling-or-transpiling-a20f2755). This frees you from needing Webpack, Yarn, npm, or any other part of the JavaScript toolchain. All you need is the asset pipeline that's already included in Rails.
12
-
13
- With this approach you'll ship many small JavaScript files instead of one big JavaScript file. Thanks to HTTP/2 that no longer carries a material performance penalty during the initial transport, and in fact offers substantial benefits over the long run due to better caching dynamics. Whereas before any change to any JavaScript file included in your big bundle would invalidate the cache for the whole bundle, now only the cache for that single file is invalidated.
14
-
15
- [Import maps are supported natively in all major, modern browsers](https://caniuse.com/?search=importmap). If you need to work with legacy browsers without native support, you can explore using [the shim available](https://github.com/guybedford/es-module-shims).
5
+ **Documentation: [importmap-plus.zoolutions.llc](https://importmap-plus.zoolutions.llc)** — also as [llms.txt](https://importmap-plus.zoolutions.llc/llms.txt) and a read-only MCP endpoint at `https://importmap-plus.zoolutions.llc/mcp`.
16
6
 
7
+ **Install this gem or importmap-rails, never both** — they define the same `Importmap::` constants and the same engine.
17
8
 
18
9
  ## Installation
19
10
 
20
- Rails 7+ ships importmap-rails for new applications. To use importmap-plus instead:
21
-
22
- 1. Replace `gem "importmap-rails"` with `gem "importmap-plus"` in your `Gemfile`, or run `./bin/bundle add importmap-plus` in an app that has neither
23
- 2. Run `./bin/rails importmap:install` if the app has no `config/importmap.rb` yet
24
-
25
- An app already on importmap-rails needs nothing else: the pins, the `config/importmap.rb`, the helpers and the `Importmap::` constants are unchanged.
26
-
27
- Note: In order to use JavaScript from Rails frameworks like Action Cable, Action Text, and Active Storage, you must be running Rails 7.0+. This was the first version that shipped with ESM compatible builds of these libraries.
28
-
29
- You can pin those libraries manually by relying on the compiled versions included in Rails like this:
30
-
31
- ```ruby
32
- pin "@rails/actioncable", to: "actioncable.esm.js"
33
- pin "@rails/activestorage", to: "activestorage.esm.js"
34
- pin "@rails/actiontext", to: "actiontext.esm.js"
35
- pin "trix"
36
- ```
37
-
38
- ## How do importmaps work?
39
-
40
- At their core, importmaps are essentially a string substitution for what are referred to as "bare module specifiers". A "bare module specifier" looks like this: `import React from "react"`. This is not compatible with the ES Module loader spec. Instead, to be ESM compatible, you must provide 1 of the 3 following types of specifiers:
41
-
42
- - Absolute path:
43
- ```js
44
- import React from "/Users/DHH/projects/basecamp/node_modules/react"
45
- ```
46
-
47
- - Relative path:
48
- ```js
49
- import React from "./node_modules/react"
50
- ```
51
-
52
- - HTTP path:
53
- ```js
54
- import React from "https://ga.jspm.io/npm:react@17.0.1/index.js"
55
- ```
56
-
57
- Importmap-rails provides a clean API for mapping "bare module specifiers" like `"react"`
58
- to 1 of the 3 viable ways of loading ES Module javascript packages.
59
-
60
- For example:
61
-
62
- ```rb
63
- # config/importmap.rb
64
- pin "react", to: "https://ga.jspm.io/npm:react@17.0.2/index.js"
65
- ```
66
-
67
- means "every time you see `import React from "react"`
68
- change it to `import React from "https://ga.jspm.io/npm:react@17.0.2/index.js"`"
69
-
70
- ```js
71
- import React from "react"
72
- // => import React from "https://ga.jspm.io/npm:react@17.0.2/index.js"
73
- ```
74
-
75
- ## Usage
76
-
77
- 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.
78
-
79
- 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. Then 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`.
80
-
81
- It's in `app/javascript/application.js` you setup your application by importing any of the modules that have been defined in the import map. You can use the full ESM functionality of importing any particular export of the modules or everything.
82
-
83
- It makes sense to use logical names that match the package names used by npm, such that if you later want to start transpiling or bundling your code, you won't have to change any module imports.
84
-
85
- ### Local modules
86
-
87
- If you want to import local js module files from `app/javascript/src` or other sub-folders of `app/javascript` (such as `channels`), you must pin these to be able to import them. You can use `pin_all_from` to pick all files in a specific folder, so you don't have to `pin` each module individually.
88
-
89
- ```rb
90
- # config/importmap.rb
91
- pin_all_from 'app/javascript/src', under: 'src', to: 'src'
92
-
93
- # With automatic integrity calculation for enhanced security
94
- enable_integrity!
95
- pin_all_from 'app/javascript/controllers', under: 'controllers', integrity: true
96
- ```
97
-
98
- The `:to` parameter is only required if you want to change the destination logical import name. If you drop the :to option, you must place the :under option directly after the first parameter.
99
-
100
- The `enable_integrity!` call enables integrity calculation globally, and `integrity: true` automatically calculates integrity hashes for all files in the directory, providing security benefits without manual hash management.
101
-
102
- Allows you to:
103
-
104
- ```js
105
- // app/javascript/application.js
106
- import { ExampleFunction } from 'src/example_function'
107
- ```
108
- Which imports the function from `app/javascript/src/example_function.js`.
109
-
110
- Note: Sprockets used to serve assets (albeit without filename digests) it couldn't find from the `app/javascripts` folder with logical relative paths, meaning pinning local files wasn't needed. Propshaft doesn't have this fallback, so when you use Propshaft you have to pin your local modules.
11
+ Replace `gem "importmap-rails"` with `gem "importmap-plus"` in your `Gemfile` and run `bundle install`. An app already on importmap-rails needs nothing else: the pins, `config/importmap.rb`, the helpers and the `Importmap::` constants are unchanged.
111
12
 
112
- ## Using npm packages via JavaScript CDNs
113
-
114
- Importmap for Rails downloads and vendors your npm package dependencies via JavaScript CDNs that provide pre-compiled distribution versions.
115
-
116
- You can use the `./bin/importmap` command that's added as part of the install to pin, unpin, or update npm packages in your import map. By default this command uses an API from [JSPM.org](https://jspm.org) to resolve your package dependencies efficiently, and then add the pins to your `config/importmap.rb` file.
117
-
118
- ```bash
119
- ./bin/importmap pin react
120
- Pinning "react" to vendor/javascript/react.js via download from https://ga.jspm.io/npm:react@19.1.0/index.js
121
- ```
122
-
123
- This will produce a pin in your `config/importmap.rb` like so:
124
-
125
- ```ruby
126
- pin "react" # @19.1.0
127
- ```
128
-
129
- Other CDNs like [unpkg.com](https://unpkg.com) and [jsdelivr.com](https://www.jsdelivr.com) can be specified with `--from`:
130
-
131
- ```bash
132
- ./bin/importmap pin react --from unpkg
133
- Pinning "react" to vendor/javascript/react.js via download from https://unpkg.com/react@19.1.0/index.js
134
- ```
135
-
136
- ```bash
137
- ./bin/importmap pin react --from jsdelivr
138
- Pinning "react" to vendor/javascript/react.js via download from https://cdn.jsdelivr.net/npm/react@19.1.0/index.js
139
- ```
140
-
141
- The packages are downloaded to `vendor/javascript`, which you can check into your source control, and they'll be available through your application's own asset pipeline serving.
142
-
143
- If you later wish to remove a downloaded pin:
13
+ An app without an import map yet:
144
14
 
145
15
  ```bash
146
- ./bin/importmap unpin react
147
- Unpinning and removing "react"
148
- ```
149
-
150
- ### Pinning to remote CDN URLs
151
-
152
- If you'd rather load a package straight from the CDN instead of vendoring a download, pass `--remote`:
16
+ ./bin/bundle add importmap-plus
17
+ ./bin/rails importmap:install
18
+ ```
19
+
20
+ ## What it adds
21
+
22
+ | | |
23
+ |---|---|
24
+ | `pin --minify` | Runs a download through bun, esbuild or terser before it lands in `vendor/javascript`; later updates keep minifying it. |
25
+ | `--from esm.run` | Vendors jsDelivr's one-file bundle, rewrites its imports to bare specifiers, and pins the dependencies it needs. |
26
+ | `pin --lock`, `lock`, `unlock` | Holds a package at a version. `update`, `pristine` and `pin` leave it there until you unlock it or pass `--force`. |
27
+ | `update [PACKAGES] --all --force` | Update by name, or everything explicitly; `--force` moves locked packages and re-locks them. |
28
+ | Multi-file packages | A package whose entry imports siblings by relative path is vendored with its whole file graph, mapped by one `pin_all_from` line. One that needs more than files can give it — a worker, `import.meta.url`, a `.wasm` — stays on its CDN with the reason on the pin. |
29
+ | Registry-latest, then CDN fallback | A bare name is resolved on the npm registry, then asked of jspm, esm.run and jsDelivr in turn until one of them has it. `--from` disables the fallback. |
30
+ | `doctor` | Checks the import map against the files that are actually there — offline, reporting only, non-zero on an error — so CI catches a 404 that otherwise shows up on one page in the browser. |
31
+ | Provenance | The pin comment records the CDN, minification, lock and why a package was kept remote — `pin "luxon" # @3.7.2 (esm.run, minified, locked)` — so nothing silently drifts back to jspm. |
32
+ | Remote pins stay remote | A pin with a CDN URL is re-resolved from that CDN and carries a subresource-integrity hash of the bytes that were resolved; `preload:` and a boolean `integrity:` survive every rewrite; a custom URL is left alone. |
33
+ | Preload what the page reaches | `config.importmap.preload_strategy = :reachable` preloads what the entry point actually imports rather than every preloaded pin, and `config.importmap.early_hints` sends those links as a 103 Early Hints response. Both opt-in. |
34
+ | Requests retry | A reset connection, a timeout or a 429/5xx is tried three times with a growing pause before the command gives up. |
153
35
 
154
36
  ```bash
155
- ./bin/importmap pin react --remote
156
- Pinning "react" to https://ga.jspm.io/npm:react@19.1.0/index.js
37
+ ./bin/importmap pin luxon --from esm.run --minify
38
+ ./bin/importmap pin @hotwired/stimulus@3.2.2 --lock
39
+ ./bin/importmap update stimulus-use
40
+ ./bin/importmap outdated
41
+ ./bin/importmap doctor
157
42
  ```
158
43
 
159
- This will produce a pin in your `config/importmap.rb` like so:
160
-
161
- ```ruby
162
- pin "react", to: "https://ga.jspm.io/npm:react@19.1.0/index.js"
163
- ```
164
-
165
- Remote pins are respected from then on — no `--remote` flag needed. When a remote-pinned package is pinned again or picked up by `./bin/importmap update` (whether directly or as a dependency of another package), the pin stays remote: the URL is re-resolved from the same CDN provider it already points to (`ga.jspm.io`, `unpkg.com`, `cdn.jsdelivr.net`, `cdn.skypack.dev`, or `esm.sh`) instead of being replaced with a download. Pins pointing at any other host are left completely untouched and reported as skipped, and `./bin/importmap pristine` skips remote pins since there is nothing to redownload.
166
-
167
- Options on existing pins, like `preload: false`, are preserved when a pin is rewritten. An explicit `integrity:` value is dropped when the URL changes, since the old hash would no longer match — see the SRI section below for pinning fresh integrity hashes.
168
-
169
- ### Loading bundles from esm.run
170
-
171
- [esm.run](https://www.jsdelivr.com/esm) is jsDelivr's bundling endpoint: it serves one minified ES module per package, no matter what the package ships on npm. Where jspm hands you a package's own `dist` file (unminified for plenty of packages), `--from esm.run` gives you the bundle:
172
-
173
- ```bash
174
- ./bin/importmap pin luxon --from esm.run
175
- Pinning "luxon" to vendor/javascript/luxon.js via download from https://cdn.jsdelivr.net/npm/luxon@3.7.2/+esm
176
- ```
177
-
178
- A bundle references the packages it depends on as absolute `/npm/dep@1.2.3/+esm` imports, which only resolve on jsDelivr. When the bundle is vendored, those imports are rewritten to bare specifiers (`import { Controller } from "@hotwired/stimulus"`) so they resolve through your import map, and every dependency without a pin is pinned the same way — vendored from esm.run, at the version the bundle was built against:
179
-
180
- ```bash
181
- ./bin/importmap pin stimulus-use --from esm.run
182
- Pinning "stimulus-use" to vendor/javascript/stimulus-use.js via download from https://cdn.jsdelivr.net/npm/stimulus-use@0.53.1/+esm
183
- Keeping existing pin for "@hotwired/stimulus" (bundle was built against @3.2.2)
184
- ```
185
-
186
- A dependency you already pin is left alone: the bundle then resolves to whatever your import map says, exactly like a jspm download would. With `--remote`, the pin points at the bundle URL and its imports load from jsDelivr as-is.
187
-
188
- Versions are resolved through jsDelivr's data API, so `pin luxon@3 --from esm.run` and subpaths like `pin apexcharts/core --from esm.run` work the way they do on npm.
189
-
190
- ### Where a package came from is remembered
191
-
192
- The version comment on a vendored pin also names the CDN when it isn't jspm:
193
-
194
- ```ruby
195
- pin "luxon" # @3.7.2 (esm.run)
196
- pin "react" # @19.1.0 (unpkg)
197
- ```
198
-
199
- `./bin/importmap update` and `./bin/importmap pristine` read it and go back to the same CDN — an esm.run bundle stays a bundle, an unpkg download stays on unpkg — and so does `pin` when you leave out `--from`. Pass `--from` to move a package to another CDN; an explicit `--from` moves a remote pin too, which is otherwise re-resolved from the CDN it already points at.
200
-
201
- ### Minifying vendored packages
202
-
203
- Lighthouse's unminified-javascript audit will tell you which packages ship unminified builds. Pass `--minify` to run a download through a JavaScript minifier before it lands in `vendor/javascript`:
204
-
205
- ```bash
206
- ./bin/importmap pin luxon --minify
207
- Pinning "luxon" to vendor/javascript/luxon.js via download from https://ga.jspm.io/npm:luxon@3.7.2/build/es6/luxon.mjs (minified)
208
- ```
209
-
210
- The first of [bun](https://bun.sh), [esbuild](https://esbuild.github.io) or [terser](https://terser.org) found in `node_modules/.bin` or on your `PATH` is used, always in transform-only mode so bare import specifiers are left exactly as the CDN resolved them. The pin records it (`pin "luxon" # @3.7.2 (minified)`, or `(esm.run, minified)` for a bundle), and from then on `update`, `pristine` and a plain `pin` keep minifying that package; `--no-minify` turns it off again, and `./bin/importmap pristine --minify` minifies everything you have vendored in one go.
211
-
212
- To use a different minifier, assign anything that responds to `call(source)` and returns the minified source. `bin/importmap` loads `config/application.rb` but not your initializers, so the assignment has to happen there (or in a file it requires):
213
-
214
- ```ruby
215
- # config/application.rb
216
- require "importmap/packager"
217
-
218
- Importmap::Packager.minifier = ->(source) { MyMinifier.minify(source) }
219
- ```
220
-
221
- ## Subresource Integrity (SRI)
222
-
223
- For enhanced security, importmap-rails supports [Subresource Integrity (SRI)](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) hashes for packages loaded from external CDNs.
224
-
225
- ### Automatic integrity for local assets
226
-
227
- To enable automatic integrity calculation for local assets served by the Rails asset pipeline, you must first call `enable_integrity!` in your importmap configuration:
228
-
229
44
  ```ruby
230
45
  # config/importmap.rb
231
-
232
- # Enable integrity calculation globally
233
- enable_integrity!
234
-
235
- # With integrity enabled, these will auto-calculate integrity hashes
236
- pin "application" # Auto-calculated integrity
237
- pin "admin", to: "admin.js" # Auto-calculated integrity
238
- pin_all_from "app/javascript/controllers", under: "controllers" # Auto-calculated integrity
239
-
240
- # Mixed usage - explicitly controlling integrity
241
- pin "cdn_package", integrity: "sha384-abc123..." # Pre-calculated hash
242
- pin "no_integrity_package", integrity: false # Explicitly disable integrity
243
- pin "nil_integrity_package", integrity: nil # Explicitly disable integrity
244
- ```
245
-
246
- This is particularly useful for:
247
- * **Local JavaScript files** managed by your Rails asset pipeline
248
- * **Bulk operations** with `pin_all_from` where calculating hashes manually would be tedious
249
- * **Development workflow** where asset contents change frequently
250
-
251
- **Note:** Integrity calculation is opt-in and must be enabled with `enable_integrity!`. This behavior can be further controlled by setting `integrity: false` or `integrity: nil` on individual pins.
252
-
253
- **Important for Propshaft users:** SRI support requires Propshaft 1.2+ and you must configure the integrity hash algorithm in your application:
254
-
255
- ```ruby
256
- # config/application.rb or config/environments/*.rb
257
- config.assets.integrity_hash_algorithm = 'sha256' # or 'sha384', 'sha512'
258
- ```
259
-
260
- Without this configuration, integrity will be disabled by default when using Propshaft. Sprockets includes integrity support out of the box.
261
-
262
- **Example output with `enable_integrity!` and `integrity: true`:**
263
- ```json
264
- {
265
- "imports": {
266
- "application": "/assets/application-abc123.js",
267
- "controllers/hello_controller": "/assets/controllers/hello_controller-def456.js"
268
- },
269
- "integrity": {
270
- "/assets/application-abc123.js": "sha256-xyz789...",
271
- "/assets/controllers/hello_controller-def456.js": "sha256-uvw012..."
272
- }
273
- }
46
+ pin "luxon" # @3.7.2 (esm.run, minified)
47
+ pin "@hotwired/stimulus", to: "@hotwired--stimulus.js" # @3.2.2 (locked)
48
+ pin "@popperjs/core", to: "@popperjs--core.js" # @2.11.8
49
+ pin_all_from "vendor/javascript/@popperjs--core", under: "@popperjs/core", to: "@popperjs--core" # @2.11.8 (graph of @popperjs/core)
50
+ pin "fflate", to: "https://ga.jspm.io/npm:fflate@0.8.2/esm/browser.js" # @0.8.2 (remote: workers)
274
51
  ```
275
52
 
276
- ### How integrity works
277
-
278
- The integrity hashes are automatically included in your import map and module preload tags:
279
-
280
- **Import map JSON:**
281
- ```json
282
- {
283
- "imports": {
284
- "lodash": "https://ga.jspm.io/npm:lodash@4.17.21/lodash.js",
285
- "application": "/assets/application-abc123.js",
286
- "controllers/hello_controller": "/assets/controllers/hello_controller-def456.js"
287
- },
288
- "integrity": {
289
- "https://ga.jspm.io/npm:lodash@4.17.21/lodash.js": "sha384-PkIkha4kVPRlGtFantHjuv+Y9mRefUHpLFQbgOYUjzy247kvi16kLR7wWnsAmqZF"
290
- "/assets/application-abc123.js": "sha256-xyz789...",
291
- "/assets/controllers/hello_controller-def456.js": "sha256-uvw012..."
292
- }
293
- }
294
- ```
295
-
296
- **Module preload tags:**
297
- ```html
298
- <link rel="modulepreload" href="https://ga.jspm.io/npm:lodash@4.17.21/lodash.js" integrity="sha384-PkIkha4kVPRlGtFantHjuv+Y9mRefUHpLFQbgOYUjzy247kvi16kLR7wWnsAmqZF">
299
- <link rel="modulepreload" href="/assets/application-abc123.js" integrity="sha256-xyz789...">
300
- <link rel="modulepreload" href="/assets/controllers/hello_controller-def456.js" integrity="sha256-uvw012...">
301
- ```
302
-
303
- Modern browsers will automatically validate these integrity hashes when loading the JavaScript modules, ensuring the files haven't been modified.
304
-
305
- ## Preloading pinned modules
306
-
307
- To avoid the waterfall effect where the browser has to load one file after another before it can get to the deepest nested import, importmap-rails uses [modulepreload links](https://developers.google.com/web/updates/2017/12/modulepreload) by default. If you don't want to preload a dependency, because you want to load it on-demand for efficiency, append `preload: false` to the pin.
308
-
309
- Example:
310
-
311
- ```ruby
312
- # config/importmap.rb
313
- pin "@github/hotkey", to: "@github--hotkey.js" # file lives in vendor/javascript/@github--hotkey.js
314
- pin "md5", preload: false # file lives in vendor/javascript/md5.js
315
-
316
- # app/views/layouts/application.html.erb
317
- <%= javascript_importmap_tags %>
318
-
319
- # will include the following link before the importmap is setup:
320
- <link rel="modulepreload" href="/assets/javascript/@github--hotkey.js">
321
- ...
322
- ```
323
-
324
- You can also specify which entry points to preload a particular dependency in by providing `preload:` a string or array of strings.
325
-
326
- Example:
327
-
328
- ```ruby
329
- # config/importmap.rb
330
- pin "@github/hotkey", to: "@github--hotkey.js", preload: 'application'
331
- pin "md5", preload: ['application', 'alternate']
332
-
333
- # app/views/layouts/application.html.erb
334
- <%= javascript_importmap_tags 'alternate' %>
335
-
336
- # will include the following link before the importmap is setup:
337
- <link rel="modulepreload" href="/assets/javascript/md5.js">
338
- ...
339
- ```
53
+ The full guide — every command, option and behaviour, plus importmap-rails' own documentation for the parts that are unchanged — is at [importmap-plus.zoolutions.llc](https://importmap-plus.zoolutions.llc).
340
54
 
55
+ ## Tracking importmap-rails
341
56
 
57
+ This gem tracks importmap-rails at the release named in `Importmap::UPSTREAM_VERSION`; its own version is `Importmap::VERSION`. Upstream changes are merged as they land, and the parts of the documentation that describe upstream behaviour are kept in step. See [CHANGELOG.md](CHANGELOG.md) for what each release adds.
342
58
 
343
- ## Composing import maps
59
+ ## Development
344
60
 
345
- By default, Rails loads import map definition from the application's `config/importmap.rb` to the `Importmap::Map` object available at `Rails.application.importmap`.
346
-
347
- You can combine multiple import maps by adding paths to additional import map configs to `Rails.application.config.importmap.paths`. For example, appending import maps defined in Rails engines:
348
-
349
- ```ruby
350
- # my_engine/lib/my_engine/engine.rb
351
-
352
- module MyEngine
353
- class Engine < ::Rails::Engine
354
- # ...
355
- initializer "my-engine.importmap", before: "importmap" do |app|
356
- app.config.importmap.paths << Engine.root.join("config/importmap.rb")
357
- # ...
358
- end
359
- end
360
- end
361
- ```
362
-
363
- And pinning JavaScript modules from the engine:
364
-
365
- ```ruby
366
- # my_engine/config/importmap.rb
367
-
368
- pin_all_from File.expand_path("../app/assets/javascripts", __dir__)
369
- ```
370
-
371
-
372
- ## Selectively importing modules
373
-
374
- You can selectively import your javascript modules on specific pages.
375
-
376
- Create your javascript in `app/javascript`:
377
-
378
- ```js
379
- // /app/javascript/checkout.js
380
- // some checkout specific js
381
- ```
382
-
383
- Pin your js file:
384
-
385
- ```rb
386
- # config/importmap.rb
387
- # ... other pins...
388
- pin "checkout", preload: false
389
- ```
390
-
391
- Import your module on the specific page. Note: you'll likely want to use a `content_for` block on the specific page/partial, then yield it in your layout.
392
-
393
- ```erb
394
- <% content_for :head do %>
395
- <%= javascript_import_module_tag "checkout" %>
396
- <% end %>
397
- ```
398
-
399
- **Important**: The `javascript_import_module_tag` should come after your `javascript_importmap_tags`
400
-
401
- ```erb
402
- <%= javascript_importmap_tags %>
403
- <%= yield(:head) %>
404
- ```
405
-
406
-
407
- ## Include a digest of the import map in your ETag
408
-
409
- If you're using [ETags](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) generated by Rails helpers like `stale?` or `fresh_when`, you need to include the digest of the import map into this calculation. Otherwise your application will return [304](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304) cache responses even when your JavaScript assets have changed. You can avoid this using the `stale_when_importmap_changes` method:
410
-
411
- ```ruby
412
- class ApplicationController < ActionController::Base
413
- stale_when_importmap_changes
414
- end
415
- ```
416
-
417
- This will add the digest of the importmap to the etag calculation when the request format is HTML.
418
-
419
-
420
- ## Sweeping the cache in development and test
421
-
422
- 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`.
423
-
424
- If you're pinning local files from outside of `app/javascript`, you'll need to add them to the cache sweeper configuration or restart your development server upon changes to those external files. For example, here's how you can do it for Rails engine:
425
-
426
- ```ruby
427
- # my_engine/lib/my_engine/engine.rb
428
-
429
- module MyEngine
430
- class Engine < ::Rails::Engine
431
- # ...
432
- initializer "my-engine.importmap", before: "importmap" do |app|
433
- # ...
434
- app.config.importmap.cache_sweepers << Engine.root.join("app/assets/javascripts")
435
- end
436
- end
437
- end
61
+ ```bash
62
+ bundle install
63
+ bundle exec rake test # the command tests talk to live CDNs (jspm, jsDelivr)
64
+ cd docs && bin/dev # the docs site, a docs-kit app at docs/
438
65
  ```
439
66
 
440
- ## Checking for outdated or vulnerable packages
441
-
442
- Importmap for Rails provides two commands to check your pinned packages:
443
- - `./bin/importmap outdated` checks the NPM registry for new versions
444
- - `./bin/importmap audit` checks the NPM registry for known security issues
445
-
446
- ## Supporting legacy browsers such as Safari on iOS 15
447
-
448
- If you want to support [legacy browsers that do not support import maps](https://caniuse.com/import-maps) such as [iOS 15.8.1 released on 22 Jan 2024](https://support.apple.com/en-us/HT201222), insert [`es-module-shims`](https://github.com/guybedford/es-module-shims) before `javascript_importmap_tags` as below.
449
-
450
- ```erb
451
- <script async src="https://ga.jspm.io/npm:es-module-shims@1.8.2/dist/es-module-shims.js" data-turbo-track="reload"></script>
452
- <%= javascript_importmap_tags %>
453
- ```
67
+ Releases are cut with `bin/release`, which tags a version and publishes a GitHub Release; that fires `.github/workflows/release.yml` (RubyGems trusted publishing) and `.github/workflows/deploy-docs.yml` (the docs site).
454
68
 
455
69
  ## License
456
70
 
457
- Importmap for Rails is released under the [MIT License](https://opensource.org/licenses/MIT).
71
+ Importmap for Rails is released under the [MIT License](https://opensource.org/licenses/MIT), and so is importmap-plus.
@@ -1,6 +1,9 @@
1
1
  module Importmap::ImportmapTagsHelper
2
2
  # Setup all script tags needed to use an importmap-powered entrypoint (which defaults to application.js)
3
3
  def javascript_importmap_tags(entry_point = "application", importmap: Rails.application.importmap)
4
+ preloaded = importmap.preloaded_module_packages(resolver: self, entry_point:, cache_key: entry_point)
5
+ Importmap::EarlyHints.send_modulepreload_links(self, preloaded)
6
+
4
7
  safe_join [
5
8
  javascript_inline_importmap_tag(importmap.to_json(resolver: self)),
6
9
  javascript_importmap_module_preload_tags(importmap, entry_point:),
@@ -0,0 +1,133 @@
1
+ require "importmap/provider_chain"
2
+
3
+ # Resolves a group of specs against a CDN, batch first and then one at a time.
4
+ #
5
+ # The batch is the fast path and stays: one round trip, and jspm resolves the
6
+ # specs' shared dependencies as a single graph, which is what upstream does.
7
+ # But a CDN answers a batch as a whole — one spec its generator can't build is
8
+ # "no" for all of them — so a refused batch of more than one spec says nothing
9
+ # about the specs in it. Each is then asked on its own, along the path it would
10
+ # have taken alone: through the chain when the group named no CDN, of the same
11
+ # provider once when it did. A package that was always going to resolve is
12
+ # pinned from the CDN it was always going to be pinned from, whatever its
13
+ # siblings did.
14
+ #
15
+ # Specs nobody could resolve are collected rather than raised: each pin is
16
+ # independent of the others, so the rest still land and the exit code says the
17
+ # command didn't do all it was asked.
18
+ class Importmap::BatchResolver
19
+ # The specs no CDN answered for, in the order they were asked.
20
+ attr_reader :unresolved
21
+
22
+ # +on_miss+ is the command's own "couldn't find" reporter, so the sentence a
23
+ # single spec gets is written in exactly one place.
24
+ def initialize(packager, on_miss:, chain: Importmap::ProviderChain.new)
25
+ @packager = packager
26
+ @on_miss = on_miss
27
+ @chain = chain
28
+ @unresolved = []
29
+ end
30
+
31
+ # Yields [ package, url ] for everything that resolved, as it resolves, so a
32
+ # spec that fails later can't discard the work of one that succeeded earlier.
33
+ def each_import(specs, env:, from:, fallback:, &block)
34
+ @named = specs.map { |spec| @packager.package_key_for(spec) }
35
+ @seen = {}
36
+
37
+ if specs.one?
38
+ resolve_one(specs.first, env: env, from: from, fallback: fallback, &block)
39
+ elsif (response = resolve_batch(specs, env: env, from: from, fallback: fallback))
40
+ emit(specs, response, &block)
41
+ else
42
+ specs.each { |spec| resolve_one(spec, env: env, from: from, fallback: fallback, &block) }
43
+ end
44
+ end
45
+
46
+ private
47
+ # The batch a group with no CDN of its own sends goes to jspm alone. Handing
48
+ # the whole list to the next CDN is what moved a healthy package's provenance
49
+ # when a sibling failed; the specs travel the rest of the chain separately.
50
+ def resolve_batch(specs, env:, from:, fallback:)
51
+ provider = fallback ? Importmap::ProviderChain::DEFAULT : from
52
+ error = nil
53
+
54
+ response =
55
+ begin
56
+ @packager.import(*specs, env: env, from: provider)
57
+ rescue Importmap::Packager::Error => raised
58
+ error = raised
59
+ nil
60
+ end
61
+
62
+ return response if response
63
+
64
+ report_split(specs, provider, error&.message || @packager.last_import_error, fallback)
65
+ nil
66
+ end
67
+
68
+ def report_split(specs, provider, reason, fallback)
69
+ detail = Importmap::ProviderChain.tidy_reason(reason)
70
+ miss = if fallback
71
+ %(#{provider} couldn't resolve #{quoted(specs)})
72
+ else
73
+ %(Couldn't find any packages in #{specs.inspect} on #{provider})
74
+ end
75
+
76
+ puts miss + (detail ? %( (#{detail})) : "") + "; asking for each on its own"
77
+ end
78
+
79
+ def resolve_one(spec, env:, from:, fallback:, &block)
80
+ source = fallback ? Importmap::ProviderChain.to_sentence : from
81
+
82
+ if (response = request_one(spec, env: env, from: from, fallback: fallback))
83
+ emit([ spec ], response, &block)
84
+ else
85
+ # A chain that came up empty has already said why each CDN couldn't.
86
+ @on_miss.call([ spec ], source, reason: fallback ? nil : @packager.last_import_error)
87
+ @unresolved << spec
88
+ end
89
+ rescue Importmap::Packager::Error => error
90
+ puts %(Couldn't resolve "#{spec}" from #{source}: #{error.message})
91
+ @unresolved << spec
92
+ end
93
+
94
+ def request_one(spec, env:, from:, fallback:)
95
+ if fallback
96
+ @chain.resolve(@packager, [ spec ], env: env) { |_provider, response| response }
97
+ else
98
+ @packager.import(spec, env: env, from: from)
99
+ end
100
+ end
101
+
102
+ # Split responses overlap: each carries the dependencies of its own spec.
103
+ # A spec the user named answers for itself, so a sibling's response naming
104
+ # it is a dependency edge and not the answer asked for. Anything else is
105
+ # taken from the first response that carried it, because rewriting it to a
106
+ # second URL would move a package the user never mentioned.
107
+ def emit(specs, response, &block)
108
+ asked_for = specs.map { |spec| @packager.package_key_for(spec) }
109
+
110
+ response[:imports].each do |package, url|
111
+ next if @named.include?(package) && !asked_for.include?(package)
112
+
113
+ if (kept = @seen[package])
114
+ report_kept(package, kept, url, specs.first) unless kept == url
115
+ else
116
+ @seen[package] = url
117
+ block.call(package, url)
118
+ end
119
+ end
120
+ end
121
+
122
+ def report_kept(package, kept, url, spec)
123
+ puts %(Keeping "#{package}" at #{version(kept)} ("#{spec}" resolved it to #{version(url)}))
124
+ end
125
+
126
+ def version(url)
127
+ @packager.extract_package_version_from(url) || url
128
+ end
129
+
130
+ def quoted(specs)
131
+ specs.map { |spec| %("#{spec}") }.join(", ")
132
+ end
133
+ end