forked from CosmosContracts/old-website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
60 lines (49 loc) · 2.57 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
const fs = require('fs');
const util = require('util');
const pMap = require('p-map');
const globby = require('globby');
const readFileAsync = util.promisify(fs.readFile);
const writeFileAsync = util.promisify(fs.writeFile);
const TRANSFORM_CONCURRENCY = 10;
const relativizeManifest = async () => {
// See https://github.com/moxystudio/gatsby-plugin-ipfs/issues/24
// replace prefix paths for manifest file
const path = 'public/manifest.webmanifest';
const buffer = await readFileAsync(path);
let contents = buffer.toString();
if (!contents.includes('__GATSBY_IPFS_PATH_PREFIX__')) {
return;
}
contents = contents
.replace('"/__GATSBY_IPFS_PATH_PREFIX__"', '"/"')
.replace(/\/__GATSBY_IPFS_PATH_PREFIX__\//g, '/');
await writeFileAsync(path, contents);
};
const patchInvalidJS = async () => {
// There appears to be a bug in gatsby-plugin-ipfs:
// - https://github.com/moxystudio/gatsby-plugin-ipfs/blob/bc2df21052c14c3945187ce4f4a1eb94cd196b96/src/gatsby-node.js#L46
// - There, "/__GATSBY_IPFS_PATH_PREFIX__/" strings are replaced with __GATSBY_IPFS_PATH_PREFIX__ + "/"
// - But if __GATSBY_IPFS_PATH_PREFIX__ is itself within a string, the (+ "/") would lead to quotation imbalance and result in invalid JS.
// - In particular, in one of the generated JS files:
// - Original: throw new Error("We couldn't load \"/__GATSBY_IPFS_PATH_PREFIX__/page-data/sq/d/"+t+'.json"')
// - Final: throw new Error("We couldn't load \ __GATSBY_IPFS_PATH_PREFIX__/page-data/sq/d/"+t+'.json"') <- missing double quote before '+' to be valid JS
// If there's an escaped double quote before /__GATSBY_IPFS_PATH_PREFIX__, then it's part of a string, and after gatsby-plugin-ipfs processing,
// we'll be left with '\ __GATSBY_IPFS_PATH_PREFIX__ + ", so we can patch this particular case:
const paths = await globby(['public/**/*.js']);
await pMap(paths, async (path) => {
const buffer = await readFileAsync(path);
let contents = buffer.toString();
// Skip if there's nothing to do
if (!contents.includes('\\ __GATSBY_IPFS_PATH_PREFIX__ + "')) {
return;
}
// Add closing double quote to make the JS valid again
contents = contents
.replace('\\ __GATSBY_IPFS_PATH_PREFIX__ + "', '\\ __GATSBY_IPFS_PATH_PREFIX__" + "');
await writeFileAsync(path, contents);
}, { concurrency: TRANSFORM_CONCURRENCY });
};
exports.onPostBuild = async ({ reporter }) => {
await relativizeManifest();
await patchInvalidJS();
};