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

Browserify src #311

Merged
merged 15 commits into from
Nov 20, 2017
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
vendor
node_modules
package-lock.json
firefox
cache
build
npm-debug.log
crowdin.yml
.*~
add-on/dist
6 changes: 3 additions & 3 deletions add-on/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
],

"background": {
"page": "src/background/background.html"
"page": "dist/background/background.html"
},

"browser_action": {
Expand All @@ -46,12 +46,12 @@
"128": "icons/png/ipfs-logo-off_128.png"
},
"default_title": "__MSG_browserAction_title__",
"default_popup": "src/popup/browser-action.html"
"default_popup": "dist/popup/browser-action.html"
},

"options_ui": {
"browser_style": false,
"page": "src/options/options.html"
"page": "dist/options/options.html"
},

"web_accessible_resources": [
Expand Down
7 changes: 1 addition & 6 deletions add-on/src/background/background.html
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
<!DOCTYPE html>
<meta charset="utf-8">
<script src="../lib/npm/is-ipfs.min.js"></script>
<script src="../lib/npm/ipfs-api.min.js"></script>
<script src="../lib/npm/lru.js"></script>
<script src="../lib/npm/browser-polyfill.min.js"></script>
<script src="../lib/option-defaults.js"></script>
<script src="../lib/ipfs-companion.js"></script>
<script src="../common.js"></script>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚲🏠 ipfs-companion-bundle.js (or just bundle.js) may be a better name (common.js is too vague, we've just deprecated it in master branch)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about ipfs-companion-common.js? It's not the full bundle, just the dependencies that are common to more than one of our bundles.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good!

ps. This PR is our priority, as it gives us the biggest bang for the buck (potentially closes #306) and is required by other PRs. Let me know when you feel it is ready to merge, I will do my best to find time to review it before anything else 👍

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixing the tests is the only thing left to do for this...

<script src="background.js"></script>
3 changes: 2 additions & 1 deletion add-on/src/background/background.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict'
/* eslint-env browser, webextensions */
/* global init */

const init = require('../lib/ipfs-companion')

// init add-on after all libs are loaded
document.addEventListener('DOMContentLoaded', init)
26 changes: 15 additions & 11 deletions add-on/src/lib/data-i18n.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
'use strict'
/* eslint-env browser, webextensions */

const browser = require('webextension-polyfill')

function safeTranslation (key) {
const translation = browser.i18n.getMessage(key)
return translation || '[i18n: ' + key + ']'
}

// Search for items with data-i18n attribute and replace them with values from current locale
const items = document.querySelectorAll('[data-i18n]')
for (let item of items) {
const key = item.getAttribute('data-i18n')
if (key) {
const translation = safeTranslation(key)
if (typeof item.value !== 'undefined' && item.value === 'i18n') {
// things like inputs can trigger translation with value equal "i18n"
item.value = translation
} else {
item.innerText = translation
module.exports = function () {
// Search for items with data-i18n attribute and replace them with values from current locale
const items = document.querySelectorAll('[data-i18n]')
for (let item of items) {
const key = item.getAttribute('data-i18n')
if (key) {
const translation = safeTranslation(key)
if (typeof item.value !== 'undefined' && item.value === 'i18n') {
// things like inputs can trigger translation with value equal "i18n"
item.value = translation
} else {
item.innerText = translation
}
}
}
}
54 changes: 33 additions & 21 deletions add-on/src/lib/ipfs-companion.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
'use strict'
/* eslint-env browser, webextensions */
/* global optionDefaults */

const browser = require('webextension-polyfill')
const optionDefaults = require('./option-defaults')
const { LRUMap } = require('lru_map')
const IsIpfs = require('is-ipfs')
const IpfsApi = require('ipfs-api')

// INIT
// ===================================================================
var ipfs // ipfs-api instance
var state = {} // avoid redundant API reads by utilizing local cache of various states
var state = window.state = {} // avoid redundant API reads by utilizing local cache of various states

// init happens on addon load in background/background.js
// eslint-disable-next-line no-unused-vars
async function init () {
module.exports = async function init () {
try {
const options = await browser.storage.local.get(optionDefaults)
ipfs = initIpfsApi(options.ipfsApiUrl)
ipfs = window.ipfs = initIpfsApi(options.ipfsApiUrl)
initStates(options)
registerListeners()
setApiStatusUpdateInterval(options.ipfsApiPollMs)
Expand All @@ -25,7 +29,7 @@ async function init () {

function initIpfsApi (ipfsApiUrl) {
const url = new URL(ipfsApiUrl)
return window.IpfsApi({host: url.hostname, port: url.port, procotol: url.protocol})
return IpfsApi({host: url.hostname, port: url.port, procotol: url.protocol})
}

function initStates (options) {
Expand All @@ -44,7 +48,7 @@ function initStates (options) {
state.preloadAtPublicGateway = options.preloadAtPublicGateway
state.catchUnhandledProtocols = options.catchUnhandledProtocols
state.displayNotifications = options.displayNotifications
state.dnslinkCache = /* global LRUMap */ new LRUMap(1000)
state.dnslinkCache = new LRUMap(1000)
}

function registerListeners () {
Expand All @@ -65,11 +69,11 @@ function publicIpfsOrIpnsResource (url) {
// first, exclude gateway and api, otherwise we have infinite loop
if (!url.startsWith(state.gwURLString) && !url.startsWith(state.apiURLString)) {
// /ipfs/ is easy to validate, we just check if CID is correct and return if true
if (window.IsIpfs.ipfsUrl(url)) {
if (IsIpfs.ipfsUrl(url)) {
return true
}
// /ipns/ requires multiple stages/branches, as it can be FQDN with dnslink or CID
if (window.IsIpfs.ipnsUrl(url) && validIpnsPath(new URL(url).pathname)) {
if (IsIpfs.ipnsUrl(url) && validIpnsPath(new URL(url).pathname)) {
return true
}
}
Expand All @@ -78,12 +82,12 @@ function publicIpfsOrIpnsResource (url) {
}

function validIpnsPath (path) {
if (window.IsIpfs.ipnsPath(path)) {
if (IsIpfs.ipnsPath(path)) {
// we may have false-positives here, so we do additional checks below
const ipnsRoot = path.match(/^\/ipns\/([^/]+)/)[1]
// console.log('==> IPNS root', ipnsRoot)
// first check if root is a regular CID
if (window.IsIpfs.cid(ipnsRoot)) {
if (IsIpfs.cid(ipnsRoot)) {
// console.log('==> IPNS is a valid CID', ipnsRoot)
return true
}
Expand All @@ -96,7 +100,7 @@ function validIpnsPath (path) {
}

function validIpfsOrIpnsPath (path) {
return window.IsIpfs.ipfsPath(path) || validIpnsPath(path)
return IsIpfs.ipfsPath(path) || validIpnsPath(path)
}

function redirectToCustomGateway (requestUrl) {
Expand Down Expand Up @@ -187,7 +191,7 @@ function normalizedWebPlusRequest (request) {
path = path.replace(/^\/web\+dweb:\//i, '/') // web+dweb:/ipfs/Qm → /ipfs/Qm
path = path.replace(/^\/web\+ipfs:\/\//i, '/ipfs/') // web+ipfs://Qm → /ipfs/Qm
path = path.replace(/^\/web\+ipns:\/\//i, '/ipns/') // web+ipns://Qm → /ipns/Qm
if (oldPath !== path && window.IsIpfs.path(path)) {
if (oldPath !== path && IsIpfs.path(path)) {
return { redirectUrl: urlAtPublicGw(path) }
}
return null
Expand All @@ -207,14 +211,14 @@ function unhandledIpfsPath (requestUrl) {
if (unhandled && unhandled.length > 1) {
const unhandledProtocol = decodeURIComponent(unhandled[1])
const unhandledPath = `/${decodeURIComponent(unhandled[2])}`
return window.IsIpfs.path(unhandledPath) ? unhandledPath : `/${unhandledProtocol}${unhandledPath}`
return IsIpfs.path(unhandledPath) ? unhandledPath : `/${unhandledProtocol}${unhandledPath}`
}
return null
}

function normalizedUnhandledIpfsProtocol (request) {
const path = unhandledIpfsPath(request.url)
if (window.IsIpfs.path(path)) {
if (IsIpfs.path(path)) {
// replace search query with fake request to the public gateway
// (will be redirected later, if needed)
return { redirectUrl: urlAtPublicGw(path) }
Expand All @@ -234,7 +238,7 @@ function isDnslookupSafeForURL (requestUrl) {
// skip URLs that could produce infinite recursion or weird loops
return isDnslookupPossible() &&
requestUrl.startsWith('http') &&
!window.IsIpfs.url(requestUrl) &&
!IsIpfs.url(requestUrl) &&
!requestUrl.startsWith(state.apiURLString) &&
!requestUrl.startsWith(state.gwURLString)
}
Expand Down Expand Up @@ -295,7 +299,7 @@ function readDnslinkFromTxtRecord (fqdn) {
if (xhr.status === 200) {
const dnslink = JSON.parse(xhr.responseText).Path
// console.log('readDnslinkFromTxtRecord', readDnslinkFromTxtRecord)
if (!window.IsIpfs.path(dnslink)) {
if (!IsIpfs.path(dnslink)) {
throw new Error(`dnslink for '${fqdn}' is not a valid IPFS path: '${dnslink}'`)
}
return dnslink
Expand Down Expand Up @@ -504,6 +508,8 @@ function uploadResultHandler (err, result) {
})
}

window.uploadResultHandler = uploadResultHandler

// Copying URLs
// -------------------------------------------------------------------

Expand All @@ -512,6 +518,8 @@ function safeIpfsPath (urlOrPath) {
return decodeURIComponent(urlOrPath.replace(/^.*(\/ip(f|n)s\/.+)$/, '$1'))
}

window.safeIpfsPath = safeIpfsPath

async function findUrlForContext (context) {
if (context) {
if (context.linkUrl) {
Expand Down Expand Up @@ -539,13 +547,17 @@ async function copyCanonicalAddress (context) {
notify('notify_copiedCanonicalAddressTitle', rawIpfsAddress)
}

window.copyCanonicalAddress = copyCanonicalAddress

async function copyAddressAtPublicGw (context) {
const url = await findUrlForContext(context)
const urlAtPubGw = url.replace(state.gwURLString, state.pubGwURLString)
copyTextToClipboard(urlAtPubGw)
notify('notify_copiedPublicURLTitle', urlAtPubGw)
}

window.copyAddressAtPublicGw = copyAddressAtPublicGw

async function copyTextToClipboard (copyText) {
const currentTab = await browser.tabs.query({active: true, currentWindow: true}).then(tabs => tabs[0])
const tabId = currentTab.id
Expand Down Expand Up @@ -596,7 +608,7 @@ async function updateContextMenus (changedTabId) {
// used in browser-action popup
// eslint-disable-next-line no-unused-vars
function isIpfsPageActionsContext (url) {
return window.IsIpfs.url(url) && !url.startsWith(state.apiURLString)
return IsIpfs.url(url) && !url.startsWith(state.apiURLString)
}

async function onActivatedTab (activeInfo) {
Expand All @@ -615,14 +627,14 @@ async function onUpdatedTab (tabId, changeInfo, tab) {
const browserApiPresent = (await browser.tabs.executeScript(tabId, { runAt: 'document_start', code: "typeof browser !== 'undefined'" }))[0]
if (!browserApiPresent) {
await browser.tabs.executeScript(tabId, {
file: '/src/lib/npm/browser-polyfill.min.js',
file: '/dist/lib/browser-polyfill.min.js',
matchAboutBlank: false,
allFrames: true,
runAt: 'document_start'
})
}
await browser.tabs.executeScript(tabId, {
file: '/src/lib/linkifyDOM.js',
file: '/dist/lib/linkifyDOM.js',
matchAboutBlank: false,
allFrames: true,
runAt: 'document_idle'
Expand Down Expand Up @@ -831,7 +843,7 @@ function onStorageChange (changes, area) { // eslint-disable-line no-unused-vars
if (key === 'ipfsApiUrl') {
state.apiURL = new URL(change.newValue)
state.apiURLString = state.apiURL.toString()
ipfs = initIpfsApi(state.apiURLString)
ipfs = window.ipfs = initIpfsApi(state.apiURLString)
apiStatusUpdate()
} else if (key === 'ipfsApiPollMs') {
setApiStatusUpdateInterval(change.newValue)
Expand Down
7 changes: 0 additions & 7 deletions add-on/src/lib/npm/.gitignore

This file was deleted.

2 changes: 1 addition & 1 deletion add-on/src/lib/option-defaults.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict'
/* eslint-env browser, webextensions */

const optionDefaults = Object.freeze({ // eslint-disable-line no-unused-vars
module.exports = Object.freeze({
publicGatewayUrl: 'https://ipfs.io',
useCustomGateway: true,
automaticMode: true,
Expand Down
4 changes: 1 addition & 3 deletions add-on/src/options/options.html
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,6 @@
transition: box-shadow 0.3s;
}
</style>
<script src="../lib/npm/browser-polyfill.min.js"></script>
</head>
<body>
<form>
Expand Down Expand Up @@ -221,8 +220,7 @@
</fieldset>
</form>

<script src="../lib/data-i18n.js"></script>
<script src="../lib/option-defaults.js"></script>
<script src="../common.js"></script>
<script src="options.js"></script>

</body>
Expand Down
7 changes: 6 additions & 1 deletion add-on/src/options/options.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
'use strict'
/* eslint-env browser, webextensions */
/* global optionDefaults */

const browser = require('webextension-polyfill')
const optionDefaults = require('../lib/option-defaults')
const translateDataAttrs = require('../lib/data-i18n')

translateDataAttrs()

async function saveOption (name) {
const element = document.querySelector(`#${name}`)
Expand Down
3 changes: 1 addition & 2 deletions add-on/src/popup/browser-action.html
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,6 @@
}
.hidden { display: none !important; }
</style>
<script src="../lib/npm/browser-polyfill.min.js"></script>
</head>

<body>
Expand Down Expand Up @@ -235,7 +234,7 @@
</div>
</div>

<script src="../lib/data-i18n.js"></script>
<script src="../common.js"></script>
<script src="browser-action.js"></script>
</body>

Expand Down
7 changes: 6 additions & 1 deletion add-on/src/popup/browser-action.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
'use strict'
/* eslint-env browser, webextensions */

const browser = require('webextension-polyfill')
const translateDataAttrs = require('../lib/data-i18n')

translateDataAttrs()

const ipfsContextActions = document.getElementById('ipfs-resource-context-actions')
const pinResourceButton = document.getElementById('pin-current-ipfs-address')
const unpinResourceButton = document.getElementById('unpin-current-ipfs-address')
Expand Down Expand Up @@ -186,7 +191,7 @@ async function updatePageActions () {
// Global Actions
// ===================================================================

quickUpload.onclick = () => browser.tabs.create({ url: browser.extension.getURL('src/popup/quick-upload.html') })
quickUpload.onclick = () => browser.tabs.create({ url: browser.extension.getURL('dist/popup/quick-upload.html') })

enableRedirect.onclick = () => browser.storage.local.set({useCustomGateway: true})
.then(updateBrowserActionPopup)
Expand Down
4 changes: 1 addition & 3 deletions add-on/src/popup/quick-upload.html
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@
<span id="quickUploadMessage" data-i18n="panel_quickUpload"></span><br>
<input type="file" id="quickUploadInput" />
</p>
<script src="../lib/npm/browser-polyfill.min.js"></script>
<script src="../lib/data-i18n.js"></script>
<script src="../lib/npm/ipfs-api.min.js"></script>
<script src="../common.js"></script>
<script src="quick-upload.js"></script>
</body>

Expand Down
Loading