UNPKG

1.88 kBPlain TextView Raw
1/**
2 * @license
3 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
4 * This code may only be used under the BSD style license found at
5 * http://polymer.github.io/LICENSE.txt
6 * The complete set of authors may be found at
7 * http://polymer.github.io/AUTHORS.txt
8 * The complete set of contributors may be found at
9 * http://polymer.github.io/CONTRIBUTORS.txt
10 * Code distributed by Google as part of the polymer project is also
11 * subject to an additional IP rights grant found at
12 * http://polymer.github.io/PATENTS.txt
13 */
14
15import * as dom5 from 'dom5/lib/index-next';
16import * as parse5 from 'parse5';
17import File = require('vinyl');
18import {AsyncTransformStream, getFileContents} from './streams';
19import {LocalFsPath} from './path-transformers';
20
21const baseMatcher = dom5.predicates.hasTagName('base');
22
23/**
24 * Find a `<base>` tag in the specified file and if found, update its `href`
25 * with the given new value.
26 */
27export class BaseTagUpdater extends AsyncTransformStream<File, File> {
28 constructor(private filePath: LocalFsPath, private newHref: string) {
29 super({objectMode: true});
30 }
31
32 protected async *
33 _transformIter(files: AsyncIterable<File>): AsyncIterable<File> {
34 for await (const file of files) {
35 if (file.path !== this.filePath) {
36 yield file;
37 continue;
38 }
39
40 const contents = await getFileContents(file);
41 const parsed = parse5.parse(contents, {locationInfo: true});
42 const base = dom5.query(parsed, baseMatcher);
43 if (!base || dom5.getAttribute(base, 'href') === this.newHref) {
44 yield file;
45 continue;
46 }
47
48 dom5.setAttribute(base, 'href', this.newHref);
49 dom5.removeFakeRootElements(parsed);
50 const updatedFile = file.clone();
51 updatedFile.contents = Buffer.from(parse5.serialize(parsed), 'utf-8');
52 yield updatedFile;
53 }
54 }
55}