diff --git a/docs/_data/importMap.cjs b/docs/_data/importMap.cjs
index dd79d08705..3adacc0b80 100644
--- a/docs/_data/importMap.cjs
+++ b/docs/_data/importMap.cjs
@@ -12,83 +12,44 @@ function readPackageVersion(module) {
return packageLock.packages[`node_modules/${module}`].version;
}
-const LIT_VERSION = readPackageVersion('lit');
-const FUSE_VERSION = readPackageVersion('fuse.js');
-const PRISM_VERSION = readPackageVersion('prismjs');
-
-const LIT_DEPS = [
- {
- target: `lit@${LIT_VERSION}`,
- subpaths: [
- '.',
- './decorators/query-all.js',
- './decorators/query-assigned-nodes.js',
- './decorators/query-assigned-elements.js',
- './decorators/query-async.js',
- './decorators/query.js',
- './decorators/state.js',
- './decorators/property.js',
- './decorators/custom-element.js',
- './directives/async-append.js',
- './directives/async-replace.js',
- './directives/cache.js',
- './directives/class-map.js',
- './directives/guard.js',
- './directives/if-defined.js',
- './directives/live.js',
- './directives/ref.js',
- './directives/repeat.js',
- './directives/style-map.js',
- './directives/template-content.js',
- './directives/unsafe-html.js',
- './directives/unsafe-svg.js',
- './directives/until.js',
- './async-directive.js',
- './decorators.js',
- './directive.js',
- './directive-helpers.js',
- './html.js',
- './polyfill-support.js',
- './static-html.js',
- ],
- },
- {
- target: `@lit-labs/ssr-client`,
- subpaths: [
- '.',
- './lit-element-hydrate-support.js',
- ],
- },
+const LOCAL_PACKAGES = [
+ '@patternfly/elements',
+ '@patternfly/pfe-core',
+ '@patternfly/pfe-tools',
+ '@patternfly/icons',
];
module.exports = async function() {
- const { Generator } = await import('@jspm/generator');
-
- const generator = new Generator({
- defaultProvider: 'jsdelivr',
- env: ['production', 'browser', 'module'],
+ const { generate } = await import('@pwrs/mappa');
+
+ const map = await generate({
+ dependencies: {
+ 'tslib': readPackageVersion('tslib'),
+ '@rhds/elements': readPackageVersion('@rhds/elements'),
+ 'prismjs': readPackageVersion('prismjs'),
+ 'element-internals-polyfill': readPackageVersion('element-internals-polyfill'),
+ 'fuse.js': readPackageVersion('fuse.js'),
+ 'lit': readPackageVersion('lit'),
+ '@lit-labs/ssr-client': readPackageVersion('@lit-labs/ssr-client'),
+ },
+ }, {
+ cdn: 'jsdelivr',
+ exclude: LOCAL_PACKAGES,
});
- await generator.install([
- 'tslib',
- '@rhds/elements',
- '@rhds/elements/rh-footer/rh-footer-universal.js',
- `prismjs@${PRISM_VERSION}`,
- 'element-internals-polyfill',
- `fuse.js@${FUSE_VERSION}`,
- ...LIT_DEPS,
- ]);
+ for (const key of Object.keys(map.imports)) {
+ for (const pkg of LOCAL_PACKAGES) {
+ if (key === pkg || key.startsWith(`${pkg}/`)) {
+ delete map.imports[key];
+ }
+ }
+ }
- const map = generator.getMap();
map.imports['/docs/zero-md.js'] = '/zero-md.js';
map.imports['@patternfly/elements/'] = '/assets/@patternfly/elements/';
map.imports['@patternfly/pfe-core/'] = '/assets/@patternfly/pfe-core/';
map.imports['@patternfly/pfe-core'] = '/assets/@patternfly/pfe-core/core.js';
map.imports['@patternfly/pfe-tools/'] = '/assets/@patternfly/pfe-tools/';
map.imports['@patternfly/icons/'] = '/assets/@patternfly/icons/';
- map.imports['@lit/context'] = map.scopes['https://cdn.jsdelivr.net/']['@lit/context'];
- map.imports['lit/'] = map.imports.lit.replace('index.js', '');
- map.scopes['https://cdn.jsdelivr.net/'].lit = map.imports.lit;
- map.scopes['https://cdn.jsdelivr.net/']['lit/'] = map.imports.lit.replace('index.js', '');
return map;
};
diff --git a/docs/_data/versions.json b/docs/_data/versions.json
index 5a82922a6d..de78b59e13 100644
--- a/docs/_data/versions.json
+++ b/docs/_data/versions.json
@@ -1,9 +1,15 @@
[
+ {
+ "version": "v5.0.0",
+ "slug": "v5",
+ "label": "v5",
+ "current": true
+ },
{
"version": "v4.0.0",
"slug": "v4",
"label": "v4",
- "current": true
+ "current": false
},
{
"version": "v3.0.0",
diff --git a/docs/_plugins/create-import-map.cjs b/docs/_plugins/create-import-map.cjs
index 26b3d36e4c..6deeff4375 100644
--- a/docs/_plugins/create-import-map.cjs
+++ b/docs/_plugins/create-import-map.cjs
@@ -1,21 +1,22 @@
module.exports = function(eleventyConfig) {
eleventyConfig.addPairedAsyncShortcode('generateImportMap', async content => {
- const { Generator } = await import('@jspm/generator');
+ const { generate } = await import('@pwrs/mappa');
- const generator = new Generator({
- defaultProvider: 'jspm.io',
- env: ['production', 'browser', 'module'],
- });
+ const deps = {};
+ const specifierRe = /['"]([^'"]+)['"]/g;
+ for (const [, spec] of content.matchAll(specifierRe)) {
+ if (!spec.startsWith('.') && !spec.startsWith('/')) {
+ const name = spec.startsWith('@') ?
+ spec.split('/').slice(0, 2).join('/')
+ : spec.split('/')[0];
+ deps[name] = '*';
+ }
+ }
- const pins = await generator.addMappings(content);
+ const map = await generate({ dependencies: deps }, { cdn: 'esm.sh' });
- const html = await generator.htmlInject(content, {
- pins,
- esModuleShims: true,
- whitespace: true,
- });
-
- return html;
+ const script = ``;
+ return content.replace(/' + preloads + (analysis.map.newScript ? newlineTab : ''));
-+ replacer.replace(analysis.map.start, analysis.map.end, (comment ? '' + newlineTab : '') + esms + '' + preloads + (analysis.map.newScript ? newlineTab : ''));
- return replacer.source;
- }
- async install(install, mode) {
diff --git a/tools/pfe-tools/11ty/DocsPage.ts b/tools/pfe-tools/11ty/DocsPage.ts
index 6ddeb15c3d..108687687b 100644
--- a/tools/pfe-tools/11ty/DocsPage.ts
+++ b/tools/pfe-tools/11ty/DocsPage.ts
@@ -23,12 +23,12 @@ export class DocsPage {
constructor(public manifest: Manifest, options?: DocsPageOptions) {
const config = getPfeConfig(options?.rootDir);
this.tagName = options?.tagName ?? '';
- this.title = options?.title ?? Manifest.prettyTag(this.tagName);
this.docsTemplatePath = options?.docsTemplatePath;
this.summary = this.manifest.getSummary(this.tagName);
this.description = this.manifest.getDescription(this.tagName);
const prefix = `${config.tagPrefix.replace(/-$/, '')}-`;
const aliased = config.aliases[this.tagName] ?? this.tagName.replace(prefix, '');
+ this.title = options?.title ?? Manifest.prettyTag(this.tagName, config.aliases, prefix);
this.slug = slugify(aliased, { strict: true, lower: true });
}
}
diff --git a/tools/pfe-tools/custom-elements-manifest/lib/Manifest.ts b/tools/pfe-tools/custom-elements-manifest/lib/Manifest.ts
index d70a27f199..266e9ae229 100644
--- a/tools/pfe-tools/custom-elements-manifest/lib/Manifest.ts
+++ b/tools/pfe-tools/custom-elements-manifest/lib/Manifest.ts
@@ -175,11 +175,12 @@ export class Manifest {
public static prettyTag = (
tagName: string,
aliases?: Record,
- ): string => aliases?.[tagName] ?? tagName
- .replace(/^\w+-/, '')
- .toLowerCase()
- .replace(/(?:^|[-/\s])\w/g, x => x.toUpperCase())
- .replace(/-/g, ' ');
+ prefix?: string,
+ ): string => aliases?.[tagName]
+ ?? (prefix ? tagName.replace(prefix, '') : tagName.replace(/^\w+-/, ''))
+ .toLowerCase()
+ .replace(/(?:^|[-/\s])\w/g, x => x.toUpperCase())
+ .replace(/-/g, ' ');
declarations: Map = new Map();
@@ -323,10 +324,12 @@ export class Manifest {
const [last = ''] = filePath.split(path.sep).reverse();
const filename = last.replace('.html', '');
const isMainElementDemo = filename === 'index';
- const title = isMainElementDemo ? options.aliases[tagName] ?? prettyTag(tagName) : last
- .replace(/(?:^|[-/\s])\w/g, x => x.toUpperCase())
- .replace(/-/g, ' ')
- .replace('.html', '');
+ const prefix = `${options.tagPrefix.replace(/-$/, '')}-`;
+ const title = isMainElementDemo ? prettyTag(tagName, options.aliases, prefix)
+ : last
+ .replace(/(?:^|[-/\s])\w/g, x => x.toUpperCase())
+ .replace(/-/g, ' ')
+ .replace('.html', '');
return {
tagName,
primaryElementName,
diff --git a/tools/pfe-tools/dev-server/config.ts b/tools/pfe-tools/dev-server/config.ts
index 6685fb72a5..806e9a182f 100644
--- a/tools/pfe-tools/dev-server/config.ts
+++ b/tools/pfe-tools/dev-server/config.ts
@@ -52,7 +52,6 @@ function normalizeOptions(options?: PfeDevServerConfigOptions) {
.replace(/\/node_modules$/, '/')
.replace('//', '/');
config.importMapOptions ??= {} as PfeDevServerConfigOptions['importMapOptions'];
- config.importMapOptions!.providers ??= {};
config.site = { ...config.site, ...options?.site ?? {} };
config.loadDemo ??= true;
config.watchFiles ??= '{elements,core}/**/*.{css,html}';
@@ -147,26 +146,7 @@ export function pfeDevServerConfig(options?: PfeDevServerConfigOptions): DevServ
// load .css files as lit CSSResult modules
litCss(config.litcssOptions),
- importMapGeneratorPlugin({
- ...config.importMapOptions,
- providers: {
- 'construct-style-sheets-polyfill': 'nodemodules',
- 'element-internals-polyfill': 'nodemodules',
- 'lit-html': 'nodemodules',
- 'lit': 'nodemodules',
- '@lit/reactive-element': 'nodemodules',
- '@lit/context': 'nodemodules',
- ...config.importMapOptions?.providers,
- },
- resolveHtmlUrl(fileUrl, rootUrl) {
- const override = config.importMapOptions.resolveHtmlUrl?.(fileUrl, rootUrl);
- if (override) {
- return override;
- } else {
- return fileUrl.replace('/components/', '/elements/pf-');
- }
- },
- }),
+ importMapGeneratorPlugin(config.importMapOptions),
...config?.plugins ?? [],
diff --git a/tools/pfe-tools/dev-server/plugins/import-map-generator.ts b/tools/pfe-tools/dev-server/plugins/import-map-generator.ts
index e6a56acbb6..9c0aa6c494 100644
--- a/tools/pfe-tools/dev-server/plugins/import-map-generator.ts
+++ b/tools/pfe-tools/dev-server/plugins/import-map-generator.ts
@@ -1,129 +1,41 @@
import type { Middleware } from 'koa';
import type { Plugin } from '@web/dev-server-core';
-import type { GeneratorOptions, Provider } from '@jspm/generator';
-import { readFile, stat } from 'node:fs/promises';
+import { resolve } from '@pwrs/mappa';
-import { join } from 'node:path';
-
-import { Generator } from '@jspm/generator';
-
-import { glob } from 'node:fs/promises';
-
-export interface Options extends GeneratorOptions {
+export interface Options {
resolveHtmlUrl?: (fileUrl: string, rootUrl: string) => string;
+ providers?: Record;
+ inputMap?: { imports?: Record; scopes?: Record> };
+ resolutions?: Record;
+ ignore?: string[];
+ typeScript?: boolean;
}
-const exists = async (path: string) => {
- try {
- await stat(path); return true;
- } catch {
- return false;
- }
-};
-
-async function getPotentialPackageDirs(cwd: string, workspaces: string[]) {
- const potentialPackageDirs: string[] = [];
- await Promise.all(
- (workspaces ?? []).map(async (pattern: string) => {
- for await (const dir of glob(pattern, { cwd })) {
- potentialPackageDirs.push(dir);
- }
- })
- );
- return potentialPackageDirs;
-}
-
-async function resolveMonorepoPackages() {
- const cwd = process.cwd();
-
- const { workspaces } = JSON.parse(await readFile(join(cwd, 'package.json'), 'utf-8'));
-
- const potentialPackageDirs = await getPotentialPackageDirs(cwd, workspaces);
- const packages = new Map();
-
- for (const dir of ['.', ...potentialPackageDirs]) {
- const pkgDir = join(cwd, dir);
- const pkgJsonPath = join(pkgDir, 'package.json');
- if (await exists(pkgJsonPath)) {
- const { name } = JSON.parse(await readFile(pkgJsonPath, 'utf-8'));
- packages.set(name, pkgDir);
- }
- }
-
- return packages;
-}
-
-function getProvider(packages: Map): Provider {
- return {
- async pkgToUrl({ name }) {
- const pkgPath = packages.get(name);
- if (!pkgPath) {
- throw new Error(`could not resolve ${name}`);
- }
- return `file://${pkgPath}/`;
- },
- // @ts-expect-error: types vs docs
- parseUrlPkg(url: string) {
- for (const [name, dir] of packages) {
- if (url.startsWith(dir)) {
- return {
- name,
- registry: 'monorepotypescript',
- version: '*',
- };
- }
- }
- },
- async resolveLatestTarget(target) {
- return { ...target, version: '*' };
- },
- };
+interface ImportMap {
+ imports?: Record;
+ scopes?: Record>;
}
-function generatorMiddleware(generator: Generator, options?: Partial): Middleware {
+function importMapMiddleware(importMap: ImportMap): Middleware {
return async function injectMiddleware(ctx, next) {
- if (ctx.path.endsWith('.html') || ctx.path.endsWith('/')) {
- if (ctx.body?.length) {
- const rootUrl = `file://${process.cwd()}/`;
- const fileUrl = `${rootUrl.replace(/\/$/, '')}${ctx.url}`;
- const htmlUrl = options?.resolveHtmlUrl?.(fileUrl, rootUrl) ?? fileUrl;
- try {
- ctx.body = await generator.htmlInject(ctx.body, {
- htmlUrl,
- rootUrl,
- trace: true,
- whitespace: true,
- esModuleShims: true,
- });
- } catch (e) {
- // eslint-disable-next-line no-console
- console.error(e);
- }
- }
+ await next();
+ if ((ctx.path.endsWith('.html') || ctx.path.endsWith('/')) && ctx.body?.length) {
+ const script = ``;
+ ctx.body = (ctx.body as string).replace('', `${script}\n`);
}
- return next();
};
}
-/**
- * @param options plugin options
- */
export function importMapGeneratorPlugin(options?: Partial): Plugin {
return {
name: 'import-map-inject',
async serverStart(args) {
- const monorepotypescript = getProvider(await resolveMonorepoPackages());
- args.app.use(generatorMiddleware(new Generator({
- defaultProvider: 'nodemodules',
- env: ['development', 'production', 'browser', 'module'],
- providers: options?.providers,
+ const importMap = await resolve('.', {
+ conditions: ['development', 'production', 'browser', 'import', 'default'],
inputMap: options?.inputMap,
- customProviders: { monorepotypescript },
- resolutions: options?.resolutions,
- ignore: options?.ignore,
- typeScript: options?.typeScript,
- }), options));
+ });
+ args.app.use(importMapMiddleware(importMap));
},
};
}
diff --git a/tools/pfe-tools/package.json b/tools/pfe-tools/package.json
index ea6c753dc4..a48a09aba4 100644
--- a/tools/pfe-tools/package.json
+++ b/tools/pfe-tools/package.json
@@ -67,11 +67,11 @@
"@11ty/eleventy-plugin-directory-output": "^1.0.2",
"@11ty/eleventy-plugin-syntaxhighlight": "^5.0.2",
"@changesets/cli": "^2.29.8",
- "@jspm/generator": "~2.7.6",
"@koa/router": "^15.1.1",
"@lit-labs/ssr": "^4.0.0",
"@open-wc/testing": "^4.0.0",
"@playwright/test": "~1.48.0",
+ "@pwrs/mappa": "^0.0.4",
"@rollup/plugin-replace": "^6.0.3",
"@web/dev-server": "^0.4.6",
"@web/dev-server-esbuild": "^1.0.4",
diff --git a/tsconfig.settings.json b/tsconfig.settings.json
index ef69951558..7d56602e06 100644
--- a/tsconfig.settings.json
+++ b/tsconfig.settings.json
@@ -74,6 +74,9 @@
],
"@patternfly/pfe-tools/*": [
"./tools/pfe-tools/*"
+ ],
+ "@pwrs/mappa": [
+ "./node_modules/@pwrs/mappa/dist/mappa.d.ts"
]
}
}