screw-bugs 0.1.6 → 0.1.8

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 (61) hide show
  1. package/README.md +86 -16
  2. package/dist/browser-playwright/launch.d.ts +4 -2
  3. package/dist/browser-playwright/launch.js +8 -1
  4. package/dist/browser-playwright/page.d.ts +2 -2
  5. package/dist/browser-playwright/page.js +15 -2
  6. package/dist/browser-playwright/still.d.ts +12 -0
  7. package/dist/browser-playwright/still.js +51 -0
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli/app.d.ts +1 -1
  10. package/dist/cli/commands.js +57 -12
  11. package/dist/cli/mcp.d.ts +11 -4
  12. package/dist/cli/mcp.js +86 -23
  13. package/dist/cli/operations.d.ts +30 -2
  14. package/dist/cli/operations.js +126 -20
  15. package/dist/cli/report-links.js +2 -2
  16. package/dist/cli/report-server.d.ts +41 -9
  17. package/dist/cli/report-server.js +139 -23
  18. package/dist/cli/share.d.ts +71 -4
  19. package/dist/cli/share.js +549 -118
  20. package/dist/cli/sign-in.d.ts +22 -10
  21. package/dist/cli/sign-in.js +23 -23
  22. package/dist/core/engine.js +67 -17
  23. package/dist/core/liveness.js +3 -1
  24. package/dist/core/services.d.ts +30 -5
  25. package/dist/core/share.d.ts +31 -0
  26. package/dist/core/share.js +139 -0
  27. package/dist/core/steps.d.ts +5 -0
  28. package/dist/core/steps.js +15 -1
  29. package/dist/core/video.d.ts +31 -0
  30. package/dist/core/video.js +132 -0
  31. package/dist/report/html.d.ts +4 -2
  32. package/dist/report/html.js +45 -13
  33. package/dist/report/icons.d.ts +3 -0
  34. package/dist/report/icons.js +5 -1
  35. package/dist/report/index.d.ts +3 -1
  36. package/dist/report/index.js +3 -1
  37. package/dist/report/live.d.ts +7 -0
  38. package/dist/report/live.js +135 -0
  39. package/dist/report/menu-bar.d.ts +3 -3
  40. package/dist/report/menu-bar.js +4 -4
  41. package/dist/report/player.d.ts +3 -3
  42. package/dist/report/player.js +3 -3
  43. package/dist/report/share-page.d.ts +48 -0
  44. package/dist/report/share-page.js +291 -0
  45. package/dist/report/styles.d.ts +2 -0
  46. package/dist/report/styles.js +2 -2
  47. package/dist/report/view.d.ts +16 -5
  48. package/dist/report/view.js +60 -24
  49. package/dist/report/walkthrough.d.ts +7 -3
  50. package/dist/report/walkthrough.js +21 -8
  51. package/dist/schema/accounts.js +10 -1
  52. package/dist/schema/evidence.d.ts +30 -8
  53. package/dist/schema/evidence.js +17 -4
  54. package/dist/schema/findings.js +1 -1
  55. package/dist/schema/job.d.ts +205 -65
  56. package/dist/schema/job.js +63 -11
  57. package/dist/schema/ledger.d.ts +88 -16
  58. package/dist/schema/ledger.js +36 -0
  59. package/dist/schema/share.d.ts +17 -0
  60. package/dist/schema/share.js +22 -0
  61. package/package.json +1 -1
@@ -0,0 +1,135 @@
1
+ import { progressText, runFiles, summaryOf } from '../schema/index.js';
2
+ import { favicon, html, Markup, safeRelative } from './markup.js';
3
+ import { dark, light } from './styles.js';
4
+ import { countsOf, formatTime, statusLabel } from './view.js';
5
+ /*
6
+ * `live.html`: the page a person watches a run on while it goes. Written by the run with every
7
+ * ledger write (see the engine), it reloads itself every `LIVE_REFRESH_S` seconds while the run is
8
+ * going; once the run ended it stops and links the report (and the walkthrough). No script.
9
+ */
10
+ /** How often the page reloads itself while the run is going, in seconds. */
11
+ export const LIVE_REFRESH_S = 3;
12
+ /** No script, nothing from elsewhere: only its own styles and the favicon's data URL. */
13
+ export const LIVE_CSP = "default-src 'none'; img-src data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'";
14
+ const liveStyles = /* css */ `
15
+ :root { ${light} }
16
+ @media (prefers-color-scheme: dark) { :root { ${dark} } }
17
+ * { box-sizing: border-box; }
18
+ body { margin: 0; background: var(--bg); color: var(--text);
19
+ font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
20
+ main { max-width: 760px; margin: 0 auto; padding: 32px 16px 48px; }
21
+ h1 { font-size: 20px; margin: 0 0 4px; }
22
+ .sub, .note { color: var(--muted); font-size: 13px; margin: 0; }
23
+ .now { margin: 20px 0 8px; padding: 12px 14px; border: 1px solid var(--accent-border);
24
+ background: var(--accent-subtle); border-radius: 8px; font-weight: 600; }
25
+ .now.ended { border-color: var(--border); background: var(--panel); }
26
+ .now a { color: var(--link); }
27
+ .counts { margin: 0 0 16px; color: var(--muted); }
28
+ ol { list-style: none; padding: 0; margin: 0 0 16px; border: 1px solid var(--border);
29
+ border-radius: 8px; overflow: hidden; }
30
+ li { display: flex; gap: 12px; align-items: baseline; padding: 10px 14px;
31
+ border-top: 1px solid var(--border); background: var(--panel); }
32
+ li:first-child { border-top: 0; }
33
+ li.current { background: var(--accent-subtle); }
34
+ .state { flex: none; width: 112px; font-size: 13px; font-weight: 600; }
35
+ .s-failed, .s-blocked { color: var(--fail-text); }
36
+ .s-pending, .s-not_verified { color: var(--muted); }
37
+ .title { min-width: 0; overflow-wrap: anywhere; }
38
+ .title code { font-size: 12px; color: var(--muted); }
39
+ .reason { display: block; font-size: 13px; color: var(--muted); }
40
+ `;
41
+ const isEnded = (page) => page.ledger.state === 'finished' || page.ledger.state === 'errored';
42
+ /** A case's state as the page shows it: its result, or running, or pending while the run goes. */
43
+ const stateOf = (page, entry, index) => {
44
+ if (isEnded(page) || entry.status !== 'not_verified' || entry.reason !== undefined)
45
+ return { key: entry.status, label: statusLabel[entry.status] };
46
+ const current = page.ledger.progress?.case;
47
+ if (current === index + 1) {
48
+ const { step, kind } = page.ledger.progress ?? {};
49
+ return {
50
+ key: 'running',
51
+ label: step === undefined ? 'Running' : `Running step ${step}${kind ? ` (${kind})` : ''}`,
52
+ };
53
+ }
54
+ return { key: 'pending', label: 'Pending' };
55
+ };
56
+ const countsLine = (cases) => {
57
+ const counts = countsOf(cases);
58
+ return (`${counts.passed} passed, ${counts.failed} failed, ${counts.blocked} blocked, ` +
59
+ `${counts.not_verified} not verified`);
60
+ };
61
+ /** What the run is doing now, or how it ended and where its report is. */
62
+ const nowLine = (page) => {
63
+ const { ledger } = page;
64
+ if (!isEnded(page)) {
65
+ const where = progressText(ledger);
66
+ return html `<p class="now" role="status">
67
+ ${where === undefined
68
+ ? ledger.state === 'queued'
69
+ ? 'Starting the browser…'
70
+ : 'The run is going.'
71
+ : `Running ${where}.`}
72
+ </p>`;
73
+ }
74
+ const report = safeRelative(page.report);
75
+ const walkthrough = safeRelative(page.walkthrough);
76
+ const how = ledger.state === 'finished' ? 'The run finished.' : `The run stopped: ${ledger.error ?? ''}`;
77
+ const links = [
78
+ ...(report ? [html `<a href="${report}">Open the report</a>`] : []),
79
+ ...(walkthrough ? [html `<a href="${walkthrough}">watch it step by step</a>`] : []),
80
+ ];
81
+ return html `<p class="now ended" role="status">
82
+ ${how}
83
+ ${links.length === 0
84
+ ? `Its report could not be written; \`screw-bugs report ${ledger.jobId}\` tries again.`
85
+ : html `${links.length === 2 ? html `${links[0]} or ${links[1]}` : links[0]}.`}
86
+ </p>`;
87
+ };
88
+ /** The whole `live.html`. */
89
+ export const renderLivePage = (page) => {
90
+ const { ledger, spec } = page;
91
+ const ended = isEnded(page);
92
+ const updated = ledger.heartbeatAt ?? ledger.startedAt;
93
+ const heading = summaryOf(spec).text;
94
+ return html `<!doctype html>
95
+ <html lang="en">
96
+ <head>
97
+ <meta charset="utf-8" />
98
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
99
+ <meta http-equiv="Content-Security-Policy" content="${LIVE_CSP}" />
100
+ ${ended ? '' : html `<meta http-equiv="refresh" content="${LIVE_REFRESH_S}" />`}
101
+ <title>${ended ? 'Run ended' : 'Running'} · screw-bugs</title>
102
+ ${favicon}
103
+ <style>
104
+ ${new Markup(liveStyles)}
105
+ </style>
106
+ </head>
107
+ <body>
108
+ <main>
109
+ <h1>${spec.title?.trim() ? spec.title : heading}</h1>
110
+ <p class="sub">Job ${ledger.jobId} · ${spec.url}</p>
111
+ ${nowLine(page)}
112
+ <p class="counts">${countsLine(ledger.cases)}</p>
113
+ <ol>
114
+ ${ledger.cases.map((entry, index) => {
115
+ const state = stateOf(page, entry, index);
116
+ return html `<li class="${state.key === 'running' ? 'current' : ''}">
117
+ <span class="${`state s-${state.key}`}">${state.label}</span>
118
+ <span class="title"
119
+ >${entry.title} <code>${entry.id}</code> ${entry.reason !== undefined
120
+ ? html `<span class="reason">${entry.reason}</span>`
121
+ : ''}</span
122
+ >
123
+ </li>`;
124
+ })}
125
+ </ol>
126
+ <p class="note">
127
+ ${updated !== undefined ? `Last updated ${formatTime(updated)}. ` : ''}${ended
128
+ ? `This page no longer changes; ${runFiles.html} has the results.`
129
+ : `This page reloads itself every ${LIVE_REFRESH_S} s while the run is going. ` +
130
+ 'If “last updated” stops moving, the run has stopped: its status then gives its report.'}
131
+ </p>
132
+ </main>
133
+ </body>
134
+ </html>`.value;
135
+ };
@@ -9,9 +9,9 @@ export declare const REPO: string;
9
9
  export declare const SHARE_START_PATH = "/.screw-bugs/share/start";
10
10
  /**
11
11
  * The Share button, in the place of Cloud's Sign in button: a link to the report server's start of
12
- * a share. Hidden until the page's script finds it was served by the local report server (`http:`
13
- * on 127.0.0.1 or localhost): opened from disk or on a host such as screw-bugs Cloud, there is no
14
- * server to share it.
12
+ * a share. Hidden until the page's script finds it was served over `http:`, as the local report
13
+ * server serves it (on 127.0.0.1, or a tailnet address with `SCREW_BUGS_REPORT_HOST`): opened from
14
+ * disk or on a host such as screw-bugs Cloud (`https:`), there is no server to share it.
15
15
  */
16
16
  export declare const shareButton: (jobId: string) => Markup;
17
17
  /**
@@ -17,14 +17,14 @@ export const REPO = REPO_URL.replace('https://github.com/', '');
17
17
  export const SHARE_START_PATH = '/.screw-bugs/share/start';
18
18
  /**
19
19
  * The Share button, in the place of Cloud's Sign in button: a link to the report server's start of
20
- * a share. Hidden until the page's script finds it was served by the local report server (`http:`
21
- * on 127.0.0.1 or localhost): opened from disk or on a host such as screw-bugs Cloud, there is no
22
- * server to share it.
20
+ * a share. Hidden until the page's script finds it was served over `http:`, as the local report
21
+ * server serves it (on 127.0.0.1, or a tailnet address with `SCREW_BUGS_REPORT_HOST`): opened from
22
+ * disk or on a host such as screw-bugs Cloud (`https:`), there is no server to share it.
23
23
  */
24
24
  export const shareButton = (jobId) => html `<a
