deictic 0.8.1 → 0.10.0

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 (128) hide show
  1. package/API.md +81 -17
  2. package/README.md +1 -1
  3. package/dist/annotations/client.js +1 -1
  4. package/dist/bun.d.ts.map +1 -1
  5. package/dist/bun.js +26 -8
  6. package/dist/bun.js.map +1 -1
  7. package/dist/cli.js +1 -1
  8. package/dist/cli.js.map +1 -1
  9. package/dist/client/index.d.ts +13 -13
  10. package/dist/client/index.d.ts.map +1 -1
  11. package/dist/client/index.js +19 -7
  12. package/dist/client/index.js.map +1 -1
  13. package/dist/next.d.ts.map +1 -1
  14. package/dist/next.js +45 -25
  15. package/dist/next.js.map +1 -1
  16. package/dist/react/client.d.ts +19 -0
  17. package/dist/react/client.d.ts.map +1 -0
  18. package/dist/react/client.js +504 -0
  19. package/dist/react/client.js.map +1 -0
  20. package/dist/react/index.d.ts +2 -0
  21. package/dist/react/index.js +1 -0
  22. package/dist/recommended/index.d.ts +15 -7
  23. package/dist/recommended/index.d.ts.map +1 -1
  24. package/dist/recommended/index.js +1 -1
  25. package/dist/recordings/client.d.ts.map +1 -1
  26. package/dist/recordings/client.js +48 -5
  27. package/dist/recordings/client.js.map +1 -1
  28. package/dist/screenshots/client.d.ts +9 -1
  29. package/dist/screenshots/client.d.ts.map +1 -1
  30. package/dist/screenshots/rrweb.d.ts +0 -6
  31. package/dist/screenshots/rrweb.d.ts.map +1 -1
  32. package/dist/screenshots/rrweb.js +46 -12
  33. package/dist/screenshots/rrweb.js.map +1 -1
  34. package/dist/shared/board.js +1 -1
  35. package/dist/shared/client.js +44 -2
  36. package/dist/shared/client.js.map +1 -1
  37. package/dist/shared/dom.js +7 -1
  38. package/dist/shared/dom.js.map +1 -1
  39. package/dist/shared/drawer.js +1 -1
  40. package/dist/shared/endpoints.js +15 -4
  41. package/dist/shared/endpoints.js.map +1 -1
  42. package/dist/shared/index.d.ts +11 -0
  43. package/dist/shared/index.d.ts.map +1 -1
  44. package/dist/shared/index10.d.ts +70 -0
  45. package/dist/shared/index10.d.ts.map +1 -0
  46. package/dist/shared/index3.d.ts +11 -0
  47. package/dist/shared/index3.d.ts.map +1 -1
  48. package/dist/shared/index7.d.ts +92 -312
  49. package/dist/shared/index7.d.ts.map +1 -1
  50. package/dist/shared/index8.d.ts +324 -47
  51. package/dist/shared/index8.d.ts.map +1 -1
  52. package/dist/shared/index9.d.ts +45 -63
  53. package/dist/shared/index9.d.ts.map +1 -1
  54. package/dist/shared/init.js +15 -11
  55. package/dist/shared/init.js.map +1 -1
  56. package/dist/shared/integration.d.ts +6 -0
  57. package/dist/shared/integration.d.ts.map +1 -1
  58. package/dist/shared/integration.js +28 -1
  59. package/dist/shared/integration.js.map +1 -1
  60. package/dist/shared/marks.js +7 -1
  61. package/dist/shared/marks.js.map +1 -1
  62. package/dist/shared/package.js +3 -1
  63. package/dist/shared/packages.js +1 -1
  64. package/dist/shared/playwright.js +39 -1
  65. package/dist/shared/playwright.js.map +1 -1
  66. package/dist/shared/react.js +25 -0
  67. package/dist/shared/react.js.map +1 -0
  68. package/dist/shared/recommended.js +6 -3
  69. package/dist/shared/recommended.js.map +1 -1
  70. package/dist/shared/recording.js +80 -3
  71. package/dist/shared/recording.js.map +1 -1
  72. package/dist/shared/recordings.js +30 -2
  73. package/dist/shared/recordings.js.map +1 -1
  74. package/dist/shared/screenshots.js.map +1 -1
  75. package/dist/shared/src.js.map +1 -1
  76. package/dist/shared/task.js +1 -0
  77. package/dist/shared/task.js.map +1 -1
  78. package/dist/shared/tasks.js +11 -0
  79. package/dist/shared/tasks.js.map +1 -1
  80. package/dist/shared/vite.d.ts +1 -1
  81. package/dist/shared/vite.d.ts.map +1 -1
  82. package/dist/shared/vite.js +28 -10
  83. package/dist/shared/vite.js.map +1 -1
  84. package/dist/tailwind/client.d.ts +1 -1
  85. package/dist/tailwind/index.d.ts +1 -1
  86. package/dist/tasks/client.d.ts +1 -1
  87. package/dist/tasks/client.js +45 -19
  88. package/dist/tasks/client.js.map +1 -1
  89. package/dist/tasks/index.d.ts +1 -1
  90. package/dist/voice/client.d.ts +1 -1
  91. package/dist/voice/client.js +1 -1
  92. package/dist/voice/index.d.ts +1 -1
  93. package/dist/webpack.d.ts +4 -0
  94. package/dist/webpack.d.ts.map +1 -1
  95. package/dist/webpack.js +37 -15
  96. package/dist/webpack.js.map +1 -1
  97. package/package.json +25 -1
  98. package/src/bun.ts +32 -8
  99. package/src/cli/bun.ts +2 -2
  100. package/src/cli/init.ts +14 -9
  101. package/src/cli/recording.ts +90 -4
  102. package/src/cli/task.ts +4 -0
  103. package/src/cli.ts +13 -6
  104. package/src/client/dom.ts +14 -0
  105. package/src/client/index.ts +25 -14
  106. package/src/index.ts +11 -0
  107. package/src/next.ts +34 -15
  108. package/src/plugins/react/client.ts +162 -0
  109. package/src/plugins/react/index.ts +130 -0
  110. package/src/plugins/react/renders.ts +219 -0
  111. package/src/plugins/react/serialize.ts +139 -0
  112. package/src/plugins/react/timeline.ts +143 -0
  113. package/src/plugins/recommended/index.ts +17 -5
  114. package/src/plugins/recordings/client.ts +64 -4
  115. package/src/plugins/recordings/marks.ts +7 -0
  116. package/src/plugins/recordings/replay.ts +30 -2
  117. package/src/plugins/screenshots/client.ts +42 -2
  118. package/src/plugins/screenshots/index.ts +11 -0
  119. package/src/plugins/screenshots/playwright.ts +65 -1
  120. package/src/plugins/screenshots/rrweb.ts +55 -28
  121. package/src/plugins/screenshots/states.ts +26 -0
  122. package/src/plugins/tasks/client.ts +41 -6
  123. package/src/plugins/tasks/composer.ts +24 -7
  124. package/src/plugins/tasks/index.ts +16 -2
  125. package/src/tools/integration.ts +33 -0
  126. package/src/tools/source.ts +14 -2
  127. package/src/vite.ts +31 -10
  128. package/src/webpack.ts +48 -16
