Debian Codegraph @

vendor/wikimedia/parsoid/bin/roundtrip-test.js

raw
1 #!/usr/bin/env node
2
3 'use strict';
4
5 require('../core-upgrade.js');
6 require('colors');
7
8 var entities = require('entities');
9 var fs = require('fs');
10 var yargs = require('yargs');
11 var zlib = require('pn/zlib');
12
13 var Promise = require('../lib/utils/promise.js');
14 var Util = require('../lib/utils/Util.js').Util;
15 var ScriptUtils = require('../tools/ScriptUtils.js').ScriptUtils;
16 var ContentUtils = require('../lib/utils/ContentUtils.js').ContentUtils;
17 var DOMUtils = require('../lib/utils/DOMUtils.js').DOMUtils;
18 var DOMDataUtils = require('../lib/utils/DOMDataUtils.js').DOMDataUtils;
19 var TestUtils = require('../tests/TestUtils.js').TestUtils;
20 var WTUtils = require('../lib/utils/WTUtils.js').WTUtils;
21 var ParsoidConfig = require('../lib/config/ParsoidConfig.js').ParsoidConfig;
22 var Diff = require('../lib/utils/Diff.js').Diff;
23 var JSUtils = require('../lib/utils/jsutils.js').JSUtils;
24 var MockEnv = require('../tests/MockEnv.js').MockEnv;
25
26 var defaultContentVersion = '2.8.0';
27
28 var MAX_RETRIES = 10;
29
30 function displayDiff(type, count) {
31 var pad = (10 - type.length); // Be positive!
32 type = type[0].toUpperCase() + type.slice(1);
33 return type + ' differences' + ' '.repeat(pad) + ': ' + count + '\n';
34 }
35
36 var jsonFormat = function(error, prefix, title, results, profile) {
37 var diffs = {
38 html2wt: { semantic: 0, syntactic: 0 },
39 selser: { semantic: 0, syntactic: 0 },
40 };
41 if (!error) {
42 results.forEach(function(result) {
43 var mode = diffs[result.selser ? 'selser' : 'html2wt'];
44 mode[result.type === 'fail' ? 'semantic' : 'syntactic']++;
45 });
46 }
47 return {
48 error: error,
49 results: diffs,
50 };
51 };
52
53 var plainFormat = function(err, prefix, title, results, profile) {
54 var testDivider = '='.repeat(70) + '\n';
55 var diffDivider = '-'.repeat(70) + '\n';
56 var output = '';
57
58 if (err) {
59 output += 'Parser failure!\n\n';
60 output += diffDivider;
61 output += err;
62 if (err.stack) {
63 output += '\nStack trace: ' + err.stack;
64 }
65 } else {
66 var diffs = {
67 html2wt: { semantic: 0, syntactic: 0 },
68 selser: { semantic: 0, syntactic: 0 },
69 };
70 for (var i = 0; i < results.length; i++) {
71 var result = results[i];
72 output += testDivider;
73 if (result.type === 'fail') {
74 output += 'Semantic difference' +
75 (result.selser ? ' (selser)' : '') + ':\n\n';
76 output += result.wtDiff + '\n';
77 output += diffDivider + 'HTML diff:\n\n' +
78 result.htmlDiff + '\n';
79 diffs[result.selser ? 'selser' : 'html2wt'].semantic++;
80 } else {
81 output += 'Syntactic difference' +
82 (result.selser ? ' (selser)' : '') + ':\n\n';
83 output += result.wtDiff + '\n';
84 diffs[result.selser ? 'selser' : 'html2wt'].syntactic++;
85 }
86 }
87 output += testDivider;
88 output += testDivider;
89 output += 'SUMMARY:\n';
90 output += diffDivider;
91 var total = 0;
92 Object.keys(diffs).forEach(function(diff) {
93 output += diff + '\n';
94 output += diffDivider;
95 Object.keys(diffs[diff]).forEach(function(type) {
96 var count = diffs[diff][type];
97 total += count;
98 output += displayDiff(type, count);
99 });
100 output += diffDivider;
101 });
102 output += displayDiff('all', total);
103 output += testDivider;
104 output += testDivider;
105 }
106
107 return output;
108 };
109
110 var xmlFormat = function(err, prefix, title, results, profile) {
111 var i, result;
112 var article = Util.escapeHtml(prefix + ':' + title);
113 var output = '<testsuites>\n';
114 var outputTestSuite = function(selser) {
115 output += '<testsuite name="Roundtrip article ' + article;
116 if (selser) {
117 output += ' (selser)';
118 }
119 output += '">\n';
120 };
121
122 if (err) {
123 outputTestSuite(false);
124 output += '<testcase name="entire article">';
125 output += '<error type="parserFailedToFinish">';
126 output += Util.escapeHtml(err.stack || err.toString());
127 output += '</error></testcase>';
128 } else if (!results.length) {
129 outputTestSuite(false);
130 } else {
131 var currentSelser = results[0].selser;
132 outputTestSuite(currentSelser);
133 for (i = 0; i < results.length; i++) {
134 result = results[i];
135
136 // When going from normal to selser results, switch to a new
137 // test suite.
138 if (currentSelser !== result.selser) {
139 output += '</testsuite>\n';
140 currentSelser = result.selser;
141 outputTestSuite(currentSelser);
142 }
143
144 output += '<testcase name="' + article;
145 output += ' character ' + result.offset[0].start + '">\n';
146
147 if (result.type === 'fail') {
148 output += '<failure type="significantHtmlDiff">\n';
149
150 output += '<diff class="wt">\n';
151 output += Util.escapeHtml(result.wtDiff);
152 output += '\n</diff>\n';
153
154 output += '<diff class="html">\n';
155 output += Util.escapeHtml(result.htmlDiff);
156 output += '\n</diff>\n';
157
158 output += '</failure>\n';
159 } else {
160 output += '<skipped type="insignificantWikitextDiff">\n';
161 output += Util.escapeHtml(result.wtDiff);
162 output += '\n</skipped>\n';
163 }
164
165 output += '</testcase>\n';
166 }
167 }
168 output += '</testsuite>\n';
169
170 // Output the profiling data
171 if (profile) {
172 // Delete the start time to avoid serializing it
173 if (profile.time && profile.time.start) {
174 delete profile.time.start;
175 }
176 output += '<perfstats>\n';
177 Object.keys(profile).forEach(function(type) {
178 Object.keys(profile[type]).forEach(function(prop) {
179 output += '<perfstat type="' + TestUtils.encodeXml(type) + ':';
180 output += TestUtils.encodeXml(prop);
181 output += '">';
182 output += TestUtils.encodeXml(profile[type][prop].toString());
183 output += '</perfstat>\n';
184 });
185 });
186 output += '</perfstats>\n';
187 }
188 output += '</testsuites>';
189
190 return output;
191 };
192
193 // Find the subset of leaf/non-leaf nodes whose DSR ranges
194 // span the wikitext range provided as input.
195 var findMatchingNodes = function(node, range) {
196 console.assert(DOMUtils.isElt(node));
197
198 // Skip subtrees that are outside our target range
199 var dp = DOMDataUtils.getDataParsoid(node);
200 if (!Util.isValidDSR(dp.dsr) || dp.dsr[0] > range.end || dp.dsr[1] < range.start) {
201 return [];
202 }
203
204 // If target range subsumes the node, we are done.
205 if (dp.dsr[0] >= range.start && dp.dsr[1] <= range.end) {
206 return [node];
207 }
208
209 // Cannot inspect template content subtree at a finer grained level
210 if (WTUtils.isFirstEncapsulationWrapperNode(node)) {
211 return [node];
212 }
213
214 // Cannot inspect image subtree at a finer grained level
215 var typeOf = node.getAttribute('typeof') || '';
216 if (/\bmw:File(\/|\s|$)/.test(typeOf) && /^(FIGURE|SPAN)$/.test(node.nodeName)) {
217 return [node];
218 }
219
220 // We are in the target range -- examine children.
221 // 1. Walk past nodes that are before our desired range.
222 // 2. Collect nodes within our desired range.
223 // 3. Stop walking once you move beyond the desired range.
224 var elts = [];
225 var offset = dp.dsr[0];
226 var c = node.firstChild;
227 while (c) {
228 if (DOMUtils.isElt(c)) {
229 dp = DOMDataUtils.getDataParsoid(c);
230 var dsr = dp.dsr;
231 if (Util.isValidDSR(dsr)) {
232 if (dsr[1] >= range.start) {
233 // We have an overlap!
234 elts = elts.concat(findMatchingNodes(c, range));
235 }
236 offset = dp.dsr[1];
237 } else {
238 // SSS FIXME: This is defensive coding here.
239 //
240 // This should not happen really anymore.
241 // DSR computation is fairly solid now and
242 // shouldn't be leaving holes.
243 //
244 // If we see no errors in rt-testing runs,
245 // I am going to rip this out.
246
247 console.log("error/diff", "Bad dsr for " + c.nodeName + ": "
248 + c.outerHTML.slice(0, 50));
249
250 if (dp.dsr && typeof (dsr[1]) === 'number') {
251 // We can cope in this case
252 if (dsr[1] >= range.start) {
253 // Update dsr[0]
254 dp.dsr[0] = offset;
255
256 // We have an overlap!
257 elts = elts.concat(findMatchingNodes(c, range));
258 }
259 offset = dp.dsr[1];
260 } else if (offset >= range.start) {
261 // Swallow it wholesale rather than try
262 // to find finer-grained matches in the subtree
263 elts.push(c);
264
265 // offset will now be out-of-sync till we hit
266 // another element with a valid DSR[1] value.
267 }
268 }
269 } else {
270 var len = DOMUtils.isText(c) ? c.nodeValue.length : WTUtils.decodedCommentLength(c);
271 if (offset + len >= range.start) {
272 // We have an overlap!
273 elts.push(c);
274 }
275 offset += len;
276 }
277
278 // All done!
279 if (offset > range.end) {
280 break;
281 }
282
283 // Skip over encapsulated content
284 if (WTUtils.isFirstEncapsulationWrapperNode(c)) {
285 c = WTUtils.skipOverEncapsulatedContent(c);
286 } else {
287 c = c.nextSibling;
288 }
289 }
290
291 return elts;
292 };
293
294 function stripTranscludedWhitespaceSpans(node) {
295 while (node) {
296 const sibling = node.nextSibling;
297 if (DOMUtils.isElt(node)) {
298 const about = node.getAttribute('about');
299 const nTypeOf = node.getAttribute('typeof') || '';
300
301 // remove whitespace spans that are first nodes of a transclusion,
302 // have whitespace content, and transfer attributes to their sibling.
303 if (node.nodeName === 'SPAN' &&
304 /^\s*$/.test(node.textContent) &&
305 /mw:Transclusion/.test(nTypeOf) &&
306 DOMUtils.isElt(sibling) &&
307 sibling.getAttribute('about') === about
308 ) {
309 var sTypeOf = sibling.getAttribute('typeof') || '';
310 if (sTypeOf) {
311 sTypeOf = sTypeOf + ' ' + nTypeOf;
312 } else {
313 sTypeOf = nTypeOf;
314 }
315 sibling.setAttribute('typeof', sTypeOf);
316 sibling.setAttribute('data-mw', node.getAttribute('data-mw'));
317 sibling.setAttribute('data-parsoid', node.getAttribute('data-parsoid'));
318
319 const whitespace = node.ownerDocument.createTextNode(node.textContent);
320 node.parentNode.replaceChild(whitespace, node);
321
322 // Skip transclusion nodes
323 node = sibling;
324 while (node && DOMUtils.isElt(node) && node.getAttribute('about') === about) {
325 node = node.nextSibling;
326 }
327 } else if (/mw:Transclusion/.test(nTypeOf)) {
328 node = WTUtils.skipOverEncapsulatedContent(node);
329 // No skipping to nextSibling here!
330 } else if (node.firstChild) {
331 stripTranscludedWhitespaceSpans(node.firstChild);
332 node = sibling;
333 } else {
334 node = sibling;
335 }
336 } else {
337 node = sibling;
338 }
339 }
340 }
341
342 var getMatchingHTML = function(body, offsetRange, nlDiffs) {
343 // If the diff context straddles a template boundary (*) and if
344 // the HTML context includes the template content in only one
345 // the new/old DOMs, we can falsely flag this as a semantic
346 // diff. To improve the possibility of including the template
347 // content in both DOMs, expand range at both ends by 1 char.
348 //
349 // (*) This happens because our P-wrapping code occasionally
350 // swallows newlines into template context.
351 // See https://phabricator.wikimedia.org/T89628
352 if (nlDiffs) {
353 offsetRange.start -= 1;
354 offsetRange.end += 1;
355 }
356
357 var html = '';
358 var out = findMatchingNodes(body, offsetRange);
359 for (var i = 0; i < out.length; i++) {
360 // node need not be an element always!
361 const node = out[i];
362 DOMDataUtils.visitAndStoreDataAttribs(node);
363 html += ContentUtils.toXML(node, { smartQuote: false });
364 DOMDataUtils.visitAndLoadDataAttribs(node);
365 }
366 html = TestUtils.normalizeOut(html);
367
368 // Normalize away <br/>'s added by Parsoid because of newlines in wikitext.
369 // Do this always, not just when nlDiffs is true, because newline diffs
370 // can show up at extremities of other wt diffs.
371 return html.replace(/<p>\s*<br\s*\/?>\s*/g, '<p>').replace(/<p><\/p>/g, '').replace(/(^\s+|\s+$)/g, '');
372 };
373
374 /* This doesn't try to do a really thorough job of normalization and misses a number
375 * of scenarios, for example, anywhere where sol-transparent markup like comments,
376 * noinclude, category links, etc. are present.
377 *
378 * On the flip side, it can occasionally do incorrect normalization when this markup
379 * is present in extension blocks (nowiki, syntaxhighlight, etc.) where this text
380 * is not really interpreted as wikitext.
381 */
382 function normalizeWikitext(wt, opts) {
383 if (opts.preDiff) {
384 // Whitespace in ordered, unordered, definition lists
385 // Whitespace in first table cell/header, row, and caption
386 wt = wt.replace(/^([*#:;]|\|[-+|]?|!!?)[ \t]*(.*?)[ \t]*$/mg, "$1$1");
387
388 // Whitespace in headings
389 wt = wt.replace(/^(=+)[ \t]*([^\n]*?)[ \t]*(=+)[ \t]*$/mg, "$1$2$3");
390 }
391
392 if (opts.newlines) {
393 // Normalize newlines before/after headings
394 wt = wt.replace(/\n*(\n=[^\n]*=$\n)\n*/mg, "$1");
395
396 // Normalize newlines before lists
397 wt = wt.replace(/(^[^*][^\n]*$\n)\n+([*])/mg, "$1$2");
398 wt = wt.replace(/(^[^#][^\n]*$\n)\n+([#])/mg, "$1$2");
399 wt = wt.replace(/(^[^:][^\n]*$\n)\n+([:])/mg, "$1$2");
400 wt = wt.replace(/(^[^;][^\n]*$\n)\n+([;])/mg, "$1$2");
401
402 // Normalize newlines after lists
403 wt = wt.replace(/(^[*][^\n]*$\n)\n+([^*])/mg, "$1$2");
404 wt = wt.replace(/(^[#][^\n]*$\n)\n+([^#])/mg, "$1$2");
405 wt = wt.replace(/(^[:][^\n]*$\n)\n+([^:])/mg, "$1$2");
406 wt = wt.replace(/(^[;][^\n]*$\n)\n+([^;])/mg, "$1$2");
407
408 // Normalize newlines before/after tables
409 wt = wt.replace(/\n+(\n{\|)/mg, "$1");
410 wt = wt.replace(/(\|}\n)\n+/mg, "$1");
411
412 // Strip leading & trailing newlines
413 wt = wt.replace(/^\n+|\n$/, '');
414 }
415
416 if (opts.postDiff) {
417 // Ignore leading tabs vs. leading spaces
418 wt = wt.replace(/^\t/, ' ');
419 wt = wt.replace(/\n\t/g, '\n ');
420 // Normalize multiple spaces to single space
421 wt = wt.replace(/ +/g, ' ');
422 // Ignore capitalization of tags and void tag indications
423 wt = wt.replace(/<(\/?)([^ >\/]+)((?:[^>\/]|\/(?!>))*)\/?>/g,
424 function(match, close, name, remaining) {
425 return '<' + close + name.toLowerCase() +
426 remaining.replace(/ $/, '') + '>';
427 });
428 // Ignore whitespace in table cell attributes
429 wt = wt.replace(/(^|\n|\|(?=\|)|!(?=!))(\{\||\|[\-+]*|!) *([^|\n]*?) *(?=[|\n]|$)/g, '$1$2$3');
430 // Ignore trailing semicolons and spaces in style attributes
431 wt = wt.replace(/style\s*=\s*"[^"]+"/g, function(match) {
432 return match.replace(/\s|;(?=")/g, '');
433 });
434 // Strip double-quotes
435 wt = wt.replace(/"([^"]*?)"/g, '$1');
436 // Ignore implicit </small> and </center> in table cells or the end
437 // of the wting for now
438 wt = wt.replace(/(^|\n)<\/(?:small|center)>(?=\n[|!]|\n?$)/g, '');
439 wt = wt.replace(/([|!].*?)<\/(?:small|center)>(?=\n[|!]|\n?$)/gi, '$1');
440 }
441
442 return wt;
443 }
444
445 // Get diff slices from offsets
446 var formatDiff = function(oldWt, newWt, offset, context) {
447 return [
448 '------',
449 oldWt.slice(offset[0].start - context, offset[0].start).blue +
450 oldWt.slice(offset[0].start, offset[0].end).green +
451 oldWt.slice(offset[0].end, offset[0].end + context).blue,
452 '++++++',
453 newWt.slice(offset[1].start - context, offset[1].start).blue +
454 newWt.slice(offset[1].start, offset[1].end).red +
455 newWt.slice(offset[1].end, offset[1].end + context).blue,
456 ].join('\n');
457 };
458
459 function stripElementIds(node) {
460 while (node) {
461 if (DOMUtils.isElt(node)) {
462 var id = node.getAttribute('id') || '';
463 if (/^mw[\w-]{2,}$/.test(id)) {
464 node.removeAttribute('id');
465 }
466 if (node.firstChild) {
467 stripElementIds(node.firstChild);
468 }
469 }
470 node = node.nextSibling;
471 }
472 }
473
474 function genSyntacticDiffs(data) {
475 var results = [];
476 var diff = Diff.diffLines(data.oldWt, data.newWt);
477 var offsets = Diff.convertDiffToOffsetPairs(diff, data.oldLineLengths, data.newLineLengths);
478 for (var i = 0; i < offsets.length; i++) {
479 var offset = offsets[i];
480 results.push({
481 type: 'skip',
482 offset: offset,
483 wtDiff: formatDiff(data.oldWt, data.newWt, offset, 0),
484 });
485 }
486 return results;
487 }
488
489 function normalizeDocumentHTML(body) {
490 // Strip whitspace spans that are first elements of a transclusion
491 stripTranscludedWhitespaceSpans(body);
492
493 // Strip 'mw..' ids from the DOMs. This matters for 2 scenarios:
494 // * reduces noise in visual diffs
495 // * all other things being equal after normalization, we don't
496 // assume DOMs are different simply because ids are different
497 stripElementIds(body);
498
499 // Strip section tags from the DOMs
500 ContentUtils.stripUnnecessaryWrappersAndFallbackIds(body);
501 }
502
503 var checkIfSignificant = function(offsets, data) {
504 var oldWt = data.oldWt;
505 var newWt = data.newWt;
506
507 const dummyEnv = new MockEnv({}, null);
508
509 var oldBody = dummyEnv.createDocument(data.oldHTML.body).body;
510 var newBody = dummyEnv.createDocument(data.newHTML.body).body;
511
512 // Merge pagebundles so that HTML nodes can be compared and diff'ed.
513 DOMDataUtils.applyPageBundle(oldBody.ownerDocument, {
514 parsoid: data.oldDp.body,
515 mw: data.oldMw && data.oldMw.body,
516 });
517 DOMDataUtils.applyPageBundle(newBody.ownerDocument, {
518 parsoid: data.newDp.body,
519 mw: data.newMw && data.newMw.body,
520 });
521
522 normalizeDocumentHTML(oldBody.ownerDocument.body);
523 normalizeDocumentHTML(newBody.ownerDocument.body);
524
525 var i, offset;
526 var results = [];
527 // Use the full tests for fostered content.
528 // Fostered/misnested content => semantic diffs.
529 if (!/("|&quot;)(fostered|misnested)("|&quot;)\s*:\s*true\b/.test(oldBody.outerHTML)) {
530 // Quick test for no semantic diffs
531 // If parsoid-normalized HTML for old and new wikitext is identical,
532 // the wt-diffs are purely syntactic.
533 //
534 // FIXME: abstract to ensure same opts are used for parsoidPost and normalizeOut
535 const normOpts = {
536 parsoidOnly: true,
537 // Eliminate spurious semantic errors that may arise because
538 // of the normalization done to new html before it got serialized.
539 // For example,
540 // "== ==" will parse to "<h2><h2>" and then serialize to ""
541 //
542 // FIXME: Normally we would only run this on the old DOM since that is
543 // sufficient. BUT, for links with trailing whitespace like [[Foo ]],
544 // wt2wt has special handling to use syntactic variations from data-parsoid
545 // independent of what the DOM iself says. Try wt2wt on that wikitext to verify.
546 // But, till such time we strip data-parsoid based syntactic variations in
547 // link handlers, run DOM normalizations on both old and new HTML
548 // so that we don't report spurious semantic diffs because of this.
549 // In any case, DOM normalizations are idempotent and so at best, rerunning
550 // DOM normalization is wasteful and not harmful.
551 hackyNormalize: true
552 };
553 const normalizedOld = TestUtils.normalizeOut(oldBody, normOpts);
554 const normalizedNew = TestUtils.normalizeOut(newBody, normOpts);
555 if (normalizedOld === normalizedNew) {
556 return genSyntacticDiffs(data);
557 } else {
558 // Uncomment to log the cause of the failure. This is often useful
559 // for determining the root of non-determinism in rt. See T151474
560 // console.log(Diff.diffLines(normalizedOld, normalizedNew));
561 }
562 }
563
564 /*
565 console.log("---------OLD DOC HTML---------\n" + oldBody.ownerDocument.body.innerHTML);
566 console.log("---------NEW DOC HTML---------\n" + newBody.ownerDocument.body.innerHTML);
567 */
568
569 // FIXME: In this code path below, the returned diffs might
570 // underreport syntactic diffs since these are based on
571 // diffs on normalized wikitext. Unclear how to tackle this.
572
573 // Do this after the quick test above because in `parsoidOnly`
574 // normalization, data-mw is not stripped.
575 DOMDataUtils.visitAndLoadDataAttribs(oldBody);
576 DOMDataUtils.visitAndLoadDataAttribs(newBody);
577
578 // Now, proceed with full blown diffs
579 for (i = 0; i < offsets.length; i++) {
580 offset = offsets[i];
581 var thisResult = { offset: offset };
582
583 // Default: syntactic diff + no diff context
584 thisResult.type = 'skip';
585 thisResult.wtDiff = formatDiff(oldWt, newWt, offset, 0);
586
587 // Is this a newline separator diff?
588 var oldStr = oldWt.slice(offset[0].start, offset[0].end);
589 var newStr = newWt.slice(offset[1].start, offset[1].end);
590 var nlDiffs = /^\s*$/.test(oldStr) && /^\s*$/.test(newStr)
591 && (/\n/.test(oldStr) || /\n/.test(newStr));
592
593 // Check if this is really a semantic diff
594 var oldHTML = getMatchingHTML(oldBody, offset[0], nlDiffs);
595 var newHTML = getMatchingHTML(newBody, offset[1], nlDiffs);
596 var diff = Diff.patchDiff(oldHTML, newHTML);
597 if (diff !== null) {
598 // Normalize wts to check if we really have a semantic diff
599 var wt1 = normalizeWikitext(oldWt.slice(offset[0].start, offset[0].end), { newlines: true, postDiff: true });
600 var wt2 = normalizeWikitext(newWt.slice(offset[1].start, offset[1].end), { newlines: true, postDiff: true });
601 if (wt1 !== wt2) {
602 // Syntatic diff + provide context for semantic diffs
603 thisResult.type = 'fail';
604 thisResult.wtDiff = formatDiff(oldWt, newWt, offset, 25);
605
606 // Don't clog the rt-test server db with humongous diffs
607 if (diff.length > 1000) {
608 diff = diff.slice(0, 1000) + "-- TRUNCATED TO 1000 chars --";
609 }
610 thisResult.htmlDiff = diff;
611 }
612 }
613 results.push(thisResult);
614 }
615
616 return results;
617 };
618
619 var UA = 'Roundtrip-Test';
620
621 var parsoidPost = Promise.async(function *(profile, options) {
622 var httpOptions = {
623 method: 'POST',
624 body: options.data,
625 headers: {
626 'User-Agent': UA,
627 },
628 };
629 // For compatibility with Parsoid/PHP service
630 httpOptions.body.offsetType = 'ucs2';
631
632 var uri = options.uri + 'transform/';
633 if (options.html2wt) {
634 uri += 'pagebundle/to/wikitext/' + options.title;
635 if (options.oldid) {
636 uri += '/' + options.oldid;
637 }
638 // We want to encode the request but *not* decode the response.
639 httpOptions.body = JSON.stringify(httpOptions.body);
640 httpOptions.headers['Content-Type'] = 'application/json';
641 } else { // wt2html
642 uri += 'wikitext/to/pagebundle/' + options.title;
643 if (options.oldid) {
644 uri += '/' + options.oldid;
645 }
646 httpOptions.headers.Accept = 'application/json; charset=utf-8; profile="https://www.mediawiki.org/wiki/Specs/pagebundle/' + options.outputContentVersion + '"';
647 // setting json here encodes the request *and* decodes the response.
648 httpOptions.json = true;
649 }
650 httpOptions.uri = uri;
651 httpOptions.proxy = options.proxy;
652
653 var result = yield issueRequest(httpOptions);
654 var body = result[1];
655
656 // FIXME: Parse time was removed from profiling when we stopped
657 // sending the x-parsoid-performance header.
658 if (options.recordSizes) {
659 var pre = '';
660 if (options.profilePrefix) {
661 pre += options.profilePrefix + ':';
662 }
663 var str;
664
665 // Detect standard error response
666 if ( typeof body === 'object' && body.httpCode >= 400 ) {
667 throw new Error('Received error: ' + body.reason);
668 }
669
670 if (options.html2wt) {
671 pre += 'wt:';
672 str = body;
673 } else {
674 pre += 'html:';
675 str = body.html.body;
676 }
677
678 profile.size[pre + 'raw'] = str.length;
679 // Compress to record the gzipped size
680 var gzippedbuf = yield zlib.gzip(str);
681 profile.size[pre + 'gzip'] = gzippedbuf.length;
682 }
683 return body;
684 });
685
686 function genLineLengths(str) {
687 return str.split(/^/m).map(function(l) {
688 return l.length;
689 });
690 }
691
692 var roundTripDiff = Promise.async(function *(profile, parsoidOptions, data) {
693 var normOpts = { preDiff: true, newlines: true };
694 data.oldLineLengths = genLineLengths(data.oldWt);
695 data.newLineLengths = genLineLengths(data.newWt);
696
697 // Newline normalization to see if we can get to identical wt.
698 var wt1 = normalizeWikitext(data.oldWt, normOpts);
699 var wt2 = normalizeWikitext(data.newWt, normOpts);
700 if (wt1 === wt2) {
701 return genSyntacticDiffs(data);
702 }
703
704 // Do another diff without normalizations
705 // More conservative normalization this time around
706 normOpts.newlines = false;
707 wt1 = normalizeWikitext(data.oldWt, normOpts);
708 wt2 = normalizeWikitext(data.newWt, normOpts);
709 var diff = Diff.diffLines(wt1, wt2);
710 var offsets = Diff.convertDiffToOffsetPairs(diff, data.oldLineLengths, data.newLineLengths);
711 if (!offsets.length) {
712 // FIXME: Can this really happen??
713 return genSyntacticDiffs(data);
714 }
715
716 var contentmodel = data.contentmodel || 'wikitext';
717 var options = Object.assign({
718 wt2html: true,
719 data: { wikitext: data.newWt, contentmodel: contentmodel },
720 }, parsoidOptions);
721 var body = yield parsoidPost(profile, options);
722 data.newHTML = body.html;
723 data.newDp = body['data-parsoid'];
724 data.newMw = body['data-mw'];
725 return checkIfSignificant(offsets, data);
726 });
727
728 // Custom httpClient global variable that can be set by ci tests
729 var httpClient;
730
731 var issueRequest = function(httpOptions) {
732 if (httpClient) {
733 return httpClient.request(httpOptions);
734 } else {
735 return ScriptUtils.retryingHTTPRequest(MAX_RETRIES, httpOptions);
736 }
737 };
738
739 // Returns a Promise for a object containing a formatted string and an
740 // exitCode.
741 var runTests = Promise.async(function *(title, options, formatter) {
742 // Only support lookups for WMF domains. At some point we should rid
743 // ourselves of prefixes in this file entirely, but that'll take some
744 // coordination in rt.
745 var parsoidConfig = new ParsoidConfig(null, { loadWMF: true });
746
747 var domain = options.domain;
748 var prefix = options.prefix;
749
750 if (options.httpClient) {
751 httpClient = options.httpClient;
752 }
753
754 // Preserve the default, but only if neither was provided.
755 if (!prefix && !domain) {
756 domain = 'en.wikipedia.org';
757 }
758
759 if (domain && prefix) {
760 // All good.
761 } else if (!domain && prefix) {
762 // Get the domain from the mw api map.
763 if (parsoidConfig.mwApiMap.has(prefix)) {
764 domain = parsoidConfig.mwApiMap.get(prefix).domain;
765 } else {
766 throw new Error('Couldn\'t find the domain for prefix: ' + prefix);
767 }
768 } else if (!prefix && domain) {
769 // Get the prefix from the reverse mw api map.
770 prefix = parsoidConfig.getPrefixFor(domain);
771 if (!prefix) {
772 // Bogus, but `prefix` is only used for reporting.
773 prefix = domain;
774 }
775 } else {
776 // Should be unreachable.
777 throw new Error('No domain or prefix provided.');
778 }
779
780 const uriOpts = options.parsoidURLOpts;
781 let uri = uriOpts.baseUrl;
782 let proxy;
783 if (uriOpts.proxy) {
784 proxy = uriOpts.proxy.host;
785 if (uriOpts.proxy.port) {
786 proxy += ":" + uriOpts.proxy.port;
787 }
788 // Special support for the WMF cluster
789 uri = uri.replace(/DOMAIN/, domain);
790 }
791
792 // make sure the Parsoid URI ends on /
793 if (!/\/$/.test(uri)) {
794 uri += '/';
795 }
796 var parsoidOptions = {
797 uri: uri + domain + '/v3/',
798 proxy: proxy,
799 title: encodeURIComponent(title),
800 outputContentVersion: options.outputContentVersion || defaultContentVersion,
801 };
802 var uri2 = parsoidOptions.uri + 'page/wikitext/' + parsoidOptions.title;
803 if (options.oldid) {
804 uri2 += '/' + options.oldid;
805 }
806
807 var profile = { time: { total: 0, start: 0 }, size: {} };
808 var data = {};
809 var error;
810 var exitCode;
811 try {
812 var opts;
813 var req = yield issueRequest({
814 method: 'GET',
815 uri: uri2,
816 proxy: proxy,
817 headers: {
818 'User-Agent': UA,
819 },
820 });
821 profile.time.start = JSUtils.startTime();
822 // We may have been redirected to the latest revision. Record the
823 // oldid for later use in selser.
824 data.oldid = req[0].request.path.replace(/^(.*)\//, '');
825 data.oldWt = req[1];
826 data.contentmodel = req[0].headers['x-contentmodel'] || 'wikitext';
827 // First, fetch the HTML for the requested page's wikitext
828 opts = Object.assign({
829 wt2html: true,
830 recordSizes: true,
831 data: { wikitext: data.oldWt, contentmodel: data.contentmodel },
832 }, parsoidOptions);
833 var body = yield parsoidPost(profile, opts);
834
835 // Check for wikitext redirects
836 const redirectMatch = body.html.body.match(/<link rel="mw:PageProp\/redirect" href="([^"]*)"/);
837 if (redirectMatch) {
838 const target = Util.decodeURIComponent(entities.decodeHTML5(redirectMatch[1].replace(/^(\.\/)?/, '')));
839 // Log this so we can collect these and update the database titles
840 console.error(`REDIRECT: ${ prefix }:${ title.replace(/"/g, '\\"') } -> ${ prefix }:${ target.replace(/"/g, '\\"') }`);
841 return yield runTests(target, options, formatter);
842 }
843
844 data.oldHTML = body.html;
845 data.oldDp = body['data-parsoid'];
846 data.oldMw = body['data-mw'];
847 // Now, request the wikitext for the obtained HTML
848 opts = Object.assign({
849 html2wt: true,
850 recordSizes: true,
851 data: {
852 html: data.oldHTML.body,
853 contentmodel: data.contentmodel,
854 original: {
855 'data-parsoid': data.oldDp,
856 'data-mw': data.oldMw,
857 },
858 },
859 }, parsoidOptions);
860 data.newWt = yield parsoidPost(profile, opts);
861 data.diffs = yield roundTripDiff(profile, parsoidOptions, data);
862 // Once we have the diffs between the round-tripped wt,
863 // to test rt selser we need to modify the HTML and request
864 // the wt again to compare with selser, and then concat the
865 // resulting diffs to the ones we got from basic rt
866 var newDocument = DOMUtils.parseHTML(data.oldHTML.body);
867 var newNode = newDocument.createComment('rtSelserEditTestComment');
868 newDocument.body.appendChild(newNode);
869 opts = Object.assign({
870 html2wt: true,
871 useSelser: true,
872 oldid: data.oldid,
873 data: {
874 html: newDocument.outerHTML,
875 contentmodel: data.contentmodel,
876 original: {
877 'data-parsoid': data.oldDp,
878 'data-mw': data.oldMw,
879 wikitext: { body: data.oldWt },
880 html: data.oldHTML,
881 },
882 },
883 profilePrefix: 'selser',
884 }, parsoidOptions);
885 var out = yield parsoidPost(profile, opts);
886 // Finish the total time now
887 // FIXME: Is the right place to end it?
888 profile.time.total = JSUtils.elapsedTime(profile.time.start);
889 // Remove the selser trigger comment
890 data.newWt = out.replace(/<!--rtSelserEditTestComment-->\n*$/, '');
891 var selserDiffs = yield roundTripDiff(profile, parsoidOptions, data);
892 selserDiffs.forEach(function(diff) {
893 diff.selser = true;
894 });
895 if (selserDiffs.length) {
896 data.diffs = data.diffs.concat(selserDiffs);
897 exitCode = 1;
898 } else {
899 exitCode = 0;
900 }
901 } catch (e) {
902 error = e;
903 exitCode = 1;
904 }
905
906 var output = formatter(error, prefix, title, data.diffs, profile);
907
908 return {
909 output: output,
910 exitCode: exitCode
911 };
912 });
913
914
915 if (require.main === module) {
916 var standardOpts = {
917 xml: {
918 description: 'Use xml callback',
919 boolean: true,
920 default: false,
921 },
922 prefix: {
923 description: 'Deprecated. Please provide a domain.',
924 boolean: false,
925 default: '',
926 },
927 domain: {
928 description: 'Which wiki to use; e.g. "en.wikipedia.org" for' +
929 ' English wikipedia',
930 boolean: false,
931 default: '', // Add a default when `prefix` is removed.
932 },
933 oldid: {
934 description: 'Optional oldid of the given page. If not given,' +
935 ' will use the latest revision.',
936 boolean: false,
937 default: null,
938 },
939 parsoidURL: {
940 description: 'The URL for the Parsoid API',
941 boolean: false,
942 default: '',
943 },
944 proxyURL: {
945 description: 'URL (with protocol and port, if any) for the proxy fronting Parsoid',
946 boolean: false,
947 default: null,
948 },
949 apiURL: {
950 description: 'http path to remote API,' +
951 ' e.g. http://en.wikipedia.org/w/api.php',
952 boolean: false,
953 default: '',
954 },
955 outputContentVersion: {
956 description: 'The acceptable content version.',
957 boolean: false,
958 default: defaultContentVersion,
959 },
960 check: {
961 description: 'Exit with non-zero exit code if differences found using selser',
962 boolean: true,
963 default: false,
964 alias: 'c',
965 },
966 };
967
968 Promise.async(function *() {
969 var opts = yargs
970 .usage(
971 'Usage: $0 [options] <page-title> \n' +
972 'The page title should be the "true title",' +
973 'i.e., without any url encoding which might be necessary if it appeared in wikitext.' +
974 '\n\n'
975 )
976 .options(standardOpts)
977 .strict();
978
979 var argv = opts.argv;
980 if (!argv._.length) {
981 return opts.showHelp();
982 }
983 var title = String(argv._[0]);
984
985 if (!argv.parsoidURL) {
986 throw new Error('No parsoidURL provided!');
987 }
988 argv.parsoidURLOpts = { baseUrl: argv.parsoidURL };
989 if (argv.proxyURL) {
990 argv.parsoidURLOpts.proxy = { host: argv.proxyURL };
991 }
992 var formatter = ScriptUtils.booleanOption(argv.xml) ? xmlFormat : plainFormat;
993 var r = yield runTests(title, argv, formatter);
994 console.log(r.output);
995 if (argv.check) {
996 process.exit(r.exitCode);
997 }
998 })().done();
999 } else if (typeof module === 'object') {
1000 module.exports.runTests = runTests;
1001 module.exports.jsonFormat = jsonFormat;
1002 module.exports.plainFormat = plainFormat;
1003 module.exports.xmlFormat = xmlFormat;
1004 }