-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.ts
290 lines (244 loc) · 9.82 KB
/
index.ts
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import fs from 'fs'
import path from 'path'
import { minimatch } from 'minimatch'
import { globbySync } from 'globby'
import type { InputOptions } from 'rollup'
import type {
Manifest,
ManifestChunk,
Plugin,
ResolvedConfig,
UserConfig,
} from 'vite'
export interface PluginConfig {
/** Use to map input files to template paths
*
* @default {
'graphics/*.{js,ts}': './src/graphics/template.html',
'dashboard/*.{js,ts}': './src/dashboard/template.html',
}
*/
inputs?: { [key: string]: string } | undefined
/** Base directory for input-file paths
* @default './src'
*/
srcDir?: string | undefined
}
export default function viteNodeCGPlugin(pluginConfig: PluginConfig): Plugin {
const bundleName = path.basename(process.cwd())
const inputConfig = pluginConfig?.inputs ?? {
'graphics/*.{js,ts}': './src/graphics/template.html',
'dashboard/*.{js,ts}': './src/dashboard/template.html',
}
const srcDir = pluginConfig?.srcDir ?? './src'
const inputPatterns = [
...Object.keys(inputConfig).map((matchPath) =>
path.posix.join(srcDir, matchPath)
),
'!**.d.ts',
]
// string array of paths to all input files (always ignore ts declaration files)
const inputs = globbySync(inputPatterns)
if (!inputs || !inputs.length) {
console.error('vite-plugin-nodecg: No inputs were found! Exiting')
process.exit(1)
} else {
console.log('vite-plugin-nodecg: Found the following inputs: ', inputs)
}
// now we know which inputs actually exist, lets clean up unused inputConfig entries so we don't load templates we don't need
// useful in the case the default inputsConfig is used, but the nodecg bundle has only dashboards or only graphics (or no inputs at all)
Object.keys(inputConfig).forEach((matchPath) => {
if (
!inputs.some((input) =>
minimatch(input, path.posix.join(srcDir, matchPath))
)
)
delete inputConfig[matchPath]
})
// map from template paths to file buffers
const templates = {} as { [key: string]: string }
Object.values(inputConfig).forEach((templatePath) => {
if (templates[templatePath]) return // skip if already read
const fullPath = path.posix.join(process.cwd(), templatePath)
templates[templatePath] = fs.readFileSync(fullPath, 'utf-8')
})
let config: ResolvedConfig
let dSrvProtocol: string
let dSrvHost: string
let assetManifest: Manifest
let resolvedInputOptions: InputOptions
// take the template html and inject script and css assets into <head>
function injectAssetsTags(html: string, entry: string) {
const tags = []
if (config.mode === 'development') {
tags.push(
`<script type="module" src="${dSrvProtocol}://${path.posix.join(
dSrvHost,
'bundles',
bundleName,
'@vite/client'
)}"></script>`
)
tags.push(
`<script type="module" src="${dSrvProtocol}://${path.posix.join(
dSrvHost,
'bundles',
bundleName,
entry
)}"></script>`
)
} else if (config.mode === 'production' && assetManifest) {
let entryChunk = assetManifest[entry]
function generateCssTags(
chunk: ManifestChunk,
alreadyProcessed: string[] = []
) {
chunk.css?.forEach((cssPath) => {
if (alreadyProcessed.includes(cssPath)) return // de-dupe assets
tags.push(
`<link rel="stylesheet" href="${path.posix.join(
config.base,
cssPath
)}" />`
)
alreadyProcessed.push(cssPath)
})
// recurse
chunk.imports?.forEach((importPath) => {
generateCssTags(assetManifest[importPath], alreadyProcessed)
})
}
generateCssTags(entryChunk)
tags.push(
`<script type="module" src="${path.posix.join(
config.base,
entryChunk.file
)}"></script>`
)
}
const newHtml = html.includes('</head>')
? html.replace('</head>', tags.join('\n') + '\n</head>')
: tags.join('\n') + '\n' + html
return newHtml
}
// for each input (graphics & dashboard panels) create an html doc and emit to disk
function generateHTMLFiles() {
let resolvedInputs: string[]
// populate inputs, taking into account "input" can come in 3 forms
if (typeof resolvedInputOptions.input === 'string') {
resolvedInputs = [resolvedInputOptions.input]
} else if (Array.isArray(resolvedInputOptions.input)) {
resolvedInputs = resolvedInputOptions.input
} else {
resolvedInputs = Object.values(resolvedInputOptions.input)
}
const htmlDocs = {} as { [key: string]: string }
// generate string html for each input
resolvedInputs.forEach((inputPath) => {
// find first template that has a match path that this input satisfies
const matchPath = Object.keys(inputConfig).find((matchPath) => {
return minimatch(inputPath, path.posix.join(srcDir, matchPath))
})
const templatePath = inputConfig[matchPath]
const template = templates[templatePath]
// check template was found in the inputConfig and we loaded it from disk, otherwise skip this input
if (!template) {
console.error(
`vite-plugin-nodecg: No template found to match input "${inputPath}". This probably means the input file was manually specified in the vite rollup config, and the graphic/dashboard will not be built.`
)
return
}
// add asset tags to template
const html = injectAssetsTags(
templates[templatePath],
inputPath.replace(/^(\.\/)/, '')
)
const buildDir = path.dirname(path.relative(srcDir, inputPath))
const name = path.basename(inputPath, path.extname(inputPath))
const filePath = path.join(buildDir, `${name}.html`)
htmlDocs[filePath] = html
})
// write each html doc to disk
for (const [filePath, htmlDoc] of Object.entries(htmlDocs)) {
const fullFilePath = path.join(process.cwd(), filePath)
const dir = path.dirname(fullFilePath)
try {
fs.mkdirSync(dir, { recursive: true })
} catch (e) {
console.error(
`vite-plugin-nodecg: Could not create directory ${dir} for input ${filePath}. Skipping...`
)
continue
}
fs.writeFile(fullFilePath, htmlDoc, () => {
console.log(
`vite-plugin-nodecg: Wrote input ${filePath} to disk`
)
})
}
}
return {
name: 'nodecg',
// validate and setup defaults in user's vite config
config: (_config, { mode }): UserConfig => {
return {
build: {
manifest: 'manifest.json',
outDir: 'shared/dist',
rollupOptions: {
input: inputs,
},
},
base: `/bundles/${bundleName}/${
mode === 'development' ? '' : 'shared/dist/'
}`,
}
},
configResolved(resolvedConfig: ResolvedConfig) {
// Capture resolved config for use in injectAssets
config = resolvedConfig
},
buildStart(options: InputOptions) {
// capture inputOptions for use in generateHtmlFiles in both dev & prod
resolvedInputOptions = options
},
writeBundle() {
if (!resolvedInputOptions?.input || config.mode !== 'production')
return
try {
// would be nice to not have to read the asset manifest from disk but I don't see another way
// relevant: https://github.com/vitejs/vite/blob/a9dfce38108e796e0de0e3b43ced34d60883cef3/packages/vite/src/node/ssr/ssrManifestPlugin.ts
assetManifest = JSON.parse(
fs
.readFileSync(
path.posix.join(
process.cwd(),
config.build.outDir,
'manifest.json'
)
)
.toString()
)
} catch (err) {
console.error(
"vite-plugin-nodecg: Failed to load manifest.json from build directory. HTML files won't be generated."
)
return
}
// prod inject
generateHTMLFiles()
},
configureServer(server) {
server.httpServer.on('listening', () => {
dSrvProtocol = server.config.server.https ? 'https' : 'http'
dSrvHost = `${server.config.server.host ?? 'localhost'}:${
server.config.server.port ?? '5173'
}`
// fix dev server origin
server.config.server.origin = `${dSrvProtocol}://${dSrvHost}`
// dev inject
generateHTMLFiles()
})
},
}
}