@typeroll/mcp-server 0.45.133 → 0.45.134

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.
@@ -1,9 +1,81 @@
1
1
  // Isolated QA browser only. Never persist storage state, cookies or signed URLs.
2
- const { chromium } = require('playwright');
3
2
  const fs = require('node:fs/promises');
4
3
  const path = require('node:path');
4
+ // Polite pacing: home connections (ISP, router, DNS) can throttle many rapid
5
+ // requests, so the local profile is slow. Cloud runners may go faster.
6
+ // Override with TYPEROLL_REQUEST_PROFILE=local|cloud and TYPEROLL_REQUEST_CONCURRENCY=N.
7
+ const PROFILES = { local: { concurrency: 2, interval: 300 }, cloud: { concurrency: 5, interval: 100 } };
8
+ const CLOUD_MARKERS = ['CLAUDE_CODE_REMOTE', 'CODESPACES', 'GITHUB_ACTIONS', 'CI'];
9
+ const RETRY_STATUSES = new Set([429, 500, 502, 503, 504]);
10
+ const MAX_RETRIES = 3, MAX_DELAY = 60000;
11
+ const isSet = value => !['', '0', 'false', 'no', 'off'].includes(String(value ?? '').trim().toLowerCase());
12
+ function selectProfile(env = process.env) {
13
+ const explicit = String(env.TYPEROLL_REQUEST_PROFILE ?? '').trim().toLowerCase();
14
+ if (explicit && !PROFILES[explicit]) throw Error('TYPEROLL_REQUEST_PROFILE must be local or cloud');
15
+ const marker = CLOUD_MARKERS.find(name => isSet(env[name]));
16
+ const name = explicit || (marker ? 'cloud' : 'local');
17
+ const profile = { ...PROFILES[name], name, reason: explicit ? 'TYPEROLL_REQUEST_PROFILE' : marker || 'default' };
18
+ const raw = String(env.TYPEROLL_REQUEST_CONCURRENCY ?? '').trim();
19
+ if (raw) {
20
+ if (!/^\d+$/.test(raw) || +raw < 1 || +raw > 16) throw Error('TYPEROLL_REQUEST_CONCURRENCY must be a whole number from 1 to 16');
21
+ profile.concurrency = +raw;
22
+ }
23
+ return profile;
24
+ }
25
+ function describeProfile(p) {
26
+ const hint = p.name === 'local' ? 'on a cloud runner set TYPEROLL_REQUEST_PROFILE=cloud' : 'set TYPEROLL_REQUEST_PROFILE=local on your own computer';
27
+ return `Request profile: ${p.name} (${p.reason}; ${p.concurrency} concurrent, ${p.interval} ms between requests per host). To change it, ${hint}; TYPEROLL_REQUEST_CONCURRENCY=N sets concurrency.`;
28
+ }
29
+ // Milliseconds requested by a Retry-After header (delta seconds or HTTP date), or null.
30
+ function retryAfter(value, now = Date.now()) {
31
+ if (value == null) return null;
32
+ const text = String(value).trim();
33
+ if (/^\d+$/.test(text)) return +text * 1000;
34
+ if (!/[a-z]/i.test(text)) return null;
35
+ const when = Date.parse(text);
36
+ return Number.isNaN(when) ? null : Math.max(0, when - now);
37
+ }
38
+ // Delay before retry attempt+1, or null to stop. status null/undefined means a network error.
39
+ function retryDelay(attempt, status, header, now) {
40
+ if (attempt >= MAX_RETRIES || (status != null && !RETRY_STATUSES.has(status))) return null;
41
+ const hinted = retryAfter(header, now);
42
+ const delay = hinted ?? 1000 * 2 ** attempt;
43
+ return delay > MAX_DELAY ? null : delay;
44
+ }
45
+ let active = null;
46
+ const nextStart = new Map();
47
+ function requestProfile() {
48
+ if (!active) { active = selectProfile(); console.error(describeProfile(active)); }
49
+ return active;
50
+ }
51
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
52
+ async function pace(url) {
53
+ const host = new URL(url).hostname, now = Date.now();
54
+ const start = Math.max(now, nextStart.get(host) ?? now);
55
+ nextStart.set(host, start + requestProfile().interval);
56
+ if (start > now) await sleep(start - now);
57
+ }
58
+ // Paced navigation; a network error, 429 or 5xx is retried a bounded number of times with backoff.
59
+ async function navigate(page, url, options = {}) {
60
+ for (let attempt = 0; ; attempt++) {
61
+ await pace(url);
62
+ let response, delay;
63
+ try {
64
+ response = await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000, ...options });
65
+ } catch (error) {
66
+ delay = error.name === 'TimeoutError' ? null : retryDelay(attempt);
67
+ if (delay == null) throw error;
68
+ }
69
+ if (response !== undefined) {
70
+ const status = response?.status();
71
+ delay = status != null && RETRY_STATUSES.has(status) ? retryDelay(attempt, status, response.headers()['retry-after']) : null;
72
+ if (delay == null) return response;
73
+ }
74
+ await sleep(delay);
75
+ }
76
+ }
5
77
  async function open(page, url) {
6
- await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 });
78
+ await navigate(page, url);
7
79
  // Select only Typeroll's own preview, never an arbitrary ad/video iframe.
