refactor: implement Chrome Extension APIs without the remote module (#16686)

* refactor: implement Chrome Extension APIs without the remote module

* remove unused potentiallyRemoteRequire
This commit is contained in:
Milan Burda 2019-02-10 19:38:14 +01:00 committed by Shelley Vohr
parent 1898f91620
commit 7a3d220347
3 changed files with 79 additions and 77 deletions

View file

@ -10,6 +10,7 @@ const { Buffer } = require('buffer')
const fs = require('fs')
const path = require('path')
const url = require('url')
const util = require('util')
// Mapping between extensionId(hostname) and manifest.
const manifestMap = {} // extensionId => manifest
@ -226,6 +227,65 @@ ipcMainUtils.handleSync('CHROME_GET_MESSAGES', function (event, extensionId) {
return fs.readFileSync(messagesPath)
})
const validStorageTypes = new Set(['sync', 'local'])
const getChromeStoragePath = (storageType, extensionId) => {
if (!validStorageTypes.has(storageType)) {
throw new Error(`Invalid storageType: ${storageType}`)
}
if (!manifestMap[extensionId]) {
throw new Error(`Invalid extensionId: ${extensionId}`)
}
return path.join(app.getPath('userData'), `/Chrome Storage/${extensionId}-${storageType}.json`)
}
const mkdirp = util.promisify((dir, callback) => {
fs.mkdir(dir, (error) => {
if (error && error.code === 'ENOENT') {
mkdirp(path.dirname(dir), (error) => {
if (!error) {
mkdirp(dir, callback)
}
})
} else if (error && error.code === 'EEXIST') {
callback(null)
} else {
callback(error)
}
})
})
const readFile = util.promisify(fs.readFile)
const writeFile = util.promisify(fs.writeFile)
ipcMainUtils.handle('CHROME_STORAGE_READ', async function (event, storageType, extensionId) {
const filePath = getChromeStoragePath(storageType, extensionId)
try {
return await readFile(filePath, 'utf8')
} catch (error) {
if (error.code === 'ENOENT') {
return null
} else {
throw error
}
}
})
ipcMainUtils.handle('CHROME_STORAGE_WRITE', async function (event, storageType, extensionId, data) {
const filePath = getChromeStoragePath(storageType, extensionId)
try {
await mkdirp(path.dirname(filePath))
} catch (error) {
// we just ignore the errors of mkdir or mkdirp
}
return writeFile(filePath, data, 'utf8')
})
const isChromeExtension = function (pageURL) {
const { protocol } = url.parse(pageURL)
return protocol === 'chrome-extension:'