-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
gatsby-node.js
250 lines (215 loc) · 6.99 KB
/
gatsby-node.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
import fs from "fs"
import path from "path"
import sharp from "./safe-sharp"
import { createContentDigest, cpuCoreCount, slash } from "gatsby-core-utils"
import { defaultIcons, doesIconExist, addDigestToPath } from "./common"
sharp.simd(true)
// Handle Sharp's concurrency based on the Gatsby CPU count
// See: http://sharp.pixelplumbing.com/en/stable/api-utility/#concurrency
// See: https://www.gatsbyjs.org/docs/multi-core-builds/
sharp.concurrency(cpuCoreCount())
async function generateIcon(icon, srcIcon) {
const imgPath = path.join(`public`, icon.src)
// console.log(`generating icon: `, icon.src)
// if (fs.existsSync(imgPath)) {
// console.log(`icon already Exists, not regenerating`)
// return true
// }
const size = parseInt(icon.sizes.substring(0, icon.sizes.lastIndexOf(`x`)))
// For vector graphics, instruct sharp to use a pixel density
// suitable for the resolution we're rasterizing to.
// For pixel graphics sources this has no effect.
// Sharp accept density from 1 to 2400
const density = Math.min(2400, Math.max(1, size))
return sharp(srcIcon, { density })
.resize({
width: size,
height: size,
fit: `contain`,
background: { r: 255, g: 255, b: 255, alpha: 0 },
})
.toFile(imgPath)
}
async function checkCache(cache, icon, srcIcon, srcIconDigest, callback) {
const cacheKey = createContentDigest(`${icon.src}${srcIcon}${srcIconDigest}`)
let created = cache.get(cacheKey, srcIcon)
if (!created) {
cache.set(cacheKey, true)
try {
// console.log(`creating icon`, icon.src, srcIcon)
await callback(icon, srcIcon)
} catch (e) {
cache.set(cacheKey, false)
throw e
}
} else {
// console.log(`icon exists`, icon.src, srcIcon)
}
}
exports.onPostBootstrap = async (
{ reporter, parentSpan, basePath },
{ localize, ...manifest }
) => {
const activity = reporter.activityTimer(`Build manifest and related icons`, {
parentSpan,
})
activity.start()
let cache = new Map()
await makeManifest({ cache, reporter, pluginOptions: manifest, basePath })
if (Array.isArray(localize)) {
const locales = [...localize]
await Promise.all(
locales.map(locale => {
let cacheModeOverride = {}
/* localization requires unique filenames for output files if a different src Icon is defined.
otherwise one language would override anothers icons in automatic mode.
*/
if (locale.hasOwnProperty(`icon`) && !locale.hasOwnProperty(`icons`)) {
// console.debug(`OVERRIDING CACHE BUSTING`, locale)
cacheModeOverride = { cache_busting_mode: `name` }
}
return makeManifest({
cache,
reporter,
pluginOptions: {
...manifest,
...locale,
...cacheModeOverride,
},
shouldLocalize: true,
basePath,
})
})
)
}
activity.end()
}
/**
* The complete Triforce, or one or more components of the Triforce.
* @typedef {Object} makeManifestArgs
* @property {Object} cache - from gatsby-node api
* @property {Object} reporter - from gatsby-node api
* @property {Object} pluginOptions - from gatsby-node api/gatsby config
* @property {boolean?} shouldLocalize
* @property {string?} basePath - string of base path frpvided by gatsby node
*/
/**
* Build manifest
* @param {makeManifestArgs}
*/
const makeManifest = async ({
cache,
reporter,
pluginOptions,
shouldLocalize = false,
basePath = ``,
}) => {
const { icon, ...manifest } = pluginOptions
const suffix =
shouldLocalize && pluginOptions.lang ? `_${pluginOptions.lang}` : ``
// Delete options we won't pass to the manifest.webmanifest.
delete manifest.plugins
delete manifest.legacy
delete manifest.theme_color_in_head
delete manifest.cache_busting_mode
delete manifest.crossOrigin
delete manifest.icon_options
delete manifest.include_favicon
// If icons are not manually defined, use the default icon set.
if (!manifest.icons) {
manifest.icons = [...defaultIcons]
}
// Specify extra options for each icon (if requested).
if (pluginOptions.icon_options) {
manifest.icons = manifest.icons.map(icon => {
return {
...pluginOptions.icon_options,
...icon,
}
})
}
// Determine destination path for icons.
let paths = {}
manifest.icons.forEach(icon => {
const iconPath = path.join(`public`, path.dirname(icon.src))
if (!paths[iconPath]) {
const exists = fs.existsSync(iconPath)
//create destination directory if it doesn't exist
if (!exists) {
fs.mkdirSync(iconPath)
}
paths[iconPath] = true
}
})
// Only auto-generate icons if a src icon is defined.
if (icon !== undefined) {
// Check if the icon exists
if (!doesIconExist(icon)) {
throw new Error(
`icon (${icon}) does not exist as defined in gatsby-config.js. Make sure the file exists relative to the root of the site.`
)
}
const sharpIcon = sharp(icon)
const metadata = await sharpIcon.metadata()
if (metadata.width !== metadata.height) {
reporter.warn(
`The icon(${icon}) you provided to 'gatsby-plugin-manifest' is not square.\n` +
`The icons we generate will be square and for the best results we recommend you provide a square icon.\n`
)
}
//add cache busting
const cacheMode =
typeof pluginOptions.cache_busting_mode !== `undefined`
? pluginOptions.cache_busting_mode
: `query`
const iconDigest = createContentDigest(fs.readFileSync(icon))
//if cacheBusting is being done via url query icons must be generated before cache busting runs
if (cacheMode === `query`) {
await Promise.all(
manifest.icons.map(dstIcon =>
checkCache(cache, dstIcon, icon, iconDigest, generateIcon)
)
)
}
if (cacheMode !== `none`) {
manifest.icons = manifest.icons.map(icon => {
let newIcon = { ...icon }
newIcon.src = addDigestToPath(icon.src, iconDigest, cacheMode)
return newIcon
})
}
//if file names are being modified by cacheBusting icons must be generated after cache busting runs
if (cacheMode !== `query`) {
await Promise.all(
manifest.icons.map(dstIcon =>
checkCache(cache, dstIcon, icon, iconDigest, generateIcon)
)
)
}
}
//Fix #18497 by prefixing paths
manifest.icons = manifest.icons.map(icon => {
return {
...icon,
src: slash(path.join(basePath, icon.src)),
}
})
if (manifest.start_url) {
manifest.start_url = path.posix.join(basePath, manifest.start_url)
}
//Write manifest
fs.writeFileSync(
path.join(`public`, `manifest${suffix}.webmanifest`),
JSON.stringify(manifest)
)
}
exports.onCreateWebpackConfig = ({ actions, plugins }, pluginOptions) => {
actions.setWebpackConfig({
plugins: [
plugins.define({
__MANIFEST_PLUGIN_HAS_LOCALISATION__:
pluginOptions.localize && pluginOptions.localize.length,
}),
],
})
}