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

New: Add a standalone parser-html #1277

Closed
wants to merge 12 commits into from
1 change: 1 addition & 0 deletions packages/connector-local/package.json
Original file line number Diff line number Diff line change
@@ -12,6 +12,7 @@
},
"description": "hint local connector",
"devDependencies": {
"@hint/parser-html": "^1.0.0",
alrra marked this conversation as resolved.
Show resolved Hide resolved
"@types/chokidar": "^1.7.5",
"@types/mock-require": "^2.0.0",
"@types/node": "^8.0.14",
57 changes: 50 additions & 7 deletions packages/connector-local/src/connector.ts
Original file line number Diff line number Diff line change
@@ -24,6 +24,7 @@ import { debug as d } from 'hint/dist/src/lib/utils/debug';
import { getAsUri } from 'hint/dist/src/lib/utils/network/as-uri';
import asPathString from 'hint/dist/src/lib/utils/network/as-path-string';
import { getContentTypeData, isTextMediaType, getType } from 'hint/dist/src/lib/utils/content-type';
import { IAsyncHTMLDocument, IAsyncHTMLElement, IAsyncWindow } from 'hint/dist/src/lib/types/async-html';

import isFile from 'hint/dist/src/lib/utils/fs/is-file';
import readFileAsync from 'hint/dist/src/lib/utils/fs/read-file-async';
@@ -32,9 +33,10 @@ import * as logger from 'hint/dist/src/lib/utils/logging';
import {
IConnector,
IFetchOptions,
Event, FetchEnd, ScanEnd, NetworkData
Event, FetchEnd, ScanEnd, NetworkData, CanEvaluateScript
} from 'hint/dist/src/lib/types';
import { Engine } from 'hint/dist/src/lib/engine';
import { HTMLParse } from '@hint/parser-html';

/*
* ------------------------------------------------------------------------------
@@ -47,6 +49,7 @@ const debug: debug.IDebugger = d(__filename);
const defaultOptions = {};

export default class LocalConnector implements IConnector {
private _window: IAsyncWindow = null;
private _options: any;
private engine: Engine;
private _href: string = '';
@@ -57,6 +60,8 @@ export default class LocalConnector implements IConnector {
this._options = Object.assign({}, defaultOptions, config);
this.filesPattern = this.getFilesPattern();
this.engine = engine;

this.engine.on('parse::html::end', this.onParseHTML.bind(this));
}

/*
@@ -85,7 +90,19 @@ export default class LocalConnector implements IConnector {
return [pattern];
}

private async notifyFetch(event: FetchEnd) {
const type = getType(event.response.mediaType);

await this.engine.emitAsync(`fetch::end::${type}`, event);
}

private async fetch(target: string, options?: IFetchOptions) {
const event = await this.fetchData(target, options);

return this.notifyFetch(event);
}

private async fetchData(target: string, options?: IFetchOptions): Promise<FetchEnd> {
/*
* target can have one of these forms:
* - /path/to/file
@@ -99,15 +116,13 @@ export default class LocalConnector implements IConnector {
const uri: url.URL = getAsUri(target);
const filePath: string = asPathString(uri);
const content: NetworkData = await this.fetchContent(filePath, null, options);
const event: FetchEnd = {

return {
element: null,
request: content.request,
resource: url.format(getAsUri(filePath)),
response: content.response
};
const type = getType(event.response.mediaType);

await this.engine.emitAsync(`fetch::end::${type}`, event);
}

private getGitIgnore = async () => {
@@ -243,6 +258,11 @@ export default class LocalConnector implements IConnector {
});
}

private async onParseHTML(event: HTMLParse) {
this._window = event.window;
await this.engine.emitAsync('can-evaluate::script', { resource: this._href } as CanEvaluateScript);
}

/*
* ------------------------------------------------------------------------------
* Public methods
@@ -308,19 +328,42 @@ export default class LocalConnector implements IConnector {
}
}

await Promise.all(files.map((file) => {
return this.fetch(file, options);
const events = await Promise.all<FetchEnd>(files.map((file) => {
return this.fetchData(file, options);
}));

for (let i = 0; i < events.length; i++) {
await this.notifyFetch(events[i]);
}

if (this._options.watch) {
await this.watch(pathString);
} else {
await this.engine.emitAsync('scan::end', initialEvent);
}
}

public evaluate(source: string): Promise<any> {
return Promise.resolve(this._window.evaluate(source));
}

/* istanbul ignore next */
public querySelectorAll(selector: string): Promise<Array<IAsyncHTMLElement>> {
return this._window ? this._window.document.querySelectorAll(selector) : Promise.resolve([]);
}

/* istanbul ignore next */
public close() {
return Promise.resolve();
}

/* istanbul ignore next */
public get dom(): IAsyncHTMLDocument {
return this._window && this._window.document;
}

/* istanbul ignore next */
public get html(): Promise<string> {
return this._window ? this._window.document.pageHTML() : Promise.resolve('');
}
}
3 changes: 2 additions & 1 deletion packages/connector-local/tests/tests.ts
Original file line number Diff line number Diff line change
@@ -23,7 +23,8 @@ test.beforeEach((t) => {
clean() { },
clear() { },
emitAsync() { },
notify() { }
notify() { },
on() { }
};
t.context.isFile = isFile;
});
3 changes: 2 additions & 1 deletion packages/create-parser/src/shared-templates/package.hbs
Original file line number Diff line number Diff line change
@@ -78,7 +78,8 @@
"lint:js": "eslint . --cache --ext js --ext md --ext ts --ignore-path ../../.eslintignore --report-unused-disable-directives",{{else}}
"lint:js": "eslint . --cache --ext js --ext md --ext ts --report-unused-disable-directives",{{/if}}
"lint:md": "markdownlint --ignore CHANGELOG.md *.md",
"test": "npm run lint && npm run build && nyc ava",
"test": "npm run lint && npm run build && nyc ava",{{#if official}}
"test-only": "nyc ava",{{/if}}
alrra marked this conversation as resolved.
Show resolved Hide resolved
"init": "npm install && npm run build",
"watch": "npm run build && npm-run-all --parallel -c watch:*",
"watch:assets": "npm run build:assets -- -w --no-initial",
7 changes: 7 additions & 0 deletions packages/hint/src/lib/types/async-html.ts
Original file line number Diff line number Diff line change
@@ -31,3 +31,10 @@ export interface IAsyncHTMLDocument {
/** The HTML of the page as returned by document.children[0].outerHTML or similar */
pageHTML(): Promise<string>;
}

export interface IAsyncWindow {
/** Returns the document associated with this window */
readonly document: IAsyncHTMLDocument;
/** Run the provided JavaScript in the context of this window */
evaluate(source: string): Promise<any>;
}
21 changes: 20 additions & 1 deletion packages/hint/src/lib/types/jsdom-async-html.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { IAsyncHTMLDocument, IAsyncHTMLElement } from './async-html'; //eslint-disable-line
import { IAsyncHTMLDocument, IAsyncHTMLElement, IAsyncWindow } from './async-html';
import { DOMWindow } from 'jsdom';

/** An implementation of AsyncHTMLDocument on top of JSDDOM */
export class JSDOMAsyncHTMLDocument implements IAsyncHTMLDocument {
@@ -84,3 +85,21 @@ export class JSDOMAsyncHTMLElement implements IAsyncHTMLElement {
return this._ownerDocument;
}
}

export class JSDOMAsyncWindow implements IAsyncWindow {
private _window: DOMWindow;
private _document: JSDOMAsyncHTMLDocument;

public constructor(window: DOMWindow) {
this._window = window;
this._document = new JSDOMAsyncHTMLDocument(window.document);
}

public get document(): IAsyncHTMLDocument {
return this._document;
}

public evaluate(source: string): Promise<any> {
return this._window.eval(source) as any;
}
}
1 change: 1 addition & 0 deletions packages/parser-html/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
201 changes: 201 additions & 0 deletions packages/parser-html/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.

"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:

(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and

(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and

(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and

(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.

You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright JS Foundation and other contributors, https://js.foundation

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.
60 changes: 60 additions & 0 deletions packages/parser-html/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# HTML parser (`@hint/parser-html`)

The `HTML` parser is built on top of [`jsdom`][jsdom] so hints can
analyze `HTML` files.

Note: This parser is currently only needed if using the local
[connector][connectors]. Other connectors provide their own DOM to
generate events instead.

To use it you will have to install it via `npm`:

```bash
npm install @hint/parser-html
```

Note: You can make `npm` install it as a `devDependency` using the
`--save-dev` parameter, or to install it globally, you can use the
`-g` parameter. For other options see [`npm`'s
documentation](https://docs.npmjs.com/cli/install).

And then activate it via the [`.hintrc`][hintrc] configuration file:

```json
{
"connector": {...},
"formatters": [...],
"hints": {
...
},
"parsers": ["html"],
...
}
```

## Events emitted

This `parser` emits the event `parse::html` of type `HTMLParse`
which has the following information:

* `window`: an [`IAsyncWindow`][asynchtml] object containing the
parsed document.
* `html`: a string containing the raw HTML source code.
* `resource`: the parsed resource.

This `parser` also automatically traverses and emits events for
elements in the tree (see [events][events] for details):

* `element::<element-type>`
* `traverse::down`
* `traverse::end`
* `traverse::start`
* `traverse::up`

<!-- Link labels: -->

[asynchtml]: https://webhint.io/docs/contributor-guide/how-to/connector/#iasynchtml
[connectors]: https://webhint.io/docs/user-guide/concepts/connectors/
[events]: https://webhint.io/docs/contributor-guide/getting-started/events/
[hintrc]: https://webhint.io/docs/user-guide/further-configuration/hintrc-formats/
[jsdom]: https://github.com/jsdom/jsdom
74 changes: 74 additions & 0 deletions packages/parser-html/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
{
"ava": {
"failFast": false,
"files": [
"dist/tests/**/*.js"
],
"timeout": "1m"
},
"dependencies": {
"jsdom": "^12.0.0"
},
"description": "webhint parser needed to analyze HTML files",
"devDependencies": {
"@types/jsdom": "^11.0.6",
"ava": "^0.25.0",
"cpx": "^1.5.0",
"eslint": "^5.2.0",
"eslint-plugin-markdown": "^1.0.0-beta.7",
"eslint-plugin-typescript": "^0.12.0",
"eventemitter2": "^5.0.1",
"hint": "^3.2.1",
"markdownlint-cli": "^0.13.0",
"npm-link-check": "^2.0.0",
"npm-run-all": "^4.1.2",
"nyc": "^13.0.1",
"proxyquire": "2.0.0",
"rimraf": "^2.6.2",
"sinon": "^6.1.5",
"typescript": "^3.0.1",
"typescript-eslint-parser": "^18.0.0"
},
"engines": {
"node": ">=8.0.0"
},
"files": [
"dist/src",
"npm-shrinkwrap.json"
],
"homepage": "https://webhint.io/",
"keywords": [
"hint",
"html",
"html-parser"
],
"license": "Apache-2.0",
"main": "dist/src/parser.js",
"name": "@hint/parser-html",
"nyc": {
"extends": "../../.nycrc"
},
"peerDependencies": {
"hint": "^3.2.1"
},
"private": true,
"repository": "webhintio/hint",
"scripts": {
"build": "npm run clean && npm-run-all build:*",
"build-release": "npm run clean && npm run build:assets && tsc --inlineSourceMap false --removeComments true",
"build:assets": "cpx \"./{src,tests}/**/{!(*.ts),.!(ts)}\" dist",
"build:ts": "tsc",
"clean": "rimraf dist",
"lint": "npm-run-all lint:*",
"lint:js": "eslint . --cache --ext js --ext md --ext ts --ignore-path ../../.eslintignore --report-unused-disable-directives",
"lint:md": "markdownlint --ignore CHANGELOG.md *.md",
"test": "npm run lint && npm run build && nyc ava",
"test-only": "nyc ava",
"init": "npm install && npm run build",
"watch": "npm run build && npm-run-all --parallel -c watch:*",
"watch:assets": "npm run build:assets -- -w --no-initial",
"watch:test": "ava --watch",
"watch:ts": "npm run build:ts -- --watch"
},
"version": "1.0.0"
}
76 changes: 76 additions & 0 deletions packages/parser-html/src/parser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* @fileoverview webhint parser needed to analyze HTML files
*/

import { JSDOM } from 'jsdom';
import { JSDOMAsyncHTMLElement, JSDOMAsyncWindow } from 'hint/dist/src/lib/types/jsdom-async-html';
import { Event, ElementFound, FetchEnd, Parser, TraverseDown, TraverseUp } from 'hint/dist/src/lib/types';
import { Engine } from 'hint/dist/src/lib/engine';
import { HTMLParse } from './types';

export { HTMLParse } from './types';

export default class HTMLParser extends Parser {

private _url = '';

public constructor(engine: Engine) {
super(engine, 'html');

engine.on('fetch::end::html', this.onFetchEndHtml.bind(this));
}

private async onFetchEndHtml(fetchEnd: FetchEnd) {
const resource = this._url = fetchEnd.response.url;

const html = fetchEnd.response.body.content;

const dom = new JSDOM(html, {

/** Needed to provide line/column positions for elements. */
includeNodeLocations: true,

/**
* Needed to let hints run script against the DOM.
* However the page itself is kept static because `connector-local`
* validates files individually without loading resources.
*/
runScripts: 'outside-only'

});

const window = new JSDOMAsyncWindow(dom.window);
const documentElement = dom.window.document.documentElement;

await this.engine.emitAsync(`parse::${this.name}::end`, { html, resource, window } as HTMLParse);

const event = { resource } as Event;

await this.engine.emitAsync('traverse::start', event);
await this.traverseAndNotify(documentElement);
await this.engine.emitAsync('traverse::end', event);
}

/** Traverses the DOM while sending `element::typeofelement` events. */
private async traverseAndNotify(element: HTMLElement): Promise<void> {

await this.engine.emitAsync(`element::${element.tagName.toLowerCase()}`, {
element: new JSDOMAsyncHTMLElement(element),
resource: this._url
} as ElementFound);

const traverseEvent = {
element: new JSDOMAsyncHTMLElement(element),
resource: this._url
} as TraverseDown | TraverseUp;

await this.engine.emitAsync(`traverse::down`, traverseEvent);

// Recursively traverse child elements.
for (let i = 0; i < element.children.length; i++) {
await this.traverseAndNotify(element.children[i] as HTMLElement);
}

await this.engine.emitAsync(`traverse::up`, traverseEvent);
}
}
10 changes: 10 additions & 0 deletions packages/parser-html/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Event } from 'hint/dist/src/lib/types/events';
import { IAsyncWindow } from 'hint/dist/src/lib/types/async-html';

/** The object emitted by the `html` parser */
export type HTMLParse = Event & {
/** The raw HTML source code */
html: string;
/** An IAsyncWindow containing the IAsyncHTMLDocument generated from the HTML */
window: IAsyncWindow;
};
117 changes: 117 additions & 0 deletions packages/parser-html/tests/parser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import * as sinon from 'sinon';
import test from 'ava';
import { EventEmitter2 } from 'eventemitter2';

import * as HTMLParser from '../src/parser';

test.beforeEach((t) => {
t.context.engine = new EventEmitter2({
delimiter: '::',
maxListeners: 0,
wildcard: true
});
});

test.serial('If `fetch::end::html` is received, then the code should be parsed and the `parse::html::end` event emitted', async (t) => {
const sandbox = sinon.createSandbox();
const parser = new HTMLParser.default(t.context.engine); // eslint-disable-line new-cap,no-unused-vars
const code = '<!DOCTYPE html><div id="test">Test</div>';

sandbox.spy(t.context.engine, 'emitAsync');

await t.context.engine.emitAsync('fetch::end::html', {
resource: 'test.html',
response: {
body: { content: code },
mediaType: 'text/html',
url: 'test.html'
}
});

const args = t.context.engine.emitAsync.args;
const document = args[1][1].window.document;
const div = (await document.querySelectorAll('div'))[0];
const div2 = (await document.querySelectorAll('body > div'))[0];

let id = null;

for (let i = 0; i < div.attributes.length; i++) {
if (div.attributes[i].name === 'id') {
id = div.attributes[i];
break;
}
}

t.is(args[1][0], 'parse::html::end');
t.is(args[1][1].resource, 'test.html');
t.is(args[1][1].html, code);
t.is(await document.pageHTML(), '<html><head></head><body><div id="test">Test</div></body></html>');
t.is(await div.outerHTML(), '<div id="test">Test</div>');
t.is(div.nodeName.toLowerCase(), 'div');
t.is(div.getAttribute('id'), 'test');
t.is(id.value, 'test');
t.true(div.isSame(div2));

console.log(JSON.stringify(args.map((a) => {
return a[0];
})));

t.is(args[2][0], 'traverse::start');
t.is(args[3][0], 'element::html');
t.is(args[4][0], 'traverse::down');
t.is(args[5][0], 'element::head');
t.is(args[6][0], 'traverse::down');
t.is(args[7][0], 'traverse::up');
t.is(args[8][0], 'element::body');
t.is(args[9][0], 'traverse::down');
t.is(args[10][0], 'element::div');
t.is(args[11][0], 'traverse::down');
t.is(args[12][0], 'traverse::up');
t.is(args[13][0], 'traverse::up');
t.is(args[14][0], 'traverse::up');
t.is(args[15][0], 'traverse::end');

sandbox.restore();
});

test.serial('The `parse::html::end` event should include a window with support for evaluating script', async (t) => {
const sandbox = sinon.createSandbox();
const parser = new HTMLParser.default(t.context.engine); // eslint-disable-line new-cap,no-unused-vars
const code = '<!DOCTYPE html><div id="test">Test</div>';

sandbox.spy(t.context.engine, 'emitAsync');

await t.context.engine.emitAsync('fetch::end::html', {
resource: 'test.html',
response: {
body: { content: code },
mediaType: 'text/html',
url: 'test.html'
}
});

const args = t.context.engine.emitAsync.args;

const window = args[1][1].window;

const result1 = await window.evaluate(`
(function(){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(document.body.firstElementChild.id);
}, 1000);
});
}());
`);

const result2 = await window.evaluate(`
(function(){
return document.getElementsByTagName('div')[0].textContent;
}());
`);

t.is(result1, 'test');
t.is(result2, 'Test');

sandbox.restore();
});
14 changes: 14 additions & 0 deletions packages/parser-html/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"outDir": "dist"
},
"exclude": [
"dist",
"node_modules"
],
"extends": "../../tsconfig.json",
"include": [
"src/**/*.ts",
"tests/**/*.ts"
]
}
315 changes: 146 additions & 169 deletions yarn.lock

Large diffs are not rendered by default.