-
Notifications
You must be signed in to change notification settings - Fork 7
/
wcc.js
289 lines (243 loc) · 8.51 KB
/
wcc.js
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/* eslint-disable max-depth */
// this must come first
import './dom-shim.js';
import * as acorn from 'acorn';
import * as walk from 'acorn-walk';
import { generate } from '@projectevergreen/escodegen-esm';
import { getParser, parseJsx } from './jsx-loader.js';
import { parse, parseFragment, serialize } from 'parse5';
// Need an acorn plugin for now - https://github.com/ProjectEvergreen/greenwood/issues/1218
import { importAttributes } from 'acorn-import-attributes';
import { transform } from 'sucrase';
import fs from 'fs';
// https://developer.mozilla.org/en-US/docs/Glossary/Void_element
const VOID_ELEMENTS = [
'area',
'base',
'br',
'col',
'embed',
'hr',
'img',
'input',
'link',
'meta',
'param', // deprecated
'source',
'track',
'wbr'
];
function getParse(html) {
return html.indexOf('<html>') >= 0 || html.indexOf('<body>') >= 0 || html.indexOf('<head>') >= 0
? parse
: parseFragment;
}
function isCustomElementDefinitionNode(node) {
const { expression } = node;
return expression.type === 'CallExpression' && expression.callee && expression.callee.object
&& expression.callee.property && expression.callee.object.name === 'customElements'
&& expression.callee.property.name === 'define';
}
async function renderComponentRoots(tree, definitions) {
for (const node of tree.childNodes) {
if (node.tagName && node.tagName.indexOf('-') > 0) {
const { tagName } = node;
if (definitions[tagName]) {
const { moduleURL } = definitions[tagName];
const elementInstance = await initializeCustomElement(moduleURL, tagName, node, definitions);
if (elementInstance) {
const hasShadow = elementInstance.shadowRoot;
const elementHtml = hasShadow
? elementInstance.getInnerHTML({ includeShadowRoots: true })
: elementInstance.innerHTML;
const elementTree = parseFragment(elementHtml);
const hasLight = elementTree.childNodes > 0;
node.childNodes = node.childNodes.length === 0 && hasLight && !hasShadow
? elementTree.childNodes
: hasShadow
? [...elementTree.childNodes, ...node.childNodes]
: elementTree.childNodes;
} else {
console.warn(`WARNING: customElement <${tagName}> detected but not serialized. You may not have exported it.`);
}
} else {
console.warn(`WARNING: customElement <${tagName}> is not defined. You may not have imported it.`);
}
}
if (node.childNodes && node.childNodes.length > 0) {
await renderComponentRoots(node, definitions);
}
// does this only apply to `<template>` tags?
if (node.content && node.content.childNodes && node.content.childNodes.length > 0) {
await renderComponentRoots(node.content, definitions);
}
}
return tree;
}
function registerDependencies(moduleURL, definitions, depth = 0) {
const moduleContents = fs.readFileSync(moduleURL, 'utf-8');
const result = transform(moduleContents, {
transforms: ['typescript', 'jsx'],
jsxRuntime: 'preserve'
});
const nextDepth = depth += 1;
const customParser = getParser(moduleURL);
const parser = customParser ? customParser.parser : acorn.Parser;
const config = customParser ? customParser.config : {
...walk.base
};
walk.simple(parser.extend(importAttributes).parse(result.code, {
ecmaVersion: 'latest',
sourceType: 'module'
}), {
ImportDeclaration(node) {
const specifier = node.source.value;
const isBareSpecifier = specifier.indexOf('.') !== 0 && specifier.indexOf('/') !== 0;
const extension = specifier.split('.').pop();
// would like to decouple .jsx from the core, ideally
// https://github.com/ProjectEvergreen/wcc/issues/122
if (!isBareSpecifier && ['js', 'jsx', 'ts'].includes(extension)) {
const dependencyModuleURL = new URL(node.source.value, moduleURL);
registerDependencies(dependencyModuleURL, definitions, nextDepth);
}
},
ExpressionStatement(node) {
if (isCustomElementDefinitionNode(node)) {
const { arguments: args } = node.expression;
const tagName = args[0].type === 'Literal'
? args[0].value // single and double quotes
: args[0].quasis[0].value.raw; // template literal
const tree = parseJsx(moduleURL);
const isEntry = nextDepth - 1 === 1;
definitions[tagName] = {
instanceName: args[1].name,
moduleURL,
source: generate(tree),
url: moduleURL,
isEntry
};
}
}
}, config);
}
async function getTagName(moduleURL) {
const moduleContents = await fs.promises.readFile(moduleURL, 'utf-8');
const result = transform(moduleContents, {
transforms: ['typescript', 'jsx'],
jsxRuntime: 'preserve'
});
const customParser = getParser(moduleURL);
const parser = customParser ? customParser.parser : acorn.Parser;
const config = customParser ? customParser.config : {
...walk.base
};
let tagName;
walk.simple(parser.extend(importAttributes).parse(result.code, {
ecmaVersion: 'latest',
sourceType: 'module'
}), {
ExpressionStatement(node) {
if (isCustomElementDefinitionNode(node)) {
tagName = node.expression.arguments[0].value;
}
}
}, config);
return tagName;
}
function renderLightDomChildren(childNodes, iHTML = '') {
let innerHTML = iHTML;
childNodes.forEach((child) => {
const { nodeName, attrs = [], value } = child;
if (nodeName !== '#text') {
innerHTML += `<${nodeName}`;
if (attrs.length > 0) {
attrs.forEach(attr => {
innerHTML += ` ${attr.name}="${attr.value}"`;
});
}
innerHTML += '>';
if (child.childNodes.length > 0) {
innerHTML = renderLightDomChildren(child.childNodes, innerHTML);
}
innerHTML += VOID_ELEMENTS.includes(nodeName)
? ''
: `</${nodeName}>`;
} else if (nodeName === '#text') {
innerHTML += value;
}
});
return innerHTML;
}
async function initializeCustomElement(elementURL, tagName, node = {}, definitions = [], isEntry, props = {}) {
const { attrs = [], childNodes = [] } = node;
if (!tagName) {
const depth = isEntry ? 1 : 0;
registerDependencies(elementURL, definitions, depth);
}
// https://github.com/ProjectEvergreen/wcc/pull/67/files#r902061804
// https://github.com/ProjectEvergreen/wcc/pull/159
const { href } = elementURL;
const element = customElements.get(tagName) ?? (await import(href)).default;
const dataLoader = (await import(href)).getData;
const data = props
? props
: dataLoader
? await dataLoader(props)
: {};
if (element) {
const elementInstance = new element(data); // eslint-disable-line new-cap
// support for HTML (Light DOM) Web Components
elementInstance.innerHTML = renderLightDomChildren(childNodes);
attrs.forEach((attr) => {
elementInstance.setAttribute(attr.name, attr.value);
if (attr.name === 'hydrate') {
definitions[tagName].hydrate = attr.value;
}
});
await elementInstance.connectedCallback();
return elementInstance;
}
}
async function renderToString(elementURL, wrappingEntryTag = true, props = {}) {
const definitions = [];
const elementTagName = wrappingEntryTag && await getTagName(elementURL);
const isEntry = !!elementTagName;
const elementInstance = await initializeCustomElement(elementURL, undefined, undefined, definitions, isEntry, props);
let html;
// in case the entry point isn't valid
if (elementInstance) {
const elementHtml = elementInstance.shadowRoot
? elementInstance.getInnerHTML({ includeShadowRoots: true })
: elementInstance.innerHTML;
const elementTree = getParse(elementHtml)(elementHtml);
const finalTree = await renderComponentRoots(elementTree, definitions);
html = wrappingEntryTag && elementTagName ? `
<${elementTagName}>
${serialize(finalTree)}
</${elementTagName}>
`
: serialize(finalTree);
} else {
console.warn('WARNING: No custom element class found for this entry point.');
}
return {
html,
metadata: definitions
};
}
async function renderFromHTML(html, elements = []) {
const definitions = [];
for (const url of elements) {
registerDependencies(url, definitions, 1);
}
const elementTree = getParse(html)(html);
const finalTree = await renderComponentRoots(elementTree, definitions);
return {
html: serialize(finalTree),
metadata: definitions
};
}
export {
renderToString,
renderFromHTML
};