2
0
mirror of https://github.com/tenrok/vue-meta.git synced 2026-06-15 00:12:24 +03:00

test: add e2e tests

fix: boolean attributes client side
This commit is contained in:
pimlie
2019-03-09 17:56:47 +01:00
committed by Alexander Lichter
parent a853ce3de7
commit 05b8891110
36 changed files with 1999 additions and 105 deletions
+4 -4
View File
@@ -1,13 +1,13 @@
{
"plugins": ["@babel/plugin-syntax-dynamic-import"],
"env": {
"test": {
"plugins": ["dynamic-import-node"],
"presets": [
[ "@babel/env", {
"targets": {
"node": "current"
}
"targets": { "node": "current" }
}]
]
}
}
},
}
+1
View File
@@ -40,6 +40,7 @@ package-lock.json
# built code
lib
es
.vue-meta
# examples yarn lock
examples/yarn.lock
+2 -1
View File
@@ -1,3 +1,4 @@
{
"presets": ["@babel/preset-env"]
"presets": ["@babel/preset-env"],
"plugins": ["@babel/plugin-syntax-dynamic-import"],
}
+1
View File
@@ -21,6 +21,7 @@
"devDependencies": {
"@babel/core": "^7.3.3",
"@babel/node": "^7.2.2",
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
"@babel/preset-env": "^7.3.1",
"babel-loader": "^8.0.5",
"cross-env": "^5.2.0",
+3 -2
View File
@@ -1,12 +1,13 @@
import Vue from 'vue'
import Router from 'vue-router'
import Meta from 'vue-meta'
import Home from './views/Home.vue'
import Post from './views/Post.vue'
Vue.use(Router)
Vue.use(Meta)
const Home = () => import('./views/Home.vue')
const Post = () => import('./views/Post.vue')
export default new Router({
mode: 'history',
base: '/vuex',
+11 -2
View File
@@ -46,7 +46,9 @@
"lint": "eslint src test",
"prerelease": "npm run build",
"release": "npm publish",
"test": "jest",
"test": "yarn test:unit && yarn test:e2e",
"test:e2e": "jest test/e2e",
"test:unit": "jest test/unit",
"toc": "doctoc README.md --title '# Table of Contents'",
"update-cdn": "babel-node scripts/update-cdn.js",
"preversion": "npm run toc",
@@ -59,6 +61,7 @@
"@babel/cli": "^7.2.3",
"@babel/core": "^7.3.3",
"@babel/node": "^7.2.2",
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
"@babel/preset-env": "^7.3.1",
"@nuxt/babel-preset-app": "^2.4.5",
"@nuxtjs/eslint-config": "^0.0.1",
@@ -68,6 +71,7 @@
"babel-eslint": "^10.0.1",
"babel-jest": "^24.1.0",
"babel-loader": "^8.0.5",
"babel-plugin-dynamic-import-node": "^2.2.0",
"codecov": "^3.2.0",
"doctoc": "^1.4.0",
"eslint": "^5.14.1",
@@ -83,6 +87,8 @@
"jest-environment-jsdom": "^24.3.1",
"jest-environment-jsdom-global": "^1.1.1",
"jsdom": "^13.2.0",
"lodash": "^4.17.11",
"puppeteer-core": "^1.13.0",
"rimraf": "^2.6.3",
"rollup": "^1.2.2",
"rollup-plugin-babel": "^4.3.2",
@@ -94,7 +100,10 @@
"update-section": "^0.3.3",
"vue": "^2.6.6",
"vue-jest": "^3.0.3",
"vue-loader": "^15.7.0",
"vue-router": "^3.0.2",
"vue-server-renderer": "^2.6.6",
"vue-template-compiler": "^2.6.6"
"vue-template-compiler": "^2.6.6",
"webpack": "^4.29.6"
}
}
+1 -3
View File
@@ -15,9 +15,7 @@ const startUpdate = (hasGlobalWindow ? window.requestAnimationFrame : null) || (
* @return {Number} id - a new ID
*/
export default function batchUpdate(id, callback) {
if (id) {
stopUpdate(id)
}
stopUpdate(id)
return startUpdate(() => {
id = null
+1 -1
View File
@@ -24,7 +24,7 @@ export default function updateClientMetaInfo(options = {}, newInfo) {
const htmlTag = getTag(tags, 'html')
// if this is a server render, then dont update
if (htmlTag.getAttribute(ssrAttribute)) {
if (htmlTag.hasAttribute(ssrAttribute)) {
// remove the server render attribute so we can update on (next) changes
htmlTag.removeAttribute(ssrAttribute)
return false
+4 -1
View File
@@ -1,3 +1,4 @@
import { booleanHtmlAttributes } from '../../shared/constants'
import isArray from '../../shared/isArray'
/**
@@ -14,7 +15,9 @@ export default function updateAttribute({ attribute } = {}, attrs, tag) {
const keepIndexes = []
for (const attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
const value = isArray(attrs[attr]) ? attrs[attr].join(' ') : attrs[attr]
const value = booleanHtmlAttributes.includes(attr)
? ''
: isArray(attrs[attr]) ? attrs[attr].join(' ') : attrs[attr]
tag.setAttribute(attr, value || '')
+79
View File
@@ -0,0 +1,79 @@
import Browser from '../utils/browser'
import { buildFixture } from '../utils/build'
const browser = new Browser()
describe('basic browser with ssr page', () => {
let page = null
let url
let html
beforeAll(async () => {
const fixture = await buildFixture('basic')
url = fixture.url
html = fixture.html
await browser.start({
// slowMo: 50,
// headless: false
})
})
// Stop browser
afterAll(async () => {
if (page) await page.close()
await browser.close()
})
test('validate ssr', () => {
const htmlTag = html.match(/<html([^>]+)>/)[0]
expect(htmlTag).toContain('data-vue-meta-server-rendered')
expect(htmlTag).toContain(' lang="en" ')
expect(htmlTag).toContain(' amp ')
expect(htmlTag).not.toContain('allowfullscreen')
expect(html.match(/<title[^>]*>(.*?)<\/title>/)[1]).toBe('Home | Vue Meta Test')
expect(html.match(/<meta/g).length).toBe(2)
expect(html.match(/<meta/g).length).toBe(2)
const re = /<(no)?script[^>]+type="application\/ld\+json"[^>]*>(.*?)</g
const sanitizeCheck = []
let match
while ((match = re.exec(html))) {
sanitizeCheck.push(match[2])
}
expect(sanitizeCheck.length).toBe(3)
expect(() => JSON.parse(sanitizeCheck[0])).not.toThrow()
expect(() => JSON.parse(sanitizeCheck[1])).toThrow()
expect(() => JSON.parse(sanitizeCheck[2])).not.toThrow()
})
test('Open /', async () => {
page = await browser.page(url)
expect(await page.$attr('html', 'data-vue-meta-server-rendered')).toBe(null)
expect(await page.$attr('html', 'lang')).toBe('en')
expect(await page.$attr('html', 'amp')).toBe('')
expect(await page.$attr('html', 'allowfullscreen')).toBe(null)
expect(await page.$attr('head', 'test')).toBe('true')
expect(await page.$text('h1')).toBe('Basic')
expect(await page.$text('title')).toBe('Home | Vue Meta Test')
expect(await page.$$eval('meta', metas => metas.length)).toBe(2)
let sanitizeCheck = await page.$$text('script')
sanitizeCheck.push(...(await page.$$text('noscript')))
sanitizeCheck = sanitizeCheck.filter(v => !!v)
expect(sanitizeCheck.length).toBe(3)
expect(() => JSON.parse(sanitizeCheck[0])).not.toThrow()
expect(() => JSON.parse(sanitizeCheck[1])).not.toThrow()
expect(() => JSON.parse(sanitizeCheck[2])).not.toThrow()
})
test('/about', async () => {
const { hook } = await page.vueMeta.navigate('/about', false)
await hook
expect(await page.$text('title')).toBe('About')
expect(await page.$$eval('meta', metas => metas.length)).toBe(1)
})
})
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html data-vue-meta-server-rendered {{ htmlAttrs.text() }}>
<head {{ headAttrs.text() }}>
{{ meta.text() }}
{{ title.text() }}
{{ link.text() }}
{{ style.text() }}
{{ webpackAssets }}
{{ script.text() }}
{{ noscript.text() }}
</head>
<body {{ bodyAttrs.text() }}>
{{ app }}
{{ script.text({ body: true }) }}
{{ noscript.text({ body: true }) }}
</body>
</html>
-33
View File
@@ -1,33 +0,0 @@
<template>
<html {{ head.headAttrs.text() }}>
<head></head>
bla
</html>
</template>
<script>
export default {
metaInfo() {
return {
title: this.title
}
},
data() {
return {
title: 'Hello World',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' }
]
}
},
computed: {
head() {
return meta.inject()
}
}
}
</script>
+21
View File
@@ -0,0 +1,21 @@
<template>
<div id="app">
<h1>Basic</h1>
<router-view></router-view>
<p>Inspect Element to see the meta info</p>
</div>
</template>
<script>
export default {
metaInfo: {
meta: [
{ vmid: 'charset', charset: 'utf-8' }
]
},
mounted() {
this.$router.afterEach((to, from) => this.$emit('routeChanged', to, from))
window.$vueMeta = this
}
}
</script>
+10
View File
@@ -0,0 +1,10 @@
import Vue from 'vue'
import VueMeta from '../../../src/browser'
import App from './App.vue'
import createRouter from './router'
Vue.use(VueMeta)
App.router = createRouter()
new Vue(App).$mount('#app')
+18
View File
@@ -0,0 +1,18 @@
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const Home = () => import('./views/home.vue')
const Post = () => import('./views/about.vue')
export default function createRouter() {
return new Router({
mode: 'hash',
base: '/',
routes: [
{ path: '/', component: Home },
{ path: '/about', component: Post }
]
})
}
+10
View File
@@ -0,0 +1,10 @@
import Vue from 'vue'
import VueMeta from '../../../src'
import App from './App.vue'
import createRouter from './router'
Vue.use(VueMeta)
App.router = createRouter()
export default new Vue(App)
+16
View File
@@ -0,0 +1,16 @@
<template>
<div>
<h2>About</h2>
<router-link to="/">Go to Home</router-link>
</div>
</template>
<script>
export default {
metaInfo() {
return {
title: 'About'
}
}
}
</script>
+37
View File
@@ -0,0 +1,37 @@
<template>
<div>
<h2>Home</h2>
<router-link to="/about">Go to About</router-link>
</div>
</template>
<script>
export default {
metaInfo() {
return {
title: 'Home',
titleTemplate: '%s | Vue Meta Test',
htmlAttrs: {
lang: 'en',
allowfullscreen: undefined,
amp: true
},
headAttrs: {
test: true
},
meta: [
{ name: 'description', content: 'Hello', vmid: 'test' }
],
script: [
{ vmid: 'ldjson', innerHTML: '{ "@context": "http://www.schema.org", "@type": "Organization" }', type: 'application/ld+json' },
{ innerHTML: '{ "more": "data" }', type: 'application/ld+json' }
],
noscript: [
{ innerHTML: '{ "body": "yes" }', body: true, type: 'application/ld+json' }
],
__dangerouslyDisableSanitizers: ['noscript'],
__dangerouslyDisableSanitizersByTagID: { ldjson: ['innerHTML'] }
}
}
}
</script>
@@ -1,15 +1,15 @@
import _getMetaInfo from '../src/shared/getMetaInfo'
import { mount, loadVueMetaPlugin, vmTick } from './utils'
import { defaultOptions } from './utils/constants'
import _getMetaInfo from '../../src/shared/getMetaInfo'
import { mount, loadVueMetaPlugin, vmTick } from '../utils'
import { defaultOptions } from '../utils/constants'
import GoodbyeWorld from './fixtures/goodbye-world.vue'
import HelloWorld from './fixtures/hello-world.vue'
import KeepAlive from './fixtures/keep-alive.vue'
import Changed from './fixtures/changed.vue'
import GoodbyeWorld from '../components/goodbye-world.vue'
import HelloWorld from '../components/hello-world.vue'
import KeepAlive from '../components/keep-alive.vue'
import Changed from '../components/changed.vue'
const getMetaInfo = component => _getMetaInfo(defaultOptions, component)
jest.mock('../src/shared/window', () => ({
jest.mock('../../src/shared/window', () => ({
hasGlobalWindow: false
}))
@@ -1,6 +1,6 @@
import _getMetaInfo from '../src/shared/getMetaInfo'
import { loadVueMetaPlugin } from './utils'
import { defaultOptions } from './utils/constants'
import _getMetaInfo from '../../src/shared/getMetaInfo'
import { loadVueMetaPlugin } from '../utils'
import { defaultOptions } from '../utils/constants'
const getMetaInfo = (component, escapeSequences) => _getMetaInfo(defaultOptions, component, escapeSequences)
@@ -1,6 +1,6 @@
import _generateServerInjector from '../src/server/generateServerInjector'
import { defaultOptions } from './utils/constants'
import metaInfoData from './utils/meta-info-data'
import _generateServerInjector from '../../src/server/generateServerInjector'
import { defaultOptions } from '../utils/constants'
import metaInfoData from '../utils/meta-info-data'
const generateServerInjector = (type, data) => _generateServerInjector(defaultOptions, type, data)
@@ -1,6 +1,6 @@
import getComponentOption from '../src/shared/getComponentOption'
import inMetaInfoBranch from '../src/shared/inMetaInfoBranch'
import { mount, getVue, loadVueMetaPlugin } from './utils'
import getComponentOption from '../../src/shared/getComponentOption'
import inMetaInfoBranch from '../../src/shared/inMetaInfoBranch'
import { mount, getVue, loadVueMetaPlugin } from '../utils'
describe('getComponentOption', () => {
let Vue
@@ -1,6 +1,6 @@
import _getMetaInfo from '../src/shared/getMetaInfo'
import { loadVueMetaPlugin } from './utils'
import { defaultOptions } from './utils/constants'
import _getMetaInfo from '../../src/shared/getMetaInfo'
import { loadVueMetaPlugin } from '../utils'
import { defaultOptions } from '../utils/constants'
const getMetaInfo = component => _getMetaInfo(defaultOptions, component)
@@ -1,11 +1,11 @@
import triggerUpdate from '../src/client/triggerUpdate'
import batchUpdate from '../src/client/batchUpdate'
import { mount, vmTick, VueMetaBrowserPlugin, loadVueMetaPlugin } from './utils'
import { defaultOptions } from './utils/constants'
import triggerUpdate from '../../src/client/triggerUpdate'
import batchUpdate from '../../src/client/batchUpdate'
import { mount, vmTick, VueMetaBrowserPlugin, loadVueMetaPlugin } from '../utils'
import { defaultOptions } from '../utils/constants'
jest.mock('../src/client/triggerUpdate')
jest.mock('../src/client/batchUpdate')
jest.mock('../package.json', () => ({
jest.mock('../../src/client/triggerUpdate')
jest.mock('../../src/client/batchUpdate')
jest.mock('../../package.json', () => ({
version: 'test-version'
}))
@@ -48,8 +48,8 @@ describe('plugin', () => {
})
test('updates can be paused and resumed', async () => {
const _triggerUpdate = jest.requireActual('../src/client/triggerUpdate').default
const _batchUpdate = jest.requireActual('../src/client/batchUpdate').default
const _triggerUpdate = jest.requireActual('../../src/client/triggerUpdate').default
const _batchUpdate = jest.requireActual('../../src/client/batchUpdate').default
const triggerUpdateSpy = triggerUpdate.mockImplementation(_triggerUpdate)
const batchUpdateSpy = batchUpdate.mockImplementation(_batchUpdate)
@@ -1,7 +1,7 @@
import { mount, VueMetaServerPlugin, loadVueMetaPlugin } from './utils'
import { defaultOptions } from './utils/constants'
import { mount, VueMetaServerPlugin, loadVueMetaPlugin } from '../utils'
import { defaultOptions } from '../utils/constants'
jest.mock('../package.json', () => ({
jest.mock('../../package.json', () => ({
version: 'test-version'
}))
@@ -1,10 +1,10 @@
/**
* @jest-environment node
*/
import { ensureIsArray } from '../src/shared/ensure'
import setOptions from '../src/shared/options'
import { hasGlobalWindowFn } from '../src/shared/window'
import { defaultOptions } from './utils/constants'
import { ensureIsArray } from '../../src/shared/ensure'
import setOptions from '../../src/shared/options'
import { hasGlobalWindowFn } from '../../src/shared/window'
import { defaultOptions } from '../utils/constants'
const noop = () => {}
@@ -1,6 +1,6 @@
import _updateClientMetaInfo from '../src/client/updateClientMetaInfo'
import { defaultOptions } from './utils/constants'
import metaInfoData from './utils/meta-info-data'
import _updateClientMetaInfo from '../../src/client/updateClientMetaInfo'
import { defaultOptions } from '../utils/constants'
import metaInfoData from '../utils/meta-info-data'
const updateClientMetaInfo = (type, data) => _updateClientMetaInfo(defaultOptions, { [type]: data })
+99
View File
@@ -0,0 +1,99 @@
import puppeteer from 'puppeteer-core'
import ChromeDetector from './chrome'
export default class Browser {
constructor() {
this.detector = new ChromeDetector()
}
async start(options = {}) {
// https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions
const _opts = {
args: [
'--no-sandbox',
'--disable-setuid-sandbox'
],
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH,
...options
}
if (!_opts.executablePath) {
_opts.executablePath = this.detector.detect()
}
this.browser = await puppeteer.launch(_opts)
}
async close() {
if (!this.browser) return
await this.browser.close()
}
async page(url, globalName = 'vueMeta') {
if (!this.browser) throw new Error('Please call start() before page(url)')
const page = await this.browser.newPage()
// pass on console messages
const typeMap = {
debug: 'debug',
warning: 'warn',
error: 'error'
}
page.on('console', (msg) => {
if (typeMap[msg.type()]) {
console[typeMap[msg.type()]](msg.text()) // eslint-disable-line no-console
}
})
await page.goto(url)
page.$globalHandle = `window.$${globalName}`
await page.waitForFunction(`!!${page.$globalHandle}`)
page.html = () => page.evaluate(() => window.document.documentElement.outerHTML)
page.$text = (selector, trim) => page.$eval(selector, (el, trim) => {
return trim ? el.textContent.replace(/^\s+|\s+$/g, '') : el.textContent
}, trim)
page.$$text = (selector, trim) =>
page.$$eval(selector, (els, trim) => els.map((el) => {
return trim ? el.textContent.replace(/^\s+|\s+$/g, '') : el.textContent
}), trim)
page.$attr = (selector, attr) =>
page.$eval(selector, (el, attr) => el.getAttribute(attr), attr)
page.$$attr = (selector, attr) =>
page.$$eval(
selector,
(els, attr) => els.map(el => el.getAttribute(attr)),
attr
)
page.$vueMeta = await page.evaluateHandle(page.$globalHandle)
page.vueMeta = {
async navigate(path, waitEnd = true) {
const hook = page.evaluate(`
new Promise(resolve =>
${page.$globalHandle}.$once('routeChanged', resolve)
).then(() => new Promise(resolve => setTimeout(resolve, 50)))
`)
await page.evaluate(
($vueMeta, path) => $vueMeta.$router.push(path),
page.$vueMeta,
path
)
if (waitEnd) {
await hook
}
return { hook }
},
routeData() {
return page.evaluate(($vueMeta) => {
return {
path: $vueMeta.$route.path,
query: $vueMeta.$route.query
}
}, page.$vueMeta)
}
}
return page
}
}
+114
View File
@@ -0,0 +1,114 @@
import fs from 'fs'
import path from 'path'
import { promisify } from 'util'
import { template } from 'lodash'
import webpack from 'webpack'
import VueLoaderPlugin from 'vue-loader/lib/plugin'
import { createRenderer } from 'vue-server-renderer'
const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)
const renderer = createRenderer()
export function webpackRun(config) {
const compiler = webpack(config)
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) {
reject(err)
}
resolve(stats.toJson())
})
})
}
export async function buildFixture(fixture, config = {}) {
if (!fixture) {
throw new Error('buildFixture should be called with a fixture name')
}
const fixturePath = path.resolve(__dirname, '..', 'fixtures', fixture)
config.entry = path.resolve(fixturePath, 'client.js')
if (!config.name) {
config.name = path.basename(path.dirname(config.entry))
}
const webpackConfig = createWebpackConfig(config)
const webpackStats = await webpackRun(webpackConfig)
// for test debugging
webpackStats.errors.map(e => console.error(e)) // eslint-disable-line no-console
webpackStats.warnings.map(e => console.warn(e)) // eslint-disable-line no-console
const vueApp = await import(path.resolve(fixturePath, 'server')).then(m => m.default || m)
const templateFile = await readFile(path.resolve(fixturePath, '..', 'app.template.html'), { encoding: 'utf8' })
const compiled = template(templateFile, { interpolate: /{{([\s\S]+?)}}/g })
const webpackAssets = webpackStats.assets.reduce((s, asset) => `${s}<script src="./${asset.name}"${asset.name.includes('chunk') ? '' : ' defer'}></script>\n`, '')
const app = await renderer.renderToString(vueApp)
// !!! run inject after renderToString !!!
const metaInfo = vueApp.$meta().inject()
const appFile = path.resolve(webpackStats.outputPath, 'index.html')
const html = compiled({ app, webpackAssets, ...metaInfo })
await writeFile(appFile, html)
return {
url: `file://${appFile}`,
appFile,
webpackStats,
html,
metaInfo
}
}
export function createWebpackConfig(config = {}) {
const publicPath = '.vue-meta'
return {
mode: 'development',
output: {
path: path.join(path.dirname(config.entry), publicPath),
filename: '[name].js',
chunkFilename: '[id].chunk.js',
publicPath: `/${publicPath}/`
},
module: {
rules: [
{ test: /\.js$/, exclude: /node_modules/, use: 'babel-loader' },
{ test: /\.vue$/, use: 'vue-loader' }
]
},
// Expose __dirname to allow automatically setting basename.
context: __dirname,
node: {
__dirname: true
},
optimization: {
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all'
}
}
}
},
plugins: [
new VueLoaderPlugin()
],
resolve: {
alias: {
'vue': 'vue/dist/vue.esm.js'
}
},
...config
}
}
+264
View File
@@ -0,0 +1,264 @@
/**
* @license Copyright 2016 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
import fs from 'fs'
import path from 'path'
import { execSync, execFileSync } from 'child_process'
import isWsl from 'is-wsl'
import uniq from 'lodash/uniq'
const newLineRegex = /\r?\n/
/**
* This class is based on node-get-chrome
* https://github.com/mrlee23/node-get-chrome
* https://github.com/gwuhaolin/chrome-finder
*/
export default class ChromeDetector {
constructor() {
this.platform = isWsl ? 'wsl' : process.platform
}
detect(platform = this.platform) {
const handler = this[platform]
if (typeof handler !== 'function') {
throw new Error(`${platform} is not supported.`)
}
return this[platform]()[0]
}
darwin() {
const suffixes = [
'/Contents/MacOS/Chromium',
'/Contents/MacOS/Google Chrome Canary',
'/Contents/MacOS/Google Chrome'
]
const LSREGISTER =
'/System/Library/Frameworks/CoreServices.framework' +
'/Versions/A/Frameworks/LaunchServices.framework' +
'/Versions/A/Support/lsregister'
const installations = []
const customChromePath = this.resolveChromePath()
if (customChromePath) {
installations.push(customChromePath)
}
execSync(
`${LSREGISTER} -dump` +
" | grep -i '(google chrome\\( canary\\)\\?|chromium).app$'" +
' | awk \'{$1=""; print $0}\''
)
.toString()
.split(newLineRegex)
.forEach((inst) => {
suffixes.forEach((suffix) => {
const execPath = path.join(inst.trim(), suffix)
if (this.canAccess(execPath)) {
installations.push(execPath)
}
})
})
// Retains one per line to maintain readability.
// clang-format off
const priorities = [
{ regex: new RegExp(`^${process.env.HOME}/Applications/.*Chrome.app`), weight: 50 },
{ regex: new RegExp(`^${process.env.HOME}/Applications/.*Chrome Canary.app`), weight: 51 },
{ regex: new RegExp(`^${process.env.HOME}/Applications/.*Chromium.app`), weight: 52 },
{ regex: /^\/Applications\/.*Chrome.app/, weight: 100 },
{ regex: /^\/Applications\/.*Chrome Canary.app/, weight: 101 },
{ regex: /^\/Applications\/.*Chromium.app/, weight: 102 },
{ regex: /^\/Volumes\/.*Chrome.app/, weight: -3 },
{ regex: /^\/Volumes\/.*Chrome Canary.app/, weight: -2 },
{ regex: /^\/Volumes\/.*Chromium.app/, weight: -1 }
]
if (process.env.LIGHTHOUSE_CHROMIUM_PATH) {
priorities.push({ regex: new RegExp(process.env.LIGHTHOUSE_CHROMIUM_PATH), weight: 150 })
}
if (process.env.CHROME_PATH) {
priorities.push({ regex: new RegExp(process.env.CHROME_PATH), weight: 151 })
}
// clang-format on
return this.sort(installations, priorities)
}
/**
* Look for linux executables in 3 ways
* 1. Look into CHROME_PATH env variable
* 2. Look into the directories where .desktop are saved on gnome based distro's
* 3. Look for google-chrome-stable & google-chrome executables by using the which command
*/
linux() {
let installations = []
// 1. Look into CHROME_PATH env variable
const customChromePath = this.resolveChromePath()
if (customChromePath) {
installations.push(customChromePath)
}
// 2. Look into the directories where .desktop are saved on gnome based distro's
const desktopInstallationFolders = [
path.join(require('os').homedir(), '.local/share/applications/'),
'/usr/share/applications/'
]
desktopInstallationFolders.forEach((folder) => {
installations = installations.concat(this.findChromeExecutables(folder))
})
// Look for chromium(-browser) & google-chrome(-stable) executables by using the which command
const executables = [
'chromium-browser',
'chromium',
'google-chrome-stable',
'google-chrome'
]
executables.forEach((executable) => {
try {
const chromePath = execFileSync('which', [executable])
.toString()
.split(newLineRegex)[0]
if (this.canAccess(chromePath)) {
installations.push(chromePath)
}
} catch (e) {
// Not installed.
}
})
if (!installations.length) {
throw new Error(
'The environment variable CHROME_PATH must be set to ' +
'executable of a build of Chromium version 54.0 or later.'
)
}
const priorities = [
{ regex: /chromium-browser$/, weight: 51 },
{ regex: /chromium$/, weight: 50 },
{ regex: /chrome-wrapper$/, weight: 49 },
{ regex: /google-chrome-stable$/, weight: 48 },
{ regex: /google-chrome$/, weight: 47 }
]
if (process.env.LIGHTHOUSE_CHROMIUM_PATH) {
priorities.push({
regex: new RegExp(process.env.LIGHTHOUSE_CHROMIUM_PATH),
weight: 100
})
}
if (process.env.CHROME_PATH) {
priorities.push({ regex: new RegExp(process.env.CHROME_PATH), weight: 101 })
}
return this.sort(uniq(installations.filter(Boolean)), priorities)
}
wsl() {
// Manually populate the environment variables assuming it's the default config
process.env.LOCALAPPDATA = this.getLocalAppDataPath(process.env.PATH)
process.env.PROGRAMFILES = '/mnt/c/Program Files'
process.env['PROGRAMFILES(X86)'] = '/mnt/c/Program Files (x86)'
return this.win32()
}
win32() {
const installations = []
const sep = path.sep
const suffixes = [
`${sep}Chromium${sep}Application${sep}chrome.exe`,
`${sep}Google${sep}Chrome SxS${sep}Application${sep}chrome.exe`,
`${sep}Google${sep}Chrome${sep}Application${sep}chrome.exe`,
`${sep}chrome-win32${sep}chrome.exe`,
`${sep}Google${sep}Chrome Beta${sep}Application${sep}chrome.exe`
]
const prefixes = [
process.env.LOCALAPPDATA,
process.env.PROGRAMFILES,
process.env['PROGRAMFILES(X86)']
].filter(Boolean)
const customChromePath = this.resolveChromePath()
if (customChromePath) {
installations.push(customChromePath)
}
prefixes.forEach(prefix =>
suffixes.forEach((suffix) => {
const chromePath = path.join(prefix, suffix)
if (this.canAccess(chromePath)) {
installations.push(chromePath)
}
})
)
return installations
}
resolveChromePath() {
if (this.canAccess(process.env.CHROME_PATH)) {
return process.env.CHROME_PATH
}
if (this.canAccess(process.env.LIGHTHOUSE_CHROMIUM_PATH)) {
console.warn( // eslint-disable-line no-console
'ChromeLauncher',
'LIGHTHOUSE_CHROMIUM_PATH is deprecated, use CHROME_PATH env variable instead.'
)
return process.env.LIGHTHOUSE_CHROMIUM_PATH
}
}
getLocalAppDataPath(path) {
const userRegExp = /\/mnt\/([a-z])\/Users\/([^/:]+)\/AppData\//
const results = userRegExp.exec(path) || []
return `/mnt/${results[1]}/Users/${results[2]}/AppData/Local`
}
sort(installations, priorities) {
const defaultPriority = 10
return installations
.map((inst) => {
for (const pair of priorities) {
if (pair.regex.test(inst)) {
return { path: inst, weight: pair.weight }
}
}
return { path: inst, weight: defaultPriority }
})
.sort((a, b) => b.weight - a.weight)
.map(pair => pair.path)
}
canAccess(file) {
if (!file) {
return false
}
try {
fs.accessSync(file)
return true
} catch (e) {
return false
}
}
findChromeExecutables(folder) {
const argumentsRegex = /(^[^ ]+).*/ // Take everything up to the first space
const chromeExecRegex = '^Exec=/.*/(google-chrome|chrome|chromium)-.*'
const installations = []
if (this.canAccess(folder)) {
// Output of the grep & print looks like:
// /opt/google/chrome/google-chrome --profile-directory
// /home/user/Downloads/chrome-linux/chrome-wrapper %U
let execPaths
// Some systems do not support grep -R so fallback to -r.
// See https://github.com/GoogleChrome/chrome-launcher/issues/46 for more context.
try {
execPaths = execSync(
`grep -ER "${chromeExecRegex}" ${folder} | awk -F '=' '{print $2}'`
)
} catch (e) {
execPaths = execSync(
`grep -Er "${chromeExecRegex}" ${folder} | awk -F '=' '{print $2}'`
)
}
execPaths = execPaths
.toString()
.split(newLineRegex)
.map(execPath => execPath.replace(argumentsRegex, '$1'))
execPaths.forEach(
execPath => this.canAccess(execPath) && installations.push(execPath)
)
}
return installations
}
}
+1
View File
@@ -1 +1,2 @@
jest.useFakeTimers()
jest.setTimeout(15000)
+1246 -19
View File
File diff suppressed because it is too large Load Diff