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

feat: enable onload callbacks (#414)

* refactor(examples): run ssr example from server

* chore: switch to babel for build

buble complains too much

* feat: enable loaded callbacks

feat: add skip option

* examples: add async-callback browser example

* examples: fix server

* examples(ssr): add reactive script with callback

* fix: also skip on ssr

* chore: remove unused var

* feat: only add mutationobserver if DOM is still loading

feat: disconnect mutation observer once DOM has loaded

* examples: pass vmid to loadCallback instead of el

* feat: also support load callbacks for link/style tags

* test: add unit tests for load

* test: add load e2e test

* chore: fix lint

* chore: remove unused files

* test: fix e2e load callback test

* test: fix attempt

* examples: ie9 compatiblity

destructuring doesnt work in ie9

* fix: add onload attribute on ssr

dont rely on mutationobserver

* chore: lint ci conf

* refactor: remove loadCallbackAttribute config option

test: fix coverage for load

* test: improve coverage

* fix: only use console when it exists (for ie9)

* chore: fix coverage
This commit is contained in:
Pim
2019-07-24 10:18:40 +02:00
committed by GitHub
parent 05163a77a8
commit fc71e1f1c4
49 changed files with 963 additions and 632 deletions
-99
View File
@@ -1,99 +0,0 @@
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
}
}
+18 -3
View File
@@ -2,11 +2,14 @@ import path from 'path'
import fs from 'fs-extra'
import { template } from 'lodash'
import webpack from 'webpack'
import CopyWebpackPlugin from 'copy-webpack-plugin'
import VueLoaderPlugin from 'vue-loader/lib/plugin'
import { createRenderer } from 'vue-server-renderer'
const renderer = createRenderer()
export { default as getPort } from 'get-port'
export function webpackRun (config) {
const compiler = webpack(config)
@@ -50,13 +53,22 @@ export async function buildFixture (fixture, config = {}) {
const templateFile = await fs.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 assets = webpackStats.assets.filter(asset => !asset.name.includes('load-test'))
const headAssets = assets
.filter(asset => asset.name.includes('chunk'))
.reduce((s, asset) => `${s}<script src="./${asset.name}"></script>\n`, '')
const bodyAssets = assets
.filter(asset => !asset.name.includes('chunk'))
.reduce((s, asset) => `${s}<script src="./${asset.name}"></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 })
const html = compiled({ app, headAssets, bodyAssets, ...metaInfo })
await fs.writeFile(appFile, html)
@@ -125,7 +137,10 @@ export function createWebpackConfig (config = {}) {
// make sure our simple polyfills are enabled
'NODE_ENV': '"test"'
}
})
}),
new CopyWebpackPlugin([
{ from: path.join(path.dirname(config.entry), 'static') }
])
],
resolve: {
alias: {
-264
View File
@@ -1,264 +0,0 @@
/**
* @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 TypeError(`${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
}
}
+13
View File
@@ -1,3 +1,4 @@
import { JSDOM } from 'jsdom'
import { mount, shallowMount, createWrapper, createLocalVue } from '@vue/test-utils'
import { renderToString } from '@vue/server-test-utils'
import { defaultOptions } from '../../src/shared/constants'
@@ -32,3 +33,15 @@ export const vmTick = (vm) => {
vm.$nextTick(resolve)
})
}
export const pTick = () => new Promise(resolve => process.nextTick(resolve))
export function createDOM (html = '<!DOCTYPE html>', options = {}) {
const dom = new JSDOM(html, options)
return {
dom,
window: dom.window,
document: dom.window.document
}
}
+22 -20
View File
@@ -26,11 +26,11 @@ const metaInfoData = {
base: {
add: {
data: [{ href: 'href' }],
expect: ['<base data-vue-meta="test" href="href">']
expect: ['<base data-vue-meta="ssr" href="href">']
},
change: {
data: [{ href: 'href2' }],
expect: ['<base data-vue-meta="test" href="href2">']
expect: ['<base data-vue-meta="ssr" href="href2">']
},
remove: {
data: [],
@@ -41,8 +41,8 @@ const metaInfoData = {
add: {
data: [{ charset: 'utf-8' }, { property: 'a', content: 'a' }],
expect: [
'<meta data-vue-meta="test" charset="utf-8">',
'<meta data-vue-meta="test" property="a" content="a">'
'<meta data-vue-meta="ssr" charset="utf-8">',
'<meta data-vue-meta="ssr" property="a" content="a">'
]
},
change: {
@@ -51,8 +51,8 @@ const metaInfoData = {
{ property: 'a', content: 'b' }
],
expect: [
'<meta data-vue-meta="test" charset="utf-16">',
'<meta data-vue-meta="test" property="a" content="b">'
'<meta data-vue-meta="ssr" charset="utf-16">',
'<meta data-vue-meta="ssr" property="a" content="b">'
]
},
// make sure elements that already exists are not unnecessarily updated
@@ -62,8 +62,8 @@ const metaInfoData = {
{ property: 'a', content: 'c' }
],
expect: [
'<meta data-vue-meta="test" charset="utf-16">',
'<meta data-vue-meta="test" property="a" content="c">'
'<meta data-vue-meta="ssr" charset="utf-16">',
'<meta data-vue-meta="ssr" property="a" content="c">'
],
test (side, defaultTest) {
if (side === 'client') {
@@ -85,11 +85,11 @@ const metaInfoData = {
link: {
add: {
data: [{ rel: 'stylesheet', href: 'href' }],
expect: ['<link data-vue-meta="test" rel="stylesheet" href="href">']
expect: ['<link data-vue-meta="ssr" rel="stylesheet" href="href">']
},
change: {
data: [{ rel: 'stylesheet', href: 'href', media: 'screen' }],
expect: ['<link data-vue-meta="test" rel="stylesheet" href="href" media="screen">']
expect: ['<link data-vue-meta="ssr" rel="stylesheet" href="href" media="screen">']
},
remove: {
data: [],
@@ -99,11 +99,11 @@ const metaInfoData = {
style: {
add: {
data: [{ type: 'text/css', cssText: '.foo { color: red; }' }],
expect: ['<style data-vue-meta="test" type="text/css">.foo { color: red; }</style>']
expect: ['<style data-vue-meta="ssr" type="text/css">.foo { color: red; }</style>']
},
change: {
data: [{ type: 'text/css', cssText: '.foo { color: blue; }' }],
expect: ['<style data-vue-meta="test" type="text/css">.foo { color: blue; }</style>']
expect: ['<style data-vue-meta="ssr" type="text/css">.foo { color: blue; }</style>']
},
remove: {
data: [],
@@ -113,20 +113,22 @@ const metaInfoData = {
script: {
add: {
data: [
{ src: 'src', async: false, defer: true, [defaultOptions.tagIDKeyName]: 'content' },
{ src: 'src1', async: false, defer: true, [defaultOptions.tagIDKeyName]: 'content', callback: () => {} },
{ src: 'src-prepend', async: true, defer: false, pbody: true },
{ src: 'src', async: false, defer: true, body: true }
{ src: 'src2', async: false, defer: true, body: true },
{ src: 'src3', async: false, skip: true }
],
expect: [
'<script data-vue-meta="test" src="src" defer data-vmid="content"></script>',
'<script data-vue-meta="test" src="src-prepend" async data-pbody="true"></script>',
'<script data-vue-meta="test" src="src" defer data-body="true"></script>'
'<script data-vue-meta="ssr" src="src1" defer data-vmid="content" onload="this.__vm_l=1"></script>',
'<script data-vue-meta="ssr" src="src-prepend" async data-pbody="true"></script>',
'<script data-vue-meta="ssr" src="src2" defer data-body="true"></script>'
],
test (side, defaultTest) {
return () => {
if (side === 'client') {
for (const index in this.expect) {
this.expect[index] = this.expect[index].replace(/(async|defer)/g, '$1=""')
this.expect[index] = this.expect[index].replace(/ onload="this.__vm_l=1"/, '')
}
const tags = defaultTest()
@@ -150,7 +152,7 @@ const metaInfoData = {
// this test only runs for client so we can directly expect wrong boolean attributes
change: {
data: [{ src: 'src', async: true, defer: true, [defaultOptions.tagIDKeyName]: 'content2' }],
expect: ['<script data-vue-meta="test" src="src" async="" defer="" data-vmid="content2"></script>']
expect: ['<script data-vue-meta="ssr" src="src" async="" defer="" data-vmid="content2"></script>']
},
remove: {
data: [],
@@ -160,11 +162,11 @@ const metaInfoData = {
noscript: {
add: {
data: [{ innerHTML: '<p>noscript</p>' }],
expect: ['<noscript data-vue-meta="test"><p>noscript</p></noscript>']
expect: ['<noscript data-vue-meta="ssr"><p>noscript</p></noscript>']
},
change: {
data: [{ innerHTML: '<p>noscript, no really</p>' }],
expect: ['<noscript data-vue-meta="test"><p>noscript, no really</p></noscript>']
expect: ['<noscript data-vue-meta="ssr"><p>noscript, no really</p></noscript>']
},
remove: {
data: [],