shapewall 0.0.0-stage → 0.2.2
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.
- package/CHANGELOG.md +139 -0
- package/Dockerfile.agent +45 -0
- package/LICENSE +202 -0
- package/NOTICE +12 -0
- package/README.md +651 -2
- package/THIRD_PARTY.md +165 -0
- package/bin/shapewall.js +29 -0
- package/dist/agent/package-lock.json +8384 -0
- package/dist/client/assets/BoardChat-D5SFd8HE.js +28 -0
- package/dist/client/assets/BuzzDialog-HWXBy52W.js +1 -0
- package/dist/client/assets/ChecksPanel-DTdImWoD.js +1 -0
- package/dist/client/assets/History-CEv6b-av.js +1 -0
- package/dist/client/assets/LocalSettings-C4vriEVQ.js +1 -0
- package/dist/client/assets/Management-DCfhcEUY.js +1 -0
- package/dist/client/assets/QuickConnect-DQGgUsl1.js +1 -0
- package/dist/client/assets/ShareDialog-C_plIto0.js +2 -0
- package/dist/client/assets/app-update-dialog-2hPz_N9G.js +1 -0
- package/dist/client/assets/circle-x-BZMPi8Zf.js +1 -0
- package/dist/client/assets/index-ByQRKVit.css +2 -0
- package/dist/client/assets/index-DweQ8Qtu.js +29 -0
- package/dist/client/assets/refresh-cw-CRow0Nbq.js +1 -0
- package/dist/client/assets/runtime-Bft6x_6E.js +4 -0
- package/dist/client/assets/square-A8EnIYLR.js +1 -0
- package/dist/client/assets/tts-dist-DYlBQmwG.js +18 -0
- package/dist/client/assets/tts-en-g2p-BPUtBFGG.js +1 -0
- package/dist/client/assets/tts-ort-wasm-simd-threaded-qh98TCA_.wasm +0 -0
- package/dist/client/assets/tts-ort.wasm.bundle.min-rEkcs_ow.js +12 -0
- package/dist/client/assets/tts-rolldown-runtime-D8NudN84.js +1 -0
- package/dist/client/assets/tts-spacy-en-tokenizer-6SNMl--A.json +1 -0
- package/dist/client/assets/tts-tts.worker-Bzm6aWbv.js +1 -0
- package/dist/client/assets/tts-us_gold-DcjeNMH1.json +92589 -0
- package/dist/client/assets/tts-us_silver-C964mEB5.json +93363 -0
- package/dist/client/assets/ui-CLbws0rx.js +41 -0
- package/dist/client/build-info.json +1 -0
- package/dist/client/favicon.svg +7 -0
- package/dist/client/icons/apple-touch-icon.png +0 -0
- package/dist/client/icons/icon-192.png +0 -0
- package/dist/client/icons/icon-512.png +0 -0
- package/dist/client/icons/maskable-512.png +0 -0
- package/dist/client/index.html +25 -0
- package/dist/client/manifest.webmanifest +15 -0
- package/dist/client/sw.js +53 -0
- package/dist/client/theme-boot.js +27 -0
- package/dist/console/assets/LocalAccountsApp-BQCcmj3x.js +1 -0
- package/dist/console/assets/LocalConsole-Bb2FUDs7.js +1 -0
- package/dist/console/assets/app-update-dialog-DIeYepLZ.js +1 -0
- package/dist/console/assets/console-C7uJLLOn.js +51 -0
- package/dist/console/assets/console-R8IBY3Am.css +2 -0
- package/dist/console/build-info.json +1 -0
- package/dist/console/console.html +21 -0
- package/dist/console/favicon.svg +7 -0
- package/dist/console/icons/apple-touch-icon.png +0 -0
- package/dist/console/icons/icon-192.png +0 -0
- package/dist/console/icons/icon-512.png +0 -0
- package/dist/console/icons/maskable-512.png +0 -0
- package/dist/console/manifest.webmanifest +15 -0
- package/dist/console/theme-boot.js +27 -0
- package/docs/agent-hardening.md +342 -0
- package/docs/agent-recipes.md +187 -0
- package/docs/agent-workflow.md +320 -0
- package/docs/agents.md +894 -0
- package/docs/architecture.md +242 -0
- package/docs/buzz.md +140 -0
- package/docs/capture-warnings.md +57 -0
- package/docs/config.md +489 -0
- package/docs/deployment.md +289 -0
- package/docs/design-system.md +162 -0
- package/docs/github.md +107 -0
- package/docs/hosted.md +764 -0
- package/docs/images/board-overview.png +0 -0
- package/docs/images/journeys.png +0 -0
- package/docs/images/live-comment.png +0 -0
- package/docs/images/phone-comment.png +0 -0
- package/docs/images/phone-overview.png +0 -0
- package/docs/images/variant.png +0 -0
- package/docs/interaction-audits.md +40 -0
- package/docs/journeys.md +137 -0
- package/docs/local-accounts.md +80 -0
- package/docs/notifications.md +237 -0
- package/docs/page-checks.md +69 -0
- package/docs/performance.md +174 -0
- package/docs/starter-agent.md +325 -0
- package/docs/updates.md +87 -0
- package/examples/audits/interaction.audit.json +17 -0
- package/package.json +132 -4
- package/src/accounts/avatar.js +121 -0
- package/src/accounts/local.js +464 -0
- package/src/agent/acp/command.js +204 -0
- package/src/agent/acp/detect.js +75 -0
- package/src/agent/acp/sandbox.js +160 -0
- package/src/agent/agent-health.js +75 -0
- package/src/agent/backends/acp.js +1297 -0
- package/src/agent/backends/index.js +61 -0
- package/src/agent/backends/openai.js +308 -0
- package/src/agent/composer.js +221 -0
- package/src/agent/config.js +338 -0
- package/src/agent/context.js +191 -0
- package/src/agent/control.js +122 -0
- package/src/agent/errors.js +17 -0
- package/src/agent/feedback-loop.js +137 -0
- package/src/agent/manage.js +94 -0
- package/src/agent/next-steps.js +51 -0
- package/src/agent/owner-mcp.js +38 -0
- package/src/agent/plain-text.js +52 -0
- package/src/agent/ratings-core.js +213 -0
- package/src/agent/ratings.js +100 -0
- package/src/agent/reply-text.js +67 -0
- package/src/agent/routes.js +1065 -0
- package/src/agent/run.js +326 -0
- package/src/agent/settings-routes.js +704 -0
- package/src/agent/showable.js +23 -0
- package/src/agent/starter/approvals.js +181 -0
- package/src/agent/starter/build-image.js +90 -0
- package/src/agent/starter/cli.js +163 -0
- package/src/agent/starter/disk.js +53 -0
- package/src/agent/starter/doctor.js +180 -0
- package/src/agent/starter/egress-proxy.js +351 -0
- package/src/agent/starter/gate.js +90 -0
- package/src/agent/starter/loop.js +114 -0
- package/src/agent/starter/model-relay.js +289 -0
- package/src/agent/starter/pause.js +14 -0
- package/src/agent/starter/probe.js +272 -0
- package/src/agent/starter/prompt.js +41 -0
- package/src/agent/starter/push-guard.js +146 -0
- package/src/agent/starter/rpc.js +164 -0
- package/src/agent/starter/runtime.js +287 -0
- package/src/agent/starter/sandbox-main.js +121 -0
- package/src/agent/starter/settings.js +290 -0
- package/src/agent/starter/source.js +69 -0
- package/src/agent/starter/supervisor.js +755 -0
- package/src/agent/starter/sweep.js +46 -0
- package/src/agent/starter/tools.js +524 -0
- package/src/agent/starter/watch.js +84 -0
- package/src/agent/starter/worktree.js +409 -0
- package/src/agent/text-diff.js +210 -0
- package/src/agent/thread-history.js +223 -0
- package/src/agent/threads.js +399 -0
- package/src/agent/tools.js +200 -0
- package/src/agent/turn-changes.js +424 -0
- package/src/agent/undo-state.js +26 -0
- package/src/agent/user-settings.js +308 -0
- package/src/auth/record.js +375 -0
- package/src/broken-links.js +164 -0
- package/src/buzz/client.js +75 -0
- package/src/buzz/config.js +151 -0
- package/src/buzz/environment.js +13 -0
- package/src/buzz/gateway.js +192 -0
- package/src/buzz/routes.js +61 -0
- package/src/buzz/signer-child.js +205 -0
- package/src/buzz/store.js +89 -0
- package/src/buzz/transport.js +60 -0
- package/src/buzz/verify.js +140 -0
- package/src/capture/actions.js +159 -0
- package/src/capture/capture.js +776 -0
- package/src/capture/dom-names.js +189 -0
- package/src/capture/element-map.js +509 -0
- package/src/capture/live.js +827 -0
- package/src/capture/media-scheme.js +317 -0
- package/src/capture/network-summary.js +86 -0
- package/src/capture/pacing.js +34 -0
- package/src/capture/requests.js +167 -0
- package/src/capture/sanitize.js +752 -0
- package/src/checks/accessibility.js +134 -0
- package/src/checks/budgets.js +58 -0
- package/src/checks/cli.js +55 -0
- package/src/checks/comparison.js +113 -0
- package/src/checks/environments.js +32 -0
- package/src/checks/flow-config.js +82 -0
- package/src/checks/flow-origin.js +53 -0
- package/src/checks/flows.js +398 -0
- package/src/checks/lighthouse-auth.js +145 -0
- package/src/checks/lighthouse-findings.js +130 -0
- package/src/checks/lighthouse.js +395 -0
- package/src/checks/robots.js +85 -0
- package/src/checks/routes.js +52 -0
- package/src/checks/run-control.js +259 -0
- package/src/checks/runner.js +724 -0
- package/src/checks/schema.js +133 -0
- package/src/checks/seo-analysis.js +443 -0
- package/src/checks/seo-probe.js +190 -0
- package/src/checks/seo-snapshot.js +99 -0
- package/src/checks/store.js +214 -0
- package/src/checks/transport.js +47 -0
- package/src/cli/args.js +319 -0
- package/src/cli/capture.js +79 -0
- package/src/cli/commands.js +92 -0
- package/src/cli/comments.js +84 -0
- package/src/cli/help.js +243 -0
- package/src/cli/init.js +214 -0
- package/src/cli/misc.js +64 -0
- package/src/cli/notify.js +87 -0
- package/src/cli/open.js +22 -0
- package/src/cli/serve.js +274 -0
- package/src/cli/variant.js +82 -0
- package/src/cli/watch.js +70 -0
- package/src/cli.js +130 -0
- package/src/comment-fields.js +76 -0
- package/src/comments-cli.js +208 -0
- package/src/config-reload.js +100 -0
- package/src/config.js +1061 -0
- package/src/devices-cli.js +21 -0
- package/src/diff.js +95 -0
- package/src/discover.js +284 -0
- package/src/doctor.js +295 -0
- package/src/event-log.js +268 -0
- package/src/events-cli.js +102 -0
- package/src/events.js +113 -0
- package/src/export.js +119 -0
- package/src/feedback.js +246 -0
- package/src/github.js +551 -0
- package/src/hosted/LICENSE.md +105 -0
- package/src/hosted/access-cli.js +78 -0
- package/src/hosted/admin.js +682 -0
- package/src/hosted/agent-approvals.js +163 -0
- package/src/hosted/agent-policy.js +189 -0
- package/src/hosted/app.js +510 -0
- package/src/hosted/auth-routes.js +540 -0
- package/src/hosted/auth.js +536 -0
- package/src/hosted/backup.js +483 -0
- package/src/hosted/board-context.js +35 -0
- package/src/hosted/board-routes.js +486 -0
- package/src/hosted/board-view.js +94 -0
- package/src/hosted/clean-worker.js +24 -0
- package/src/hosted/cleaner.js +89 -0
- package/src/hosted/comments.js +355 -0
- package/src/hosted/console-routes.js +401 -0
- package/src/hosted/cookies.js +18 -0
- package/src/hosted/crypto.js +80 -0
- package/src/hosted/db.js +496 -0
- package/src/hosted/device-routes.js +175 -0
- package/src/hosted/device.js +233 -0
- package/src/hosted/events.js +63 -0
- package/src/hosted/guards.js +172 -0
- package/src/hosted/guest-view.js +65 -0
- package/src/hosted/http.js +39 -0
- package/src/hosted/import.js +300 -0
- package/src/hosted/mail.js +73 -0
- package/src/hosted/mcp-http.js +71 -0
- package/src/hosted/membership.js +114 -0
- package/src/hosted/operator.js +478 -0
- package/src/hosted/ops-cli.js +345 -0
- package/src/hosted/pages.js +146 -0
- package/src/hosted/permissions.js +113 -0
- package/src/hosted/presence.js +372 -0
- package/src/hosted/projects.js +124 -0
- package/src/hosted/public.js +109 -0
- package/src/hosted/push.js +622 -0
- package/src/hosted/quotas.js +115 -0
- package/src/hosted/ratelimit.js +96 -0
- package/src/hosted/rebind.js +316 -0
- package/src/hosted/retention.js +128 -0
- package/src/hosted/server.js +260 -0
- package/src/hosted/setup-link.js +64 -0
- package/src/hosted/setup.js +323 -0
- package/src/hosted/shares.js +444 -0
- package/src/hosted/tailscale.js +204 -0
- package/src/hosted/tenancy.js +301 -0
- package/src/hosted/token-api.js +455 -0
- package/src/hosted/token-events.js +60 -0
- package/src/hosted/tokens.js +57 -0
- package/src/hosted/turnstile.js +49 -0
- package/src/hosted/usercontent.js +154 -0
- package/src/hosted/zip.js +155 -0
- package/src/invocation.js +58 -0
- package/src/journey-paths.js +282 -0
- package/src/journeys.js +189 -0
- package/src/links.js +106 -0
- package/src/local-projects.js +182 -0
- package/src/lock.js +193 -0
- package/src/mcp.js +417 -0
- package/src/mentions.js +151 -0
- package/src/net.js +15 -0
- package/src/notify/config.js +275 -0
- package/src/notify/index.js +301 -0
- package/src/notify/lease.js +73 -0
- package/src/notify/messages.js +212 -0
- package/src/notify/run.js +174 -0
- package/src/pixeldiff.js +49 -0
- package/src/png.js +143 -0
- package/src/reactions.js +111 -0
- package/src/remote/cli.js +133 -0
- package/src/remote/credentials.js +62 -0
- package/src/remote/ids.js +12 -0
- package/src/remote/login.js +155 -0
- package/src/remote/remote-mcp.js +237 -0
- package/src/remote/remote-watch.js +291 -0
- package/src/remote/remote.js +313 -0
- package/src/remote/share-state.js +78 -0
- package/src/remote/share.js +369 -0
- package/src/remote/terminal.js +13 -0
- package/src/serve-state.js +64 -0
- package/src/server/app.js +824 -0
- package/src/server/devices.js +186 -0
- package/src/server/local-console.js +28 -0
- package/src/server/local-user.js +59 -0
- package/src/server/pairing-routes.js +159 -0
- package/src/server/share-routes.js +89 -0
- package/src/server/tailscale.js +97 -0
- package/src/sitemap.js +431 -0
- package/src/store.js +983 -0
- package/src/tokens.js +11 -0
- package/src/update/routes.js +245 -0
- package/src/watch.js +403 -0
- package/src/which.js +58 -0
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
// What a notification says, per channel type. Every message links back to
|
|
2
|
+
// the comment on the board. Comment text is data: it is escaped for each
|
|
3
|
+
// format, and only people mapped in `notifications.people` are ever pinged
|
|
4
|
+
// (no @channel, @here or @everyone from a comment).
|
|
5
|
+
|
|
6
|
+
import { splitMentions } from '../mentions.js'
|
|
7
|
+
import { DEFAULT_BOARD_URL, runningBoardUrl } from '../serve-state.js'
|
|
8
|
+
import { boardViewports } from '../config.js'
|
|
9
|
+
|
|
10
|
+
const QUOTE_MAX = 500
|
|
11
|
+
|
|
12
|
+
// Where links in messages point: $SHAPEWALL_BOARD_URL, the config
|
|
13
|
+
// (notifications.boardUrl, then boardUrl), this server's own address, a
|
|
14
|
+
// `shapewall serve` running for this config, and only then the default port.
|
|
15
|
+
export function boardUrlFor(config, { boardUrl = null, env = process.env } = {}) {
|
|
16
|
+
return (
|
|
17
|
+
env.SHAPEWALL_BOARD_URL || config.notifications?.boardUrl || config.boardUrl || boardUrl || runningBoardUrl(config) || DEFAULT_BOARD_URL
|
|
18
|
+
)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// The board, scrolled to the comment and with its thread open: ?board=&c=,
|
|
22
|
+
// every state shown (so a resolved one is visible) and the comment's viewport.
|
|
23
|
+
export function commentLink(config, boardUrl, boardId, comment) {
|
|
24
|
+
const url = new URL(boardUrl)
|
|
25
|
+
url.searchParams.set('board', boardId)
|
|
26
|
+
if (comment?.id) {
|
|
27
|
+
url.searchParams.set('c', String(comment.id))
|
|
28
|
+
url.searchParams.set('filter', 'all')
|
|
29
|
+
const board = config.boards?.find((item) => item.id === boardId)
|
|
30
|
+
const first = Object.keys(boardViewports(config, board))[0]
|
|
31
|
+
if (comment.viewport && comment.viewport !== first) url.searchParams.set('vp', comment.viewport)
|
|
32
|
+
}
|
|
33
|
+
url.hash = ''
|
|
34
|
+
return url.toString()
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const clip = (value, max = QUOTE_MAX) => {
|
|
38
|
+
const textValue = String(value || '').trim()
|
|
39
|
+
return textValue.length > max ? `${textValue.slice(0, max - 3).trimEnd()}...` : textValue
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function pageTitle(config, boardId, pageId) {
|
|
43
|
+
const board = config.boards.find((item) => item.id === boardId)
|
|
44
|
+
const page = board?.pages.find((item) => item.id === pageId)
|
|
45
|
+
return page?.title || String(pageId || '').replace(/^variant:/, '') || 'a page'
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// The parts every format shares: { title, quote, link, board, page, mentionsIn }.
|
|
49
|
+
export function summarize(config, event, boardUrl) {
|
|
50
|
+
const board = config.boards.find((item) => item.id === event.boardId)
|
|
51
|
+
const comment = event.comment || {}
|
|
52
|
+
const page = pageTitle(config, event.boardId, comment.pageId)
|
|
53
|
+
const where = `${page}${comment.viewport ? ` (${comment.viewport})` : ''}`
|
|
54
|
+
const who = (name) => clip(name || 'Someone', 60)
|
|
55
|
+
const n = `#${comment.id}`
|
|
56
|
+
let title
|
|
57
|
+
let quote = comment.body
|
|
58
|
+
switch (event.type) {
|
|
59
|
+
case 'comment.created':
|
|
60
|
+
title = `${who(comment.author)} commented on ${where}`
|
|
61
|
+
break
|
|
62
|
+
case 'comment.replied':
|
|
63
|
+
title = `${who(event.reply?.author)} replied to ${n} on ${where}`
|
|
64
|
+
quote = event.reply?.body
|
|
65
|
+
break
|
|
66
|
+
case 'comment.mentioned':
|
|
67
|
+
title = `@${event.handle}, you were mentioned on ${n}, ${where}`
|
|
68
|
+
quote = event.reply ? event.reply.body : comment.body
|
|
69
|
+
break
|
|
70
|
+
case 'comment.status_changed':
|
|
71
|
+
title = `Agent status of ${n} on ${where}: ${event.previous?.agentStatus || 'none'} -> ${event.agentStatus || 'none'}`
|
|
72
|
+
break
|
|
73
|
+
case 'comment.resolved':
|
|
74
|
+
title = `${n} on ${where} was resolved`
|
|
75
|
+
if (comment.resolution) quote = `${comment.body}\n\nResolution: ${comment.resolution}`
|
|
76
|
+
if (comment.fixRef) quote = `${quote}\nFix: ${comment.fixRef}`
|
|
77
|
+
break
|
|
78
|
+
case 'comment.reopened':
|
|
79
|
+
title = `${n} on ${where} was reopened`
|
|
80
|
+
break
|
|
81
|
+
default:
|
|
82
|
+
title = 'Shapewall test message: notifications reach this channel'
|
|
83
|
+
quote = 'Sent by "shapewall notify test". Nothing happened on the board.'
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
title,
|
|
87
|
+
quote: clip(quote),
|
|
88
|
+
link: commentLink(config, boardUrl, event.boardId || board?.id || config.boards[0].id, event.comment),
|
|
89
|
+
board: { id: board?.id || null, title: board?.title || null },
|
|
90
|
+
page,
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ---- Slack (incoming webhook, mrkdwn) ------------------------------------------
|
|
95
|
+
|
|
96
|
+
const slackEscape = (value) => String(value).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
97
|
+
|
|
98
|
+
// @handle -> <@U123> for mapped people; everything else escaped, so a comment
|
|
99
|
+
// can never write <!channel> or a link of its own.
|
|
100
|
+
function slackText(value, people) {
|
|
101
|
+
return splitMentions(value)
|
|
102
|
+
.map((part) => (part.handle && people[part.handle]?.slack ? `<@${people[part.handle].slack}>` : slackEscape(part.text)))
|
|
103
|
+
.join('')
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function slackMessage(config, event, boardUrl) {
|
|
107
|
+
const people = config.notifications?.people || {}
|
|
108
|
+
const summary = summarize(config, event, boardUrl)
|
|
109
|
+
const ping = event.type === 'comment.mentioned' && people[event.handle]?.slack ? `<@${people[event.handle].slack}> ` : ''
|
|
110
|
+
const quote = summary.quote ? `\n${slackText(summary.quote, people).replace(/^/gm, '>')}` : ''
|
|
111
|
+
const text = `${ping}*${slackEscape(summary.title)}*${quote}\n<${summary.link}|Open on the board>`
|
|
112
|
+
return { text, unfurl_links: false, unfurl_media: false }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ---- Discord (webhook) -------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
// Markdown characters escaped; pings limited to mapped people by allowed_mentions.
|
|
118
|
+
const discordEscape = (value) => String(value).replace(/([\\*_~`|<>[\]])/g, '\\$1')
|
|
119
|
+
|
|
120
|
+
export function discordMessage(config, event, boardUrl) {
|
|
121
|
+
const people = config.notifications?.people || {}
|
|
122
|
+
const summary = summarize(config, event, boardUrl)
|
|
123
|
+
const users = new Set()
|
|
124
|
+
const textOf = (value) =>
|
|
125
|
+
splitMentions(value)
|
|
126
|
+
.map((part) => {
|
|
127
|
+
const id = part.handle && people[part.handle]?.discord
|
|
128
|
+
if (!id) return discordEscape(part.text).replace(/@/g, '@\u200b')
|
|
129
|
+
users.add(id)
|
|
130
|
+
return `<@${id}>`
|
|
131
|
+
})
|
|
132
|
+
.join('')
|
|
133
|
+
let ping = ''
|
|
134
|
+
if (event.type === 'comment.mentioned' && people[event.handle]?.discord) {
|
|
135
|
+
users.add(people[event.handle].discord)
|
|
136
|
+
ping = `<@${people[event.handle].discord}> `
|
|
137
|
+
}
|
|
138
|
+
const quote = summary.quote ? `\n${textOf(summary.quote).replace(/^/gm, '> ')}` : ''
|
|
139
|
+
const content = `${ping}**${discordEscape(summary.title).replace(/@/g, '@\u200b')}**${quote}\n[Open on the board](${summary.link})`
|
|
140
|
+
return { content: content.slice(0, 2000), allowed_mentions: { parse: [], users: [...users].slice(0, 100) } }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ---- Email (Resend) ----------------------------------------------------------------
|
|
144
|
+
|
|
145
|
+
const htmlEscape = (value) =>
|
|
146
|
+
String(value).replace(/[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char])
|
|
147
|
+
|
|
148
|
+
// Who gets it: the mentioned person (if mapped to an email) for a mention,
|
|
149
|
+
// the channel's `to` list for anything else.
|
|
150
|
+
export function emailRecipients(config, channel, event) {
|
|
151
|
+
if (event.type === 'comment.mentioned') {
|
|
152
|
+
const email = config.notifications?.people?.[event.handle]?.email
|
|
153
|
+
return email ? [email] : []
|
|
154
|
+
}
|
|
155
|
+
return channel.to || []
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function emailMessage(config, channel, event, boardUrl, to) {
|
|
159
|
+
const summary = summarize(config, event, boardUrl)
|
|
160
|
+
const subject = `[Shapewall] ${summary.title}`.replace(/[\r\n]+/g, ' ').slice(0, 200)
|
|
161
|
+
const text = `${summary.title}\n\n${summary.quote ? `${summary.quote}\n\n` : ''}Open on the board: ${summary.link}\n`
|
|
162
|
+
const html = [
|
|
163
|
+
`<p><strong>${htmlEscape(summary.title)}</strong></p>`,
|
|
164
|
+
summary.quote
|
|
165
|
+
? `<blockquote style="margin:0 0 16px;padding-left:12px;border-left:3px solid #ccc">${htmlEscape(summary.quote).replace(/\n/g, '<br>')}</blockquote>`
|
|
166
|
+
: '',
|
|
167
|
+
`<p><a href="${htmlEscape(summary.link)}">Open on the board</a></p>`,
|
|
168
|
+
].join('')
|
|
169
|
+
return { from: channel.from, to, subject, text, html }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// ---- Generic webhook (JSON) --------------------------------------------------------
|
|
173
|
+
|
|
174
|
+
// The event without anything internal: no anchors or file paths, and people
|
|
175
|
+
// by handle only (never their email or chat ids).
|
|
176
|
+
export function webhookPayload(config, event, boardUrl) {
|
|
177
|
+
const summary = summarize(config, event, boardUrl)
|
|
178
|
+
const comment = event.comment
|
|
179
|
+
const payload = {
|
|
180
|
+
id: event.id,
|
|
181
|
+
type: event.type,
|
|
182
|
+
at: event.at,
|
|
183
|
+
board: summary.board,
|
|
184
|
+
text: summary.title,
|
|
185
|
+
url: summary.link,
|
|
186
|
+
}
|
|
187
|
+
if (comment) {
|
|
188
|
+
payload.comment = {
|
|
189
|
+
id: comment.id,
|
|
190
|
+
pageId: comment.pageId,
|
|
191
|
+
pageTitle: summary.page,
|
|
192
|
+
viewport: comment.viewport,
|
|
193
|
+
author: comment.author || null,
|
|
194
|
+
body: comment.body,
|
|
195
|
+
status: comment.status,
|
|
196
|
+
agentStatus: comment.agentStatus ?? null,
|
|
197
|
+
mentions: comment.mentions || [],
|
|
198
|
+
// Events read back from the shared log carry a count instead of the thread.
|
|
199
|
+
replyCount: Array.isArray(comment.replies) ? comment.replies.length : Number(comment.replyCount) || 0,
|
|
200
|
+
resolution: comment.resolution ?? null,
|
|
201
|
+
fixRef: comment.fixRef ?? null,
|
|
202
|
+
createdAt: comment.createdAt,
|
|
203
|
+
updatedAt: comment.updatedAt,
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (event.reply)
|
|
207
|
+
payload.reply = { id: event.reply.id, author: event.reply.author, body: event.reply.body, createdAt: event.reply.createdAt }
|
|
208
|
+
if (event.handle) payload.handle = event.handle
|
|
209
|
+
if (event.previous) payload.previous = event.previous
|
|
210
|
+
if (event.actor !== undefined) payload.actor = event.actor
|
|
211
|
+
return payload
|
|
212
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// Who sends a notification: exactly one process per change.
|
|
2
|
+
//
|
|
3
|
+
// - `shapewall serve` is the notifier while it runs. It holds the lease
|
|
4
|
+
// (lease.js), reads the shared event log (src/event-log.js) and sends every
|
|
5
|
+
// change made from then on, whichever process made it: the board, `comments
|
|
6
|
+
// resolve` in another shell, `watch`, MCP, the starter agent. Its own
|
|
7
|
+
// environment (webhook secrets, API keys) is what counts. It starts at the
|
|
8
|
+
// end of the log, so nothing old is sent again when it restarts.
|
|
9
|
+
// - Any other process (and a server that does not hold the lease) sends only
|
|
10
|
+
// its own changes, and only those no live server lease covers: the same as
|
|
11
|
+
// before when no server runs, nothing twice when one does.
|
|
12
|
+
// - An event whose line could not be written to the log is always sent by
|
|
13
|
+
// the process that made it, so nothing is lost to a full disk.
|
|
14
|
+
// - A server that stalls (a blocked event loop, a suspended laptop) past
|
|
15
|
+
// LEASE_STALE_MS looks gone to the others, and they send their own
|
|
16
|
+
// changes. When it wakes, it skips the events from that gap: it sends a
|
|
17
|
+
// record only when one of its own heartbeats was fresh at the record's
|
|
18
|
+
// time (ownedAt), the same test the others made.
|
|
19
|
+
// - Left: a server killed with SIGKILL (or a crash) cannot release the lease
|
|
20
|
+
// or drain the log. Events written after its last read are sent by nobody
|
|
21
|
+
// until the lease is stale (up to LEASE_STALE_MS); others then send their
|
|
22
|
+
// own changes again. A clean stop drains the log once before releasing.
|
|
23
|
+
|
|
24
|
+
import { onCommentEvent } from '../events.js'
|
|
25
|
+
import { LOGGED, followEventLog, recordEvent } from '../event-log.js'
|
|
26
|
+
import { HEARTBEAT_MS, LEASE_STALE_MS, acquireLease, heartbeat, leaseCovers, liveLease, releaseLease } from './lease.js'
|
|
27
|
+
import { createNotifier } from './index.js'
|
|
28
|
+
|
|
29
|
+
// startNotifications(config, options) -> null (no channels) or
|
|
30
|
+
// { channels, notifier, holdsLease(), drain(), flush(ms), close(ms), stop() }.
|
|
31
|
+
// Options: serve (try to be the server notifier), log, boardUrl, env, fetch,
|
|
32
|
+
// backoffMs, pollMs (log poll), heartbeatMs, staleMs.
|
|
33
|
+
export function startNotifications(
|
|
34
|
+
config,
|
|
35
|
+
{
|
|
36
|
+
serve = false,
|
|
37
|
+
log = () => {},
|
|
38
|
+
boardUrl = null,
|
|
39
|
+
env,
|
|
40
|
+
fetch,
|
|
41
|
+
backoffMs,
|
|
42
|
+
timeoutMs,
|
|
43
|
+
pollMs = 1000,
|
|
44
|
+
heartbeatMs = HEARTBEAT_MS,
|
|
45
|
+
staleMs = LEASE_STALE_MS,
|
|
46
|
+
} = {},
|
|
47
|
+
) {
|
|
48
|
+
if (!config.notifications?.channels.length) return null
|
|
49
|
+
const notifier = createNotifier(config, { log, boardUrl, env, fetch, backoffMs, timeoutMs })
|
|
50
|
+
let lease = null
|
|
51
|
+
let follower = null
|
|
52
|
+
let timer = null
|
|
53
|
+
// The times this server's heartbeats were written (the lease's start
|
|
54
|
+
// first), newest last; about an hour of them.
|
|
55
|
+
let beats = []
|
|
56
|
+
const BEATS_MAX = 400
|
|
57
|
+
|
|
58
|
+
// True when the lease was fresh at `at` to the other processes: a beat at
|
|
59
|
+
// or before it, less than staleMs earlier.
|
|
60
|
+
function ownedAt(at) {
|
|
61
|
+
const time = Date.parse(at || '')
|
|
62
|
+
if (!Number.isFinite(time)) return false
|
|
63
|
+
for (let index = beats.length - 1; index >= 0; index -= 1) {
|
|
64
|
+
if (beats[index] <= time) return time - beats[index] < staleMs
|
|
65
|
+
}
|
|
66
|
+
return false
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// This process's own changes: sent here unless a live server sends them.
|
|
70
|
+
const unsubscribe = onCommentEvent((event) => {
|
|
71
|
+
if (event[LOGGED]) {
|
|
72
|
+
const live = liveLease(config)
|
|
73
|
+
if (live && leaseCovers(live, event)) return
|
|
74
|
+
}
|
|
75
|
+
notifier.handle(event)
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
// The follower starts at the end of the log before the lease is taken, so
|
|
79
|
+
// every event at or after lease.startedAt is past its starting point.
|
|
80
|
+
function take() {
|
|
81
|
+
const next = followEventLog(config, {
|
|
82
|
+
from: 'end',
|
|
83
|
+
pollMs,
|
|
84
|
+
onRecord: (record) => {
|
|
85
|
+
if (lease && leaseCovers(lease, record) && ownedAt(record.at)) notifier.handle(recordEvent(record))
|
|
86
|
+
},
|
|
87
|
+
})
|
|
88
|
+
let held
|
|
89
|
+
try {
|
|
90
|
+
held = acquireLease(config)
|
|
91
|
+
} catch (error) {
|
|
92
|
+
next.stop()
|
|
93
|
+
throw error
|
|
94
|
+
}
|
|
95
|
+
if (!held) {
|
|
96
|
+
next.stop()
|
|
97
|
+
return false
|
|
98
|
+
}
|
|
99
|
+
lease = held
|
|
100
|
+
beats = [Date.parse(held.startedAt)]
|
|
101
|
+
follower = next
|
|
102
|
+
log(`notify: this server sends the notifications for ${config.outputDir} (changes from any process)`)
|
|
103
|
+
return true
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (serve) {
|
|
107
|
+
take()
|
|
108
|
+
if (!lease) {
|
|
109
|
+
const other = liveLease(config)
|
|
110
|
+
if (other) log(`notify: another shapewall serve (pid ${other.pid}) sends the notifications for this output folder`)
|
|
111
|
+
}
|
|
112
|
+
timer = setInterval(() => {
|
|
113
|
+
// A throw here (the lease file, the disk) would be uncaught in a timer: log it, try again next beat.
|
|
114
|
+
try {
|
|
115
|
+
if (lease) {
|
|
116
|
+
const now = new Date()
|
|
117
|
+
const last = beats.at(-1)
|
|
118
|
+
if (heartbeat(config, lease, now)) {
|
|
119
|
+
if (now.getTime() - last >= staleMs) {
|
|
120
|
+
log('notify: this server stalled; changes made meanwhile were sent by the processes that made them')
|
|
121
|
+
}
|
|
122
|
+
beats.push(now.getTime())
|
|
123
|
+
if (beats.length > BEATS_MAX) beats = beats.slice(-BEATS_MAX)
|
|
124
|
+
return
|
|
125
|
+
}
|
|
126
|
+
// Lost it (removed by hand, or taken over): fall back to own changes.
|
|
127
|
+
follower?.stop()
|
|
128
|
+
follower = null
|
|
129
|
+
lease = null
|
|
130
|
+
log("notify: lost the notifier lease; sending only this server's own changes")
|
|
131
|
+
}
|
|
132
|
+
take()
|
|
133
|
+
} catch (error) {
|
|
134
|
+
log(`notify: the lease check failed (${error.message}); trying again`)
|
|
135
|
+
}
|
|
136
|
+
}, heartbeatMs)
|
|
137
|
+
timer.unref?.()
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
channels: notifier.channels,
|
|
142
|
+
notifier,
|
|
143
|
+
holdsLease: () => Boolean(lease),
|
|
144
|
+
// Reads what is new in the log now (tests; the follower also does it by itself).
|
|
145
|
+
drain: () => follower?.drain(),
|
|
146
|
+
flush: (ms) => {
|
|
147
|
+
follower?.drain()
|
|
148
|
+
return notifier.flush(ms)
|
|
149
|
+
},
|
|
150
|
+
// Hands over cleanly: reads the log once more (what other processes
|
|
151
|
+
// wrote since the last poll is still this server's), releases the lease
|
|
152
|
+
// so they send their own changes from now on, then gives the queued
|
|
153
|
+
// messages up to `ms` before stopping.
|
|
154
|
+
async close(ms = 1500) {
|
|
155
|
+
release()
|
|
156
|
+
await notifier.flush(ms)
|
|
157
|
+
notifier.stop()
|
|
158
|
+
},
|
|
159
|
+
stop() {
|
|
160
|
+
release()
|
|
161
|
+
notifier.stop()
|
|
162
|
+
},
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function release() {
|
|
166
|
+
clearInterval(timer)
|
|
167
|
+
unsubscribe()
|
|
168
|
+
if (lease) follower?.drain()
|
|
169
|
+
follower?.stop()
|
|
170
|
+
follower = null
|
|
171
|
+
if (lease) releaseLease(config)
|
|
172
|
+
lease = null
|
|
173
|
+
}
|
|
174
|
+
}
|
package/src/pixeldiff.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// The pixel diff itself, on raw RGBA pixels: no Node APIs, so the server
|
|
2
|
+
// (compare mode, src/diff.js) and the board client (page history, in a
|
|
3
|
+
// canvas) draw exactly the same red mask.
|
|
4
|
+
|
|
5
|
+
import pixelmatch from 'pixelmatch'
|
|
6
|
+
|
|
7
|
+
// Per-pixel color distance (0-1) below which pixels count as the same;
|
|
8
|
+
// anti-aliased edges are ignored too.
|
|
9
|
+
export const DIFF_THRESHOLD = 0.1
|
|
10
|
+
export const DIFF_COLOR = [239, 68, 68]
|
|
11
|
+
|
|
12
|
+
// Compares two images ({ width, height, data } with RGBA bytes). Different
|
|
13
|
+
// sizes are compared over the shared area; the rest counts as changed.
|
|
14
|
+
// Returns { width, height, changed, total, percent, data } where data is the
|
|
15
|
+
// mask (red where changed, transparent elsewhere) at the larger size.
|
|
16
|
+
export function diffPixels(a, b, { threshold = DIFF_THRESHOLD } = {}) {
|
|
17
|
+
const width = Math.max(a.width, b.width)
|
|
18
|
+
const height = Math.max(a.height, b.height)
|
|
19
|
+
const shared = { width: Math.min(a.width, b.width), height: Math.min(a.height, b.height) }
|
|
20
|
+
const crop = (image) => {
|
|
21
|
+
if (image.width === shared.width && image.height === shared.height) return image.data
|
|
22
|
+
const out = new Uint8Array(shared.width * shared.height * 4)
|
|
23
|
+
for (let y = 0; y < shared.height; y += 1)
|
|
24
|
+
out.set(image.data.subarray(y * image.width * 4, (y * image.width + shared.width) * 4), y * shared.width * 4)
|
|
25
|
+
return out
|
|
26
|
+
}
|
|
27
|
+
const data = new Uint8Array(width * height * 4)
|
|
28
|
+
const sharedMask = new Uint8Array(shared.width * shared.height * 4)
|
|
29
|
+
let changed = pixelmatch(crop(a), crop(b), sharedMask, shared.width, shared.height, {
|
|
30
|
+
threshold,
|
|
31
|
+
diffMask: true,
|
|
32
|
+
diffColor: DIFF_COLOR,
|
|
33
|
+
alpha: 0,
|
|
34
|
+
})
|
|
35
|
+
for (let y = 0; y < shared.height; y += 1) data.set(sharedMask.subarray(y * shared.width * 4, (y + 1) * shared.width * 4), y * width * 4)
|
|
36
|
+
// Area only one image has.
|
|
37
|
+
for (let y = 0; y < height; y += 1) {
|
|
38
|
+
for (let x = y < shared.height ? shared.width : 0; x < width; x += 1) {
|
|
39
|
+
const offset = (y * width + x) * 4
|
|
40
|
+
data[offset] = DIFF_COLOR[0]
|
|
41
|
+
data[offset + 1] = DIFF_COLOR[1]
|
|
42
|
+
data[offset + 2] = DIFF_COLOR[2]
|
|
43
|
+
data[offset + 3] = 255
|
|
44
|
+
changed += 1
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const total = width * height
|
|
48
|
+
return { width, height, changed, total, percent: total ? Math.round((changed / total) * 10000) / 100 : 0, data }
|
|
49
|
+
}
|
package/src/png.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// A small PNG reader and writer, enough to crop a capture around a comment
|
|
2
|
+
// pin for the MCP server without an image library. Handles what Chromium
|
|
3
|
+
// writes: 8-bit gray, gray + alpha, RGB and RGBA, not interlaced.
|
|
4
|
+
|
|
5
|
+
import zlib from 'node:zlib'
|
|
6
|
+
|
|
7
|
+
const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
|
|
8
|
+
const CHANNELS = { 0: 1, 2: 3, 4: 2, 6: 4 }
|
|
9
|
+
|
|
10
|
+
const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
|
|
11
|
+
let c = n
|
|
12
|
+
for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
|
|
13
|
+
return c >>> 0
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
function crc32(buffer) {
|
|
17
|
+
let crc = 0xffffffff
|
|
18
|
+
for (const byte of buffer) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8)
|
|
19
|
+
return (crc ^ 0xffffffff) >>> 0
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function chunk(type, data) {
|
|
23
|
+
const head = Buffer.alloc(8)
|
|
24
|
+
head.writeUInt32BE(data.length, 0)
|
|
25
|
+
head.write(type, 4, 'latin1')
|
|
26
|
+
const crc = Buffer.alloc(4)
|
|
27
|
+
crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])), 0)
|
|
28
|
+
return Buffer.concat([head, data, crc])
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const paeth = (a, b, c) => {
|
|
32
|
+
const p = a + b - c
|
|
33
|
+
const pa = Math.abs(p - a)
|
|
34
|
+
const pb = Math.abs(p - b)
|
|
35
|
+
const pc = Math.abs(p - c)
|
|
36
|
+
return pa <= pb && pa <= pc ? a : pb <= pc ? b : c
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Returns { width, height, channels, colorType, pixels } (rows of raw bytes).
|
|
40
|
+
export function decodePng(buffer) {
|
|
41
|
+
if (!Buffer.isBuffer(buffer) || buffer.length < 33 || !buffer.subarray(0, 8).equals(SIGNATURE)) throw new Error('not a PNG')
|
|
42
|
+
let offset = 8
|
|
43
|
+
let header = null
|
|
44
|
+
const data = []
|
|
45
|
+
while (offset + 8 <= buffer.length) {
|
|
46
|
+
const length = buffer.readUInt32BE(offset)
|
|
47
|
+
const type = buffer.toString('latin1', offset + 4, offset + 8)
|
|
48
|
+
const body = buffer.subarray(offset + 8, offset + 8 + length)
|
|
49
|
+
offset += 12 + length
|
|
50
|
+
if (type === 'IHDR') {
|
|
51
|
+
header = {
|
|
52
|
+
width: body.readUInt32BE(0),
|
|
53
|
+
height: body.readUInt32BE(4),
|
|
54
|
+
bitDepth: body[8],
|
|
55
|
+
colorType: body[9],
|
|
56
|
+
interlace: body[12],
|
|
57
|
+
}
|
|
58
|
+
} else if (type === 'IDAT') data.push(body)
|
|
59
|
+
else if (type === 'IEND') break
|
|
60
|
+
}
|
|
61
|
+
if (!header) throw new Error('PNG without a header')
|
|
62
|
+
const channels = CHANNELS[header.colorType]
|
|
63
|
+
if (header.bitDepth !== 8 || !channels || header.interlace !== 0) throw new Error('unsupported PNG format')
|
|
64
|
+
if (header.width > 20000 || header.height > 40000) throw new Error('PNG too large')
|
|
65
|
+
const raw = zlib.inflateSync(Buffer.concat(data))
|
|
66
|
+
const stride = header.width * channels
|
|
67
|
+
if (raw.length < (stride + 1) * header.height) throw new Error('truncated PNG')
|
|
68
|
+
const pixels = Buffer.alloc(stride * header.height)
|
|
69
|
+
for (let y = 0; y < header.height; y += 1) {
|
|
70
|
+
const filter = raw[y * (stride + 1)]
|
|
71
|
+
const src = y * (stride + 1) + 1
|
|
72
|
+
const row = y * stride
|
|
73
|
+
for (let x = 0; x < stride; x += 1) {
|
|
74
|
+
const a = x >= channels ? pixels[row + x - channels] : 0
|
|
75
|
+
const b = y > 0 ? pixels[row - stride + x] : 0
|
|
76
|
+
const c = x >= channels && y > 0 ? pixels[row - stride + x - channels] : 0
|
|
77
|
+
const value = raw[src + x]
|
|
78
|
+
let out
|
|
79
|
+
if (filter === 0) out = value
|
|
80
|
+
else if (filter === 1) out = value + a
|
|
81
|
+
else if (filter === 2) out = value + b
|
|
82
|
+
else if (filter === 3) out = value + ((a + b) >> 1)
|
|
83
|
+
else if (filter === 4) out = value + paeth(a, b, c)
|
|
84
|
+
else throw new Error('bad PNG filter')
|
|
85
|
+
pixels[row + x] = out & 0xff
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return { width: header.width, height: header.height, channels, colorType: header.colorType, pixels }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function encodePng({ width, height, channels, colorType, pixels }) {
|
|
92
|
+
const stride = width * channels
|
|
93
|
+
const raw = Buffer.alloc((stride + 1) * height)
|
|
94
|
+
for (let y = 0; y < height; y += 1) {
|
|
95
|
+
// Filter "up" (2) compresses screenshots well and is simple.
|
|
96
|
+
raw[y * (stride + 1)] = y > 0 ? 2 : 0
|
|
97
|
+
for (let x = 0; x < stride; x += 1) {
|
|
98
|
+
const value = pixels[y * stride + x]
|
|
99
|
+
raw[y * (stride + 1) + 1 + x] = y > 0 ? (value - pixels[(y - 1) * stride + x]) & 0xff : value
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const ihdr = Buffer.alloc(13)
|
|
103
|
+
ihdr.writeUInt32BE(width, 0)
|
|
104
|
+
ihdr.writeUInt32BE(height, 4)
|
|
105
|
+
ihdr[8] = 8
|
|
106
|
+
ihdr[9] = colorType
|
|
107
|
+
return Buffer.concat([SIGNATURE, chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))])
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Crops to the rectangle (clamped to the image). Returns a PNG buffer.
|
|
111
|
+
export function cropPng(buffer, rect) {
|
|
112
|
+
return cropImage(decodePng(buffer), rect)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function cropImage(image, { x, y, width, height }) {
|
|
116
|
+
const left = Math.max(0, Math.min(image.width - 1, Math.round(x)))
|
|
117
|
+
const top = Math.max(0, Math.min(image.height - 1, Math.round(y)))
|
|
118
|
+
const w = Math.max(1, Math.min(image.width - left, Math.round(width)))
|
|
119
|
+
const h = Math.max(1, Math.min(image.height - top, Math.round(height)))
|
|
120
|
+
const stride = image.width * image.channels
|
|
121
|
+
const out = Buffer.alloc(w * h * image.channels)
|
|
122
|
+
for (let row = 0; row < h; row += 1) {
|
|
123
|
+
const start = (top + row) * stride + left * image.channels
|
|
124
|
+
image.pixels.copy(out, row * w * image.channels, start, start + w * image.channels)
|
|
125
|
+
}
|
|
126
|
+
return { png: encodePng({ ...image, width: w, height: h, pixels: out }), rect: { x: left, y: top, width: w, height: h } }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// The part of a capture around a point: up to `width` x `height`, the point
|
|
130
|
+
// as central as the edges allow.
|
|
131
|
+
export function cropAround(buffer, point, size) {
|
|
132
|
+
const image = decodePng(buffer)
|
|
133
|
+
return cropImage(image, aroundRect(point, image, size))
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// The rectangle cropAround cuts from an image of `image.width` x `image.height`.
|
|
137
|
+
export function aroundRect({ x, y }, image, { width = 900, height = 700 } = {}) {
|
|
138
|
+
const w = Math.min(width, image.width)
|
|
139
|
+
const h = Math.min(height, image.height)
|
|
140
|
+
const left = Math.max(0, Math.min(image.width - w, Math.round(x - w / 2)))
|
|
141
|
+
const top = Math.max(0, Math.min(image.height - h, Math.round(y - h / 2)))
|
|
142
|
+
return { x: left, y: top, width: w, height: h }
|
|
143
|
+
}
|