forked from ProjectEvergreen/wcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wcc.js
240 lines (200 loc) · 7.13 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
/* 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 'astring';
import { getParser, parseJsx } from './jsx-loader.js';
import { parse, parseFragment, serialize } from 'parse5';
import { transform } from 'sucrase';
import fs from 'fs';
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 { attrs, tagName } = node;
if (definitions[tagName]) {
const { moduleURL } = definitions[tagName];
const elementInstance = await initializeCustomElement(moduleURL, tagName, node, definitions);
if (elementInstance) {
const hasShadow = elementInstance.shadowRoot;
node.childNodes = hasShadow
? [...elementInstance.shadowRoot.childNodes, ...node.childNodes]
: elementInstance.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.`);
}
attrs.forEach((attr) => {
if (attr.name === 'hydrate') {
definitions[tagName].hydrate = attr.value;
}
});
}
if (node.childNodes && node.childNodes.length > 0) {
await renderComponentRoots(node, definitions);
}
if (node.shadowRoot && node.shadowRoot.childNodes?.length > 0) {
await renderComponentRoots(node.shadowRoot, definitions);
}
// does this only apply to `<template>` tags?
if (node.content && 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.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.parse(result.code, {
ecmaVersion: 'latest',
sourceType: 'module'
}), {
ExpressionStatement(node) {
if (isCustomElementDefinitionNode(node)) {
tagName = node.expression.arguments[0].value;
}
}
}, config);
return tagName;
}
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
elementInstance.childNodes = childNodes;
attrs.forEach((attr) => {
elementInstance.setAttribute(attr.name, 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) {
elementInstance.nodeName = elementTagName ?? '';
elementInstance.tagName = elementTagName ?? '';
await renderComponentRoots(
elementInstance.shadowRoot
?
{
nodeName: '#document-fragment',
childNodes: [elementInstance]
}
: elementInstance,
definitions
);
html = wrappingEntryTag && elementTagName ? `
<${elementTagName}>
${serialize(elementInstance)}
</${elementTagName}>
`
: serialize(elementInstance);
} 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
};