25
25
  class="share-btn"
26
26
  href="${`${SHARE_START_PATH}?run=${encodeURIComponent(jobId)}`}"
27
- title="Share this report on screw-bugs Cloud: a link anyone can open for 7 days"
27
+ title="Share this report on Screw Bugs Cloud: a link anyone can open for 7 days"
28
28
  hidden
29
29
  >${icon('share', { size: 16 })}<span class="share-word">Share</span></a
30
30
  >`;
@@ -73,8 +73,8 @@ export declare const controlsBlock: (options: {
73
73
  export declare const share: (ms: number, of: number | undefined) => string;
74
74
  /**
75
75
  * The script both pages start with: the theme (set before anything is painted, kept where the
76
- * browser allows, and the menu bar's theme button, `THEME_BUTTON_JS`), the Share button (shown only on a page the local report server served: `http:`
77
- * on 127.0.0.1 or localhost), where the sticky menu bar ends (`topEdge`), when the run started in the reader's
76
+ * browser allows, and the menu bar's theme button, `THEME_BUTTON_JS`), the Share button (shown only on a page served over `http:`, as the local report server serves
77
+ * it), where the sticky menu bar ends (`topEdge`), when the run started in the reader's
78
78
  * own time zone (`Nov 4, 2026 · 23:50`, with the full date and zone as its title), the prompt's
79
79
  * "Show full prompt" (offered only when it does not fit, measured again whenever the prompt's box
80
80
  * changes size and once the page's fonts have loaded; while open it stays, as "Show less"), and `player(prefix, hooks)`, which takes over the video:
@@ -99,4 +99,4 @@ export declare const share: (ms: number, of: number | undefined) => string;
99
99
  * hooks use. The big play button over the video shows from the start until the video first plays
100
100
  * (by whatever control), and never after. Plain ES2020; no backslashes, so it reads the same in the TypeScript source.
101
101
  */
102
- export declare const PLAYER_JS = "const d=document,r=d.documentElement,K='screw-bugs-theme';\nconst still=()=>matchMedia('(prefers-reduced-motion: reduce)').matches;\nconst topEdge=()=>{const b=d.querySelector('.menubar');return b?Math.max(0,b.getBoundingClientRect().bottom):0};\nconst pad=n=>String(n).padStart(2,'0');\nconst clock=s=>{s=Math.max(0,Math.floor(s||0));const h=Math.floor(s/3600),m=Math.floor(s%3600/60);return(h?h+':'+pad(m):String(m))+':'+pad(s%60)};\nlet theme='system';try{theme=localStorage.getItem(K)||theme}catch(e){}r.dataset.theme=theme;\nconst themeCycle=(b,key)=>{\n const r=document.documentElement,T=['light','dark','system'],N={light:'Light theme',dark:'Dark theme',system:'Theme from system'};\n const at=()=>{const i=T.indexOf(r.dataset.theme);return i<0?2:i};\n const show=()=>{const i=at(),f=document.getElementById('favicon'),h=f&&f.dataset[T[i]];if(h)f.href=h;b.setAttribute('aria-label',N[T[i]]+'. Switch to '+N[T[(i+1)%3]].toLowerCase());b.title=N[T[i]]};\n show();\n b.addEventListener('click',()=>{const m=T[(at()+1)%3];r.dataset.theme=m;if(key)try{localStorage.setItem(key,m)}catch(e){}show()});\n};\nconst chrome=()=>{\n d.querySelectorAll('.menubar .theme').forEach(b=>{themeCycle(b,K);b.hidden=false});\n if(location.protocol==='http:'&&(location.hostname==='127.0.0.1'||location.hostname==='localhost'))d.querySelectorAll('a.share-btn').forEach(a=>{a.hidden=false});\n d.querySelectorAll('time.when[datetime]').forEach(e=>{\n const t=new Date(e.getAttribute('datetime'));if(isNaN(t.getTime()))return;const p={};\n try{new Intl.DateTimeFormat('en-US',{month:'short',day:'numeric',year:'numeric',hour:'2-digit',minute:'2-digit',hourCycle:'h23'}).formatToParts(t).forEach(x=>{p[x.type]=x.value});\n const y=d.createElement('span');y.className='year';y.textContent=', '+p.year;\n e.replaceChildren(p.month+' '+p.day,y,' '+String.fromCharCode(183)+' '+p.hour+':'+p.minute);\n e.title=new Intl.DateTimeFormat('en-US',{dateStyle:'full',timeStyle:'long'}).format(t)}catch(x){}\n });\n d.querySelectorAll('.prompt').forEach(p=>{\n const t=p.querySelector('.prompt-text'),b=p.querySelector('.prompt-more');if(!t||!b)return;\n const fits=()=>{if(!p.classList.contains('open'))b.hidden=t.scrollHeight<=t.clientHeight+1};\n fits();if(window.ResizeObserver)new ResizeObserver(fits).observe(t);if(d.fonts&&d.fonts.ready)d.fonts.ready.then(fits);\n b.addEventListener('click',()=>{const o=p.classList.toggle('open');b.textContent=o?'Show less':'Show full prompt';b.setAttribute('aria-expanded',String(o));fits()});\n });\n};\nconst bare=u=>{const i=u.indexOf('://');return i<0?u:u.slice(i+3)};\nconst player=(p,o)=>{\n const v=d.getElementById(p+'-video'),fig=v.closest('.player'),note=d.getElementById(p+'-unloaded'),c=d.getElementById(p+'-controls'),url=d.getElementById(p+'-url');\n const srcs=new Map([...fig.querySelectorAll('[data-session-src]')].map(e=>[e.dataset.session,e.dataset.sessionSrc]));\n const order=[...srcs.keys()];\n const urls=[...fig.querySelectorAll('[data-url]')].map(e=>({s:e.dataset.s,t:Number(e.dataset.at),u:e.dataset.url}));\n const dead=new Set(),errs=new Map(),empty=d.getElementById(p+'-none');let shown=0,cur=v.dataset.session,down=null,held=false,ask=0,auto=false,rate=1,raf=0,drag=false;\n const play=c.querySelector('.play'),now=c.querySelector('.now'),total=c.querySelector('.total'),bar=c.querySelector('.scrub'),head=c.querySelector('.head'),tracks=[...c.querySelectorAll('.track')];\n v.removeAttribute('controls');c.hidden=false;\n const big=d.getElementById(p+'-start');\n if(big){big.hidden=false;big.addEventListener('click',()=>{grow();v.play().catch(()=>{})});v.addEventListener('play',()=>big.remove(),{once:true})}\n const track=()=>tracks.find(t=>t.dataset.s===cur);\n const len=()=>{const t=track(),n=t?Number(t.dataset.total):0;return n>0?n:(isFinite(v.duration)?v.duration:0)};\n const paint=()=>{\n const L=len(),t=v.currentTime,f=L?Math.min(1,t/L):0,k=track();\n tracks.forEach(x=>{x.hidden=x!==k});head.style.left=(f*100)+'%';\n const done=k&&k.querySelector('.done');if(done)done.style.width=(f*100)+'%';\n now.textContent=clock(t);total.textContent=clock(L);\n bar.setAttribute('aria-valuemax',String(Math.round(L)));bar.setAttribute('aria-valuenow',String(Math.round(t)));bar.setAttribute('aria-valuetext',clock(t)+' of '+clock(L));\n play.classList.toggle('playing',!v.paused);play.setAttribute('aria-label',v.paused?'Play':'Pause');\n if(url){let u='';if(down!=='')for(const x of urls){if(x.s===cur&&x.t<=t+0.02)u=x.u}url.textContent=bare(u);url.parentElement.title=u}\n };\n const update=()=>{paint();if(o.tick)o.tick(v.currentTime)};\n const frame=()=>{update();raf=v.paused?0:requestAnimationFrame(frame)};\n const show=s=>{if(down===null)held=!v.paused;down=s;v.pause();fig.classList.add('broken');c.hidden=true;if(empty)empty.hidden=true;if(note){++shown;note.hidden=false;const a=note.querySelector('a');if(a){a.href=srcs.get(s);a.textContent=srcs.get(s)}const ft=note.querySelector('.fix-text'),fd=note.querySelector('.fix-done');if(ft){ft.hidden=true;ft.value=''}if(fd)fd.textContent=''}if(o.broken)o.broken()};\n const fine=()=>{if(down===null)return;down=null;fig.classList.remove('broken');c.hidden=false;if(note)note.hidden=true;if(empty)empty.hidden=true;if(o.fine)o.fine()};\n const none=()=>{if(down===null)held=!v.paused;++ask;auto=false;down='';v.pause();fig.classList.add('broken');c.hidden=true;if(note)note.hidden=true;if(empty)empty.hidden=false;paint();if(o.broken)o.broken()};\n const playing=()=>down===null?!v.paused:held;\n const next=s=>order.slice(order.indexOf(s)+1).find(n=>!dead.has(n));\n const load=(s,t,go,a)=>{\n const my=++ask;auto=!!a;if(dead.has(s))return show(s);\n if(s!==cur||!v.currentSrc||v.error){cur=s;v.dataset.session=s;v.src=srcs.get(s);v.load()}\n const done=()=>{if(my!==ask)return;auto=false;fine();v.playbackRate=rate;v.currentTime=t;update();if(go)v.play().catch(()=>{})};\n if(v.readyState>0)done();else v.addEventListener('loadedmetadata',done,{once:true});\n };\n const bad=()=>{const e=v.error;if(!e)return;dead.add(cur);errs.set(cur,'error code '+e.code+(e.message?': '+e.message:''));if(down==='')return;const n=auto?next(cur):undefined;if(n!==undefined)return load(n,0,true,true);auto=false;show(cur)};\n ['timeupdate','seeked','loadedmetadata','pause','play','durationchange'].forEach(n=>v.addEventListener(n,update));\n v.addEventListener('play',()=>{if(!raf)raf=requestAnimationFrame(frame)});\n addEventListener('resize',update);\n v.addEventListener('error',bad);if(v.error)queueMicrotask(bad);\n const fix=d.getElementById(p+'-fix');\n if(fix){const box=fix.parentElement,ta=box.querySelector('.fix-text'),said=box.querySelector('.fix-done');\n fix.addEventListener('click',()=>{\n let t=ta.dataset.template||'';\n [['video',down?srcs.get(down)||'':''],['page',location.href],['browser',navigator.userAgent],['error',errs.get(down)||'nothing']].forEach(([k,x])=>{t=t.split('{'+k+'}').join(x)});\n const g=shown;ta.value=t;const ok=()=>{if(g!==shown)return;said.textContent='Copied. Paste it into your coding agent.'};\n const by=()=>{if(g!==shown)return;ta.hidden=false;ta.focus();ta.setSelectionRange(0,t.length);ta.scrollTop=0;let c=false;try{c=d.execCommand('copy')}catch(x){}if(c)ok();else said.textContent='Copy the prompt below.'};\n if(navigator.clipboard&&window.isSecureContext)navigator.clipboard.writeText(t).then(ok,by);else by();\n })}\n v.addEventListener('ended',()=>{if(o.ended&&o.ended())return;const n=next(cur);if(n!==undefined)load(n,0,true,true)});\n play.addEventListener('click',()=>{if(v.paused)v.play().catch(()=>{});else v.pause()});\n v.addEventListener('click',()=>{if(down!==null)return;if(grow())v.play().catch(()=>{});else play.click()});\n c.querySelectorAll('[data-rate]').forEach(b=>b.addEventListener('click',()=>{rate=Number(b.dataset.rate);v.playbackRate=rate;v.defaultPlaybackRate=rate;c.querySelectorAll('[data-rate]').forEach(x=>x.setAttribute('aria-pressed',String(x===b)))}));\n const seek=t=>{const L=len();t=Math.max(0,L?Math.min(L,t):t);v.currentTime=t;if(o.seek)o.seek(t);update()};\n const at=e=>{const b=bar.getBoundingClientRect();return Math.max(0,Math.min(1,(e.clientX-b.left)/b.width))*len()};\n bar.addEventListener('pointerdown',e=>{if(e.button>0||down!==null)return;drag=true;bar.setPointerCapture(e.pointerId);seek(at(e))});\n bar.addEventListener('pointermove',e=>{if(drag)seek(at(e))});\n ['pointerup','pointercancel'].forEach(n=>bar.addEventListener(n,()=>{drag=false}));\n bar.addEventListener('keydown',e=>{\n const k=e.key,t=v.currentTime,by={ArrowLeft:-1,ArrowDown:-1,ArrowRight:1,ArrowUp:1,PageDown:-10,PageUp:10}[k];\n const to=by!==undefined?t+by:k==='Home'?0:k==='End'?len():null;if(to===null)return;e.preventDefault();seek(to);\n });\n const full=c.querySelector('.full'),screen=o.full||fig.querySelector('.screen');\n const api=!!(d.fullscreenEnabled&&screen.requestFullscreen),inPage=()=>!!o.inPage&&(o.inPage()||!api);\n const mark=()=>{const f=d.fullscreenElement===screen||screen.classList.contains('focus');full.classList.toggle('out',f);full.setAttribute('aria-label',f?'Exit fullscreen':'Fullscreen');update()};\n let back=0;const focus=on=>{if(on)back=scrollY;screen.classList.toggle('focus',on);scrollTo({top:on?0:back,behavior:'auto'});mark()};\n const grow=()=>{if(!o.expand||!o.inPage||!o.inPage()||d.fullscreenElement||screen.classList.contains('focus'))return false;focus(true);return true};\n if(!api&&!o.inPage)full.hidden=true;\n else{full.addEventListener('click',()=>{const f=screen.classList.contains('focus');if(d.fullscreenElement){d.exitFullscreen().catch(()=>{});if(f)focus(false)}else if(f)focus(false);else if(inPage())focus(true);else screen.requestFullscreen().catch(()=>{})});\n d.addEventListener('fullscreenchange',mark);\n d.addEventListener('keydown',e=>{if(e.key==='Escape'&&!e.defaultPrevented&&screen.classList.contains('focus')&&!d.querySelector('dialog[open]')){e.preventDefault();focus(false)}})}\n d.addEventListener('keydown',e=>{if(e.key!==' '||down!==null||e.defaultPrevented||d.querySelector('dialog[open]')||e.target.closest('button,a,input,textarea,select,summary,[role=slider]'))return;e.preventDefault();play.click()});\n return {v,load,none,playing,update,len,cur:()=>cur,down:()=>down,has:s=>srcs.has(s)};\n};\n";
102
+ export declare const PLAYER_JS = "const d=document,r=d.documentElement,K='screw-bugs-theme';\nconst still=()=>matchMedia('(prefers-reduced-motion: reduce)').matches;\nconst topEdge=()=>{const b=d.querySelector('.menubar');return b?Math.max(0,b.getBoundingClientRect().bottom):0};\nconst pad=n=>String(n).padStart(2,'0');\nconst clock=s=>{s=Math.max(0,Math.floor(s||0));const h=Math.floor(s/3600),m=Math.floor(s%3600/60);return(h?h+':'+pad(m):String(m))+':'+pad(s%60)};\nlet theme='system';try{theme=localStorage.getItem(K)||theme}catch(e){}r.dataset.theme=theme;\nconst themeCycle=(b,key)=>{\n const r=document.documentElement,T=['light','dark','system'],N={light:'Light theme',dark:'Dark theme',system:'Theme from system'};\n const at=()=>{const i=T.indexOf(r.dataset.theme);return i<0?2:i};\n const show=()=>{const i=at(),f=document.getElementById('favicon'),h=f&&f.dataset[T[i]];if(h)f.href=h;b.setAttribute('aria-label',N[T[i]]+'. Switch to '+N[T[(i+1)%3]].toLowerCase());b.title=N[T[i]]};\n show();\n b.addEventListener('click',()=>{const m=T[(at()+1)%3];r.dataset.theme=m;if(key)try{localStorage.setItem(key,m)}catch(e){}show()});\n};\nconst chrome=()=>{\n d.querySelectorAll('.menubar .theme').forEach(b=>{themeCycle(b,K);b.hidden=false});\n if(location.protocol==='http:')d.querySelectorAll('a.share-btn').forEach(a=>{a.hidden=false});\n d.querySelectorAll('time.when[datetime]').forEach(e=>{\n const t=new Date(e.getAttribute('datetime'));if(isNaN(t.getTime()))return;const p={};\n try{new Intl.DateTimeFormat('en-US',{month:'short',day:'numeric',year:'numeric',hour:'2-digit',minute:'2-digit',hourCycle:'h23'}).formatToParts(t).forEach(x=>{p[x.type]=x.value});\n const y=d.createElement('span');y.className='year';y.textContent=', '+p.year;\n e.replaceChildren(p.month+' '+p.day,y,' '+String.fromCharCode(183)+' '+p.hour+':'+p.minute);\n e.title=new Intl.DateTimeFormat('en-US',{dateStyle:'full',timeStyle:'long'}).format(t)}catch(x){}\n });\n d.querySelectorAll('.prompt').forEach(p=>{\n const t=p.querySelector('.prompt-text'),b=p.querySelector('.prompt-more');if(!t||!b)return;\n const fits=()=>{if(!p.classList.contains('open'))b.hidden=t.scrollHeight<=t.clientHeight+1};\n fits();if(window.ResizeObserver)new ResizeObserver(fits).observe(t);if(d.fonts&&d.fonts.ready)d.fonts.ready.then(fits);\n b.addEventListener('click',()=>{const o=p.classList.toggle('open');b.textContent=o?'Show less':'Show full prompt';b.setAttribute('aria-expanded',String(o));fits()});\n });\n};\nconst bare=u=>{const i=u.indexOf('://');return i<0?u:u.slice(i+3)};\nconst player=(p,o)=>{\n const v=d.getElementById(p+'-video'),fig=v.closest('.player'),note=d.getElementById(p+'-unloaded'),c=d.getElementById(p+'-controls'),url=d.getElementById(p+'-url');\n const srcs=new Map([...fig.querySelectorAll('[data-session-src]')].map(e=>[e.dataset.session,e.dataset.sessionSrc]));\n const order=[...srcs.keys()];\n const urls=[...fig.querySelectorAll('[data-url]')].map(e=>({s:e.dataset.s,t:Number(e.dataset.at),u:e.dataset.url}));\n const dead=new Set(),errs=new Map(),empty=d.getElementById(p+'-none');let shown=0,cur=v.dataset.session,down=null,held=false,ask=0,auto=false,rate=1,raf=0,drag=false;\n const play=c.querySelector('.play'),now=c.querySelector('.now'),total=c.querySelector('.total'),bar=c.querySelector('.scrub'),head=c.querySelector('.head'),tracks=[...c.querySelectorAll('.track')];\n v.removeAttribute('controls');c.hidden=false;\n const big=d.getElementById(p+'-start');\n if(big){big.hidden=false;big.addEventListener('click',()=>{grow();v.play().catch(()=>{})});v.addEventListener('play',()=>big.remove(),{once:true})}\n const track=()=>tracks.find(t=>t.dataset.s===cur);\n const len=()=>{const t=track(),n=t?Number(t.dataset.total):0;return n>0?n:(isFinite(v.duration)?v.duration:0)};\n const paint=()=>{\n const L=len(),t=v.currentTime,f=L?Math.min(1,t/L):0,k=track();\n tracks.forEach(x=>{x.hidden=x!==k});head.style.left=(f*100)+'%';\n const done=k&&k.querySelector('.done');if(done)done.style.width=(f*100)+'%';\n now.textContent=clock(t);total.textContent=clock(L);\n bar.setAttribute('aria-valuemax',String(Math.round(L)));bar.setAttribute('aria-valuenow',String(Math.round(t)));bar.setAttribute('aria-valuetext',clock(t)+' of '+clock(L));\n play.classList.toggle('playing',!v.paused);play.setAttribute('aria-label',v.paused?'Play':'Pause');\n if(url){let u='';if(down!=='')for(const x of urls){if(x.s===cur&&x.t<=t+0.02)u=x.u}url.textContent=bare(u);url.parentElement.title=u}\n };\n const update=()=>{paint();if(o.tick)o.tick(v.currentTime)};\n const frame=()=>{update();raf=v.paused?0:requestAnimationFrame(frame)};\n const show=s=>{if(down===null)held=!v.paused;down=s;v.pause();fig.classList.add('broken');c.hidden=true;if(empty)empty.hidden=true;if(note){++shown;note.hidden=false;const a=note.querySelector('a');if(a){a.href=srcs.get(s);a.textContent=srcs.get(s)}const ft=note.querySelector('.fix-text'),fd=note.querySelector('.fix-done');if(ft){ft.hidden=true;ft.value=''}if(fd)fd.textContent=''}if(o.broken)o.broken()};\n const fine=()=>{if(down===null)return;down=null;fig.classList.remove('broken');c.hidden=false;if(note)note.hidden=true;if(empty)empty.hidden=true;if(o.fine)o.fine()};\n const none=()=>{if(down===null)held=!v.paused;++ask;auto=false;down='';v.pause();fig.classList.add('broken');c.hidden=true;if(note)note.hidden=true;if(empty)empty.hidden=false;paint();if(o.broken)o.broken()};\n const playing=()=>down===null?!v.paused:held;\n const next=s=>order.slice(order.indexOf(s)+1).find(n=>!dead.has(n));\n const load=(s,t,go,a)=>{\n const my=++ask;auto=!!a;if(dead.has(s))return show(s);\n if(s!==cur||!v.currentSrc||v.error){cur=s;v.dataset.session=s;v.src=srcs.get(s);v.load()}\n const done=()=>{if(my!==ask)return;auto=false;fine();v.playbackRate=rate;v.currentTime=t;update();if(go)v.play().catch(()=>{})};\n if(v.readyState>0)done();else v.addEventListener('loadedmetadata',done,{once:true});\n };\n const bad=()=>{const e=v.error;if(!e)return;dead.add(cur);errs.set(cur,'error code '+e.code+(e.message?': '+e.message:''));if(down==='')return;const n=auto?next(cur):undefined;if(n!==undefined)return load(n,0,true,true);auto=false;show(cur)};\n ['timeupdate','seeked','loadedmetadata','pause','play','durationchange'].forEach(n=>v.addEventListener(n,update));\n v.addEventListener('play',()=>{if(!raf)raf=requestAnimationFrame(frame)});\n addEventListener('resize',update);\n v.addEventListener('error',bad);if(v.error)queueMicrotask(bad);\n const fix=d.getElementById(p+'-fix');\n if(fix){const box=fix.parentElement,ta=box.querySelector('.fix-text'),said=box.querySelector('.fix-done');\n fix.addEventListener('click',()=>{\n let t=ta.dataset.template||'';\n [['video',down?srcs.get(down)||'':''],['page',location.href],['browser',navigator.userAgent],['error',errs.get(down)||'nothing']].forEach(([k,x])=>{t=t.split('{'+k+'}').join(x)});\n const g=shown;ta.value=t;const ok=()=>{if(g!==shown)return;said.textContent='Copied. Paste it into your coding agent.'};\n const by=()=>{if(g!==shown)return;ta.hidden=false;ta.focus();ta.setSelectionRange(0,t.length);ta.scrollTop=0;let c=false;try{c=d.execCommand('copy')}catch(x){}if(c)ok();else said.textContent='Copy the prompt below.'};\n if(navigator.clipboard&&window.isSecureContext)navigator.clipboard.writeText(t).then(ok,by);else by();\n })}\n v.addEventListener('ended',()=>{if(o.ended&&o.ended())return;const n=next(cur);if(n!==undefined)load(n,0,true,true)});\n play.addEventListener('click',()=>{if(v.paused)v.play().catch(()=>{});else v.pause()});\n v.addEventListener('click',()=>{if(down!==null)return;if(grow())v.play().catch(()=>{});else play.click()});\n c.querySelectorAll('[data-rate]').forEach(b=>b.addEventListener('click',()=>{rate=Number(b.dataset.rate);v.playbackRate=rate;v.defaultPlaybackRate=rate;c.querySelectorAll('[data-rate]').forEach(x=>x.setAttribute('aria-pressed',String(x===b)))}));\n const seek=t=>{const L=len();t=Math.max(0,L?Math.min(L,t):t);v.currentTime=t;if(o.seek)o.seek(t);update()};\n const at=e=>{const b=bar.getBoundingClientRect();return Math.max(0,Math.min(1,(e.clientX-b.left)/b.width))*len()};\n bar.addEventListener('pointerdown',e=>{if(e.button>0||down!==null)return;drag=true;bar.setPointerCapture(e.pointerId);seek(at(e))});\n bar.addEventListener('pointermove',e=>{if(drag)seek(at(e))});\n ['pointerup','pointercancel'].forEach(n=>bar.addEventListener(n,()=>{drag=false}));\n bar.addEventListener('keydown',e=>{\n const k=e.key,t=v.currentTime,by={ArrowLeft:-1,ArrowDown:-1,ArrowRight:1,ArrowUp:1,PageDown:-10,PageUp:10}[k];\n const to=by!==undefined?t+by:k==='Home'?0:k==='End'?len():null;if(to===null)return;e.preventDefault();seek(to);\n });\n const full=c.querySelector('.full'),screen=o.full||fig.querySelector('.screen');\n const api=!!(d.fullscreenEnabled&&screen.requestFullscreen),inPage=()=>!!o.inPage&&(o.inPage()||!api);\n const mark=()=>{const f=d.fullscreenElement===screen||screen.classList.contains('focus');full.classList.toggle('out',f);full.setAttribute('aria-label',f?'Exit fullscreen':'Fullscreen');update()};\n let back=0;const focus=on=>{if(on)back=scrollY;screen.classList.toggle('focus',on);scrollTo({top:on?0:back,behavior:'auto'});mark()};\n const grow=()=>{if(!o.expand||!o.inPage||!o.inPage()||d.fullscreenElement||screen.classList.contains('focus'))return false;focus(true);return true};\n if(!api&&!o.inPage)full.hidden=true;\n else{full.addEventListener('click',()=>{const f=screen.classList.contains('focus');if(d.fullscreenElement){d.exitFullscreen().catch(()=>{});if(f)focus(false)}else if(f)focus(false);else if(inPage())focus(true);else screen.requestFullscreen().catch(()=>{})});\n d.addEventListener('fullscreenchange',mark);\n d.addEventListener('keydown',e=>{if(e.key==='Escape'&&!e.defaultPrevented&&screen.classList.contains('focus')&&!d.querySelector('dialog[open]')){e.preventDefault();focus(false)}})}\n d.addEventListener('keydown',e=>{if(e.key!==' '||down!==null||e.defaultPrevented||d.querySelector('dialog[open]')||e.target.closest('button,a,input,textarea,select,summary,[role=slider]'))return;e.preventDefault();play.click()});\n return {v,load,none,playing,update,len,cur:()=>cur,down:()=>down,has:s=>srcs.has(s)};\n};\n";
@@ -188,8 +188,8 @@ export const share = (ms, of) => of === undefined || of <= 0
188
188
  : `${Math.round(Math.max(0, Math.min(1, ms / of)) * 1e6) / 1e4}%`;
189
189
  /**
190
190
  * The script both pages start with: the theme (set before anything is painted, kept where the
191
- * browser allows, and the menu bar's theme button, `THEME_BUTTON_JS`), the Share button (shown only on a page the local report server served: `http:`
192
- * on 127.0.0.1 or localhost), where the sticky menu bar ends (`topEdge`), when the run started in the reader's
191
+ * browser allows, and the menu bar's theme button, `THEME_BUTTON_JS`), the Share button (shown only on a page served over `http:`, as the local report server serves
192
+ * it), where the sticky menu bar ends (`topEdge`), when the run started in the reader's
193
193
  * own time zone (`Nov 4, 2026 · 23:50`, with the full date and zone as its title), the prompt's
194
194
  * "Show full prompt" (offered only when it does not fit, measured again whenever the prompt's box
195
195
  * changes size and once the page's fonts have loaded; while open it stays, as "Show less"), and `player(prefix, hooks)`, which takes over the video:
@@ -223,7 +223,7 @@ let theme='system';try{theme=localStorage.getItem(K)||theme}catch(e){}r.dataset.
223
223
  ${THEME_BUTTON_JS}
224
224
  const chrome=()=>{
225
225
  d.querySelectorAll('.menubar .theme').forEach(b=>{themeCycle(b,K);b.hidden=false});
226
- if(location.protocol==='http:'&&(location.hostname==='127.0.0.1'||location.hostname==='localhost'))d.querySelectorAll('a.share-btn').forEach(a=>{a.hidden=false});
226
+ if(location.protocol==='http:')d.querySelectorAll('a.share-btn').forEach(a=>{a.hidden=false});
227
227
  d.querySelectorAll('time.when[datetime]').forEach(e=>{
228
228
  const t=new Date(e.getAttribute('datetime'));if(isNaN(t.getTime()))return;const p={};
229
229
  try{new Intl.DateTimeFormat('en-US',{month:'short',day:'numeric',year:'numeric',hour:'2-digit',minute:'2-digit',hourCycle:'h23'}).formatToParts(t).forEach(x=>{p[x.type]=x.value});
@@ -0,0 +1,48 @@
1
+ /** The quality the upload's page encodes screenshots with (0 to 1). */
2
+ export declare const SHARE_WEBP_QUALITY = 0.8;
3
+ /** How often the upload's page asks how the share is going, in milliseconds. */
4
+ export declare const SHARE_POLL_MS = 500;
5
+ /** Plain ES2020, without backslashes. */
6
+ export declare const SHARE_PAGE_SCRIPT = "(() => {\n const d = document, r = d.documentElement, K = 'screw-bugs-theme';\n let theme = 'system'; try { theme = localStorage.getItem(K) || theme; } catch (e) {} r.dataset.theme = theme;\n const themeCycle=(b,key)=>{\n const r=document.documentElement,T=['light','dark','system'],N={light:'Light theme',dark:'Dark theme',system:'Theme from system'};\n const at=()=>{const i=T.indexOf(r.dataset.theme);return i<0?2:i};\n const show=()=>{const i=at(),f=document.getElementById('favicon'),h=f&&f.dataset[T[i]];if(h)f.href=h;b.setAttribute('aria-label',N[T[i]]+'. Switch to '+N[T[(i+1)%3]].toLowerCase());b.title=N[T[i]]};\n show();\n b.addEventListener('click',()=>{const m=T[(at()+1)%3];r.dataset.theme=m;if(key)try{localStorage.setItem(key,m)}catch(e){}show()});\n};\n const t = d.querySelector('.menubar .theme'); if (t) { themeCycle(t, K); t.hidden = false; }\n const c = d.getElementById('copy');\n if (c) {\n const label = c.querySelector('.copy-label'), was = label.textContent;\n let timer;\n c.hidden = false;\n c.addEventListener('click', async () => {\n const code = c.dataset.code;\n let ok = false;\n try { await navigator.clipboard.writeText(code); ok = true; } catch (e) {}\n if (!ok) {\n const a = d.createElement('textarea');\n a.value = code; a.setAttribute('readonly', ''); a.style.position = 'fixed'; a.style.opacity = '0';\n d.body.append(a); a.select();\n try { ok = d.execCommand('copy'); } catch (e) {}\n a.remove();\n }\n label.textContent = ok ? 'Copied' : 'Select the code to copy it';\n c.classList.toggle('copied', ok);\n clearTimeout(timer);\n timer = setTimeout(() => { label.textContent = was; c.classList.remove('copied'); }, 2000);\n });\n }\n const b = d.body.dataset;\n if (b.refresh) setTimeout(() => location.reload(), Number(b.refresh) * 1000);\n if (b.wait) {\n const tick = async () => {\n try {\n const res = await fetch(location.href, { redirect: 'manual', cache: 'no-store' });\n if (res.type === 'opaqueredirect' || res.status !== 200) return location.reload();\n // The page's own phase, read from its body (the text also holds this script).\n const next = new DOMParser().parseFromString(await res.text(), 'text/html').body;\n if (next.dataset.phase !== 'pairing') return location.reload();\n } catch (e) {}\n setTimeout(tick, Number(b.wait) * 1000);\n };\n setTimeout(tick, Number(b.wait) * 1000);\n }\n if (b.phase === 'following') {\n const ask = (route, path) =>\n route + '?state=' + encodeURIComponent(b.state) +\n (path === undefined ? '' : '&path=' + encodeURIComponent(path));\n const text = d.getElementById('text'), bar = d.getElementById('bar');\n const shot = d.getElementById('shot'), name = d.getElementById('name');\n let shown;\n const show = (path) => {\n if (path === shown) return;\n shown = path;\n name.textContent = path === undefined ? '' : path;\n if (path !== undefined && /[.](png|jpe?g|webp)$/i.test(path)) {\n shot.src = '/' + encodeURIComponent(b.run) + '/' + path.split('/').map(encodeURIComponent).join('/');\n shot.hidden = false;\n } else {\n shot.hidden = true;\n shot.removeAttribute('src');\n }\n };\n const say = (sentence, done, total) => {\n text.textContent = sentence;\n if (total > 0) { bar.max = total; bar.value = done; } else bar.removeAttribute('value');\n };\n const webp = async (blob) => {\n const bitmap = await createImageBitmap(blob);\n try {\n if (typeof OffscreenCanvas === 'function') {\n const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);\n canvas.getContext('2d', { alpha: false }).drawImage(bitmap, 0, 0);\n return await canvas.convertToBlob({ type: 'image/webp', quality: 0.8 });\n }\n const canvas = d.createElement('canvas');\n canvas.width = bitmap.width;\n canvas.height = bitmap.height;\n canvas.getContext('2d', { alpha: false }).drawImage(bitmap, 0, 0);\n return await new Promise((done) => canvas.toBlob(done, 'image/webp', 0.8));\n } finally {\n bitmap.close();\n }\n };\n // Each screenshot once, one at a time; anything that goes wrong hands back nothing, and the\n // original goes up instead. A 410 means the server stopped waiting.\n let encoding = false;\n const encode = async (files) => {\n encoding = true;\n for (const file of files) {\n show(file.path);\n let made = null;\n try {\n const source = await fetch(ask(b.source, file.path), { cache: 'no-store' });\n if (source.ok) {\n const blob = await webp(await source.blob());\n if (blob && blob.type === 'image/webp' && blob.size < file.size) made = blob;\n }\n } catch (e) {}\n let answer;\n try {\n answer = await fetch(ask(b.encoded, file.path), {\n method: 'POST',\n headers: { 'content-type': 'image/webp' },\n body: made || new Blob([]),\n });\n } catch (e) {\n return;\n }\n if (answer.status === 410) return;\n }\n };\n const poll = async () => {\n let status;\n try {\n const answer = await fetch(ask(b.status), { cache: 'no-store' });\n if (answer.status !== 200) return location.reload();\n status = await answer.json();\n } catch (e) {\n return setTimeout(poll, 500 * 4);\n }\n if (status.phase === 'preparing') {\n say('Making the screenshots smaller: ' + status.settled + ' of ' + status.files.length + '.', status.settled, status.files.length);\n if (!encoding) encode(status.files);\n } else if (status.phase === 'uploading') {\n say(\n status.total === 0\n ? 'Uploading the report\u2026'\n : 'Uploading screenshots and videos: ' + status.done + ' of ' + status.total + '.',\n status.done,\n status.total,\n );\n show(status.current[status.current.length - 1]);\n } else return location.reload();\n setTimeout(poll, 500);\n };\n poll();\n }\n})();";
7
+ /**
8
+ * The pages' policy: their own styles and script, the fonts, nothing else; never in a frame. A
9
+ * page with a form may post it to this server, then follow its redirect to `formTo` (Cloud).
10
+ */
11
+ export declare const sharePageCsp: (formTo?: string) => string;
12
+ export interface SharePage {
13
+ readonly title: string;
14
+ /** Plain text under the title. */
15
+ readonly text: string;
16
+ /** A failure: the title in the failure color. */
17
+ readonly failed?: boolean;
18
+ /** A pairing code to show large, with a Copy button; the page then waits for it to be used. */
19
+ readonly code?: string;
20
+ /** How often the code's page asks whether it moved on, in seconds. */
21
+ readonly wait?: number;
22
+ /** A link to open in a new tab, as the main button. */
23
+ readonly link?: {
24
+ readonly href: string;
25
+ readonly text: string;
26
+ };
27
+ /** A button that posts to `action` on this server, as the main button. */
28
+ readonly form?: {
29
+ readonly action: string;
30
+ readonly label: string;
31
+ };
32
+ /** The report to go back to. */
33
+ readonly back?: string;
34
+ /** Reload after this many seconds (without script, for the upload's page). */
35
+ readonly refresh?: number;
36
+ /** The upload's page: it follows the share `state` of the run `run` live, at `routes`. */
37
+ readonly follow?: {
38
+ readonly state: string;
39
+ readonly run: string;
40
+ readonly routes: {
41
+ readonly status: string;
42
+ readonly source: string;
43
+ readonly encoded: string;
44
+ };
45
+ };
46
+ }
47
+ /** A page of the Share button's routes (see the top of this file). */
48
+ export declare const renderSharePage: (page: SharePage) => string;
@@ -0,0 +1,291 @@
1
+ import { favicon, html, icon, Markup, webFonts } from './markup.js';
2
+ import { githubLink, menuBar, THEME_BUTTON_JS, themeButton } from './menu-bar.js';
3
+ import { cspHash } from './sha256.js';
4
+ import { styles } from './styles.js';
5
+ /*
6
+ * The pages of the Share button's routes on the local report server (`src/cli/share.ts`): asking
7
+ * before a share, the pairing code to type on Screw Bugs Cloud, the upload's progress, and what
8
+ * went wrong. In the reports' look: their menu bar, tokens and type, one card in the middle.
9
+ *
10
+ * Their one script (`SHARE_PAGE_SCRIPT`, allowed by its hash) keeps the theme the reports keep,
11
+ * copies the pairing code (`navigator.clipboard`, which an `http:` tailnet address does not have,
12
+ * else a selected text area), and moves the page on: a page with `data-refresh` reloads after that
13
+ * many seconds; the pairing code's page (`data-phase="pairing"`) asks for itself again every
14
+ * `data-wait` seconds and reloads only once it is no longer the code (so a copy or a selection is
15
+ * not lost every few seconds). Without the script, a meta refresh does both.
16
+ *
17
+ * The upload's page (`data-phase="following"`) follows the share live instead: it asks how it is
18
+ * going (`status`, as JSON) and shows the screenshot going up right now. While the server prepares
19
+ * the share, it makes the screenshots smaller: it fetches each one (`source`), encodes it as WebP
20
+ * at its own size and hands it back (`encoded`), or hands back nothing when it cannot (an empty
21
+ * body: a browser without a WebP encoder, such as Safari, or one that fails). The upload never
22
+ * needs the page; it goes on with the original files when the page is closed or has no script.
23
+ */
24
+ /** The quality the upload's page encodes screenshots with (0 to 1). */
25
+ export const SHARE_WEBP_QUALITY = 0.8;
26
+ /** How often the upload's page asks how the share is going, in milliseconds. */
27
+ export const SHARE_POLL_MS = 500;
28
+ /** Plain ES2020, without backslashes. */
29
+ export const SHARE_PAGE_SCRIPT = `(() => {
30
+ const d = document, r = d.documentElement, K = 'screw-bugs-theme';
31
+ let theme = 'system'; try { theme = localStorage.getItem(K) || theme; } catch (e) {} r.dataset.theme = theme;
32
+ ${THEME_BUTTON_JS}
33
+ const t = d.querySelector('.menubar .theme'); if (t) { themeCycle(t, K); t.hidden = false; }
34
+ const c = d.getElementById('copy');
35
+ if (c) {
36
+ const label = c.querySelector('.copy-label'), was = label.textContent;
37
+ let timer;
38
+ c.hidden = false;
39
+ c.addEventListener('click', async () => {
40
+ const code = c.dataset.code;
41
+ let ok = false;
42
+ try { await navigator.clipboard.writeText(code); ok = true; } catch (e) {}
43
+ if (!ok) {
44
+ const a = d.createElement('textarea');
45
+ a.value = code; a.setAttribute('readonly', ''); a.style.position = 'fixed'; a.style.opacity = '0';
46
+ d.body.append(a); a.select();
47
+ try { ok = d.execCommand('copy'); } catch (e) {}
48
+ a.remove();
49
+ }
50
+ label.textContent = ok ? 'Copied' : 'Select the code to copy it';
51
+ c.classList.toggle('copied', ok);
52
+ clearTimeout(timer);
53
+ timer = setTimeout(() => { label.textContent = was; c.classList.remove('copied'); }, 2000);
54
+ });
55
+ }
56
+ const b = d.body.dataset;
57
+ if (b.refresh) setTimeout(() => location.reload(), Number(b.refresh) * 1000);
58
+ if (b.wait) {
59
+ const tick = async () => {
60
+ try {
61
+ const res = await fetch(location.href, { redirect: 'manual', cache: 'no-store' });
62
+ if (res.type === 'opaqueredirect' || res.status !== 200) return location.reload();
63
+ // The page's own phase, read from its body (the text also holds this script).
64
+ const next = new DOMParser().parseFromString(await res.text(), 'text/html').body;
65
+ if (next.dataset.phase !== 'pairing') return location.reload();
66
+ } catch (e) {}
67
+ setTimeout(tick, Number(b.wait) * 1000);
68
+ };
69
+ setTimeout(tick, Number(b.wait) * 1000);
70
+ }
71
+ if (b.phase === 'following') {
72
+ const ask = (route, path) =>
73
+ route + '?state=' + encodeURIComponent(b.state) +
74
+ (path === undefined ? '' : '&path=' + encodeURIComponent(path));
75
+ const text = d.getElementById('text'), bar = d.getElementById('bar');
76
+ const shot = d.getElementById('shot'), name = d.getElementById('name');
77
+ let shown;
78
+ const show = (path) => {
79
+ if (path === shown) return;
80
+ shown = path;
81
+ name.textContent = path === undefined ? '' : path;
82
+ if (path !== undefined && /[.](png|jpe?g|webp)$/i.test(path)) {
83
+ shot.src = '/' + encodeURIComponent(b.run) + '/' + path.split('/').map(encodeURIComponent).join('/');
84
+ shot.hidden = false;
85
+ } else {
86
+ shot.hidden = true;
87
+ shot.removeAttribute('src');
88
+ }
89
+ };
90
+ const say = (sentence, done, total) => {
91
+ text.textContent = sentence;
92
+ if (total > 0) { bar.max = total; bar.value = done; } else bar.removeAttribute('value');
93
+ };
94
+ const webp = async (blob) => {
95
+ const bitmap = await createImageBitmap(blob);
96
+ try {
97
+ if (typeof OffscreenCanvas === 'function') {
98
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
99
+ canvas.getContext('2d', { alpha: false }).drawImage(bitmap, 0, 0);
100
+ return await canvas.convertToBlob({ type: 'image/webp', quality: ${SHARE_WEBP_QUALITY} });
101
+ }
102
+ const canvas = d.createElement('canvas');
103
+ canvas.width = bitmap.width;
104
+ canvas.height = bitmap.height;
105
+ canvas.getContext('2d', { alpha: false }).drawImage(bitmap, 0, 0);
106
+ return await new Promise((done) => canvas.toBlob(done, 'image/webp', ${SHARE_WEBP_QUALITY}));
107
+ } finally {
108
+ bitmap.close();
109
+ }
110
+ };
111
+ // Each screenshot once, one at a time; anything that goes wrong hands back nothing, and the
112
+ // original goes up instead. A 410 means the server stopped waiting.
113
+ let encoding = false;
114
+ const encode = async (files) => {
115
+ encoding = true;
116
+ for (const file of files) {
117
+ show(file.path);
118
+ let made = null;
119
+ try {
120
+ const source = await fetch(ask(b.source, file.path), { cache: 'no-store' });
121
+ if (source.ok) {
122
+ const blob = await webp(await source.blob());
123
+ if (blob && blob.type === 'image/webp' && blob.size < file.size) made = blob;
124
+ }
125
+ } catch (e) {}
126
+ let answer;
127
+ try {
128
+ answer = await fetch(ask(b.encoded, file.path), {
129
+ method: 'POST',
130
+ headers: { 'content-type': 'image/webp' },
131
+ body: made || new Blob([]),
132
+ });
133
+ } catch (e) {
134
+ return;
135
+ }
136
+ if (answer.status === 410) return;
137
+ }
138
+ };
139
+ const poll = async () => {
140
+ let status;
141
+ try {
142
+ const answer = await fetch(ask(b.status), { cache: 'no-store' });
143
+ if (answer.status !== 200) return location.reload();
144
+ status = await answer.json();
145
+ } catch (e) {
146
+ return setTimeout(poll, ${SHARE_POLL_MS} * 4);
147
+ }
148
+ if (status.phase === 'preparing') {
149
+ say('Making the screenshots smaller: ' + status.settled + ' of ' + status.files.length + '.', status.settled, status.files.length);
150
+ if (!encoding) encode(status.files);
151
+ } else if (status.phase === 'uploading') {
152
+ say(
153
+ status.total === 0
154
+ ? 'Uploading the report…'
155
+ : 'Uploading screenshots and videos: ' + status.done + ' of ' + status.total + '.',
156
+ status.done,
157
+ status.total,
158
+ );
159
+ show(status.current[status.current.length - 1]);
160
+ } else return location.reload();
161
+ setTimeout(poll, ${SHARE_POLL_MS});
162
+ };
163
+ poll();
164
+ }
165
+ })();`;
166
+ /**
167
+ * The pages' policy: their own styles and script, the fonts, nothing else; never in a frame. A
168
+ * page with a form may post it to this server, then follow its redirect to `formTo` (Cloud).
169
+ */
170
+ export const sharePageCsp = (formTo) => "default-src 'none'; img-src 'self' data:; font-src https://fonts.gstatic.com; " +
171
+ "style-src 'unsafe-inline' https://fonts.googleapis.com; " +
172
+ `script-src ${cspHash(SHARE_PAGE_SCRIPT)}; connect-src 'self'; base-uri 'none'; ` +
173
+ "frame-ancestors 'none'; " +
174
+ (formTo === undefined ? "form-action 'none'" : `form-action 'self' ${formTo}`);
175
+ const sharePageStyles = /* css */ `
176
+ html, body { height: 100%; }
177
+ body { display: flex; flex-direction: column; margin: 0; background: var(--bg); color: var(--text); font: var(--t-body); }
178
+ main { display: flex; flex: 1; align-items: center; justify-content: center; padding: 24px 16px 88px; }
179
+ .card { box-sizing: border-box; width: 420px; max-width: 100%; padding: 40px 40px 32px; border: 1px solid var(--border); border-radius: 28px; background: var(--panel); text-align: center; }
180
+ .card h1 { margin: 0 0 16px; font: 700 24px/30px var(--sans); letter-spacing: -0.7px; }
181
+ .card p { margin: 0 0 16px; font: var(--t-body-lg); color: var(--muted); }
182
+ .card.failed h1 { color: var(--fail-text); }
183
+ .code { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 12px; margin: 28px 0; }
184
+ .code output { font: 500 32px/40px var(--mono); letter-spacing: 0.08em; color: var(--text); white-space: nowrap; user-select: all; }
185
+ @media (max-width: 479px) { .card { padding: 32px 20px 24px; } }
186
+ .acts { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 8px; margin-top: 28px; }
187
+ .acts form { margin: 0; }
188
+ .pill { display: inline-flex; align-items: center; justify-content: center; gap: 6px; height: 36px; padding: 0 16px; border: 0; border-radius: 999px; font: var(--t-control); text-decoration: none; cursor: pointer; }
189
+ .pill.primary { background: var(--accent); color: var(--on-accent); font-weight: 500; }
190
+ .pill.primary:hover { filter: brightness(.95); }
191
+ .pill.quiet { background: var(--subtle); color: var(--text); }
192
+ .pill.quiet:hover { background: var(--subtle-hover); }
193
+ .pill.copied { background: var(--accent-subtle); }
194
+ .pill .i-copy, .pill .i-check { display: inline-flex; }
195
+ .pill .i-check, .pill.copied .i-copy { display: none; }
196
+ .pill.copied .i-check { display: inline-flex; }
197
+ .pill .icon { width: 16px; height: 16px; }
198
+ .pill:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
199
+ .follow progress { display: block; width: 100%; height: 6px; margin: 4px 0 20px; accent-color: var(--accent); }
200
+ .follow figure { margin: 0; }
201
+ .follow img { display: block; width: 100%; max-height: 40vh; object-fit: contain; object-position: center top; border: 1px solid var(--border); border-radius: 12px; background: var(--bg); }
202
+ .follow figcaption { margin-top: 8px; font: 12px/16px var(--mono); color: var(--muted); overflow-wrap: anywhere; }
203
+ `;
204
+ /** A page of the Share button's routes (see the top of this file). */
205
+ export const renderSharePage = (page) => {
206
+ const again = page.code === undefined ? page.refresh : page.wait;
207
+ return `<!doctype html>\n${html `<html lang="en">
208
+ <head>
209
+ <meta charset="utf-8" />
210
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
211
+ ${again === undefined
212
+ ? ''
213
+ : html `<noscript><meta http-equiv="refresh" content="${String(again)}" /></noscript>`}
214
+ <title>${`${page.title} · screw-bugs`}</title>
215
+ ${favicon} ${webFonts}
216
+ <style>
217
+ ${new Markup(styles + sharePageStyles)}
218
+ </style>
219
+ </head>
220
+ <body
221
+ ${page.code === undefined ? '' : new Markup('data-phase="pairing"')}
222
+ ${page.follow === undefined
223
+ ? ''
224
+ : html `data-phase="following" data-state="${page.follow.state}"
225
+ data-run="${page.follow.run}" data-status="${page.follow.routes.status}"
226
+ data-source="${page.follow.routes.source}" data-encoded="${page.follow.routes.encoded}"`}
227
+ ${page.code === undefined || page.wait === undefined
228
+ ? ''
229
+ : new Markup(`data-wait="${page.wait}"`)}
230
+ ${page.code === undefined && page.follow === undefined && page.refresh !== undefined
231
+ ? new Markup(`data-refresh="${page.refresh}"`)
232
+ : ''}
233
+ >
234
+ ${menuBar({ ends: html `${githubLink(640)}${themeButton(true)}` })}
235
+ <main>
236
+ <section
237
+ class="${['card', page.failed ? 'failed' : '', page.follow ? 'follow' : ''].filter(Boolean).join(' ')}"
238
+ aria-labelledby="title"
239
+ >
240
+ <h1 id="title">${page.title}</h1>
241
+ <p id="text" aria-live="polite">${page.text}</p>
242
+ ${page.follow === undefined
243
+ ? ''
244
+ : html `<progress id="bar" aria-label="Upload progress"></progress>
245
+ <figure>
246
+ <img id="shot" alt="The screenshot going up now" hidden />
247
+ <figcaption id="name"></figcaption>
248
+ </figure>`}
249
+ ${page.code === undefined
250
+ ? ''
251
+ : html `<div class="code">
252
+ <output aria-label="Pairing code">${page.code}</output>
253
+ <button
254
+ id="copy"
255
+ type="button"
256
+ class="pill quiet"
257
+ data-code="${page.code}"
258
+ hidden
259
+ >
260
+ <span class="i-copy">${icon('copy', { size: 16 })}</span
261
+ ><span class="i-check">${icon('check', { size: 16 })}</span
262
+ ><span class="copy-label">Copy</span>
263
+ </button>
264
+ </div>`}
265
+ ${page.link === undefined && page.form === undefined && page.back === undefined
266
+ ? ''
267
+ : html `<div class="acts">
268
+ ${page.form === undefined
269
+ ? ''
270
+ : html `<form method="post" action="${page.form.action}">
271
+ <button type="submit" class="pill primary">${page.form.label}</button>
272
+ </form>`}
273
+ ${page.link === undefined
274
+ ? ''
275
+ : html `<a
276
+ class="pill primary"
277
+ href="${page.link.href}"
278
+ target="_blank"
279
+ rel="noopener noreferrer"
280
+ >${page.link.text}${icon('external-link', { size: 16 })}</a
281
+ >`}
282
+ ${page.back === undefined
283
+ ? ''
284
+ : html `<a class="pill quiet" href="${page.back}">Back to the report</a>`}
285
+ </div>`}
286
+ </section>
287
+ </main>
288
+ ${new Markup(`<script>${SHARE_PAGE_SCRIPT}</script>`)}
289
+ </body>
290
+ </html>`}`;
291
+ };
@@ -1 +1,3 @@
1
+ export declare const light = "\n --bg: #ffffff; --bg-2: #f9f9f9; --panel: #fcfdfc; --subtle: #eff1ef;\n --border: #d7dad7; --border-strong: #b9bcb8;\n --muted: #60655f; --header: #9a9e98; --text: #1d211c;\n --accent: #94f20d; --on-accent: #1d211c; --accent-subtle: #eef6d6; --accent-border: #abc978;\n --fail: #e54d2e; --fail-text: #d13415; --pass: #8d8d8d;\n --link: #1d211c;\n --input: var(--border-strong); --ring: var(--header);\n --shadow: 0 16px 40px -4px rgba(29, 33, 28, .14), 0 2px 6px rgba(29, 33, 28, .08);\n --scrim: rgba(29, 33, 28, .55);\n --caption: #d7dad7; --caption-border: #b9bcb8; --video-edge: #111210;\n color-scheme: light;\n";
2
+ export declare const dark = "\n --bg: #111210; --bg-2: #181917; --panel: #181917; --subtle: #212220;\n --border: #383a36; --border-strong: #5c625b;\n --muted: #afb5ad; --header: #5c625b; --text: #eceeec;\n --accent: #94f20d; --on-accent: #1d211c; --accent-subtle: #1f2917; --accent-border: #496231;\n --fail: #e54d2e; --fail-text: #ff977d; --pass: #8d8d8d;\n --link: #eceeec;\n --input: var(--border-strong); --ring: var(--muted);\n --shadow: 0 20px 48px -4px rgba(0, 0, 0, .6), 0 2px 6px rgba(0, 0, 0, .4);\n --scrim: rgba(0, 0, 0, .7);\n --caption: #181917; --caption-border: #383a36; --video-edge: #383a36;\n color-scheme: dark;\n";
1
3
  export declare const styles: string;
@@ -12,7 +12,7 @@ import { CROP_WIDE } from './view.js';
12
12
  * markup.ts). Offline, the system's fonts after them in `--sans` and `--mono` take their place,
13
13
  * and no weight or slant is ever faked (`font-synthesis: none`).
14
14
  */
15
- const light = `
15
+ export const light = `
16
16
  --bg: #ffffff; --bg-2: #f9f9f9; --panel: #fcfdfc; --subtle: #eff1ef;
17
17
  --border: #d7dad7; --border-strong: #b9bcb8;
18
18
  --muted: #60655f; --header: #9a9e98; --text: #1d211c;
@@ -25,7 +25,7 @@ const light = `
25
25
  --caption: #d7dad7; --caption-border: #b9bcb8; --video-edge: #111210;
26
26
  color-scheme: light;
27
27
  `;
28
- const dark = `
28
+ export const dark = `
29
29
  --bg: #111210; --bg-2: #181917; --panel: #181917; --subtle: #212220;
30
30
  --border: #383a36; --border-strong: #5c625b;
31
31
  --muted: #afb5ad; --header: #5c625b; --text: #eceeec;