forked from codesandbox/static-browser-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild-relay.ts
More file actions
85 lines (72 loc) · 2.32 KB
/
build-relay.ts
File metadata and controls
85 lines (72 loc) · 2.32 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
import esbuild from "esbuild";
import Mustache from "mustache";
import pathUtils from "path";
import fs from "fs";
import { hashString } from "./utils";
const SHOULD_MINIFY = !!process.env.MINIFY;
const PREVIEW_OUT_DIR = pathUtils.join(__dirname, "./out/preview");
const RELAY_OUT_DIR = pathUtils.join(__dirname, "./out/preview/__csb_relay");
fs.mkdirSync(RELAY_OUT_DIR, { recursive: true });
async function bundleRelay(swPath: string): Promise<string> {
const entry = pathUtils.join(__dirname, "./src/preview/relay/main.ts");
const result = await esbuild.build({
write: false,
bundle: true,
minify: SHOULD_MINIFY,
sourcemap: false,
platform: "browser",
format: "iife",
outdir: PREVIEW_OUT_DIR,
entryPoints: [entry],
define: {
__SERVICE_WORKER_BUNDLE_NAME: JSON.stringify(swPath),
},
});
const text = result.outputFiles[0].text;
const bundleName = `/__csb_relay/__csb_relay.${hashString(text)}.js`;
const fullPath = pathUtils.join(PREVIEW_OUT_DIR, bundleName);
fs.writeFileSync(fullPath, text, "utf-8");
return bundleName;
}
async function bundleServiceWorker(): Promise<string> {
const entry = pathUtils.join(
__dirname,
"./src/preview/relay/service-worker.ts"
);
const result = await esbuild.build({
write: false,
bundle: true,
minify: SHOULD_MINIFY,
sourcemap: false,
platform: "browser",
format: "iife",
outdir: PREVIEW_OUT_DIR,
entryPoints: [entry],
});
const text = result.outputFiles[0].text;
const bundleName = `/__csb_sw.${hashString(text)}.js`;
const fullPath = pathUtils.join(PREVIEW_OUT_DIR, bundleName);
fs.writeFileSync(fullPath, text, "utf-8");
return bundleName;
}
async function run() {
const swBundleUrl = await bundleServiceWorker();
const relayBundleUrl = await bundleRelay(swBundleUrl);
const relayIndexHTMLTemplate = fs.readFileSync(
pathUtils.join(__dirname, "src/preview/relay/index.html"),
"utf-8"
);
const renderedRelayIndexHTML = Mustache.render(relayIndexHTMLTemplate, {
relayBundleUrl,
});
fs.writeFileSync(
pathUtils.join(__dirname, "out/preview/__csb_relay/index.html"),
renderedRelayIndexHTML,
"utf-8"
);
fs.copyFileSync(
pathUtils.join(__dirname, "src/preview/index.html"),
pathUtils.join(__dirname, "out/preview/index.html")
);
}
run().catch(console.error);