-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathweb-dev-server.config.js
More file actions
263 lines (252 loc) · 8.21 KB
/
web-dev-server.config.js
File metadata and controls
263 lines (252 loc) · 8.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
// @ts-check
import { pfeDevServerConfig } from '@patternfly/pfe-tools/dev-server/config.js';
import { glob, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { makeDemoEnv } from './scripts/environment.js';
import { parse, serialize } from 'parse5';
import {
createElement,
getAttribute,
getTextContent,
isElementNode,
query,
removeAttribute,
setAttribute,
setTextContent,
spliceChildren,
} from '@parse5/tools';
/**
* Find all modules in a glob pattern, relative to the repo root, and resolve them as package paths
* @param {string} pattern
* @param {string} [relativeTo='.']
*/
async function resolveLocal(pattern, relativeTo = './') {
const TEST_RE = /\/test\/|(\.d\.ts$)/;
// eslint-disable-next-line jsdoc/check-tag-names
/** @type [string, string][] */
const files = [];
for await (const file of glob(pattern, { cwd: join(process.cwd(), relativeTo) })) {
if (!TEST_RE.test(file)) {
files.push([
`@rhds/elements/${file.replace('.ts', '.js')}`,
join(relativeTo, file).replace('./', '/'),
]);
}
}
return Object.fromEntries(files);
}
/**
* manually inject icon import map with trailing slash.
* jspm generator doesn't yet support trailing slash
* @param {import('@parse5/tools').Document} document
*/
function injectManuallyResolvedModulesToImportMap(document) {
const importMapNode = query(document, node =>
isElementNode(node)
&& node.tagName === 'script'
&& node.attrs.some(attr =>
attr.name === 'type'
&& attr.value === 'importmap'));
if (importMapNode && isElementNode(importMapNode)) {
const json = JSON.parse(getTextContent(importMapNode));
Object.assign(json.imports, {
'lit': '/node_modules/lit/index.js',
'lit/': '/node_modules/lit/',
'@lit/context': '/node_modules/@lit/context/index.js',
'@patternfly/pfe-core': '/node_modules/@patternfly/pfe-core/core.js',
'@patternfly/pfe-core/': '/node_modules/@patternfly/pfe-core/',
'@rhds/icons/': '/node_modules/@rhds/icons/',
'@rhds/tokens/': '/node_modules/@rhds/tokens/js/',
'@rhds/tokens/css/': '/node_modules/@rhds/tokens/css/',
'@floating-ui/dom': '/node_modules/@floating-ui/dom/dist/floating-ui.dom.browser.min.mjs',
'@floating-ui/core': '/node_modules/@floating-ui/core/dist/floating-ui.core.browser.min.mjs',
'vue/dist/vue.esm-browser.js': 'https://ga.jspm.io/npm:vue@3.5.21/dist/vue.esm-browser.js',
});
for (const key of Object.keys(json.scopes ?? {})) {
json.scopes[key]['@patternfly/pfe-core'] = '/node_modules/@patternfly/pfe-core/core.js';
}
setTextContent(importMapNode, JSON.stringify(json, null, 2));
}
}
/**
* add context picker to dev sserver chrome
* @param {import('@parse5/tools').Document} document
*/
function transformDevServerHTML(document) {
const surfaceId = 'rhds-dev-server-main';
// replace the <main> element with a surface
const main = query(document, x =>
isElementNode(x)
&& x.tagName === 'main');
if (main && isElementNode(main)) {
main.tagName = 'rh-surface';
removeAttribute(main, 'color-palette');
setAttribute(main, 'id', surfaceId);
setAttribute(main, 'role', 'main');
}
// add a context picker to header, targeting main
const header = query(document, x =>
isElementNode(x)
&& getAttribute(x, 'id') === 'main-header');
if (header && isElementNode(header)) {
const picker = createElement('rh-context-picker');
setAttribute(picker, 'target', surfaceId);
setAttribute(picker, 'value', '');
const logoBar = query(header, node =>
isElementNode(node)
&& getAttribute(node, 'class') === 'logo-bar');
if (logoBar) {
spliceChildren(logoBar, 4, 0, picker);
}
}
// import surface and picker
const module = query(document, x =>
isElementNode(x)
&& x.tagName === 'script'
&& getAttribute(x, 'type') === 'module');
if (module) {
setTextContent(module, /* js */`${getTextContent(module)}
import '@rhds/elements/rh-surface/rh-surface.js';
import '@rhds/elements/rh-tooltip/rh-tooltip.js';
import '@rhds/elements/lib/elements/rh-context-picker/rh-context-picker.js';
`);
}
}
/**
* Web dev server plugin to strip CSS import attributes from element source files
* This runs BEFORE esbuild transforms the TypeScript
* Removes `with { type: 'css' }` so browsers don't expect CSS MIME type modules
*
* NB: this can be removed when browsers widely support CSS modules
*/
export function stripCssImportAttributesPlugin() {
return {
name: 'strip-css-import-attributes',
transform(context) {
// Only process element and lib source files, not test files or node_modules
if (/\/(elements|lib)\/.*\.ts$/.test(context.path)
&& !/\.spec\.ts$/.test(context.path)
&& context.body
&& typeof context.body === 'string') {
// Remove `with { type: 'css' }` from CSS imports
const transformed = context.body.replace(
/(\bimport\s+[^;]+from\s+['"][^'"]+\.css['"])\s+with\s+\{\s*type:\s*['"]css['"]\s*\}/g,
'$1'
);
if (transformed !== context.body) {
return { body: transformed };
}
}
},
};
}
export const litcssOptions = {
exclude: [
/(lightdom)/,
/node_modules\/@rhds\/tokens\/css\/.*\.css/,
],
include: [
/elements\/rh-[\w-]+\/[\w-]+\.css$/,
/@rhds\/tokens\/css\/.*\.css$/,
/lib\/.*\.css$/,
],
};
const imports = {
...await resolveLocal('./lib/**/*.ts'),
...await resolveLocal('./**/*.ts', './elements'),
};
export default pfeDevServerConfig({
tsconfig: 'tsconfig.settings.json',
litcssOptions,
importMapOptions: {
typeScript: true,
ignore: [
/^\./,
/^@rhds\/icons/,
/^vue/,
],
inputMap: { imports },
},
middleware: [
async function(ctx, next) {
if (ctx.path === '/lib/environment.ts') {
ctx.type = 'text/javascript';
ctx.body = await makeDemoEnv();
} else {
return next();
}
},
/**
* redirect requests for /assets/ css to /docs/assets/
* @param ctx koa context
* @param next next koa middleware
*/
function(ctx, next) {
if (ctx.path.startsWith('/styles/')) {
ctx.redirect(`/docs${ctx.path}`);
} else {
return next();
}
},
/**
* serve lightdom CSS files directly from filesystem
* Handles: /elements/rh-foo/rh-foo-lightdom.css or /rh-foo/rh-foo-lightdom-*.css
* @param ctx koa context
* @param next next koa middleware
*/
async function(ctx, next) {
if (!ctx.path.includes('-lightdom')) {
return next();
}
// Match paths like /elements/rh-button/rh-button-lightdom.css or /rh-button-lightdom.css
const match = ctx.path.match(
/(?:\/elements)?\/(rh-[\w-]+)(?:\/\1)?-(lightdom(?:-[\w-]*)?)\.css$/);
if (!match) {
return next();
}
const [, elementName, suffix] = match;
const filePath = join(process.cwd(), 'elements', elementName, `${elementName}-${suffix}.css`);
try {
ctx.type = 'text/css';
ctx.body = await readFile(filePath, 'utf-8');
} catch (e) {
// eslint-disable-next-line no-console
console.error(`Lightdom CSS not found: ${filePath}`);
// eslint-disable-next-line no-console
console.error(e);
}
return;
},
/**
* @param ctx koa context
* @param next next koa middleware
*/
async function(ctx, next) {
if (ctx.path.endsWith('/') && !ctx.path.includes('.')) {
await next();
const document = parse(ctx.body);
injectManuallyResolvedModulesToImportMap(document);
transformDevServerHTML(document);
ctx.body = serialize(document);
} else {
return next();
}
},
],
plugins: [
stripCssImportAttributesPlugin(),
{
name: 'watch-demos',
serverStart(args) {
const fsDemoFilesGlob = new URL('./elements/*/demo/**/*.html', import.meta.url).pathname;
args.fileWatcher.add(fsDemoFilesGlob);
args.app.use(function(ctx, next) {
if (ctx.path.match(/\/|\.css|\.html|\.js$/)) {
ctx.etag = `e${Math.random() * Date.now()}`;
}
return next();
});
},
},
],
});