Debian Codegraph @

vendor/wikimedia/parsoid/bin/diff.html.js

raw
1 #!/usr/bin/env node
2
3 'use strict';
4
5 require('colors');
6 const yaml = require('js-yaml');
7 const fs = require('fs');
8 const Promise = require('../lib/utils/promise.js');
9 const { Diff } = require('../lib/utils/Diff.js');
10 const { DOMUtils } = require('../lib/utils/DOMUtils.js');
11 const { ScriptUtils } = require('../tools/ScriptUtils.js');
12 const XMLSerializer = require('../lib/wt2html/XMLSerializer.js');
13
14 let jsServer = { baseURI: 'http://localhost:8142', proxy: '' };
15 let phpServer = { baseURI: 'http://localhost/rest.php', proxy: '' };
16
17 function normalizeHTML(html, isPHP) {
18 // Normalize about ids
19 html = html.replace(/#mwt[0-9]*/gm, '#mwtX');
20
21 // Normalized unexpanded DOM fragments (T235656)
22 html = html.replace(/mwf[0-9]*/gm, 'mwfX');
23
24 // Remove stray nowiki strip tags left behind by extensions
25 html = html.replace(/UNIQ--nowiki-.*?QINU/gm, '');
26
27 // JS output has bad maplinks (on wikivoyages). Strip out maplink
28 // wrapper in both JS & PHP HTML
29 html = html.replace(/<div class="magnify" title="Enlarge map">.*?<\/div>/gm, '');
30
31 // JS & PHP introduce differing # of significant digits after the decimal
32 // In any case, fractional pixels don't make sense, so simply strip those out.
33 // (T229594 -- Neither PHP nor JS should emit fractional dims here)
34 html = html.replace(/((?:width|height):\s*[0-9]*)(?:\.[0-9]*)?(px)?/gm, '$1$2');
35
36 // Normalize minor variations in dsr (T231570 is one source)
37 // ,null as well as ,null,null (Ex: jawiki:J-WAVE)
38 html = html.replace(/,null,null/gm, '');
39 html = html.replace(/,null/gm, ',0');
40 html = html.replace(/,0,0/gm, '');
41
42 // Parse to DOM for additional normalization easier done
43 // on the DOM vs a HTML string.
44 const body = DOMUtils.parseHTML(html).body;
45 // data-parsoid:
46 // - JS & PHP seem to be inserting some keys in different order
47 // (Ex: jawiki:ICalendar)
48 // Sort keys
49 DOMUtils.visitDOM(body, function(node) {
50 if (DOMUtils.isElt(node)) {
51 if (node.hasAttribute('data-parsoid')) {
52 const dpStr = node.getAttribute('data-parsoid');
53 const dp = JSON.parse(dpStr);
54 const dp2 = {};
55 Object.keys(dp).sort().forEach(function(k) {
56 dp2[k] = dp[k];
57 });
58 node.setAttribute('data-parsoid', JSON.stringify(dp2));
59 }
60 }
61 });
62
63 // Serialize back the parsed DOM - use XMLSerializer for smart quoting.
64 // Return body inner HTML (normalize diffs in <head> and <body> attributes)
65 // This is a lazy normalization. We can do more finer-grained normalization
66 // and include the <head> tag once we narrow down diffs elsewhere.
67 html = XMLSerializer.serialize(body, { innerXML: true, smartQuote: true }).html;
68
69 // Add copious new lines to generate finer-grained diffs
70 return html.replace(/</gm, '\n<');
71 }
72
73 const fetchHTML = Promise.async(function *(server, proxy, domain, title, isPHP) {
74 const httpOptions = {
75 method: 'GET',
76 headers: { 'User-Agent': 'Parsoid-Test' },
77 proxy: proxy,
78 uri: server.replace(/\/$/, '') + '/' + domain + '/v3/page/html/' + encodeURIComponent(title),
79 };
80
81 if (isPHP) {
82 // Append a trailing / to workaround T232556
83 // Request ucs2 offsets to ensure dsr offsets line up
84 httpOptions.uri += '/?offsetType=ucs2';
85 }
86
87 const result = yield ScriptUtils.retryingHTTPRequest(2, httpOptions);
88 return normalizeHTML(result[1], isPHP);
89 });
90
91 function genLineLengths(str) {
92 return str.split(/^/m).map(function(l) {
93 return l.length;
94 });
95 }
96
97 const fetchAllHTML = Promise.async(function *(domain, title) {
98 const jsHTML = yield fetchHTML(jsServer.baseURI, '', domain, title);
99 const phpHTML = yield fetchHTML(phpServer.baseURI.replace(/DOMAIN/, domain), phpServer.proxy, domain, title, true);
100 return {
101 js: {
102 html: jsHTML,
103 lineLens: genLineLengths(jsHTML),
104 },
105 php: {
106 html: phpHTML,
107 lineLens: genLineLengths(phpHTML),
108 }
109 };
110 });
111
112 // Get diff slices from offsets
113 function formatDiff(str1, str2, offset, context) {
114 return [
115 `----- JS:[${ offset[0].start }, ${ offset[0].end }] -----`,
116 str1.slice(offset[0].start - context, offset[0].start).blue +
117 str1.slice(offset[0].start, offset[0].end).green +
118 str1.slice(offset[0].end, offset[0].end + context).blue,
119 `+++++ PHP:[${ offset[1].start }, ${ offset[1].end }] +++++`,
120 str2.slice(offset[1].start - context, offset[1].start).blue +
121 str2.slice(offset[1].start, offset[1].end).red +
122 str2.slice(offset[1].end, offset[1].end + context).blue,
123 ].join('\n');
124 }
125
126 function afterFetch(res) {
127 const diff = Diff.diffLines(res.js.html, res.php.html);
128 const offsets = Diff.convertDiffToOffsetPairs(diff, res.js.lineLens, res.php.lineLens);
129 const lineDiffs = [];
130 if (offsets.length > 0) {
131 for (let i = 0; i < offsets.length; i++) {
132 lineDiffs.push(formatDiff(res.js.html, res.php.html, offsets[i], 0));
133 }
134 }
135 return lineDiffs;
136 }
137
138 function htmlDiff(config, domain, title) {
139 jsServer = config.jsServer || jsServer;
140 phpServer = config.phpServer || phpServer;
141
142 return fetchAllHTML(domain, title)
143 .then(afterFetch)
144 .catch(function(e) {
145 console.error(e);
146 });
147 }
148
149 function fileDiff(jsFilename, phpFilename) {
150 const jsOut = fs.readFileSync(jsFilename, 'utf8');
151 const phpOut = fs.readFileSync(phpFilename, 'utf8');
152 const out = {
153 js: {
154 html: normalizeHTML(jsOut, false),
155 },
156 php: {
157 html: normalizeHTML(phpOut, true),
158 }
159 };
160 out.js.lineLens = genLineLengths(out.js.html);
161 out.php.lineLens = genLineLengths(out.php.html);
162 return afterFetch(out);
163 }
164
165 function displayResult(diffs, domain, title) {
166 domain = domain || '<unknown>';
167 title = title || '<unknown>';
168 if (diffs.length === 0) {
169 console.log(`${ domain }:${ title }: NO HTML DIFFS FOUND!`);
170 } else {
171 console.log(`Parsoid/JS vs. Parsoid/PHP HTML diffs for ${ domain }:${ title }`);
172 console.log(diffs.join('\n'));
173 }
174 }
175
176 if (require.main === module) {
177 const config = yaml.load(fs.readFileSync(process.argv[2], 'utf8'));
178 const domain = process.argv[3];
179 const title = process.argv[4];
180 htmlDiff(config, domain, title).then(function(diffs) {
181 displayResult(diffs, domain, title);
182 }).done();
183 } else if (typeof module === "object") {
184 module.exports.htmlDiff = htmlDiff;
185 module.exports.fileDiff = fileDiff;
186 module.exports.displayResult = displayResult;
187 module.exports.fetchHTML = fetchHTML;
188 }