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

core(hreflang): remove eval, import axe valid-langs.js directly #13385

Merged
merged 9 commits into from
Feb 4, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ jobs:
- run: yarn i18n:checks
- run: yarn dogfood-lhci
- run: bash lighthouse-core/scripts/copy-util-commonjs.sh
- run: bash lighthouse-core/scripts/copy-axe-valid-langs.sh
Copy link
Member

@brendankenny brendankenny Nov 16, 2021

Choose a reason for hiding this comment

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

can we skip introducing machinery to update? The list of langs hasn't changed since March 2018. The third-party directory needs a readme anyways, we could just put update instructions in there too. Ideally long term we just get the file to be importable from the node_modules/ dependency.


# Fail if any changes were written to any source files or generated untracked files (ex, from: build/build-cdt-lib.js).
- run: git add -A && git diff --cached --exit-code
Expand Down
29 changes: 8 additions & 21 deletions lighthouse-core/audits/seo/hreflang.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@

const Audit = require('../audit.js');
const i18n = require('../../lib/i18n/i18n.js');
const axeLibSource = require('../../lib/axe.js').source;

const VALID_LANGS = importValidLangs();
const NO_LANGUAGE = 'x-default';

const UIStrings = {
Expand All @@ -33,20 +31,6 @@ const UIStrings = {

const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings);

/**
* Import list of valid languages from axe core.
* This is a huge array of language codes that can be stored more efficiently if we will need to
* shrink the bundle size.
* @return {Array<string>}
*/
function importValidLangs() {
// Define a window-ish object so axe will export to it.
const window = {getComputedStyle: () => {}};
eval(axeLibSource);
// @ts-expect-error
return window.axe.utils.validLangs();
}

/**
* @param {string} href
* @return {boolean}
Expand All @@ -57,16 +41,17 @@ function isFullyQualified(href) {

/**
* @param {string} hreflang
* @param {(lang: string) => boolean} isValidLang From axe.
* @return {boolean}
*/
function isExpectedLanguageCode(hreflang) {
function isExpectedLanguageCode(hreflang, isValidLang) {
Copy link
Member

Choose a reason for hiding this comment

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

Any reason to make this a callback? Could import where needed:

Suggested change
function isExpectedLanguageCode(hreflang, isValidLang) {
async function isExpectedLanguageCode(hreflang) {
// TODO(esmodules): use static import when file is esm.
const isValidLang = (await import('../../../third-party/axe/valid-langs.js')).default;
// ...

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I was trying to limit the async from going where it made less sense.

if (hreflang.toLowerCase() === NO_LANGUAGE) {
return true;
}

// hreflang can consist of language-script-region, we are validating only language
const [lang] = hreflang.split('-');
return VALID_LANGS.includes(lang.toLowerCase());
return isValidLang(lang.toLowerCase());
}

class Hreflang extends Audit {
Expand All @@ -86,9 +71,11 @@ class Hreflang extends Audit {

/**
* @param {LH.Artifacts} artifacts
* @return {LH.Audit.Product}
* @return {Promise<LH.Audit.Product>}
*/
static audit({LinkElements}) {
Copy link
Member

Choose a reason for hiding this comment

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

This doesn't need to be async anymore

static async audit({LinkElements}) {
const isValidLang = (await import('../../../third-party/axe/valid-langs.js')).default;

/** @type {InvalidHreflang[]} */
const invalidHreflangs = [];

Expand All @@ -105,7 +92,7 @@ class Hreflang extends Audit {
/** @type {Source} */
let source;

if (!isExpectedLanguageCode(link.hreflang)) {
if (!isExpectedLanguageCode(link.hreflang, isValidLang)) {
reasons.push(str_(UIStrings.unexpectedLanguage));
}

Expand Down
18 changes: 18 additions & 0 deletions lighthouse-core/scripts/copy-axe-valid-langs.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#!/usr/bin/env bash

##
# @license Copyright 2021 The Lighthouse Authors. 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.
##

# Necessary because axe-core does not publish as type: 'module', even though axe-core/lib/ is esmodules.

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
LH_ROOT_DIR="$SCRIPT_DIR/../.."

OUT_FILE="$LH_ROOT_DIR"/third-party/axe/valid-langs.js

echo '// @ts-nocheck' > "$OUT_FILE"
echo '// Auto-generated by lighthouse-core/scripts/copy-axe-valid-langs.sh' >> "$OUT_FILE"
sed 's/Sting/string/' "$LH_ROOT_DIR"/node_modules/axe-core/lib/core/utils/valid-langs.js >> "$OUT_FILE"
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
sed 's/Sting/string/' "$LH_ROOT_DIR"/node_modules/axe-core/lib/core/utils/valid-langs.js >> "$OUT_FILE"
sed 's/String/string/' "$LH_ROOT_DIR"/node_modules/axe-core/lib/core/utils/valid-langs.js >> "$OUT_FILE"

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Indeed, it is Sting.

image

Copy link
Member

Choose a reason for hiding this comment

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

I think they fixed it so it is String now

33 changes: 17 additions & 16 deletions lighthouse-core/test/audits/seo/hreflang-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const node = {};
/* eslint-env jest */

describe('SEO: Document has valid hreflang code', () => {
it('fails when the language code provided in hreflang via link element is invalid', () => {
it('fails when the language code provided in hreflang via link element is invalid', async () => {
const artifacts = {
LinkElements: [
{rel: 'alternate', hreflang: 'xx1', hrefRaw: 'http://example.com/', source: 'headers', node},
Expand All @@ -24,12 +24,12 @@ describe('SEO: Document has valid hreflang code', () => {
],
};

const {score, details} = HreflangAudit.audit(artifacts);
const {score, details} = await HreflangAudit.audit(artifacts);
assert.equal(score, 0);
assert.equal(details.items.length, 5);
});

it('succeeds when the language code provided in hreflang via body is invalid', () => {
it('succeeds when the language code provided in hreflang via body is invalid', async () => {
const hreflangValues = ['xx', 'XX-be', 'XX-be-Hans', '', ' es'];

for (const hreflangValue of hreflangValues) {
Expand All @@ -44,12 +44,12 @@ describe('SEO: Document has valid hreflang code', () => {
],
};

const {score} = HreflangAudit.audit(artifacts);
const {score} = await HreflangAudit.audit(artifacts);
assert.equal(score, 1);
}
});

it('succeeds when language code provided via head/headers is valid', () => {
it('succeeds when language code provided via head/headers is valid', async () => {
const hreflangValues = ['pl', 'nl-be', 'zh-Hans', 'x-default', 'FR-BE'];

let inHead = false;
Expand All @@ -66,17 +66,18 @@ describe('SEO: Document has valid hreflang code', () => {
],
};

const {score} = HreflangAudit.audit(artifacts);
const {score} = await HreflangAudit.audit(artifacts);
assert.equal(score, 1);
inHead = !inHead;
}
});

it('succeeds when there are no rel=alternate link elements nor headers', () => {
assert.equal(HreflangAudit.audit({LinkElements: []}).score, 1);
it('succeeds when there are no rel=alternate link elements nor headers', async () => {
const {score} = await HreflangAudit.audit({LinkElements: []});
assert.equal(score, 1);
});

it('returns all failing items', () => {
it('returns all failing items', async () => {
const artifacts = {
LinkElements: [
{rel: 'alternate', hreflang: 'xx1', hrefRaw: 'http://xx1.example.com/', source: 'headers', node},
Expand All @@ -86,37 +87,37 @@ describe('SEO: Document has valid hreflang code', () => {
],
};

const {score, details} = HreflangAudit.audit(artifacts);
const {score, details} = await HreflangAudit.audit(artifacts);
assert.equal(score, 0);
assert.equal(details.items.length, 4);
});

it('fails when the hreflang url is not fully-qualified', () => {
it('fails when the hreflang url is not fully-qualified', async () => {
const artifacts = {
LinkElements: [
{rel: 'alternate', hreflang: 'es', hrefRaw: 'example.com', source: 'head', node},
{rel: 'alternate', hreflang: 'es', hrefRaw: '//example.com', source: 'headers', node},
],
};

const {score, details} = HreflangAudit.audit(artifacts);
const {score, details} = await HreflangAudit.audit(artifacts);
assert.equal(score, 0);
assert.equal(details.items.length, 2);
});

it('fails with an invalid language code and a href which is not fully-qualified', () => {
it('fails with an invalid language code and a href which is not fully-qualified', async () => {
const artifacts = {
LinkElements: [
{rel: 'alternate', hreflang: ' es', hrefRaw: 'example.com', source: 'head', node},
{rel: 'alternate', hreflang: 'xx1', hrefRaw: '//example.com', source: 'headers', node},
],
};

const {score} = HreflangAudit.audit(artifacts);
const {score} = await HreflangAudit.audit(artifacts);
assert.equal(score, 0);
});

it('outputs the reasons for which a hreflang failed', () => {
it('outputs the reasons for which a hreflang failed', async () => {
const artifacts = {
LinkElements: [
{rel: 'alternate', hreflang: '@@', hrefRaw: 'example.com', source: 'head', node},
Expand All @@ -126,7 +127,7 @@ describe('SEO: Document has valid hreflang code', () => {
],
};

const {details: {items}} = HreflangAudit.audit(artifacts);
const {details: {items}} = await HreflangAudit.audit(artifacts);

assert.equal(items.length, 3);
assert.equal(items[0].subItems.items.length, 2);
Expand Down
4 changes: 4 additions & 0 deletions third-party/axe/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"type": "module",
Copy link
Member

Choose a reason for hiding this comment

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

directory needs a license/readme (or metadata but readme is fine, honestly): go/thirdparty/non-google3

"//": "Any directory that uses `import ... from` or `export ...` must be type module. Temporary file until root package.json is type: module"
Copy link
Member

Choose a reason for hiding this comment

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

There is no "type": "module" anymore, should this comment refer to the license or can we remove this file?

}
107 changes: 107 additions & 0 deletions third-party/axe/valid-langs.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"build/**/*.js",
"./types/**/*.d.ts",
"eslint-local-rules.js",
"third-party/axe/valid-langs.js",

// TODO(esmodules): JSON files included via resolveJsonModule. Removable on the switch to ES Modules.
"package.json",
Expand Down