@@ -1 +1 @@
1
- {"version":3,"file":"recordings.js","names":[],"sources":["../../src/plugins/recordings/replay.ts","../../src/plugins/recordings/index.ts"],"sourcesContent":["/**\n * The replay page, `replay/<id>`: rrweb's own player (`rrweb-player`), its timeline, speeds, skipping idle\n * stretches and fullscreen, sized to the window, with what it doesn't do drawn over it:\n *\n * - The page shows in the colour scheme it was recorded in, whatever the viewer's: the replay's iframe\n * answers `prefers-color-scheme` as the viewer's browser does, so the recorded CSS's queries are rewritten\n * before it's replayed, the recorded scheme's to always match and the other's never.\n * - The marks drawn while recording come as custom events, an SVG in page coordinates each; they're drawn\n * over the replay in the player's own scaled wrapper, moved with its scroll, rather than into its document,\n * which the replayer rebuilds. Each is a marker on the timeline.\n * - The voice clips play in step, at the player's speed. A recording with voice starts paused, as a browser\n * plays sound only after a click.\n * - What the page logged and asked for (rrweb's console and network plugins' events, which its player doesn't\n * show) is a list beside the replay, where the window has the room: the row the replay is at is lit, a click on\n * one goes to its moment and shows the rest of it, and each error and failed request is a mark on the timeline.\n * - A recorded canvas is replayed (`UNSAFE_replayCanvas`, which lets the replay's frame run rrweb's own script\n * to draw it), for a recording that has one.\n *\n * `?t=<seconds>` opens it paused there, and `&bare` without the controls at the recorded size, 1:1, for a\n * screenshot; `?embed` is it filling a frame, with no header of its own (the lightbox's); `body[data-ready]` says\n * it's in place.\n *\n * The plugin's routes serve it, the player and what it plays. A page with no server behind it (a `standalone` build)\n * publishes it as a file instead, `replayPage(sources)`: which recording is `?id=`, and a script of its own says\n * where one is.\n */\nimport { MARKS } from './marks.ts';\n\n/** Where the replay page finds what the plugin's routes would serve it, for a page published as a file. */\nexport interface ReplaySources {\n /** The folder `player.js` and `player.css` are in (`rrweb-player`'s `rrweb-player.umd.min.cjs` and `style.css`), from the page: `..`, the routes', by default. */\n player?: string;\n /**\n * A script, from the page, that sets `globalThis.deicticReplay` before the page asks: `recording(id)` answers the\n * recording (a `Kept`) and `clip(id)` a voice clip's URL, either as a promise. The routes by default.\n */\n source?: string;\n}\n\n/** The replay page's HTML: the routes' as it is, or one for a page published as a file. */\nexport const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!doctype html>\n<html lang=\"en\">\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Recording · deictic</title>\n<link rel=\"stylesheet\" href=\"${player}/player.css\">\n<style>\n :root { color-scheme: dark; --accent: #12b358; }\n body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; background: #18181b; color: #fafafa; font: 13px/1.4 system-ui, sans-serif; }\n header { display: flex; gap: 10px; align-items: center; padding: 10px 16px; border-bottom: 1px solid #3f3f46; }\n header a { color: #a1a1aa; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n #stage { flex: 1; display: flex; min-height: 0; }\n main { flex: 1; min-width: 0; display: flex; justify-content: center; align-items: flex-start; padding: 16px; }\n body.bare header { display: none; }\n body.bare main { padding: 0; }\n body.embed header { display: none; }\n body.embed main { padding: 0; }\n /* What the page logged and asked for, beside the replay: the window's height, its list scrolling in it. */\n #log { display: none; flex: none; width: 340px; flex-direction: column; border-left: 1px solid #3f3f46; background: #1f1f23; }\n body.logged { height: 100vh; }\n body.logged #log { display: flex; }\n @media (max-width: 899px) { body.logged #log { display: none; } }\n #log .filters { display: flex; gap: 6px; padding: 8px; border-bottom: 1px solid #3f3f46; }\n #log .filters button { padding: 3px 8px; border: 1px solid #3f3f46; border-radius: 6px; background: none; color: #a1a1aa; font: inherit; font-size: 12px; cursor: pointer; }\n #log .filters button[aria-pressed='true'] { color: #fafafa; background: #3f3f46; }\n #log ol { flex: 1; min-height: 0; overflow: auto; margin: 0; padding: 0; list-style: none; font: 12px/1.45 ui-monospace, monospace; }\n #log li { border-bottom: 1px solid #2e2e33; border-left: 2px solid transparent; }\n #log li.ahead { opacity: 0.45; }\n #log li.now { border-left-color: var(--accent); background: #27272a; }\n #log li.warn .label { color: #fbbf24; }\n #log li.bad .label, #log li.bad .text { color: #f87171; }\n #log li > button { display: flex; gap: 8px; align-items: baseline; width: 100%; padding: 5px 8px; border: 0; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; }\n #log li > button:hover { background: #2e2e33; }\n #log time { flex: none; color: #71717a; }\n #log .label { flex: none; min-width: 4ch; color: #a1a1aa; }\n #log .text { min-width: 0; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow-wrap: anywhere; }\n #log li.open .text { display: block; white-space: pre-wrap; }\n #log pre { margin: 0; padding: 2px 8px 8px calc(8px + 6ch + 8px); color: #a1a1aa; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; }\n #log.no-console li.console, #log.no-network li.network, #log.only-bad li:not(.bad) { display: none; }\n #main .rr-player .rr-progress .bad-mark { position: absolute; top: -3px; width: 3px; height: 10px; margin-left: -1px; border-radius: 1px; background: #f87171; pointer-events: none; }\n body.embed #main .rr-player { box-shadow: none; border-radius: 0; }\n #marks { position: absolute; left: 0; top: 0; pointer-events: none; z-index: 3; }\n #marks svg { position: absolute; left: 0; top: 0; overflow: visible; }\n .problem { color: #f87171; padding: 16px; }\n /* rrweb-player, in the dark of the rest of deictic. Its rules repeat Svelte's scoping class, so these start\n from #main, which outweighs any number of classes. */\n #main .rr-player { background: #27272a; box-shadow: 0 12px 32px rgb(0 0 0 / 0.5); border-radius: 8px; overflow: hidden; }\n body.bare #main .rr-player { box-shadow: none; border-radius: 0; }\n #main .rr-player .rr-player__frame { background: #fff; }\n #main .rr-player .rr-controller { background: #18181b; border-top: 1px solid #3f3f46; border-radius: 0; }\n #main .rr-player .rr-timeline__time { color: #a1a1aa; font: 12px ui-monospace, monospace; }\n #main .rr-player .rr-progress { background: #3f3f46; border-color: #18181b; }\n #main .rr-player .rr-progress__step { background: color-mix(in srgb, var(--accent) 45%, transparent); }\n #main .rr-player .rr-progress__handler { background: var(--accent); }\n #main .rr-player .rr-controller__btns button { color: #e4e4e7; }\n #main .rr-player .rr-controller__btns button:disabled { color: #52525b; }\n #main .rr-player .rr-controller__btns button svg { fill: currentColor; }\n #main .rr-player .rr-controller__btns button.active { color: #04130b; background: var(--accent); }\n #main .rr-player .rr-controller__btns button:active { background: color-mix(in srgb, var(--accent) 60%, transparent); }\n #main .rr-player .switch .label { color: #e4e4e7; }\n #main .rr-player .switch.disabled .label { color: #52525b; }\n #main .rr-player .switch label:before { background: #52525b; }\n #main .rr-player .switch input:checked + label:before { background: var(--accent); }\n</style>\n<header>\n <strong>Recording</strong>\n <a id=\"page\" target=\"_blank\" rel=\"noreferrer\"></a>\n</header>\n<div id=\"stage\">\n <main id=\"main\"></main>\n <aside id=\"log\" aria-label=\"Console and network\">\n <div class=\"filters\">\n <button type=\"button\" data-hides=\"no-console\" aria-pressed=\"true\">Console</button>\n <button type=\"button\" data-hides=\"no-network\" aria-pressed=\"true\">Network</button>\n <button type=\"button\" data-shows=\"only-bad\" aria-pressed=\"false\" title=\"Errors, and requests that failed\">Problems</button>\n </div>\n <ol></ol>\n </aside>\n</div>\n<script src=\"${player}/player.js\"></script>${\n source === undefined\n ? ''\n : `\n<script src=\"${source}\"></script>`\n}\n<script>\n const params = new URLSearchParams(location.search);\n const bare = params.has('bare');\n const embed = params.has('embed');\n if (bare) document.body.classList.add('bare');\n if (embed) document.body.classList.add('embed');\n const id = params.get('id') ?? location.pathname.split('/').at(-1);\n // The plugin's routes, unless the page was given a source of its own (\\`replayPage\\`).\n const from = globalThis.deicticReplay ?? {\n recording: (id) => fetch('../recording/' + id).then((r) => (r.ok ? r.json() : r.text().then((t) => Promise.reject(new Error(t))))),\n clip: (id) => '../../voice/clip/' + id,\n };\n Promise.resolve(from.recording(id)).then(async (kept) => {\n const scheme = kept.colorScheme ?? 'light';\n const events = JSON.parse(\n JSON.stringify(kept.events).replace(/\\\\(\\\\s*prefers-color-scheme\\\\s*:\\\\s*(light|dark)\\\\s*\\\\)/g, (_, s) =>\n s === scheme ? '(min-width: 0px)' : '(max-width: 0px) and (min-width: 1px)',\n ),\n );\n page.textContent = kept.page;\n page.href = kept.page;\n\n // What the page logged and asked for, where the recording has it (rrweb's console and network plugins' events):\n // a row each, in their order, beside the replay. Not in a bare one, which is the page alone.\n const t0 = events[0].timestamp;\n const clock = (ms) => { const s = Math.max(0, ms) / 1000; return Math.floor(s / 60) + ':' + (s % 60).toFixed(1).padStart(4, '0'); };\n // An argument is kept as JSON: a string reads better without its quotes.\n const plain = (arg) => { try { const v = JSON.parse(arg); return typeof v === 'string' ? v : arg; } catch { return arg; } };\n const origin = (() => { try { return new URL(kept.page).origin; } catch { return ''; } })();\n const fields = (title, held) => (held && Object.keys(held).length > 0 ? [title, ...Object.entries(held).map(([k, v]) => ' ' + k + ': ' + v)] : []);\n const rows = [];\n for (const e of events) {\n if (e.type !== 6 || bare) continue;\n const at = e.timestamp - t0;\n if (e.data.plugin === 'rrweb/console@1') {\n const { level, payload = [], trace = [] } = e.data.payload;\n rows.push({ at, kind: 'console', label: level, bad: level === 'error' || level === 'assert', warn: level === 'warn', text: payload.map(plain).join(' '), more: trace.map((l) => 'at ' + l) });\n }\n if (e.data.plugin === 'rrweb/network@1') {\n for (const r of e.data.payload.requests ?? []) {\n // The page's own origin goes without saying.\n let name = r.name;\n try { const u = new URL(r.name); if (u.origin === origin) name = u.pathname + u.search + u.hash; } catch {}\n const more = [\n r.name,\n [r.initiatorType, Number.isFinite(r.duration) ? Math.round(r.duration) + ' ms' : '', e.data.payload.isInitial ? 'as the page loaded' : ''].filter(Boolean).join(' · '),\n ...fields('Request headers', r.requestHeaders),\n ...(r.requestBody ? ['Request body', ' ' + r.requestBody] : []),\n ...fields('Response headers', r.responseHeaders),\n ...(r.responseBody ? ['Response body', ' ' + r.responseBody] : []),\n ];\n // No status is one the browser won't say (another origin's), not one that failed.\n rows.push({ at, kind: 'network', label: r.status ? String(r.status) : '···', bad: r.status >= 400, text: (r.method ? r.method + ' ' : '') + name, more });\n }\n }\n }\n const logged = rows.length > 0;\n const log = document.getElementById('log');\n if (logged) document.body.classList.add('logged');\n // The panel's room, where the window is wide enough to show it (as the stylesheet has it).\n const side = () => (logged && innerWidth >= 900 ? 340 : 0);\n\n // A recording with the mic starts paused: a browser plays sound only after a click, which Play is.\n const clips = await Promise.all((kept.voice ?? []).map(async (c) => ({ ...c, audio: Object.assign(new Audio(await from.clip(c.id)), { preload: 'auto' }) })));\n const t = Number.parseFloat(params.get('t') ?? '');\n // The player's frame, at most the window's room, the controls (80px) under it; 1:1 when bare.\n const size = () => bare\n ? { width: kept.viewport.width, height: kept.viewport.height }\n : embed\n ? { width: innerWidth - side(), height: innerHeight - 80 }\n : { width: Math.min(kept.viewport.width, innerWidth - 32 - side()), height: Math.min(kept.viewport.height, innerHeight - 90 - 80 - 16) };\n const Player = rrwebPlayer.default ?? rrwebPlayer.Player ?? rrwebPlayer;\n const player = new Player({\n target: main,\n props: {\n events,\n ...size(),\n autoPlay: !Number.isFinite(t) && clips.length === 0,\n showController: !bare,\n speedOption: [1, 2, 4, 8],\n tags: { ${JSON.stringify(MARKS)}: '#12b358' },\n inactiveColor: '#3f3f46',\n mouseTail: false,\n // A recorded canvas is drawn by rrweb's own script in the replay's frame, which then must run scripts\n // (the page's own were never recorded): only for a recording that has one.\n ...(events.some((e) => e.type === 3 && e.data.source === 9) ? { UNSAFE_replayCanvas: true } : {}),\n },\n });\n addEventListener('resize', () => { player.$set(size()); player.triggerResize(); });\n const replayer = player.getReplayer();\n const total = player.getMetaData().totalTime;\n\n // The marks as they were at this point: the latest custom event's, in the player's scaled wrapper, moved with the replay's scroll.\n const marks = Object.assign(document.createElement('div'), { id: 'marks' });\n replayer.wrapper.append(marks);\n replayer.on('custom-event', (e) => { if (e.data.tag === ${JSON.stringify(MARKS)}) marks.innerHTML = e.data.payload.svg; });\n\n let playing = false;\n player.addEventListener('ui-update-player-state', (e) => { playing = e.payload === 'playing'; });\n\n // The rows: a click goes to its moment, and shows the rest of it (where a line was logged from, a request's\n // headers and bodies). All set as text: it's the recorded page's, not ours.\n const list = log.querySelector('ol');\n const bar = main.querySelector('.rr-progress');\n for (const row of rows) {\n const cell = (tag, name, text) => Object.assign(document.createElement(tag), { className: name, textContent: text });\n const go = Object.assign(document.createElement('button'), { type: 'button' });\n go.append(cell('time', '', clock(row.at)), cell('span', 'label', row.label), cell('span', 'text', row.text));\n const more = Object.assign(cell('pre', '', row.more.join('\\\\n')), { hidden: true });\n row.el = Object.assign(document.createElement('li'), { className: row.kind + (row.bad ? ' bad' : row.warn ? ' warn' : '') });\n go.addEventListener('click', () => {\n player.goto(Math.min(row.at, total), playing);\n more.hidden = !more.hidden || row.more.length === 0;\n row.el.classList.toggle('open', !more.hidden);\n });\n row.el.append(go, more);\n list.append(row.el);\n // An error, or a request that failed, is a mark on the timeline too.\n if (row.bad && bar) bar.append(Object.assign(cell('i', 'bad-mark', ''), { title: row.text.slice(0, 200), style: 'left:' + (total > 0 ? (row.at / total) * 100 : 0) + '%' }));\n }\n for (const button of log.querySelectorAll('.filters button')) {\n button.addEventListener('click', () => {\n const on = button.getAttribute('aria-pressed') !== 'true';\n button.setAttribute('aria-pressed', String(on));\n if (button.dataset.hides) log.classList.toggle(button.dataset.hides, !on);\n if (button.dataset.shows) log.classList.toggle(button.dataset.shows, on);\n });\n }\n // The row the replay is at: the last whose moment has come, lit, the ones to come faint, kept in sight unless\n // the list is being read.\n let lit;\n const light = (now) => {\n let i = -1;\n while (i + 1 < rows.length && rows[i + 1].at <= now) i++;\n if (i === lit) return;\n lit = i;\n rows.forEach((row, k) => { row.el.classList.toggle('ahead', k > i); row.el.classList.toggle('now', k === i); });\n if (i >= 0 && !log.matches(':hover')) rows[i].el.scrollIntoView({ block: 'nearest' });\n };\n const follow = () => {\n const win = replayer.iframe.contentWindow;\n if (win) marks.style.transform = 'translate(' + -win.scrollX + 'px,' + -win.scrollY + 'px)';\n const now = Math.min(replayer.getCurrentTime(), total);\n light(now);\n const speed = replayer.config.speed ?? 1;\n // Each clip plays while the replay is inside it, at its speed, kept within a few frames of the replay's time.\n for (const c of clips) {\n const into = now - c.at;\n if (!playing || into < 0 || into >= c.duration) { if (!c.audio.paused) c.audio.pause(); continue; }\n if (c.audio.playbackRate !== speed) c.audio.playbackRate = speed;\n if (Math.abs(c.audio.currentTime * 1000 - into) > 250 * speed) c.audio.currentTime = into / 1000;\n if (c.audio.paused) c.audio.play().catch(() => {});\n }\n requestAnimationFrame(follow);\n };\n follow();\n\n if (Number.isFinite(t)) player.goto(Math.min(Math.max(0, t * 1000), total), false);\n document.body.dataset.ready = '';\n }).catch((e) => { document.querySelector('main').innerHTML = '<p class=\"problem\"></p>'; document.querySelector('.problem').textContent = e.message; });\n</script>\n</html>\n`;\n","/**\n * `deictic/recordings`: records the page with rrweb, for other plugins to attach (tasks does). No tab of\n * its own: `use('recordings').record()` shows a toolbar on the page (drag it to any edge) with annotate\n * mode's tools, where that plugin is loaded, a mic where the voice plugin is, and Stop and Discard. What's drawn while recording is in the\n * recording too, as custom events the replay draws.\n *\n * Recordings are kept under `.deictic/recordings`, the latest `keep`, as JSON: rrweb's\n * events, with the page, its viewport and how long it ran. `replay/<id>` plays one back in the browser.\n *\n * The page sends one as it goes (`begin`, then `part/<id>` each second or so, then `end/<id>` or `discard/<id>`),\n * not whole at the end, so it outlasts the page: after a reload, or a link to another page of the site, the next\n * page carries on with the same recording, which then holds each page in turn.\n */\nimport { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join, resolve } from 'node:path';\n\nimport type { record } from 'rrweb';\n\nimport { definePlugin } from '#src/index.ts';\nimport type { Masking, ResolvedMasking } from '#src/plugins/screenshots/index.ts';\nimport { keptIn } from '#src/tools/kept.ts';\n\nimport { replayPage } from './replay.ts';\n\nexport { MARKS } from './marks.ts';\nexport { replayPage, type ReplaySources } from './replay.ts';\n\n/** A recording as the page knows it: its ID, where it plays back, and how long it ran, in milliseconds. */\nexport interface Recording {\n id: string;\n url: string;\n duration: number;\n /** What the mic took while it was on, where the voice plugin is loaded. */\n voice?: VoiceClip[];\n}\n\n/** A stretch of the mic in a recording: the voice plugin's clip, and when it starts in the recording, in milliseconds. */\nexport interface VoiceClip {\n id: string;\n at: number;\n duration: number;\n}\n\n/** The page's half, for other plugins' page halves. */\nexport interface Recorder {\n /**\n * Records the page, with the toolbar, until Stop: answers the recording, kept by the dev server, or\n * nothing when it's discarded. Rejects while another is going, or when it couldn't be kept. A page load\n * doesn't end it: the next page of the site carries on, and `going` there answers what this would have.\n */\n record(): Promise<Recording | undefined>;\n /** Whether one is going. */\n recording(): boolean;\n /** The one going, as `record` answers it: also one a page before this started, carried on here. */\n going(): Promise<Recording | undefined> | undefined;\n}\n\n/** A plugin of rrweb's own, as its `record` takes them: what puts more than the page in a recording. */\nexport type RecordPlugin = NonNullable<NonNullable<Parameters<typeof record>[0]>['plugins']>[number];\n\n/**\n * What a plugin that adds to recordings answers in the page, under its name (`logs` and `network` do): the\n * recorder asks each it knows for its rrweb plugin as a recording starts, so nothing listens before, or after it stops.\n */\nexport interface Recorded {\n /** `sinceLoad`: the recording was going as this page loaded, so what the page did before now is its too. */\n plugin(from: { sinceLoad: boolean }): Promise<RecordPlugin>;\n}\n\n/** The server's half, for other plugins' server halves. */\nexport interface Recordings {\n /** A recording's JSON, or nothing for one not kept (any more). */\n read(id: string): { data: Uint8Array<ArrayBuffer>; name: string; type: 'application/json' } | undefined;\n}\n\n/** What a recording says as it begins: all of a `Kept` that's known then. */\nexport type Meta = Omit<Kept, 'events' | 'duration' | 'voice'>;\n\n/** What's kept: rrweb's events and what they can't say. */\nexport interface Kept {\n /** The page it started on. One that went on to others has each in its events, as rrweb's own: a `Meta`, then a snapshot. */\n page: string;\n viewport: { width: number; height: number };\n /**\n * The colour scheme the page was in, which rrweb doesn't record: the replay shows it in the same, or a\n * page styled by `prefers-color-scheme` would take the replay's.\n */\n colorScheme?: 'light' | 'dark';\n startedAt: number;\n duration: number;\n events: unknown[];\n /** The mic's clips, played along with the replay. */\n voice?: VoiceClip[];\n}\n\ndeclare module 'deictic' {\n interface ServerApis {\n recordings: Recordings;\n }\n interface ClientApis {\n recordings: Recorder;\n }\n}\n\nexport interface RecordingsOptions extends Masking {\n /** How many recordings to keep, the latest: 20 by default. */\n keep?: number;\n /** Where they're kept, from the project's root: `.deictic/recordings` by default. */\n dir?: string;\n /**\n * What a `<canvas>` draws (a chart, a map, WebGL), which is no part of the page's markup: a picture of each\n * canvas that changed, `fps` times a second, 2 by default. `false` for none, and a canvas replays blank.\n */\n canvas?: boolean | { fps?: number };\n}\n\nconst ID = /^[a-z0-9]+-[a-z0-9]+$/;\n/** What one recording may weigh: minutes of a busy page are a few MB. */\nconst MAX = 50 * 1024 * 1024;\n/** How long a recording nobody ended keeps its parts, in milliseconds. */\nconst STALE = 24 * 60 * 60 * 1000;\n\n/** rrweb's player (`rrweb-player`), served to the replay page: its build for a script tag, and its styles. */\nconst player = (file: string) => {\n try {\n return join(dirname(createRequire(import.meta.url).resolve('rrweb-player')), file);\n } catch {\n // Not installed: `file` answers what to add.\n return '';\n }\n};\n\nexport function recordings(options: RecordingsOptions = {}) {\n const keep = options.keep ?? 20;\n let dir = '';\n let taken = 0;\n const pathOf = (id: string) => join(dir, `${id}.json`);\n const read: Recordings['read'] = (id) => {\n if (!ID.test(id) || !existsSync(pathOf(id))) return undefined;\n return { data: new Uint8Array(readFileSync(pathOf(id))), name: `recording-${id}.json`, type: 'application/json' };\n };\n const partOf = (id: string) => join(dir, `${id}.part`);\n /** The recording going on that a request names, as its last segment: its ID, or the answer that there's none. */\n const going = (req: Request): string | Response => {\n const id = new URL(req.url).pathname.split('/').at(-1) ?? '';\n if (ID.test(id) && existsSync(partOf(id))) return id;\n return Response.json({ problem: `no recording ${id} is going any more: record again` }, { status: 404 });\n };\n const json = async <T>(req: Request): Promise<T | undefined> => {\n try {\n return (await req.json()) as T;\n } catch {\n return undefined;\n }\n };\n /** A recording begun: its ID, and the file its parts are added to, which starts with what `Kept` says besides the events. */\n const begin = (meta: Meta) => {\n // Sorts by when it was made, which is what pruning keeps by: the count orders two in one millisecond.\n const id = `${Date.now().toString(36).padStart(9, '0')}${(taken++ % 1296).toString(36).padStart(2, '0')}-${crypto.randomUUID().slice(0, 8)}`;\n mkdirSync(dir, { recursive: true });\n // One nobody ended, as its tab was closed: gone a day on.\n for (const f of readdirSync(dir)) if (f.endsWith('.part') && Date.now() - statSync(join(dir, f)).mtimeMs > STALE) rmSync(join(dir, f));\n\n writeFileSync(partOf(id), `${JSON.stringify(meta)}\\n`);\n return id;\n };\n /** The parts as one recording, in their order whatever order they came in: a page's last may overtake the one before. */\n const end = (id: string, last: Pick<Kept, 'duration' | 'voice'>): boolean => {\n const [meta, ...lines] = readFileSync(partOf(id), 'utf8').trimEnd().split('\\n');\n const parts = lines.map((line) => JSON.parse(line) as { seq: number; events: unknown[] });\n const events = parts.toSorted((a, b) => a.seq - b.seq).flatMap((part) => part.events);\n rmSync(partOf(id));\n if (events.length === 0) return false;\n const kept: Kept = { ...(JSON.parse(meta!) as Meta), ...last, events };\n writeFileSync(pathOf(id), JSON.stringify(kept));\n const all = readdirSync(dir)\n .filter((f) => f.endsWith('.json'))\n .toSorted();\n for (const old of all.slice(0, Math.max(0, all.length - keep))) rmSync(join(dir, old));\n return true;\n };\n const file = (path: string, type: string) => {\n if (!existsSync(path)) return new Response('rrweb-player is missing: add it to your devDependencies', { status: 404 });\n return new Response(readFileSync(path), { headers: { 'content-type': type } });\n };\n\n return definePlugin<never, never, never, Recordings>({\n name: 'recordings',\n client: 'deictic/recordings/client',\n packages: ['rrweb', 'rrweb-player'],\n clientOptions: {\n masking: {\n blockClass: options.blockClass ?? 'rr-block',\n blockSelector: options.blockSelector,\n maskTextClass: options.maskTextClass ?? 'rr-mask',\n maskTextSelector: options.maskTextSelector,\n maskAllInputs: options.maskAllInputs ?? false,\n } satisfies ResolvedMasking,\n canvas: options.canvas === false ? false : { fps: (options.canvas === true ? undefined : options.canvas?.fps) ?? 2 },\n },\n setup: ({ root }) => {\n dir = options.dir === undefined ? keptIn(root, 'recordings') : resolve(root, options.dir);\n return { read };\n },\n routes: {\n // A recording starts: the page, its viewport and when. Its events come in parts, as they happen, so a page\n // load in the middle loses none of them, and the next page carries on under the same ID.\n begin: async (req) => {\n const meta = await json<Partial<Meta>>(req);\n if (meta?.viewport === undefined || typeof meta.page !== 'string' || typeof meta.startedAt !== 'number')\n return Response.json({ problem: 'send the page, its viewport and when it started, as JSON' }, { status: 400 });\n const { page, viewport, colorScheme, startedAt } = meta;\n return Response.json({ id: begin({ page, viewport, ...(colorScheme === undefined ? {} : { colorScheme }), startedAt }) });\n },\n // `part/<id>?seq=<n>`: more of its events, a JSON array, and their place among the parts.\n part: async (req) => {\n const id = going(req);\n if (typeof id !== 'string') return id;\n const seq = Number(new URL(req.url).searchParams.get('seq') ?? 'none');\n const events = await json<unknown>(req);\n if (!Array.isArray(events) || !Number.isInteger(seq))\n return Response.json({ problem: 'send the events as a JSON array, and `seq`, their place' }, { status: 400 });\n const line = `${JSON.stringify({ seq, events })}\\n`;\n if (statSync(partOf(id)).size + line.length > MAX)\n return Response.json({ problem: `a recording may weigh ${MAX / 1024 / 1024} MB at most: stop this one` }, { status: 413 });\n appendFileSync(partOf(id), line);\n return Response.json({ id });\n },\n // `end/<id>`: it's over, and kept: how long it ran, and the mic's clips.\n end: async (req) => {\n const id = going(req);\n if (typeof id !== 'string') return id;\n const last = await json<Partial<Kept>>(req);\n if (typeof last?.duration !== 'number') return Response.json({ problem: 'send how long it ran, as JSON' }, { status: 400 });\n if (!end(id, { duration: last.duration, ...(last.voice === undefined ? {} : { voice: last.voice }) }))\n return Response.json({ problem: 'the recording has no events: record for a moment longer' }, { status: 400 });\n return Response.json({ id });\n },\n // `discard/<id>`: it's over, and not kept.\n discard: (req) => {\n const id = going(req);\n if (typeof id !== 'string') return id;\n rmSync(partOf(id));\n return Response.json({ id });\n },\n // `recording/<id>`: the JSON, for the replay page.\n recording: (req) => {\n const found = read(new URL(req.url).pathname.split('/').at(-1) ?? '');\n if (found === undefined) return new Response('no such recording, or not kept any more', { status: 404 });\n return new Response(found.data, { headers: { 'content-type': found.type, 'cache-control': 'no-store' } });\n },\n // `replay/<id>`: a page that plays it back.\n replay: () => new Response(replayPage(), { headers: { 'content-type': 'text/html; charset=utf-8' } }),\n 'player.js': () => file(player('rrweb-player.umd.min.cjs'), 'text/javascript'),\n 'player.css': () => file(player('style.css'), 'text/css'),\n },\n });\n}\n\nexport default recordings;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,cAAc,EAAE,SAAS,MAAM,WAA0B,CAAC,MAAM;;;;;+BAK9C,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eA0EvB,OAAO,wBACpB,WAAW,KAAA,IACP,KACA;eACS,OAAO,cACrB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAiFiB,KAAK,UAAU,KAAK,EAAE;;;;;;;;;;;;;;;8DAesB,KAAK,UAAU,KAAK,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACvGpF,MAAM,KAAK;;AAEX,MAAM,MAAM;;AAEZ,MAAM,QAAQ;;AAGd,MAAM,UAAU,SAAiB;CAC/B,IAAI;EACF,OAAO,KAAK,QAAQ,cAAc,YAAY,GAAG,CAAC,CAAC,QAAQ,cAAc,CAAC,GAAG,IAAI;CACnF,QAAQ;EAEN,OAAO;CACT;AACF;AAEA,SAAgB,WAAW,UAA6B,CAAC,GAAG;CAC1D,MAAM,OAAO,QAAQ,QAAQ;CAC7B,IAAI,MAAM;CACV,IAAI,QAAQ;CACZ,MAAM,UAAU,OAAe,KAAK,KAAK,GAAG,GAAG,MAAM;CACrD,MAAM,QAA4B,OAAO;EACvC,IAAI,CAAC,GAAG,KAAK,EAAE,KAAK,CAAC,WAAW,OAAO,EAAE,CAAC,GAAG,OAAO,KAAA;EACpD,OAAO;G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OAAO,UAAU,OAAO;IACnC,MAAM,OAAO,MAAM,KAAoB,GAAG;IAC1C,IAAI,OAAO,MAAM,aAAa,UAAU,OAAO,SAAS,KAAK,EAAE,SAAS,gCAAgC,GAAG,EAAE,QAAQ,IAAI,CAAC;IAC1H,IAAI,CAAC,IAAI,IAAI;KAAE,UAAU,KAAK;KAAU,GAAI,KAAK,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,KAAK,MAAM;IAAG,CAAC,GAClG,OAAO,SAAS,KAAK,EAAE,SAAS,0DAA0D,GAAG,EAAE,QAAQ,IAAI,CAAC;IAC9G,OAAO,SAAS,KAAK,EAAE,GAAG,CAAC;GAC7B;GAEA,UAAU,QAAQ;IAChB,MAAM,KAAK,MAAM,GAAG;IACpB,IAAI,OAAO,OAAO,UAAU,OAAO;IACnC,OAAO,OAAO,EAAE,CAAC;IACjB,OAAO,SAAS,KAAK,EAAE,GAAG,CAAC;GAC7B;GAEA,YAAY,QAAQ;IAClB,MAAM,QAAQ,KAAK,IAAI,IAAI,IAAI,GAAG,CAAC,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE;IACpE,IAAI,UAAU,KAAA,GAAW,OAAO,IAAI,SAAS,2CAA2C,EAAE,QAAQ,IAAI,CAAC;IACvG,OAAO,IAAI,SAAS,MAAM,MAAM,EAAE,SAAS;KAAE,gBAAgB,MAAM;KAAM,iBAAiB;IAAW,EAAE,CAAC;GAC1G;GAEA,cAAc,IAAI,SAAS,WAAW,GAAG,EAAE,SAAS,EAAE,gBAAgB,2BAA2B,EAAE,CAAC;GACpG,mBAAmB,KAAK,OAAO,0BAA0B,GAAG,iBAAiB;GAC7E,oBAAoB,KAAK,OAAO,WAAW,GAAG,UAAU;EAC1D;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"recordings.js","names":[],"sources":["../../src/plugins/recordings/replay.ts","../../src/plugins/recordings/index.ts"],"sourcesContent":["/**\n * The replay page, `replay/<id>`: rrweb's own player (`rrweb-player`), its timeline, speeds, skipping idle\n * stretches and fullscreen, sized to the window, with what it doesn't do drawn over it:\n *\n * - The page shows in the colour scheme it was recorded in, whatever the viewer's: the replay's iframe\n * answers `prefers-color-scheme` as the viewer's browser does, so the recorded CSS's queries are rewritten\n * before it's replayed, the recorded scheme's to always match and the other's never.\n * - The marks drawn while recording come as custom events, an SVG in page coordinates each; they're drawn\n * over the replay in the player's own scaled wrapper, moved with its scroll, rather than into its document,\n * which the replayer rebuilds. Each is a marker on the timeline.\n * - The voice clips play in step, at the player's speed. A recording with voice starts paused, as a browser\n * plays sound only after a click.\n * - What the page logged and asked for (rrweb's console and network plugins' events, which its player doesn't\n * show) is a list beside the replay, where the window has the room: the row the replay is at is lit, a click on\n * one goes to its moment and shows the rest of it, and each error and failed request is a mark on the timeline.\n * - A recorded canvas is replayed (`UNSAFE_replayCanvas`, which lets the replay's frame run rrweb's own script\n * to draw it), for a recording that has one.\n *\n * `?t=<seconds>` opens it paused there, and `&bare` without the controls at the recorded size, 1:1, for a\n * screenshot; `?embed` is it filling a frame, with no header of its own (the lightbox's); `body[data-ready]` says\n * it's in place.\n *\n * The plugin's routes serve it, the player and what it plays. A page with no server behind it (a `standalone` build)\n * publishes it as a file instead, `replayPage(sources)`: which recording is `?id=`, and a script of its own says\n * where one is.\n */\nimport { MARKS, REACT } from './marks.ts';\n\n/** Where the replay page finds what the plugin's routes would serve it, for a page published as a file. */\nexport interface ReplaySources {\n /** The folder `player.js` and `player.css` are in (`rrweb-player`'s `rrweb-player.umd.min.cjs` and `style.css`), from the page: `..`, the routes', by default. */\n player?: string;\n /**\n * A script, from the page, that sets `globalThis.deicticReplay` before the page asks: `recording(id)` answers the\n * recording (a `Kept`) and `clip(id)` a voice clip's URL, either as a promise. The routes by default.\n */\n source?: string;\n}\n\n/** The replay page's HTML: the routes' as it is, or one for a page published as a file. */\nexport const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!doctype html>\n<html lang=\"en\">\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Recording · deictic</title>\n<link rel=\"stylesheet\" href=\"${player}/player.css\">\n<style>\n :root { color-scheme: dark; --accent: #12b358; }\n body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; background: #18181b; color: #fafafa; font: 13px/1.4 system-ui, sans-serif; }\n header { display: flex; gap: 10px; align-items: center; padding: 10px 16px; border-bottom: 1px solid #3f3f46; }\n header a { color: #a1a1aa; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n #stage { flex: 1; display: flex; min-height: 0; }\n main { flex: 1; min-width: 0; display: flex; justify-content: center; align-items: flex-start; padding: 16px; }\n body.bare header { display: none; }\n body.bare main { padding: 0; }\n body.embed header { display: none; }\n body.embed main { padding: 0; }\n /* What the page logged and asked for, beside the replay: the window's height, its list scrolling in it. */\n #log { display: none; flex: none; width: 340px; flex-direction: column; border-left: 1px solid #3f3f46; background: #1f1f23; }\n body.logged { height: 100vh; }\n body.logged #log { display: flex; }\n @media (max-width: 899px) { body.logged #log { display: none; } }\n #log .filters { display: flex; gap: 6px; padding: 8px; border-bottom: 1px solid #3f3f46; }\n #log .filters button { padding: 3px 8px; border: 1px solid #3f3f46; border-radius: 6px; background: none; color: #a1a1aa; font: inherit; font-size: 12px; cursor: pointer; }\n #log .filters button[aria-pressed='true'] { color: #fafafa; background: #3f3f46; }\n #log ol { flex: 1; min-height: 0; overflow: auto; margin: 0; padding: 0; list-style: none; font: 12px/1.45 ui-monospace, monospace; }\n #log li { border-bottom: 1px solid #2e2e33; border-left: 2px solid transparent; }\n #log li.ahead { opacity: 0.45; }\n #log li.now { border-left-color: var(--accent); background: #27272a; }\n #log li.warn .label { color: #fbbf24; }\n #log li.bad .label, #log li.bad .text { color: #f87171; }\n #log li > button { display: flex; gap: 8px; align-items: baseline; width: 100%; padding: 5px 8px; border: 0; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; }\n #log li > button:hover { background: #2e2e33; }\n #log time { flex: none; color: #71717a; }\n #log .label { flex: none; min-width: 4ch; color: #a1a1aa; }\n #log .text { min-width: 0; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow-wrap: anywhere; }\n #log li.open .text { display: block; white-space: pre-wrap; }\n #log pre { margin: 0; padding: 2px 8px 8px calc(8px + 6ch + 8px); color: #a1a1aa; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; }\n #log.no-console li.console, #log.no-network li.network, #log.no-react li.react, #log.only-bad li:not(.bad) { display: none; }\n #log li.react .label { color: #58c4dc; }\n #log li.react.warn .label { color: #fbbf24; }\n #main .rr-player .rr-progress .slow-mark { position: absolute; top: -3px; width: 3px; height: 10px; margin-left: -1px; border-radius: 1px; background: #fbbf24; pointer-events: none; }\n #main .rr-player .rr-progress .bad-mark { position: absolute; top: -3px; width: 3px; height: 10px; margin-left: -1px; border-radius: 1px; background: #f87171; pointer-events: none; }\n body.embed #main .rr-player { box-shadow: none; border-radius: 0; }\n #marks { position: absolute; left: 0; top: 0; pointer-events: none; z-index: 3; }\n #marks svg { position: absolute; left: 0; top: 0; overflow: visible; }\n .problem { color: #f87171; padding: 16px; }\n /* rrweb-player, in the dark of the rest of deictic. Its rules repeat Svelte's scoping class, so these start\n from #main, which outweighs any number of classes. */\n #main .rr-player { background: #27272a; box-shadow: 0 12px 32px rgb(0 0 0 / 0.5); border-radius: 8px; overflow: hidden; }\n body.bare #main .rr-player { box-shadow: none; border-radius: 0; }\n #main .rr-player .rr-player__frame { background: #fff; }\n #main .rr-player .rr-controller { background: #18181b; border-top: 1px solid #3f3f46; border-radius: 0; }\n #main .rr-player .rr-timeline__time { color: #a1a1aa; font: 12px ui-monospace, monospace; }\n #main .rr-player .rr-progress { background: #3f3f46; border-color: #18181b; }\n #main .rr-player .rr-progress__step { background: color-mix(in srgb, var(--accent) 45%, transparent); }\n #main .rr-player .rr-progress__handler { background: var(--accent); }\n #main .rr-player .rr-controller__btns button { color: #e4e4e7; }\n #main .rr-player .rr-controller__btns button:disabled { color: #52525b; }\n #main .rr-player .rr-controller__btns button svg { fill: currentColor; }\n #main .rr-player .rr-controller__btns button.active { color: #04130b; background: var(--accent); }\n #main .rr-player .rr-controller__btns button:active { background: color-mix(in srgb, var(--accent) 60%, transparent); }\n #main .rr-player .switch .label { color: #e4e4e7; }\n #main .rr-player .switch.disabled .label { color: #52525b; }\n #main .rr-player .switch label:before { background: #52525b; }\n #main .rr-player .switch input:checked + label:before { background: var(--accent); }\n</style>\n<header>\n <strong>Recording</strong>\n <a id=\"page\" target=\"_blank\" rel=\"noreferrer\"></a>\n</header>\n<div id=\"stage\">\n <main id=\"main\"></main>\n <aside id=\"log\" aria-label=\"Console and network\">\n <div class=\"filters\">\n <button type=\"button\" data-hides=\"no-console\" aria-pressed=\"true\">Console</button>\n <button type=\"button\" data-hides=\"no-network\" aria-pressed=\"true\">Network</button>\n <button type=\"button\" data-hides=\"no-react\" aria-pressed=\"true\" hidden title=\"React's commits: what rendered, how long it took, and why\">React</button>\n <button type=\"button\" data-shows=\"only-bad\" aria-pressed=\"false\" title=\"Errors, and requests that failed\">Problems</button>\n </div>\n <ol></ol>\n </aside>\n</div>\n<script src=\"${player}/player.js\"></script>${\n source === undefined\n ? ''\n : `\n<script src=\"${source}\"></script>`\n}\n<script>\n const params = new URLSearchParams(location.search);\n const bare = params.has('bare');\n const embed = params.has('embed');\n if (bare) document.body.classList.add('bare');\n if (embed) document.body.classList.add('embed');\n const id = params.get('id') ?? location.pathname.split('/').at(-1);\n // The plugin's routes, unless the page was given a source of its own (\\`replayPage\\`).\n const from = globalThis.deicticReplay ?? {\n recording: (id) => fetch('../recording/' + id).then((r) => (r.ok ? r.json() : r.text().then((t) => Promise.reject(new Error(t))))),\n clip: (id) => '../../voice/clip/' + id,\n };\n Promise.resolve(from.recording(id)).then(async (kept) => {\n const scheme = kept.colorScheme ?? 'light';\n const events = JSON.parse(\n JSON.stringify(kept.events).replace(/\\\\(\\\\s*prefers-color-scheme\\\\s*:\\\\s*(light|dark)\\\\s*\\\\)/g, (_, s) =>\n s === scheme ? '(min-width: 0px)' : '(max-width: 0px) and (min-width: 1px)',\n ),\n );\n page.textContent = kept.page;\n page.href = kept.page;\n\n // What the page logged and asked for, where the recording has it (rrweb's console and network plugins' events):\n // a row each, in their order, beside the replay. Not in a bare one, which is the page alone.\n const t0 = events[0].timestamp;\n const clock = (ms) => { const s = Math.max(0, ms) / 1000; return Math.floor(s / 60) + ':' + (s % 60).toFixed(1).padStart(4, '0'); };\n // An argument is kept as JSON: a string reads better without its quotes.\n const plain = (arg) => { try { const v = JSON.parse(arg); return typeof v === 'string' ? v : arg; } catch { return arg; } };\n const origin = (() => { try { return new URL(kept.page).origin; } catch { return ''; } })();\n const fields = (title, held) => (held && Object.keys(held).length > 0 ? [title, ...Object.entries(held).map(([k, v]) => ' ' + k + ': ' + v)] : []);\n const rows = [];\n // React's commits, where the recording had them on: a row an entry, slow ones (past a frame) marked.\n const ms = (n) => (n === undefined ? '' : (n < 10 ? n.toFixed(1) : Math.round(n)) + ' ms');\n for (const e of events) {\n if (e.type !== 5 || bare || e.data.tag !== ${JSON.stringify(REACT)}) continue;\n const at = e.timestamp - t0;\n const c = e.data.payload;\n if (c.on !== undefined) {\n rows.push({ at, kind: 'react', label: 'React', text: c.on ? 'commits recorded from here' : 'commits no longer recorded', more: [] });\n continue;\n }\n const named = (c.components ?? []).map((r) => r.name + (r.count > 1 ? ' ×' + r.count : '') + ' (' + r.why + ')');\n const text = (named.length > 0 ? named.slice(0, 3).join(', ') : (c.more ?? 0) + ' components') + (named.length > 3 || (c.more && named.length > 0) ? ', …' : '');\n const more = [\n [c.commits > 1 ? c.commits + ' commits' + (c.over === undefined ? '' : ' over ' + (c.over / 1000).toFixed(1) + ' s') : '1 commit', c.priority, ms(c.ms), c.slowest === undefined ? '' : 'slowest ' + ms(c.slowest)].filter(Boolean).join(' · '),\n ...(c.components ?? []).map((r) => [r.name + (r.count > 1 ? ' ×' + r.count : ''), r.at, ms(r.ms), r.selfMs === undefined ? '' : ms(r.selfMs) + ' own', r.why].filter(Boolean).join(' · ')),\n ...(c.more ? ['and ' + c.more + ' more'] : []),\n ];\n // One slow commit is what makes a page stutter, not many quick ones.\n const slow = (c.slowest ?? c.ms) > 16;\n rows.push({ at, kind: 'react', label: c.ms === undefined ? 'React' : ms(c.ms), warn: slow, slow, text: (c.over === undefined ? '' : c.commits + ' commits: ') + text, more });\n }\n for (const e of events) {\n if (e.type !== 6 || bare) continue;\n const at = e.timestamp - t0;\n if (e.data.plugin === 'rrweb/console@1') {\n const { level, payload = [], trace = [] } = e.data.payload;\n rows.push({ at, kind: 'console', label: level, bad: level === 'error' || level === 'assert', warn: level === 'warn', text: payload.map(plain).join(' '), more: trace.map((l) => 'at ' + l) });\n }\n if (e.data.plugin === 'rrweb/network@1') {\n for (const r of e.data.payload.requests ?? []) {\n // The page's own origin goes without saying.\n let name = r.name;\n try { const u = new URL(r.name); if (u.origin === origin) name = u.pathname + u.search + u.hash; } catch {}\n const more = [\n r.name,\n [r.initiatorType, Number.isFinite(r.duration) ? Math.round(r.duration) + ' ms' : '', e.data.payload.isInitial ? 'as the page loaded' : ''].filter(Boolean).join(' · '),\n ...fields('Request headers', r.requestHeaders),\n ...(r.requestBody ? ['Request body', ' ' + r.requestBody] : []),\n ...fields('Response headers', r.responseHeaders),\n ...(r.responseBody ? ['Response body', ' ' + r.responseBody] : []),\n ];\n // No status is one the browser won't say (another origin's), not one that failed.\n rows.push({ at, kind: 'network', label: r.status ? String(r.status) : '···', bad: r.status >= 400, text: (r.method ? r.method + ' ' : '') + name, more });\n }\n }\n }\n rows.sort((a, b) => a.at - b.at);\n const logged = rows.length > 0;\n const log = document.getElementById('log');\n if (rows.some((r) => r.kind === 'react')) log.querySelector('[data-hides=\"no-react\"]').hidden = false;\n if (logged) document.body.classList.add('logged');\n // The panel's room, where the window is wide enough to show it (as the stylesheet has it).\n const side = () => (logged && innerWidth >= 900 ? 340 : 0);\n\n // A recording with the mic starts paused: a browser plays sound only after a click, which Play is.\n const clips = await Promise.all((kept.voice ?? []).map(async (c) => ({ ...c, audio: Object.assign(new Audio(await from.clip(c.id)), { preload: 'auto' }) })));\n const t = Number.parseFloat(params.get('t') ?? '');\n // The player's frame, at most the window's room, the controls (80px) under it; 1:1 when bare.\n const size = () => bare\n ? { width: kept.viewport.width, height: kept.viewport.height }\n : embed\n ? { width: innerWidth - side(), height: innerHeight - 80 }\n : { width: Math.min(kept.viewport.width, innerWidth - 32 - side()), height: Math.min(kept.viewport.height, innerHeight - 90 - 80 - 16) };\n const Player = rrwebPlayer.default ?? rrwebPlayer.Player ?? rrwebPlayer;\n const player = new Player({\n target: main,\n props: {\n events,\n ...size(),\n autoPlay: !Number.isFinite(t) && clips.length === 0,\n showController: !bare,\n speedOption: [1, 2, 4, 8],\n tags: { ${JSON.stringify(MARKS)}: '#12b358' },\n inactiveColor: '#3f3f46',\n mouseTail: false,\n // A recorded canvas is drawn by rrweb's own script in the replay's frame, which then must run scripts\n // (the page's own were never recorded): only for a recording that has one.\n ...(events.some((e) => e.type === 3 && e.data.source === 9) ? { UNSAFE_replayCanvas: true } : {}),\n },\n });\n addEventListener('resize', () => { player.$set(size()); player.triggerResize(); });\n const replayer = player.getReplayer();\n const total = player.getMetaData().totalTime;\n\n // The marks as they were at this point: the latest custom event's, in the player's scaled wrapper, moved with the replay's scroll.\n const marks = Object.assign(document.createElement('div'), { id: 'marks' });\n replayer.wrapper.append(marks);\n replayer.on('custom-event', (e) => { if (e.data.tag === ${JSON.stringify(MARKS)}) marks.innerHTML = e.data.payload.svg; });\n\n let playing = false;\n player.addEventListener('ui-update-player-state', (e) => { playing = e.payload === 'playing'; });\n\n // The rows: a click goes to its moment, and shows the rest of it (where a line was logged from, a request's\n // headers and bodies). All set as text: it's the recorded page's, not ours.\n const list = log.querySelector('ol');\n const bar = main.querySelector('.rr-progress');\n for (const row of rows) {\n const cell = (tag, name, text) => Object.assign(document.createElement(tag), { className: name, textContent: text });\n const go = Object.assign(document.createElement('button'), { type: 'button' });\n go.append(cell('time', '', clock(row.at)), cell('span', 'label', row.label), cell('span', 'text', row.text));\n const more = Object.assign(cell('pre', '', row.more.join('\\\\n')), { hidden: true });\n row.el = Object.assign(document.createElement('li'), { className: row.kind + (row.bad ? ' bad' : row.warn ? ' warn' : '') });\n go.addEventListener('click', () => {\n player.goto(Math.min(row.at, total), playing);\n more.hidden = !more.hidden || row.more.length === 0;\n row.el.classList.toggle('open', !more.hidden);\n });\n row.el.append(go, more);\n list.append(row.el);\n // An error, or a request that failed, is a mark on the timeline too.\n if (row.slow && bar) bar.append(Object.assign(cell('i', 'slow-mark', ''), { title: row.label + ': ' + row.text.slice(0, 200), style: 'left:' + (total > 0 ? (row.at / total) * 100 : 0) + '%' }));\n if (row.bad && bar) bar.append(Object.assign(cell('i', 'bad-mark', ''), { title: row.text.slice(0, 200), style: 'left:' + (total > 0 ? (row.at / total) * 100 : 0) + '%' }));\n }\n for (const button of log.querySelectorAll('.filters button')) {\n button.addEventListener('click', () => {\n const on = button.getAttribute('aria-pressed') !== 'true';\n button.setAttribute('aria-pressed', String(on));\n if (button.dataset.hides) log.classList.toggle(button.dataset.hides, !on);\n if (button.dataset.shows) log.classList.toggle(button.dataset.shows, on);\n });\n }\n // The row the replay is at: the last whose moment has come, lit, the ones to come faint, kept in sight unless\n // the list is being read.\n let lit;\n const light = (now) => {\n let i = -1;\n while (i + 1 < rows.length && rows[i + 1].at <= now) i++;\n if (i === lit) return;\n lit = i;\n rows.forEach((row, k) => { row.el.classList.toggle('ahead', k > i); row.el.classList.toggle('now', k === i); });\n if (i >= 0 && !log.matches(':hover')) rows[i].el.scrollIntoView({ block: 'nearest' });\n };\n const follow = () => {\n const win = replayer.iframe.contentWindow;\n if (win) marks.style.transform = 'translate(' + -win.scrollX + 'px,' + -win.scrollY + 'px)';\n const now = Math.min(replayer.getCurrentTime(), total);\n light(now);\n const speed = replayer.config.speed ?? 1;\n // Each clip plays while the replay is inside it, at its speed, kept within a few frames of the replay's time.\n for (const c of clips) {\n const into = now - c.at;\n if (!playing || into < 0 || into >= c.duration) { if (!c.audio.paused) c.audio.pause(); continue; }\n if (c.audio.playbackRate !== speed) c.audio.playbackRate = speed;\n if (Math.abs(c.audio.currentTime * 1000 - into) > 250 * speed) c.audio.currentTime = into / 1000;\n if (c.audio.paused) c.audio.play().catch(() => {});\n }\n requestAnimationFrame(follow);\n };\n follow();\n\n if (Number.isFinite(t)) player.goto(Math.min(Math.max(0, t * 1000), total), false);\n document.body.dataset.ready = '';\n }).catch((e) => { document.querySelector('main').innerHTML = '<p class=\"problem\"></p>'; document.querySelector('.problem').textContent = e.message; });\n</script>\n</html>\n`;\n","/**\n * `deictic/recordings`: records the page with rrweb, for other plugins to attach (tasks does). No tab of\n * its own: `use('recordings').record()` shows a toolbar on the page (drag it to any edge) with annotate\n * mode's tools, where that plugin is loaded, a mic where the voice plugin is, and Stop and Discard. What's drawn while recording is in the\n * recording too, as custom events the replay draws.\n *\n * Recordings are kept under `.deictic/recordings`, the latest `keep`, as JSON: rrweb's\n * events, with the page, its viewport and how long it ran. `replay/<id>` plays one back in the browser.\n *\n * The page sends one as it goes (`begin`, then `part/<id>` each second or so, then `end/<id>` or `discard/<id>`),\n * not whole at the end, so it outlasts the page: after a reload, or a link to another page of the site, the next\n * page carries on with the same recording, which then holds each page in turn.\n */\nimport { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join, resolve } from 'node:path';\n\nimport type { record } from 'rrweb';\n\nimport { definePlugin } from '#src/index.ts';\nimport type { Masking, ResolvedMasking } from '#src/plugins/screenshots/index.ts';\nimport { keptIn } from '#src/tools/kept.ts';\n\nimport { replayPage } from './replay.ts';\n\nexport { MARKS } from './marks.ts';\nexport { replayPage, type ReplaySources } from './replay.ts';\n\n/** A recording as the page knows it: its ID, where it plays back, and how long it ran, in milliseconds. */\nexport interface Recording {\n id: string;\n url: string;\n duration: number;\n /** What the mic took while it was on, where the voice plugin is loaded. */\n voice?: VoiceClip[];\n}\n\n/** A stretch of the mic in a recording: the voice plugin's clip, and when it starts in the recording, in milliseconds. */\nexport interface VoiceClip {\n id: string;\n at: number;\n duration: number;\n}\n\n/** The page's half, for other plugins' page halves. */\nexport interface Recorder {\n /**\n * Records the page, with the toolbar, until Stop: answers the recording, kept by the dev server, or\n * nothing when it's discarded. Rejects while another is going, or when it couldn't be kept. A page load\n * doesn't end it: the next page of the site carries on, and `going` there answers what this would have.\n */\n record(): Promise<Recording | undefined>;\n /** Whether one is going. */\n recording(): boolean;\n /** The one going, as `record` answers it: also one a page before this started, carried on here. */\n going(): Promise<Recording | undefined> | undefined;\n}\n\n/** A plugin of rrweb's own, as its `record` takes them: what puts more than the page in a recording. */\nexport type RecordPlugin = NonNullable<NonNullable<Parameters<typeof record>[0]>['plugins']>[number];\n\n/**\n * What a plugin that adds to recordings answers in the page, under its name (`logs` and `network` do): the\n * recorder asks each it knows for its rrweb plugin as a recording starts, so nothing listens before, or after it stops.\n */\nexport interface Recorded {\n /** `sinceLoad`: the recording was going as this page loaded, so what the page did before now is its too. */\n plugin(from: { sinceLoad: boolean }): Promise<RecordPlugin>;\n}\n\n/** The server's half, for other plugins' server halves. */\nexport interface Recordings {\n /** A recording's JSON, or nothing for one not kept (any more). */\n read(id: string): { data: Uint8Array<ArrayBuffer>; name: string; type: 'application/json' } | undefined;\n}\n\n/** What a recording says as it begins: all of a `Kept` that's known then. */\nexport type Meta = Omit<Kept, 'events' | 'duration' | 'voice'>;\n\n/** What's kept: rrweb's events and what they can't say. */\nexport interface Kept {\n /** The page it started on. One that went on to others has each in its events, as rrweb's own: a `Meta`, then a snapshot. */\n page: string;\n viewport: { width: number; height: number };\n /**\n * The colour scheme the page was in, which rrweb doesn't record: the replay shows it in the same, or a\n * page styled by `prefers-color-scheme` would take the replay's.\n */\n colorScheme?: 'light' | 'dark';\n startedAt: number;\n duration: number;\n events: unknown[];\n /** The mic's clips, played along with the replay. */\n voice?: VoiceClip[];\n}\n\ndeclare module 'deictic' {\n interface ServerApis {\n recordings: Recordings;\n }\n interface ClientApis {\n recordings: Recorder;\n }\n}\n\nexport interface RecordingsOptions extends Masking {\n /** How many recordings to keep, the latest: 20 by default. */\n keep?: number;\n /** Where they're kept, from the project's root: `.deictic/recordings` by default. */\n dir?: string;\n /**\n * What a `<canvas>` draws (a chart, a map, WebGL), which is no part of the page's markup: a picture of each\n * canvas that changed, `fps` times a second, 2 by default. `false` for none, and a canvas replays blank.\n */\n canvas?: boolean | { fps?: number };\n}\n\nconst ID = /^[a-z0-9]+-[a-z0-9]+$/;\n/** What one recording may weigh: minutes of a busy page are a few MB. */\nconst MAX = 50 * 1024 * 1024;\n/** How long a recording nobody ended keeps its parts, in milliseconds. */\nconst STALE = 24 * 60 * 60 * 1000;\n\n/** rrweb's player (`rrweb-player`), served to the replay page: its build for a script tag, and its styles. */\nconst player = (file: string) => {\n try {\n return join(dirname(createRequire(import.meta.url).resolve('rrweb-player')), file);\n } catch {\n // Not installed: `file` answers what to add.\n return '';\n }\n};\n\nexport function recordings(options: RecordingsOptions = {}) {\n const keep = options.keep ?? 20;\n let dir = '';\n let taken = 0;\n const pathOf = (id: string) => join(dir, `${id}.json`);\n const read: Recordings['read'] = (id) => {\n if (!ID.test(id) || !existsSync(pathOf(id))) return undefined;\n return { data: new Uint8Array(readFileSync(pathOf(id))), name: `recording-${id}.json`, type: 'application/json' };\n };\n const partOf = (id: string) => join(dir, `${id}.part`);\n /** The recording going on that a request names, as its last segment: its ID, or the answer that there's none. */\n const going = (req: Request): string | Response => {\n const id = new URL(req.url).pathname.split('/').at(-1) ?? '';\n if (ID.test(id) && existsSync(partOf(id))) return id;\n return Response.json({ problem: `no recording ${id} is going any more: record again` }, { status: 404 });\n };\n const json = async <T>(req: Request): Promise<T | undefined> => {\n try {\n return (await req.json()) as T;\n } catch {\n return undefined;\n }\n };\n /** A recording begun: its ID, and the file its parts are added to, which starts with what `Kept` says besides the events. */\n const begin = (meta: Meta) => {\n // Sorts by when it was made, which is what pruning keeps by: the count orders two in one millisecond.\n const id = `${Date.now().toString(36).padStart(9, '0')}${(taken++ % 1296).toString(36).padStart(2, '0')}-${crypto.randomUUID().slice(0, 8)}`;\n mkdirSync(dir, { recursive: true });\n // One nobody ended, as its tab was closed: gone a day on.\n for (const f of readdirSync(dir)) if (f.endsWith('.part') && Date.now() - statSync(join(dir, f)).mtimeMs > STALE) rmSync(join(dir, f));\n\n writeFileSync(partOf(id), `${JSON.stringify(meta)}\\n`);\n return id;\n };\n /** The parts as one recording, in their order whatever order they came in: a page's last may overtake the one before. */\n const end = (id: string, last: Pick<Kept, 'duration' | 'voice'>): boolean => {\n const [meta, ...lines] = readFileSync(partOf(id), 'utf8').trimEnd().split('\\n');\n const parts = lines.map((line) => JSON.parse(line) as { seq: number; events: unknown[] });\n const events = parts.toSorted((a, b) => a.seq - b.seq).flatMap((part) => part.events);\n rmSync(partOf(id));\n if (events.length === 0) return false;\n const kept: Kept = { ...(JSON.parse(meta!) as Meta), ...last, events };\n writeFileSync(pathOf(id), JSON.stringify(kept));\n const all = readdirSync(dir)\n .filter((f) => f.endsWith('.json'))\n .toSorted();\n for (const old of all.slice(0, Math.max(0, all.length - keep))) rmSync(join(dir, old));\n return true;\n };\n const file = (path: string, type: string) => {\n if (!existsSync(path)) return new Response('rrweb-player is missing: add it to your devDependencies', { status: 404 });\n return new Response(readFileSync(path), { headers: { 'content-type': type } });\n };\n\n return definePlugin<never, never, never, Recordings>({\n name: 'recordings',\n client: 'deictic/recordings/client',\n packages: ['rrweb', 'rrweb-player'],\n clientOptions: {\n masking: {\n blockClass: options.blockClass ?? 'rr-block',\n blockSelector: options.blockSelector,\n maskTextClass: options.maskTextClass ?? 'rr-mask',\n maskTextSelector: options.maskTextSelector,\n maskAllInputs: options.maskAllInputs ?? false,\n } satisfies ResolvedMasking,\n canvas: options.canvas === false ? false : { fps: (options.canvas === true ? undefined : options.canvas?.fps) ?? 2 },\n },\n setup: ({ root }) => {\n dir = options.dir === undefined ? keptIn(root, 'recordings') : resolve(root, options.dir);\n return { read };\n },\n routes: {\n // A recording starts: the page, its viewport and when. Its events come in parts, as they happen, so a page\n // load in the middle loses none of them, and the next page carries on under the same ID.\n begin: async (req) => {\n const meta = await json<Partial<Meta>>(req);\n if (meta?.viewport === undefined || typeof meta.page !== 'string' || typeof meta.startedAt !== 'number')\n return Response.json({ problem: 'send the page, its viewport and when it started, as JSON' }, { status: 400 });\n const { page, viewport, colorScheme, startedAt } = meta;\n return Response.json({ id: begin({ page, viewport, ...(colorScheme === undefined ? {} : { colorScheme }), startedAt }) });\n },\n // `part/<id>?seq=<n>`: more of its events, a JSON array, and their place among the parts.\n part: async (req) => {\n const id = going(req);\n if (typeof id !== 'string') return id;\n const seq = Number(new URL(req.url).searchParams.get('seq') ?? 'none');\n const events = await json<unknown>(req);\n if (!Array.isArray(events) || !Number.isInteger(seq))\n return Response.json({ problem: 'send the events as a JSON array, and `seq`, their place' }, { status: 400 });\n const line = `${JSON.stringify({ seq, events })}\\n`;\n if (statSync(partOf(id)).size + line.length > MAX)\n return Response.json({ problem: `a recording may weigh ${MAX / 1024 / 1024} MB at most: stop this one` }, { status: 413 });\n appendFileSync(partOf(id), line);\n return Response.json({ id });\n },\n // `end/<id>`: it's over, and kept: how long it ran, and the mic's clips.\n end: async (req) => {\n const id = going(req);\n if (typeof id !== 'string') return id;\n const last = await json<Partial<Kept>>(req);\n if (typeof last?.duration !== 'number') return Response.json({ problem: 'send how long it ran, as JSON' }, { status: 400 });\n if (!end(id, { duration: last.duration, ...(last.voice === undefined ? {} : { voice: last.voice }) }))\n return Response.json({ problem: 'the recording has no events: record for a moment longer' }, { status: 400 });\n return Response.json({ id });\n },\n // `discard/<id>`: it's over, and not kept.\n discard: (req) => {\n const id = going(req);\n if (typeof id !== 'string') return id;\n rmSync(partOf(id));\n return Response.json({ id });\n },\n // `recording/<id>`: the JSON, for the replay page.\n recording: (req) => {\n const found = read(new URL(req.url).pathname.split('/').at(-1) ?? '');\n if (found === undefined) return new Response('no such recording, or not kept any more', { status: 404 });\n return new Response(found.data, { headers: { 'content-type': found.type, 'cache-control': 'no-store' } });\n },\n // `replay/<id>`: a page that plays it back.\n replay: () => new Response(replayPage(), { headers: { 'content-type': 'text/html; charset=utf-8' } }),\n 'player.js': () => file(player('rrweb-player.umd.min.cjs'), 'text/javascript'),\n 'player.css': () => file(player('style.css'), 'text/css'),\n },\n });\n}\n\nexport default recordings;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,cAAc,EAAE,SAAS,MAAM,WAA0B,CAAC,MAAM;;;;;+BAK9C,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eA8EvB,OAAO,wBACpB,WAAW,KAAA,IACP,KACA;eACS,OAAO,cACrB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mDAmCkD,KAAK,UAAU,KAAK,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAqEvD,KAAK,UAAU,KAAK,EAAE;;;;;;;;;;;;;;;8DAesB,KAAK,UAAU,KAAK,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AClIpF,MAAM,KAAK;;AAEX,MAAM,MAAM;;AAEZ,MAAM,QAAQ;;AAGd,MAAM,UAAU,SAAiB;CAC/B,IAAI;EACF,OAAO,KAAK,QAAQ,cAAc,YAAY,GAAG,CAAC,CAAC,QAAQ,cAAc,CAAC,GAAG,IAAI;CACnF,QAAQ;EAEN,OAAO;CACT;AACF;AAEA,SAAgB,WAAW,UAA6B,CAAC,GAAG;CAC1D,MAAM,OAAO,QAAQ,QAAQ;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AK,OAAO,0BAA0B,GAAG,iBAAiB;GAC7E,oBAAoB,KAAK,OAAO,WAAW,GAAG,UAAU;EAC1D;CACF,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"screenshots.js","names":[],"sources":["../../src/plugins/screenshots/index.ts"],"sourcesContent":["/**\n * `deictic/screenshots`: a plugin with no panel, for others to build on. In the page,\n * `use('screenshots').capture(element)` takes what the viewport shows (or the element alone), with\n * nothing of deictic's in it, and says where the element is; on the server, `use('screenshots').read(id)`\n * hands the PNG to another plugin, which the tasks plugin attaches to a task.\n *\n * How a shot is made is its renderer's: `rrweb()` by default, which snapshots the page's DOM and renders it\n * in a browser beside the dev server, so text lays out as the page's does; or `dom()`, which draws the page\n * in the page itself, for a target with no server to render on. A renderer is a page module and, where it\n * renders elsewhere, a `render` here (`Renderer`): another may take pixels from screen sharing or devtools.\n *\n * Shots are kept under `.deictic/screenshots`, the latest `keep` of them, so they outlive a\n * restart of the dev server and stay out of git.\n */\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nimport { definePlugin } from '#src/index.ts';\nimport { keptIn } from '#src/tools/kept.ts';\n\n/** A rectangle in CSS pixels, from the shot's top left. */\nexport interface Box {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** A shot as the page knows it: its ID, where the dev server serves its PNG, and where the element is in it. */\nexport interface Shot {\n id: string;\n url: string;\n /** The element, in the shot: nothing marks it there, as nothing of deictic's is drawn. */\n box: Box;\n /** The shot's size in CSS pixels; its PNG may have more, on a high-density screen. */\n size: { width: number; height: number };\n}\n\nexport interface CaptureOptions {\n /** `viewport`, what the page shows, by default; or `element`, the element alone. */\n area?: 'viewport' | 'element';\n}\n\n/** The page's half, for other plugins' page halves. */\nexport interface Capture {\n capture(element: Element, options?: CaptureOptions): Promise<Shot>;\n /** Keeps a PNG made of a shot (the same one with marks drawn over it, say) as a shot of its own. */\n upload(png: Blob, of: Pick<Shot, 'box' | 'size'>): Promise<Shot>;\n /** A copy of an element with what a shot hides hidden in it too: for a plugin that sends its HTML somewhere. */\n masked(element: Element): Element;\n}\n\n/** The server's half, for other plugins' server halves. */\nexport interface Screenshots {\n /** A shot's PNG, or nothing for one not kept (any more). */\n read(id: string): { data: Uint8Array<ArrayBuffer>; name: string; type: 'image/png' } | undefined;\n}\n\ndeclare module 'deictic' {\n interface ServerApis {\n screenshots: Screenshots;\n }\n interface ClientApis {\n screenshots: Capture;\n }\n}\n\n/**\n * What a shot hides, as rrweb names it and by its defaults, so one marking in the app hides the same\n * things from a screenshot as from an rrweb recording or snapshot.\n */\nexport interface Masking {\n /** Elements drawn as a blank box their size: `rr-block` by default. */\n blockClass?: string;\n blockSelector?: string;\n /** Elements whose text is drawn as `*`: `rr-mask` by default. */\n maskTextClass?: string;\n maskTextSelector?: string;\n /** Every field's value as `*`, not only passwords': false by default. */\n maskAllInputs?: boolean;\n}\n\n/** Masking with its defaults, as a renderer's page half gets it. */\nexport type ResolvedMasking = Required<Pick<Masking, 'blockClass' | 'maskTextClass' | 'maskAllInputs'>> & Masking;\n\n/**\n * How shots are made. `client` is the page module that captures, default-exporting `screenshotsClient(…)`\n * from `deictic/screenshots/client`. A page half that sends a PNG needs nothing here; one that sends\n * something else, as JSON (a DOM snapshot), needs `render` to make the PNG of it.\n */\nexport interface Renderer {\n client: string;\n /** What the page half gets, besides the masking. */\n clientOptions?: unknown;\n /** The packages it imports that the project installs, as a plugin's `packages`. */\n packages?: string[];\n /** The PNG, or with it the element's `box` in it, where it's not where the page said (the page was drawn again elsewhere). */\n render?(input: unknown): Promise<Uint8Array | { png: Uint8Array; box?: Box }>;\n}\n\n/** Where `rrweb()` finds a browser: any Chromium renders the snapshot as the page's own would. */\nexport interface BrowserOptions {\n /** A Chromium-based browser's executable. */\n executablePath?: string;\n /** An installed browser by Playwright's name: `chrome`, `msedge`. By default Playwright's own Chromium, then Chrome, then Edge. */\n channel?: string;\n}\n\n/** Draws the page in the page, from its DOM (`modern-screenshot`): no server needed, but text may lay out a little differently. */\nexport const dom = (): Renderer => ({ client: 'deictic/screenshots/dom', packages: ['modern-screenshot'] });\n\n/**\n * Snapshots the page's DOM in the page (`rrweb-snapshot`, masking as rrweb does) and renders it in a\n * browser beside the dev server (`playwright-core`), so text lays out as the page's does.\n */\nexport const rrweb = (options: BrowserOptions = {}): Renderer => ({\n client: 'deictic/screenshots/rrweb',\n packages: ['rrweb-snapshot', 'playwright-core'],\n // Loaded on the first shot, so a project rendering in the page needn't install Playwright.\n render: async (input) => (await import('./playwright.ts')).render(input, options),\n});\n\nexport interface ScreenshotsOptions extends Masking {\n /** How shots are made: `rrweb()` by default, or `dom()` where there's no server to render on. */\n renderer?: Renderer;\n /** How many shots to keep, the latest: 100 by default. */\n keep?: number;\n /** Where they're kept, from the project's root: `.deictic/screenshots` by default. */\n dir?: string;\n}\n\nconst ID = /^[a-z0-9]+-[a-z0-9]+$/;\n/** What one PNG, or one snapshot to render, may weigh: a viewport at twice its pixels is a few MB. */\nconst MAX = 20 * 1024 * 1024;\n\nexport function screenshots(options: ScreenshotsOptions = {}) {\n const renderer = options.renderer ?? rrweb();\n const keep = options.keep ?? 100;\n let dir = '';\n let taken = 0;\n const pathOf = (id: string) => join(dir, `${id}.png`);\n const read: Screenshots['read'] = (id) => {\n if (!ID.test(id) || !existsSync(pathOf(id))) return undefined;\n return { data: new Uint8Array(readFileSync(pathOf(id))), name: `${id}.png`, type: 'image/png' };\n };\n const keepShot = (data: Uint8Array) => {\n // Sorts by when it was taken, which is what pruning keeps by: the count orders two in one millisecond.\n const id = `${Date.now().toString(36).padStart(9, '0')}${(taken++ % 1296).toString(36).padStart(2, '0')}-${crypto.randomUUID().slice(0, 8)}`;\n mkdirSync(dir, { recursive: true });\n writeFileSync(pathOf(id), data);\n const kept = readdirSync(dir)\n .filter((f) => f.endsWith('.png'))\n .toSorted();\n for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));\n return id;\n };\n\n return definePlugin<never, never, never, Screenshots>({\n name: 'screenshots',\n client: renderer.client,\n packages: renderer.packages,\n clientOptions: {\n masking: {\n blockClass: options.blockClass ?? 'rr-block',\n blockSelector: options.blockSelector,\n maskTextClass: options.maskTextClass ?? 'rr-mask',\n maskTextSelector: options.maskTextSelector,\n maskAllInputs: options.maskAllInputs ?? false,\n } satisfies ResolvedMasking,\n renderer: renderer.clientOptions,\n },\n setup: ({ root }) => {\n dir = options.dir === undefined ? keptIn(root, 'screenshots') : resolve(root, options.dir);\n return { read };\n },\n routes: {\n // A PNG the page made, or what the renderer makes one of.\n add: async (req) => {\n const type = req.headers.get('content-type') ?? '';\n const body = new Uint8Array(await req.arrayBuffer());\n if (body.byteLength > MAX) return Response.json({ problem: `a shot may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });\n if (type === 'image/png') return Response.json({ id: keepShot(body) });\n if (renderer.render === undefined || !type.startsWith('application/json'))\n return Response.json({ problem: 'send the shot as image/png' }, { status: 415 });\n try {\n const made = await renderer.render(JSON.parse(new TextDecoder().decode(body)));\n if (made instanceof Uint8Array) return Response.json({ id: keepShot(made) });\n return Response.json({ id: keepShot(made.png), ...(made.box === undefined ? {} : { box: made.box }) });\n } catch (e) {\n return Response.json({ problem: e instanceof Error ? e.message : String(e) }, { status: 500 });\n }\n },\n // `shot/<id>`: the PNG, for a panel to show.\n shot: (req) => {\n const shot = read(new URL(req.url).pathname.split('/').at(-1) ?? '');\n if (shot === undefined) return new Response('no such shot, or not kept any more', { status: 404 });\n return new Response(shot.data, { headers: { 'content-type': shot.type, 'cache-control': 'no-store' } });\n },\n },\n });\n}\n\nexport default screenshots;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA6GA,MAAa,aAAuB;CAAE,QAAQ;CAA2B,UAAU,CAAC,mBAAmB;AAAE;;;;;AAMzG,MAAa,SAAS,UAA0B,CAAC,OAAiB;CAChE,QAAQ;CACR,UAAU,CAAC,kBAAkB,iBAAiB;CAE9C,QAAQ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AAI,IAAI,IAAI,GAAG,CAAC,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE;IACnE,IAAI,SAAS,KAAA,GAAW,OAAO,IAAI,SAAS,sCAAsC,EAAE,QAAQ,IAAI,CAAC;IACjG,OAAO,IAAI,SAAS,KAAK,MAAM,EAAE,SAAS;KAAE,gBAAgB,KAAK;KAAM,iBAAiB;IAAW,EAAE,CAAC;GACxG;EACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"screenshots.js","names":[],"sources":["../../src/plugins/screenshots/index.ts"],"sourcesContent":["/**\n * `deictic/screenshots`: a plugin with no panel, for others to build on. In the page,\n * `use('screenshots').capture(element)` takes what the viewport shows (or the element alone), with\n * nothing of deictic's in it, and says where the element is; on the server, `use('screenshots').read(id)`\n * hands the PNG to another plugin, which the tasks plugin attaches to a task.\n *\n * How a shot is made is its renderer's: `rrweb()` by default, which snapshots the page's DOM and renders it\n * in a browser beside the dev server, so text lays out as the page's does; or `dom()`, which draws the page\n * in the page itself, for a target with no server to render on. A renderer is a page module and, where it\n * renders elsewhere, a `render` here (`Renderer`): another may take pixels from screen sharing or devtools.\n *\n * Shots are kept under `.deictic/screenshots`, the latest `keep` of them, so they outlive a\n * restart of the dev server and stay out of git.\n */\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nimport { definePlugin } from '#src/index.ts';\nimport { keptIn } from '#src/tools/kept.ts';\n\n/** A rectangle in CSS pixels, from the shot's top left. */\nexport interface Box {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** A shot as the page knows it: its ID, where the dev server serves its PNG, and where the element is in it. */\nexport interface Shot {\n id: string;\n url: string;\n /** The element, in the shot: nothing marks it there, as nothing of deictic's is drawn. */\n box: Box;\n /** The shot's size in CSS pixels; its PNG may have more, on a high-density screen. */\n size: { width: number; height: number };\n}\n\nexport interface CaptureOptions {\n /** `viewport`, what the page shows, by default; or `element`, the element alone. */\n area?: 'viewport' | 'element';\n}\n\n/** The page's half, for other plugins' page halves. */\nexport interface Capture {\n capture(element: Element, options?: CaptureOptions): Promise<Shot>;\n /** Keeps a PNG made of a shot (the same one with marks drawn over it, say) as a shot of its own. */\n upload(png: Blob, of: Pick<Shot, 'box' | 'size'>): Promise<Shot>;\n /** A copy of an element with what a shot hides hidden in it too: for a plugin that sends its HTML somewhere. */\n masked(element: Element): Element;\n /**\n * Keeps what a shot of the page now needs, to render later: the overlay calls it (through the plugin's\n * `pressed`) as a shortcut's press goes down, so a tooltip, a hover's styles or a focused menu are still there.\n * Only a renderer that can take the page at once does (`rrweb()`, once it has loaded); the last press's is kept.\n */\n freeze(element: Element): void;\n /**\n * The shot of the page as the last press on `element` froze it, rendered on the first ask, or nothing where the\n * last press was on another element or nothing was frozen: then `capture` takes the page as it is now.\n */\n frozen(element: Element): Promise<Shot> | undefined;\n}\n\n/** The server's half, for other plugins' server halves. */\nexport interface Screenshots {\n /** A shot's PNG, or nothing for one not kept (any more). */\n read(id: string): { data: Uint8Array<ArrayBuffer>; name: string; type: 'image/png' } | undefined;\n}\n\ndeclare module 'deictic' {\n interface ServerApis {\n screenshots: Screenshots;\n }\n interface ClientApis {\n screenshots: Capture;\n }\n}\n\n/**\n * What a shot hides, as rrweb names it and by its defaults, so one marking in the app hides the same\n * things from a screenshot as from an rrweb recording or snapshot.\n */\nexport interface Masking {\n /** Elements drawn as a blank box their size: `rr-block` by default. */\n blockClass?: string;\n blockSelector?: string;\n /** Elements whose text is drawn as `*`: `rr-mask` by default. */\n maskTextClass?: string;\n maskTextSelector?: string;\n /** Every field's value as `*`, not only passwords': false by default. */\n maskAllInputs?: boolean;\n}\n\n/** Masking with its defaults, as a renderer's page half gets it. */\nexport type ResolvedMasking = Required<Pick<Masking, 'blockClass' | 'maskTextClass' | 'maskAllInputs'>> & Masking;\n\n/**\n * How shots are made. `client` is the page module that captures, default-exporting `screenshotsClient(…)`\n * from `deictic/screenshots/client`. A page half that sends a PNG needs nothing here; one that sends\n * something else, as JSON (a DOM snapshot), needs `render` to make the PNG of it.\n */\nexport interface Renderer {\n client: string;\n /** What the page half gets, besides the masking. */\n clientOptions?: unknown;\n /** The packages it imports that the project installs, as a plugin's `packages`. */\n packages?: string[];\n /** The PNG, or with it the element's `box` in it, where it's not where the page said (the page was drawn again elsewhere). */\n render?(input: unknown): Promise<Uint8Array | { png: Uint8Array; box?: Box }>;\n}\n\n/** Where `rrweb()` finds a browser: any Chromium renders the snapshot as the page's own would. */\nexport interface BrowserOptions {\n /** A Chromium-based browser's executable. */\n executablePath?: string;\n /** An installed browser by Playwright's name: `chrome`, `msedge`. By default Playwright's own Chromium, then Chrome, then Edge. */\n channel?: string;\n}\n\n/** Draws the page in the page, from its DOM (`modern-screenshot`): no server needed, but text may lay out a little differently. */\nexport const dom = (): Renderer => ({ client: 'deictic/screenshots/dom', packages: ['modern-screenshot'] });\n\n/**\n * Snapshots the page's DOM in the page (`rrweb-snapshot`, masking as rrweb does) and renders it in a\n * browser beside the dev server (`playwright-core`), so text lays out as the page's does.\n */\nexport const rrweb = (options: BrowserOptions = {}): Renderer => ({\n client: 'deictic/screenshots/rrweb',\n packages: ['rrweb-snapshot', 'playwright-core'],\n // Loaded on the first shot, so a project rendering in the page needn't install Playwright.\n render: async (input) => (await import('./playwright.ts')).render(input, options),\n});\n\nexport interface ScreenshotsOptions extends Masking {\n /** How shots are made: `rrweb()` by default, or `dom()` where there's no server to render on. */\n renderer?: Renderer;\n /** How many shots to keep, the latest: 100 by default. */\n keep?: number;\n /** Where they're kept, from the project's root: `.deictic/screenshots` by default. */\n dir?: string;\n}\n\nconst ID = /^[a-z0-9]+-[a-z0-9]+$/;\n/** What one PNG, or one snapshot to render, may weigh: a viewport at twice its pixels is a few MB. */\nconst MAX = 20 * 1024 * 1024;\n\nexport function screenshots(options: ScreenshotsOptions = {}) {\n const renderer = options.renderer ?? rrweb();\n const keep = options.keep ?? 100;\n let dir = '';\n let taken = 0;\n const pathOf = (id: string) => join(dir, `${id}.png`);\n const read: Screenshots['read'] = (id) => {\n if (!ID.test(id) || !existsSync(pathOf(id))) return undefined;\n return { data: new Uint8Array(readFileSync(pathOf(id))), name: `${id}.png`, type: 'image/png' };\n };\n const keepShot = (data: Uint8Array) => {\n // Sorts by when it was taken, which is what pruning keeps by: the count orders two in one millisecond.\n const id = `${Date.now().toString(36).padStart(9, '0')}${(taken++ % 1296).toString(36).padStart(2, '0')}-${crypto.randomUUID().slice(0, 8)}`;\n mkdirSync(dir, { recursive: true });\n writeFileSync(pathOf(id), data);\n const kept = readdirSync(dir)\n .filter((f) => f.endsWith('.png'))\n .toSorted();\n for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));\n return id;\n };\n\n return definePlugin<never, never, never, Screenshots>({\n name: 'screenshots',\n client: renderer.client,\n packages: renderer.packages,\n clientOptions: {\n masking: {\n blockClass: options.blockClass ?? 'rr-block',\n blockSelector: options.blockSelector,\n maskTextClass: options.maskTextClass ?? 'rr-mask',\n maskTextSelector: options.maskTextSelector,\n maskAllInputs: options.maskAllInputs ?? false,\n } satisfies ResolvedMasking,\n renderer: renderer.clientOptions,\n },\n setup: ({ root }) => {\n dir = options.dir === undefined ? keptIn(root, 'screenshots') : resolve(root, options.dir);\n return { read };\n },\n routes: {\n // A PNG the page made, or what the renderer makes one of.\n add: async (req) => {\n const type = req.headers.get('content-type') ?? '';\n const body = new Uint8Array(await req.arrayBuffer());\n if (body.byteLength > MAX) return Response.json({ problem: `a shot may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });\n if (type === 'image/png') return Response.json({ id: keepShot(body) });\n if (renderer.render === undefined || !type.startsWith('application/json'))\n return Response.json({ problem: 'send the shot as image/png' }, { status: 415 });\n try {\n const made = await renderer.render(JSON.parse(new TextDecoder().decode(body)));\n if (made instanceof Uint8Array) return Response.json({ id: keepShot(made) });\n return Response.json({ id: keepShot(made.png), ...(made.box === undefined ? {} : { box: made.box }) });\n } catch (e) {\n return Response.json({ problem: e instanceof Error ? e.message : String(e) }, { status: 500 });\n }\n },\n // `shot/<id>`: the PNG, for a panel to show.\n shot: (req) => {\n const shot = read(new URL(req.url).pathname.split('/').at(-1) ?? '');\n if (shot === undefined) return new Response('no such shot, or not kept any more', { status: 404 });\n return new Response(shot.data, { headers: { 'content-type': shot.type, 'cache-control': 'no-store' } });\n },\n },\n });\n}\n\nexport default screenshots;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwHA,MAAa,aAAuB;CAAE,QAAQ;CAA2B,UAAU,CAAC,mBAAmB;AAAE;;;;;AAMzG,MAAa,SAAS,UAA0B,CAAC,OAAiB;CAChE,QAAQ;CACR,UAAU,CAAC,kBAAkB,iBAAiB;CAE9C,QAAQ,OAAO,WAAW,MAAM,OAAO,mBAAA,CAAoB,OAAO,OAAO,OAAO;AAClF;AAWA,MAAM,KAAK;;AAEX,MAAM,MAAM;AAEZ,SAAgB,YAAY,UAA8B,CAAC,GAAG;CAC5D,MAAM,WAAW,QAAQ,YAAY,MAAM;CAC3C,MAAM,OAAO,QAAQ,QAAQ;CAC7B,IAAI,MAAM;CACV,IAAI,QAAQ;CACZ,MAAM,UAAU,OAAe,KAAK,KAAK,GAAG,GAAG,KAAK;CACpD,MAAM,QAA6B,OAAO;EACxC,IAAI,CAAC,GAAG,KAAK,EAAE,KAAK,CAAC,WAAW,OAAO,EAAE,CAAC,GAAG,OAAO,KAAA;EACpD,OAAO;GAAE,MAAM,IAAI,WAAW,aAAa,OAAO,EAAE,CAAC,CAAC;GAAG,MAAM,GAAG,GAAG;GAAO,MAAM;EAAY;CAChG;CACA,MAAM,YAAY,SAAqB;EAErC,MAAM,KAAK,GAAG,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,KAAK,UAAU,KAAA,CAAM,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,EAAE,GAAG,OAAO,WAAW,CAAC,CAAC,MAAM,G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,OAAO,KAAK,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC;KAC7E,IAAI,gBAAgB,YAAY,OAAO,SAAS,KAAK,EAAE,IAAI,SAAS,IAAI,EAAE,CAAC;KAC3E,OAAO,SAAS,KAAK;MAAE,IAAI,SAAS,KAAK,GAAG;MAAG,GAAI,KAAK,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,KAAK,KAAK,IAAI;KAAG,CAAC;IACvG,SAAS,GAAG;KACV,OAAO,SAAS,KAAK,EAAE,SAAS,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;IAC/F;GACF;GAEA,OAAO,QAAQ;IACb,MAAM,OAAO,KAAK,IAAI,IAAI,IAAI,GAAG,CAAC,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE;IACnE,IAAI,SAAS,KAAA,GAAW,OAAO,IAAI,SAAS,sCAAsC,EAAE,QAAQ,IAAI,CAAC;IACjG,OAAO,IAAI,SAAS,KAAK,MAAM,EAAE,SAAS;KAAE,gBAAgB,KAAK;KAAM,iBAAiB;IAAW,EAAE,CAAC;GACxG;EACF;CACF,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"src.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/**\n * `deictic`: what a plugin is. Every plugin is optional: deictic itself is the glue (the\n * transform that ties elements to source, the dev server's endpoints, the history, shortcuts and the\n * overlay's panel), and each plugin adds what it does on top.\n *\n * A plugin has two halves, each optional that meet over the dev server's endpoints (`tools/endpoints.ts`). The\n * server half runs beside the bundler and is the only one that reads source: it turns the element\n * under the pointer into a model its panel can show, and an op from that panel into text edits. It\n * never writes files; deictic does, so every plugin's changes land in one history and undo the\n * same way. A change that isn't to a file (a task added to a board) the plugin makes itself and\n * answers with what it did (`Done`): the history keeps that beside the files' changes and hands it\n * back to the plugin's own `undo` and `redo`.\n * The client half is a module the page loads, named by the server half's `client`, which draws the\n * panel and previews an op on the page before it is applied.\n *\n * A plugin may have no panel at all, only an API for others (screenshots, a recording) and routes of\n * its own on the dev server. Each half's `setup` answers its API, and `use(name)` reaches another\n * plugin's, on the same side; `needs` names the plugins it can't do without.\n *\n * Both halves import from here, so the parser is imported for its types only: the browser must not load it.\n */\nimport type { JSXOpeningElement, Program } from 'oxc-parser';\n\nimport type { Shortcut } from './shortcut.ts';\n\nexport type { Modifier, Shortcut } from './shortcut.ts';\n\n/** A place in the source: the file from the project's root, with `/`, and the line and column, from 1. */\nexport interface Loc {\n file: string;\n line: number;\n column: number;\n}\n\n/** An element the pointer picked: where its opening tag starts, and the tag, which the server checks is still there. */\nexport interface Target {\n loc: Loc;\n tag: string;\n}\n\n/** Text in a file to replace, by UTF-16 offsets. `file` is the target's unless named, from the project's root. */\nexport interface TextEdit {\n file?: string;\n start: number;\n end: number;\n text: string;\n}\n\n/** What a server half reads: the target's file, parsed, and its element. */\nexport interface Source {\n /** The target's file, from the project's root. */\n file: string;\n code: string;\n /** The file's module; for an `.astro` component, its frontmatter's. */\n program: Program;\n /** The target's opening tag. */\n element: JSXOpeningElement;\n /** Another file under the project's root, for plugins whose edits go elsewhere (a locale's messages). */\n read(file: string): string;\n}\n\n/**\n * What answers the overlay's requests in a page with no dev server behind it (`deictic/vite`'s `standalone`): the\n * default export of a module of the page's. A request is one the endpoints would get, under `<base>__deictic/`;\n * the answer is theirs too (`{ model }`, `{ model, change }`, `{ problem }` with a status that isn't ok).\n */\nexport type Standalone = (request: Request) => Response | Promise<Response>;\n\n/** An op a plugin won't make. The message says why and what to do instead; the panel shows it. */\nexport class Refusal extends Error {\n override name = 'Refusal';\n}\n\n/**\n * A change the plugin made itself, not to a file: what its `undo` and `redo` need to take it back and\n * make it again. JSON, since the history keeps it on disk across restarts of the dev server.\n */\nexport interface Done<Record = unknown> {\n done: Record;\n}\n\ntype Maybe<T> = T | Promise<T>;\n\n/**\n * Something of deictic's that went wrong, which nothing a person did in the page caused: a package the project\n * hasn't installed, a plugin that failed. The dev server says it, and hands it to each plugin with a `problem`\n * (tasks posts it to the board, for an agent to fix).\n */\nexport interface Problem {\n /**\n * What tells it apart, and the same problem again from a new one: `packages:rrweb`, `setup:tailwind`. Never a\n * time or an ID, so a problem that comes back is known.\n */\n key: string;\n /**\n * `setup`: the project's to fix, as `message` says (install a package, configure a plugin). `bug`: deictic's own, or\n * a plugin's, to report where it's made, not to patch where it's installed.\n */\n kind: 'setup' | 'bug';\n /** What went wrong, and the fix where there is one, as any problem message says it. */\n message: string;\n /** What more there is to look into: a stack. */\n details?: string;\n /** The plugin it's about, where it's one's: none for deictic's own. */\n plugin?: string;\n}\n\n/**\n * Each plugin's API to the others on the server, by name. A plugin adds its own, so `use` knows its type:\n * `declare module 'deictic' { interface ServerApis { screenshots: Screenshots } }`.\n */\n// oxlint-disable-next-line typescript/no-empty-interface -- filled by declaration merging\nexport interface ServerApis {}\n\n/** The same, in the page: `declare module 'deictic' { interface ClientApis { screenshots: Capture } }`. */\n// oxlint-disable-next-line typescript/no-empty-interface -- filled by declaration merging\nexport interface ClientApis {}\n\n/** A plugin's API, by its name: what its package declared, or `unknown` for one that declared none. */\nexport type ApiOf<Apis, Name extends string> = Name extends keyof Apis ? Apis[Name] : unknown;\n\nexport interface ServerContext {\n /** The project's root, as an absolute path. */\n root: string;\n /**\n * Another plugin's API, as its `setup` answered it, or nothing when it isn't loaded (or its `setup` failed,\n * which is reported). One the plugin `needs` always is loaded; any other may not be, so check.\n */\n use: <Name extends string>(name: Name) => ApiOf<ServerApis, Name> | undefined;\n /** Says a problem of the plugin's own, as deictic says its own: in the dev server's output, and to each plugin's `problem`. */\n report: (problem: Problem) => void;\n}\n\n/**\n * A route of the plugin's own, at `/__deictic/plugins/<name>/<route>`, and below it. A `GET` must\n * change nothing: anything else reaches it only from the page itself, which deictic checks.\n */\nexport type Route = (request: Request, context: ServerContext) => Maybe<Response>;\n\nexport interface ServerPlugin<Model = unknown, Op = unknown, Record = unknown, Api = unknown> {\n /** Ties the halves together; also the label of its changes in the history, and its routes' path. Lowercase, with `-`. */\n name: string;\n /** The module the page loads for this plugin's half there, which default-exports its `ClientPlugin`. */\n client?: string;\n /** What the page half gets as `context.options`: the user's options it needs there, as JSON. */\n clientOptions?: unknown;\n /** What opens its panel: its own default, which its options let the user change. A plugin with no panel has none. */\n shortcut?: Shortcut;\n /** The plugins it can't do without, by name: the dev server won't start without them. */\n needs?: string[];\n /**\n * The packages it imports that the project installs itself (optional peers), by name: as the dev server starts,\n * it says how to install any that's missing, rather than failing when first used.\n */\n packages?: string[];\n /** Runs once, as the dev server starts and before it answers anything. Answers the plugin's API to the others. */\n setup?(context: ServerContext): Maybe<Api>;\n /** Routes of its own, by their first segment under `/__deictic/plugins/<name>/`. */\n routes?: { [route: string]: Route };\n /**\n * The model its panel shows for an element. Without it, the panel gets none. `source` is a `Refusal` where the\n * element isn't to be found in its file (it doesn't parse, or the page runs other code than it has): throw it where\n * the plugin needs the source, or go on without it, as a task does.\n */\n read?(source: Source | Refusal, target: Target): Maybe<Model>;\n /** Text edits for deictic to write, which it refuses without the source, or a change the plugin made itself. */\n apply?(source: Source | Refusal, target: Target, op: Op): Maybe<TextEdit[] | Done<Record>>;\n /**\n * Takes back a change `apply` made itself, or throws a `Refusal` saying why it can't any more. It may\n * answer what the next redo needs, where that differs (what it put back has a new ID).\n */\n undo?(record: Record): Maybe<void | Record>;\n /** Makes it again after an undo, and answers what the next undo needs, which may differ (a new ID). */\n redo?(record: Record): Maybe<Record>;\n /** Says what an op does, for the history: `className: px-2 → px-4`. */\n describe?(op: Op, before: Model): string;\n /**\n * Hears each problem deictic or a plugin reports, on the server or in the page, after every `setup` has run: once\n * per `key` while the dev server runs. Its own failure is only said, never reported again.\n */\n problem?(problem: Problem): Maybe<void>;\n}\n\nexport const definePlugin = <Model, Op, Record = unknown, Api = unknown>(\n plugin: ServerPlugin<Model, Op, Record, Api>,\n): ServerPlugin<Model, Op, Record, Api> => plugin;\n\n/** Where something is in an element, in CSS pixels from its top left. */\nexport interface Point {\n x: number;\n y: number;\n}\n\n/** A spot on the page: a marked element, and a point in it (or beside it, for the nearest to a point no marked element is under). */\nexport interface Spot {\n element: Element;\n at: Point;\n}\n\n/**\n * The tool panel: a bar docked to an edge of the window, which shows while a shortcut's keys are held and stays\n * while it's in use. A plugin adds its tools to it from its page half's `setup`.\n */\nexport interface ToolPanel {\n /**\n * Adds a plugin's controls, as one group, in the order plugins are loaded. Groups of one `section` sit together,\n * with no line between them, after the groups of none: the screenshots', recordings', voice's and tasks' are\n * `capture`. `last` puts a group at the end of its section, or after all the others for one of none. Each control is a button named by its `title`; its `aria-keyshortcuts`\n * (`B`, `Control+Z`) is the key the panel hears for it, alone or with the keys held to point, and what its tooltip\n * shows.\n */\n add: (group: HTMLElement, options?: { last?: boolean; section?: string }) => void;\n /**\n * Takes the page for a tool that works on it (drawing, picking a point): the tool that had it lets go first, and\n * the panel stays shown. `left` is called when another takes it, or Esc or the pointer tool gives the page back.\n * Answers what lets go of it, for the tool to call when it's done on its own.\n */\n hold: (left: () => void) => () => void;\n /** Keeps the panel shown while something goes on that its controls end (a recording). Answers what ends that. */\n keep: () => () => void;\n /**\n * Takes the page until a point of it is pressed, lighting what's under the pointer as pointing does: answers the\n * spot, the marked element there or the nearest to it, or nothing where the page was given back first.\n */\n pick: () => Promise<Spot | undefined>;\n}\n\n/**\n * The drawer: on the window's side, where what the plugins have for the page lands, a section each. It\n * shows while a shortcut's keys are held and a section has something, and stays while it's in use.\n */\nexport interface Drawer {\n /**\n * Adds a section, in the order added, or before the others with `first`. A section that has nothing to show sets\n * its own `hidden`: the drawer stays away while every one is. Folded away, the drawer counts what the sections\n * have: each says how many things it lists in `data-count`, and how many are unread in `data-unread`.\n */\n add: (section: HTMLElement, options?: { first?: boolean }) => void;\n /**\n * Opens one item in the drawer, in the sections' place, under `title` and a way back. The drawer stays while it's\n * open. `closed` is called when it's left, by the way back, Esc, or another item opening. Answers what closes it.\n */\n show: (view: HTMLElement, options?: { title?: string; closed?: () => void }) => () => void;\n /** Keeps the drawer up while something goes on in it; answers what lets it go. */\n keep: () => () => void;\n}\n\n/** Something a plugin made on the page that nothing has taken yet: a shot, a recording, a voice clip. */\nexport interface TrayItem {\n /** The plugin that made it. */\n plugin: string;\n /** Its ID, as that plugin has it. */\n id: string;\n /** What that plugin says of it, as JSON: the screenshots plugin's `Shot`, a `Recording`, a `Clip`. */\n value: unknown;\n}\n\n/**\n * What plugins made on the page from the tool panel, until something takes it: a task attaches what's there and\n * removes it. Kept for the tab's session, so it's there on the tab's next page too.\n */\nexport interface Tray {\n /** What's kept, oldest first: all of it, or one plugin's. */\n list: (plugin?: string) => TrayItem[];\n add: (plugin: string, id: string, value: unknown) => void;\n /** Takes one out, or all of a plugin's. */\n remove: (plugin: string, id?: string) => void;\n /** Hears every change from now on; answers what stops it. */\n subscribe: (listener: () => void) => () => void;\n}\n\nexport interface ClientContext {\n /** The dev server's base URL, ending in `/`. */\n base: string;\n /** deictic's shadow root, to draw in: neither the page's styles nor the overlay's cross over. */\n root: ShadowRoot;\n /** The server half's `clientOptions`, or nothing. */\n options: unknown;\n /** Another plugin's API in the page, as its `setup` answered it, or nothing when it isn't loaded. */\n use: <Name extends string>(name: Name) => ApiOf<ClientApis, Name> | undefined;\n /** Asks one of this plugin's own routes, from the page: `request('shots', { method: 'POST', body: blob })`. */\n request: (route: string, init?: RequestInit) => Promise<Response>;\n /** Says a problem of the plugin's own to the dev server, as the server half's `report` does: its `plugin` is this one. */\n report: (problem: Problem) => void;\n /**\n * Opens the popup on an element at a plugin's tab, as its shortcut would, or with `at` on a spot in it: the\n * popup is then beside the spot, which is what's lit, and the tab's context has it. An element rendered again\n * since stands in for one no longer on the page. False when there's no such tab or no such element any more, and\n * while the open popup holds something unsaved, whose button then shakes. Not as `setup` runs, which is before the\n * popup can open.\n */\n open: (plugin: string, element: Element, at?: Point) => boolean;\n /** The tool panel, to add this plugin's tools to. */\n tools: ToolPanel;\n /** What was made from the tool panel and not taken yet. */\n tray: Tray;\n /** The drawer, to add this plugin's section to. */\n drawer: Drawer;\n /**\n * Lights an element on the page as pointing at it does, for something of the overlay's own that stands for it (a\n * task's row in the drawer, while the pointer is on it); none puts the light back as it was.\n */\n light: (element?: Element) => void;\n /**\n * Shows `items` in the lightbox over everything, at `at` (the first by default), stepping between them with\n * ← and →. With `from`, it grows out of that element (the chip clicked) and shrinks back into it on close.\n */\n lightbox: (items: LightboxItem[], options?: LightboxOptions) => { close: () => void };\n}\n\n/** What the lightbox shows: a picture, a page in a frame (a recording's replay), or a sound with its waveform. */\nexport type LightboxItem = {\n /** Its name, over it. */\n title: string;\n /** Buttons beside the name: each closes the lightbox and runs. */\n actions?: LightboxAction[];\n} & ({ kind: 'image'; url: string } | { kind: 'page'; url: string } | { kind: 'audio'; url: string });\n\nexport interface LightboxAction {\n label: string;\n title?: string;\n run: () => void;\n}\n\nexport interface LightboxOptions {\n /** The item it opens at. */\n at?: number;\n /** The element it grows out of, and goes back into. */\n from?: Element;\n}\n\nexport interface PanelContext<Model, Op> extends ClientContext {\n /**\n * The element clicked: the one the source marked, under the pointer or around what is. Back from `away`\n * it may be off the page (`isConnected` is false), where the page moved on without it: the element as it\n * was left, or after a page load an empty one of its tag and mark. `elements` is then empty.\n */\n element: Element;\n /**\n * What was under the pointer, where it isn't `element` but inside it: markup nothing marked, as a\n * dependency's, or in an open shadow root, as the popup's own on a page that shows it (`popupIn`).\n */\n pointed?: Element;\n /** The spot in `element` the popup was opened on, where it was (the tool panel's task tool), not the element as a whole. */\n at?: Point;\n /** Every element on the page from the same place in the source, the clicked one among them: the rows of a list. */\n elements: Element[];\n target: Target;\n model: Model;\n /**\n * Applies an op on disk, and reads the model again. Rejects with the server's reason, which the panel also shows.\n * On another element with `on`, whose model is then the one answered: for an op that's about that one.\n */\n apply(op: Op, on?: Target): Promise<Model>;\n close: () => void;\n /**\n * Says there's something here that leaving would lose (words typed, a change tried on the page), and the button\n * that keeps it: a click outside the popup then shakes that button, where it would have closed the popup.\n * `undefined` once there's nothing to lose. Forgotten as the panel unmounts.\n */\n unsaved: (action: HTMLElement | undefined) => void;\n /**\n * Leaves the popup to do something on the page, then comes back: closes it, runs `task` (a recording, a\n * pick of another element), and opens it again at this tab on this element. The next mount gets\n * `resumed`: the `state` kept now (what was typed, what's attached), and what `task` answered, or why\n * it failed. The state stays in the page, as it is: no need for JSON. It's also kept for the tab's next\n * page, as a structured clone, where it can be one: after a page load, the plugin's `resume` says whether\n * the task carries on, and the popup comes back there.\n */\n away: <T>(state: unknown, task: () => Promise<T>) => void;\n /** Set when this mount is the panel coming back from `away`. */\n resumed?: Resumed;\n}\n\n/** What a panel coming back from `away` gets: the state it kept, and the task's result or problem. */\nexport interface Resumed {\n state: unknown;\n result?: unknown;\n /** Why the task failed: its error's message. */\n problem?: string;\n}\n\nexport interface ClientPlugin<Model = unknown, Op = unknown, Api = unknown> {\n /** The server half's `name`. */\n name: string;\n /** Shown over the element while its shortcut's keys are held, and atop the panel. */\n label?: string;\n /**\n * Runs once, as the page starts, before any panel opens (a recording starts here). Answers the\n * plugin's API to the others in the page, at once: one that needs time keeps its promises inside it.\n */\n setup?(context: ClientContext): Api;\n /**\n * Asked as a page starts where the page before it left this plugin's panel `away`: the task it left for,\n * where that carries on in this page (a recording does), or nothing where it ended with the page. When it's\n * done the popup opens at this tab with `resumed`, on the element where this page has it and without where not.\n */\n resume?(context: ClientContext): Promise<unknown> | undefined;\n /**\n * What it shows on the page while a shortcut's keys are held, and the page is dimmed to point on: the tasks\n * plugin pins each task where its element is. Answers what takes it away.\n */\n pointing?(context: ClientContext): () => void;\n /** Draws into `panel`, inside deictic's shadow root. Returns what to undo on the page when the panel closes. */\n mount?: (panel: HTMLElement, context: PanelContext<Model, Op>) => (() => void) | void;\n}\n\nexport const defineClientPlugin = <Model, Op, Api = unknown>(plugin: ClientPlugin<Model, Op, Api>): ClientPlugin<Model, Op, Api> => plugin;\n"],"mappings":";;AAqEA,IAAa,UAAb,cAA6B,MAAM;CACxB,OAAO;AAClB;AAgHA,MAAa,gBACX,WACyC;AA8N3C,MAAa,sBAAgD,WAAuE"}
1
+ {"version":3,"file":"src.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/**\n * `deictic`: what a plugin is. Every plugin is optional: deictic itself is the glue (the\n * transform that ties elements to source, the dev server's endpoints, the history, shortcuts and the\n * overlay's panel), and each plugin adds what it does on top.\n *\n * A plugin has two halves, each optional that meet over the dev server's endpoints (`tools/endpoints.ts`). The\n * server half runs beside the bundler and is the only one that reads source: it turns the element\n * under the pointer into a model its panel can show, and an op from that panel into text edits. It\n * never writes files; deictic does, so every plugin's changes land in one history and undo the\n * same way. A change that isn't to a file (a task added to a board) the plugin makes itself and\n * answers with what it did (`Done`): the history keeps that beside the files' changes and hands it\n * back to the plugin's own `undo` and `redo`.\n * The client half is a module the page loads, named by the server half's `client`, which draws the\n * panel and previews an op on the page before it is applied.\n *\n * A plugin may have no panel at all, only an API for others (screenshots, a recording) and routes of\n * its own on the dev server. Each half's `setup` answers its API, and `use(name)` reaches another\n * plugin's, on the same side; `needs` names the plugins it can't do without.\n *\n * Both halves import from here, so the parser is imported for its types only: the browser must not load it.\n */\nimport type { JSXOpeningElement, Program } from 'oxc-parser';\n\nimport type { Shortcut } from './shortcut.ts';\n\nexport type { Modifier, Shortcut } from './shortcut.ts';\n\n/** A place in the source: the file from the project's root, with `/`, and the line and column, from 1. */\nexport interface Loc {\n file: string;\n line: number;\n column: number;\n}\n\n/** An element the pointer picked: where its opening tag starts, and the tag, which the server checks is still there. */\nexport interface Target {\n loc: Loc;\n tag: string;\n}\n\n/** Text in a file to replace, by UTF-16 offsets. `file` is the target's unless named, from the project's root. */\nexport interface TextEdit {\n file?: string;\n start: number;\n end: number;\n text: string;\n}\n\n/** What a server half reads: the target's file, parsed, and its element. */\nexport interface Source {\n /** The target's file, from the project's root. */\n file: string;\n code: string;\n /** The file's module; for an `.astro` component, its frontmatter's. */\n program: Program;\n /** The target's opening tag. */\n element: JSXOpeningElement;\n /** Another file under the project's root, for plugins whose edits go elsewhere (a locale's messages). */\n read(file: string): string;\n}\n\n/**\n * What answers the overlay's requests in a page with no dev server behind it (`deictic/vite`'s `standalone`): the\n * default export of a module of the page's. A request is one the endpoints would get, under `<base>__deictic/`;\n * the answer is theirs too (`{ model }`, `{ model, change }`, `{ problem }` with a status that isn't ok).\n */\nexport type Standalone = (request: Request) => Response | Promise<Response>;\n\n/** An op a plugin won't make. The message says why and what to do instead; the panel shows it. */\nexport class Refusal extends Error {\n override name = 'Refusal';\n}\n\n/**\n * A change the plugin made itself, not to a file: what its `undo` and `redo` need to take it back and\n * make it again. JSON, since the history keeps it on disk across restarts of the dev server.\n */\nexport interface Done<Record = unknown> {\n done: Record;\n}\n\ntype Maybe<T> = T | Promise<T>;\n\n/**\n * Something of deictic's that went wrong, which nothing a person did in the page caused: a package the project\n * hasn't installed, a plugin that failed. The dev server says it, and hands it to each plugin with a `problem`\n * (tasks posts it to the board, for an agent to fix).\n */\nexport interface Problem {\n /**\n * What tells it apart, and the same problem again from a new one: `packages:rrweb`, `setup:tailwind`. Never a\n * time or an ID, so a problem that comes back is known.\n */\n key: string;\n /**\n * `setup`: the project's to fix, as `message` says (install a package, configure a plugin). `bug`: deictic's own, or\n * a plugin's, to report where it's made, not to patch where it's installed.\n */\n kind: 'setup' | 'bug';\n /** What went wrong, and the fix where there is one, as any problem message says it. */\n message: string;\n /** What more there is to look into: a stack. */\n details?: string;\n /** The plugin it's about, where it's one's: none for deictic's own. */\n plugin?: string;\n}\n\n/**\n * Each plugin's API to the others on the server, by name. A plugin adds its own, so `use` knows its type:\n * `declare module 'deictic' { interface ServerApis { screenshots: Screenshots } }`.\n */\n// oxlint-disable-next-line typescript/no-empty-interface -- filled by declaration merging\nexport interface ServerApis {}\n\n/** The same, in the page: `declare module 'deictic' { interface ClientApis { screenshots: Capture } }`. */\n// oxlint-disable-next-line typescript/no-empty-interface -- filled by declaration merging\nexport interface ClientApis {}\n\n/** A plugin's API, by its name: what its package declared, or `unknown` for one that declared none. */\nexport type ApiOf<Apis, Name extends string> = Name extends keyof Apis ? Apis[Name] : unknown;\n\nexport interface ServerContext {\n /** The project's root, as an absolute path. */\n root: string;\n /**\n * Another plugin's API, as its `setup` answered it, or nothing when it isn't loaded (or its `setup` failed,\n * which is reported). One the plugin `needs` always is loaded; any other may not be, so check.\n */\n use: <Name extends string>(name: Name) => ApiOf<ServerApis, Name> | undefined;\n /** Says a problem of the plugin's own, as deictic says its own: in the dev server's output, and to each plugin's `problem`. */\n report: (problem: Problem) => void;\n}\n\n/**\n * A route of the plugin's own, at `/__deictic/plugins/<name>/<route>`, and below it. A `GET` must\n * change nothing: anything else reaches it only from the page itself, which deictic checks.\n */\nexport type Route = (request: Request, context: ServerContext) => Maybe<Response>;\n\nexport interface ServerPlugin<Model = unknown, Op = unknown, Record = unknown, Api = unknown> {\n /** Ties the halves together; also the label of its changes in the history, and its routes' path. Lowercase, with `-`. */\n name: string;\n /** The module the page loads for this plugin's half there, which default-exports its `ClientPlugin`. */\n client?: string;\n /** What the page half gets as `context.options`: the user's options it needs there, as JSON. */\n clientOptions?: unknown;\n /** What opens its panel: its own default, which its options let the user change. A plugin with no panel has none. */\n shortcut?: Shortcut;\n /** The plugins it can't do without, by name: the dev server won't start without them. */\n needs?: string[];\n /**\n * The packages it imports that the project installs itself (optional peers), by name: as the dev server starts,\n * it says how to install any that's missing, rather than failing when first used.\n */\n packages?: string[];\n /** Runs once, as the dev server starts and before it answers anything. Answers the plugin's API to the others. */\n setup?(context: ServerContext): Maybe<Api>;\n /** Routes of its own, by their first segment under `/__deictic/plugins/<name>/`. */\n routes?: { [route: string]: Route };\n /**\n * The model its panel shows for an element. Without it, the panel gets none. `source` is a `Refusal` where the\n * element isn't to be found in its file (it doesn't parse, or the page runs other code than it has): throw it where\n * the plugin needs the source, or go on without it, as a task does.\n */\n read?(source: Source | Refusal, target: Target): Maybe<Model>;\n /** Text edits for deictic to write, which it refuses without the source, or a change the plugin made itself. */\n apply?(source: Source | Refusal, target: Target, op: Op): Maybe<TextEdit[] | Done<Record>>;\n /**\n * Takes back a change `apply` made itself, or throws a `Refusal` saying why it can't any more. It may\n * answer what the next redo needs, where that differs (what it put back has a new ID).\n */\n undo?(record: Record): Maybe<void | Record>;\n /** Makes it again after an undo, and answers what the next undo needs, which may differ (a new ID). */\n redo?(record: Record): Maybe<Record>;\n /** Says what an op does, for the history: `className: px-2 → px-4`. */\n describe?(op: Op, before: Model): string;\n /**\n * Hears each problem deictic or a plugin reports, on the server or in the page, after every `setup` has run: once\n * per `key` while the dev server runs. Its own failure is only said, never reported again.\n */\n problem?(problem: Problem): Maybe<void>;\n}\n\nexport const definePlugin = <Model, Op, Record = unknown, Api = unknown>(\n plugin: ServerPlugin<Model, Op, Record, Api>,\n): ServerPlugin<Model, Op, Record, Api> => plugin;\n\n/** Where something is in an element, in CSS pixels from its top left. */\nexport interface Point {\n x: number;\n y: number;\n}\n\n/** A spot on the page: a marked element, and a point in it (or beside it, for the nearest to a point no marked element is under). */\nexport interface Spot {\n element: Element;\n at: Point;\n}\n\n/**\n * The tool panel: a bar docked to an edge of the window, which shows while a shortcut's keys are held and stays\n * while it's in use. A plugin adds its tools to it from its page half's `setup`.\n */\nexport interface ToolPanel {\n /**\n * Adds a plugin's controls, as one group, in the order plugins are loaded. Groups of one `section` sit together,\n * with no line between them, after the groups of none: the screenshots', recordings', voice's and tasks' are\n * `capture`. `last` puts a group at the end of its section, or after all the others for one of none. Each control is a button named by its `title`; its `aria-keyshortcuts`\n * (`B`, `Control+Z`) is the key the panel hears for it, alone or with the keys held to point, and what its tooltip\n * shows.\n */\n add: (group: HTMLElement, options?: { last?: boolean; section?: string }) => void;\n /**\n * Takes the page for a tool that works on it (drawing, picking a point): the tool that had it lets go first, and\n * the panel stays shown. `left` is called when another takes it, or Esc or the pointer tool gives the page back.\n * Answers what lets go of it, for the tool to call when it's done on its own.\n */\n hold: (left: () => void) => () => void;\n /** Keeps the panel shown while something goes on that its controls end (a recording). Answers what ends that. */\n keep: () => () => void;\n /**\n * Takes the page until a point of it is pressed, lighting what's under the pointer as pointing does: answers the\n * spot, the marked element there or the nearest to it, or nothing where the page was given back first.\n */\n pick: () => Promise<Spot | undefined>;\n}\n\n/**\n * The drawer: on the window's side, where what the plugins have for the page lands, a section each. It\n * shows while a shortcut's keys are held and a section has something, and stays while it's in use.\n */\nexport interface Drawer {\n /**\n * Adds a section, in the order added, or before the others with `first`. A section that has nothing to show sets\n * its own `hidden`: the drawer stays away while every one is. Folded away, the drawer counts what the sections\n * have: each says how many things it lists in `data-count`, and how many are unread in `data-unread`.\n */\n add: (section: HTMLElement, options?: { first?: boolean }) => void;\n /**\n * Opens one item in the drawer, in the sections' place, under `title` and a way back. The drawer stays while it's\n * open. `closed` is called when it's left, by the way back, Esc, or another item opening. Answers what closes it.\n */\n show: (view: HTMLElement, options?: { title?: string; closed?: () => void }) => () => void;\n /** Keeps the drawer up while something goes on in it; answers what lets it go. */\n keep: () => () => void;\n}\n\n/** Something a plugin made on the page that nothing has taken yet: a shot, a recording, a voice clip. */\nexport interface TrayItem {\n /** The plugin that made it. */\n plugin: string;\n /** Its ID, as that plugin has it. */\n id: string;\n /** What that plugin says of it, as JSON: the screenshots plugin's `Shot`, a `Recording`, a `Clip`. */\n value: unknown;\n}\n\n/**\n * What plugins made on the page from the tool panel, until something takes it: a task attaches what's there and\n * removes it. Kept for the tab's session, so it's there on the tab's next page too.\n */\nexport interface Tray {\n /** What's kept, oldest first: all of it, or one plugin's. */\n list: (plugin?: string) => TrayItem[];\n add: (plugin: string, id: string, value: unknown) => void;\n /** Takes one out, or all of a plugin's. */\n remove: (plugin: string, id?: string) => void;\n /** Hears every change from now on; answers what stops it. */\n subscribe: (listener: () => void) => () => void;\n}\n\nexport interface ClientContext {\n /** The dev server's base URL, ending in `/`. */\n base: string;\n /** deictic's shadow root, to draw in: neither the page's styles nor the overlay's cross over. */\n root: ShadowRoot;\n /** The server half's `clientOptions`, or nothing. */\n options: unknown;\n /** Another plugin's API in the page, as its `setup` answered it, or nothing when it isn't loaded. */\n use: <Name extends string>(name: Name) => ApiOf<ClientApis, Name> | undefined;\n /** Asks one of this plugin's own routes, from the page: `request('shots', { method: 'POST', body: blob })`. */\n request: (route: string, init?: RequestInit) => Promise<Response>;\n /** Says a problem of the plugin's own to the dev server, as the server half's `report` does: its `plugin` is this one. */\n report: (problem: Problem) => void;\n /**\n * Opens a place in a file under the root in the editor, as the popup's own link opens the element's: through the\n * dev server, or what answers in its place (`Standalone`). Rejects with why it couldn't.\n */\n edit: (place: Loc) => Promise<void>;\n /**\n * Opens the popup on an element at a plugin's tab, as its shortcut would, or with `at` on a spot in it: the\n * popup is then beside the spot, which is what's lit, and the tab's context has it. An element rendered again\n * since stands in for one no longer on the page. False when there's no such tab or no such element any more, and\n * while the open popup holds something unsaved, whose button then shakes. Not as `setup` runs, which is before the\n * popup can open.\n */\n open: (plugin: string, element: Element, at?: Point) => boolean;\n /** The tool panel, to add this plugin's tools to. */\n tools: ToolPanel;\n /** What was made from the tool panel and not taken yet. */\n tray: Tray;\n /** The drawer, to add this plugin's section to. */\n drawer: Drawer;\n /**\n * Lights an element on the page as pointing at it does, for something of the overlay's own that stands for it (a\n * task's row in the drawer, while the pointer is on it); none puts the light back as it was.\n */\n light: (element?: Element) => void;\n /**\n * Shows `items` in the lightbox over everything, at `at` (the first by default), stepping between them with\n * ← and →. With `from`, it grows out of that element (the chip clicked) and shrinks back into it on close.\n */\n lightbox: (items: LightboxItem[], options?: LightboxOptions) => { close: () => void };\n}\n\n/** What the lightbox shows: a picture, a page in a frame (a recording's replay), or a sound with its waveform. */\nexport type LightboxItem = {\n /** Its name, over it. */\n title: string;\n /** Buttons beside the name: each closes the lightbox and runs. */\n actions?: LightboxAction[];\n} & ({ kind: 'image'; url: string } | { kind: 'page'; url: string } | { kind: 'audio'; url: string });\n\nexport interface LightboxAction {\n label: string;\n title?: string;\n run: () => void;\n}\n\nexport interface LightboxOptions {\n /** The item it opens at. */\n at?: number;\n /** The element it grows out of, and goes back into. */\n from?: Element;\n}\n\nexport interface PanelContext<Model, Op> extends ClientContext {\n /**\n * The element clicked: the one the source marked, under the pointer or around what is. Back from `away`\n * it may be off the page (`isConnected` is false), where the page moved on without it: the element as it\n * was left, or after a page load an empty one of its tag and mark. `elements` is then empty.\n */\n element: Element;\n /**\n * What was under the pointer, where it isn't `element` but inside it: markup nothing marked, as a\n * dependency's, or in an open shadow root, as the popup's own on a page that shows it (`popupIn`).\n */\n pointed?: Element;\n /** The spot in `element` the popup was opened on, where it was (the tool panel's task tool), not the element as a whole. */\n at?: Point;\n /** Every element on the page from the same place in the source, the clicked one among them: the rows of a list. */\n elements: Element[];\n target: Target;\n model: Model;\n /**\n * Applies an op on disk, and reads the model again. Rejects with the server's reason, which the panel also shows.\n * On another element with `on`, whose model is then the one answered: for an op that's about that one.\n */\n apply(op: Op, on?: Target): Promise<Model>;\n close: () => void;\n /**\n * Says there's something here that leaving would lose (words typed, a change tried on the page), and the button\n * that keeps it: a click outside the popup then shakes that button, where it would have closed the popup.\n * `undefined` once there's nothing to lose. Forgotten as the panel unmounts.\n */\n unsaved: (action: HTMLElement | undefined) => void;\n /**\n * Leaves the popup to do something on the page, then comes back: closes it, runs `task` (a recording, a\n * pick of another element), and opens it again at this tab on this element. The next mount gets\n * `resumed`: the `state` kept now (what was typed, what's attached), and what `task` answered, or why\n * it failed. The state stays in the page, as it is: no need for JSON. It's also kept for the tab's next\n * page, as a structured clone, where it can be one: after a page load, the plugin's `resume` says whether\n * the task carries on, and the popup comes back there.\n */\n away: <T>(state: unknown, task: () => Promise<T>) => void;\n /** Set when this mount is the panel coming back from `away`. */\n resumed?: Resumed;\n}\n\n/** What a panel coming back from `away` gets: the state it kept, and the task's result or problem. */\nexport interface Resumed {\n state: unknown;\n result?: unknown;\n /** Why the task failed: its error's message. */\n problem?: string;\n}\n\nexport interface ClientPlugin<Model = unknown, Op = unknown, Api = unknown> {\n /** The server half's `name`. */\n name: string;\n /** Shown over the element while its shortcut's keys are held, and atop the panel. */\n label?: string;\n /**\n * Runs once, as the page starts, before any panel opens (a recording starts here). Answers the\n * plugin's API to the others in the page, at once: one that needs time keeps its promises inside it.\n */\n setup?(context: ClientContext): Api;\n /**\n * Asked as a page starts where the page before it left this plugin's panel `away`: the task it left for,\n * where that carries on in this page (a recording does), or nothing where it ended with the page. When it's\n * done the popup opens at this tab with `resumed`, on the element where this page has it and without where not.\n */\n resume?(context: ClientContext): Promise<unknown> | undefined;\n /**\n * What it shows on the page while a shortcut's keys are held, and the page is dimmed to point on: the tasks\n * plugin pins each task where its element is. Answers what takes it away.\n */\n pointing?(context: ClientContext): () => void;\n /**\n * A shortcut's press on a marked element, before the page hears it and before the popup opens: the page as the\n * person saw it, a tooltip still open under the pointer, a menu still focused. Called as the press goes down, so\n * it must be quick; the screenshots plugin keeps what a shot needs here, and renders it later.\n */\n pressed?(context: ClientContext, element: Element): void;\n /** Draws into `panel`, inside deictic's shadow root. Returns what to undo on the page when the panel closes. */\n mount?: (panel: HTMLElement, context: PanelContext<Model, Op>) => (() => void) | void;\n}\n\nexport const defineClientPlugin = <Model, Op, Api = unknown>(plugin: ClientPlugin<Model, Op, Api>): ClientPlugin<Model, Op, Api> => plugin;\n"],"mappings":";;AAqEA,IAAa,UAAb,cAA6B,MAAM;CACxB,OAAO;AAClB;AAgHA,MAAa,gBACX,WACyC;AAyO3C,MAAa,sBAAgD,WAAuE"}
@@ -137,6 +137,7 @@ function attachments(message, out, indent, task) {
137
137
  console.log(`${indent}${a.name} (${kb}), a voice clip${saved}`);
138
138
  if (task === void 0) console.log(`${indent} ${ME} voice ${/^voice-(.+)\.\w+$/.exec(a.name)?.[1] ?? a.id} (speech)`);
139
139
  } else if (a.name === "element.html") console.log(`${indent}${a.name} (${kb}), the element's HTML as it rendered, if you need it${saved}`);
140
+ else if (/^react(\.\d+)?\.json$/.test(a.name)) console.log(`${indent}${a.name} (${kb}), the props, state and hooks of the components that wrote it, as React's DevTools has them, if the change depends on them${saved}`);
140
141
  else console.log(`${indent}${a.name} (${kb})${saved}`);
141
142
  }
142
143
  if (task !== void 0 && message.attachments.some((a) => a.name.startsWith("voice-"))) console.log(`${indent}${ME} voice ${task} (speech in every clip), ${ME} transcribe ${task} (the words)`);
@@ -1 +1 @@
1
- {"version":3,"file":"task.js","names":[],"sources":["../../src/cli/task.ts"],"sourcesContent":["/**\n * `deictic task`: a task, briefly: what was asked, where (and whether that place has moved in the source since), the\n * page, what's attached with the command to look at each, the replies, and the other open tasks about the same page.\n */\nimport { existsSync, mkdirSync, readFileSync } from 'node:fs';\nimport { dirname, join, relative, resolve } from 'node:path';\n\nimport { deicticDirs, download, ME, type Message, read, vbJson } from './board.ts';\n\n/** An actor by the profile its ID ends in (`…+claude`), or the ID of one that writes as itself. */\nconst nameOf = (actor: string) => (actor.includes('+') ? actor.slice(actor.lastIndexOf('+') + 1) : actor);\n\nexport function run(id: string, values: { out?: string }): void {\n const { message: root, replies } = read(id);\n const [asked = '', where = ''] = root.text.split(/\\n---\\n/);\n const label = (key: string) => root.labels[key];\n const at = label('deictic.at');\n\n // Who asked, said as that: the line's state is beside it, and a board's record names no one for a task's end.\n console.log(`#${root.id} ${root.task?.state ?? 'not a task'}, asked by ${root.author?.handle ?? root.by.actor}, ${root.createdAt}`);\n const claim = root.task?.claim;\n if (claim) console.log(`Claimed by ${nameOf(claim.actor)} until ${claim.until}`);\n // A task not over yet has them, as null.\n if (root.task?.result != null) console.log(`Result: ${root.task.result}`);\n if (root.task?.reason != null) console.log(`Reason: ${root.task.reason}`);\n console.log(`\\nAsked:\\n${asked.trim()}\\n`);\n // The part inside the element that was pointed at, where nothing marked it: what the person means.\n const pointed = /\\nPointed at, inside it: `([^`]*)`\\n`{3,}\\w*\\n([\\s\\S]*?)\\n`{3,}/.exec(where);\n // Where, from the labels: the place, the page, and the viewport to look at it in.\n const facts: [string, (v: string) => string | undefined][] = [\n ['deictic.project', (v) => `Project ${v}`],\n ['deictic.at', (v) => `${v} <${label('deictic.tag') ?? '?'}>`],\n // From its own line out: before the label, tasks said it in their text, which is printed below as it is.\n // The first is often a shared component (`ui/label.tsx`), which the task isn't about changing everywhere.\n ['deictic.source', (v) => `Source: ${at?.replace(/:\\d+$/, '') ?? '?'} ← ${v} (a shared component's change is usually at the next)`],\n ['deictic.url', (v) => v],\n ['deictic.viewport', (v) => `Viewport ${v}`],\n [\n 'deictic.count',\n (v) => {\n if (v === '1') return undefined;\n const nth = label('deictic.nth');\n const text = label('deictic.text');\n const which = nth === undefined ? '' : `: it's number ${nth}${text === undefined ? '' : `, saying \"${text}\"`}`;\n return `${v} elements on the page come from that line${which}`;\n },\n ],\n [\n 'deictic.point',\n // Circled only in a shot taken as the task went, which no label tells from one drawn on before.\n (v) =>\n `About the spot at x,y ${v} in that element (CSS px from its top left): a screenshot taken as the task was added has it circled`,\n ],\n // A task added before shots were numbered had its one shot's place here.\n ['deictic.position', (v) => `In the screenshot at x,y ${v}, ${label('deictic.size') ?? '?'} (CSS px)`],\n ];\n for (const [key, say] of facts) {\n const value = label(key);\n const line = value === undefined ? undefined : say(value);\n if (line !== undefined) console.log(line);\n }\n const problem = label('deictic.problem.kind');\n if (problem !== undefined) {\n const plugin = label('deictic.problem.plugin');\n console.log(\n `A problem deictic ${label('deictic.version') ?? ''} reported${plugin === undefined ? '' : ` in its ${plugin} plugin`}, not a person's ask`,\n );\n } else if (at === undefined) {\n console.log(\"About the page as a whole: no element was attached, so find it from the words, the page's URL and the screenshot\");\n }\n for (const line of drawn(root)) console.log(line);\n // A task added before these were labels says them after its words; a problem, its details.\n const told = (pointed ? where.slice(0, pointed.index) : where).trim();\n if (told !== '') console.log(problem === undefined ? told : `Details:\\n${told}`);\n if (pointed) console.log(`\\nPointed at, inside it: ${pointed[1]}\\n ${pointed[2]}`);\n const path = label('deictic.pointed');\n if (path !== undefined) {\n const file = root.attachments.some((a) => a.name === 'pointed.html') ? 'pointed.html' : 'element.html';\n // Markup no line marks, a dependency's.\n console.log(\n `\\nPointed at, inside it: ${path} (its HTML is in ${file}): what they mean, though no line marks it; find it by its classes`,\n );\n }\n\n if (at !== undefined) placeOf(at, label('deictic.line'));\n const out = values.out === undefined ? undefined : resolve(values.out);\n if (root.attachments.length > 0) console.log('\\nAttached:');\n attachments(root, out, ' ', String(root.id));\n\n if (replies.length > 0) console.log('\\nReplies:');\n for (const r of replies) {\n console.log(` ${r.author?.handle ?? r.by.actor}: ${r.text}`);\n // A reply may attach what a task does: shots, a recording, a voice note.\n for (const line of drawn(r)) console.log(` ${line}`);\n attachments(r, out, ' ');\n }\n // Said once, not as a command per file: most tasks need their shots, and `--out` gets everything at once.\n if (out === undefined && [root, ...replies].some((m) => m.attachments.length > 0))\n console.log(`\\nTo download what's attached: ${ME} task ${root.id} --out <dir>`);\n others(root);\n}\n\n/**\n * What the attached files don't say, from the numbered labels: where the element is in each shot and the notes on it, the\n * notes drawn on the page, and what wasn't kept any more. Where a recording replays, `recording` says.\n */\nfunction drawn({ labels, attachments }: Message): string[] {\n const numbered = (prefix: string) => {\n const out: string[] = [];\n for (let n = 1; labels[`${prefix}.${n}`] !== undefined; n++) out.push(labels[`${prefix}.${n}`]!);\n return out;\n };\n const notes = (prefix: string) => numbered(`${prefix}.note`).map((note) => JSON.stringify(note));\n const lines: string[] = [];\n // `deictic.screenshot.N` is the Nth PNG attached, `deictic.recording.N` the Nth recording.\n for (const [i, { name }] of attachments.filter((a) => a.type === 'image/png').entries()) {\n const shot = `deictic.screenshot.${i + 1}`;\n const position = labels[`${shot}.position`];\n if (position === undefined) continue;\n const said = notes(shot);\n lines.push(\n `${name}: the element at x,y ${position}, ${labels[`${shot}.size`] ?? '?'} (CSS px)${said.length === 0 ? '' : `; notes drawn on it: ${said.join(', ')}`}`,\n );\n }\n // The others it's about, after the one it names first: the Nth element's HTML is `element.N.html`.\n for (const [i, other] of numbered('deictic.also').entries()) {\n const html = attachments.some((a) => a.name === `element.${i + 2}.html`) ? ` (its HTML is in element.${i + 2}.html)` : '';\n lines.push(`Also about ${other}${html}`);\n }\n const onPage = notes('deictic');\n if (onPage.length > 0) lines.push(`Notes drawn on the page: ${onPage.join(', ')}`);\n const dropped = numbered('deictic.dropped');\n if (dropped.length > 0) lines.push(`Not attached, as it wasn't kept any more: ${dropped.join(', ')}`);\n return lines;\n}\n\n/** The place as the task saw it, against the file now: the element's opening tag may have moved or changed. */\nfunction placeOf(at: string, first: string | undefined): void {\n const file = at.replace(/:\\d+:\\d+$/, '');\n const line = Number(at.split(':').at(-2));\n // Marks are from the dev server's root: here, above, or a folder with a .deictic/ of its own.\n const roots = [process.cwd(), ...deicticDirs().map(dirname)];\n const path = roots.map((r) => resolve(r, file)).find((p) => existsSync(p));\n if (path === undefined) {\n console.log(`\\n${file} isn't under ${roots.join(' or ')}: find the dev server's root.`);\n return;\n }\n const lines = readFileSync(path, 'utf8').split('\\n');\n const shown = relative(process.cwd(), path) || path;\n // The tag's first line may follow other code on its line: `const App = () => <h1>`.\n const now = lines[line - 1]?.trim();\n if (first === undefined || now?.includes(first.slice(0, 40))) {\n console.log(`\\nFile: ${shown}:${line}, as the task saw it.`);\n return;\n }\n const moved = lines.findIndex((l) => l.includes(first.slice(0, 40)));\n console.log(\n moved >= 0\n ? `\\nFile: moved to ${shown}:${moved + 1} (the task says line ${line}).`\n : `\\nFile: ${shown}:${line} no longer reads as the task saw it; it was:\\n ${first}`,\n );\n}\n\n/**\n * A message's files, with the command to read a recording or voice clip by, downloaded to `out` where it's given. The\n * task's own are read by its ID (all its voice clips at once); a reply's recording by where it replays, and its voice\n * note by the clip's ID.\n */\nfunction attachments(message: Message, out: string | undefined, indent: string, task?: string): void {\n if (out !== undefined && message.attachments.length > 0) mkdirSync(out, { recursive: true });\n const recordings = message.attachments.filter((a) => a.name.startsWith('recording-'));\n for (const a of message.attachments) {\n const kb = `${Math.round(a.size / 1024)} KB`;\n if (out !== undefined) download(a, join(out, a.name));\n const saved = out === undefined ? '' : ` → ${relative(process.cwd(), join(out, a.name))}`;\n if (a.name.startsWith('recording-')) {\n const n = recordings.indexOf(a) + 1;\n const ref = task === undefined ? message.labels[`deictic.recording.${n}.replay`] : `${task}${n > 1 ? ` --nth ${n}` : ''}`;\n console.log(`${indent}${a.name} (${kb})${saved}`);\n if (ref !== undefined) console.log(`${indent} ${ME} recording ${ref} (timeline), ${ME} frame ${ref} (frames)`);\n } else if (a.name.startsWith('voice-')) {\n console.log(`${indent}${a.name} (${kb}), a voice clip${saved}`);\n if (task === undefined) console.log(`${indent} ${ME} voice ${/^voice-(.+)\\.\\w+$/.exec(a.name)?.[1] ?? a.id} (speech)`);\n } else if (a.name === 'element.html') {\n console.log(`${indent}${a.name} (${kb}), the element's HTML as it rendered, if you need it${saved}`);\n } else {\n console.log(`${indent}${a.name} (${kb})${saved}`);\n }\n }\n if (task !== undefined && message.attachments.some((a) => a.name.startsWith('voice-')))\n console.log(`${indent}${ME} voice ${task} (speech in every clip), ${ME} transcribe ${task} (the words)`);\n}\n\n/** The other open tasks about the same page, of the same project: left a minute apart, they're often one change. */\nfunction others(root: Message): void {\n const page = root.labels['deictic.page'];\n if (page === undefined) return;\n const project = root.labels['deictic.project'];\n const labels = [`deictic.page=${page}`, ...(project === undefined ? [] : [`deictic.project=${project}`])];\n const { tasks } = vbJson<{ tasks: { message: Message }[] }>(['tasks', root.channel, ...labels.flatMap((l) => ['--label', l])]);\n const rest = tasks.map((t) => t.message).filter((m) => m.id !== root.id);\n if (rest.length === 0) return;\n console.log(\n `\\n${rest.length} other open task${rest.length === 1 ? '' : 's'} on ${page}: read them before you start, they may be one change.`,\n );\n for (const m of rest) {\n const title = (m.text.split(/\\n---\\n/)[0] ?? '').split('\\n')[0]?.slice(0, 100);\n console.log(` #${m.id} ${m.task?.state ?? ''}, ${m.labels['deictic.at'] ?? '?'}: ${title}`);\n }\n}\n"],"mappings":";;;;;;;;;AAUA,MAAM,UAAU,UAAmB,MAAM,SAAS,GAAG,IAAI,MAAM,MAAM,MAAM,YA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;EAC7E,QAAQ,IAAI,MAAM,EAAE,GAAG,GAAG,EAAE,MAAM,SAAS,GAAG,IAAI,EAAE,OAAO,iBAAiB,IAAI,IAAI,OAAO;CAC7F;AACF"}
1
+ {"version":3,"file":"task.js","names":[],"sources":["../../src/cli/task.ts"],"sourcesContent":["/**\n * `deictic task`: a task, briefly: what was asked, where (and whether that place has moved in the source since), the\n * page, what's attached with the command to look at each, the replies, and the other open tasks about the same page.\n */\nimport { existsSync, mkdirSync, readFileSync } from 'node:fs';\nimport { dirname, join, relative, resolve } from 'node:path';\n\nimport { deicticDirs, download, ME, type Message, read, vbJson } from './board.ts';\n\n/** An actor by the profile its ID ends in (`…+claude`), or the ID of one that writes as itself. */\nconst nameOf = (actor: string) => (actor.includes('+') ? actor.slice(actor.lastIndexOf('+') + 1) : actor);\n\nexport function run(id: string, values: { out?: string }): void {\n const { message: root, replies } = read(id);\n const [asked = '', where = ''] = root.text.split(/\\n---\\n/);\n const label = (key: string) => root.labels[key];\n const at = label('deictic.at');\n\n // Who asked, said as that: the line's state is beside it, and a board's record names no one for a task's end.\n console.log(`#${root.id} ${root.task?.state ?? 'not a task'}, asked by ${root.author?.handle ?? root.by.actor}, ${root.createdAt}`);\n const claim = root.task?.claim;\n if (claim) console.log(`Claimed by ${nameOf(claim.actor)} until ${claim.until}`);\n // A task not over yet has them, as null.\n if (root.task?.result != null) console.log(`Result: ${root.task.result}`);\n if (root.task?.reason != null) console.log(`Reason: ${root.task.reason}`);\n console.log(`\\nAsked:\\n${asked.trim()}\\n`);\n // The part inside the element that was pointed at, where nothing marked it: what the person means.\n const pointed = /\\nPointed at, inside it: `([^`]*)`\\n`{3,}\\w*\\n([\\s\\S]*?)\\n`{3,}/.exec(where);\n // Where, from the labels: the place, the page, and the viewport to look at it in.\n const facts: [string, (v: string) => string | undefined][] = [\n ['deictic.project', (v) => `Project ${v}`],\n ['deictic.at', (v) => `${v} <${label('deictic.tag') ?? '?'}>`],\n // From its own line out: before the label, tasks said it in their text, which is printed below as it is.\n // The first is often a shared component (`ui/label.tsx`), which the task isn't about changing everywhere.\n ['deictic.source', (v) => `Source: ${at?.replace(/:\\d+$/, '') ?? '?'} ← ${v} (a shared component's change is usually at the next)`],\n ['deictic.url', (v) => v],\n ['deictic.viewport', (v) => `Viewport ${v}`],\n [\n 'deictic.count',\n (v) => {\n if (v === '1') return undefined;\n const nth = label('deictic.nth');\n const text = label('deictic.text');\n const which = nth === undefined ? '' : `: it's number ${nth}${text === undefined ? '' : `, saying \"${text}\"`}`;\n return `${v} elements on the page come from that line${which}`;\n },\n ],\n [\n 'deictic.point',\n // Circled only in a shot taken as the task went, which no label tells from one drawn on before.\n (v) =>\n `About the spot at x,y ${v} in that element (CSS px from its top left): a screenshot taken as the task was added has it circled`,\n ],\n // A task added before shots were numbered had its one shot's place here.\n ['deictic.position', (v) => `In the screenshot at x,y ${v}, ${label('deictic.size') ?? '?'} (CSS px)`],\n ];\n for (const [key, say] of facts) {\n const value = label(key);\n const line = value === undefined ? undefined : say(value);\n if (line !== undefined) console.log(line);\n }\n const problem = label('deictic.problem.kind');\n if (problem !== undefined) {\n const plugin = label('deictic.problem.plugin');\n console.log(\n `A problem deictic ${label('deictic.version') ?? ''} reported${plugin === undefined ? '' : ` in its ${plugin} plugin`}, not a person's ask`,\n );\n } else if (at === undefined) {\n console.log(\"About the page as a whole: no element was attached, so find it from the words, the page's URL and the screenshot\");\n }\n for (const line of drawn(root)) console.log(line);\n // A task added before these were labels says them after its words; a problem, its details.\n const told = (pointed ? where.slice(0, pointed.index) : where).trim();\n if (told !== '') console.log(problem === undefined ? told : `Details:\\n${told}`);\n if (pointed) console.log(`\\nPointed at, inside it: ${pointed[1]}\\n ${pointed[2]}`);\n const path = label('deictic.pointed');\n if (path !== undefined) {\n const file = root.attachments.some((a) => a.name === 'pointed.html') ? 'pointed.html' : 'element.html';\n // Markup no line marks, a dependency's.\n console.log(\n `\\nPointed at, inside it: ${path} (its HTML is in ${file}): what they mean, though no line marks it; find it by its classes`,\n );\n }\n\n if (at !== undefined) placeOf(at, label('deictic.line'));\n const out = values.out === undefined ? undefined : resolve(values.out);\n if (root.attachments.length > 0) console.log('\\nAttached:');\n attachments(root, out, ' ', String(root.id));\n\n if (replies.length > 0) console.log('\\nReplies:');\n for (const r of replies) {\n console.log(` ${r.author?.handle ?? r.by.actor}: ${r.text}`);\n // A reply may attach what a task does: shots, a recording, a voice note.\n for (const line of drawn(r)) console.log(` ${line}`);\n attachments(r, out, ' ');\n }\n // Said once, not as a command per file: most tasks need their shots, and `--out` gets everything at once.\n if (out === undefined && [root, ...replies].some((m) => m.attachments.length > 0))\n console.log(`\\nTo download what's attached: ${ME} task ${root.id} --out <dir>`);\n others(root);\n}\n\n/**\n * What the attached files don't say, from the numbered labels: where the element is in each shot and the notes on it, the\n * notes drawn on the page, and what wasn't kept any more. Where a recording replays, `recording` says.\n */\nfunction drawn({ labels, attachments }: Message): string[] {\n const numbered = (prefix: string) => {\n const out: string[] = [];\n for (let n = 1; labels[`${prefix}.${n}`] !== undefined; n++) out.push(labels[`${prefix}.${n}`]!);\n return out;\n };\n const notes = (prefix: string) => numbered(`${prefix}.note`).map((note) => JSON.stringify(note));\n const lines: string[] = [];\n // `deictic.screenshot.N` is the Nth PNG attached, `deictic.recording.N` the Nth recording.\n for (const [i, { name }] of attachments.filter((a) => a.type === 'image/png').entries()) {\n const shot = `deictic.screenshot.${i + 1}`;\n const position = labels[`${shot}.position`];\n if (position === undefined) continue;\n const said = notes(shot);\n lines.push(\n `${name}: the element at x,y ${position}, ${labels[`${shot}.size`] ?? '?'} (CSS px)${said.length === 0 ? '' : `; notes drawn on it: ${said.join(', ')}`}`,\n );\n }\n // The others it's about, after the one it names first: the Nth element's HTML is `element.N.html`.\n for (const [i, other] of numbered('deictic.also').entries()) {\n const html = attachments.some((a) => a.name === `element.${i + 2}.html`) ? ` (its HTML is in element.${i + 2}.html)` : '';\n lines.push(`Also about ${other}${html}`);\n }\n const onPage = notes('deictic');\n if (onPage.length > 0) lines.push(`Notes drawn on the page: ${onPage.join(', ')}`);\n const dropped = numbered('deictic.dropped');\n if (dropped.length > 0) lines.push(`Not attached, as it wasn't kept any more: ${dropped.join(', ')}`);\n return lines;\n}\n\n/** The place as the task saw it, against the file now: the element's opening tag may have moved or changed. */\nfunction placeOf(at: string, first: string | undefined): void {\n const file = at.replace(/:\\d+:\\d+$/, '');\n const line = Number(at.split(':').at(-2));\n // Marks are from the dev server's root: here, above, or a folder with a .deictic/ of its own.\n const roots = [process.cwd(), ...deicticDirs().map(dirname)];\n const path = roots.map((r) => resolve(r, file)).find((p) => existsSync(p));\n if (path === undefined) {\n console.log(`\\n${file} isn't under ${roots.join(' or ')}: find the dev server's root.`);\n return;\n }\n const lines = readFileSync(path, 'utf8').split('\\n');\n const shown = relative(process.cwd(), path) || path;\n // The tag's first line may follow other code on its line: `const App = () => <h1>`.\n const now = lines[line - 1]?.trim();\n if (first === undefined || now?.includes(first.slice(0, 40))) {\n console.log(`\\nFile: ${shown}:${line}, as the task saw it.`);\n return;\n }\n const moved = lines.findIndex((l) => l.includes(first.slice(0, 40)));\n console.log(\n moved >= 0\n ? `\\nFile: moved to ${shown}:${moved + 1} (the task says line ${line}).`\n : `\\nFile: ${shown}:${line} no longer reads as the task saw it; it was:\\n ${first}`,\n );\n}\n\n/**\n * A message's files, with the command to read a recording or voice clip by, downloaded to `out` where it's given. The\n * task's own are read by its ID (all its voice clips at once); a reply's recording by where it replays, and its voice\n * note by the clip's ID.\n */\nfunction attachments(message: Message, out: string | undefined, indent: string, task?: string): void {\n if (out !== undefined && message.attachments.length > 0) mkdirSync(out, { recursive: true });\n const recordings = message.attachments.filter((a) => a.name.startsWith('recording-'));\n for (const a of message.attachments) {\n const kb = `${Math.round(a.size / 1024)} KB`;\n if (out !== undefined) download(a, join(out, a.name));\n const saved = out === undefined ? '' : ` → ${relative(process.cwd(), join(out, a.name))}`;\n if (a.name.startsWith('recording-')) {\n const n = recordings.indexOf(a) + 1;\n const ref = task === undefined ? message.labels[`deictic.recording.${n}.replay`] : `${task}${n > 1 ? ` --nth ${n}` : ''}`;\n console.log(`${indent}${a.name} (${kb})${saved}`);\n if (ref !== undefined) console.log(`${indent} ${ME} recording ${ref} (timeline), ${ME} frame ${ref} (frames)`);\n } else if (a.name.startsWith('voice-')) {\n console.log(`${indent}${a.name} (${kb}), a voice clip${saved}`);\n if (task === undefined) console.log(`${indent} ${ME} voice ${/^voice-(.+)\\.\\w+$/.exec(a.name)?.[1] ?? a.id} (speech)`);\n } else if (a.name === 'element.html') {\n console.log(`${indent}${a.name} (${kb}), the element's HTML as it rendered, if you need it${saved}`);\n } else if (/^react(\\.\\d+)?\\.json$/.test(a.name)) {\n console.log(\n `${indent}${a.name} (${kb}), the props, state and hooks of the components that wrote it, as React's DevTools has them, if the change depends on them${saved}`,\n );\n } else {\n console.log(`${indent}${a.name} (${kb})${saved}`);\n }\n }\n if (task !== undefined && message.attachments.some((a) => a.name.startsWith('voice-')))\n console.log(`${indent}${ME} voice ${task} (speech in every clip), ${ME} transcribe ${task} (the words)`);\n}\n\n/** The other open tasks about the same page, of the same project: left a minute apart, they're often one change. */\nfunction others(root: Message): void {\n const page = root.labels['deictic.page'];\n if (page === undefined) return;\n const project = root.labels['deictic.project'];\n const labels = [`deictic.page=${page}`, ...(project === undefined ? [] : [`deictic.project=${project}`])];\n const { tasks } = vbJson<{ tasks: { message: Message }[] }>(['tasks', root.channel, ...labels.flatMap((l) => ['--label', l])]);\n const rest = tasks.map((t) => t.message).filter((m) => m.id !== root.id);\n if (rest.length === 0) return;\n console.log(\n `\\n${rest.length} other open task${rest.length === 1 ? '' : 's'} on ${page}: read them before you start, they may be one change.`,\n );\n for (const m of rest) {\n const title = (m.text.split(/\\n---\\n/)[0] ?? '').split('\\n')[0]?.slice(0, 100);\n console.log(` #${m.id} ${m.task?.state ?? ''}, ${m.labels['deictic.at'] ?? '?'}: ${title}`);\n }\n}\n"],"mappings":";;;;;;;;;AAUA,MAAM,UAAU,UAAmB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;CACA,KAAK,MAAM,KAAK,MAAM;EACpB,MAAM,SAAS,EAAE,KAAK,MAAM,SAAS,CAAC,CAAC,MAAM,GAAA,CAAI,MAAM,IAAI,CAAC,CAAC,EAAE,EAAE,MAAM,GAAG,GAAG;EAC7E,QAAQ,IAAI,MAAM,EAAE,GAAG,GAAG,EAAE,MAAM,SAAS,GAAG,IAAI,EAAE,OAAO,iBAAiB,IAAI,IAAI,OAAO;CAC7F;AACF"}
@@ -283,7 +283,16 @@ function tasks(options = {}) {
283
283
  name: "pointed.html",
284
284
  type: "text/html"
285
285
  });
286
+ const json = (of, name) => {
287
+ if (typeof of === "string" && of !== "") files.push({
288
+ data: new TextEncoder().encode(of.slice(0, REACT)),
289
+ name,
290
+ type: "application/json"
291
+ });
292
+ };
293
+ json(op.react, "react.json");
286
294
  for (const [i, other] of (op.also ?? []).entries()) {
295
+ json(other.react, `react.${i + 2}.json`);
287
296
  if (typeof other.html !== "string" || other.html === "") continue;
288
297
  files.push({
289
298
  data: new TextEncoder().encode(other.html.slice(0, HTML)),
@@ -582,6 +591,8 @@ const boxOf = ({ x, y, width, height }) => [
582
591
  ].map(Math.round);
583
592
  /** What `element.html` holds of an element at most, in characters: a table's rows, not a whole page. */
584
593
  const HTML = 1e5;
594
+ /** What `react.json` holds at most, in characters: the page half cuts it to less. */
595
+ const REACT = 25e4;
585
596
  /** A label's value: a board holds 256 characters. */
586
597
  const LABEL = 256;
587
598
  /** The project's name: the `name` in the root's `package.json`, or nothing where it has none. */