@esm.sh/import-map 0.1.0 → 0.2.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.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  The MIT License (MIT)
2
2
 
3
- Copyright (c) 2024-2025 Je Xia <i@jex.me>
3
+ Copyright (c) 2025-2026 Je Xia <i@jex.me>
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,3 +1,143 @@
1
- # import-map
1
+ # @esm.sh/import-map
2
2
 
3
- A [import maps](https://wicg.github.io/import-maps/) parser and resolver.
3
+ An [Import Maps](https://wicg.github.io/import-maps/) manager.
4
+
5
+ - create blank import maps
6
+ - parse import maps from JSON/HTML
7
+ - resolve specifiers with `imports` and `scopes`
8
+ - add npm/jsr/github packages from [esm.sh](https://esm.sh) CDN into an import map
9
+ - maintain optional `integrity` metadata
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm i @esm.sh/import-map
15
+ ```
16
+
17
+ ## API
18
+
19
+ ### `createBlankImportMap(baseURL?: string)`
20
+
21
+ Create an empty import map:
22
+
23
+ ```ts
24
+ import { createBlankImportMap } from "@esm.sh/import-map";
25
+
26
+ const im = createBlankImportMap("file:///");
27
+ ```
28
+
29
+ ### `importMapFrom(value: any, baseURL?: string)`
30
+
31
+ Build an import map from a JS object.
32
+ Supports `config`, `imports`, `scopes`, and `integrity`.
33
+ Non-string values inside these maps are removed during validation.
34
+
35
+ ```ts
36
+ import { importMapFrom } from "@esm.sh/import-map";
37
+
38
+ const im = importMapFrom({
39
+ imports: { react: "https://esm.sh/react@19.2.4/es2022/react.mjs" },
40
+ integrity: { "https://esm.sh/react@19.2.4/es2022/react.mjs": "sha384-..." },
41
+ });
42
+ ```
43
+
44
+ ### `parseImportMapFromJson(json: string, baseURL?: string)`
45
+
46
+ Parse an import map from JSON text.
47
+ Preserves and validates `config`, `imports`, `scopes`, and `integrity`.
48
+
49
+ ```ts
50
+ import { parseImportMapFromJson } from "@esm.sh/import-map";
51
+
52
+ const im = parseImportMapFromJson(`{
53
+ "imports": {
54
+ "react": "https://esm.sh/react@19.2.4/es2022/react.mjs"
55
+ }
56
+ }`);
57
+ ```
58
+
59
+ ### `parseImportMapFromHtml(html: string, baseURL?: string)`
60
+
61
+ Parse the first `<script type="importmap">` from HTML (browser environment). Returns an empty import map if no `importmap` script tag is found.
62
+
63
+ ```ts
64
+ import { parseImportMapFromHtml } from "@esm.sh/import-map";
65
+
66
+ const im = parseImportMapFromHtml(`<script type="importmap">
67
+ {
68
+ "imports": {
69
+ "react": "https://esm.sh/react@19.2.4/es2022/react.mjs"
70
+ }
71
+ }
72
+ </script>`);
73
+ ```
74
+
75
+ > Note: This function requires a browser environment.
76
+
77
+ ### `resolve(importMap: ImportMap, specifier: string, containingFile: string)`
78
+
79
+ Resolve a specifier using import-map matching rules:
80
+
81
+ ```ts
82
+ import { resolve } from "@esm.sh/import-map";
83
+
84
+ const [url, ok] = resolve(im, "react", "file:///app/main.ts");
85
+ ```
86
+
87
+ Returns `[resolvedUrl, true]` when matched, otherwise `[originalSpecifier, false]`.
88
+
89
+ ### `addImport(importMap: ImportMap, specifier: string, noSRI?: boolean)`
90
+
91
+ Fetch package metadata from [esm.sh](https://esm.sh) CDN and add an import entry (plus relevant deps)
92
+ into the map.
93
+
94
+ Supported specifiers include:
95
+
96
+ - npm: `react@19.2.4`, `react-dom@19/client`
97
+ - jsr: `jsr:@std/fs@1.0.0`
98
+ - github: `gh:owner/repo@tag`
99
+
100
+ Behavior highlights:
101
+
102
+ - adds top-level specifier into `imports`
103
+ - adds nested deps into `scopes` when needed
104
+ - cleans up empty scopes
105
+ - updates `integrity` unless `noSRI` is `true`
106
+
107
+ ```ts
108
+ import { addImport, createBlankImportMap } from "@esm.sh/import-map";
109
+
110
+ const im = createBlankImportMap();
111
+ await addImport(im, "react-dom@19/client");
112
+ ```
113
+
114
+ ### `isSupportImportMap()`
115
+
116
+ Returns whether the current browser supports import maps.
117
+
118
+ ```ts
119
+ import { isSupportImportMap } from "@esm.sh/import-map";
120
+
121
+ const supported = isSupportImportMap();
122
+ ```
123
+
124
+ ### `isBlankImportMap(importMap: ImportMap)`
125
+
126
+ Returns `true` when `imports` and `scopes` are empty.
127
+
128
+ ```ts
129
+ import { isBlankImportMap } from "@esm.sh/import-map";
130
+
131
+ const blank = isBlankImportMap(im);
132
+ ```
133
+
134
+ ## Development
135
+
136
+ ```bash
137
+ npm test
138
+ npm run build
139
+ ```
140
+
141
+ ## License
142
+
143
+ MIT
package/dist/add.mjs ADDED
@@ -0,0 +1,374 @@
1
+ import { satisfies, valid } from "semver";
2
+ async function addImport(importMap, specifier, noSRI) {
3
+ const imp = parseImportSpecifier(specifier);
4
+ const config = importMap.config ?? {};
5
+ const target = normalizeTarget(config.target);
6
+ const cdnOrigin = getCdnOrigin(config.cdn);
7
+ const meta = await fetchImportMeta(cdnOrigin, imp, target);
8
+ const mark = /* @__PURE__ */ new Set();
9
+ await addImportMeta(importMap, mark, meta, false, void 0, cdnOrigin, target, noSRI ?? false);
10
+ }
11
+ const KNOWN_TARGETS = /* @__PURE__ */ new Set([
12
+ "es2015",
13
+ "es2016",
14
+ "es2017",
15
+ "es2018",
16
+ "es2019",
17
+ "es2020",
18
+ "es2021",
19
+ "es2022",
20
+ "es2023",
21
+ "es2024",
22
+ "esnext"
23
+ ]);
24
+ const ESM_SEGMENTS = /* @__PURE__ */ new Set([
25
+ "es2015",
26
+ "es2016",
27
+ "es2017",
28
+ "es2018",
29
+ "es2019",
30
+ "es2020",
31
+ "es2021",
32
+ "es2022",
33
+ "es2023",
34
+ "es2024",
35
+ "esnext",
36
+ "denonext",
37
+ "deno",
38
+ "node"
39
+ ]);
40
+ const SPECIFIER_MARK_SEPARATOR = "\0";
41
+ const META_CACHE = /* @__PURE__ */ new Map();
42
+ function parseImportSpecifier(specifier) {
43
+ let source = specifier.trim();
44
+ const imp = {
45
+ name: "",
46
+ version: "",
47
+ subPath: "",
48
+ github: false,
49
+ jsr: false,
50
+ external: false,
51
+ dev: false
52
+ };
53
+ if (source.startsWith("gh:")) {
54
+ imp.github = true;
55
+ source = source.slice(3);
56
+ } else if (source.startsWith("jsr:")) {
57
+ imp.jsr = true;
58
+ source = source.slice(4);
59
+ }
60
+ let scopeName = "";
61
+ if ((source.startsWith("@") || imp.github) && source.includes("/")) {
62
+ [scopeName, source] = splitByFirst(source, "/");
63
+ }
64
+ let packageAndVersion = "";
65
+ [packageAndVersion, imp.subPath] = splitByFirst(source, "/");
66
+ [imp.name, imp.version] = splitByFirst(packageAndVersion, "@");
67
+ if (scopeName) {
68
+ imp.name = `${scopeName}/${imp.name}`;
69
+ }
70
+ if (!imp.name) {
71
+ throw new Error(`invalid package name or version: ${specifier}`);
72
+ }
73
+ return imp;
74
+ }
75
+ function normalizeTarget(target) {
76
+ if (target && KNOWN_TARGETS.has(target)) {
77
+ return target;
78
+ }
79
+ return "es2022";
80
+ }
81
+ function getCdnOrigin(cdn) {
82
+ if (cdn && (cdn.startsWith("https://") || cdn.startsWith("http://"))) {
83
+ return cdn.replace(/\/+$/, "");
84
+ }
85
+ return "https://esm.sh";
86
+ }
87
+ function specifierOf(imp) {
88
+ const prefix = imp.github ? "gh:" : imp.jsr ? "jsr:" : "";
89
+ return `${prefix}${imp.name}${imp.subPath ? `/${imp.subPath}` : ""}`;
90
+ }
91
+ function esmSpecifierOf(imp) {
92
+ const prefix = imp.github ? "gh/" : imp.jsr ? "jsr/" : "";
93
+ const external = hasExternalImports(imp) ? "*" : "";
94
+ return `${prefix}${external}${imp.name}@${imp.version}`;
95
+ }
96
+ function registryPrefix(imp) {
97
+ if (imp.github) {
98
+ return "gh/";
99
+ }
100
+ if (imp.jsr) {
101
+ return "jsr/";
102
+ }
103
+ return "";
104
+ }
105
+ function hasExternalImports(meta) {
106
+ if (meta.peerImports.length > 0) {
107
+ return true;
108
+ }
109
+ for (const dep of meta.imports) {
110
+ if (!dep.startsWith("/node/") && !dep.startsWith(`/${meta.name}@`)) {
111
+ return true;
112
+ }
113
+ }
114
+ return false;
115
+ }
116
+ function moduleUrlOf(cdnOrigin, target, imp) {
117
+ let url = `${cdnOrigin}/${esmSpecifierOf(imp)}/${target}/`;
118
+ if (imp.subPath) {
119
+ if (imp.dev || imp.subPath === "jsx-dev-runtime") {
120
+ url += `${imp.subPath}.development.mjs`;
121
+ } else {
122
+ url += `${imp.subPath}.mjs`;
123
+ }
124
+ return url;
125
+ }
126
+ const fileName = imp.name.includes("/") ? imp.name.split("/").at(-1) : imp.name;
127
+ return `${url}${fileName}.mjs`;
128
+ }
129
+ async function fetchImportMeta(cdnOrigin, imp, target) {
130
+ const star = imp.external ? "*" : "";
131
+ const version = imp.version ? `@${imp.version}` : "";
132
+ const subPath = imp.subPath ? `/${imp.subPath}` : "";
133
+ const targetQuery = target !== "es2022" ? `&target=${encodeURIComponent(target)}` : "";
134
+ const url = `${cdnOrigin}/${star}${registryPrefix(imp)}${imp.name}${version}${subPath}?meta${targetQuery}`;
135
+ const cached = META_CACHE.get(url);
136
+ if (cached) {
137
+ return cached;
138
+ }
139
+ const pending = (async () => {
140
+ const res = await fetch(url);
141
+ if (res.status === 404) {
142
+ throw new Error(`package not found: ${imp.name}${version}${subPath}`);
143
+ }
144
+ if (!res.ok) {
145
+ throw new Error(`unexpected http status ${res.status}: ${await res.text()}`);
146
+ }
147
+ const bodyText = await res.text();
148
+ let data;
149
+ try {
150
+ data = JSON.parse(bodyText);
151
+ } catch {
152
+ throw new Error(`invalid meta response from ${url}: ${bodyText.slice(0, 200)}`);
153
+ }
154
+ return {
155
+ name: data.name ?? imp.name,
156
+ version: data.version ?? imp.version,
157
+ subPath: imp.subPath,
158
+ github: imp.github,
159
+ jsr: imp.jsr,
160
+ external: imp.external,
161
+ dev: imp.dev,
162
+ module: data.module ?? "",
163
+ integrity: data.integrity ?? "",
164
+ exports: data.exports ?? [],
165
+ imports: data.imports ?? [],
166
+ peerImports: data.peerImports ?? []
167
+ };
168
+ })();
169
+ META_CACHE.set(url, pending);
170
+ try {
171
+ return await pending;
172
+ } catch (error) {
173
+ META_CACHE.delete(url);
174
+ throw error;
175
+ }
176
+ }
177
+ async function addImportMeta(importMap, mark, imp, indirect, targetImports, cdnOrigin, target, noSRI) {
178
+ const markedSpecifier = `${specifierOf(imp)}${SPECIFIER_MARK_SEPARATOR}${imp.version}`;
179
+ if (mark.has(markedSpecifier)) {
180
+ return;
181
+ }
182
+ mark.add(markedSpecifier);
183
+ const cdnScopeKey = `${cdnOrigin}/`;
184
+ const cdnScopeImports = importMap.scopes?.[cdnScopeKey];
185
+ const imports = indirect ? targetImports ?? ensureScope(importMap, cdnScopeKey) : importMap.imports;
186
+ const moduleUrl = moduleUrlOf(cdnOrigin, target, imp);
187
+ const currentSpecifier = specifierOf(imp);
188
+ imports[currentSpecifier] = moduleUrl;
189
+ await updateIntegrity(importMap, imp, moduleUrl, cdnOrigin, target, noSRI);
190
+ if (!indirect) {
191
+ if (cdnScopeImports) {
192
+ delete cdnScopeImports[currentSpecifier];
193
+ }
194
+ pruneEmptyScopes(importMap);
195
+ }
196
+ const allDeps = [
197
+ ...imp.peerImports.map((pathname) => ({ pathname, isPeer: true })),
198
+ ...imp.imports.map((pathname) => ({ pathname, isPeer: false }))
199
+ ];
200
+ await Promise.all(
201
+ allDeps.map(async ({ pathname, isPeer }) => {
202
+ if (pathname.startsWith("/node/")) {
203
+ return;
204
+ }
205
+ const depImport = parseEsmPath(pathname);
206
+ if (depImport.name === imp.name) {
207
+ depImport.version = imp.version;
208
+ }
209
+ const depSpecifier = specifierOf(depImport);
210
+ const existingUrl = importMap.imports[depSpecifier] ?? importMap.scopes?.[cdnScopeKey]?.[depSpecifier];
211
+ let scopedTargetImports = targetImports;
212
+ if (existingUrl?.startsWith(`${cdnOrigin}/`)) {
213
+ const existingImport = parseEsmPath(existingUrl);
214
+ const existingVersion = valid(existingImport.version);
215
+ if (existingVersion && depImport.version === existingImport.version) {
216
+ return;
217
+ }
218
+ if (existingVersion && depImport.version && !valid(depImport.version)) {
219
+ if (satisfies(existingVersion, depImport.version, { includePrerelease: true })) {
220
+ return;
221
+ }
222
+ if (isPeer) {
223
+ console.warn(
224
+ `incorrect peer dependency(unmeet ${depImport.version}): ${depImport.name}@${existingVersion}`
225
+ );
226
+ return;
227
+ }
228
+ const scope = `${cdnOrigin}/${esmSpecifierOf(imp)}/`;
229
+ scopedTargetImports = ensureScope(importMap, scope);
230
+ }
231
+ }
232
+ const depMeta = await fetchImportMeta(cdnOrigin, depImport, target);
233
+ await addImportMeta(importMap, mark, depMeta, !isPeer, scopedTargetImports, cdnOrigin, target, noSRI);
234
+ })
235
+ );
236
+ pruneEmptyScopes(importMap);
237
+ }
238
+ async function updateIntegrity(importMap, imp, moduleUrl, cdnOrigin, target, noSRI) {
239
+ if (noSRI) {
240
+ if (importMap.integrity) {
241
+ delete importMap.integrity[moduleUrl];
242
+ if (Object.keys(importMap.integrity).length === 0) {
243
+ delete importMap.integrity;
244
+ }
245
+ }
246
+ return;
247
+ }
248
+ if (!hasExternalImports(imp)) {
249
+ if (imp.integrity) {
250
+ importMap.integrity ??= {};
251
+ importMap.integrity[moduleUrl] = imp.integrity;
252
+ }
253
+ return;
254
+ }
255
+ const integrityMeta = await fetchImportMeta(
256
+ cdnOrigin,
257
+ {
258
+ name: imp.name,
259
+ version: imp.version,
260
+ subPath: imp.subPath,
261
+ github: imp.github,
262
+ jsr: imp.jsr,
263
+ external: true,
264
+ dev: imp.dev
265
+ },
266
+ target
267
+ );
268
+ if (integrityMeta.integrity) {
269
+ importMap.integrity ??= {};
270
+ importMap.integrity[moduleUrl] = integrityMeta.integrity;
271
+ }
272
+ }
273
+ function ensureScope(importMap, scopeKey) {
274
+ importMap.scopes ??= {};
275
+ importMap.scopes[scopeKey] ??= {};
276
+ return importMap.scopes[scopeKey];
277
+ }
278
+ function pruneEmptyScopes(importMap) {
279
+ if (!importMap.scopes) {
280
+ return;
281
+ }
282
+ for (const [scope, imports] of Object.entries(importMap.scopes)) {
283
+ if (Object.keys(imports).length === 0) {
284
+ delete importMap.scopes[scope];
285
+ }
286
+ }
287
+ if (Object.keys(importMap.scopes).length === 0) {
288
+ delete importMap.scopes;
289
+ }
290
+ }
291
+ function parseEsmPath(pathnameOrUrl) {
292
+ let pathname;
293
+ if (pathnameOrUrl.startsWith("https://") || pathnameOrUrl.startsWith("http://")) {
294
+ pathname = new URL(pathnameOrUrl).pathname;
295
+ } else if (pathnameOrUrl.startsWith("/")) {
296
+ pathname = splitByFirst(splitByFirst(pathnameOrUrl, "#")[0], "?")[0];
297
+ } else {
298
+ throw new Error(`invalid pathname or url: ${pathnameOrUrl}`);
299
+ }
300
+ const imp = {
301
+ name: "",
302
+ version: "",
303
+ subPath: "",
304
+ github: false,
305
+ jsr: false,
306
+ external: false,
307
+ dev: false
308
+ };
309
+ if (pathname.startsWith("/gh/")) {
310
+ imp.github = true;
311
+ pathname = pathname.slice(3);
312
+ } else if (pathname.startsWith("/jsr/")) {
313
+ imp.jsr = true;
314
+ pathname = pathname.slice(4);
315
+ }
316
+ const segs = pathname.split("/").filter(Boolean);
317
+ if (segs.length === 0) {
318
+ throw new Error(`invalid pathname: ${pathnameOrUrl}`);
319
+ }
320
+ if (segs[0].startsWith("@")) {
321
+ if (!segs[1]) {
322
+ throw new Error(`invalid pathname: ${pathnameOrUrl}`);
323
+ }
324
+ const [name, version] = splitByLast(segs[1], "@");
325
+ imp.name = `${segs[0]}/${name}`.replace(/^\*/, "");
326
+ imp.version = version;
327
+ segs.splice(0, 2);
328
+ } else {
329
+ const [name, version] = splitByLast(segs[0], "@");
330
+ imp.name = name.replace(/^\*/, "");
331
+ imp.version = version;
332
+ segs.splice(0, 1);
333
+ }
334
+ let hasTargetSegment = false;
335
+ if (segs[0] && ESM_SEGMENTS.has(segs[0])) {
336
+ hasTargetSegment = true;
337
+ segs.shift();
338
+ }
339
+ if (segs.length > 0) {
340
+ if (hasTargetSegment && pathname.endsWith(".mjs")) {
341
+ let subPath = segs.join("/");
342
+ if (subPath.endsWith(".mjs")) {
343
+ subPath = subPath.slice(0, -4);
344
+ }
345
+ if (subPath.endsWith(".development")) {
346
+ subPath = subPath.slice(0, -12);
347
+ imp.dev = true;
348
+ }
349
+ if (subPath.includes("/") || subPath !== imp.name && !imp.name.endsWith(`/${subPath}`)) {
350
+ imp.subPath = subPath;
351
+ }
352
+ } else {
353
+ imp.subPath = segs.join("/");
354
+ }
355
+ }
356
+ return imp;
357
+ }
358
+ function splitByFirst(value, separator) {
359
+ const idx = value.indexOf(separator);
360
+ if (idx < 0) {
361
+ return [value, ""];
362
+ }
363
+ return [value.slice(0, idx), value.slice(idx + separator.length)];
364
+ }
365
+ function splitByLast(value, separator) {
366
+ const idx = value.lastIndexOf(separator);
367
+ if (idx < 0) {
368
+ return [value, ""];
369
+ }
370
+ return [value.slice(0, idx), value.slice(idx + separator.length)];
371
+ }
372
+ export {
373
+ addImport
374
+ };
package/dist/blank.mjs ADDED
@@ -0,0 +1,17 @@
1
+ function createBlankImportMap(baseURL) {
2
+ return {
3
+ baseURL: new URL(baseURL ?? ".", "file:///"),
4
+ imports: {}
5
+ };
6
+ }
7
+ function isBlankImportMap(importMap) {
8
+ const { imports, scopes } = importMap;
9
+ if (Object.keys(imports).length > 0 || scopes && Object.keys(scopes).length > 0) {
10
+ return false;
11
+ }
12
+ return true;
13
+ }
14
+ export {
15
+ createBlankImportMap,
16
+ isBlankImportMap
17
+ };
package/dist/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ export * from "./add.ts";
2
+ export * from "./blank.ts";
3
+ export * from "./parse.ts";
4
+ export * from "./resolve.ts";
5
+ export * from "./support.ts";
package/dist/parse.mjs ADDED
@@ -0,0 +1,88 @@
1
+ import { createBlankImportMap } from "./blank.ts";
2
+ function importMapFrom(v, baseURL) {
3
+ const im = createBlankImportMap(baseURL);
4
+ if (isObject(v)) {
5
+ const { config, imports, scopes, integrity } = v;
6
+ if (isObject(config)) {
7
+ validateStringMap(config);
8
+ im.config = config;
9
+ }
10
+ if (isObject(imports)) {
11
+ validateImports(imports);
12
+ im.imports = imports;
13
+ }
14
+ if (isObject(scopes)) {
15
+ validateScopes(scopes);
16
+ im.scopes = scopes;
17
+ }
18
+ if (isObject(integrity)) {
19
+ validateStringMap(integrity);
20
+ im.integrity = integrity;
21
+ }
22
+ }
23
+ return im;
24
+ }
25
+ function parseImportMapFromJson(json, baseURL) {
26
+ const im = createBlankImportMap(baseURL);
27
+ const v = JSON.parse(json);
28
+ if (isObject(v)) {
29
+ const { config, imports, scopes, integrity } = v;
30
+ if (isObject(config)) {
31
+ validateStringMap(config);
32
+ im.config = config;
33
+ }
34
+ if (isObject(imports)) {
35
+ validateImports(imports);
36
+ im.imports = imports;
37
+ }
38
+ if (isObject(scopes)) {
39
+ validateScopes(scopes);
40
+ im.scopes = scopes;
41
+ }
42
+ if (isObject(integrity)) {
43
+ validateStringMap(integrity);
44
+ im.integrity = integrity;
45
+ }
46
+ }
47
+ return im;
48
+ }
49
+ function parseImportMapFromHtml(html, baseURL) {
50
+ const tplEl = document.createElement("template");
51
+ tplEl.innerHTML = html;
52
+ const scriptEl = tplEl.content.querySelector("script[type='importmap']");
53
+ if (scriptEl) {
54
+ return parseImportMapFromJson(scriptEl.textContent, baseURL);
55
+ }
56
+ return createBlankImportMap(baseURL);
57
+ }
58
+ function validateImports(imports) {
59
+ for (const [k, v] of Object.entries(imports)) {
60
+ if (!v || typeof v !== "string") {
61
+ delete imports[k];
62
+ }
63
+ }
64
+ }
65
+ function validateScopes(imports) {
66
+ for (const [k, v] of Object.entries(imports)) {
67
+ if (isObject(v)) {
68
+ validateImports(v);
69
+ } else {
70
+ delete imports[k];
71
+ }
72
+ }
73
+ }
74
+ function validateStringMap(map) {
75
+ for (const [k, v] of Object.entries(map)) {
76
+ if (typeof v !== "string") {
77
+ delete map[k];
78
+ }
79
+ }
80
+ }
81
+ function isObject(v) {
82
+ return typeof v === "object" && v !== null && !Array.isArray(v);
83
+ }
84
+ export {
85
+ importMapFrom,
86
+ parseImportMapFromHtml,
87
+ parseImportMapFromJson
88
+ };
@@ -0,0 +1,46 @@
1
+ function resolve(importMap, specifier, containingFile) {
2
+ const { baseURL, imports, scopes } = importMap;
3
+ const { origin, pathname } = new URL(containingFile, baseURL);
4
+ const sameOriginScopes = [];
5
+ for (const scopeName in scopes ?? {}) {
6
+ const scopeUrl = new URL(scopeName, baseURL);
7
+ if (scopeUrl.origin === origin) {
8
+ sameOriginScopes.push([scopeUrl.pathname, (scopes ?? {})[scopeName]]);
9
+ }
10
+ }
11
+ sameOriginScopes.sort(([a], [b]) => b.split("/").length - a.split("/").length);
12
+ if (sameOriginScopes.length > 0) {
13
+ for (const [scopePathname, scopeImports] of sameOriginScopes) {
14
+ if (pathname.startsWith(scopePathname)) {
15
+ const url = matchImport(specifier, scopeImports);
16
+ if (url) {
17
+ return [url, true];
18
+ }
19
+ }
20
+ }
21
+ }
22
+ if (origin === baseURL.origin) {
23
+ const url = matchImport(specifier, imports);
24
+ if (url) {
25
+ return [url, true];
26
+ }
27
+ }
28
+ return [specifier, false];
29
+ }
30
+ function matchImport(specifier, imports) {
31
+ if (specifier in imports) {
32
+ return imports[specifier];
33
+ }
34
+ let bestMatch = null;
35
+ let bestKeyLength = -1;
36
+ for (const [k, v] of Object.entries(imports)) {
37
+ if (k.endsWith("/") && specifier.startsWith(k) && k.length > bestKeyLength) {
38
+ bestMatch = v + specifier.slice(k.length);
39
+ bestKeyLength = k.length;
40
+ }
41
+ }
42
+ return bestMatch;
43
+ }
44
+ export {
45
+ resolve
46
+ };
@@ -0,0 +1,6 @@
1
+ function isSupportImportMap() {
2
+ return !!globalThis.HTMLScriptElement?.supports?.("importmap");
3
+ }
4
+ export {
5
+ isSupportImportMap
6
+ };
package/package.json CHANGED
@@ -1,26 +1,29 @@
1
1
  {
2
2
  "name": "@esm.sh/import-map",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A import map parser and resolver.",
5
5
  "type": "module",
6
- "main": "dist/import-map.mjs",
7
- "module": "dist/import-map.mjs",
8
- "exports": {
9
- ".": {
10
- "import": "./dist/import-map.mjs",
11
- "types": "./types/import-map.d.ts"
12
- },
13
- "./generator": {
14
- "import": "./dist/generator.mjs",
15
- "types": "./types/generator.d.ts"
16
- }
17
- },
6
+ "main": "dist/index.mjs",
7
+ "module": "dist/index.mjs",
8
+ "types": "types/index.d.ts",
9
+ "files": [
10
+ "dist",
11
+ "types",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
18
15
  "scripts": {
19
16
  "prepublishOnly": "npm run build",
20
- "build": "esbuild --format=esm --outdir=dist --out-extension:.js=.mjs src/*.ts"
17
+ "build": "rm -rf dist && esbuild --format=esm --outdir=dist --out-extension:.js=.mjs src/index.ts src/add.ts src/blank.ts src/parse.ts src/resolve.ts src/support.ts",
18
+ "test": "bun test src/*.test.ts"
19
+ },
20
+ "dependencies": {
21
+ "semver": "^7.7.4"
21
22
  },
22
23
  "devDependencies": {
23
- "esbuild": "^0.25.0"
24
+ "@types/bun": "^1.3.9",
25
+ "@types/semver": "^7.7.1",
26
+ "esbuild": "0.27.3"
24
27
  },
25
28
  "repository": {
26
29
  "type": "git",
@@ -1,31 +1,39 @@
1
1
  /** The import maps follow the spec at https://wicg.github.io/import-maps/. */
2
2
  export interface ImportMap {
3
- $src?: string;
4
- $baseURL: string;
3
+ baseURL: URL;
4
+ config?: Record<string, string>;
5
5
  imports: Record<string, string>;
6
- scopes: Record<string, Record<string, string>>;
6
+ scopes?: Record<string, Record<string, string>>;
7
+ integrity?: Record<string, string>;
7
8
  }
8
9
 
9
10
  /** Create a blank import map. */
10
- export function createBlankImportMap(): ImportMap;
11
+ export function createBlankImportMap(baseURL?: string): ImportMap;
11
12
 
12
13
  /** Create an import map from the given object. */
13
14
  export function importMapFrom(v: any, baseURL?: string): ImportMap;
14
15
 
15
- /** Parse the import map from JSON. */
16
+ /** Parse the import map from a JSON string. */
16
17
  export function parseImportMapFromJson(json: string, baseURL?: string): ImportMap;
17
18
 
18
- /** Parse the import map from the given HTML. (requires Browser environment) */
19
+ /** Parse the import map from the given HTML. (Requires Browser environment) */
19
20
  export function parseImportMapFromHtml(html: string, baseURL?: string): ImportMap;
20
21
 
22
+ /**
23
+ * Add an import from esm.sh CDN to the import map.
24
+ *
25
+ * @param importMap - The import map to add the import to.
26
+ * @param specifier - The specifier of the import to add.
27
+ * @param noSRI - Whether to add the import without SRI.
28
+ * @returns A promise that resolves when the import is added.
29
+ */
30
+ export function addImport(importMap: ImportMap, specifier: string, noSRI?: boolean): Promise<void>;
31
+
21
32
  /** Resolve the specifier with the import map. */
22
- export function resolve(importMap: ImportMap, specifier: string, containingFile: string): string;
33
+ export function resolve(importMap: ImportMap, specifier: string, containingFile: string): [url: string, ok: boolean];
23
34
 
24
35
  /** Check if current browser supports import maps. */
25
36
  export function isSupportImportMap(): boolean;
26
37
 
27
38
  /** Check if the import map is blank. */
28
39
  export function isBlankImportMap(importMap: ImportMap): boolean;
29
-
30
- /** Check if the given two import maps are the same. */
31
- export function isSameImportMap(a: ImportMap, b: ImportMap): boolean;
@@ -1,24 +0,0 @@
1
- let cdnOrigin = "https://esm.sh";
2
- function setCDNOrigin(origin) {
3
- const url = new URL(origin);
4
- cdnOrigin = url.origin;
5
- }
6
- function add(importMap, specifier) {
7
- throw new Error("Not implemented");
8
- }
9
- function update(importMap, specifier, version) {
10
- throw new Error("Not implemented");
11
- }
12
- function remove(importMap) {
13
- throw new Error("Not implemented");
14
- }
15
- function tidy(importMap) {
16
- throw new Error("Not implemented");
17
- }
18
- export {
19
- add,
20
- remove,
21
- setCDNOrigin,
22
- tidy,
23
- update
24
- };
@@ -1,159 +0,0 @@
1
- function createBlankImportMap(baseURL) {
2
- return {
3
- $baseURL: new URL(baseURL ?? ".", "file:///").href,
4
- imports: {},
5
- scopes: {}
6
- };
7
- }
8
- function importMapFrom(v, baseURL) {
9
- const im = createBlankImportMap(baseURL);
10
- if (isObject(v)) {
11
- const { imports, scopes } = v;
12
- if (isObject(imports)) {
13
- validateImports(imports);
14
- im.imports = imports;
15
- }
16
- if (isObject(scopes)) {
17
- validateScopes(scopes);
18
- im.scopes = scopes;
19
- }
20
- }
21
- return im;
22
- }
23
- function parseImportMapFromJson(json, baseURL) {
24
- const importMap = {
25
- $baseURL: new URL(baseURL ?? ".", "file:///").href,
26
- imports: {},
27
- scopes: {}
28
- };
29
- const v = JSON.parse(json);
30
- if (isObject(v)) {
31
- const { imports, scopes } = v;
32
- if (isObject(imports)) {
33
- validateImports(imports);
34
- importMap.imports = imports;
35
- }
36
- if (isObject(scopes)) {
37
- validateScopes(scopes);
38
- importMap.scopes = scopes;
39
- }
40
- }
41
- return importMap;
42
- }
43
- function parseImportMapFromHtml(html, baseURL) {
44
- const tplEl = document.createElement("template");
45
- tplEl.innerHTML = html;
46
- const scriptEl = tplEl.content.querySelector("script[type='importmap']");
47
- if (scriptEl) {
48
- return parseImportMapFromJson(scriptEl.textContent, baseURL);
49
- }
50
- return createBlankImportMap(baseURL);
51
- }
52
- function resolve(importMap, specifier, containingFile) {
53
- const { $baseURL, imports, scopes } = importMap;
54
- const { origin, pathname } = new URL(containingFile, $baseURL);
55
- const sameOriginScopes = [];
56
- for (const scopeName in scopes) {
57
- const scopeUrl = new URL(scopeName, $baseURL);
58
- if (scopeUrl.origin === origin) {
59
- sameOriginScopes.push([scopeUrl.pathname, scopes[scopeName]]);
60
- }
61
- }
62
- sameOriginScopes.sort(([a], [b]) => b.split("/").length - a.split("/").length);
63
- if (sameOriginScopes.length > 0) {
64
- for (const [scopePathname, scopeImports] of sameOriginScopes) {
65
- if (pathname.startsWith(scopePathname)) {
66
- const url = matchImport(specifier, scopeImports);
67
- if (url) {
68
- return [url, true];
69
- }
70
- }
71
- }
72
- }
73
- if (origin === new URL($baseURL).origin) {
74
- const url = matchImport(specifier, imports);
75
- if (url) {
76
- return [url, true];
77
- }
78
- }
79
- return [specifier, false];
80
- }
81
- function isSupportImportMap() {
82
- return !globalThis.HTMLScriptElement?.supports?.("importmap");
83
- }
84
- function isBlankImportMap(importMap) {
85
- const { imports, scopes } = importMap;
86
- if (isObject(imports) && Object.keys(imports).length > 0 || isObject(scopes) && Object.keys(scopes).length > 0) {
87
- return false;
88
- }
89
- return true;
90
- }
91
- function isSameImportMap(a, b) {
92
- if (!isSameImports(a.imports, b.imports)) {
93
- return false;
94
- }
95
- for (const k in a.scopes) {
96
- if (!(k in b.scopes) || !isObject(b.scopes[k])) {
97
- return false;
98
- }
99
- if (!isSameImports(a.scopes[k], b.scopes[k])) {
100
- return false;
101
- }
102
- }
103
- return true;
104
- }
105
- function matchImport(specifier, imports) {
106
- if (specifier in imports) {
107
- return imports[specifier];
108
- }
109
- for (const [k, v] of Object.entries(imports)) {
110
- if (k.endsWith("/")) {
111
- if (specifier.startsWith(k)) {
112
- return v + specifier.slice(k.length);
113
- }
114
- } else if (specifier.startsWith(k + "/")) {
115
- return v + specifier.slice(k.length);
116
- }
117
- }
118
- return null;
119
- }
120
- function validateImports(imports) {
121
- for (const [k, v] of Object.entries(imports)) {
122
- if (!v || typeof v !== "string") {
123
- delete imports[k];
124
- }
125
- }
126
- }
127
- function validateScopes(imports) {
128
- for (const [k, v] of Object.entries(imports)) {
129
- if (isObject(v)) {
130
- validateImports(v);
131
- } else {
132
- delete imports[k];
133
- }
134
- }
135
- }
136
- function isObject(v) {
137
- return typeof v === "object" && v !== null && !Array.isArray(v);
138
- }
139
- function isSameImports(a, b) {
140
- if (Object.keys(a).length !== Object.keys(b).length) {
141
- return false;
142
- }
143
- for (const k in a) {
144
- if (a[k] !== b[k]) {
145
- return false;
146
- }
147
- }
148
- return true;
149
- }
150
- export {
151
- createBlankImportMap,
152
- importMapFrom,
153
- isBlankImportMap,
154
- isSameImportMap,
155
- isSupportImportMap,
156
- parseImportMapFromHtml,
157
- parseImportMapFromJson,
158
- resolve
159
- };
package/src/generator.ts DELETED
@@ -1,28 +0,0 @@
1
- import type { ImportMap } from "../types/import-map.d.ts";
2
-
3
- let cdnOrigin = "https://esm.sh";
4
-
5
- export function setCDNOrigin(origin: string): void {
6
- const url = new URL(origin);
7
- cdnOrigin = url.origin;
8
- }
9
-
10
- /** Add a module to the import map. */
11
- export function add(importMap: ImportMap, specifier: string): Promise<void> {
12
- throw new Error("Not implemented");
13
- }
14
-
15
- /** Update a module in the import map. */
16
- export function update(importMap: ImportMap, specifier: string, version: string): Promise<void> {
17
- throw new Error("Not implemented");
18
- }
19
-
20
- /** Remove a module from the import map. */
21
- export function remove(importMap: ImportMap): Promise<void> {
22
- throw new Error("Not implemented");
23
- }
24
-
25
- /** Tidy the import map. */
26
- export function tidy(importMap: ImportMap): Promise<void> {
27
- throw new Error("Not implemented");
28
- }
package/src/import-map.ts DELETED
@@ -1,171 +0,0 @@
1
- import type { ImportMap } from "../types/import-map.d.ts";
2
-
3
- /** Create a blank import map. */
4
- export function createBlankImportMap(baseURL?: string): ImportMap {
5
- return {
6
- $baseURL: new URL(baseURL ?? ".", "file:///").href,
7
- imports: {},
8
- scopes: {},
9
- };
10
- }
11
-
12
- /** Create an import map from the given object. */
13
- export function importMapFrom(v: any, baseURL?: string): ImportMap {
14
- const im = createBlankImportMap(baseURL);
15
- if (isObject(v)) {
16
- const { imports, scopes } = v;
17
- if (isObject(imports)) {
18
- validateImports(imports);
19
- im.imports = imports as ImportMap["imports"];
20
- }
21
- if (isObject(scopes)) {
22
- validateScopes(scopes);
23
- im.scopes = scopes as ImportMap["scopes"];
24
- }
25
- }
26
- return im;
27
- }
28
-
29
- /** Parse the import map from JSON. */
30
- export function parseImportMapFromJson(json: string, baseURL?: string): ImportMap {
31
- const importMap: ImportMap = {
32
- $baseURL: new URL(baseURL ?? ".", "file:///").href,
33
- imports: {},
34
- scopes: {},
35
- };
36
- const v = JSON.parse(json);
37
- if (isObject(v)) {
38
- const { imports, scopes } = v;
39
- if (isObject(imports)) {
40
- validateImports(imports);
41
- importMap.imports = imports as ImportMap["imports"];
42
- }
43
- if (isObject(scopes)) {
44
- validateScopes(scopes);
45
- importMap.scopes = scopes as ImportMap["scopes"];
46
- }
47
- }
48
- return importMap;
49
- }
50
-
51
- /** Parse the import map from the given HTML. (requires Browser environment) */
52
- export function parseImportMapFromHtml(html: string, baseURL?: string): ImportMap {
53
- const tplEl = document.createElement("template");
54
- tplEl.innerHTML = html;
55
- const scriptEl: HTMLScriptElement | null = tplEl.content.querySelector("script[type='importmap']");
56
- if (scriptEl) {
57
- return parseImportMapFromJson(scriptEl.textContent!, baseURL);
58
- }
59
- return createBlankImportMap(baseURL);
60
- }
61
-
62
- /** Resolve the specifier with the import map. */
63
- export function resolve(importMap: ImportMap, specifier: string, containingFile: string): [string, boolean] {
64
- const { $baseURL, imports, scopes } = importMap;
65
- const { origin, pathname } = new URL(containingFile, $baseURL);
66
- const sameOriginScopes: [string, ImportMap["imports"]][] = [];
67
- for (const scopeName in scopes) {
68
- const scopeUrl = new URL(scopeName, $baseURL);
69
- if (scopeUrl.origin === origin) {
70
- sameOriginScopes.push([scopeUrl.pathname, scopes[scopeName]]);
71
- }
72
- }
73
- sameOriginScopes.sort(([a], [b]) => b.split("/").length - a.split("/").length);
74
- if (sameOriginScopes.length > 0) {
75
- for (const [scopePathname, scopeImports] of sameOriginScopes) {
76
- if (pathname.startsWith(scopePathname)) {
77
- const url = matchImport(specifier, scopeImports);
78
- if (url) {
79
- return [url, true];
80
- }
81
- }
82
- }
83
- }
84
- if (origin === new URL($baseURL).origin) {
85
- const url = matchImport(specifier, imports);
86
- if (url) {
87
- return [url, true];
88
- }
89
- }
90
- return [specifier, false];
91
- }
92
-
93
- /** Check if current browser supports import maps. */
94
- export function isSupportImportMap(): boolean {
95
- return !(globalThis.HTMLScriptElement?.supports?.("importmap"));
96
- }
97
-
98
- /** Check if the import map is blank. */
99
- export function isBlankImportMap(importMap: ImportMap) {
100
- const { imports, scopes } = importMap;
101
- if ((isObject(imports) && Object.keys(imports).length > 0) || (isObject(scopes) && Object.keys(scopes).length > 0)) {
102
- return false;
103
- }
104
- return true;
105
- }
106
-
107
- /** Check if the given two import maps are the same. */
108
- export function isSameImportMap(a: ImportMap, b: ImportMap): boolean {
109
- if (!isSameImports(a.imports, b.imports)) {
110
- return false;
111
- }
112
- for (const k in a.scopes) {
113
- if (!(k in b.scopes) || !isObject(b.scopes[k])) {
114
- return false;
115
- }
116
- if (!isSameImports(a.scopes[k], b.scopes[k])) {
117
- return false;
118
- }
119
- }
120
- return true;
121
- }
122
-
123
- function matchImport(specifier: string, imports: ImportMap["imports"]): string | null {
124
- if (specifier in imports) {
125
- return imports[specifier];
126
- }
127
- for (const [k, v] of Object.entries(imports)) {
128
- if (k.endsWith("/")) {
129
- if (specifier.startsWith(k)) {
130
- return v + specifier.slice(k.length);
131
- }
132
- } else if (specifier.startsWith(k + "/")) {
133
- return v + specifier.slice(k.length);
134
- }
135
- }
136
- return null;
137
- }
138
-
139
- function validateImports(imports: Record<string, unknown>) {
140
- for (const [k, v] of Object.entries(imports)) {
141
- if (!v || typeof v !== "string") {
142
- delete imports[k];
143
- }
144
- }
145
- }
146
-
147
- function validateScopes(imports: Record<string, unknown>) {
148
- for (const [k, v] of Object.entries(imports)) {
149
- if (isObject(v)) {
150
- validateImports(v);
151
- } else {
152
- delete imports[k];
153
- }
154
- }
155
- }
156
-
157
- function isObject(v: unknown): v is Record<string, unknown> {
158
- return typeof v === "object" && v !== null && !Array.isArray(v);
159
- }
160
-
161
- function isSameImports(a: Record<string, string>, b: Record<string, string>): boolean {
162
- if (Object.keys(a).length !== Object.keys(b).length) {
163
- return false;
164
- }
165
- for (const k in a) {
166
- if (a[k] !== b[k]) {
167
- return false;
168
- }
169
- }
170
- return true;
171
- }
@@ -1,4 +0,0 @@
1
- import type { ImportMap } from "./import-map.d.ts";
2
-
3
- /** Search a NPM package from esm.sh CDN and add it to the import map. */
4
- export function addImport(importMap: ImportMap, specifier: string): void;