@typeroll/mcp-server 0.45.168 → 0.45.169

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/AGENTS.md +2 -1
  2. package/dist/bundled-content.js +26 -13
  3. package/dist/server.js +4 -0
  4. package/dist/tools/apps.js +33 -0
  5. package/dist/tools/fonts.js +1 -1
  6. package/dist/tools/forms.js +4 -3
  7. package/dist/tools/media.js +2 -2
  8. package/dist/tools/migration.js +1 -1
  9. package/dist/tools/pages.js +4 -0
  10. package/dist/tools/preview.js +4 -0
  11. package/dist/tools/settings.js +1 -1
  12. package/dist/tools/styles.js +1 -1
  13. package/dist/version.d.ts +1 -1
  14. package/dist/version.js +1 -1
  15. package/dist/workspace.d.ts +1 -1
  16. package/dist/workspace.js +17 -8
  17. package/package.json +1 -1
  18. package/skills/tr-brand.md +1 -1
  19. package/skills/tr-migrate-astro.md +4 -13
  20. package/skills/tr-migrate-multisite.md +10 -31
  21. package/skills/tr-migrate-wp.md +73 -384
  22. package/skills/tr-responsive.md +14 -0
  23. package/workspace-templates/scripts/README.md +18 -0
  24. package/workspace-templates/scripts/typeroll/browser.cjs +6 -1
  25. package/workspace-templates/scripts/typeroll/call.py +5 -2
  26. package/workspace-templates/scripts/typeroll/css_report.py +45 -0
  27. package/workspace-templates/scripts/typeroll/inventory.py +264 -0
  28. package/workspace-templates/scripts/typeroll/media_fit.py +112 -0
  29. package/workspace-templates/scripts/typeroll/migration.py +254 -0
  30. package/workspace-templates/scripts/typeroll/page_part.cjs +34 -0
  31. package/workspace-templates/scripts/typeroll/page_source.py +148 -0
  32. package/workspace-templates/scripts/typeroll/pages.py +156 -0
  33. package/workspace-templates/scripts/typeroll/read_pages.cjs +169 -0
  34. package/workspace-templates/scripts/typeroll/shoot_hosted.cjs +13 -6
  35. package/workspace-templates/scripts/typeroll/trlib.py +45 -7
  36. package/workspace-templates/scripts/typeroll/verify_migration.cjs +47 -0
  37. package/workspace-templates/scripts/typeroll/verify_migration.py +274 -0
  38. package/workspace-templates/scripts/typeroll/write_pages.py +542 -0
  39. package/workspace-templates/skills/typeroll-migrate-sources.md +36 -0
  40. package/workspace-templates/skills/typeroll-migrate.md +109 -0
  41. package/workspace-templates/workflows/design.md +1 -1
  42. package/workspace-templates/workflows/migration.md +12 -5
