Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: webpack 5.x #938

Merged
merged 8 commits into from Oct 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 20 additions & 4 deletions Makefile
Expand Up @@ -3,7 +3,7 @@
#
# https://www.npmjs.com/package/fakefile
#
# Please do not edit this file directly, but propose changed upstream instead:
# Please do not edit this file directly, but propose changed upstream instead:
# https://github.com/kvz/fakefile/blob/master/Makefile
#
# This Makefile offers convience shortcuts into any Node.js project that utilizes npm scripts.
Expand All @@ -28,10 +28,26 @@
# OSX users will have to install bash-completion
# (http://davidalger.com/development/bash-completion-on-os-x-with-brew/)

ifeq ($(shell test -e ./yarn.lock && echo -n yes),yes)
RUNNER=yarn
INSTALLER=yarn install
else
RUNNER=npm run
INSTALLER=npm install
endif

define npm_script_targets
TARGETS := $(shell node -e 'for (var k in require("./package.json").scripts) {console.log(k.replace(/:/g, "-"));}')
TARGETS := $(shell \
node -e 'for (var k in require("./package.json").scripts) {console.log(k.replace(/:/g, "-"));}'
| grep -v -E "^install$$"
)
$$(TARGETS):
npm run $(subst -,:,$(MAKECMDGOALS))
$(RUNNER) $(shell \
node -e 'for (var k in require("./package.json").scripts) {console.log(k.replace(/:/g, "-"), k);}'
| grep -E "^$(MAKECMDGOALS)\s"
| head -n1
| awk '{print $$2}'
)

.PHONY: $$(TARGETS)
endef
Expand All @@ -40,4 +56,4 @@ $(eval $(call npm_script_targets))

