hd-garden 0.10.1 → 0.10.3

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/README.en.md CHANGED
@@ -44,7 +44,17 @@ npx garden ui check --staged # Check staged posts for uncompi
44
44
  npx garden ui catalog # Generate an offline component gallery at .garden/ui-catalog.html
45
45
  ```
46
46
 
47
- ## 4. Handbook and reference docs
47
+ ## 4. Excalidraw
48
+
49
+ Point a Markdown image at the `.excalidraw` source. `garden build` exports one light flat SVG beside that file, with a transparent background, and embeds that SVG in the article so its text can be selected. No separate export command.
50
+
51
+ ```markdown
52
+ ![A sketch](./assets/flow.excalidraw)
53
+ ```
54
+
55
+ The first page that references `.excalidraw` downloads the exporter (Chromium is not required; fonts are embedded in the SVG). See [Local Image](docs/handbook/en/components/image.md).
56
+
57
+ ## 5. Handbook and reference docs
48
58
 
49
59
  Start `make dev` and open `/garden/en` (Chinese at `/garden`), or read the markdown sources directly:
50
60
 
package/README.md CHANGED
@@ -46,7 +46,17 @@ npx garden ui check --staged # 检查暂存区稿件中的想
46
46
  npx garden ui catalog # 在 .garden/ui-catalog.html 生成离线组件清单
47
47
  ```
48
48
 
49
- ## 4. 使用说明与深入文档
49
+ ## 4. Excalidraw
50
+
51
+ 正文用 Markdown 图片指向 `.excalidraw` 源文件。`garden build` 会在同目录导出一张浅色扁平 SVG,画布背景透明,并把这张 SVG 嵌进正文,图里的文字可以选中。不需要单独的导出命令。
52
+
53
+ ```markdown
54
+ ![说明](./assets/flow.excalidraw)
55
+ ```
56
+
57
+ 页面里第一次出现 `.excalidraw` 时,构建会下载导出程序(不需要 Chromium;字体写进 SVG)。说明见[本地图片](docs/handbook/components/image.md)。
58
+
59
+ ## 5. 使用说明与深入文档
50
60
 
51
61
  本地运行 `make dev` 后访问 `/garden`(英文版在 `/garden/en`),或直接阅读仓库内的文档:
52
62
 
@@ -45,10 +45,10 @@ export async function generateMetadata({
45
45
  images: post.cover ? [{ url: post.cover, alt: post.title }] : undefined,
46
46
  },
47
47
  twitter: {
48
- card: "summary_large_image",
48
+ card: post.cover ? "summary_large_image" : "summary",
49
49
  title: post.title,
50
50
  description: post.description,
51
- images: post.cover ? [post.cover] : ["/og.png"],
51
+ images: post.cover ? [post.cover] : undefined,
52
52
  },
53
53
  } satisfies Metadata;
54
54
  }
@@ -55,10 +55,10 @@ export async function generateMetadata({
55
55
  images: entry.cover ? [{ url: entry.cover, alt: entry.title }] : undefined,
56
56
  },
57
57
  twitter: {
58
- card: "summary_large_image",
58
+ card: entry.cover ? "summary_large_image" : "summary",
59
59
  title,
60
60
  description: entry.description,
61
- images: entry.cover ? [entry.cover] : ["/og.png"],
61
+ images: entry.cover ? [entry.cover] : undefined,
62
62
  },
63
63
  } satisfies Metadata;
64
64
  }
@@ -137,7 +137,7 @@ export function ArticleMeasure() {
137
137
  });
138
138
  // Images: as wide as they display (2x screenshots at half their pixels), up to 1040px in total.
