/
build-html.ts
437 lines (389 loc) · 11.5 KB
/
build-html.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import Bluebird from "bluebird"
import fs from "fs-extra"
import reporter from "gatsby-cli/lib/reporter"
import { createErrorFromString } from "gatsby-cli/lib/reporter/errors"
import { chunk } from "lodash"
import webpack, { Stats } from "webpack"
import * as path from "path"
import { emitter, store } from "../redux"
import { IWebpackWatchingPauseResume } from "../utils/start-server"
import webpackConfig from "../utils/webpack.config"
import { structureWebpackErrors } from "../utils/webpack-error-utils"
import * as buildUtils from "./build-utils"
import { Span } from "opentracing"
import { IProgram, Stage } from "./types"
import { PackageJson } from "../.."
import type { GatsbyWorkerPool } from "../utils/worker/pool"
type IActivity = any // TODO
export interface IBuildArgs extends IProgram {
directory: string
sitePackageJson: PackageJson
prefixPaths: boolean
noUglify: boolean
logPages: boolean
writeToFile: boolean
profile: boolean
graphqlTracing: boolean
openTracingConfigFile: string
keepPageRenderer: boolean
}
let devssrWebpackCompiler: webpack.Compiler
let devssrWebpackWatcher: IWebpackWatchingPauseResume
let needToRecompileSSRBundle = true
export const getDevSSRWebpack = (): {
devssrWebpackWatcher: IWebpackWatchingPauseResume
devssrWebpackCompiler: webpack.Compiler
needToRecompileSSRBundle: boolean
} => {
if (process.env.gatsby_executing_command !== `develop`) {
throw new Error(`This function can only be called in development`)
}
return {
devssrWebpackWatcher,
devssrWebpackCompiler,
needToRecompileSSRBundle,
}
}
let oldHash = ``
let newHash = ``
const runWebpack = (
compilerConfig,
stage: Stage,
directory,
parentSpan?: Span
): Bluebird<{
stats: Stats
waitForCompilerClose: Promise<void>
}> =>
new Bluebird((resolve, reject) => {
if (!process.env.GATSBY_EXPERIMENTAL_DEV_SSR || stage === `build-html`) {
const compiler = webpack(compilerConfig)
compiler.run((err, stats) => {
let activity
if (process.env.GATSBY_EXPERIMENTAL_PRESERVE_WEBPACK_CACHE) {
activity = reporter.activityTimer(
`Caching HTML renderer compilation`,
{ parentSpan }
)
activity.start()
}
const waitForCompilerClose = new Promise<void>((resolve, reject) => {
compiler.close(error => {
if (activity) {
activity.end()
}
if (error) {
return reject(error)
}
return resolve()
})
})
if (err) {
return reject(err)
} else {
return resolve({ stats: stats as Stats, waitForCompilerClose })
}
})
} else if (
process.env.GATSBY_EXPERIMENTAL_DEV_SSR &&
stage === `develop-html`
) {
devssrWebpackCompiler = webpack(compilerConfig)
devssrWebpackCompiler.hooks.invalid.tap(`ssr file invalidation`, () => {
needToRecompileSSRBundle = true
})
devssrWebpackWatcher = devssrWebpackCompiler.watch(
{
ignored: /node_modules/,
},
(err, stats) => {
needToRecompileSSRBundle = false
emitter.emit(`DEV_SSR_COMPILATION_DONE`)
devssrWebpackWatcher.suspend()
if (err) {
return reject(err)
} else {
newHash = stats?.hash || ``
const {
restartWorker,
} = require(`../utils/dev-ssr/render-dev-html`)
// Make sure we use the latest version during development
if (oldHash !== `` && newHash !== oldHash) {
restartWorker(`${directory}/public/render-page.js`)
}
oldHash = newHash
return resolve({
stats: stats as Stats,
waitForCompilerClose: Promise.resolve(),
})
}
}
) as IWebpackWatchingPauseResume
}
})
const doBuildRenderer = async (
{ directory }: IProgram,
webpackConfig: webpack.Configuration,
stage: Stage,
parentSpan?: Span
): Promise<{ rendererPath: string; waitForCompilerClose }> => {
const { stats, waitForCompilerClose } = await runWebpack(
webpackConfig,
stage,
directory,
parentSpan
)
if (stats.hasErrors()) {
reporter.panic(structureWebpackErrors(stage, stats.compilation.errors))
}
if (
stage === `build-html` &&
store.getState().html.ssrCompilationHash !== stats.hash
) {
store.dispatch({
type: `SET_SSR_WEBPACK_COMPILATION_HASH`,
payload: stats.hash as string,
})
}
// render-page.js is hard coded in webpack.config
return {
rendererPath: `${directory}/public/render-page.js`,
waitForCompilerClose,
}
}
export const buildRenderer = async (
program: IProgram,
stage: Stage,
parentSpan?: IActivity
): Promise<{ rendererPath: string; waitForCompilerClose }> => {
const { directory } = program
const config = await webpackConfig(program, directory, stage, null, {
parentSpan,
})
return doBuildRenderer(program, config, stage, parentSpan)
}
export const deleteRenderer = async (rendererPath: string): Promise<void> => {
try {
await fs.remove(rendererPath)
await fs.remove(`${rendererPath}.map`)
} catch (e) {
// This function will fail on Windows with no further consequences.
}
}
export interface IRenderHtmlResult {
unsafeBuiltinsUsageByPagePath: Record<string, Array<string>>
}
const renderHTMLQueue = async (
workerPool: GatsbyWorkerPool,
activity: IActivity,
htmlComponentRendererPath: string,
pages: Array<string>,
stage: Stage = Stage.BuildHTML
): Promise<void> => {
// We need to only pass env vars that are set programmatically in gatsby-cli
// to child process. Other vars will be picked up from environment.
const envVars: Array<[string, string | undefined]> = [
[`NODE_ENV`, process.env.NODE_ENV],
[`gatsby_executing_command`, process.env.gatsby_executing_command],
[`gatsby_log_level`, process.env.gatsby_log_level],
]
const segments = chunk(pages, 50)
const sessionId = Date.now()
const renderHTML =
stage === `build-html`
? workerPool.single.renderHTMLProd
: workerPool.single.renderHTMLDev
const uniqueUnsafeBuiltinUsedStacks = new Set<string>()
try {
await Bluebird.map(segments, async pageSegment => {
const renderHTMLResult = await renderHTML({
envVars,
htmlComponentRendererPath,
paths: pageSegment,
sessionId,
})
if (stage === `build-html`) {
const htmlRenderMeta = renderHTMLResult as IRenderHtmlResult
store.dispatch({
type: `HTML_GENERATED`,
payload: pageSegment,
})
for (const [_pagePath, arrayOfUsages] of Object.entries(
htmlRenderMeta.unsafeBuiltinsUsageByPagePath
)) {
for (const unsafeUsageStack of arrayOfUsages) {
uniqueUnsafeBuiltinUsedStacks.add(unsafeUsageStack)
}
}
}
if (activity && activity.tick) {
activity.tick(pageSegment.length)
}
})
} catch (e) {
if (e?.context?.unsafeBuiltinsUsageByPagePath) {
for (const [_pagePath, arrayOfUsages] of Object.entries(
e.context.unsafeBuiltinsUsageByPagePath
)) {
// @ts-ignore TS doesn't know arrayOfUsages is Iterable
for (const unsafeUsageStack of arrayOfUsages) {
uniqueUnsafeBuiltinUsedStacks.add(unsafeUsageStack)
}
}
}
throw e
} finally {
if (uniqueUnsafeBuiltinUsedStacks.size > 0) {
console.warn(
`Unsafe builtin method was used, future builds will need to rebuild all pages`
)
store.dispatch({
type: `SSR_USED_UNSAFE_BUILTIN`,
})
}
for (const unsafeBuiltinUsedStack of uniqueUnsafeBuiltinUsedStacks) {
const prettyError = await createErrorFromString(
unsafeBuiltinUsedStack,
`${htmlComponentRendererPath}.map`
)
const warningMessage = `${prettyError.stack}${
prettyError.codeFrame ? `\n\n${prettyError.codeFrame}\n` : ``
}`
reporter.warn(warningMessage)
}
}
}
class BuildHTMLError extends Error {
codeFrame = ``
context?: {
path: string
}
constructor(error: Error) {
super(error.message)
// We must use getOwnProperty because keys like `stack` are not enumerable,
// but we want to copy over the entire error
Object.getOwnPropertyNames(error).forEach(key => {
this[key] = error[key]
})
}
}
export const doBuildPages = async (
rendererPath: string,
pagePaths: Array<string>,
activity: IActivity,
workerPool: GatsbyWorkerPool,
stage: Stage
): Promise<void> => {
try {
await renderHTMLQueue(workerPool, activity, rendererPath, pagePaths, stage)
} catch (error) {
const prettyError = await createErrorFromString(
error.stack,
`${rendererPath}.map`
)
const buildError = new BuildHTMLError(prettyError)
buildError.context = error.context
throw buildError
}
}
// TODO remove in v4 - this could be a "public" api
export const buildHTML = async ({
program,
stage,
pagePaths,
activity,
workerPool,
}: {
program: IProgram
stage: Stage
pagePaths: Array<string>
activity: IActivity
workerPool: GatsbyWorkerPool
}): Promise<void> => {
const { rendererPath } = await buildRenderer(program, stage, activity.span)
await doBuildPages(rendererPath, pagePaths, activity, workerPool, stage)
await deleteRenderer(rendererPath)
}
export async function buildHTMLPagesAndDeleteStaleArtifacts({
pageRenderer,
workerPool,
buildSpan,
program,
}: {
pageRenderer: string
workerPool: GatsbyWorkerPool
buildSpan?: Span
program: IBuildArgs
}): Promise<{
toRegenerate: Array<string>
toDelete: Array<string>
}> {
buildUtils.markHtmlDirtyIfResultOfUsedStaticQueryChanged()
const {
toRegenerate,
toDelete,
toCleanupFromTrackedState,
} = buildUtils.calcDirtyHtmlFiles(store.getState())
store.dispatch({
type: `HTML_TRACKED_PAGES_CLEANUP`,
payload: toCleanupFromTrackedState,
})
if (toRegenerate.length > 0) {
const buildHTMLActivityProgress = reporter.createProgress(
`Building static HTML for pages`,
toRegenerate.length,
0,
{
parentSpan: buildSpan,
}
)
buildHTMLActivityProgress.start()
try {
await doBuildPages(
pageRenderer,
toRegenerate,
buildHTMLActivityProgress,
workerPool,
Stage.BuildHTML
)
} catch (err) {
let id = `95313` // TODO: verify error IDs exist
const context = {
errorPath: err.context && err.context.path,
ref: ``,
}
const match = err.message.match(
/ReferenceError: (window|document|localStorage|navigator|alert|location) is not defined/i
)
if (match && match[1]) {
id = `95312`
context.ref = match[1]
}
buildHTMLActivityProgress.panic({
id,
context,
error: err,
})
}
buildHTMLActivityProgress.end()
} else {
reporter.info(`There are no new or changed html files to build.`)
}
if (!program.keepPageRenderer) {
try {
await deleteRenderer(pageRenderer)
} catch (err) {
// pass through
}
}
if (toDelete.length > 0) {
const publicDir = path.join(program.directory, `public`)
const deletePageDataActivityTimer = reporter.activityTimer(
`Delete previous page data`
)
deletePageDataActivityTimer.start()
await buildUtils.removePageFiles(publicDir, toDelete)
deletePageDataActivityTimer.end()
}
return { toRegenerate, toDelete }
}