Skip to content

Commit

Permalink
Fix multiple browsers not running together
Browse files Browse the repository at this point in the history
  • Loading branch information
cezaraugusto committed Aug 22, 2024
1 parent 8bfc4f9 commit fbfd99a
Show file tree
Hide file tree
Showing 9 changed files with 44 additions and 47 deletions.
2 changes: 1 addition & 1 deletion programs/create/steps/import-external-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export async function importExternalTemplate(
await fs.mkdir(projectPath, {recursive: true})

if (process.env.EXTENSION_ENV === 'development') {
console.log(messages.installingFromTemplate(projectName, template))
console.log(messages.installingFromTemplate(projectName, template))

await fs.cp(
path.join(__dirname, '..', '..', '..', 'examples', templateName),
Expand Down
2 changes: 1 addition & 1 deletion programs/develop/plugin-browsers/browsers-lib/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export function creatingUserProfile(browser: DevOptions['browser']) {
const browsername = capitalizedBrowserName(browser)
return (
`${getLoggingPrefix(browser, 'info')} Creating ${browsername} ` +
`profile directory...`
`user profile directory...`
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ async function handleTabOnExtensionLoad() {
██████████████████████████ ████████████████████████████
██████████████████████████████████████████████████████████
██████████████████████████████████████████████████████████
MIT (c) ${new Date().getFullYear()} - Cezar Augusto and the Extension.js Authors.
`,
bgGreen('')
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,12 @@ async function getDevExtension() {

return allExtensions.filter((extension) => {
return (
// Do not include itself
extension.id !== browser.runtime.id &&
// Reload extension
extension.name !== 'Extension Manager' &&
// Show only unpackaged extensions
extension.installType === 'development'
)
})
})[0]
}

// Create a new tab and set it to background.
Expand Down Expand Up @@ -40,14 +38,13 @@ export async function createFirefoxAddonsTab(initialTab, url) {
// Function to handle first run logic
export async function handleFirstRun() {
try {
const devExtensions = await getDevExtension()
const devExtension = await getDevExtension()

if (devExtensions.length === 0) {
if (!devExtension) {
console.warn('No development extensions found')
return
}

const devExtension = await getDevExtension()
const result = await browser.storage.local.get(devExtension.id)

if (result[devExtension.id] && result[devExtension.id].didRun) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "Extension Manager",
"description": "Developer Tools for extension management.",
"description": "Extension.js developer tools for tabs and reload management.",
"version": "1.0",
"manifest_version": 2,
"background": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ chrome.tabs.query({active: true}, async ([initialTab]) => {
██████████████████████████ ████████████████████████████
██████████████████████████████████████████████████████████
██████████████████████████████████████████████████████████
Make it very easy to develop cross-browser extensions.
MIT (c) ${new Date().getFullYear()} - Cezar Augusto and the Extension.js Authors.
`,
bgGreen('')
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "Extension Manager",
"description": "Developer Tools for extension management.",
"description": "Extension.js developer tools for tabs and reload management.",
"version": "1.0",
"manifest_version": 3,
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAolEJq/DBHxY5dBpOqBRWNCl7vRPBvJPlpEzF19fYFVzzaH44AF6+sKjN3jwIKlsgI82F3TIuwoNFiN1yBu5Unf8SVBE4BTO92P02/ACcGYQxicgCLFUGQKlq4uSrwSPaBYl7FHcYl5SERgxnIGCGnaGMdL2vC7waCj2/U/iKoBF9I1lBH9/aKCSjTd3h2UYo7gg6n5nY/ENbzylDt42T3ATmvnVJfYhSNKA9Dv/zryknfnHYYgBKHtz7pDZwWnYdxs78n2VEKwGj7TgbXuIPDpCkrMnU9PTKpHbXFYARA4H9qYORQmYazfIxUZRnKQNSR+GAOGrb8JK+ijeQdwzDAwIDAQAB",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,36 +7,46 @@ export async function connect() {
return
}

webSocket = new WebSocket('ws://localhost:__RELOAD_PORT__')
try {
// Attempt to connect using wss (secure WebSocket)
webSocket = new WebSocket('wss://localhost:__RELOAD_PORT__')
} catch (error) {
console.warn(
'Extension.js ►►► Secure WebSocket (wss) failed, falling back to ws.',
error
)
// If wss fails, fallback to ws (non-secure WebSocket)
webSocket = new WebSocket('ws://localhost:__RELOAD_PORT__')
}

webSocket.onerror = (event) => {
console.error(`[Extension.js] Connection error: ${JSON.stringify(event)}`)
console.error(`Extension.js ►►► Connection error: ${JSON.stringify(event)}`)
webSocket.close()
}

webSocket.onopen = () => {
console.info(`[Extension.js] Connection opened.`)
console.info(`Extension.js ►►► Connection opened.`)
}

webSocket.onmessage = async (event) => {
const message = JSON.parse(event.data)

if (message.status === 'serverReady') {
console.info('[Extension.js] Connection ready.')
console.info('Extension.js ►►► Connection ready.')
await requestInitialLoadData()
}

if (message.changedFile) {
console.info(
`[Extension.js] Changes detected on ${message.changedFile}. Reloading extension...`
`Extension.js ►►► Changes detected on ${message.changedFile}. Reloading extension...`
)

await messageAllExtensions(message.changedFile)
}
}

webSocket.onclose = () => {
console.info('[Extension.js] Connection closed.')
console.info('Extension.js ►►► Connection closed.')
webSocket = null
}
}
Expand Down Expand Up @@ -71,7 +81,7 @@ async function messageAllExtensions(changedFile) {
const reloadAll = devExtensions.map((extension) => {
chrome.runtime.sendMessage(extension.id, {changedFile}, (response) => {
if (response) {
console.info('[Extension.js] Extension reloaded and ready.')
console.info('Extension.js ►►► Extension reloaded and ready.')
}
})

Expand All @@ -80,7 +90,7 @@ async function messageAllExtensions(changedFile) {

await Promise.all(reloadAll)
} else {
console.info('[Extension.js] External extension is not ready.')
console.info('Extension.js ►►► External extension is not ready.')
}
}

Expand Down Expand Up @@ -108,7 +118,7 @@ async function requestInitialLoadData() {

const responses = await Promise.all(messagePromises)

// We received the info from the use extension.
// We received the info from the user extension.
// All good, client is ready. Inform the server.
if (webSocket && webSocket.readyState === WebSocket.OPEN) {
const message = JSON.stringify({
Expand All @@ -135,7 +145,7 @@ export function keepAlive() {
const keepAliveIntervalId = setInterval(() => {
if (webSocket) {
webSocket.send(JSON.stringify({status: 'ping'}))
console.info('[Extension.js] Listening for changes...')
console.info('Extension.js ►►► Listening for changes...')
} else {
clearInterval(keepAliveIntervalId)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,46 +41,29 @@ function isPortInUse(port: number): Promise<boolean> {
})
}

let webSocketServer: WebSocket.Server | null = null

export async function startServer(compiler: Compiler, options: DevOptions) {
const projectPath = compiler.options.context || ''
const manifest = require(path.join(projectPath, 'manifest.json'))
const manifestName = manifest.name || 'Extension.js'

let webSocketServer: WebSocket.Server | undefined
const port = options.port || 8000
const portInUse = await isPortInUse(port)

if (options.browser === 'firefox') {
const {server} = httpsServer(manifestName, options.port || 8000)
if (!webSocketServer && !portInUse) {
const {server} = httpsServer(manifestName, port)
webSocketServer = new WebSocket.Server({server})
} else {
const portInUse = await isPortInUse(options.port as number)

if (!portInUse) {
webSocketServer = new WebSocket.Server({
host: 'localhost',
port: options.port
})
} else {
// Port is already in use. Connect to the existing server.
webSocketServer = new WebSocket.Server({
noServer: true
})
}
}
console.log(`WebSocket server started on port ${port}`)

if (webSocketServer) {
webSocketServer.on('connection', (ws) => {
ws.send(JSON.stringify({status: 'serverReady'}))

ws.on('error', (error) => {
console.log(messages.webSocketError(manifestName, error))
webSocketServer?.close()
})

ws.on('close', () => {
webSocketServer?.close()
})

// We're only ready when the extension says so
ws.on('message', (msg) => {
const message: Message = JSON.parse(msg.toString())

Expand All @@ -102,11 +85,17 @@ export async function startServer(compiler: Compiler, options: DevOptions) {
}
})
})
} else if (webSocketServer) {
console.log(`Reusing existing WebSocket server on port ${port}`)
} else {
console.log('Failed to start WebSocket server.')
console.error(
`Port ${port} is already in use but WebSocket server is not initialized.`
)
return
}

if (options.browser === 'firefox') {
// Additional logic specific to Firefox, such as certificate checks
if (options.browser === 'firefox' && !portInUse) {
if (!fs.existsSync(CERTIFICATE_DESTINATION_PATH)) {
const hardcodedMessage = getHardcodedMessage(manifest)
console.log(messages.runningInDevelopment(manifest, hardcodedMessage))
Expand Down

0 comments on commit fbfd99a

Please sign in to comment.