139
139
  article.querySelectorAll<HTMLElement>(".fig").forEach((figure) => {
140
- const image = figure.querySelector("img");
140
+ const image = figure.querySelector<HTMLImageElement>("img, svg.excalidraw");
141
141
  resetWide(figure);
142
142
  // From here on the browser decides; the build-time breakout CSS steps aside.
143
143
  figure.classList.remove("fig-wide");
@@ -148,8 +148,9 @@ export function ArticleMeasure() {
148
148
  if (baseWidth) image.style.width = `${baseWidth}px`;
149
149
  else image.style.removeProperty("width");
150
150
  // Sizes read at build time let this run before the file arrives; otherwise wait for load.
151
+ // An inline Excalidraw SVG has no naturalWidth; its width attribute is the scene size.
151
152
  const known = Number(image.dataset.nw) || 0;
152
- const pixels = image.naturalWidth || known;
153
+ const pixels = image.naturalWidth || known || Number(image.getAttribute("width")) || 0;
153
154
  if (!pixels) return;
154
155
  // width="" written by the build is the pixel size, not an author's choice.
155
156
  const attrWidth = known ? Number(image.dataset.aw) || 0 : Number(image.getAttribute("width")) || 0;
@@ -64,8 +64,8 @@ export async function handbookOverviewMetadata(lang: HandbookLang, indexDoc: Gar
64
64
  images: [
65
65
  {
66
66
  url: "/og.png",
67
- width: 1731,
68
- height: 909,
67
+ width: 1200,
68
+ height: 630,
69
69
  alt: imageAlt,
70
70
  },
71
71
  ],
@@ -94,8 +94,8 @@ export async function handbookDocMetadata(lang: HandbookLang, doc: GardenDocEntr
94
94
  images: [
95
95
  {
96
96
  url: "/og.png",
97
- width: 1731,
98
- height: 909,
97
+ width: 1200,
98
+ height: 630,
99
99
  alt: fullTitle,
100
100
  },
101
101
  ],
@@ -125,8 +125,8 @@ export async function handbookDocMetadata(lang: HandbookLang, doc: GardenDocEntr
125
125
  images: [
126
126
  {
127
127
  url: "/og.png",
128
- width: 1731,
129
- height: 909,
128
+ width: 1200,
129
+ height: 630,
130
130
  alt: `${siteConfig.name} · ${docTitle}`,
131
131
  },
132
132
  ],
@@ -292,7 +292,7 @@ export function MarkdownArticle({ content, numbering, lang, fieldTables, refDemo
292
292
  <FaviconProvider favicons={linkAssets?.favicons}>
293
293
  <div className="markdown-body prose">
294
294
  <ReactMarkdown
295
- remarkPlugins={[...(refDemos ? [remarkRefDemos] : []), ...markdownPlugins, [remarkLinkCard, { sameSite }], [remarkA2, { imageSize: (src: string) => lookupImageSize(imageSizes, src), lang: lang ?? siteLang }]]}
295
+ remarkPlugins={[...(refDemos ? [remarkRefDemos] : []), ...markdownPlugins, remarkLinkCard, [remarkA2, { imageSize: (src: string) => lookupImageSize(imageSizes, src), lang: lang ?? siteLang }]]}
296
296
  rehypePlugins={[
297
297
  rehypeRaw,
298
298
  rehypeKatex,
@@ -311,11 +311,18 @@ export function MarkdownArticle({ content, numbering, lang, fieldTables, refDemo
311
311
  const only = nodes.length === 1 && isValidElement<{ href?: string; children?: ReactNode }>(nodes[0]) ? nodes[0] : null;
312
312
  const href = only?.props.href;
313
313
  const text = only ? headingText(only.props.children).trim() : "";
314
- if (href && text === href && /^https?:\/\//iu.test(href) && !sameSite(href)) return <LinkCard href={href} />;
314
+ // Bare http(s) URL alone in a paragraph → link card (same path for every jump link).
315
+ if (href && text === href && /^https?:\/\//iu.test(href)) return <LinkCard href={href} />;
315
316
  return <p {...domProps}>{children}</p>;
316
317
  },
317
318
  a: ({ href: written, children, ...props }) => {
318
- const { href, external } = articleLink(written, sameSite);
319
+ const label = headingText(children).trim();
320
+ // Bare URL jump links stay absolute so the paragraph card path is one pipeline
321
+ // for same-site and external alike. Titled same-site prose still uses Link.
322
+ const bareJump = Boolean(written && label === written && /^https?:\/\//iu.test(written));
323
+ const { href, external } = bareJump
324
+ ? { href: written as string, external: true }
325
+ : articleLink(written, sameSite);
319
326
  const domProps = { ...props };
320
327
  Reflect.deleteProperty(domProps, "node");
321
328
  // A link to another page of the site navigates in place, like the header and lists do.
package/app/layout.tsx CHANGED
@@ -49,9 +49,9 @@ export async function generateMetadata(): Promise<Metadata> {
49
49
  images: [
50
50
  {
51
51
  url: "/og.png",
52
- width: 1731,
53
- height: 909,
54
- alt: `${siteConfig.name} · ${siteConfig.pages.home.title.replace("\n", "")}`,
52
+ width: 1200,
53
+ height: 630,
54
+ alt: `${siteConfig.name} · ${siteConfig.tagline} · ${siteConfig.pages.home.title.replace("\n", "")}`,
55
55
  },
56
56
  ],
57
57
  },
@@ -11,7 +11,8 @@ import { toString } from "mdast-util-to-string";
11
11
  * paragraph (inside the same list item or quote).
12
12
  *
13
13
  * Cards are `garden-linkcard` elements carrying `data-url`, `data-text` and,
14
- * for the standalone form, `data-standalone`.
14
+ * for the standalone form, `data-standalone`. Every http(s) jump link that
15
+ * asks for a card uses this same path — same-site and external alike.
15
16
  */
16
17
 
17
18
  const MARKER = "{card}";
@@ -32,7 +33,7 @@ const meaningful = (children) =>
32
33
  children.filter((child) => !(child.type === "text" && !child.value.trim()) && child.type !== "break");
33
34
 
34
35
  /** Take the markers out of one parent's inline children; return the marked links. */
35
- function takeMarkers(parent, source, sameSite) {
36
+ function takeMarkers(parent, source) {
36
37
  const marked = [];
37
38
  const children = parent.children ?? [];
38
39
  for (let index = 0; index < children.length - 1; index += 1) {
@@ -41,14 +42,13 @@ function takeMarkers(parent, source, sameSite) {
41
42
  if (link.type !== "link" || next.type !== "text" || !next.value.startsWith(MARKER)) continue;
42
43
  if (!isHttp(link.url) || !writtenAsLink(link, source)) continue;
43
44
  next.value = next.value.slice(MARKER.length);
44
- // A link back to this site is an ordinary internal link: the marker goes, no card.
45
- if (!sameSite(link.url)) marked.push(link);
45
+ marked.push(link);
46
46
  }
47
47
  parent.children = children.filter((child) => !(child.type === "text" && child.value === ""));
48
48
  return marked;
49
49
  }
50
50
 
51
- function walk(parent, source, sameSite) {
51
+ function walk(parent, source) {
52
52
  const children = parent.children ?? [];
53
53
  for (let index = 0; index < children.length; index += 1) {
54
54
  const node = children[index];
@@ -56,14 +56,14 @@ function walk(parent, source, sameSite) {
56
56
  if (node.type !== "paragraph") {
57
57
  if (node.children) {
58
58
  // Headings, table cells and the like: drop the marker, no card.
59
- if (node.type === "heading" || node.type === "tableCell") takeMarkers(node, source, sameSite);
60
- walk(node, source, sameSite);
59
+ if (node.type === "heading" || node.type === "tableCell") takeMarkers(node, source);
60
+ walk(node, source);
61
61
  }
62
62
  continue;
63
63
  }
64
64
  // Links nested in emphasis count too.
65
- const marked = takeMarkers(node, source, sameSite);
66
- for (const child of node.children) if (child.children && child.type !== "link") marked.push(...takeMarkers(child, source, sameSite));
65
+ const marked = takeMarkers(node, source);
66
+ for (const child of node.children) if (child.children && child.type !== "link") marked.push(...takeMarkers(child, source));
67
67
  if (!marked.length) continue;
68
68
  const rest = meaningful(node.children);
69
69
  if (marked.length === 1 && rest.length === 1 && rest[0] === marked[0]) {
@@ -97,11 +97,10 @@ function markSources(parent, source) {
97
97
  parent.children = children.filter((child) => !(child.type === "text" && child.value === ""));
98
98
  }
99
99
 
100
- export function remarkLinkCard(options = {}) {
101
- const sameSite = typeof options?.sameSite === "function" ? options.sameSite : () => null;
100
+ export function remarkLinkCard() {
102
101
  return (tree, file) => {
103
102
  const source = typeof file?.value === "string" ? file.value : String(file?.value ?? "");
104
103
  markSources(tree, source);
105
- walk(tree, source, sameSite);
104
+ walk(tree, source);
106
105
  };
107
106
  }
package/app/styles/a2.css CHANGED
@@ -720,6 +720,19 @@ html[data-theme="dark"] .markdown-body > p > img:not([class]) {
720
720
  border-radius: 8px;
721
721
  }
722
722
 
723
+ .markdown-body .fig-card > svg.excalidraw,
724
+ .markdown-body svg.excalidraw {
725
+ display: block;
726
+ width: auto;
727
+ max-width: 100%;
728
+ height: auto;
729
+ margin: 0 auto;
730
+ }
731
+
732
+ .markdown-body svg.excalidraw text {
733
+ user-select: text;
734
+ }
735
+
723
736
  .markdown-body .fig figcaption {
724
737
  margin-top: 12px;
725
738
  font-size: var(--fs-small);
@@ -23,4 +23,14 @@ order: 45
23
23
 
24
24
  随想里的图片写在 Front Matter 的 `media` 中,多张拼成宫格,不使用这套图注。见[写文章与随想](/garden/writing)。
25
25
 
26
+ ## Excalidraw
27
+
28
+ `.excalidraw` 和别的配图放在一起。正文仍用 Markdown 图片,地址指向源文件,例如 `./my-post/flow.excalidraw`。没有单独的 garden 组件。
29
+
30
+ `garden build`、`make dev` 和 `garden sync` 会找出这些图片。源文件有改动,或旁边的 `.svg` 缺失、过期时,先删掉旧的 `.svg`,再导出一张新的扁平 SVG,里面不嵌可再编辑的场景。上面的例子会得到同目录的 `flow.svg`。只这一张浅色 SVG:画布背景透明,场景里的线条和填色保持绘制时的样子,不另出深色文件,也不做 CSS 反色。页面把这张 SVG 嵌进正文,图里的文字可以选中复制;说明写在 SVG 的 `title` 里。文章脚本不会加载 Excalidraw。
31
+
32
+ 导出程序是 [excalidraw-image](https://github.com/rickardp/excalidraw-image) `0.2.0`,走的是 Excalidraw 自己的 SVG 导出。第一次遇到 `.excalidraw` 时,构建从 GitHub Releases 下载对应系统的可执行文件(压缩包约 48MB)并缓存在本机。不需要安装 Chromium。字体写进 SVG,页面不请求 excalidraw.com。已经下载过,或用 `GARDEN_EXCALIDRAW_IMAGE` 指向本机程序时,离线构建(`GARDEN_OFFLINE` 设为 `1`)不会再次下载。
33
+
34
+ 源文件缺失,或导出失败时,构建直接停止,并写明路径和原因。
35
+
26
36
  这不是 `garden` 围栏,没有字段表。
@@ -1,12 +1,12 @@
1
1
  ---
2
- title: 外部链接卡片
2
+ title: 链接卡片
3
3
  navTitle: 链接卡片
4
- description: 把一条外部链接渲染成带网站名、标题和简介的卡片。
4
+ description: 把一条跳转链接渲染成带网站名、标题和简介的卡片。
5
5
  section: components
6
6
  order: 43
7
7
  ---
8
8
 
9
- 单独占一段的网址,或链接末尾紧跟 `{card}`,会渲染成链接卡片。正文里的普通外部链接不会变成卡片,例如 [Typora](https://typora.io/):只在文字前加站点 Favicon,右上角标 `↗`,图标与第一个字留在同一行。
9
+ 单独占一段的网址,或链接末尾紧跟 `{card}`,会渲染成链接卡片(同站与外站同一套逻辑)。正文里带标题的普通链接不会变成卡片,例如 [Typora](https://typora.io/):外站只在文字前加站点 Favicon,右上角标 `↗`,图标与第一个字留在同一行;同站标题链接仍在站内跳转。
10
10
 
11
11
  - **什么时候用**:希望读者点开之前先看到网站名、标题和简介。
12
12
  - **什么时候不用**:句子里只要标出出处时用[来源胶囊](/garden/components/source);要自己写几条要点时用[知识卡片](/garden/components/card)。
@@ -41,9 +41,9 @@ https://spec.commonmark.org/
41
41
 
42
42
  [KaTeX 支持的函数](https://katex.org/docs/supported.html){card}
43
43
 
44
- `{card}` 写在代码里会原样显示,例如 `[文字](https://example.com){card}`。标记和 `)` 之间有空格时也不会变成卡片。指向本站的链接会去掉标记,仍是站内链接。
44
+ `{card}` 写在代码里会原样显示,例如 `[文字](https://example.com){card}`。标记和 `)` 之间有空格时也不会变成卡片。同站与外站的跳链共用同一套卡片路径。
45
45
 
46
- 构建时读取正文里的 `{card}` 链接,把对方页面的标题、简介和封面记入 `link-assets.json`。单独一行的网址同样变成卡片,标题和简介用同一份记录;这个网址没有以 `{card}` 出现过时,卡片上显示网址本身。抓取失败就沿用上次的结果,构建不会因此中断。只刷新这些信息时运行 `npx garden links`。离线构建时把 `GARDEN_OFFLINE` 设为 `1` 会跳过拉取。
46
+ 构建时读取正文里的 `{card}` 链接,以及单独成段的网址,把对方页面的标题、简介和封面记入 `link-assets.json`(同站与外站同一套抓取;HTML meta refresh 会跟着跳到目标页再读 OG)。抓取失败就沿用上次的结果,构建不会因此中断。只刷新这些信息时运行 `npx garden links`。离线构建时把 `GARDEN_OFFLINE` 设为 `1` 会跳过拉取。
47
47
 
48
48
  随想 Front Matter 里的 `type: link` 用你写的 `title`、`description` 和 `image`,字段见[写文章与随想](/garden/writing)。
49
49
 
@@ -23,4 +23,14 @@ The caption under this figure is its alt text:
23
23
 
24
24
  Images on a thought go in the `media` list in Front Matter and form a grid, without this caption. See [Writing Posts & Thoughts](/garden/en/writing).
25
25
 
26
+ ## Excalidraw
27
+
28
+ Put the `.excalidraw` file with the post's other images. Keep using a Markdown image, and point the address at the source file, for example `./my-post/flow.excalidraw`. There is no separate garden component for this.
29
+
30
+ `garden build`, `make dev`, and `garden sync` find those images. When the source has changed, or the sibling `.svg` is missing or out of date, the old `.svg` is deleted and a new flat SVG is exported, with no editable scene embedded. The example above produces `flow.svg` in the same directory. That is the only export: one light SVG with a transparent canvas. Strokes and fills stay as drawn. There is no dark file and no CSS invert. The page embeds that SVG in the article, so the text in the figure can be selected and copied. The alt text is the SVG `title`. The article never loads Excalidraw.
31
+
32
+ The exporter is [excalidraw-image](https://github.com/rickardp/excalidraw-image) `0.2.0`, which runs Excalidraw's own SVG export. The first `.excalidraw` reference downloads the matching executable from GitHub Releases (about 48 MB compressed) and caches it on the machine. Chromium is not required. Fonts are written into the SVG, so the page does not request excalidraw.com. After that download, or when `GARDEN_EXCALIDRAW_IMAGE` points at a local binary, an offline build (`GARDEN_OFFLINE` set to `1`) does not download again.
33
+
34
+ A missing source file or a failed export stops the build and reports the path and the reason.
35
+
26
36
  This is not a `garden` fence, so it has no field table.
@@ -1,12 +1,12 @@
1
1
  ---
2
- title: External Link Card
2
+ title: Link Card
3
3
  navTitle: Link card
4
- description: Render an external URL as a card with the site name, title, and summary.
4
+ description: Render a jump URL as a card with the site name, title, and summary.
5
5
  section: components
6
6
  order: 43
7
7
  ---
8
8
 
9
- A URL on its own paragraph, or a link followed immediately by `{card}`, renders as a link card. An ordinary external link in prose stays a link, such as [Typora](https://typora.io/): it shows the site favicon before the text and a `↗` at the upper right, and the icon stays on the same line as the first word.
9
+ A URL on its own paragraph, or a link followed immediately by `{card}`, renders as a link card (same-site and external share one path). An ordinary titled link in prose stays a link, such as [Typora](https://typora.io/): an external one shows the site favicon before the text and a `↗` at the upper right; a titled same-site link still navigates in place.
10
10
 
11
11
  - **When to use**: The reader should see the site name, title, and summary before opening the page.
12
12
  - **When to skip**: Use a [source chip](/garden/en/components/source) to cite a site inside a sentence, or a [reference card](/garden/en/components/card) when you are writing the takeaways yourself.
@@ -41,9 +41,9 @@ When the paragraph is only the marked link, that line becomes the card:
41
41
 
42
42
  [Supported KaTeX functions](https://katex.org/docs/supported.html){card}
43
43
 
44
- `{card}` inside code stays as written, for example `[text](https://example.com){card}`. A space between `)` and the marker also leaves an ordinary link. A link back to this site drops the marker and stays an internal link.
44
+ `{card}` inside code stays as written, for example `[text](https://example.com){card}`. A space between `)` and the marker also leaves an ordinary link. Same-site and external jump links share one card path.
45
45
 
46
- At build time, Garden reads `{card}` links in the body and stores the page title, summary, and image in `link-assets.json`. A URL on its own line becomes a card too, using that same record; when the URL has never appeared as `{card}`, the card shows the URL itself. A failed fetch keeps the previous record, and the build continues. Run `npx garden links` to refresh just these records. Set `GARDEN_OFFLINE` to `1` to skip the fetch during an offline build.
46
+ At build time, Garden reads `{card}` links and URLs that stand alone as a paragraph, and stores the page title, summary, and image in `link-assets.json` (same-site and external share one fetch path; HTML meta refresh is followed to the target before reading OG). A failed fetch keeps the previous record, and the build continues. Run `npx garden links` to refresh just these records. Set `GARDEN_OFFLINE` to `1` to skip the fetch during an offline build.
47
47
 
48
48
  A thought can also carry an external link in Front Matter with `type: link`, using the `title`, `description`, and `image` you write. Those fields are in [Writing Posts & Thoughts](/garden/en/writing).
49
49
 
@@ -115,6 +115,7 @@ func openStore(path string) (*Store, error) {
115
115
  These three are written in the Markdown body. Rendering rules live on the component pages. This section only records where the files go:
116
116
 
117
117
  - **Local images**: For a post at `content/posts/my-post.md`, put images in `content/posts/my-post/` and reference them as `./my-post/diagram.svg`. Captions are documented on [Local Image](/garden/en/components/image).
118
+ - **Excalidraw**: Put the source with the other images and reference it with a Markdown image whose address ends in `.excalidraw`, for example `./my-post/flow.excalidraw`. The build writes one light `flow.svg` beside it, with a transparent background, and embeds that SVG in the article so its text can be selected. See [Local Image](/garden/en/components/image).
118
119
  - **Source chips** and **link cards** stay in the prose. See [Source Chip](/garden/en/components/source) and [Link Card](/garden/en/components/link-card).
119
120
 
120
121
  ## 5. Math Formulas and Mermaid Diagrams
@@ -115,6 +115,7 @@ func openStore(path string) (*Store, error) {
115
115
  这三项写在 Markdown 正文里。渲染规则在组件页,这里只保留文件放哪:
116
116
 
117
117
  - **本地图片**:长文 `content/posts/my-post.md` 的配图放在同名目录 `content/posts/my-post/`,正文用 `./my-post/diagram.svg` 引用。图注见[本地图片](/garden/components/image)。
118
+ - **Excalidraw**:源文件和配图放在一起,用 Markdown 图片引用,地址以 `.excalidraw` 结尾,例如 `./my-post/flow.excalidraw`。构建生成旁边的一张浅色 `flow.svg`,画布背景透明,并把 SVG 嵌进正文,图里的文字可以选中。见[本地图片](/garden/components/image)。
118
119
  - **来源胶囊**与**链接卡片**不另建文件。见[来源胶囊](/garden/components/source)和[链接卡片](/garden/components/link-card)。
119
120
 
120
121
  ## 5. 数学公式与 Mermaid 图表
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hd-garden",
3
- "version": "0.10.1",
3
+ "version": "0.10.3",
4
4
  "private": false,
5
5
  "description": "用 Markdown 写作、用 GitHub Pages 发布的个人博客引擎。",
6
6
  "license": "MIT",
package/public/og.png CHANGED
Binary file
@@ -12,13 +12,15 @@ import { referenceDomain } from "../ui/garden/references.mjs";
12
12
  import { linkAssetsForRender } from "./link-assets.mjs";
13
13
  import { cardUrls } from "../ui/garden/markdown-links.mjs";
14
14
  import { formatInlineLink, replaceInlineLinks } from "../ui/garden/markdown-destination.mjs";
15
- import { configuredSiteAddress, sameSiteMatcher } from "../ui/garden/same-site.mjs";
15
+ import { configuredSiteAddress } from "../ui/garden/same-site.mjs";
16
16
  import { resolveBrand } from "./brand.mjs";
17
17
  import { imageSources, readImageCache, sizeFromBytes } from "./image-sizes.mjs";
18
18
  import { buildFullIndex, buildSearchIndex } from "../ui/garden/search-index.mjs";
19
19
  import { coverImageSet, loadSharp } from "./cover-images.mjs";
20
20
  import { readFileSizeCache } from "./file-sizes.mjs";
21
21
  import { previewDocument, previewFileName, renderFilePreview } from "./file-preview.mjs";
22
+ import { ensureExcalidrawSvg, isExcalidrawPath } from "./excalidraw.mjs";
23
+ import { embedExcalidrawImages, embedExcalidrawImgTags } from "../ui/garden/excalidraw-inline.mjs";
22
24
  import { parseGardenBlock, parseGardenInfo, scanFences } from "../ui/garden/parse.mjs";
23
25
  import { checkGardenMarkdown } from "../ui/garden/check.mjs";
24
26
  import {
@@ -74,7 +76,6 @@ const publicBaseUrl = basePath && !siteUrl.endsWith(basePath)
74
76
  : siteUrl;
75
77
  // Full URLs to this address are internal links: no new tab, no card.
76
78
  const siteAddress = configuredSiteAddress(siteConfig, process.env);
77
- const sameSite = sameSiteMatcher(siteAddress, basePath);
78
79
  const siteName = process.env.SITE_NAME ?? siteConfig.name;
79
80
  const siteDescription = process.env.SITE_DESCRIPTION ?? siteConfig.description;
80
81
  const siteLang = /^en/iu.test(String(siteConfig.locale ?? "")) ? "en" : "zh";
@@ -153,23 +154,40 @@ const assetCache = new Map();
153
154
  /** Published URL → original file and its copy, for making resized covers later. */
154
155
  const assetFiles = new Map();
155
156
 
156
- function copyLocalAsset(value, markdownPath, sourcePath, options = {}) {
157
- if (!value || isExternalAsset(value)) return value;
158
-
157
+ function locateLocalAsset(value, markdownPath, sourcePath, options = {}) {
158
+ if (!value || isExternalAsset(value)) return null;
159
159
  const baseDir = options.baseDir ?? path.dirname(markdownPath);
160
160
  const allowedRoot = options.allowedRoot ?? contentRoot;
161
- const mediaPrefix = options.mediaPrefix ?? "";
162
161
  const [assetPath, suffix = ""] = value.split(/(?=[?#])/u, 2);
163
162
  const decodedPath = decodeURIComponent(assetPath.replace(/^<|>$/g, ""));
164
163
  const absoluteSource = path.resolve(baseDir, decodedPath);
165
164
  const relativeSource = path.relative(allowedRoot, absoluteSource);
165
+ if (relativeSource.startsWith("..") || path.isAbsolute(relativeSource)) {
166
+ fail(sourcePath, options.missingMessage ?? `找不到本地媒体文件 ${value}`);
167
+ }
168
+ return { absoluteSource, relativeSource, decodedPath, suffix, mediaPrefix: options.mediaPrefix ?? "" };
169
+ }
166
170
 
167
- if (
168
- relativeSource.startsWith("..") ||
169
- path.isAbsolute(relativeSource) ||
170
- !fs.existsSync(absoluteSource) ||
171
- !fs.statSync(absoluteSource).isFile()
172
- ) {
171
+ /** Export the sibling flat SVG and return its text. The page inlines this; it is not an image URL. */
172
+ function readExportedSvg(value, markdownPath, sourcePath, options = {}) {
173
+ const located = locateLocalAsset(value, markdownPath, sourcePath, options);
174
+ if (!located || !isExcalidrawPath(located.decodedPath)) {
175
+ fail(sourcePath, `找不到 Excalidraw 源文件 ${value}`);
176
+ }
177
+ try {
178
+ const svgPath = ensureExcalidrawSvg(located.absoluteSource);
179
+ return fs.readFileSync(svgPath, "utf8");
180
+ } catch (error) {
181
+ fail(sourcePath, error instanceof Error ? error.message : String(error));
182
+ }
183
+ }
184
+
185
+ function copyLocalAsset(value, markdownPath, sourcePath, options = {}) {
186
+ const located = locateLocalAsset(value, markdownPath, sourcePath, options);
187
+ if (!located) return value;
188
+ const { absoluteSource, relativeSource, suffix, mediaPrefix } = located;
189
+
190
+ if (!fs.existsSync(absoluteSource) || !fs.statSync(absoluteSource).isFile()) {
173
191
  fail(sourcePath, options.missingMessage ?? `找不到本地媒体文件 ${value}`);
174
192
  }
175
193
 
@@ -195,15 +213,21 @@ function copyLocalAsset(value, markdownPath, sourcePath, options = {}) {
195
213
  function rewriteMarkdownAssets(content, markdownPath, sourcePath, options = {}) {
196
214
  // `![alt](<a b (1).png>)` keeps its angle brackets: without them the space
197
215
  // and the parentheses would no longer be one destination.
198
- const markdownImages = replaceInlineLinks(content, (link) =>
199
- link.image ? formatInlineLink(link, copyLocalAsset(link.url, markdownPath, sourcePath, options)) : undefined,
200
- );
216
+ // `.excalidraw` images stay in the source until the AST embed below, which
217
+ // swaps them for the inline SVG instead of an image URL.
218
+ const markdownImages = replaceInlineLinks(content, (link) => {
219
+ if (!link.image || isExcalidrawPath(link.url)) return undefined;
220
+ return formatInlineLink(link, copyLocalAsset(link.url, markdownPath, sourcePath, options));
221
+ });
201
222
 
202
- return markdownImages.replace(
223
+ const withAssets = markdownImages.replace(
203
224
  /(<(?:img|audio|video|source)\b[^>]*\bsrc=["'])([^"']+)(["'])/giu,
204
- (_, prefix, src, suffix) =>
205
- `${prefix}${copyLocalAsset(src, markdownPath, sourcePath, options)}${suffix}`,
225
+ (tag, prefix, src, suffix) =>
226
+ isExcalidrawPath(src) ? tag : `${prefix}${copyLocalAsset(src, markdownPath, sourcePath, options)}${suffix}`,
206
227
  );
228
+
229
+ const read = (url) => readExportedSvg(url, markdownPath, sourcePath, options);
230
+ return embedExcalidrawImgTags(embedExcalidrawImages(withAssets, read), read);
207
231
  }
208
232
 
209
233
  function markdownStem(markdownPath) {
@@ -997,7 +1021,7 @@ const sitemapEntries = [
997
1021
  // Card URLs in published entries: the only pages the link-card Worker may read.
998
1022
  fs.writeFileSync(
999
1023
  path.join(publicRoot, "link-allowlist.json"),
1000
- `${JSON.stringify({ urls: [...new Set([...posts, ...columns, ...thoughts].flatMap((entry) => cardUrls(entry.content)).filter((url) => !sameSite(url)))].sort() }, null, 2)}\n`,
1024
+ `${JSON.stringify({ urls: [...new Set([...posts, ...columns, ...thoughts].flatMap((entry) => cardUrls(entry.content)))].sort() }, null, 2)}\n`,
1001
1025
  );
1002
1026
  fs.writeFileSync(path.join(publicRoot, "sitemap.xml"), `<?xml version="1.0" encoding="UTF-8" ?>
1003
1027
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">${sitemapEntries.map((entry) => `
@@ -0,0 +1,372 @@
1
+ /**
2
+ * Build-time export of `.excalidraw` scenes to a sibling flat SVG.
3
+ *
4
+ * Authors reference the source (`![说明](./assets/foo.excalidraw)`). Content
5
+ * sync calls `ensureExcalidrawSvg`, which deletes a missing or stale sibling
6
+ * `foo.svg` and writes a new one. The SVG is what gets published.
7
+ *
8
+ * Rendering goes through the pinned `excalidraw-image` binary (the official
9
+ * `@excalidraw/excalidraw` export path, fonts inlined as data URIs). One light
10
+ * SVG is written: `--no-background` drops the canvas plate, and scene strokes
11
+ * and fills stay as drawn. There is no dark twin and no Chromium step. The
12
+ * article bundle never loads Excalidraw. The first export downloads that
13
+ * binary from GitHub Releases into the user cache.
14
+ * `GARDEN_EXCALIDRAW_IMAGE` points at a local binary instead.
15
+ * `GARDEN_OFFLINE=1` refuses to download.
16
+ */
17
+ import { spawnSync } from "node:child_process";
18
+ import crypto from "node:crypto";
19
+ import fs from "node:fs";
20
+ import os from "node:os";
21
+ import path from "node:path";
22
+
23
+ export const EXCALIDRAW_IMAGE_VERSION = "0.2.0";
24
+
25
+ const RELEASE_BASE = `https://github.com/rickardp/excalidraw-image/releases/download/v${EXCALIDRAW_IMAGE_VERSION}`;
26
+
27
+ /** @type {Record<string, { file: string, sha256: string }>} */
28
+ const ASSETS = {
29
+ "darwin-arm64": {
30
+ file: "excalidraw-image-aarch64-apple-darwin.tar.gz",
31
+ sha256: "387f7ef44a75528e4c6cca9f0af4bba34e017986f34581d983bb2a96afb5d9ba",
32
+ },
33
+ "darwin-x64": {
34
+ file: "excalidraw-image-x86_64-apple-darwin.tar.gz",
35
+ sha256: "bef1198f6237123ecc7f63c1fc6a456413e5f6cc91ae4c548dc26d661066fc21",
36
+ },
37
+ "linux-arm64": {
38
+ file: "excalidraw-image-aarch64-unknown-linux-gnu.tar.gz",
39
+ sha256: "c6b222e128965568e281af96edfa437393b2ddb4e3ba360ec2b9b583f273143e",
40
+ },
41
+ "linux-x64": {
42
+ file: "excalidraw-image-x86_64-unknown-linux-gnu.tar.gz",
43
+ sha256: "6a86f5188b55aef092d9cedda786565bfdb399bb58e57a1bea26335ed8f19ac6",
44
+ },
45
+ "win32-x64": {
46
+ file: "excalidraw-image-x86_64-pc-windows-msvc.zip",
47
+ sha256: "19b387b2322d3b52f8003d2e8bea9ab5693086c5886986f86b5ac6c36009aeef",
48
+ },
49
+ };
50
+
51
+ const REASONS = {
52
+ "missing-source": "找不到 Excalidraw 源文件",
53
+ "export-failed": "导出 Excalidraw 失败",
54
+ offline: "离线构建找不到 excalidraw-image",
55
+ "download-failed": "下载 excalidraw-image 失败",
56
+ checksum: "excalidraw-image 校验和不匹配",
57
+ "embedded-scene": "导出的 SVG 仍包含可编辑场景",
58
+ "remote-asset": "导出的 SVG 引用了外部地址",
59
+ "not-svg": "导出结果不是 SVG",
60
+ "canvas-background": "导出的 SVG 仍带画布底色",
61
+ "unsupported-platform": "当前系统没有 excalidraw-image 预编译包",
62
+ "binary-missing": "GARDEN_EXCALIDRAW_IMAGE 指向的文件不存在",
63
+ "no-output": "导出程序没有写出 SVG",
64
+ };
65
+
66
+ const EXPORT_POLICY = "light-transparent";
67
+ const STAMP = /<!--\s*garden-excalidraw-source:([0-9a-f]{64})(?:\s+([a-z0-9-]+))?\s*-->/u;
68
+ const LOCK_WAIT_MS = 5 * 60 * 1000;
69
+
70
+ export class ExcalidrawExportError extends Error {
71
+ /**
72
+ * @param {keyof typeof REASONS} code
73
+ * @param {string} message
74
+ * @param {string} file
75
+ */
76
+ constructor(code, message, file) {
77
+ super(message);
78
+ this.name = "ExcalidrawExportError";
79
+ this.code = code;
80
+ this.file = file;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * @param {keyof typeof REASONS} code
86
+ * @param {string} file
87
+ * @param {string} [detail]
88
+ */
89
+ function failExport(code, file, detail) {
90
+ const lead = REASONS[code];
91
+ if (!lead) {
92
+ const unknown = /** @type {never} */ (code);
93
+ throw new Error(`未知的 Excalidraw 错误码 ${unknown}`);
94
+ }
95
+ const tail = detail ? `(${detail})` : "";
96
+ return new ExcalidrawExportError(code, `[excalidraw:${code}] ${lead} ${file}${tail}`, file);
97
+ }
98
+
99
+ /** sha256 of the `.excalidraw` bytes. Any edit changes the stamp. */
100
+ export function sourceHash(contents) {
101
+ return crypto.createHash("sha256").update(contents).digest("hex");
102
+ }
103
+
104
+ /** `flow.excalidraw` → `flow.svg` beside it. The extension match is case-insensitive. */
105
+ export function siblingSvgPath(excalidrawPath) {
106
+ return String(excalidrawPath).replace(/\.excalidraw$/iu, ".svg");
107
+ }
108
+
109
+ /** True for a Markdown path whose file is an `.excalidraw` source, not an `.excalidraw.svg`. */
110
+ export function isExcalidrawPath(value) {
111
+ const clean = String(value ?? "").split(/[?#]/u, 1)[0];
112
+ return /\.excalidraw$/iu.test(clean);
113
+ }
114
+
115
+ function stampSvg(svg, hash) {
116
+ const stripped = svg.replace(/<!--\s*garden-excalidraw-source:[0-9a-f]{64}(?:\s+[a-z0-9-]+)?\s*-->/gu, "");
117
+ const at = stripped.search(/<svg[\s>]/iu);
118
+ if (at < 0) throw failExport("not-svg", "");
119
+ return `${stripped.slice(0, at)}<!-- garden-excalidraw-source:${hash} ${EXPORT_POLICY} -->${stripped.slice(at)}`;
120
+ }
121
+
122
+ /** A full-viewport `<rect>` is the exporter's canvas plate, not a scene shape. */
123
+ function hasCanvasBackground(svg) {
124
+ const svgTag = /<svg\b[^>]*>/iu.exec(svg)?.[0] ?? "";
125
+ const attr = (tag, name) => new RegExp(`\\b${name}="([^"]*)"`, "iu").exec(tag)?.[1];
126
+ const width = Number(attr(svgTag, "width"));
127
+ const height = Number(attr(svgTag, "height"));
128
+ if (!(width > 0) || !(height > 0)) return false;
129
+ const same = (left, right) => Math.abs(left - right) < 0.01;
130
+ for (const match of svg.matchAll(/<rect\b[^>]*>/giu)) {
131
+ const tag = match[0];
132
+ const x = Number(attr(tag, "x") ?? 0);
133
+ const y = Number(attr(tag, "y") ?? 0);
134
+ const rectWidth = Number(attr(tag, "width"));
135
+ const rectHeight = Number(attr(tag, "height"));
136
+ if (same(x, 0) && same(y, 0) && same(rectWidth, width) && same(rectHeight, height)) return true;
137
+ }
138
+ return false;
139
+ }
140
+
141
+ /**
142
+ * A published figure must be a flat SVG: no embedded scene, no host the
143
+ * reader's browser would have to call.
144
+ * @param {string} svg
145
+ * @param {string} svgPath
146
+ */
147
+ function assertFlatSvg(svg, svgPath) {
148
+ if (!/<svg[\s>]/iu.test(svg)) throw failExport("not-svg", svgPath);
149
+ if (/payload-start|application\/vnd\.excalidraw\+json/iu.test(svg)) {
150
+ throw failExport("embedded-scene", svgPath);
151
+ }
152
+ if (hasCanvasBackground(svg)) throw failExport("canvas-background", svgPath);
153
+ const urls = [...svg.matchAll(/https?:\/\/[^"')\s]+/giu)]
154
+ .map((match) => match[0])
155
+ .filter((url) => !/^https?:\/\/www\.w3\.org\//iu.test(url));
156
+ if (urls.length) throw failExport("remote-asset", svgPath, urls.slice(0, 3).join(" "));
157
+ }
158
+
159
+ function svgIsCurrent(svg, hash) {
160
+ const stamp = STAMP.exec(svg);
161
+ if (!stamp || stamp[1] !== hash || stamp[2] !== EXPORT_POLICY) return false;
162
+ try {
163
+ assertFlatSvg(svg, "");
164
+ return true;
165
+ } catch {
166
+ return false;
167
+ }
168
+ }
169
+
170
+ function platformKey() {
171
+ return `${process.platform}-${process.arch}`;
172
+ }
173
+
174
+ function platformAsset() {
175
+ const asset = ASSETS[platformKey()];
176
+ if (!asset) {
177
+ throw failExport(
178
+ "unsupported-platform",
179
+ `${process.platform} ${process.arch}`,
180
+ "设置 GARDEN_EXCALIDRAW_IMAGE 指向本机的 excalidraw-image",
181
+ );
182
+ }
183
+ return asset;
184
+ }
185
+
186
+ /**
187
+ * @param {{ homedir?: string }} [options]
188
+ */
189
+ function cachePath(options = {}) {
190
+ const home = options.homedir ?? os.homedir();
191
+ const exe = process.platform === "win32" ? "excalidraw-image.exe" : "excalidraw-image";
192
+ return path.join(home, ".cache", "garden", "excalidraw-image", EXCALIDRAW_IMAGE_VERSION, platformKey(), exe);
193
+ }
194
+
195
+ function sleep(ms) {
196
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
197
+ }
198
+
199
+ function withLock(lockDir, fn) {
200
+ fs.mkdirSync(path.dirname(lockDir), { recursive: true });
201
+ const deadline = Date.now() + LOCK_WAIT_MS;
202
+ for (;;) {
203
+ try {
204
+ fs.mkdirSync(lockDir);
205
+ break;
206
+ } catch (error) {
207
+ if (error?.code !== "EEXIST") throw error;
208
+ let stale = false;
209
+ try {
210
+ stale = Date.now() - fs.statSync(lockDir).mtimeMs > LOCK_WAIT_MS;
211
+ } catch {
212
+ stale = true;
213
+ }
214
+ if (stale) {
215
+ fs.rmSync(lockDir, { recursive: true, force: true });
216
+ continue;
217
+ }
218
+ if (Date.now() > deadline) throw failExport("download-failed", lockDir, "等待下载锁超时");
219
+ sleep(100);
220
+ }
221
+ }
222
+ try {
223
+ return fn();
224
+ } finally {
225
+ fs.rmSync(lockDir, { recursive: true, force: true });
226
+ }
227
+ }
228
+
229
+ function run(command, args, { timeout = 120_000 } = {}) {
230
+ return spawnSync(command, args, {
231
+ encoding: "utf8",
232
+ timeout,
233
+ maxBuffer: 32 * 1024 * 1024,
234
+ windowsHide: true,
235
+ });
236
+ }
237
+
238
+ function commandFailure(result, fallback) {
239
+ if (result.error) return result.error.message;
240
+ return (result.stderr || result.stdout || fallback).trim();
241
+ }
242
+
243
+ function findExportedBinary(dir) {
244
+ const names = new Set(["excalidraw-image", "excalidraw-image.exe"]);
245
+ const found = [];
246
+ const stack = [dir];
247
+ while (stack.length) {
248
+ const current = stack.pop();
249
+ if (!current) break;
250
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
251
+ const full = path.join(current, entry.name);
252
+ if (entry.isDirectory()) stack.push(full);
253
+ else if (names.has(entry.name)) found.push(full);
254
+ }
255
+ }
256
+ if (found.length !== 1) {
257
+ throw failExport("download-failed", dir, `压缩包里应有一个 excalidraw-image,实际 ${found.length} 个`);
258
+ }
259
+ return found[0];
260
+ }
261
+
262
+ /**
263
+ * @param {{ homedir?: string, env?: NodeJS.ProcessEnv }} options
264
+ */
265
+ function installBinary(options) {
266
+ const asset = platformAsset();
267
+ const cached = cachePath(options);
268
+ return withLock(`${cached}.lock`, () => {
269
+ if (fs.existsSync(cached)) return cached;
270
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "garden-excalidraw-"));
271
+ try {
272
+ const archive = path.join(work, asset.file);
273
+ const url = `${RELEASE_BASE}/${asset.file}`;
274
+ console.error(`正在下载 excalidraw-image ${EXCALIDRAW_IMAGE_VERSION}(${asset.file})…`);
275
+ const curl = run("curl", ["-fsSL", "--retry", "3", "--retry-delay", "2", "-o", archive, url]);
276
+ if (curl.status !== 0) throw failExport("download-failed", url, commandFailure(curl, "curl 失败"));
277
+ const got = crypto.createHash("sha256").update(fs.readFileSync(archive)).digest("hex");
278
+ if (got !== asset.sha256) throw failExport("checksum", asset.file, `期望 ${asset.sha256},实际 ${got}`);
279
+ const unpacked = path.join(work, "unpacked");
280
+ fs.mkdirSync(unpacked, { recursive: true });
281
+ const extracted = run("tar", ["-xf", archive, "-C", unpacked]);
282
+ if (extracted.status !== 0) {
283
+ throw failExport("download-failed", archive, commandFailure(extracted, "tar 无法解压"));
284
+ }
285
+ const bin = findExportedBinary(unpacked);
286
+ fs.mkdirSync(path.dirname(cached), { recursive: true });
287
+ const partial = `${cached}.partial`;
288
+ fs.copyFileSync(bin, partial);
289
+ fs.chmodSync(partial, 0o755);
290
+ const version = run(partial, ["--version"]);
291
+ if (version.status !== 0 || !/excalidraw-image/u.test(version.stdout || "")) {
292
+ fs.rmSync(partial, { force: true });
293
+ throw failExport("download-failed", partial, commandFailure(version, "excalidraw-image --version 失败"));
294
+ }
295
+ fs.renameSync(partial, cached);
296
+ return cached;
297
+ } finally {
298
+ fs.rmSync(work, { recursive: true, force: true });
299
+ }
300
+ });
301
+ }
302
+
303
+ /**
304
+ * @param {{ homedir?: string, env?: NodeJS.ProcessEnv }} [options]
305
+ */
306
+ function resolveBinary(options = {}) {
307
+ const env = options.env ?? process.env;
308
+ const override = env.GARDEN_EXCALIDRAW_IMAGE?.trim();
309
+ if (override) {
310
+ if (!fs.existsSync(override)) throw failExport("binary-missing", override);
311
+ return override;
312
+ }
313
+ platformAsset();
314
+ const cached = cachePath(options);
315
+ if (fs.existsSync(cached)) return cached;
316
+ if (env.GARDEN_OFFLINE === "1") throw failExport("offline", cached);
317
+ return installBinary(options);
318
+ }
319
+
320
+ let defaultBinary = "";
321
+
322
+ /**
323
+ * @param {string} input
324
+ * @param {string} output
325
+ * @param {{ homedir?: string, env?: NodeJS.ProcessEnv }} [options]
326
+ */
327
+ function renderWithBinary(input, output, options = {}) {
328
+ const custom = options.env !== undefined || options.homedir !== undefined;
329
+ const bin = !custom && defaultBinary && fs.existsSync(defaultBinary) ? defaultBinary : resolveBinary(options);
330
+ if (!custom) defaultBinary = bin;
331
+ const result = run(bin, [input, "--non-editable", "--no-background", "--format", "svg", "-o", output]);
332
+ if (result.status !== 0) {
333
+ throw failExport("export-failed", input, commandFailure(result, `退出码 ${result.status}`).slice(0, 800));
334
+ }
335
+ }
336
+
337
+ /**
338
+ * Write a current flat SVG next to `sourcePath`.
339
+ * A sibling SVG is reused only when it carries this source's hash and is flat.
340
+ * Otherwise it is deleted, then exported again. Export failure leaves no SVG.
341
+ *
342
+ * @param {string} sourcePath
343
+ * @param {{ render?: (input: string, output: string) => void, homedir?: string, env?: NodeJS.ProcessEnv }} [options]
344
+ * @returns {string} absolute path of the sibling SVG
345
+ */
346
+ export function ensureExcalidrawSvg(sourcePath, options = {}) {
347
+ if (!fs.existsSync(sourcePath) || !fs.statSync(sourcePath).isFile()) {
348
+ throw failExport("missing-source", sourcePath);
349
+ }
350
+ const svgPath = siblingSvgPath(sourcePath);
351
+ if (svgPath === sourcePath) throw failExport("not-svg", sourcePath, "无法把源文件路径换成 .svg");
352
+ const hash = sourceHash(fs.readFileSync(sourcePath));
353
+ if (fs.existsSync(svgPath)) {
354
+ const current = fs.readFileSync(svgPath, "utf8");
355
+ if (svgIsCurrent(current, hash)) return svgPath;
356
+ fs.rmSync(svgPath, { force: true });
357
+ }
358
+ const render = options.render ?? ((input, output) => renderWithBinary(input, output, options));
359
+ try {
360
+ render(sourcePath, svgPath);
361
+ if (!fs.existsSync(svgPath) || !fs.statSync(svgPath).isFile()) throw failExport("no-output", svgPath);
362
+ const raw = fs.readFileSync(svgPath, "utf8");
363
+ assertFlatSvg(raw, svgPath);
364
+ fs.writeFileSync(svgPath, stampSvg(raw, hash));
365
+ } catch (error) {
366
+ fs.rmSync(svgPath, { force: true });
367
+ if (error instanceof ExcalidrawExportError) throw error;
368
+ const reason = error instanceof Error ? error.message : String(error);
369
+ throw failExport("export-failed", sourcePath, reason);
370
+ }
371
+ return svgPath;
372
+ }
@@ -16,7 +16,7 @@ import { isIP } from "node:net";
16
16
  import path from "node:path";
17
17
  import { pathToFileURL } from "node:url";
18
18
  import matter from "gray-matter";
19
- import { fetchFavicon, fetchImage, fetchPageMeta, isPublicUrl, linkHost } from "./link-meta-core.mjs";
19
+ import { fetchFavicon, fetchImage, fetchPageMeta, isPublicUrl, isSiteBrandOgImage, linkHost } from "./link-meta-core.mjs";
20
20
  import { parse as parseYaml } from "yaml";
21
21
  import { markdownLinks } from "../ui/garden/markdown-links.mjs";
22
22
  import { gardenSourceUrls } from "../ui/garden/source-icon.mjs";
@@ -60,10 +60,11 @@ function readSiteConfig(siteRoot) {
60
60
  }
61
61
  }
62
62
 
63
- /** External links across every post: the sites (for favicons) and the URLs. */
63
+ /** Jump links across every post: the sites (for favicons) and the URLs. */
64
64
  export function collectSiteLinks(siteRoot, env = process.env) {
65
65
  const config = readSiteConfig(siteRoot);
66
- // Links back to this site are internal: no favicon, no card.
66
+ // Ordinary same-site prose links need no favicon fetch. Card URLs — same-site
67
+ // or external — share one OG/link-assets path.
67
68
  const sameSite = sameSiteMatcher(configuredSiteAddress(config, env), env.NEXT_PUBLIC_BASE_PATH ?? "");
68
69
  const hosts = new Map();
69
70
  const cards = new Set();
@@ -71,7 +72,8 @@ export function collectSiteLinks(siteRoot, env = process.env) {
71
72
  for (const file of markdownFiles(path.join(siteRoot, "content"))) {
72
73
  const { content } = matter(fs.readFileSync(file, "utf8"));
73
74
  for (const { url, card } of markdownLinks(content)) {
74
- if (!isPublicUrl(url) || sameSite(url)) continue;
75
+ if (!isPublicUrl(url)) continue;
76
+ if (sameSite(url) && !card) continue;
75
77
  urls.add(url);
76
78
  if (card) cards.add(url);
77
79
  const host = linkHost(url);
@@ -184,7 +186,7 @@ export async function refreshLinkAssets({
184
186
  const meta = await fetchPageMeta(url, { fetch: fetchImpl, timeoutMs });
185
187
  if (!meta.title) return keepCachedCard(url);
186
188
  let image;
187
- if (meta.image) {
189
+ if (meta.image && !isSiteBrandOgImage(meta.image)) {
188
190
  try {
189
191
  const picture = await shrinkImage(await fetchImage(meta.image, { fetch: fetchImpl, timeoutMs: timeoutMs * 2 }));
190
192
  const name = `${digest(Buffer.from(url))}-${digest(picture.bytes)}.${picture.ext}`;
@@ -184,6 +184,17 @@ const absolute = (value, base) => {
184
184
  }
185
185
  };
186
186
 
187
+
188
+ /** Site brand OG path `/og.png` (any host) — not an article cover for link cards. */
189
+ export function isSiteBrandOgImage(url) {
190
+ if (!url) return false;
191
+ try {
192
+ return new URL(url).pathname === "/og.png";
193
+ } catch {
194
+ return false;
195
+ }
196
+ }
197
+
187
198
  /** Title, description, image, site name, author, date and icon candidates from a page's head. */
188
199
  export function parseHead(html, baseUrl) {
189
200
  const head = (/<head[\s>][\s\S]*?(<\/head>|$)/iu.exec(html)?.[0]) ?? html.slice(0, 200_000);
@@ -210,10 +221,11 @@ export function parseHead(html, baseUrl) {
210
221
  const published = meta["article:published_time"] || meta["og:published_time"] || meta.date || meta.datepublished || meta["parsely-pub-date"] || "";
211
222
  const publishedTime = published && !Number.isNaN(Date.parse(published)) ? new Date(Date.parse(published)).toISOString().slice(0, 10) : "";
212
223
  const author = meta["article:author"] || meta.author || meta["twitter:creator"] || "";
224
+ const imageCandidate = absolute(meta["og:image:secure_url"] || meta["og:image"] || meta["og:image:url"] || meta["twitter:image"], baseUrl);
213
225
  return {
214
226
  title: clean(meta["og:title"] || meta["twitter:title"] || title, 200),
215
227
  description: clean(meta["og:description"] || meta["twitter:description"] || meta.description, 300),
216
- image: absolute(meta["og:image:secure_url"] || meta["og:image"] || meta["og:image:url"] || meta["twitter:image"], baseUrl),
228
+ image: isSiteBrandOgImage(imageCandidate) ? "" : imageCandidate,
217
229
  siteName: clean(meta["og:site_name"] || meta["application-name"], 80),
218
230
  // article:author is sometimes a profile URL; only keep readable names.
219
231
  author: /^https?:\/\//iu.test(author) ? "" : clean(author, 80),
@@ -222,6 +234,18 @@ export function parseHead(html, baseUrl) {
222
234
  };
223
235
  }
224
236
 
237
+ /** Target of an HTML meta refresh, when the page asks the browser to move. */
238
+ export function metaRefreshTarget(html, baseUrl) {
239
+ for (const tag of html.match(/<meta\b[^>]*>/giu) ?? []) {
240
+ const attrs = attributes(tag);
241
+ if ((attrs["http-equiv"] || "").toLowerCase() !== "refresh") continue;
242
+ const match = /(?:^|;)\s*url\s*=\s*["']?([^"'>\s]+)/iu.exec(attrs.content || "");
243
+ const target = absolute(match?.[1] ?? "", baseUrl);
244
+ if (target) return target;
245
+ }
246
+ return "";
247
+ }
248
+
225
249
  /** A page's head, fetched safely: HTML only, at most maxBytes, stopping at </head>. */
226
250
  export async function fetchHead(url, { fetch: fetcher, timeoutMs = DEFAULT_TIMEOUT_MS, maxBytes = DEFAULT_MAX_HTML_BYTES } = {}) {
227
251
  const { response, url: finalUrl } = await safeFetch(url, { fetch: fetcher, timeoutMs });
@@ -232,9 +256,22 @@ export async function fetchHead(url, { fetch: fetcher, timeoutMs = DEFAULT_TIMEO
232
256
  return { html: new TextDecoder().decode(bytes), url: finalUrl };
233
257
  }
234
258
 
235
- /** Open Graph fields for a page. */
259
+ /** Open Graph fields for a page. Follows HTML meta refresh the way a browser would. */
236
260
  export async function fetchPageMeta(url, options = {}) {
237
- const { html, url: finalUrl } = await fetchHead(url, options);
261
+ let current = url;
262
+ const seen = new Set();
263
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
264
+ if (seen.has(current)) break;
265
+ seen.add(current);
266
+ const { html, url: finalUrl } = await fetchHead(current, options);
267
+ const refresh = metaRefreshTarget(html, finalUrl);
268
+ if (refresh && refresh !== finalUrl && !seen.has(refresh)) {
269
+ current = refresh;
270
+ continue;
271
+ }
272
+ return { ...parseHead(html, finalUrl), url: finalUrl };
273
+ }
274
+ const { html, url: finalUrl } = await fetchHead(current, options);
238
275
  return { ...parseHead(html, finalUrl), url: finalUrl };
239
276
  }
240
277
 
@@ -86,9 +86,17 @@ const absolute = (src, siteUrl) => (src && siteUrl && src.startsWith("/") ? `${s
86
86
  const escapeHtml = (value) =>
87
87
  String(value).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
88
88
 
89
+ /** Text a reader can select inside an inlined Excalidraw SVG; path data and fonts stay out of search. */
90
+ function excalidrawVisibleText(svg) {
91
+ const parts = [];
92
+ for (const match of svg.matchAll(/<(?:text|title)\b[^>]*>([^<]*)<\/(?:text|title)>/giu)) parts.push(match[1]);
93
+ return parts.join(" ");
94
+ }
95
+
89
96
  /** Readable text for search and word count: captions and snapshot text, never intent. */
90
97
  export function contentToSearchText(content) {
91
- return replaceFences(stripCardMarkers(content), (fence) => {
98
+ const withoutDiagramMarkup = String(content ?? "").replace(/<svg\b[^>]*class="[^"]*\bexcalidraw\b[^"]*"[\s\S]*?<\/svg>/giu, (svg) => ` ${excalidrawVisibleText(svg)} `);
99
+ return replaceFences(stripCardMarkers(withoutDiagramMarkup), (fence) => {
92
100
  if (fence.lang === "ui") {
93
101
  const payload = readPayload(fence.body);
94
102
  if (!payload) return " ";
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Turn an exported Excalidraw SVG into article HTML.
3
+ *
4
+ * The Markdown image stays the author's syntax until content sync. This walks
5
+ * the Markdown AST, swaps each `.excalidraw` image for the sanitized SVG, and
6
+ * leaves every other byte of the post alone. rehype-raw then parses that SVG
7
+ * into the article tree, so the text is part of the page rather than an
8
+ * `<img src>`.
9
+ */
10
+ import crypto from "node:crypto";
11
+ import { fromMarkdown } from "mdast-util-from-markdown";
12
+ import { fromHtml } from "hast-util-from-html";
13
+ import { toHtml } from "hast-util-to-html";
14
+ import { visit } from "unist-util-visit";
15
+ import { figureLayout } from "./enhance.mjs";
16
+ import { mapOutsideCode } from "./markdown-links.mjs";
17
+
18
+ /** Same rule as scripts/excalidraw.mjs: a source file, not an `.excalidraw.svg`. */
19
+ function isExcalidrawPath(value) {
20
+ const clean = String(value ?? "").split(/[?#]/u, 1)[0];
21
+ return /\.excalidraw$/iu.test(clean);
22
+ }
23
+
24
+ const DROP_TAGS = new Set([
25
+ "script",
26
+ "noscript",
27
+ "iframe",
28
+ "object",
29
+ "embed",
30
+ "foreignobject",
31
+ "audio",
32
+ "video",
33
+ "canvas",
34
+ "link",
35
+ "meta",
36
+ "base",
37
+ "form",
38
+ ]);
39
+
40
+ const escapeHtml = (value) =>
41
+ String(value)
42
+ .replaceAll("&", "&amp;")
43
+ .replaceAll("<", "&lt;")
44
+ .replaceAll(">", "&gt;")
45
+ .replaceAll('"', "&quot;");
46
+
47
+ function meaningfulChildren(node) {
48
+ return (node?.children ?? []).filter((child) => !(child.type === "text" && !String(child.value).trim()));
49
+ }
50
+
51
+ /** Same caption rule as article figures: title, otherwise alt, unless the alt is a placeholder. */
52
+ function imageCaption(image) {
53
+ const title = String(image.title ?? "").trim();
54
+ const alt = String(image.alt ?? "").trim();
55
+ if (title) return title;
56
+ if (alt && !/^image|^截图|^img/iu.test(alt)) return alt;
57
+ return "";
58
+ }
59
+
60
+ function unsafeUrl(value) {
61
+ const url = String(value ?? "").trim().replace(/[\u0000-\u001f\s]+/gu, "");
62
+ if (!url || url.startsWith("#") || url.startsWith("/")) return false;
63
+ if (/^javascript:/iu.test(url)) return true;
64
+ if (/^https?:/iu.test(url)) return false;
65
+ if (/^data:image\/(?:png|gif|jpe?g|webp|svg\+xml);/iu.test(url)) return false;
66
+ if (/^data:font\//iu.test(url)) return false;
67
+ if (/^data:/iu.test(url)) return true;
68
+ return false;
69
+ }
70
+
71
+ function sanitizeNode(node) {
72
+ if (!node || node.type === "text" || node.type === "comment") return node;
73
+ if (node.type !== "element") return null;
74
+ if (DROP_TAGS.has(String(node.tagName).toLowerCase())) return null;
75
+ const properties = { ...(node.properties ?? {}) };
76
+ for (const key of Object.keys(properties)) {
77
+ const value = properties[key];
78
+ if (/^on/iu.test(key)) {
79
+ delete properties[key];
80
+ continue;
81
+ }
82
+ if (typeof value === "string" && /^(?:href|src|xlinkHref)$/iu.test(key) && unsafeUrl(value)) {
83
+ delete properties[key];
84
+ continue;
85
+ }
86
+ if (key === "style" && typeof value === "string" && /javascript:/iu.test(value)) delete properties[key];
87
+ }
88
+ node.properties = properties;
89
+ node.children = (node.children ?? []).map(sanitizeNode).filter(Boolean);
90
+ return node;
91
+ }
92
+
93
+ /**
94
+ * Sanitized SVG markup for the page. Alt or title becomes `<title>` and
95
+ * `aria-labelledby`. Scene `<text>` nodes stay.
96
+ * @param {string} svgText
97
+ * @param {{ alt?: string, title?: string }} [labels]
98
+ */
99
+ export function inlineSvgDocument(svgText, { alt = "", title = "" } = {}) {
100
+ const stripped = String(svgText).replace(/<!--\s*garden-excalidraw-source:[^>]*-->/gu, "");
101
+ const root = fromHtml(stripped, { fragment: true });
102
+ const svg = root.children.find((node) => node.type === "element" && node.tagName === "svg");
103
+ if (!svg) throw new Error("导出结果不是 SVG");
104
+ sanitizeNode(svg);
105
+ const label = String(title || alt || "").trim();
106
+ if (label) {
107
+ const id = `garden-excalidraw-${crypto.createHash("sha256").update(`${label}\0${stripped}`).digest("hex").slice(0, 10)}`;
108
+ svg.properties.ariaLabelledby = id;
109
+ svg.children.unshift({
110
+ type: "element",
111
+ tagName: "title",
112
+ properties: { id },
113
+ children: [{ type: "text", value: label }],
114
+ });
115
+ }
116
+ const classes = Array.isArray(svg.properties.className)
117
+ ? svg.properties.className
118
+ : svg.properties.className
119
+ ? [svg.properties.className]
120
+ : [];
121
+ if (!classes.includes("excalidraw")) classes.push("excalidraw");
122
+ svg.properties.className = classes;
123
+ const width = Number(svg.properties.width) || 0;
124
+ const height = Number(svg.properties.height) || 0;
125
+ if (width > 0) svg.properties.dataNw = String(width);
126
+ if (width > 0) svg.properties.dataAw = String(width);
127
+ return { html: toHtml(svg), width, height };
128
+ }
129
+
130
+ function figureHtml(svgHtml, caption, width) {
131
+ const side = figureLayout({ naturalWidth: width }).side;
132
+ const classes = side > 0 ? "fig fig-wide" : "fig";
133
+ const style = side > 0 ? ` style="--wl:${side}px;--wr:${side}px"` : "";
134
+ const cap = caption ? `<figcaption>${escapeHtml(caption)}</figcaption>` : "";
135
+ return `<figure class="${classes}"${style}><div class="fig-card">${svgHtml}</div>${cap}</figure>`;
136
+ }
137
+
138
+ /**
139
+ * Replace `.excalidraw` Markdown images with inline SVG HTML.
140
+ * `readSvg(url)` returns the exported SVG text or throws.
141
+ * @param {string} markdown
142
+ * @param {(url: string) => string} readSvg
143
+ */
144
+ export function embedExcalidrawImages(markdown, readSvg) {
145
+ const source = String(markdown ?? "");
146
+ const tree = fromMarkdown(source);
147
+ const edits = [];
148
+ visit(tree, "image", (node, _index, parent) => {
149
+ const url = String(node.url ?? "");
150
+ if (!isExcalidrawPath(url)) return;
151
+ const start = node.position?.start?.offset;
152
+ const end = node.position?.end?.offset;
153
+ if (start == null || end == null) return;
154
+ const { html, width } = inlineSvgDocument(readSvg(url), { alt: node.alt, title: node.title });
155
+ const alone = parent?.type === "paragraph" && meaningfulChildren(parent).length === 1 && meaningfulChildren(parent)[0] === node;
156
+ const caption = imageCaption(node);
157
+ edits.push(alone && parent.position?.start?.offset != null && parent.position?.end?.offset != null
158
+ ? { start: parent.position.start.offset, end: parent.position.end.offset, replacement: figureHtml(html, caption, width) }
159
+ : { start, end, replacement: html });
160
+ });
161
+ edits.sort((left, right) => right.start - left.start);
162
+ let output = source;
163
+ for (const edit of edits) output = `${output.slice(0, edit.start)}${edit.replacement}${output.slice(edit.end)}`;
164
+ return output;
165
+ }
166
+
167
+ /** Raw `<img src="….excalidraw">` outside code becomes the same inline SVG. */
168
+ export function embedExcalidrawImgTags(markdown, readSvg) {
169
+ return mapOutsideCode(markdown, (text) => text.replace(/<img\b[^>]*>/giu, (tag) => {
170
+ const src = /\bsrc\s*=\s*["']([^"']+)["']/iu.exec(tag)?.[1];
171
+ if (!src || !isExcalidrawPath(src)) return tag;
172
+ const alt = /\balt\s*=\s*["']([^"']*)["']/iu.exec(tag)?.[1] ?? "";
173
+ return inlineSvgDocument(readSvg(src), { alt }).html;
174
+ }));
175
+ }
@@ -50,32 +50,68 @@ function mapInline(text, visit) {
50
50
 
51
51
  // Inline links read as CommonMark reads them (ui/garden/markdown-destination.mjs):
52
52
  // `[t](<https://e.com/a (1)>)` and `[t](https://e.com/Trie_(x))` are whole addresses.
53
- // Groups: 1 `!`, 3 or 4 the address, 6 `{card}`.
53
+ // Groups: 1 `!`, 2 label, 3 or 4 the address, 6 `{card}`.
54
54
  const LINK = new RegExp(`${INLINE_LINK_SOURCE}(\\{card\\}|\\{source\\})?`, "giu");
55
55
  const linkUrl = (match) => match[3] ?? match[4];
56
56
  const isWebUrl = (url) => /^https?:\/\//iu.test(url);
57
57
  const AUTOLINK = /<(https?:\/\/[^\s>]+)>/giu;
58
58
  const BARE = /(^|[\s((::,,。])(https?:\/\/[^\s<>()()\],。、]+[^\s<>()()\].,;:!?,。、;:!?'"])/giu;
59
59
 
60
+ /** The marker that asks for a link card: `[text](url){card}`, nothing in between. */
61
+ export const CARD_MARKER = "{card}";
62
+ /** The marker that draws a link as an inline source chip: `[site](url){source}`. */
63
+ export const SOURCE_MARKER = "{source}";
64
+
65
+
66
+ /**
67
+ * A single-line paragraph whose only content is a web URL: bare, <autolink>,
68
+ * or `[url](url)` (optional `{card}`). Those render as link cards and share
69
+ * the OG fetch path with `{card}` markers.
70
+ */
71
+ function standaloneUrl(line) {
72
+ const trimmed = String(line ?? "").trim();
73
+ if (!trimmed || /\n/u.test(trimmed)) return "";
74
+ // Fresh regex: a shared /g lastIndex would skip later matchAll calls.
75
+ const link = new RegExp(LINK.source, LINK.flags).exec(trimmed);
76
+ if (link && link.index === 0 && link[0].length === trimmed.length && link[1] !== "!") {
77
+ const url = linkUrl(link);
78
+ const label = link[2] ?? "";
79
+ if (isWebUrl(url) && (link[6] === CARD_MARKER || label === url)) return url;
80
+ return "";
81
+ }
82
+ const auto = /^<(https?:\/\/[^\s>]+)>$/iu.exec(trimmed);
83
+ if (auto) return auto[1];
84
+ const bare = /^(https?:\/\/[^\s<>()()]+)$/iu.exec(trimmed);
85
+ return bare && isWebUrl(bare[1]) ? bare[1] : "";
86
+ }
87
+
60
88
  /** Every external link in the body, in order: `{ url, card }`. Images are left out. */
61
89
  export function markdownLinks(markdown) {
62
90
  const links = [];
91
+ const standalone = new Set();
63
92
  mapOutsideCode(markdown, (text) => {
93
+ for (const block of text.split(/\n{2,}/u)) {
94
+ const url = standaloneUrl(block);
95
+ if (url) standalone.add(url);
96
+ }
64
97
  for (const match of text.matchAll(LINK)) {
65
- if (match[1] !== "!" && isWebUrl(linkUrl(match))) links.push({ url: linkUrl(match), card: match[6] === CARD_MARKER });
98
+ if (match[1] !== "!" && isWebUrl(linkUrl(match))) {
99
+ const url = linkUrl(match);
100
+ links.push({ url, card: match[6] === CARD_MARKER || standalone.has(url) });
101
+ }
66
102
  }
67
103
  const rest = text.replace(LINK, " ");
68
- for (const match of rest.matchAll(AUTOLINK)) links.push({ url: match[1], card: false });
69
- for (const match of rest.replace(AUTOLINK, " ").matchAll(BARE)) links.push({ url: match[2], card: false });
104
+ for (const match of rest.matchAll(AUTOLINK)) {
105
+ links.push({ url: match[1], card: standalone.has(match[1]) });
106
+ }
107
+ for (const match of rest.replace(AUTOLINK, " ").matchAll(BARE)) {
108
+ links.push({ url: match[2], card: standalone.has(match[2]) });
109
+ }
70
110
  return text;
71
111
  });
72
112
  return links;
73
113
  }
74
114
 
75
- /** The marker that asks for a link card: `[text](url){card}`, nothing in between. */
76
- export const CARD_MARKER = "{card}";
77
- /** The marker that draws a link as an inline source chip: `[site](url){source}`. */
78
- export const SOURCE_MARKER = "{source}";
79
115
 
80
116
  /**
81
117
  * The same Markdown without `{card}` markers, for excerpts, RSS and the search