-
Notifications
You must be signed in to change notification settings - Fork 9
/
sandbox.js
59 lines (50 loc) · 2.03 KB
/
sandbox.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
import fs from 'node:fs/promises';
import { renderFromHTML } from './src/wcc.js';
const clientSideComponents = [
'card.js',
'card.jsx',
'counter.jsx',
'counter-dsd.jsx',
'greeting.ts'
];
async function init() {
const distRoot = new URL('./dist/', import.meta.url);
const sandboxRoot = new URL('./sandbox/', import.meta.url); // './sandbox';
const sandboxHtml = await fs.readFile(new URL('./index.html', sandboxRoot), 'utf-8');
const components = await fs.readdir(new URL('./components/', sandboxRoot));
const componentsUrls = components.map(component => new URL(`./components/${component}`, sandboxRoot));
const interactiveComponents = components.filter(component => clientSideComponents.includes(component));
const { html, metadata } = await renderFromHTML(sandboxHtml, componentsUrls);
const scriptTags = interactiveComponents.map(component => {
const ext = component.split('.').pop();
const outputName = ext === 'js'
? component
: component.replace('.jsx', '-jsx.js').replace('.ts', '-ts.js');
return `<script type="module" src="./components/${outputName}"></script>`;
}).join('\n');
for (const component of interactiveComponents) {
const ext = component.split('.').pop();
const outputName = ext === 'js'
? component
: component.replace('.jsx', '-jsx.js').replace('.ts', '-ts.js');
const source = new URL(`./components/${component}`, sandboxRoot);
const destination = new URL(`./components/${outputName}`, distRoot);
await fs.mkdir(new URL('./components/', distRoot), { recursive: true });
if (ext === 'js') {
await fs.copyFile(source, destination);
} else {
const key = `sb-${component.replace('.', '-')}`;
for (const element in metadata) {
if (element === key) {
await fs.writeFile(destination, metadata[element].source);
}
}
}
}
await fs.mkdir(distRoot, { recursive: true });
await fs.writeFile(new URL('./index.html', distRoot), html.replace('</head>', `
${scriptTags}
</head>
`.trim()));
}
init();