@hybridlabor-api/aos 4.0.2 → 4.2.0-beta.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.
- package/.agents/agents.md +77 -0
- package/.agents/graph.md +43 -0
- package/.agents/state.schema.json +6 -0
- package/.claude/agents/database-reviewer.md +109 -0
- package/.claude/agents/go-build-resolver.md +112 -0
- package/.claude/agents/opensource-forker.md +216 -0
- package/.claude/agents/opensource-sanitizer.md +206 -0
- package/.claude/agents/security-reviewer.md +126 -0
- package/.claude/agents/silent-failure-hunter.md +68 -0
- package/.claude/workflows/startcycle-dispatch.mjs +126 -8
- package/CLAUDE.md +62 -0
- package/GEMINI.md +9 -1
- package/README.md +12 -19
- package/THIRD_PARTY_NOTICES.md +133 -0
- package/package.json +4 -2
- package/skills/basic/bdbmediastorm/SKILL.md +7 -1
- package/skills/basic/startcycle/SKILL.md +21 -0
- package/skills/basic/startcycle-graph/SKILL.md +27 -7
- package/skills/basic/startcycle-graph-user/SKILL.md +65 -11
- package/skills/bdbrainstorm/SKILL.md +1 -0
- package/skills/global_config/plan-canvas/SKILL.md +233 -0
- package/skills/global_config/plan-canvas/scripts/lib/loopback-guard.js +59 -0
- package/skills/global_config/plan-canvas/scripts/lib/plan-canvas/markdown.js +301 -0
- package/skills/global_config/plan-canvas/scripts/lib/plan-canvas/sdk.js +239 -0
- package/skills/global_config/plan-canvas/scripts/lib/plan-canvas/server.js +636 -0
- package/skills/global_config/plan-canvas/scripts/lib/plan-canvas/sessions.js +271 -0
- package/skills/global_config/plan-canvas/scripts/lib/plan-canvas/ui.js +630 -0
- package/skills/global_config/plan-canvas/scripts/plan-canvas.js +419 -0
- package/docs/sessions/AUDIT-HANDOVER-2026-08-28.md +0 -169
- package/docs/sessions/BDB_REMOTEOS_MCP_HANDOVER.md +0 -130
- package/docs/sessions/SESSION-HANDOVER-v3.13.md +0 -249
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: plan-canvas
|
|
3
|
+
description: Open plans and HTML artifacts in a local browser canvas where the human annotates elements, chats, and approves or requests changes without leaving the page. Use when presenting a plan for review, or when feedback like "move this, change that" is easier pointed at than typed.
|
|
4
|
+
category: bdb-core
|
|
5
|
+
metadata:
|
|
6
|
+
version: "1.0.0"
|
|
7
|
+
origin: affaan-m/ECC
|
|
8
|
+
license: MIT
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
<!-- Source: affaan-m/ECC skills/plan-canvas/SKILL.md — MIT, see THIRD_PARTY_NOTICES.md -->
|
|
12
|
+
|
|
13
|
+
# Plan Canvas
|
|
14
|
+
|
|
15
|
+
Review loop for plans and visual artifacts: you write the artifact, the human
|
|
16
|
+
reviews it in the browser — annotating the exact element they mean, chatting,
|
|
17
|
+
and delivering an **Approve plan / Request changes** verdict — while you block
|
|
18
|
+
on a single CLI call that returns their feedback as JSON.
|
|
19
|
+
|
|
20
|
+
Inspired by [lavish-axi](https://github.com/kunchenguid/lavish-axi); built
|
|
21
|
+
around a plan confirmation gate, with zero runtime dependencies. Vendored into
|
|
22
|
+
AOS from [affaan-m/ECC](https://github.com/affaan-m/ECC).
|
|
23
|
+
|
|
24
|
+
## When to Use
|
|
25
|
+
|
|
26
|
+
- You just wrote the `/startcycle` plan artifact,
|
|
27
|
+
`production_artifacts/00_execution_plan.md`, and need the CONFIRM/approve
|
|
28
|
+
decision — the canvas verdict replaces a typed "yes/proceed".
|
|
29
|
+
- **Mandatory, not optional**, at the end of `bdbrainstorm` (before writing
|
|
30
|
+
`state.goal` / handing off to `/startcycle-graph`) and `bdbmediastorm`
|
|
31
|
+
(before the show-control architecture is considered final) — both produce
|
|
32
|
+
a plan/spec artifact a human must approve before anything downstream
|
|
33
|
+
proceeds. See each skill's own "Plan Canvas Review" section.
|
|
34
|
+
- The user should *point at* what to change: reviewing designs, comparisons,
|
|
35
|
+
reports, or any local `.md` / `.html` artifact.
|
|
36
|
+
- The user asks for a visual review, or "open it in the browser".
|
|
37
|
+
|
|
38
|
+
This tool is a plain Node CLI speaking JSON over a loopback HTTP server —
|
|
39
|
+
it has no dependency on which agent harness invokes it (Claude Code, Codex,
|
|
40
|
+
Gemini/Antigravity, OpenCode, Cursor). The trigger lives in each consuming
|
|
41
|
+
skill's own instructions (synced to every harness by AOS's installer), not
|
|
42
|
+
in a harness-specific hook.
|
|
43
|
+
|
|
44
|
+
Do NOT use for: code review of diffs (`/code-review`), running web apps, or
|
|
45
|
+
remote URLs. The canvas serves local artifact files only.
|
|
46
|
+
|
|
47
|
+
## How It Works
|
|
48
|
+
|
|
49
|
+
Invoke the CLI as `aos-plan-canvas` — the bin shipped by the
|
|
50
|
+
`@hybridlabor-api/aos` package (on PATH after an AOS install). From a repo
|
|
51
|
+
checkout, `node skills/global_config/plan-canvas/scripts/plan-canvas.js` also
|
|
52
|
+
works. Run it from the project you are reviewing in; it works from any working
|
|
53
|
+
directory. It manages a detached loopback server (`127.0.0.1:4519`) shared by
|
|
54
|
+
all sessions, keyed by artifact path — no session ids to track.
|
|
55
|
+
|
|
56
|
+
The workflow is a plain CLI-plus-JSON loop, so it is model- and harness-agnostic:
|
|
57
|
+
any agent that can run a shell command and read stdout drives it the same way
|
|
58
|
+
(Claude Code, Codex, Cursor, Gemini, OpenCode, Copilot). Trigger it however your
|
|
59
|
+
harness surfaces skills — e.g. `/plan-canvas` in Claude Code, `$plan-canvas` in
|
|
60
|
+
Codex — or just run the `aos-plan-canvas` commands directly.
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
# 1. Open the artifact in the user's browser (returns immediately)
|
|
64
|
+
aos-plan-canvas open production_artifacts/00_execution_plan.md
|
|
65
|
+
|
|
66
|
+
# 2. Block until the human responds. Leave running; re-run if interrupted:
|
|
67
|
+
# queued feedback is never lost.
|
|
68
|
+
aos-plan-canvas await production_artifacts/00_execution_plan.md
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Stay listening, or the human talks to an empty chair
|
|
72
|
+
|
|
73
|
+
Feedback only reaches you while an `await` is actually parked on the session.
|
|
74
|
+
If your turn ends with nothing listening, the message sits in the queue and,
|
|
75
|
+
from the human's side of the glass, sending appears to do nothing at all.
|
|
76
|
+
|
|
77
|
+
So **run `await` as a background task** when your harness supports one (in
|
|
78
|
+
Claude Code, a Bash call with `run_in_background: true`). It exits the moment
|
|
79
|
+
feedback arrives and the harness hands you the JSON, which keeps the loop alive
|
|
80
|
+
across turns instead of dying with the foreground call. A foreground `await`
|
|
81
|
+
works too, but only until the harness time-limits it.
|
|
82
|
+
|
|
83
|
+
One backstop exists, and it is not an excuse to skip the above:
|
|
84
|
+
|
|
85
|
+
- `aos-plan-canvas pending` lists feedback queued with no listener. Check it
|
|
86
|
+
whenever you are unsure whether you missed something.
|
|
87
|
+
|
|
88
|
+
> Upstream ECC also ships a `stop:plan-canvas-pending` hook that blocks a turn
|
|
89
|
+
> from ending while canvas feedback is undelivered. **That hook is not vendored
|
|
90
|
+
> into AOS** — `pending` is the only backstop here, so the "keep `await`
|
|
91
|
+
> running" rule above carries the full weight.
|
|
92
|
+
|
|
93
|
+
`await` prints JSON when the human acts:
|
|
94
|
+
|
|
95
|
+
```json
|
|
96
|
+
{
|
|
97
|
+
"status": "feedback",
|
|
98
|
+
"items": [
|
|
99
|
+
{ "kind": "annotation", "text": "Split this into two phases",
|
|
100
|
+
"anchor": { "selector": "h2:nth-of-type(3)", "tag": "h2", "snippet": "Phase 2: Migration" } },
|
|
101
|
+
{ "kind": "verdict", "verdict": "request-changes" }
|
|
102
|
+
]
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
- `kind: "chat"` — freeform message; answer in the canvas, not the terminal.
|
|
107
|
+
- `kind: "annotation"` — feedback anchored to an element (`anchor.selector`,
|
|
108
|
+
`anchor.snippet` show what they pointed at; `anchor.textRange.text` when
|
|
109
|
+
they highlighted a passage).
|
|
110
|
+
- `kind: "verdict"` — `approve` means the plan is CONFIRMED: stop polling,
|
|
111
|
+
end the session, and start implementing. `request-changes` means revise the
|
|
112
|
+
artifact (the canvas live-reloads it) and keep the loop going.
|
|
113
|
+
|
|
114
|
+
**3. Always respond in the canvas**, then keep listening. One command does both:
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
aos-plan-canvas await <file> --reply "Split Phase 2 as requested. Take a look."
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Every human message gets a reply in the canvas, even a one-liner like
|
|
121
|
+
"On it, rewriting the risk table now." Silence in the chat panel is
|
|
122
|
+
indistinguishable from a broken canvas, which is exactly the failure this loop
|
|
123
|
+
exists to prevent. Answer there, not only in the terminal.
|
|
124
|
+
|
|
125
|
+
While you work, keep the chat honest with the activity indicator:
|
|
126
|
+
|
|
127
|
+
```bash
|
|
128
|
+
# animated "agent is thinking..." bubble; refresh it during long work
|
|
129
|
+
aos-plan-canvas typing <file> --state thinking
|
|
130
|
+
# switch to "agent is typing..." just before a reply lands
|
|
131
|
+
aos-plan-canvas typing <file> --state typing
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
`await` sets `thinking` for you the moment it hands you a batch, and `--reply`
|
|
135
|
+
clears it. Both states self-expire, so a crashed agent decays to an honest
|
|
136
|
+
"queued" instead of leaving the human watching dots forever. Refresh `thinking`
|
|
137
|
+
if a revision takes more than a minute.
|
|
138
|
+
|
|
139
|
+
**4. End** when review concludes: `aos-plan-canvas end <file>`.
|
|
140
|
+
|
|
141
|
+
## Relationship to `/startcycle`
|
|
142
|
+
|
|
143
|
+
An `approve` verdict on `production_artifacts/00_execution_plan.md` satisfies
|
|
144
|
+
the **Architect → TechLead gate (step 1 → 2)** of `/startcycle`: it is a human
|
|
145
|
+
confirmation that the plan is ready for the capability-map review. This is
|
|
146
|
+
optional — the pipeline runs unchanged without it.
|
|
147
|
+
|
|
148
|
+
## Diagrams (Mermaid)
|
|
149
|
+
|
|
150
|
+
When part of the plan is a flow, architecture, sequence, state machine, ER
|
|
151
|
+
model, or dependency graph, author it as a fenced ` ```mermaid ` block instead
|
|
152
|
+
of ASCII art or a wall of prose — the canvas renders it as a themed diagram the
|
|
153
|
+
human can point at. Reach for it when a picture reads faster than a paragraph;
|
|
154
|
+
skip it for simple lists or tables.
|
|
155
|
+
|
|
156
|
+
````markdown
|
|
157
|
+
```mermaid
|
|
158
|
+
flowchart LR
|
|
159
|
+
A[Market resolves] --> B{Watchers?}
|
|
160
|
+
B -->|yes| C[Enqueue jobs] --> D[Fan-out worker]
|
|
161
|
+
```
|
|
162
|
+
````
|
|
163
|
+
|
|
164
|
+
Diagrams render in the canvas dark theme with the accent palette. Mermaid loads
|
|
165
|
+
in the browser from a pinned CDN; if that is unavailable (offline), the block
|
|
166
|
+
degrades to showing its source, so the review is never blocked. Point a local
|
|
167
|
+
mirror at `AOS_PLAN_CANVAS_MERMAID_URL` for air-gapped use.
|
|
168
|
+
|
|
169
|
+
## Rules
|
|
170
|
+
|
|
171
|
+
- Markdown artifacts render in the built-in plan template (including Mermaid
|
|
172
|
+
blocks); `.html` artifacts render as-is with the annotation layer injected.
|
|
173
|
+
For HTML authoring guidance use the `godmode-ui-ux` and `ui-component` skills.
|
|
174
|
+
- Edit the artifact file to revise — the canvas live-reloads on save. Never
|
|
175
|
+
re-run `open` to refresh.
|
|
176
|
+
- `{"status": "ended", "endedBy": "user"}` (or `sessionEnded: true` on a
|
|
177
|
+
feedback batch) means the user closed the review: stop polling, deliver
|
|
178
|
+
remaining updates in chat, and do not reopen. A plain `open` on that
|
|
179
|
+
session is refused; pass `--reopen` only when the user asks to resume.
|
|
180
|
+
- Sibling assets (images, CSS) must sit next to the artifact and be
|
|
181
|
+
referenced by relative path.
|
|
182
|
+
- The server is loopback-only and exits after 30 idle minutes
|
|
183
|
+
(`AOS_PLAN_CANVAS_IDLE_MS`); `stop` shuts it down explicitly. State lives
|
|
184
|
+
in `~/.claude/aos-plan-canvas/` (`AOS_PLAN_CANVAS_STATE_DIR`).
|
|
185
|
+
|
|
186
|
+
## Examples
|
|
187
|
+
|
|
188
|
+
**Plan approval flow** — Architect writes
|
|
189
|
+
`production_artifacts/00_execution_plan.md` and must WAIT for confirmation:
|
|
190
|
+
|
|
191
|
+
```bash
|
|
192
|
+
aos-plan-canvas open production_artifacts/00_execution_plan.md
|
|
193
|
+
aos-plan-canvas await production_artifacts/00_execution_plan.md
|
|
194
|
+
# → {"status":"feedback","items":[{"kind":"verdict","verdict":"approve"}]}
|
|
195
|
+
aos-plan-canvas end production_artifacts/00_execution_plan.md
|
|
196
|
+
# plan is confirmed — hand off to TechLead
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
**Revision loop** — feedback arrives, you edit the file, reply, keep listening:
|
|
200
|
+
|
|
201
|
+
```bash
|
|
202
|
+
# await returned annotations → edit the plan artifact (canvas live-reloads)
|
|
203
|
+
aos-plan-canvas await <file> --reply "Reworked the risk table."
|
|
204
|
+
# → blocks again until the next response
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
## Anti-Patterns
|
|
208
|
+
|
|
209
|
+
- Polling with `--timeout-ms` in a loop. It exists for tests. Leave the plain
|
|
210
|
+
`await` running instead.
|
|
211
|
+
- Ending your turn with no `await` listening while the review is still open.
|
|
212
|
+
That is the one failure the human experiences as "I sent a message and
|
|
213
|
+
nothing happened".
|
|
214
|
+
- Reading the feedback but answering only in the terminal. The human is looking
|
|
215
|
+
at the canvas.
|
|
216
|
+
- Reopening after a user-initiated end "just to show" something.
|
|
217
|
+
- Pasting the whole plan into chat *and* opening a canvas — pick the canvas
|
|
218
|
+
and keep the terminal summary to one line.
|
|
219
|
+
- Parsing the canvas chat from state files — everything you need arrives via
|
|
220
|
+
`await`.
|
|
221
|
+
|
|
222
|
+
## Environment
|
|
223
|
+
|
|
224
|
+
| Variable | Purpose | Default |
|
|
225
|
+
|---|---|---|
|
|
226
|
+
| `AOS_PLAN_CANVAS_PORT` | Loopback server port | `4519` |
|
|
227
|
+
| `AOS_PLAN_CANVAS_STATE_DIR` | Session state directory | `~/.claude/aos-plan-canvas` |
|
|
228
|
+
| `AOS_PLAN_CANVAS_IDLE_MS` | Idle shutdown timeout | 30 minutes |
|
|
229
|
+
| `AOS_PLAN_CANVAS_MERMAID_URL` | Mermaid ESM mirror | pinned jsDelivr CDN |
|
|
230
|
+
|
|
231
|
+
`metadata.version` above and the `VERSION` literal in
|
|
232
|
+
`scripts/plan-canvas.js` are one value in two places — bump them together when
|
|
233
|
+
the vendored JS changes, so a stale detached server restarts.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Host/Origin gating for ECC's loopback HTTP servers (control pane, plan
|
|
5
|
+
* canvas). DNS rebinding can point an attacker-controlled hostname at
|
|
6
|
+
* 127.0.0.1, so every request must present a Host header from this
|
|
7
|
+
* allowlist before the server does any work.
|
|
8
|
+
*
|
|
9
|
+
* Source: affaan-m/ECC — MIT, see THIRD_PARTY_NOTICES.md
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const LOOPBACK_HOSTNAMES = new Set(['127.0.0.1', 'localhost', '[::1]', '::1']);
|
|
13
|
+
|
|
14
|
+
// Extract the hostname portion of an HTTP Host header value, stripping any
|
|
15
|
+
// port. Returns null when the header is missing or malformed.
|
|
16
|
+
function parseHostHeader(value) {
|
|
17
|
+
if (!value || typeof value !== 'string') return null;
|
|
18
|
+
const trimmed = value.trim();
|
|
19
|
+
if (!trimmed) return null;
|
|
20
|
+
const match = trimmed.match(/^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/);
|
|
21
|
+
if (!match) return null;
|
|
22
|
+
if (match[2] !== undefined) {
|
|
23
|
+
const port = Number(match[2]);
|
|
24
|
+
if (!Number.isInteger(port) || port > 65535) return null;
|
|
25
|
+
}
|
|
26
|
+
return match[1].toLowerCase();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function buildAllowedHostnames(configuredHost) {
|
|
30
|
+
const set = new Set(LOOPBACK_HOSTNAMES);
|
|
31
|
+
if (configuredHost) set.add(String(configuredHost).toLowerCase());
|
|
32
|
+
return set;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function isAllowedHostHeader(hostHeader, allowedHostnames) {
|
|
36
|
+
const hostname = parseHostHeader(hostHeader);
|
|
37
|
+
if (!hostname) return false;
|
|
38
|
+
return allowedHostnames.has(hostname);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Origin is absent on same-origin navigations and CLI clients; when present
|
|
42
|
+
// it must resolve to an allowed hostname.
|
|
43
|
+
function isAllowedOrigin(originHeader, allowedHostnames) {
|
|
44
|
+
if (!originHeader || typeof originHeader !== 'string') return true;
|
|
45
|
+
try {
|
|
46
|
+
const url = new URL(originHeader);
|
|
47
|
+
return allowedHostnames.has(url.hostname.toLowerCase());
|
|
48
|
+
} catch {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
module.exports = {
|
|
54
|
+
LOOPBACK_HOSTNAMES,
|
|
55
|
+
buildAllowedHostnames,
|
|
56
|
+
isAllowedHostHeader,
|
|
57
|
+
isAllowedOrigin,
|
|
58
|
+
parseHostHeader
|
|
59
|
+
};
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Minimal GitHub-flavored-markdown subset renderer for Plan Canvas.
|
|
5
|
+
* Renders .claude/plans/*.plan.md artifacts to HTML body content.
|
|
6
|
+
*
|
|
7
|
+
* Security model: the entire source line is HTML-escaped before any inline
|
|
8
|
+
* rule runs, so raw HTML in the markdown always displays as text. Link and
|
|
9
|
+
* image URLs are validated against an allowlist of protocols.
|
|
10
|
+
*
|
|
11
|
+
* Source: affaan-m/ECC — MIT, see THIRD_PARTY_NOTICES.md
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
// Placeholders live in the Unicode private-use area so escaped output can
|
|
15
|
+
// never collide with them. Pre-existing occurrences are stripped from input.
|
|
16
|
+
const TOKEN_OPEN = '\uE000';
|
|
17
|
+
const TOKEN_CLOSE = '\uE001';
|
|
18
|
+
const TOKEN_RE = new RegExp(TOKEN_OPEN + '(\\d+)' + TOKEN_CLOSE, 'g');
|
|
19
|
+
const STRIP_RE = new RegExp('[' + TOKEN_OPEN + TOKEN_CLOSE + ']', 'g');
|
|
20
|
+
|
|
21
|
+
const LIST_ITEM_RE = /^(\s*)([-*]|\d+\.)\s+(.*)$/;
|
|
22
|
+
const HR_RE = /^ {0,3}(-{3,}|\*{3,})\s*$/;
|
|
23
|
+
|
|
24
|
+
function escapeHtml(value) {
|
|
25
|
+
return String(value ?? '')
|
|
26
|
+
.replace(/&/g, '&')
|
|
27
|
+
.replace(/</g, '<')
|
|
28
|
+
.replace(/>/g, '>')
|
|
29
|
+
.replace(/"/g, '"')
|
|
30
|
+
.replace(/'/g, ''');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function slugify(text) {
|
|
34
|
+
return String(text ?? '')
|
|
35
|
+
.toLowerCase()
|
|
36
|
+
.replace(/[^a-z0-9\s-]/g, '')
|
|
37
|
+
.trim()
|
|
38
|
+
.replace(/[\s-]+/g, '-')
|
|
39
|
+
.replace(/^-+|-+$/g, '');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Strip whitespace/control characters so "Ja vaScript:" style tricks cannot
|
|
43
|
+
// hide a scheme, then classify against the allowlist.
|
|
44
|
+
function classifyUrl(rawUrl) {
|
|
45
|
+
const compact = String(rawUrl)
|
|
46
|
+
.split('')
|
|
47
|
+
.filter((ch) => ch.charCodeAt(0) > 32)
|
|
48
|
+
.join('')
|
|
49
|
+
.toLowerCase();
|
|
50
|
+
if (compact.startsWith('#')) return 'anchor';
|
|
51
|
+
if (compact.startsWith('//')) return 'blocked';
|
|
52
|
+
const scheme = compact.match(/^[a-z][a-z0-9+.-]*:/);
|
|
53
|
+
if (!scheme) return 'relative';
|
|
54
|
+
if (scheme[0] === 'http:' || scheme[0] === 'https:') return 'http';
|
|
55
|
+
if (scheme[0] === 'mailto:') return 'mailto';
|
|
56
|
+
return 'blocked';
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function applyEmphasis(s) {
|
|
60
|
+
return s
|
|
61
|
+
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
|
|
62
|
+
.replace(/~~([^~]+)~~/g, '<del>$1</del>')
|
|
63
|
+
.replace(/\*([^*]+)\*/g, '<em>$1</em>')
|
|
64
|
+
.replace(/(^|[^\w])_([^_]+)_(?!\w)/g, '$1<em>$2</em>');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function renderInline(rawText) {
|
|
68
|
+
const tokens = [];
|
|
69
|
+
const stash = (html) => {
|
|
70
|
+
tokens.push(html);
|
|
71
|
+
return TOKEN_OPEN + (tokens.length - 1) + TOKEN_CLOSE;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
let s = escapeHtml(rawText);
|
|
75
|
+
|
|
76
|
+
// Code spans first: contents stay escaped and opt out of all other rules.
|
|
77
|
+
s = s.replace(/`([^`]+)`/g, (_m, code) => stash('<code>' + code + '</code>'));
|
|
78
|
+
|
|
79
|
+
s = s.replace(/!\[([^\]]*)\]\(([^)]*)\)/g, (_m, alt, src) => {
|
|
80
|
+
const kind = classifyUrl(src);
|
|
81
|
+
if (kind !== 'http' && kind !== 'relative') return alt;
|
|
82
|
+
return stash('<img src="' + src.trim() + '" alt="' + alt + '">');
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
s = s.replace(/\[([^\]]+)\]\(([^)]*)\)/g, (_m, label, url) => {
|
|
86
|
+
const kind = classifyUrl(url);
|
|
87
|
+
const text = applyEmphasis(label);
|
|
88
|
+
if (kind === 'blocked') return text;
|
|
89
|
+
const extra = kind === 'http' ? ' target="_blank" rel="noopener"' : '';
|
|
90
|
+
return stash('<a href="' + url.trim() + '"' + extra + '>' + text + '</a>');
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
s = applyEmphasis(s);
|
|
94
|
+
|
|
95
|
+
// Stashed anchors may hold code-span tokens, so resolve until none remain.
|
|
96
|
+
while (s.includes(TOKEN_OPEN)) {
|
|
97
|
+
s = s.replace(TOKEN_RE, (_m, idx) => tokens[Number(idx)]);
|
|
98
|
+
}
|
|
99
|
+
return s;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function splitTableRow(line) {
|
|
103
|
+
let s = line.trim();
|
|
104
|
+
if (s.startsWith('|')) s = s.slice(1);
|
|
105
|
+
if (s.endsWith('|') && !s.endsWith('\\|')) s = s.slice(0, -1);
|
|
106
|
+
return s
|
|
107
|
+
.replace(/\\\|/g, TOKEN_OPEN)
|
|
108
|
+
.split('|')
|
|
109
|
+
.map((cell) => cell.split(TOKEN_OPEN).join('|').trim());
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function isAlignmentRow(line) {
|
|
113
|
+
if (!line || !line.includes('|')) return false;
|
|
114
|
+
const cells = splitTableRow(line);
|
|
115
|
+
return cells.length > 0 && cells.every((cell) => /^:?-+:?$/.test(cell));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function cellAlign(spec) {
|
|
119
|
+
const left = spec.startsWith(':');
|
|
120
|
+
const right = spec.endsWith(':');
|
|
121
|
+
if (left && right) return 'center';
|
|
122
|
+
if (right) return 'right';
|
|
123
|
+
if (left) return 'left';
|
|
124
|
+
return '';
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function renderListItem(text) {
|
|
128
|
+
const task = text.match(/^\[([ xX])\]\s+(.*)$/);
|
|
129
|
+
if (task) {
|
|
130
|
+
const checked = task[1].trim() ? ' checked' : '';
|
|
131
|
+
return '<li class="task"><input type="checkbox" disabled' + checked + '> ' +
|
|
132
|
+
renderInline(task[2]) + '</li>';
|
|
133
|
+
}
|
|
134
|
+
return '<li>' + renderInline(text) + '</li>';
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function listTag(marker) {
|
|
138
|
+
return /^\d/.test(marker) ? 'ol' : 'ul';
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function buildList(items, start, indent) {
|
|
142
|
+
const tag = listTag(items[start].marker);
|
|
143
|
+
const parts = [];
|
|
144
|
+
let i = start;
|
|
145
|
+
while (i < items.length && items[i].indent >= indent) {
|
|
146
|
+
if (items[i].indent > indent) {
|
|
147
|
+
// Deeper item: nest a sublist inside the previous <li>
|
|
148
|
+
const nested = buildList(items, i, items[i].indent);
|
|
149
|
+
if (parts.length > 0) {
|
|
150
|
+
const last = parts.pop();
|
|
151
|
+
parts.push(last.replace(/<\/li>$/, '\n' + nested.html + '\n</li>'));
|
|
152
|
+
} else {
|
|
153
|
+
parts.push('<li>\n' + nested.html + '\n</li>');
|
|
154
|
+
}
|
|
155
|
+
i = nested.end;
|
|
156
|
+
} else {
|
|
157
|
+
// A marker-type change at the same indent starts a new list
|
|
158
|
+
// (CommonMark); stop here so the caller renders the next run with
|
|
159
|
+
// its own tag instead of absorbing it into this one.
|
|
160
|
+
if (listTag(items[i].marker) !== tag) break;
|
|
161
|
+
parts.push(renderListItem(items[i].text));
|
|
162
|
+
i += 1;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return { html: '<' + tag + '>\n' + parts.join('\n') + '\n</' + tag + '>', end: i };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function buildListBlock(items) {
|
|
169
|
+
let lists = [];
|
|
170
|
+
let i = 0;
|
|
171
|
+
while (i < items.length) {
|
|
172
|
+
const list = buildList(items, i, items[i].indent);
|
|
173
|
+
lists = [...lists, list.html];
|
|
174
|
+
i = list.end;
|
|
175
|
+
}
|
|
176
|
+
return lists.join('\n');
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function startsBlock(line, nextLine) {
|
|
180
|
+
return /^```/.test(line) ||
|
|
181
|
+
/^#{1,6}\s/.test(line) ||
|
|
182
|
+
HR_RE.test(line) ||
|
|
183
|
+
/^ {0,3}>/.test(line) ||
|
|
184
|
+
LIST_ITEM_RE.test(line) ||
|
|
185
|
+
(line.includes('|') && isAlignmentRow(nextLine || ''));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function renderMarkdown(text) {
|
|
189
|
+
if (!text) return '';
|
|
190
|
+
const lines = String(text)
|
|
191
|
+
.replace(STRIP_RE, '')
|
|
192
|
+
.replace(/\r\n?/g, '\n')
|
|
193
|
+
.split('\n');
|
|
194
|
+
const out = [];
|
|
195
|
+
let i = 0;
|
|
196
|
+
|
|
197
|
+
while (i < lines.length) {
|
|
198
|
+
const line = lines[i];
|
|
199
|
+
|
|
200
|
+
if (!line.trim()) {
|
|
201
|
+
i += 1;
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const fence = line.match(/^```(.*)$/);
|
|
206
|
+
if (fence) {
|
|
207
|
+
const lang = fence[1].trim().split(/\s+/)[0].toLowerCase().replace(/[^a-z0-9-]/g, '');
|
|
208
|
+
const body = [];
|
|
209
|
+
i += 1;
|
|
210
|
+
while (i < lines.length && !/^```\s*$/.test(lines[i])) {
|
|
211
|
+
body.push(lines[i]);
|
|
212
|
+
i += 1;
|
|
213
|
+
}
|
|
214
|
+
i += 1; // skip closing fence (or run off EOF)
|
|
215
|
+
if (lang === 'mermaid') {
|
|
216
|
+
// Mermaid reads the element's textContent, and the browser decodes
|
|
217
|
+
// character references there — so escaping keeps `-->`/`<` intact for
|
|
218
|
+
// the renderer while preventing HTML injection or a </pre> breakout.
|
|
219
|
+
out.push('<pre class="mermaid">' + escapeHtml(body.join('\n')) + '</pre>');
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
const cls = lang ? ' class="language-' + lang + '"' : '';
|
|
223
|
+
out.push('<pre><code' + cls + '>' + escapeHtml(body.join('\n')) + '</code></pre>');
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const heading = line.match(/^(#{1,6})\s+(.+?)\s*$/);
|
|
228
|
+
if (heading) {
|
|
229
|
+
const level = heading[1].length;
|
|
230
|
+
out.push('<h' + level + ' id="' + slugify(heading[2]) + '">' +
|
|
231
|
+
renderInline(heading[2]) + '</h' + level + '>');
|
|
232
|
+
i += 1;
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Horizontal rule (alignment rows never reach here: tables consume them)
|
|
237
|
+
if (HR_RE.test(line)) {
|
|
238
|
+
out.push('<hr>');
|
|
239
|
+
i += 1;
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Blockquote: strip one `>` level and recurse, which handles nesting
|
|
244
|
+
if (/^ {0,3}>/.test(line)) {
|
|
245
|
+
const inner = [];
|
|
246
|
+
while (i < lines.length && /^ {0,3}>/.test(lines[i])) {
|
|
247
|
+
inner.push(lines[i].replace(/^ {0,3}> ?/, ''));
|
|
248
|
+
i += 1;
|
|
249
|
+
}
|
|
250
|
+
out.push('<blockquote>\n' + renderMarkdown(inner.join('\n')) + '\n</blockquote>');
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Table: header row followed by an alignment row
|
|
255
|
+
if (line.includes('|') && isAlignmentRow(lines[i + 1] || '')) {
|
|
256
|
+
const aligns = splitTableRow(lines[i + 1]).map(cellAlign);
|
|
257
|
+
const row = (tag, cells) => '<tr>' + cells.map((cell, idx) => {
|
|
258
|
+
const style = aligns[idx] ? ' style="text-align:' + aligns[idx] + '"' : '';
|
|
259
|
+
return '<' + tag + style + '>' + renderInline(cell) + '</' + tag + '>';
|
|
260
|
+
}).join('') + '</tr>';
|
|
261
|
+
const head = row('th', splitTableRow(line));
|
|
262
|
+
const body = [];
|
|
263
|
+
i += 2;
|
|
264
|
+
while (i < lines.length && lines[i].trim() && lines[i].includes('|')) {
|
|
265
|
+
body.push(row('td', splitTableRow(lines[i])));
|
|
266
|
+
i += 1;
|
|
267
|
+
}
|
|
268
|
+
out.push('<table>\n<thead>\n' + head + '\n</thead>\n<tbody>\n' +
|
|
269
|
+
body.join('\n') + '\n</tbody>\n</table>');
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (LIST_ITEM_RE.test(line)) {
|
|
274
|
+
const items = [];
|
|
275
|
+
while (i < lines.length) {
|
|
276
|
+
const m = lines[i].match(LIST_ITEM_RE);
|
|
277
|
+
if (!m) break;
|
|
278
|
+
items.push({ indent: m[1].length, marker: m[2], text: m[3] });
|
|
279
|
+
i += 1;
|
|
280
|
+
}
|
|
281
|
+
// An outdent below the first item's indentation ends that list. Render
|
|
282
|
+
// the remaining run as a sibling list so malformed indentation cannot
|
|
283
|
+
// silently drop content or create an empty parent item.
|
|
284
|
+
out.push(buildListBlock(items));
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Paragraph: run of plain lines up to a blank line or block start
|
|
289
|
+
const para = [line.trim()];
|
|
290
|
+
i += 1;
|
|
291
|
+
while (i < lines.length && lines[i].trim() && !startsBlock(lines[i], lines[i + 1])) {
|
|
292
|
+
para.push(lines[i].trim());
|
|
293
|
+
i += 1;
|
|
294
|
+
}
|
|
295
|
+
out.push('<p>' + renderInline(para.join('\n')) + '</p>');
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
return out.join('\n');
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
module.exports = { renderMarkdown, escapeHtml, slugify };
|