@@ -0,0 +1,169 @@
1
+ // Save what a visitor sees: pictures, texts in order, links and media. It says nothing about what a page is.
2
+ // Usage: node read_pages.cjs PLAN.json ({pages:[{url,key,name}], out, screens}); paced, public pages only.
3
+ const qa = require('./browser.cjs');
4
+ const fs = require('node:fs/promises');
5
+ const path = require('node:path');
6
+
7
+ // Runs in the page. Marks what is hidden, and header, footer and menus where the page
8
+ // says so itself, so the saved copy can be read later without the site's CSS.
9
+ function look() {
10
+ const words = text => (text || '').replace(/\s+/g, ' ').trim();
11
+ const visible = el => {
12
+ const style = getComputedStyle(el);
13
+ if (style.display === 'none' || style.visibility === 'hidden') return false;
14
+ if (style.display === 'contents') return true;
15
+ const box = el.getBoundingClientRect();
16
+ return box.width > 1 && box.height > 1 || [...el.children].some(visible);
17
+ };
18
+ // A closed panel a visitor can open is content.
19
+ const opens = el => el.closest('details') || (el.id && document.querySelector(`[aria-controls~="${CSS.escape(el.id)}"]`));
20
+ const walkHidden = el => {
21
+ for (const child of el.children) {
22
+ if (/^(SCRIPT|STYLE|LINK|META|TEMPLATE|NOSCRIPT|SOURCE|BR|WBR)$/.test(child.tagName)) continue;
23
+ if (!visible(child) && !opens(child)) child.setAttribute('data-tr-hidden', '');
24
+ else walkHidden(child);
25
+ }
26
+ };
27
+ walkHidden(document.body);
28
+ for (const el of document.querySelectorAll('header, footer, nav, [role=banner], [role=contentinfo], [role=navigation], [role=search], dialog, [aria-modal=true], [id*=cookie i], [class*=cookie i], [id*=consent i], [class*=consent i]')) {
29
+ if (el.closest('article header, article footer') && !/^(NAV|DIALOG)$/.test(el.tagName)) continue;
30
+ if (el === document.body || el.contains(document.querySelector('h1')) && !/^(FOOTER|NAV|DIALOG)$/.test(el.tagName)) continue;
31
+ el.setAttribute('data-tr-chrome', '');
32
+ }
33
+ const skip = el => el.closest('[data-tr-hidden], [data-tr-chrome], script, style, noscript, template');
34
+ for (const img of document.images) if (img.currentSrc || img.src) img.setAttribute('src', img.currentSrc || img.src);
35
+ for (const el of document.querySelectorAll('a[href]')) el.setAttribute('href', el.href);
36
+ for (const el of document.querySelectorAll('iframe')) if (el.src || el.dataset.src) el.setAttribute('src', el.src || new URL(el.dataset.src, location.href).href);
37
+ // A player can be a frame, a file, or an element that builds its frame later.
38
+ const player = /(?:youtube(?:-nocookie)?\.com\/(?:embed\/|watch\?|shorts\/)|youtu\.be\/|vimeo\.com\/(?:video\/)?\d)/i;
39
+ const videoOf = el => {
40
+ if (el.matches('video')) return el.currentSrc || el.src || el.querySelector('source[src]')?.src || '';
41
+ if (el.matches('iframe')) return el.src || '';
42
+ if (/youtube|vimeo/i.test(el.tagName)) {
43
+ const id = el.getAttribute('videoid') || el.getAttribute('video-id');
44
+ if (id && /^[\w-]{6,20}$/.test(id)) return /vimeo/i.test(el.tagName) ? `https://vimeo.com/${id}` : `https://www.youtube.com/watch?v=${id}`;
45
+ }
46
+ if (/^(A|LINK|META|SCRIPT|IMG)$/.test(el.tagName)) return '';
47
+ return [...el.attributes].filter(item => /^(data-|src$)/.test(item.name)).map(item => item.value.match(/https?:\/\/[^\s"'\\&]+/)?.[0] || '').find(value => player.test(value)) || '';
48
+ };
49
+ for (const el of document.body.querySelectorAll('*')) {
50
+ if (skip(el) || el.closest('[data-tr-video]')) continue;
51
+ const found = videoOf(el);
52
+ if (found && (el.matches('video') || player.test(found))) el.setAttribute('data-tr-video', found);
53
+ }
54
+ for (const el of document.body.querySelectorAll('*')) {
55
+ if (skip(el)) continue;
56
+ const style = getComputedStyle(el);
57
+ const picture = style.backgroundImage.match(/url\("?([^")]+)"?\)/);
58
+ if (picture && !picture[1].startsWith('data:')) el.setAttribute('data-tr-bg', picture[1]);
59
+ }
60
+ // A short address for an element, stable on this saved page.
61
+ const address = el => {
62
+ const parts = [];
63
+ for (let node = el; node && node !== document.body; node = node.parentElement) {
64
+ if (node.id && document.querySelectorAll('#' + CSS.escape(node.id)).length === 1) { parts.unshift('#' + CSS.escape(node.id)); break; }
65
+ const same = [...node.parentElement.children].filter(item => item.tagName === node.tagName);
66
+ parts.unshift(node.tagName.toLowerCase() + (same.length > 1 ? `:nth-of-type(${same.indexOf(node) + 1})` : ''));
67
+ }
68
+ // From body, unless an id starts it, so a selector cannot also fit a nested element.
69
+ return (parts[0]?.startsWith('#') ? '' : 'body > ') + parts.join(' > ');
70
+ };
71
+ const outline = [];
72
+ const add = (kind, item) => outline.push({ kind, ...item });
73
+ const visit = el => {
74
+ for (const child of el.children) {
75
+ if (skip(child) || /^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE|SVG)$/i.test(child.tagName)) continue;
76
+ const base = { at: address(child) };
77
+ if (/^H[1-6]$/.test(child.tagName)) add(child.tagName.toLowerCase(), { ...base, text: words(child.innerText) });
78
+ else if (child.matches('img')) {
79
+ // Lazy pictures keep the real file in a data attribute until they scroll into view.
80
+ const real = [child.currentSrc, child.src, child.dataset.src, child.dataset.lazySrc].find(value => value && !value.startsWith('data:')) || '';
81
+ const link = child.closest('a[href]');
82
+ if (real) add('image', { ...base, src: real, alt: child.alt, ...(link ? { href: link.href } : {}) });
83
+ }
84
+ else if (child.matches('iframe, video') || child.hasAttribute('data-tr-video')) add('video', { ...base, src: child.getAttribute('data-tr-video') || child.src });
85
+ else if (child.matches('form')) add('form', { ...base, fields: [...child.elements].filter(item => item.name && item.type !== 'hidden').map(item => ({
86
+ name: item.name, type: item.type || item.tagName.toLowerCase(), label: words(item.labels?.[0]?.innerText || item.getAttribute('aria-label') || item.placeholder || ''),
87
+ ...(item.required ? { required: true } : {}), ...(item.matches('select') ? { choices: [...item.options].map(option => words(option.text)) } : {}) })) });
88
+ else if (child.matches('select')) add('menu', { ...base, text: words(child.labels?.[0]?.innerText || child.getAttribute('aria-label') || ''), choices: [...child.options].map(option => words(option.text)) });
89
+ else if (child.matches('table')) add('table', { ...base, text: words(child.innerText) });
90
+ else if (child.matches('a[href]') && !child.querySelector('img, h1, h2, h3, h4, h5, h6, p'))
91
+ // Icon links (share buttons, social profiles) have no text; their name is in a label.
92
+ add('link', { ...base, text: words(child.innerText) || words(child.getAttribute('aria-label') || child.title || '') || '(icon without a name)', href: child.href });
93
+ else if (child.matches('ul, ol') && !child.querySelector('img')) {
94
+ const links = [...child.querySelectorAll('a[href]')].map(link => `${words(link.innerText) || link.getAttribute('aria-label') || ''} -> ${link.href}`);
95
+ add('list', { ...base, text: words(child.innerText), ...(links.length ? { links } : {}) });
96
+ }
97
+ else if (child.matches('p, blockquote, pre, dl') && !child.querySelector('img, iframe, form')) { if (words(child.innerText)) add('text', { ...base, text: words(child.innerText) }); }
98
+ else {
99
+ if (child.hasAttribute('data-tr-bg') && child.getAttribute('data-tr-bg') !== child.parentElement.closest('[data-tr-bg]')?.getAttribute('data-tr-bg')) add('picture', { ...base, src: child.getAttribute('data-tr-bg') });
100
+ const own = words([...child.childNodes].filter(node => node.nodeType === 3).map(node => node.data).join(' '));
101
+ if (own) add('text', { ...base, text: words(child.innerText) });
102
+ else visit(child);
103
+ }
104
+ }
105
+ };
106
+ visit(document.body);
107
+ // Parts from other sites (a badge, a widget) and pictures with clickable regions, header and footer included:
108
+ // no Core block may fit them, so they are listed for a person to decide. Films are listed under videos.
109
+ const ownHost = host => host.replace(/^www\./, '') === location.hostname.replace(/^www\./, '');
110
+ const films = new Set([...document.querySelectorAll('[data-tr-video]')].map(el => el.getAttribute('data-tr-video')));
111
+ const outside = [];
112
+ for (const el of document.querySelectorAll('img, iframe, object, embed')) {
113
+ if (el.closest('[data-tr-hidden], script, noscript, template')) continue;
114
+ const src = el.getAttribute('src') || el.getAttribute('data') || '';
115
+ let host = '';
116
+ try { host = new URL(src, location.href).hostname; } catch { /* not an address */ }
117
+ if (el.matches('img[usemap]')) outside.push({ kind: 'image_map', src, areas: document.querySelectorAll(`map[name="${CSS.escape(el.useMap.replace(/^#/, ''))}"] area`).length });
118
+ else if (host && !ownHost(host) && !films.has(src) && !src.startsWith('data:')) outside.push({ kind: el.tagName.toLowerCase(), src, host });
119
+ }
120
+ const meta = name => document.querySelector(`meta[property="${name}"], meta[name="${name}"]`)?.content || '';
121
+ const links = [...new Set([...document.querySelectorAll('a[href]')].map(el => el.href))];
122
+ const copy = document.body.cloneNode(true);
123
+ copy.querySelectorAll('script, style, noscript, template, link').forEach(el => el.remove());
124
+ copy.querySelectorAll('*').forEach(el => [...el.attributes].forEach(item => { if (/^on/i.test(item.name) || item.name === 'style' || item.name === 'srcset') el.removeAttribute(item.name); }));
125
+ return { url: location.href, title: document.title, lang: document.documentElement.lang, description: meta('description'), share_image: meta('og:image'),
126
+ published: meta('article:published_time') || document.querySelector('time[datetime]')?.dateTime || '', kind: meta('og:type'), noindex: /noindex/i.test(meta('robots')),
127
+ h1: [...document.querySelectorAll('h1')].filter(el => !el.closest('[data-tr-hidden]')).length, forms: [...document.forms].filter(el => !skip(el)).length,
128
+ videos: [...new Set([...document.querySelectorAll('[data-tr-video]')].filter(el => !skip(el)).map(el => el.getAttribute('data-tr-video')))], outside, links, outline, html: copy.innerHTML };
129
+ }
130
+
131
+ async function main() {
132
+ const plan = JSON.parse(await fs.readFile(process.argv[2], 'utf8'));
133
+ await fs.mkdir(plan.out, { recursive: true });
134
+ await fs.mkdir(plan.screens, { recursive: true });
135
+ const browser = await qa.chromium.launch();
136
+ let done = 0, failed = 0;
137
+ try {
138
+ for (const item of plan.pages) {
139
+ const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });
140
+ try {
141
+ await qa.open(page, item.url);
142
+ await qa.settle(page);
143
+ // What a person has to look at before deciding what the page is.
144
+ const shot = async width => page.screenshot({ path: path.join(plan.screens, `${item.name}-${width}.jpg`), type: 'jpeg', quality: 60, fullPage: true, animations: 'disabled' });
145
+ await shot(1280);
146
+ const found = await page.evaluate(look);
147
+ await page.setViewportSize({ width: 390, height: 844 });
148
+ await qa.settle(page);
149
+ await shot(390);
150
+ const file = path.join(plan.out, `${item.key}.json`);
151
+ await fs.writeFile(file + '.part', JSON.stringify({ ...found, screens: [1280, 390].map(width => `${item.name}-${width}.jpg`) }));
152
+ await fs.rename(file + '.part', file);
153
+ done++;
154
+ } catch (error) {
155
+ failed++;
156
+ // Public pages of the old site, so the address and the reason may be shown.
157
+ console.error(`Not read: ${new URL(item.url).pathname} (${String(error.message || error).split('\n')[0].slice(0, 160)})`);
158
+ }
159
+ await page.close();
160
+ if ((done + failed) % 10 === 0) console.error(`${done + failed} of ${plan.pages.length} pages opened`);
161
+ }
162
+ } finally { await browser.close(); }
163
+ }
164
+ if (require.main === module) main().catch(error => {
165
+ console.error(/Cannot find module|Executable doesn't exist/.test(String(error.message))
166
+ ? 'Playwright or its browser is missing: see scripts/README.md for the two install commands.' : String(error.message || error).split('\n')[0]);
167
+ process.exitCode = 2;
168
+ });
169
+ module.exports = { look };
@@ -10,17 +10,24 @@ const [origin, out, paths, ...args] = process.argv.slice(2);
10
10
  for (const width of qa.widths(args)) {
11
11
  const page = await browser.newPage({ viewport: { width, height: 900 } });
12
12
  const failed = [];
13
+ // A name a person can match to the page; query strings are never written out.
14
+ const name = (url.pathname.replace(/[^a-z0-9]+/gi, '-').replace(/^-|-$/g, '').slice(0, 60) || 'start')
15
+ + '-' + require('node:crypto').createHash('sha256').update(route).digest('hex').slice(0, 6);
13
16
  page.on('requestfailed', r => failed.push({ host: new URL(r.url()).hostname, kind: 'network' }));
14
17
  page.on('response', r => { if (r.status() >= 400) failed.push({ host: new URL(r.url()).hostname, status: r.status() }); });
15
- await qa.open(page, url.href); await qa.settle(page);
16
- const result = { path: route, width, ...await qa.inspect(page), failed };
17
- const name = require('node:crypto').createHash('sha256').update(route).digest('hex').slice(0, 12);
18
- await qa.screenshot(page, `${out}/${name}-${width}.png`);
19
- report.push(result);
18
+ try {
19
+ await qa.open(page, url.href); await qa.settle(page);
20
+ const result = { path: route, width, ...await qa.inspect(page), failed };
21
+ await qa.screenshot(page, `${out}/${name}-${width}.png`);
22
+ report.push({ ...result, file: `${name}-${width}.png` });
23
+ } catch {
24
+ // One page that does not open says nothing about the others.
25
+ report.push({ path: route, width, notOpened: true, failed });
26
+ }
20
27
  await page.close();
21
28
  }
