forked from happo/happo-plugin-storybook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (91 loc) · 2.51 KB
/
index.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
const { Writable } = require('stream');
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const Archiver = require('archiver');
const rimraf = require('rimraf');
function zipFolderToBuffer(outputDir) {
return new Promise((resolve, reject) => {
const archive = new Archiver('zip');
const stream = new Writable();
const data = [];
stream._write = (chunk, enc, done) => {
data.push(...chunk);
done();
};
stream.on('finish', () => {
const buffer = Buffer.from(data);
resolve(buffer);
});
archive.pipe(stream);
archive.directory(outputDir, '');
archive.on('error', reject);
archive.finalize();
});
}
function buildStorybook({ configDir, staticDir, outputDir }) {
return new Promise((resolve, reject) => {
rimraf.sync(outputDir);
const params = [
'build-storybook',
'--output-dir',
outputDir,
'--config-dir',
configDir,
];
if (staticDir) {
params.push('--static-dir');
params.push(staticDir);
}
const binary = fs.existsSync('yarn.lock') ? 'yarn' : 'npx';
const spawned = spawn(binary, params, {
stdio: 'inherit',
shell: process.platform == 'win32',
});
spawned.on('exit', code => {
if (code === 0) {
resolve();
} else {
reject(new Error('Failed to build static storybook package'));
}
});
});
}
module.exports = function happoStorybookPlugin({
configDir = '.storybook',
staticDir,
outputDir = '.out',
usePrebuiltPackage = false,
} = {}) {
return {
generateStaticPackage: async () => {
if (!usePrebuiltPackage) {
await buildStorybook({ configDir, staticDir, outputDir });
}
const iframePath = path.join(outputDir, 'iframe.html');
if (!fs.existsSync(iframePath)) {
throw new Error(
'Failed to build static storybook package (missing iframe.html)',
);
}
try {
const iframeContent = fs.readFileSync(iframePath, 'utf-8');
fs.writeFileSync(
iframePath,
iframeContent.replace(
'<head>',
`<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript">window.__IS_HAPPO_RUN = true;</script>
`,
),
);
const buffer = await zipFolderToBuffer(outputDir);
return buffer.toString('base64');
} catch (e) {
console.error(e);
throw e;
}
},
};
};