@herbertgao/pi-extensions 2026.11.18 → 2026.11.19

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 (151) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +3 -3
  3. package/THIRD_PARTY_NOTICES.md +2 -23
  4. package/node_modules/@estebanforge/pi-antigravity-bridge/CHANGELOG.md +956 -0
  5. package/node_modules/{pi-antigravity → @estebanforge/pi-antigravity-bridge}/LICENSE +1 -1
  6. package/node_modules/@estebanforge/pi-antigravity-bridge/README.md +240 -0
  7. package/node_modules/@estebanforge/pi-antigravity-bridge/extensions/index.ts +2117 -0
  8. package/node_modules/@estebanforge/pi-antigravity-bridge/package.json +61 -0
  9. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/connection.ts +644 -0
  10. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/driver.ts +1043 -0
  11. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/events.ts +323 -0
  12. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/home.ts +145 -0
  13. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/jsonrpc.ts +243 -0
  14. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/setup.ts +107 -0
  15. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/usage-estimate.ts +61 -0
  16. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agents.ts +64 -0
  17. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-install.ts +93 -0
  18. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-paths.ts +30 -0
  19. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-setup.ts +81 -0
  20. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-version.ts +289 -0
  21. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-detect.ts +161 -0
  22. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-gate.ts +233 -0
  23. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-hook.ts +325 -0
  24. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts-ui.ts +88 -0
  25. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts.ts +144 -0
  26. package/node_modules/@estebanforge/pi-antigravity-bridge/src/ask-tool.ts +1221 -0
  27. package/node_modules/@estebanforge/pi-antigravity-bridge/src/background-watch.ts +225 -0
  28. package/node_modules/@estebanforge/pi-antigravity-bridge/src/bridge-catalog.ts +197 -0
  29. package/node_modules/@estebanforge/pi-antigravity-bridge/src/config.ts +523 -0
  30. package/node_modules/@estebanforge/pi-antigravity-bridge/src/daily-log.ts +196 -0
  31. package/node_modules/@estebanforge/pi-antigravity-bridge/src/dialog-lock.ts +48 -0
  32. package/node_modules/@estebanforge/pi-antigravity-bridge/src/diff-render.ts +207 -0
  33. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver-types.ts +168 -0
  34. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver.ts +907 -0
  35. package/node_modules/@estebanforge/pi-antigravity-bridge/src/engine-picker.ts +160 -0
  36. package/node_modules/@estebanforge/pi-antigravity-bridge/src/frame-guard.ts +38 -0
  37. package/node_modules/@estebanforge/pi-antigravity-bridge/src/handoff-toast.ts +21 -0
  38. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-registration.ts +376 -0
  39. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-server.ts +618 -0
  40. package/node_modules/@estebanforge/pi-antigravity-bridge/src/models.ts +404 -0
  41. package/node_modules/@estebanforge/pi-antigravity-bridge/src/native-tools.ts +104 -0
  42. package/node_modules/@estebanforge/pi-antigravity-bridge/src/parked-turn.ts +125 -0
  43. package/node_modules/@estebanforge/pi-antigravity-bridge/src/patch-cleanup.ts +523 -0
  44. package/node_modules/@estebanforge/pi-antigravity-bridge/src/poll-fold.ts +55 -0
  45. package/node_modules/@estebanforge/pi-antigravity-bridge/src/prompt-images.ts +92 -0
  46. package/node_modules/@estebanforge/pi-antigravity-bridge/src/provider.ts +2214 -0
  47. package/node_modules/@estebanforge/pi-antigravity-bridge/src/queued-messages.ts +152 -0
  48. package/node_modules/@estebanforge/pi-antigravity-bridge/src/quota-notice.ts +40 -0
  49. package/node_modules/@estebanforge/pi-antigravity-bridge/src/redact.ts +27 -0
  50. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sessions.ts +197 -0
  51. package/node_modules/@estebanforge/pi-antigravity-bridge/src/skills.ts +207 -0
  52. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-events.ts +161 -0
  53. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-sanitizer.ts +180 -0
  54. package/node_modules/@estebanforge/pi-antigravity-bridge/src/subagent-roster.ts +245 -0
  55. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sysprompt-agent.ts +130 -0
  56. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks-ui.ts +90 -0
  57. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks.ts +174 -0
  58. package/node_modules/@estebanforge/pi-antigravity-bridge/src/usage.ts +174 -0
  59. package/node_modules/@estebanforge/pi-antigravity-bridge/src/web-tools.ts +320 -0
  60. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
  61. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +1 -1
  62. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +3 -1
  63. package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
  64. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +317 -105
  65. package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
  66. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -36
  67. package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
  68. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
  69. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  70. package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
  71. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
  72. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
  73. package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +20 -11
  74. package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
  75. package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
  76. package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +185 -44
  77. package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
  78. package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
  79. package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -116
  80. package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
  81. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
  82. package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
  83. package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
  84. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
  85. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
  86. package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
  87. package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
  88. package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
  89. package/node_modules/pi-commandcode-provider/README.md +3 -2
  90. package/node_modules/pi-commandcode-provider/index.ts +120 -13
  91. package/node_modules/pi-commandcode-provider/package.json +4 -3
  92. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
  93. package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
  94. package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
  95. package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
  96. package/package.json +11 -14
  97. package/node_modules/pi-antigravity/README.md +0 -298
  98. package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
  99. package/node_modules/pi-antigravity/package.json +0 -87
  100. package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
  101. package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
  102. package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
  103. package/node_modules/pi-antigravity/src/client/client.ts +0 -602
  104. package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
  105. package/node_modules/pi-antigravity/src/client/index.ts +0 -2
  106. package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
  107. package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
  108. package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
  109. package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
  110. package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
  111. package/node_modules/pi-antigravity/src/image/image.ts +0 -427
  112. package/node_modules/pi-antigravity/src/image/index.ts +0 -1
  113. package/node_modules/pi-antigravity/src/image/native.ts +0 -69
  114. package/node_modules/pi-antigravity/src/index.ts +0 -547
  115. package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
  116. package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
  117. package/node_modules/pi-antigravity/src/models/index.ts +0 -3
  118. package/node_modules/pi-antigravity/src/models/models.ts +0 -647
  119. package/node_modules/pi-antigravity/src/search/index.ts +0 -1
  120. package/node_modules/pi-antigravity/src/search/search.ts +0 -967
  121. package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
  122. package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
  123. package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
  124. package/node_modules/pi-antigravity/src/types/index.ts +0 -2
  125. package/node_modules/pi-antigravity/src/types/types.ts +0 -329
  126. package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
  127. package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
  128. package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
  129. package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
  130. package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
  131. package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
  132. package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
  133. package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
  134. package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
  135. package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
  136. package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
  137. package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
  138. package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
  139. package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
  140. package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
  141. package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
  142. package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
  143. package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
  144. package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
  145. package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
  146. package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
  147. package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
  148. package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
  149. package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
  150. package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
  151. package/node_modules/pi-antigravity/tsconfig.json +0 -21