8
80
  const frame = page.locator('iframe[title="Preview"], iframe[title="Site preview"]');
9
81
  if (await frame.count() === 1) {
@@ -12,7 +84,7 @@ async function open(page, url) {
12
84
  if (!src) throw Error('Preview frame has no source');
13
85
  const target = new URL(src, page.url());
14
86
  if (target.origin !== new URL(page.url()).origin) throw Error('Unexpected preview frame origin');
15
- await page.goto(target.href, { waitUntil: 'domcontentloaded', timeout: 60000 });
87
+ await navigate(page, target.href);
16
88
  }
17
89
  await page.evaluate(() => document.fonts.ready);
18
90
  }
@@ -47,4 +119,9 @@ function widths(args) {
47
119
  return values;
48
120
  }
49
121
  function fail() { console.error('QA failed; inspect the target privately. URLs and credentials are withheld.'); process.exitCode = 2; }
50
- module.exports = { chromium, open, settle, inspect, screenshot, widths, fail };
122
+ module.exports = {
123
+ // Loaded on use, so the pacing helpers also work (and test) without Playwright.
124
+ get chromium() { return require('playwright').chromium; },
125
+ open, navigate, settle, inspect, screenshot, widths, fail,
126
+ selectProfile, describeProfile, requestProfile, retryAfter, retryDelay,
127
+ };
@@ -4,6 +4,7 @@ import concurrent.futures
4
4
  from html.parser import HTMLParser
5
5
  import json
6
6
  import urllib.parse
7
+ import pacing
7
8
  import trlib
8
9
  from check_url_parity import origin, fetch, probe
9
10
 
@@ -43,6 +44,7 @@ def main():
43
44
  parser = argparse.ArgumentParser(description=__doc__)
44
45
  parser.add_argument('origin', type=origin)
45
46
  args = parser.parse_args()
47
+ request_profile = pacing.profile()
46
48
  pages = [p for p in trlib.all_pages() if p.get('status') in ('published', 'unlisted')]
47
49
  errors, assets = [], set()
48
50
  for page in pages:
@@ -62,7 +64,7 @@ def main():
62
64
  parser = Assets(evidence['final_url'])
63
65
  parser.feed(body.decode('utf8', 'replace'))
64
66
  assets.update(parser.urls)
65
- with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
67
+ with concurrent.futures.ThreadPoolExecutor(max_workers=request_profile['concurrency']) as pool:
66
68
  results = list(pool.map(check, sorted(assets)))
67
69
  print(json.dumps({'pages': len(pages), 'page_errors': errors, 'assets': results}, indent=2))
