1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | import * as dom5 from 'dom5/lib/index-next';
|
16 | import * as parse5 from 'parse5';
|
17 | import File = require('vinyl');
|
18 | import {AsyncTransformStream, getFileContents} from './streams';
|
19 | import {LocalFsPath} from './path-transformers';
|
20 |
|
21 | const baseMatcher = dom5.predicates.hasTagName('base');
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | export 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 | }
|