# These npm run scripts are available, without needing to be mentioned in `package.json`
install:
npm install
$(INSTALLER)
4 changes: 2 additions & 2 deletions add-on/src/contentScripts/ipfs-proxy/page.js
Expand Up @@ -18,8 +18,8 @@ function createEnableCommand (proxyClient) {
// Additional client-side features
if (opts && opts.experiments) {
if (opts.experiments.ipfsx) {
// Experiment: wrap API with https://github.com/alanshaw/ipfsx
return freeze(require('ipfsx')(proxyClient))
// Old experiment where we wrapped API with https://github.com/alanshaw/ipfsx
throw new Error('ipfsx no longer supported, use modern JS instead: https://blog.ipfs.io/2020-02-01-async-await-refactor/')
}
}
return freeze(proxyClient)
Expand Down
77 changes: 39 additions & 38 deletions add-on/src/lib/ipfs-companion.js
Expand Up @@ -16,7 +16,7 @@ const { createIpfsPathValidator, sameGateway } = require('./ipfs-path')
const createDnslinkResolver = require('./dnslink')
const { createRequestModifier } = require('./ipfs-request')
const { initIpfsClient, destroyIpfsClient } = require('./ipfs-client')
const createIpfsImportHandler = require('./ipfs-import')
const { createIpfsImportHandler, formatImportDirectory } = require('./ipfs-import')
const createNotifier = require('./notifier')
const createCopier = require('./copier')
const createInspector = require('./inspector')
Expand All @@ -42,7 +42,7 @@ module.exports = async function init () {
var contextMenus
var apiStatusUpdateInterval
var ipfsProxy
var ipfsProxyContentScript
// TODO: window.ipfs var ipfsProxyContentScript
var ipfsImportHandler
const idleInSecs = 5 * 60
const browserActionPortName = 'browser-action-port'
Expand Down Expand Up @@ -82,7 +82,7 @@ module.exports = async function init () {
})
modifyRequest = createRequestModifier(getState, dnslinkResolver, ipfsPathValidator, runtime)
ipfsProxy = createIpfsProxy(getIpfs, getState)
ipfsProxyContentScript = await registerIpfsProxyContentScript()
// TODO(window.ipfs) ipfsProxyContentScript = await registerIpfsProxyContentScript()
log('register all listeners')
registerListeners()
await registerSubdomainProxy(getState, runtime, notify)
Expand Down Expand Up @@ -139,6 +139,7 @@ module.exports = async function init () {
// The key difference between tabs.executeScript and contentScripts API
// is the latter provides guarantee to execute before anything else.
// https://github.com/ipfs-shipyard/ipfs-companion/issues/451#issuecomment-382669093
/* TODO(window.ipfs)
async function registerIpfsProxyContentScript (previousHandle) {
previousHandle = previousHandle || ipfsProxyContentScript
if (previousHandle) {
Expand Down Expand Up @@ -168,6 +169,7 @@ module.exports = async function init () {
})
return newHandle
}
*/

// HTTP Request Hooks
// ===================================================================
Expand Down Expand Up @@ -301,7 +303,6 @@ module.exports = async function init () {

async function onAddFromContext (context, contextType, options) {
const {
formatImportDirectory,
copyImportResultsToFiles,
copyShareLink,
preloadFilesAtPublicGateway,
Expand Down Expand Up @@ -451,15 +452,12 @@ module.exports = async function init () {
// update peer count
const oldPeerCount = state.peerCount
state.peerCount = await getSwarmPeerCount()
updatePeerCountDependentStates(oldPeerCount, state.peerCount)
// trigger pending updates
await sendStatusUpdateToBrowserAction()
}

function updatePeerCountDependentStates (oldPeerCount, newPeerCount) {
updateAutomaticModeRedirectState(oldPeerCount, newPeerCount)
updateBrowserActionBadge()
contextMenus.update()
await Promise.all([
updateAutomaticModeRedirectState(oldPeerCount, state.peerCount),
updateBrowserActionBadge(),
contextMenus.update(),
sendStatusUpdateToBrowserAction()
])
}

async function getSwarmPeerCount () {
Expand Down Expand Up @@ -577,17 +575,15 @@ module.exports = async function init () {
// OPTIONS
// ===================================================================

function updateAutomaticModeRedirectState (oldPeerCount, newPeerCount) {
async function updateAutomaticModeRedirectState (oldPeerCount, newPeerCount) {
// enable/disable gw redirect based on API going online or offline
// newPeerCount === -1 currently implies node is offline.
// TODO: use `node.isOnline()` if available (js-ipfs)
if (state.automaticMode && state.localGwAvailable) {
if (oldPeerCount === offlinePeerCount && newPeerCount > offlinePeerCount && !state.redirect) {
browser.storage.local.set({ useCustomGateway: true })
.then(() => notify('notify_apiOnlineTitle', 'notify_apiOnlineAutomaticModeMsg'))
await browser.storage.local.set({ useCustomGateway: true })
await notify('notify_apiOnlineTitle', 'notify_apiOnlineAutomaticModeMsg')
} else if (newPeerCount === offlinePeerCount && state.redirect) {
browser.storage.local.set({ useCustomGateway: false })
.then(() => notify('notify_apiOfflineTitle', 'notify_apiOfflineAutomaticModeMsg'))
await browser.storage.local.set({ useCustomGateway: false })
await notify('notify_apiOfflineTitle', 'notify_apiOfflineAutomaticModeMsg')
}
}
}
Expand All @@ -606,7 +602,7 @@ module.exports = async function init () {
switch (key) {
case 'active':
state[key] = change.newValue
ipfsProxyContentScript = await registerIpfsProxyContentScript()
// TODO(window.ipfs) ipfsProxyContentScript = await registerIpfsProxyContentScript()
await registerSubdomainProxy(getState, runtime)
shouldRestartIpfsClient = true
shouldStopIpfsClient = !state.active
Expand Down Expand Up @@ -673,11 +669,12 @@ module.exports = async function init () {
// Finally, update proxy settings based on the state
await registerSubdomainProxy(getState, runtime)
break
/* TODO(window.ipfs)
case 'ipfsProxy':
state[key] = change.newValue
// This is window.ipfs proxy, requires update of the content script:
ipfsProxyContentScript = await registerIpfsProxyContentScript()
break
break */
case 'dnslinkPolicy':
state.dnslinkPolicy = String(change.newValue) === 'false' ? false : change.newValue
if (state.dnslinkPolicy === 'best-effort' && !state.detectIpfsPathHeader) {
Expand Down Expand Up @@ -760,29 +757,33 @@ module.exports = async function init () {
return ipfsImportHandler
},

destroy () {
const destroyTasks = []
clearInterval(apiStatusUpdateInterval)
apiStatusUpdateInterval = null
ipfs = null
state = null
dnslinkResolver = null
modifyRequest = null
ipfsPathValidator = null
ipfsImportHandler = null
notify = null
copier = null
contextMenus = null
async destroy () {
if (state) {
state.active = false
state.peerCount = -1 // api down
}

if (apiStatusUpdateInterval) {
clearInterval(apiStatusUpdateInterval)
apiStatusUpdateInterval = null
}

/* TODO(window.ipfs)
if (ipfsProxyContentScript) {
ipfsProxyContentScript.unregister()
ipfsProxyContentScript = null
}
*/

if (ipfsProxy) {
destroyTasks.push(ipfsProxy.destroy())
await ipfsProxy.destroy()
ipfsProxy = null
}
destroyTasks.push(destroyIpfsClient())
return Promise.all(destroyTasks)

if (ipfs) {
await destroyIpfsClient()
ipfs = null
}
}
}

Expand Down
26 changes: 12 additions & 14 deletions add-on/src/lib/ipfs-import.js
Expand Up @@ -9,21 +9,9 @@ const browser = require('webextension-polyfill')

const { redirectOptOutHint } = require('./ipfs-request')

function createIpfsImportHandler (getState, getIpfs, ipfsPathValidator, runtime, copier) {
module.exports.createIpfsImportHandler = (getState, getIpfs, ipfsPathValidator, runtime, copier) => {
const { resolveToPublicUrl } = ipfsPathValidator
const ipfsImportHandler = {
formatImportDirectory (path) {
path = path.replace(/\/$|$/, '/')
path = path.replace(/(\/)\/+/g, '$1')

// needed to handle date symbols in the import directory
const now = new Date()
const dateSymbols = [/%Y/g, /%M/g, /%D/g, /%h/g, /%m/g, /%s/g]
const symbolReplacements = [now.getFullYear(), now.getMonth() + 1, now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds()].map(n => String(n).padStart(2, '0'))
dateSymbols.forEach((symbol, i) => { path = path.replace(symbol, symbolReplacements[i]) })
return path
},

getIpfsPathAndNativeAddress (cid) {
const state = getState()
const path = `/ipfs/${cid}`
Expand Down Expand Up @@ -99,4 +87,14 @@ function createIpfsImportHandler (getState, getIpfs, ipfsPathValidator, runtime,
return ipfsImportHandler
}

module.exports = createIpfsImportHandler
module.exports.formatImportDirectory = (path) => {
path = path.replace(/\/$|$/, '/')
path = path.replace(/(\/)\/+/g, '$1')

// needed to handle date symbols in the import directory
const now = new Date()
const dateSymbols = [/%Y/g, /%M/g, /%D/g, /%h/g, /%m/g, /%s/g]
const symbolReplacements = [now.getFullYear(), now.getMonth() + 1, now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds()].map(n => String(n).padStart(2, '0'))
dateSymbols.forEach((symbol, i) => { path = path.replace(symbol, symbolReplacements[i]) })
return path
}
26 changes: 17 additions & 9 deletions add-on/src/lib/notifier.js
@@ -1,25 +1,33 @@
'use strict'

const browser = require('webextension-polyfill')
const debug = require('debug')
const log = debug('ipfs-companion:notifier')
log.error = debug('ipfs-companion:notifier:error')

function createNotifier (getState) {
return (titleKey, messageKey, messageParam) => {
const { getMessage } = browser.i18n
return async (titleKey, messageKey, messageParam) => {
const title = browser.i18n.getMessage(titleKey) || titleKey
let message
if (messageKey.startsWith('notify_')) {
message = messageParam ? browser.i18n.getMessage(messageKey, messageParam) : browser.i18n.getMessage(messageKey)
message = messageParam ? getMessage(messageKey, messageParam) : getMessage(messageKey)
} else {
message = messageKey
}
log(`${title}: ${message}`)
if (getState().displayNotifications && browser && browser.notifications.create) {
browser.notifications.create({
type: 'basic',
iconUrl: browser.extension.getURL('icons/ipfs-logo-on.svg'),
title: title,
message: message
}).catch(err => console.warn(`[ipfs-companion] Browser notification failed: ${err.message}`))
try {
return await browser.notifications.create({
type: 'basic',
iconUrl: browser.extension.getURL('icons/ipfs-logo-on.svg'),
title: title,
message: message
})
} catch (err) {
log.error('failed to create a notification', err)
}
}
console.info(`[ipfs-companion] ${title}: ${message}`)
}
}

Expand Down
6 changes: 4 additions & 2 deletions add-on/src/options/forms/experiments-form.js
Expand Up @@ -106,10 +106,12 @@ function experimentsForm ({
Disabled until move to JavaScript API with async await and async iterables
<!-- TODO: https://github.com/ipfs-shipyard/ipfs-companion/pull/777
${browser.i18n.getMessage('option_ipfsProxy_description')}
<p>${ipfsProxy ? html`
<p>${ipfsProxy
? html`
<a class="link underline hover-aqua" href="${browser.extension.getURL('dist/pages/proxy-acl/index.html')}" target="_blank">
${browser.i18n.getMessage('option_ipfsProxy_link_manage_permissions')}
</a>` : html`<del>${browser.i18n.getMessage('option_ipfsProxy_link_manage_permissions')}</del>`}
</a>`
: html`<del>${browser.i18n.getMessage('option_ipfsProxy_link_manage_permissions')}</del>`}
</p>
-->
<p><a class="link underline hover-aqua" href="https://docs.ipfs.io/how-to/companion-window-ipfs/" target="_blank">
Expand Down
33 changes: 16 additions & 17 deletions add-on/src/options/forms/gateways-form.js
Expand Up @@ -80,8 +80,8 @@ function gatewaysForm ({
onchange=${onPublicSubdomainGatewayUrlChange}
value=${publicSubdomainGatewayUrl} />
</div>
${supportRedirectToCustomGateway && allowChangeOfCustomGateway ? html`
<div class="flex-row-ns pb0-ns">
${supportRedirectToCustomGateway && allowChangeOfCustomGateway
? html`<div class="flex-row-ns pb0-ns">
<label for="customGatewayUrl">
<dl>
<dt>${browser.i18n.getMessage('option_customGatewayUrl_title')}</dt>
Expand All @@ -102,22 +102,21 @@ function gatewaysForm ({
onchange=${onCustomGatewayUrlChange}
${allowChangeOfCustomGateway ? '' : 'disabled'}
value=${customGatewayUrl} />

</div>
` : null}
${supportRedirectToCustomGateway ? html`
<div class="flex-row-ns pb0-ns">
</div>`
: null}
${supportRedirectToCustomGateway
? html`<div class="flex-row-ns pb0-ns">
<label for="useCustomGateway">
<dl>
<dt>${browser.i18n.getMessage('option_useCustomGateway_title')}</dt>
<dd>${browser.i18n.getMessage('option_useCustomGateway_description')}</dd>
</dl>
</label>
<div class="self-center-ns">${switchToggle({ id: 'useCustomGateway', checked: useCustomGateway, onchange: onUseCustomGatewayChange })}</div>
</div>
` : null}
${supportRedirectToCustomGateway ? html`
<div class="flex-row-ns pb0-ns">
</div>`
: null}
${supportRedirectToCustomGateway
? html`<div class="flex-row-ns pb0-ns">
<label for="useSubdomains">
<dl>
<dt>${browser.i18n.getMessage('option_useSubdomains_title')}</dt>
Expand All @@ -130,10 +129,10 @@ function gatewaysForm ({
</dl>
</label>
<div class="self-center-ns">${switchToggle({ id: 'useSubdomains', checked: useSubdomains, onchange: onUseSubdomainProxyChange })}</div>
</div>
` : null}
${supportRedirectToCustomGateway ? html`
<div class="flex-row-ns pb0-ns">
</div>`
: null}
${supportRedirectToCustomGateway
? html`<div class="flex-row-ns pb0-ns">
<label for="disabledOn">
<dl>
<dt>${browser.i18n.getMessage('option_disabledOn_title')}</dt>
Expand Down Expand Up @@ -162,8 +161,8 @@ function gatewaysForm ({
onchange=${onEnabledOnChange}
rows="${Math.min(enabledOn.length + 1, 10)}"
>${hostArrayToText(enabledOn)}</textarea>
</div>
` : null}
</div>`
: null}

</fieldset>
</form>
Expand Down