68
70
  return 1 if not pages or errors or any(not item['ok'] for item in results) else 0
@@ -1,5 +1,6 @@
1
1
  // Read-only component rhythm QA. Deliberate exceptions require visual review.
2
- const { chromium } = require('playwright');
2
+ const qa = require('./browser.cjs');
3
+ const { chromium } = qa;
3
4
  const fs = require('node:fs');
4
5
  async function main() {
5
6
  const origin = new URL(process.argv[2]);
@@ -21,7 +22,7 @@ async function main() {
21
22
  for (const width of [375,768,1280]) {
22
23
  await page.setViewportSize({width,height:900});
23
24
  for (const path of [...new Set(paths)]) {
24
- await page.goto(new URL(path,origin).href,{waitUntil:'domcontentloaded'});
25
+ await qa.navigate(page,new URL(path,origin).href,{timeout:30000});
25
26
  await page.evaluate(()=>document.fonts.ready);
26
27
  const findings=await page.evaluate(()=>{
27
28
  const found=[];
@@ -1,9 +1,11 @@
1
1
  """Read-only URL continuity check on an explicitly supplied deployed origin."""
2
2
  import argparse
3
3
  import json
4
+ import time
4
5
  import urllib.error
5
6
  import urllib.parse
6
7
  import urllib.request
8
+ import pacing
7
9
  import trlib
8
10
 
9
11
  UA = 'Typeroll-Starter-QA/1.0 (+https://typeroll.com/docs/)'
@@ -11,17 +13,23 @@ UA = 'Typeroll-Starter-QA/1.0 (+https://typeroll.com/docs/)'
11
13
 
12
14
  def fetch(url, method='GET'):
13
15
  request = urllib.request.Request(url, method=method, headers={'User-Agent': UA})
14
- for attempt in range(2):
16
+ attempt = 0
17
+ while True:
18
+ # Paced per host; 429/5xx and network errors get a bounded, backed-off retry.
19
+ pacing.pace(url)
15
20
  try:
16
21
  with urllib.request.build_opener(trlib.NoRedirect).open(request, timeout=30) as response:
17
22
  return response.status, response.headers.get('Location'), response.read() if method == 'GET' else b''
18
23
  except urllib.error.HTTPError as error:
19
- if error.code in (502, 503, 504) and attempt == 0:
20
- continue
21
- return error.code, error.headers.get('Location'), b''
24
+ delay = pacing.retry_delay(attempt, error.code, error.headers.get('Retry-After'))
25
+ if delay is None:
26
+ return error.code, error.headers.get('Location'), b''
22
27
  except (OSError, TimeoutError):
23
- if attempt:
28
+ delay = pacing.retry_delay(attempt)
29
+ if delay is None:
24
30
  return 0, None, b''
31
+ time.sleep(delay)
32
+ attempt += 1
25
33
 
26
34
 
27
35
  def origin(value):
@@ -56,6 +64,7 @@ def main():
56
64
  parser.add_argument('origin', type=origin)
57
65
  parser.add_argument('--show-excluded', action='store_true')
58
66
  args = parser.parse_args()
67
+ pacing.profile()
59
68
  report = []
60
69
  for row in trlib.all_migration_urls():
61
70
  if row.get('status') == 'excluded' and not args.show_excluded:
@@ -0,0 +1,117 @@
1
+ """Polite request pacing for read-only QA requests to websites.
2
+
3
+ Home connections (ISP, router, DNS resolver) can throttle or block many rapid
4
+ requests from one machine, so the local profile is slow by default. Cloud
5
+ runners may go faster. Override with TYPEROLL_REQUEST_PROFILE=local|cloud and
6
+ TYPEROLL_REQUEST_CONCURRENCY=N. Never used for MCP calls or mutations.
7
+ """
8
+ import email.utils
9
+ import os
10
+ import sys
11
+ import threading
12
+ import time
13
+ import urllib.parse
14
+
15
+ PROFILES = {
16
+ 'local': {'concurrency': 2, 'interval': 0.3},
17
+ 'cloud': {'concurrency': 5, 'interval': 0.1},
18
+ }
19
+ CLOUD_MARKERS = ('CLAUDE_CODE_REMOTE', 'CODESPACES', 'GITHUB_ACTIONS', 'CI')
20
+ RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
21
+ MAX_RETRIES = 3
22
+ MAX_DELAY = 60.0
23
+
24
+
25
+ def _set(value):
26
+ return (value or '').strip().lower() not in ('', '0', 'false', 'no', 'off')
27
+
28
+
29
+ def select_profile(env=None):
30
+ """Return the request profile for this environment: local unless told otherwise."""
31
+ env = os.environ if env is None else env
32
+ explicit = (env.get('TYPEROLL_REQUEST_PROFILE') or '').strip().lower()
33
+ if explicit and explicit not in PROFILES:
34
+ raise ValueError('TYPEROLL_REQUEST_PROFILE must be local or cloud')
35
+ marker = next((name for name in CLOUD_MARKERS if _set(env.get(name))), None)
36
+ name = explicit or ('cloud' if marker else 'local')
37
+ reason = 'TYPEROLL_REQUEST_PROFILE' if explicit else marker or 'default'
38
+ profile = dict(PROFILES[name], name=name, reason=reason)
39
+ raw = (env.get('TYPEROLL_REQUEST_CONCURRENCY') or '').strip()
40
+ if raw:
41
+ if not raw.isdigit() or not 1 <= int(raw) <= 16:
42
+ raise ValueError('TYPEROLL_REQUEST_CONCURRENCY must be a whole number from 1 to 16')
43
+ profile['concurrency'] = int(raw)
44
+ return profile
45
+
46
+
47
+ def describe(profile):
48
+ hint = ('on a cloud runner set TYPEROLL_REQUEST_PROFILE=cloud' if profile['name'] == 'local'
49
+ else 'set TYPEROLL_REQUEST_PROFILE=local on your own computer')
50
+ return (f"Request profile: {profile['name']} ({profile['reason']}; {profile['concurrency']} concurrent, "
51
+ f"{int(profile['interval'] * 1000)} ms between requests per host). "
52
+ f"To change it, {hint}; TYPEROLL_REQUEST_CONCURRENCY=N sets concurrency.")
53
+
54
+
55
+ def retry_after(value, now=None):
56
+ """Seconds requested by a Retry-After header (delta seconds or HTTP date), or None."""
57
+ if value is None:
58
+ return None
59
+ value = str(value).strip()
60
+ if value.isdigit():
61
+ return float(value)
62
+ try:
63
+ when = email.utils.parsedate_to_datetime(value)
64
+ except (TypeError, ValueError, IndexError):
65
+ return None
66
+ if when is None or when.tzinfo is None:
67
+ return None
68
+ return max(0.0, when.timestamp() - (time.time() if now is None else now))
69
+
70
+
71
+ def retry_delay(attempt, status=None, header=None, now=None):
72
+ """Seconds to wait before retry number attempt+1, or None to stop.
73
+
74
+ status None means a network error. A Retry-After above MAX_DELAY stops
75
+ instead of hammering a host that asked for a long pause.
76
+ """
77
+ if attempt >= MAX_RETRIES or (status is not None and status not in RETRY_STATUSES):
78
+ return None
79
+ hinted = retry_after(header, now)
80
+ delay = hinted if hinted is not None else float(2 ** attempt)
81
+ return None if delay > MAX_DELAY else delay
82
+
83
+
84
+ class Pacer:
85
+ """Keep request starts to one host at least interval seconds apart (thread safe)."""
86
+
87
+ def __init__(self, interval, clock=time.monotonic, sleep=time.sleep):
88
+ self.interval, self.clock, self.sleep = interval, clock, sleep
89
+ self.lock, self.next = threading.Lock(), {}
90
+
91
+ def wait(self, url):
92
+ host = (urllib.parse.urlsplit(url).hostname or '').lower()
93
+ with self.lock:
94
+ now = self.clock()
95
+ start = max(now, self.next.get(host, now))
96
+ self.next[host] = start + self.interval
97
+ if start > now:
98
+ self.sleep(start - now)
99
+
100
+
101
+ _profile = None
102
+ _pacer = None
103
+
104
+
105
+ def profile():
106
+ """The active profile; prints one line to stderr the first time."""
107
+ global _profile, _pacer
108
+ if _profile is None:
109
+ _profile = select_profile()
110
+ _pacer = Pacer(_profile['interval'])
111
+ print(describe(_profile), file=sys.stderr)
112
+ return _profile
113
+
114
+
115
+ def pace(url):
116
+ profile()
117
+ _pacer.wait(url)
@@ -41,12 +41,20 @@ WordPress REST + HTML covers the source; use tr-migrate-wp's access decision
41
41
  table before asking for a helper plugin. Inventory both Pages and posts plus
42
42
  internal links and known old slugs. A sitemap alone is not complete.
43
43
 
44
+ Crawl and copy slowly on your own computer: an ISP, router or DNS resolver can
45
+ throttle or block many rapid requests to the old site. Fetch a few pages at a
46
+ time with pauses, back off on 429/503, and prefer a cloud session (Claude Code on
47
+ the web, Codespaces) for large crawls and media copies. See scripts/README.md.
48
+
44
49
  Discard HTML comments before extracting text, resolve relative links against
45
50
  the source, and keep an explicit old URL map. Do not redirect deleted content
46
51
  to the home page merely to get a 200. Preserve/renew text and design separately.
47
52
  Use capture_text.cjs + compare_text.py for preserved text with explicit selectors.
48
53
 
49
- Before every authorized test deployment run check_unsaved.py (Pages and partials).
54
+ Before every authorized test deployment run check_unsaved.py (Pages and partials),
55
+ then `trigger_deploy` with `dry_run: true` and read `get_publication_impact`. A
56
+ publication ships everything saved on the Site, including other people's and
57
+ other sessions' changes; stop and ask about any change you did not make.
50
58
  Deploy saved content to the agreed protected test host, then run check_url_parity.py,
51
59
  check_assets.py and shoot_hosted.cjs. Check whole-card targets with
52
60
  card-stacking-check.cjs and inspect actual desktop/mobile screenshots. Record a
@@ -55,6 +63,12 @@ Domain preparation/cutover and production indexing follow their own explicit
55
63
  approval scope and the platform's current guided flow; do not bypass readiness.
56
64
  Do not request a second approval for a step the owner has already authorized.
57
65
 
66
+ The migration is finished only when its status has no failed media or Pages:
67
+ `read_organization_media_migration` lists no `failed_media` for the Site, and
68
+ no import or inventory row has failed. Otherwise review each failure and record
69
+ its acceptance in brief/migration.md. After the first publication, check the
70
+ live Pages' images once (check_assets.py, shoot_hosted.cjs).
71
+
58
72
 
59
73
  ## Native controls and publication checks
60
74
 
@@ -17,7 +17,10 @@ the CMS. Do not delete source files or cancel old hosting as part of this routin
17
17
  4. Copy with bounded concurrency and bounded reads, stream large files and use
18
18
  resumable transfers when supported. Preserve a collision-safe key derived from
19
19
  the full source host/path, not just the filename. Never overwrite a different
20
- object merely because the basename matches.
20
+ object merely because the basename matches. On your own computer, copy one
21
+ or two files at a time with pauses and back off on 429/503: an ISP, router or
22
+ DNS resolver can throttle or block many rapid requests to the old host. Run
23
+ large copies in a cloud session (see scripts/README.md, request pace).
21
24
  5. Record source URL, destination key, source ID, byte count, SHA-256, media type,
22
25
  title/alt/caption, copy time and verification state in a private manifest.
23
26
  ETag is not universally MD5 (multipart objects and providers differ). Use a