Skip to content
Source
Sign inSign up
Open History to see the last commit

generate-device-stream.mts

42 lines1.6 KB

1import * as NodeFSP from "node:fs/promises";
2import * as NodePath from "node:path";
3import * as NodeURL from "node:url";
4import { build } from "vite-plus";
5​
6const mobileRoot = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");
7​
8async function generateWebViewScript(feature: string, name: string) {
9 const stem = `${name.toLowerCase()}-stream`;
10 const result = await build({
11 configFile: false,
12 logLevel: "silent",
13 build: {
14 write: false,
15 target: "es2022",
16 minify: true,
17 lib: {
18 entry: NodePath.join(mobileRoot, "src/features", feature, `${stem}.browser.ts`),
19 name: `T3${name}Stream`,
20 formats: ["iife"],
21 },
22 },
23 });
24 const bundles = Array.isArray(result) ? result : [result];
25 const chunk = bundles
26 .flatMap((bundle) => ("output" in bundle ? bundle.output : []))
27 .find((output) => output.type === "chunk");
28 if (!chunk) throw new Error(`${name} build did not emit a script.`);
29 const root = NodePath.join(mobileRoot, ".generated", stem);
30 await NodeFSP.mkdir(root, { recursive: true });
31 for (const [file, contents] of [
32 ["index.js", `module.exports = ${JSON.stringify(chunk.code)};\n`],
33 ["package.json", '{"main":"index.js"}\n'],
34 ] as const) {
35 const destination = NodePath.join(root, file);
36 const previous = await NodeFSP.readFile(destination, "utf8").catch(() => null);
37 if (previous !== contents) await NodeFSP.writeFile(destination, contents);
38 }
40​
41export const generateDeviceStreamScript = () => generateWebViewScript("devices", "Device");
42export const generatePreviewStreamScript = () => generateWebViewScript("browser", "Preview");