22
29
  }
23
30
  console.log(JSON.stringify(report, null, 2));
24
- if (report.some(r => r.overflow || r.incompleteImages.length || r.h1 !== 1 || r.failed.length || !r.scrollCoverageComplete)) process.exitCode = 1;
31
+ if (report.some(r => r.notOpened || r.overflow || r.incompleteImages.length || r.h1 !== 1 || r.failed.length || !r.scrollCoverageComplete)) process.exitCode = 1;
25
32
  } finally { await browser.close(); }
26
33
  })().catch(qa.fail);
@@ -3,8 +3,12 @@ No automatic retries for mutations. Run from the workspace root.
3
3
  """
4
4
  import hashlib
5
5
  import json
6
+ import time
7
+ import sys
6
8
  import os
7
9
  from pathlib import Path
10
+ import re
11
+ import threading
8
12
  import urllib.error
9
13
  import urllib.parse
10
14
  import urllib.request
@@ -60,10 +64,18 @@ class Client:
60
64
  self.session = None
61
65
  self.sequence = 0
62
66
  self.tools = None
67
+ self.server_version = None
63
68
  self.verified = False
64
69
  self.opener = urllib.request.build_opener(NoRedirect)
70
+ # One MCP session answers one request at a time: calls from several
71
+ # threads wait for each other instead of reading each other's answers.
72
+ self.lock = threading.RLock()
65
73
 
66
74
  def rpc(self, method, params=None, notify=False):
75
+ with self.lock:
76
+ return self._rpc(method, params, notify)
77
+
78
+ def _rpc(self, method, params, notify):
67
79
  self.sequence += 1
68
80
  body = {'jsonrpc': '2.0', 'method': method}
69
81
  if params is not None:
@@ -87,6 +99,9 @@ class Client:
87
99
  raw = response.read().decode()
88
100
  except urllib.error.HTTPError as error:
89
101
  raise RuntimeError(f'MCP HTTP {error.code}; no mutation was retried') from None
102
+ except (urllib.error.URLError, TimeoutError, ConnectionError) as error:
103
+ reason = getattr(error, 'reason', None) or type(error).__name__
104
+ raise RuntimeError(f'No answer from the portal ({reason}); check the network. A write may or may not have been made; read before trying again') from None
90
105
  if notify:
91
106
  return None
92
107
  result = decode_rpc(raw, self.sequence)
@@ -95,8 +110,9 @@ class Client:
95
110
  return result['result']
96
111
 
97
112
  def initialize(self):
98
- self.rpc('initialize', {'protocolVersion': '2025-03-26', 'capabilities': {},
99
- 'clientInfo': {'name': 'typeroll-workspace', 'version': '1'}})
113
+ answer = self.rpc('initialize', {'protocolVersion': '2025-03-26', 'capabilities': {},
114
+ 'clientInfo': {'name': 'typeroll-workspace', 'version': '1'}})
115
+ self.server_version = ((answer or {}).get('serverInfo') or {}).get('version')
100
116
  self.rpc('notifications/initialized', notify=True)
101
117
  self.tools = {}
102
118
  cursor = None
@@ -112,6 +128,10 @@ class Client:
112
128
  seen.add(cursor)
113
129
 
114
130
  def call(self, tool, args=None):
131
+ with self.lock:
132
+ return self._call(tool, args)
133
+
134
+ def _call(self, tool, args):
115
135
  if self.tools is None:
116
136
  self.initialize()
117
137
  if tool not in self.tools:
@@ -133,9 +153,19 @@ class Client:
133
153
  data[key] = wanted
134
154
  if 'version' not in props and self.config['version'] != 'main' and tool != 'get_site':
135
155
  raise ValueError(f'{tool} has no version parameter; refusing an implicit main-version operation')
136
- result = self.rpc('tools/call', {'name': tool, 'arguments': data})
137
- if result.get('isError'):
138
- raise RuntimeError(f'{tool} failed; inspect through your authenticated MCP client (no retry)')
156
+ for attempt in range(4):
157
+ result = self.rpc('tools/call', {'name': tool, 'arguments': data})
158
+ if not result.get('isError'):
159
+ break
160
+ # The reason comes from Typeroll. Addresses are cut: one can carry a signature.
161
+ reason = ' '.join(c.get('text', '') for c in result.get('content') or [] if c.get('type') == 'text')
162
+ reason = ' '.join(re.sub(r'https?://\S+', '(address)', reason).split())[:300]
163
+ # A refused call wrote nothing, so it is asked again once the limit's minute has passed.
164
+ if 'rate limit exceeded' in reason.lower() and attempt < 3:
165
+ print(f'{tool}: rate limit reached; asking again in 65 seconds', file=sys.stderr)
166
+ time.sleep(65)
167
+ continue
168
+ raise RuntimeError(f'{tool} failed (no retry): {reason or "no reason given"}')
139
169
  if 'structuredContent' in result:
140
170
  return result['structuredContent']
141
171
  text = ''.join(c.get('text', '') for c in result.get('content', []) if c.get('type') == 'text')
@@ -162,15 +192,23 @@ def decode_rpc(raw, request_id):
162
192
 
163
193
 
164
194
  _client = None
195
+ _client_lock = threading.Lock()
165
196
 
166
197
 
167
198
  def call(tool, args=None):
168
199
  global _client
169
- if _client is None:
170
- _client = Client()
200
+ with _client_lock:
201
+ if _client is None:
202
+ _client = Client()
171
203
  return _client.call(tool, args)
172
204
 
173
205
 
206
+ def server_version():
207
+ """The version of the MCP server this workspace is connected to."""
208
+ call('get_site')
209
+ return _client.server_version
210
+
211
+
174
212
  def site_id():
175
213
  return workspace()['site_id']
176
214
 
@@ -0,0 +1,47 @@
1
+ // Browser part of verify_migration.py: image sizes on every page, and sample pages at two widths.
2
+ const qa = require('./browser.cjs');
3
+ const fs = require('node:fs/promises');
4
+ const path = require('node:path');
5
+ function images() {
6
+ // Only images that take part in the layout: hidden ones have no boxes by design.
7
+ return [...document.images].flatMap(img => {
8
+ const box = img.getBoundingClientRect(), style = getComputedStyle(img);
9
+ const hidden = !img.checkVisibility?.({ checkOpacity: false, checkVisibilityCSS: true }) || style.display === 'none' || Boolean(img.closest('[hidden], [aria-hidden="true"], details:not([open]), dialog:not([open])'));
10
+ if (hidden) return [];
11
+ const name = new URL(img.currentSrc || img.src, location.href).pathname.split('/').pop();
12
+ if (!img.complete || !img.naturalWidth) return [`an image does not load: ${name}`];
13
+ if (box.width < 2 || box.height < 2) return [`an image has no size: ${name}`];
14
+ const shape = box.width / box.height, real = img.naturalWidth / img.naturalHeight;
15
+ if (style.objectFit === 'fill' && Math.abs(shape / real - 1) > 0.05) return [`an image is stretched: ${name}`];
16
+ return [];
17
+ });
18
+ }
19
+ async function main() {
20
+ const plan = JSON.parse(await fs.readFile(process.argv[2], 'utf8'));
21
+ const found = Object.fromEntries(plan.paths.map(item => [item, []]));
22
+ const browser = await qa.chromium.launch();
23
+ try {
24
+ for (const width of plan.widths) {
25
+ // The wide view covers every page; the narrow one the samples.
26
+ const wide = width === Math.max(...plan.widths);
27
+ const page = await browser.newPage({ viewport: { width, height: 900 } });
28
+ for (const item of wide ? plan.paths : plan.sample) {
29
+ const note = text => { (found[item] ??= []).includes(text) || found[item].push(text); };
30
+ try {
31
+ await qa.open(page, plan.origin + item); await qa.settle(page);
32
+ } catch { note(`does not open in a browser at ${width} px`); continue; }
33
+ for (const text of await page.evaluate(images)) note(text);
34
+ const result = await qa.inspect(page);
35
+ if (result.overflow) note(`wider than the window at ${width} px`);
36
+ if (plan.sample.includes(item)) {
37
+ const name = (item.replace(/^\/|\/$/g, '').replace(/[^a-z0-9]+/gi, '-') || 'home') + `-${width}.png`;
38
+ await qa.screenshot(page, path.join(plan.out, name));
39
+ }
40
+ }
41
+ await page.close();
42
+ }
43
+ } finally { await browser.close(); }
44
+ await fs.writeFile(plan.result, JSON.stringify(found));
45
+ }
46
+ if (require.main === module) main().catch(qa.fail);
47
+ module.exports = { images };
@@ -0,0 +1,274 @@
1
+ """Step 5: compare the published test site with the old site. One report.
2
+
3
+ verify_migration.py https://test-address.example [--no-browser]
4
+
5
+ Checks addresses, redirects, texts, main headings, references to the old host
6
+ and to private addresses, videos and files of every page, and in a browser the
7
+ size of images plus sample pages of every type at two widths. Reads only.
8
+ Saves qa/migration/compare.json and compare.md; pages are cached privately.
9
+ """
10
+ import argparse
11
+ import concurrent.futures
12
+ import difflib
13
+ import json
14
+ from pathlib import Path
15
+ import re
16
+ import subprocess
17
+ import urllib.parse
18
+ import check_assets
19
+ import inventory as inventory_step
20
+ import migration
21
+ import pacing
22
+ from check_url_parity import fetch, origin, probe
23
+ from compare_text import Text
24
+
25
+ WIDTHS = ('390', '1280')
26
+ # Addresses that work only for a signed-in editor or for a short while.
27
+ PRIVATE = re.compile(r'(?:/api/(?:v1/|media/|preview)|[?&](?:X-Amz-Signature|preview_token|token)=|localhost|127\.0\.0\.1)', re.I)
28
+ SKIP_TAGS = {'script', 'style', 'noscript', 'svg', 'template', 'nav', 'form', 'iframe'}
29
+ # Part of the page's frame, except inside its main content.
30
+ FRAME = {'header', 'footer'}
31
+
32
+
33
+ class Content(Text):
34
+ """The words of a published page: no menu, no site header or footer, no forms."""
35
+
36
+ def __init__(self):
37
+ super().__init__()
38
+ self.in_main, self.frame = 0, []
39
+
40
+ def handle_starttag(self, tag, attrs):
41
+ if tag == 'main':
42
+ self.in_main += 1
43
+ if tag in FRAME:
44
+ self.frame.append(not self.in_main)
45
+ if tag in SKIP_TAGS or tag in FRAME and not self.in_main:
46
+ self.skip += 1
47
+ self.words.append(' ')
48
+
49
+ def handle_endtag(self, tag):
50
+ if tag == 'main':
51
+ self.in_main = max(0, self.in_main - 1)
52
+ if tag in SKIP_TAGS or tag in FRAME and self.frame and self.frame.pop():
53
+ self.skip = max(0, self.skip - 1)
54
+ self.words.append(' ')
55
+
56
+
57
+ class Seen(Text):
58
+ """The words of a saved page as the visitor saw them: marks say what was hidden or frame."""
59
+ VOID = {'area', 'br', 'col', 'embed', 'hr', 'img', 'input', 'source', 'track', 'wbr'}
60
+
61
+ def handle_starttag(self, tag, attrs):
62
+ if tag in self.VOID:
63
+ self.words.append(' ')
64
+ elif self.skip or tag in SKIP_TAGS or any(name in ('data-tr-hidden', 'data-tr-chrome') for name, _ in attrs):
65
+ self.skip += 1
66
+ self.words.append(' ')
67
+
68
+ def handle_endtag(self, tag):
69
+ if self.skip and tag not in self.VOID:
70
+ self.skip -= 1
71
+ self.words.append(' ')
72
+
73
+
74
+ def seen_words(source):
75
+ parser = Seen()
76
+ parser.feed(source)
77
+ return re.findall(r'\w+', ''.join(parser.words).lower())
78
+
79
+
80
+ def words(source):
81
+ parser = Content()
82
+ parser.feed(source)
83
+ return re.findall(r'\w+', ''.join(parser.words).lower())
84
+
85
+
86
+ def text_difference(before, after):
87
+ """Phrases that disappeared or were added, and the share that is the same."""
88
+ old, new = seen_words(before), words(after)
89
+ matcher = difflib.SequenceMatcher(None, old, new, autojunk=False)
90
+ gone, added = [], []
91
+ for kind, a, b, c, d in matcher.get_opcodes():
92
+ if kind in ('delete', 'replace'):
93
+ gone.append(' '.join(old[a:b]))
94
+ if kind in ('insert', 'replace'):
95
+ added.append(' '.join(new[c:d]))
96
+ kept = sum(block.size for block in matcher.get_matching_blocks())
97
+ return {'words': len(old), 'kept': kept, 'missing': [item for item in gone if item][:20], 'added': [item for item in added if item][:20]}
98
+
99
+
100
+ def host(url):
101
+ return (urllib.parse.urlsplit(url).hostname or '').lower().removeprefix('www.')
102
+
103
+
104
+ def video_id(url):
105
+ found = re.search(r'(?:embed/|v=|youtu\.be/|shorts/|video/|vimeo\.com/)([\w-]{6,})', url)
106
+ return found.group(1) if found else urllib.parse.urlsplit(url).path.rsplit('/', 1)[-1]
107
+
108
+
109
+ def check_page(row, source, target, old, kind=None):
110
+ """Everything about one old address, without a browser."""
111
+ url = target + row['path']
112
+ answer = probe(url, expected_page=False)
113
+ item = {'path': row['path'], 'type': kind, 'problems': [], 'notes': []}
114
+ if not answer.get('ok'):
115
+ item['problems'].append(f"answers {answer.get('status') or answer.get('error')}")
116
+ return item, None
117
+ final = answer['final_url']
118
+ if host(final) != host(target):
119
+ item['problems'].append('redirects to another site: ' + final)
120
+ return item, None
121
+ if answer['hops']:
122
+ item['redirects_to'] = urllib.parse.urlsplit(final).path
123
+ if kind == 'skip':
124
+ return item, None
125
+ if row['status'] in (301, 302, 307, 308):
126
+ if not answer['hops']:
127
+ item['notes'].append('was a redirect, is now a page')
128
+ return item, None
129
+ status, _, body = fetch(final)
130
+ if status != 200:
131
+ item['problems'].append(f'answers {status}')
132
+ return item, None
133
+ after = body.decode('utf8', 'replace')
134
+ page = inventory_step.Page(final)
135
+ page.feed(after)
136
+ if page.h1 != 1:
137
+ item['problems'].append(f'{page.h1} main headings (h1)')
138
+ links = page.links | page.media
139
+ old_links = sorted(link for link in links if host(link) == host(source) != host(target))
140
+ if old_links:
141
+ item['problems'].append(f'{len(old_links)} links or files on the old site, such as {old_links[0]}')
142
+ private = sorted(link for link in links if PRIVATE.search(link))
143
+ if private:
144
+ item['problems'].append(f'{len(private)} addresses visitors cannot open')
145
+ if re.search(r'\{\{\s*(?:page|item|props|content_type)\.', after):
146
+ item['problems'].append('shows an unresolved field')
147
+ # A video can wait for a click, so the published page is searched as text.
148
+ lost = [video for video in sorted(old['videos']) if video_id(video) not in after]
149
+ if lost:
150
+ item['problems'].append(f'{len(lost)} videos missing, such as {lost[0]}')
151
+ if not item.get('redirects_to') and old['html']:
152
+ difference = text_difference(old['html'], after)
153
+ item['text'] = {'words': difference['words'], 'kept': difference['kept']}
154
+ if difference['missing']:
155
+ item['problems'].append(f"text missing ({difference['words'] - difference['kept']} words)")
156
+ item['missing_text'] = difference['missing']
157
+ if difference['added']:
158
+ item['notes'].append('text added')
159
+ item['added_text'] = difference['added']
160
+ if old['forms'] > page.forms:
161
+ item['notes'].append('fewer forms than before')
162
+ parser = check_assets.Assets(final)
163
+ parser.feed(after)
164
+ return item, parser.urls
165
+
166
+
167
+ def samples(rows):
168
+ """Two pages of every type: the ones with most and least text."""
169
+ chosen = {}
170
+ for row in rows:
171
+ if row['text_words'] is not None:
172
+ chosen.setdefault(row['type'] or 'other', []).append(row)
173
+ picked = []
174
+ for found in chosen.values():
175
+ found.sort(key=lambda row: row['text_words'])
176
+ picked += {row['path']: row for row in (found[0], found[-1])}.values()
177
+ return sorted(row['path'] for row in picked)
178
+
179
+
180
+ def browse(target, paths, sample):
181
+ out = migration.root() / 'qa' / 'reports' / 'migration'
182
+ out.mkdir(parents=True, exist_ok=True)
183
+ plan = migration.private() / 'browse.json'
184
+ answer = migration.private() / 'browse-result.json'
185
+ answer.unlink(missing_ok=True)
186
+ migration.write_json(plan, {'origin': target, 'paths': paths, 'sample': sample, 'widths': [int(width) for width in WIDTHS], 'out': str(out), 'result': str(answer)})
187
+ run = subprocess.run(['node', str(Path(__file__).with_name('verify_migration.cjs')), str(plan)], check=False)
188
+ found = migration.read_json(answer)
189
+ if run.returncode or found is None:
190
+ raise migration.StepError('The browser check did not finish. Install Playwright (scripts/README.md) and run again')
191
+ return found
192
+
193
+
194
+ def accepted(root):
195
+ """Differences the owner accepted: {"/path": ["part of the problem", ...]} with "*" for every page."""
196
+ return migration.read_json(root / 'qa' / 'migration' / 'accepted.json', {})
197
+
198
+
199
+ def verify(target, browser=True):
200
+ migration.require('compare')
201
+ import pages as worksheet
202
+ left = worksheet.left(migration.result('model'))['not_checked']
203
+ if left:
204
+ # A script cannot see that a page looks wrong.
205
+ raise migration.StepError(f'{len(left)} new pages have not been looked at (pages.py checked), such as {", ".join(left[:5])}')
206
+ inventory = migration.result('inventory')
207
+ source = inventory['source']
208
+ model = migration.result('model')
209
+ rows = [row for row in inventory['urls'] if row['status'] in (200, 301, 302, 307, 308)]
210
+ workers = pacing.profile()['concurrency']
211
+ # Records without pages of their own: the old address only has to lead somewhere.
212
+ without = {entry['content_type'] for entry in model['types'] if not entry.get('own_pages', True)}
213
+
214
+ def one(row):
215
+ old = inventory_step.seen(row['url']) or {'html': '', 'videos': [], 'forms': 0}
216
+ kind = (model['pages'].get(row['path']) or {}).get('type')
217
+ return check_page(row, source, target, old, 'skip' if kind in without else kind)
218
+
219
+ with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
220
+ results = list(pool.map(one, rows))
221
+ assets = sorted(set().union(*(found for _, found in results if found)))
222
+ answers = list(pool.map(check_assets.check, assets))
223
+ pages = [item for item, _ in results]
224
+ broken = {answer['url']: answer['status'] for answer in answers if not answer['ok']}
225
+ for item, found in results:
226
+ lost = sorted(url for url in found or () if url in broken)
227
+ if lost:
228
+ item['problems'].append(f'{len(lost)} files do not open, such as {lost[0]}')
229
+ if browser:
230
+ paths = [item['path'] for item, found in results if found is not None and not item.get('redirects_to')]
231
+ sample = samples([{**item, 'text_words': (item.get('text') or {}).get('words')} for item in pages])
232
+ seen = browse(target, paths, sample)
233
+ for item in pages:
234
+ item['problems'] += seen.get(item['path'], [])
235
+ allowed = accepted(migration.root())
236
+ for item in pages:
237
+ fine = allowed.get('*', []) + allowed.get(item['path'], [])
238
+ item['accepted'] = [problem for problem in item['problems'] if any(part in problem for part in fine)]
239
+ item['problems'] = [problem for problem in item['problems'] if problem not in item['accepted']]
240
+ kinds = {}
241
+ for item in pages:
242
+ for problem in item['problems']:
243
+ kind = re.sub(r'\s*\(.*|, such as.*|:.*', '', re.sub(r'^\d+ ', '', problem))
244
+ kinds[kind] = kinds.get(kind, 0) + 1
245
+ bad = [item for item in pages if item['problems']]
246
+ summary = {'pages': len(pages), 'pages_with_problems': len(bad), 'problems': kinds, 'files': len(assets), 'browser': browser,
247
+ 'words': sum((item.get('text') or {}).get('words', 0) for item in pages), 'words_kept': sum((item.get('text') or {}).get('kept', 0) for item in pages)}
248
+ ok = bool(pages) and not bad and browser
249
+ migration.save('compare', ok, origin=target, summary=summary, pages=[item for item in pages if item['problems'] or item['notes'] or item['accepted']])
250
+ lines = ['# Comparison with the old site', '', f"{len(pages)} addresses, {len(bad)} with problems. {summary['words_kept']} of {summary['words']} words are the same.", '']
251
+ for item in bad:
252
+ lines += [f"- {item['path']}: " + '; '.join(item['problems'])] + [f' - missing: {text}' for text in item.get('missing_text', [])[:5]]
253
+ if not browser:
254
+ lines += ['', 'The browser check was skipped, so this result does not count as passed.']
255
+ (migration.folder() / 'compare.md').write_text('\n'.join(lines) + '\n', 'utf8')
256
+ return ok, summary
257
+
258
+
259
+ def main():
260
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
261
+ parser.add_argument('origin', type=origin)
262
+ parser.add_argument('--no-browser', action='store_true', help='Faster, but the step does not pass')
263
+ args = parser.parse_args()
264
+ ok, summary = verify(args.origin, not args.no_browser)
265
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
266
+ print('Every difference is in qa/migration/compare.md. Look at the screenshots in qa/reports/migration yourself.')
267
+ return 0 if ok else 1
268
+
269
+
270
+ if __name__ == '__main__':
271
+ try:
272
+ raise SystemExit(main())
273
+ except migration.StepError as error:
274
+ raise SystemExit(str(error))