-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
build-headers-program.js
368 lines (312 loc) · 9.35 KB
/
build-headers-program.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
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
import _ from "lodash"
import { createWriteStream, existsSync } from "fs-extra"
import { parse, posix } from "path"
import kebabHash from "kebab-hash"
import { fixedPagePath } from "gatsby-core-utils"
import { IMMUTABLE_CACHING_HEADER } from "./constants"
import {
COMMON_BUNDLES,
SECURITY_HEADERS,
CACHING_HEADERS,
LINK_REGEX,
HEADERS_FILENAME,
PAGE_DATA_DIR,
} from "./constants"
import { emitHeaders } from "./ipc"
function getHeaderName(header) {
const matches = header.match(/^([^:]+):/)
return matches && matches[1]
}
function validHeaders(headers, reporter) {
if (!headers || !_.isObject(headers)) {
return false
}
return _.every(
headers,
(headersList, path) =>
_.isArray(headersList) &&
_.every(headersList, header => {
if (_.isString(header)) {
if (!getHeaderName(header)) {
// TODO panic on builds on v3
reporter.warn(
`[gatsby-plugin-gatsby-cloud] ${path} contains an invalid header (${header}). Please check your plugin configuration`
)
}
return true
}
return false
})
)
}
function linkTemplate(assetPath, type = `script`) {
return `Link: <${assetPath}>; rel=preload; as=${type}${
type === `fetch` ? `; crossorigin` : ``
}; nopush`
}
function pathChunkName(path) {
const name = path === `/` ? `index` : kebabHash(path)
return `path---${name}`
}
function getPageDataPath(path) {
return posix.join(`page-data`, fixedPagePath(path), `page-data.json`)
}
function getScriptPath(file, manifest) {
const chunk = manifest[file]
if (!chunk) {
return []
}
// convert to array if it's not already
const chunks = _.isArray(chunk) ? chunk : [chunk]
return chunks.filter(script => {
const parsed = parse(script)
// handle only .js, .css content is inlined already
// and doesn't need to be pushed
return parsed.ext === `.js`
})
}
function linkHeaders(files, pathPrefix) {
const linkHeaders = []
for (const resourceType in files) {
files[resourceType].forEach(file => {
linkHeaders.push(linkTemplate(`${pathPrefix}/${file}`, resourceType))
})
}
return linkHeaders
}
function headersPath(pathPrefix, path) {
return `${pathPrefix}${path}`
}
function preloadHeadersByPage({ pages, manifest, pathPrefix, publicFolder }) {
const linksByPage = {}
const appDataPath = publicFolder(PAGE_DATA_DIR, `app-data.json`)
const hasAppData = existsSync(appDataPath)
let hasPageData = false
if (pages.size) {
// test if 1 page-data file exists, if it does we know we're on a gatsby version that supports page-data
const pageDataPath = publicFolder(
getPageDataPath(pages.get(pages.keys().next().value).path)
)
hasPageData = existsSync(pageDataPath)
}
pages.forEach(page => {
const scripts = _.flatMap(COMMON_BUNDLES, file =>
getScriptPath(file, manifest)
)
scripts.push(...getScriptPath(pathChunkName(page.path), manifest))
scripts.push(...getScriptPath(page.componentChunkName, manifest))
const json = []
if (hasAppData) {
json.push(posix.join(PAGE_DATA_DIR, `app-data.json`))
}
if (hasPageData) {
json.push(getPageDataPath(page.path))
}
const filesByResourceType = {
script: scripts.filter(Boolean),
fetch: json,
}
const pathKey = headersPath(pathPrefix, page.path)
linksByPage[pathKey] = linkHeaders(filesByResourceType, pathPrefix)
})
return linksByPage
}
function defaultMerge(...headers) {
function unionMerge(objValue, srcValue) {
if (_.isArray(objValue)) {
return _.union(objValue, srcValue)
} else {
return undefined // opt into default merge behavior
}
}
return _.mergeWith({}, ...headers, unionMerge)
}
function headersMerge(userHeaders, defaultHeaders) {
const merged = {}
Object.keys(defaultHeaders).forEach(path => {
if (!userHeaders[path]) {
merged[path] = defaultHeaders[path]
return
}
const headersMap = {}
defaultHeaders[path].forEach(header => {
headersMap[getHeaderName(header)] = header
})
userHeaders[path].forEach(header => {
headersMap[getHeaderName(header)] = header // override if exists
})
merged[path] = Object.values(headersMap)
})
Object.keys(userHeaders).forEach(path => {
if (!merged[path]) {
merged[path] = userHeaders[path]
}
})
return merged
}
function transformLink(manifest, publicFolder, pathPrefix) {
return header =>
header.replace(LINK_REGEX, (__, prefix, file, suffix) => {
const hashed = manifest[file]
if (hashed) {
return `${prefix}${pathPrefix}${hashed}${suffix}`
} else if (existsSync(publicFolder(file))) {
return `${prefix}${pathPrefix}${file}${suffix}`
} else {
throw new Error(
`Could not find the file specified in the Link header \`${header}\`.` +
`The gatsby-plugin-gatsby-cloud is looking for a matching file (with or without a ` +
`webpack hash). Check the public folder and your gatsby-config.js to ensure you are ` +
`pointing to a public file.`
)
}
})
}
function stringifyHeaders(headers) {
return _.reduce(
headers,
(text, headerList, path) => {
const headersString = _.reduce(
headerList,
(accum, header) => `${accum} ${header}\n`,
``
)
return `${text}${path}\n${headersString}`
},
``
)
}
// program methods
const mapUserLinkHeaders =
({ manifest, pathPrefix, publicFolder }) =>
headers =>
_.mapValues(headers, headerList =>
_.map(headerList, transformLink(manifest, publicFolder, pathPrefix))
)
const mapUserLinkAllPageHeaders =
(pluginData, { allPageHeaders }) =>
headers => {
if (!allPageHeaders) {
return headers
}
const { pages, manifest, publicFolder, pathPrefix } = pluginData
const headersList = _.map(
allPageHeaders,
transformLink(manifest, publicFolder, pathPrefix)
)
const duplicateHeadersByPage = {}
pages.forEach(page => {
const pathKey = headersPath(pathPrefix, page.path)
duplicateHeadersByPage[pathKey] = headersList
})
return defaultMerge(headers, duplicateHeadersByPage)
}
const applyLinkHeaders =
(pluginData, { mergeLinkHeaders }) =>
headers => {
if (!mergeLinkHeaders) {
return headers
}
const { pages, manifest, pathPrefix, publicFolder } = pluginData
const perPageHeaders = preloadHeadersByPage({
pages,
manifest,
pathPrefix,
publicFolder,
})
return defaultMerge(headers, perPageHeaders)
}
const applySecurityHeaders =
({ mergeSecurityHeaders }) =>
headers => {
if (!mergeSecurityHeaders) {
return headers
}
return headersMerge(headers, SECURITY_HEADERS)
}
const applyCachingHeaders =
(pluginData, { mergeCachingHeaders }) =>
headers => {
if (!mergeCachingHeaders) {
return headers
}
let chunks = []
// Gatsby v3.5 added componentChunkName to store().components
// So we prefer to pull chunk names off that as it gets very expensive to loop
// over large numbers of pages.
const isComponentChunkSet = !!pluginData.components.entries()?.next()
?.value[1]?.componentChunkName
if (isComponentChunkSet) {
chunks = [...pluginData.components.values()].map(
c => c.componentChunkName
)
} else {
chunks = Array.from(pluginData.pages.values()).map(
page => page.componentChunkName
)
}
chunks.push(`pages-manifest`, `app`)
const files = [].concat(...chunks.map(chunk => pluginData.manifest[chunk]))
const cachingHeaders = {}
files.forEach(file => {
if (typeof file === `string`) {
cachingHeaders[`/` + file] = [IMMUTABLE_CACHING_HEADER]
}
})
return defaultMerge(headers, cachingHeaders, CACHING_HEADERS)
}
const applyTransfromHeaders =
({ transformHeaders }) =>
headers =>
_.mapValues(headers, transformHeaders)
const sendHeadersViaIPC = async headers => {
/**
* Emit Headers via IPC
*/
let lastMessage
Object.entries(headers).forEach(([k, val]) => {
lastMessage = emitHeaders({
url: k,
headers: val,
})
})
await lastMessage
}
const writeHeadersFile = async (publicFolder, contents) =>
new Promise((resolve, reject) => {
const contentsStr = JSON.stringify(contents)
const writeStream = createWriteStream(publicFolder(HEADERS_FILENAME))
const chunkSize = 10000
const numChunks = Math.ceil(contentsStr.length / chunkSize)
for (let i = 0; i < numChunks; i++) {
writeStream.write(
contentsStr.slice(
i * chunkSize,
Math.min((i + 1) * chunkSize, contentsStr.length)
)
)
}
writeStream.end()
writeStream.on(`finish`, () => {
resolve()
})
writeStream.on(`error`, reject)
})
const saveHeaders =
({ publicFolder }) =>
contents =>
Promise.all([
sendHeadersViaIPC(contents),
writeHeadersFile(publicFolder, contents),
])
export default function buildHeadersProgram(pluginData, pluginOptions) {
return _.flow(
mapUserLinkHeaders(pluginData),
applySecurityHeaders(pluginOptions),
applyCachingHeaders(pluginData, pluginOptions),
mapUserLinkAllPageHeaders(pluginData, pluginOptions),
applyLinkHeaders(pluginData, pluginOptions),
applyTransfromHeaders(pluginOptions),
saveHeaders(pluginData)
)(pluginOptions.headers)
}