@@ -1,744 +0,0 @@
1
- /**
2
- * HTML parsing and Markdown rendering belong to Domino and Turndown. This module
3
- * only chooses page content, resolves links, and reads the crawler's metadata.
4
- */
5
- import { parseDocument } from "./document.js";
6
- import { mediaKind } from "./media.js";
7
- import { advanceFence, FENCE_LINE, type Fence } from "./fences.js";
8
- import TurndownService from "turndown";
9
- import { tables } from "turndown-plugin-gfm";
10
- import { cleanText } from "../utils/text.js";
11
- import { METADATA_LIMITS } from "./metadata.js";
12
-
13
- const markdown = new TurndownService({
14
- headingStyle: "atx",
15
- bulletListMarker: "-",
16
- codeBlockStyle: "fenced",
17
- emDelimiter: "*",
18
- hr: "---",
19
- });
20
- markdown.use(tables);
21
- markdown.addRule("inlineCodeText", {
22
- filter: (node) => node.nodeName === "CODE" && node.parentNode?.nodeName !== "PRE",
23
- replacement: (_content, node) => {
24
- const content = (node.textContent ?? "").replace(/\r?\n|\r/g, " ");
25
- if (!content) return "";
26
- const matches: string[] = content.match(/`+/g) ?? [];
27
- let delimiter = "`";
28
- while (matches.includes(delimiter)) delimiter += "`";
29
- const padding = /^`|^ .*?[^ ].* $|`$/.test(content) ? " " : "";
30
- return delimiter + padding + content + padding + delimiter;
31
- },
32
- });
33
- markdown.addRule("strikethrough", {
34
- filter: (node) => /^(DEL|S|STRIKE)$/.test(node.nodeName),
35
- replacement: (content) => `~~${content}~~`,
36
- });
37
- // GFM cells cannot contain block-level Markdown or unescaped pipes.
38
- markdown.addRule("tableCell", {
39
- filter: ["td", "th"],
40
- replacement: (content, node) =>
41
- `${node.previousElementSibling ? " " : "| "}${content
42
- .trim()
43
- .replace(/\s*\n\s*/g, " ")
44
- .replace(/\\/g, "\\\\")
45
- .replace(/\|/g, "\\|")} |`,
46
- });
47
-
48
- const DROPPED_ELEMENTS =
49
- "script, style, noscript, template, svg, canvas, iframe, form, select, option, button";
50
- const CHROME =
51
- 'nav, aside, footer, .social-icons, .site-footer, .page-footer, .site-header, .site-nav, [role="navigation"], [role="banner"], [role="contentinfo"], [role="search"], [aria-hidden="true"], [hidden]';
52
-
53
- export type PageMetadata = {
54
- title?: string;
55
- description?: string;
56
- /** Date the page says it was last modified, exactly as the page states it. */
57
- updated?: string;
58
- };
59
-
60
- /** Collapse line breaks/control characters and bound page-controlled metadata. */
61
- export const sanitizeMetadataText = cleanText;
62
-
63
- /** Read metadata through the HTML parser, not a search through attribute text. */
64
- export function extractPageMetadata(html: string, document = parseDocument(html)): PageMetadata {
65
- const meta = (selector: string) =>
66
- document.querySelector(selector)?.getAttribute("content")?.trim() || undefined;
67
- return {
68
- title: sanitizeMetadataText(
69
- meta('meta[property="og:title"]') ??
70
- meta('meta[name="twitter:title"]') ??
71
- (document.querySelector("title")?.textContent?.trim() || undefined),
72
- METADATA_LIMITS.title,
73
- ),
74
- description: sanitizeMetadataText(
75
- meta('meta[property="og:description"]') ??
76
- meta('meta[name="description"]') ??
77
- meta('meta[name="twitter:description"]'),
78
- METADATA_LIMITS.description,
79
- ),
80
- updated: sanitizeMetadataText(
81
- meta('meta[property="article:modified_time"]') ??
82
- meta('meta[property="og:updated_time"]') ??
83
- meta('meta[name="last-modified"]') ??
84
- meta('meta[name="lastmod"]'),
85
- METADATA_LIMITS.updated,
86
- ),
87
- };
88
- }
89
-
90
- /** Any element name, block-level or inline. */
91
- const HTML_TAG = /<\/?([a-z][a-z0-9:-]*)\b[^>]*>/gi;
92
-
93
- /** Elements that never carry a closing tag. */
94
- const HTML_VOID_TAGS = new Set([
95
- "area",
96
- "base",
97
- "br",
98
- "col",
99
- "embed",
100
- "hr",
101
- "img",
102
- "input",
103
- "link",
104
- "meta",
105
- "param",
106
- "source",
107
- "track",
108
- "wbr",
109
- ]);
110
-
111
- const HTML_ELEMENTS = new Set(
112
- "html head body title meta link script style noscript template main article section header footer nav aside div p span a strong em b i u s del strike code pre blockquote h1 h2 h3 h4 h5 h6 ul ol li dl dt dd table caption thead tbody tfoot tr th td figure figcaption picture img source br hr form label input button select option textarea details summary time address small sub sup abbr cite q mark kbd samp var wbr".split(
113
- " ",
114
- ),
115
- );
116
-
117
- /**
118
- * Whether an element's closing tag ends a markup run. Text after the closing tag
119
- * belongs to the sentence around it ("closed by </p>."), not to the markup.
120
- */
121
- function closesLikeMarkup(source: string, name: string): boolean {
122
- const pattern = new RegExp(`</${name}\\s*>`, "gi");
123
- for (let match = pattern.exec(source); match; match = pattern.exec(source)) {
124
- const rest = source.slice(match.index + match[0].length);
125
- const nextMarkup = rest.indexOf("<");
126
- const tail = nextMarkup < 0 ? rest : rest.slice(0, nextMarkup);
127
- if (!tail.trim()) return true;
128
- // Prose can name an opening tag and explain how it is closed. Trailing text
129
- // alone does not disqualify an otherwise ordinary HTML fragment.
130
- const explanation = /\b(?:closed|closing|ended)\s+(?:by|with)\s*$/i.test(
131
- source.slice(0, match.index),
132
- );
133
- if (!(explanation && /^[.!?\s]*$/.test(tail))) return true;
134
- }
135
- return false;
136
- }
137
-
138
- /** Require document markers or element structure, not a prose mention of a tag. */
139
- function hasHtmlStructure(source: string): boolean {
140
- if (!source.trimStart().startsWith("<")) return false;
141
-
142
- if (/<!doctype\b[^<>]*>|<\/?(?:html|head|body)\b/i.test(source)) return true;
143
- const first = /^\s*<([a-z][\w:-]*)\b/i.exec(source)?.[1]?.toLowerCase();
144
- if (first && !HTML_ELEMENTS.has(first)) return false;
145
- const names = new Set<string>();
146
- for (const match of source.matchAll(HTML_TAG)) {
147
- const name = match[1]?.toLowerCase();
148
- if (name) names.add(name);
149
- }
150
- for (const name of names) {
151
- if (HTML_VOID_TAGS.has(name)) return true;
152
- if (!new RegExp(`<${name}\\b[^>]*>`, "i").test(source)) continue;
153
- if (closesLikeMarkup(source, name)) return true;
154
- }
155
- return false;
156
- }
157
-
158
- /** Leave plain text, JSON, and already-Markdown responses alone. */
159
- export function looksLikeHtml(text: string, contentType?: string): boolean {
160
- const kind = mediaKind(contentType);
161
- if (
162
- kind === "xml" ||
163
- /^\s*(?:<\?xml\b|<svg\b|<urlset\b|<sitemapindex\b|<feed\b|<rss\b)/i.test(text)
164
- )
165
- return false;
166
- if (kind === "html") return true;
167
- // An explicit document wrapper outweighs an incorrect text/plain service label.
168
- if (/^\s*(?:<!doctype\s+html\b|<html\b)/i.test(text)) return true;
169
- if (kind === "text" || kind === "json" || kind === "pdf") return false;
170
- if (/^\s*[{"[]/.test(text)) {
171
- try {
172
- JSON.parse(text);
173
- return false;
174
- } catch {
175
- // A leading bracket alone does not establish JSON.
176
- }
177
- }
178
- let fence: Fence | undefined;
179
- const prose: string[] = [];
180
- for (const line of text.slice(0, 4000).split("\n")) {
181
- const previous = fence;
182
- fence = advanceFence(fence, line);
183
- if (!previous && !fence && !FENCE_LINE.test(line)) prose.push(line);
184
- }
185
- const source = prose.join("\n").replace(/(?<!`)(`+)(?!`)[\s\S]*?(?<!`)\1(?!`)/g, "");
186
- // Markdown can include HTML decorations without becoming an HTML document.
187
- if (/^ {0,3}#{1,6}\s/m.test(source) && !/<!doctype\b|<(?:html|head|body)\b/i.test(source)) {
188
- const body = parseDocument(source).body;
189
- if (
190
- Array.from(body.childNodes).some(
191
- (node) => node.nodeType === 3 && /^ {0,3}#{1,6}\s/m.test(node.textContent ?? ""),
192
- )
193
- )
194
- return false;
195
- }
196
- return hasHtmlStructure(source);
197
- }
198
-
199
- /** Find a tag's closing angle bracket without mistaking a quoted attribute for markup. */
200
- function findMarkupTagEnd(source: string, start: number): number {
201
- let quote = "";
202
- let afterEquals = false;
203
- for (let index = start + 1; index < source.length; index += 1) {
204
- const character = source[index];
205
- if (quote) {
206
- if (character === quote) quote = "";
207
- continue;
208
- }
209
- if (character === ">") return index;
210
- if ((character === "'" || character === '"') && afterEquals) {
211
- quote = character;
212
- afterEquals = false;
213
- } else if (character === "=") {
214
- afterEquals = true;
215
- } else if (!/\s/.test(character)) {
216
- afterEquals = false;
217
- }
218
- }
219
- return -1;
220
- }
221
-
222
- export type CopyCompleteness = "complete" | "incomplete" | "unknown";
223
-
224
- /**
225
- * A parsed DOM repairs truncated markup, so completeness must be checked against
226
- * the original source. Missing document-end tags alone are ambiguous because HTML
227
- * permits omitting them; a clean end at an element boundary is likewise ambiguous.
228
- * Unfinished tokens and unclosed article/main regions in full documents are
229
- * positive signs of truncation; sentence punctuation alone is not.
230
- */
231
- export function classifyCopyCompleteness(html: string): CopyCompleteness {
232
- if (!html.trim()) return "complete";
233
- let index = 0;
234
- let documentRootSeen = false;
235
- let rootClosedAtEnd = false;
236
- let templateDepth = 0;
237
- let contentDepth = 0;
238
-
239
- while (index < html.length) {
240
- if (html.startsWith("<!--", index)) {
241
- const commentEnd = html.indexOf("-->", index + 4);
242
- if (commentEnd < 0) return "incomplete";
243
- index = commentEnd + 3;
244
- continue;
245
- }
246
- if (html[index] !== "<") {
247
- if (!/\s/.test(html[index])) rootClosedAtEnd = false;
248
- index += 1;
249
- continue;
250
- }
251
- if (index + 1 >= html.length) return "incomplete";
252
- const next = html[index + 1];
253
- if (!/[a-z]/i.test(next) && next !== "!" && next !== "?" && next !== "/") {
254
- rootClosedAtEnd = false;
255
- index += 1;
256
- continue;
257
- }
258
-
259
- const tagEnd = findMarkupTagEnd(html, index);
260
- if (tagEnd < 0) return "incomplete";
261
- const tag = html.slice(index, tagEnd + 1);
262
- const name = /^<\s*\/?\s*([a-z][a-z0-9:-]*)\b/i.exec(tag)?.[1]?.toLowerCase();
263
- const closing = /^<\s*\//.test(tag);
264
-
265
- if (name === "html" || name === "body" || /^<!doctype\b/i.test(tag)) {
266
- documentRootSeen = true;
267
- }
268
- if (
269
- closing &&
270
- (name === "html" || name === "body") &&
271
- documentRootSeen &&
272
- templateDepth === 0
273
- ) {
274
- rootClosedAtEnd = true;
275
- index = tagEnd + 1;
276
- continue;
277
- }
278
-
279
- rootClosedAtEnd = false;
280
- if (templateDepth === 0 && (name === "article" || name === "main"))
281
- contentDepth = Math.max(0, contentDepth + (closing ? -1 : 1));
282
- if (!closing && name === "template" && !/\/\s*>$/.test(tag)) templateDepth += 1;
283
- if (closing && name === "template" && templateDepth > 0) templateDepth -= 1;
284
-
285
- if (
286
- !closing &&
287
- name &&
288
- /^(?:script|style|textarea|title|noscript|xmp|iframe|noembed|noframes|plaintext)$/.test(name)
289
- ) {
290
- if (name === "plaintext") return "unknown";
291
- const rawClose = new RegExp("</\\s*" + name + "\\s*>", "ig");
292
- rawClose.lastIndex = tagEnd + 1;
293
- const match = rawClose.exec(html);
294
- if (!match) return "incomplete";
295
- index = match.index + match[0].length;
296
- continue;
297
- }
298
- index = tagEnd + 1;
299
- }
300
-
301
- if (rootClosedAtEnd && contentDepth === 0) return "complete";
302
- return documentRootSeen && contentDepth > 0 ? "incomplete" : "unknown";
303
- }
304
-
305
- /** Whether the source has an unambiguously unfinished final HTML token. */
306
- function isPartialCopy(html: string): boolean {
307
- return classifyCopyCompleteness(html) === "incomplete";
308
- }
309
-
310
- export type HtmlToMarkdownOptions = {
311
- /** Page URL, used to turn relative links and image sources into absolute ones. */
312
- baseUrl?: string;
313
- /** An owned DOM supplied by inspection, before destructive cleanup. */
314
- document?: Document;
315
- };
316
-
317
- /** Where relative links point: the page's `<base href>` when it has a usable one. */
318
- function documentBase(document: Document, baseUrl?: string): string | undefined {
319
- const href = document.querySelector("base[href]")?.getAttribute("href")?.trim();
320
- if (!href) return baseUrl;
321
- try {
322
- const base = new URL(href, baseUrl);
323
- return base.protocol === "http:" || base.protocol === "https:" ? base.href : baseUrl;
324
- } catch {
325
- return baseUrl;
326
- }
327
- }
328
-
329
- /** Class and id names that mark site chrome rather than page content. */
330
- const CHROME_NAME = /^(?:footer|sidebar|toc|nav|menu|breadcrumb|masthead|social)$/;
331
- /** An element this large a share of the page is the page, whatever its class says. */
332
- const CONTENT_SHARE = 0.4;
333
- const CONTENT_MIN_CHARS = 500;
334
-
335
- /**
336
- * Whether a class-marked element is the page itself. Names such as `has-sidebar`,
337
- * `menu-open`, or `content-sidebar-wrap` describe state or layout on wrappers that
338
- * hold the article; only a small, named block is chrome.
339
- */
340
- function holdsPageText(node: Element, bodyChars: number): boolean {
341
- if (node.querySelector('h1, main, [role="main"], article')) return true;
342
- const chars = node.textContent?.length ?? 0;
343
- return chars >= CONTENT_MIN_CHARS && chars >= bodyChars * CONTENT_SHARE;
344
- }
345
-
346
- function resolveTarget(target: string, baseUrl?: string): string {
347
- try {
348
- return new URL(target, baseUrl).toString();
349
- } catch {
350
- return target;
351
- }
352
- }
353
-
354
- /** Whether the effective inline style hides its element. */
355
- function isHiddenStyle(style: string | null): boolean {
356
- if (!style) return false;
357
- // A comment inside the attribute must not hide the declaration behind it.
358
- const declarations = style.replace(/\/\*[\s\S]*?\*\//g, "").split(";");
359
- const winners = new Map<string, { value: string; important: boolean }>();
360
- for (const declaration of declarations) {
361
- const separator = declaration.indexOf(":");
362
- if (separator < 0) continue;
363
- const property = declaration.slice(0, separator).trim().toLowerCase();
364
- if (property !== "display" && property !== "visibility") continue;
365
- const raw = declaration.slice(separator + 1);
366
- const important = /!\s*important\s*$/i.test(raw);
367
- const value = raw
368
- .replace(/\s*!\s*important\s*$/i, "")
369
- .trim()
370
- .toLowerCase();
371
- const current = winners.get(property);
372
- if (!current || important || !current.important) winners.set(property, { value, important });
373
- }
374
- const display = winners.get("display")?.value;
375
- const visibility = winners.get("visibility")?.value;
376
- return display === "none" || visibility === "hidden" || visibility === "collapse";
377
- }
378
-
379
- /** Remove only a dangling tag fragment at the end of a partial page. */
380
- function removeDanglingTailText(node: Node): boolean {
381
- const children = Array.from(node.childNodes);
382
- for (let index = children.length - 1; index >= 0; index -= 1) {
383
- const child = children[index];
384
- if (child.nodeType === 3) {
385
- const text = child.textContent ?? "";
386
- if (!text.trim()) {
387
- child.remove();
388
- continue;
389
- }
390
- if (/^\s*(?:<\s*|<\/?[a-z][a-z0-9:-]*(?:\s[^<>]*)?\s*)$/i.test(text)) {
391
- child.remove();
392
- return true;
393
- }
394
- return false;
395
- }
396
- if (child.nodeType === 8) continue;
397
- if (child.nodeType === 1) {
398
- if (removeDanglingTailText(child)) return true;
399
- if (!child.textContent?.trim()) continue;
400
- }
401
- return false;
402
- }
403
- return false;
404
- }
405
-
406
- function tableCellHasContent(cell: HTMLTableCellElement): boolean {
407
- return Boolean(cell.textContent?.trim() || cell.querySelector("img"));
408
- }
409
-
410
- function tableRowHasContent(row: HTMLTableRowElement): boolean {
411
- return Array.from(row.cells).some(tableCellHasContent);
412
- }
413
-
414
- function belongsToTable(row: HTMLTableRowElement, table: HTMLTableElement): boolean {
415
- let ancestor: Node | null = row.parentNode;
416
- while (ancestor && ancestor !== table) {
417
- if (ancestor.nodeName === "TABLE") return false;
418
- ancestor = ancestor.parentNode;
419
- }
420
- return ancestor === table;
421
- }
422
-
423
- function hasTableAncestor(table: HTMLTableElement): boolean {
424
- let ancestor: Node | null = table.parentNode;
425
- while (ancestor) {
426
- if (ancestor.nodeName === "TABLE") return true;
427
- ancestor = ancestor.parentNode;
428
- }
429
- return false;
430
- }
431
-
432
- /** Flatten unsupported grids without discarding links, images, or inline code. */
433
- function flattenTable(table: HTMLTableElement, document: Document): void {
434
- const flattened = document.createElement("span");
435
- const caption = table.querySelector("caption");
436
- if (caption) {
437
- for (const child of Array.from(caption.childNodes))
438
- flattened.appendChild(child.cloneNode(true));
439
- flattened.appendChild(document.createTextNode(" — "));
440
- }
441
- const rows = Array.from(table.rows).filter(
442
- (row) => belongsToTable(row, table) && tableRowHasContent(row),
443
- );
444
- rows.forEach((row, rowIndex) => {
445
- flattened.appendChild(document.createTextNode(rowIndex ? "; " : " "));
446
- Array.from(row.cells)
447
- .filter(tableCellHasContent)
448
- .forEach((cell, cellIndex) => {
449
- if (cellIndex) flattened.appendChild(document.createTextNode(" — "));
450
- for (const child of Array.from(cell.childNodes))
451
- flattened.appendChild(child.cloneNode(true));
452
- });
453
- });
454
- flattened.appendChild(document.createTextNode(" "));
455
- table.replaceWith(flattened);
456
- }
457
-
458
- function flattenNestedTables(root: Element, document: Document): void {
459
- for (const table of Array.from(root.querySelectorAll("table")).reverse()) {
460
- if (hasTableAncestor(table)) flattenTable(table, document);
461
- }
462
- }
463
-
464
- const MAX_TABLE_GRID_CELLS = 10_000;
465
-
466
- function normalizeTableRows(
467
- table: HTMLTableElement,
468
- document: Document,
469
- maxGridCells: number,
470
- ): HTMLTableRowElement[] | undefined {
471
- const rows = Array.from(table.rows).filter((row) => belongsToTable(row, table));
472
- const groupEnds = new Map<Node | null, number>();
473
- rows.forEach((row, index) => groupEnds.set(row.parentNode, index));
474
- const occupiedUntil = new Map<number, number>();
475
- const placements: Array<Array<{ cell: HTMLTableCellElement; column: number; span: number }>> =
476
- rows.map(() => []);
477
- let width = 0;
478
-
479
- for (const [rowIndex, row] of rows.entries()) {
480
- let column = 0;
481
- for (const cell of Array.from(row.cells)) {
482
- const span = Math.max(1, cell.colSpan);
483
- for (;;) {
484
- if ((column + span) * rows.length > maxGridCells) return undefined;
485
- let blocked: number | undefined;
486
- for (let offset = 0; offset < span; offset += 1) {
487
- if ((occupiedUntil.get(column + offset) ?? -1) >= rowIndex) {
488
- blocked = column + offset;
489
- break;
490
- }
491
- }
492
- if (blocked === undefined) break;
493
- column = blocked + 1;
494
- }
495
- placements[rowIndex].push({ cell, column, span });
496
- const remainingRows = groupEnds.get(row.parentNode)! - rowIndex + 1;
497
- const rowSpan = Math.min(
498
- remainingRows,
499
- cell.rowSpan === 0 ? remainingRows : Math.max(1, cell.rowSpan),
500
- );
501
- for (let offset = 0; offset < span; offset += 1) {
502
- occupiedUntil.set(column + offset, rowIndex + rowSpan - 1);
503
- }
504
- column += span;
505
- }
506
- width = Math.max(width, column);
507
- }
508
-
509
- rows.forEach((row, rowIndex) => {
510
- const placed = new Map(placements[rowIndex].map((item) => [item.column, item]));
511
- const cells: HTMLTableCellElement[] = [];
512
- for (let column = 0; column < width;) {
513
- const item = placed.get(column);
514
- if (item) {
515
- item.cell.removeAttribute("colspan");
516
- item.cell.removeAttribute("rowspan");
517
- cells.push(item.cell);
518
- for (let offset = 1; offset < item.span; offset += 1) {
519
- cells.push(document.createElement(item.cell.localName) as HTMLTableCellElement);
520
- }
521
- column += item.span;
522
- } else {
523
- cells.push(document.createElement("td"));
524
- column += 1;
525
- }
526
- }
527
- for (const child of Array.from(row.childNodes)) child.remove();
528
- for (const cell of cells) row.appendChild(cell);
529
- });
530
-
531
- return rows;
532
- }
533
-
534
- /** Read preformatted text while retaining the line breaks represented by <br>. */
535
- function preformattedText(node: Node): string {
536
- if (node.nodeType === 3) return node.textContent ?? "";
537
- if (node.nodeName === "BR") return "\n";
538
- return Array.from(node.childNodes, preformattedText).join("");
539
- }
540
-
541
- /** HN's front page uses layout tables, not tabular article data. */
542
- function hackerNewsListing(document: Document, baseUrl?: string): HTMLElement | undefined {
543
- if (!baseUrl) return undefined;
544
- const url = new URL(baseUrl);
545
- if (url.hostname !== "news.ycombinator.com" || !["/", "/news"].includes(url.pathname))
546
- return undefined;
547
- const stories = Array.from(document.querySelectorAll("tr.athing")).filter((row) =>
548
- row.querySelector(".titleline"),
549
- );
550
- if (!stories.length) return undefined;
551
- const main = document.createElement("main");
552
- const heading = document.createElement("h1");
553
- heading.textContent = document.title;
554
- main.appendChild(heading);
555
- const list = document.createElement("ol");
556
- for (const row of stories) {
557
- const item = document.createElement("li");
558
- item.appendChild(row.querySelector(".titleline")!.cloneNode(true));
559
- const metadata = row.nextElementSibling?.querySelector(".subtext");
560
- if (metadata) {
561
- item.appendChild(document.createTextNode(" — "));
562
- for (const child of Array.from(metadata.childNodes)) item.appendChild(child.cloneNode(true));
563
- }
564
- list.appendChild(item);
565
- }
566
- main.appendChild(list);
567
- const more = document.querySelector("a.morelink");
568
- if (more) main.appendChild(more.cloneNode(true));
569
- return main;
570
- }
571
-
572
- /** Convert the page's content; the DOM parser also repairs incomplete crawler copies. */
573
- export function htmlToMarkdown(
574
- html: string,
575
- { baseUrl, document = parseDocument(html) }: HtmlToMarkdownOptions = {},
576
- ): string {
577
- if (!html) return "";
578
- const linkBase = documentBase(document, baseUrl);
579
- // Mozilla Readability recommends isolating its mutating extraction on a clone (Apache-2.0):
580
- // https://github.com/mozilla/readability. This parse already owns a disposable DOM.
581
- for (const node of Array.from(document.querySelectorAll(DROPPED_ELEMENTS))) node.remove();
582
- for (const node of Array.from(document.querySelectorAll("[hidden], [aria-hidden], [style]"))) {
583
- if (
584
- node.hasAttribute("hidden") ||
585
- node.getAttribute("aria-hidden")?.trim().toLowerCase() === "true" ||
586
- isHiddenStyle(node.getAttribute("style"))
587
- ) {
588
- node.remove();
589
- }
590
- }
591
- for (const node of Array.from(document.body.querySelectorAll(CHROME))) node.remove();
592
- const bodyChars = document.body.textContent?.length ?? 0;
593
- for (const node of Array.from(
594
- document.body.querySelectorAll("div, section, ul, ol, header, footer, aside, nav"),
595
- )) {
596
- const names = `${node.getAttribute("id") ?? ""} ${node.getAttribute("class") ?? ""}`
597
- .toLowerCase()
598
- .split(/\s+/)
599
- .filter((name) => !/[:[\]/]/.test(name));
600
- if (
601
- names.some((name) => name.split(/[_-]+/).some((piece) => CHROME_NAME.test(piece))) &&
602
- !holdsPageText(node, bodyChars)
603
- )
604
- node.remove();
605
- }
606
- // Empty/hidden placeholders are not content roots. Prefer the substantive region,
607
- // not whichever <main> happens to occur first.
608
- const regions = Array.from(
609
- document.querySelectorAll<HTMLElement>('main, [role="main"], article'),
610
- );
611
- regions.sort((a, b) => (b.textContent?.trim().length ?? 0) - (a.textContent?.trim().length ?? 0));
612
- const root =
613
- hackerNewsListing(document, baseUrl) ??
614
- regions.find((node) => node.textContent?.trim()) ??
615
- document.body;
616
- if (isPartialCopy(html)) removeDanglingTailText(root);
617
-
618
- for (const link of Array.from(root.querySelectorAll("a"))) {
619
- link.removeAttribute("title");
620
- const href = link.getAttribute("href")?.trim();
621
- const textLabel = link.textContent?.trim() ?? "";
622
- const ariaLabel = link.getAttribute("aria-label")?.trim() ?? "";
623
- if (!textLabel && ariaLabel) link.textContent = ariaLabel;
624
- const label = textLabel || ariaLabel;
625
- if (!label && !link.querySelector("img")) {
626
- link.remove();
627
- continue;
628
- }
629
- if (href?.startsWith("#") && (!/[\p{L}\p{N}]/u.test(label) || /^skip\b/i.test(label))) {
630
- link.remove();
631
- } else if (
632
- href?.startsWith("#") ||
633
- /^(?:javascript|vbscript|data):/i.test(href?.replace(/\s/g, "") ?? "")
634
- ) {
635
- link.removeAttribute("href");
636
- } else if (href) {
637
- link.setAttribute("href", resolveTarget(href, linkBase));
638
- if (
639
- link.childNodes.length === 1 &&
640
- link.firstChild === link.firstElementChild &&
641
- link.firstElementChild?.tagName === "IMG"
642
- ) {
643
- link.removeAttribute("href");
644
- } else if (label === href || label === link.getAttribute("href")) {
645
- link.replaceWith(document.createTextNode(link.getAttribute("href")!));
646
- }
647
- }
648
- }
649
- for (const image of Array.from(root.querySelectorAll("img"))) {
650
- image.removeAttribute("title");
651
- const src = image.getAttribute("src")?.trim();
652
- if (!src || /^(?:data|javascript|vbscript):/i.test(src.replace(/\s/g, ""))) image.remove();
653
- else image.setAttribute("src", resolveTarget(src, linkBase));
654
- }
655
- for (const link of Array.from(root.querySelectorAll("a"))) {
656
- if (!link.textContent?.trim() && !link.querySelector("img")) link.remove();
657
- }
658
- for (const item of Array.from(root.querySelectorAll("li"))) {
659
- if (!item.textContent?.trim() && !item.querySelector("img")) item.remove();
660
- }
661
-
662
- // Turndown's fenced-code rule expects <pre><code>...</code></pre>.
663
- for (const pre of Array.from(root.querySelectorAll("pre"))) {
664
- const text = preformattedText(pre);
665
- if (pre.childNodes.length === 1 && pre.firstChild?.nodeName === "CODE") {
666
- pre.firstChild.textContent = text;
667
- continue;
668
- }
669
- const code = document.createElement("code");
670
- code.textContent = text;
671
- pre.textContent = "";
672
- pre.appendChild(code);
673
- }
674
- flattenNestedTables(root, document);
675
- // Give the GFM plugin a rectangular table with an explicit header section.
676
- let remainingTableCells = MAX_TABLE_GRID_CELLS;
677
- for (const table of Array.from(root.querySelectorAll("table"))) {
678
- const normalized = normalizeTableRows(table, document, remainingTableCells);
679
- if (!normalized) {
680
- flattenTable(table, document);
681
- continue;
682
- }
683
- remainingTableCells -= normalized.length * (normalized[0]?.cells.length ?? 0);
684
- const rows = normalized.filter(tableRowHasContent);
685
- if (!rows.length || (!table.textContent?.trim() && !table.querySelector("img"))) {
686
- table.remove();
687
- continue;
688
- }
689
- const width = rows[0].cells.length;
690
- const first = rows[0];
691
- const header = Array.from(first.cells).every((cell) => cell.tagName === "TH")
692
- ? rows.shift()!
693
- : document.createElement("tr");
694
- for (let column = header.cells.length; column < width; column += 1)
695
- header.appendChild(document.createElement("th"));
696
- const head = document.createElement("thead");
697
- const body = document.createElement("tbody");
698
- head.appendChild(header);
699
- for (const row of rows) body.appendChild(row);
700
- const sourceCaption = table.querySelector("caption");
701
- if (sourceCaption) {
702
- const caption = document.createElement("p");
703
- for (const child of Array.from(sourceCaption.childNodes))
704
- caption.appendChild(child.cloneNode(true));
705
- table.parentNode!.insertBefore(caption, table);
706
- }
707
- table.textContent = "";
708
- table.appendChild(head);
709
- table.appendChild(body);
710
- }
711
-
712
- return convertBlocks(root);
713
- }
714
-
715
- /**
716
- * Turndown joins a growing string at every sibling, repeatedly scanning the entire
717
- * prefix for trailing newlines. Convert independent blocks separately; keep inline,
718
- * list and table contexts together so their Markdown semantics remain intact.
719
- */
720
- function convertBlocks(root: HTMLElement): string {
721
- const containers = /^(BODY|DIV|MAIN|ARTICLE|SECTION|HEADER|FOOTER|ASIDE|NAV)$/;
722
- const block =
723
- /^(P|H[1-6]|UL|OL|PRE|TABLE|BLOCKQUOTE|DIV|SECTION|MAIN|ARTICLE|HR|DL|FIGURE|HEADER|FOOTER|ASIDE|NAV)$/;
724
- const children = Array.from(root.childNodes);
725
- if (
726
- containers.test(root.nodeName) &&
727
- children.every(
728
- (node) =>
729
- node.nodeType === 8 ||
730
- (node.nodeType === 3 && !node.textContent?.trim()) ||
731
- (node.nodeType === 1 && block.test(node.nodeName)),
732
- )
733
- ) {
734
- return children
735
- .filter((node): node is HTMLElement => node.nodeType === 1)
736
- .map(convertBlocks)
737
- .filter(Boolean)
738
- .join("\n\n");
739
- }
740
- // turndown(element) converts its children, not the element itself.
741
- const wrapper = root.ownerDocument.createElement("div");
742
- wrapper.appendChild(root.cloneNode(true));
743
- return markdown.turndown(wrapper).trim();
744
- }