Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): show a visible placeholder when an image src fails to load (#3208)
Abrahamd5492001a83c
diff --git a/.changeset/image-missing-placeholder.md b/.changeset/image-missing-placeholder.mdnew file mode 100644index 000000000..17b75bf5a--- /dev/null+++ b/.changeset/image-missing-placeholder.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': patch+---++Images with a missing `src` (404, broken URL, deleted asset) now render a visible placeholder card — icon + "Image failed to load" + the truncated path — instead of leaving the reader with the browser's default 16×16 broken-image glyph. Same behavior on cached-broken images that fail before onError fires (detected via `img.complete && naturalWidth === 0`). Placeholder stays inline (`<span>`) so it's safe inside `<p>` and inside `<Zoom wrapElement="span">`.diff --git a/knip.config.ts b/knip.config.tsindex 13582ee18..f004e6bc3 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -123,7 +123,9 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: ['@types/shell-quote'],+ ignoreDependencies: [+ '@types/shell-quote',+ ],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],diff --git a/packages/app/src/components/ui/loading-image.tsx b/packages/app/src/components/ui/loading-image.tsxindex 0c7ed93ae..8d1e54a91 100644--- a/packages/app/src/components/ui/loading-image.tsx+++ b/packages/app/src/components/ui/loading-image.tsx@@ -1,4 +1,5 @@import { useLingui } from '@lingui/react/macro';+import { ImageOff } from 'lucide-react';import type { CSSProperties, ImgHTMLAttributes } from 'react';import { useLayoutEffect, useRef, useState } from 'react';import { cn } from '@/lib/utils';@@ -50,6 +51,7 @@ export function LoadingImage({const { t } = useLingui();const imgRef = useRef<HTMLImageElement>(null);const [loaded, setLoaded] = useState(false);+ const [hasError, setHasError] = useState(false);const intrinsic = hasIntrinsicDimensions(width, height);const slotStyle = computeSlotStyle(width, height, style);@@ -58,19 +60,54 @@ export function LoadingImage({// forever and the <img> stay stuck at opacity-0. Treating `complete` as// the terminal-state signal (regardless of naturalWidth) also dismisses// the skeleton for cached failures whose onError may not re-fire, mirroring- // the new onError handler's semantics. Re-running on src change resets the- // skeleton when the same instance is reused with a new src (e.g.- // AssetPreview switching assets in the sidebar).+ // the onError handler's semantics. `naturalWidth === 0` on a `complete`+ // img means the load actually failed (broken/404 cache) — surface that as+ // the error placeholder instead of leaving the reader looking at the+ // browser's tiny default broken-image glyph. Re-running on src change+ // resets both flags when the same instance is reused with a new src.// biome-ignore lint/correctness/useExhaustiveDependencies: src is the reactive trigger; the body reads imgRef.current (refs don't trigger re-runs) so biome treats src as unused.useLayoutEffect(() => {const img = imgRef.current;if (img?.complete) {setLoaded(true);+ setHasError(img.naturalWidth === 0);} else {setLoaded(false);+ setHasError(false);}}, [src]);+ if (hasError) {+ // A visible placeholder card replaces the browser's default 16x16+ // broken-image glyph so the reader can tell the asset is missing+ // instead of assuming the block rendered empty. Stays a `<span>` for+ // the same phrasing-content reason the slot is — Image.tsx wraps this+ // in `<Zoom wrapElement="span">` and markdown often lands `<img>`+ // inside `<p>`, where `<div>` is forbidden.+ const label = alt && alt.length > 0 ? alt : (src ?? '');+ return (+ <span+ data-testid={slotTestId}+ data-image-error="true"+ role="img"+ aria-label={t`Image failed to load: ${label}`}+ className={cn(+ 'inline-flex max-w-full items-center gap-2 rounded-md border border-dashed border-border bg-muted/40 px-2 py-1 text-muted-foreground',+ slotClassName,+ )}+ style={intrinsic ? slotStyle : undefined}+ >+ <ImageOff aria-hidden="true" className="size-3.5 shrink-0 opacity-70" />+ <span className="text-xs font-medium">{t`Image failed to load`}</span>+ {src ? (+ <span className="max-w-[24ch] truncate font-mono text-[10px] opacity-70" title={src}>+ {src}+ </span>+ ) : null}+ </span>+ );+ }+return (<spandata-testid={slotTestId}@@ -116,14 +153,15 @@ export function LoadingImage({)}onLoad={(event) => {setLoaded(true);+ setHasError(false);onLoad?.(event);}}onError={(event) => {- // Dismiss the skeleton so the browser's native broken-image- // indicator becomes visible and screen readers stop announcing- // aria-busy="true" forever. Without this, a 404 leaves the- // <img> stuck at opacity-0 — a regression from default <img>.+ // Route into the placeholder branch on next render — the+ // skeleton also dismisses so screen readers stop announcing+ // aria-busy="true" forever.setLoaded(true);+ setHasError(true);onError?.(event);}}/>diff --git a/packages/app/src/editor/components/Image.dom.test.tsx b/packages/app/src/editor/components/Image.dom.test.tsxindex da930b0bd..3fd5d763a 100644--- a/packages/app/src/editor/components/Image.dom.test.tsx+++ b/packages/app/src/editor/components/Image.dom.test.tsx@@ -148,15 +148,15 @@ describe('Image — loading-state placeholder (PRD-6638)', () => {}});- test('removes the placeholder after the inner <img>.error event fires (broken image)', () => {- // Without an onError handler the <img> stays at opacity-0 forever — a- // regression from default <img> behavior where the browser shows its- // native broken-image indicator. Screen readers also stay parked on- // aria-busy="true" with no way to distinguish "still loading" from- // "permanently broken". Dismissing the skeleton on error lets the- // browser's broken-image indicator become visible.+ test('renders a visible placeholder card after the inner <img>.error event fires (broken image)', () => {+ // The browser's default broken-image glyph is a 16x16 icon that reads as+ // "the block rendered empty" — the reporter's ask was for something+ // visible so the reader knows the asset is missing. Placeholder is a+ // <span> for the same phrasing-content reason the slot is (Image.tsx+ // wraps in <Zoom wrapElement="span">, and markdown lands <img> inside+ // <p> where <div> is forbidden).const { container } = render(- <Image src="/missing-asset.png" alt="" width={400} height={300} />,+ <Image src="/missing-asset.png" alt="broken" width={400} height={300} />,);expect(screen.queryByTestId('image-loading-skeleton')).not.toBeNull();@@ -165,7 +165,14 @@ describe('Image — loading-state placeholder (PRD-6638)', () => {expect(img).not.toBeNull();fireEvent.error(img as HTMLImageElement);+ // Skeleton gone, placeholder card mounted, src surfaced for triage.expect(screen.queryByTestId('image-loading-skeleton')).toBeNull();+ const slot = screen.getByTestId('image-slot');+ expect(slot.getAttribute('data-image-error')).toBe('true');+ expect(slot.textContent).toContain('Image failed to load');+ expect(slot.textContent).toContain('/missing-asset.png');+ // Stays inline for phrasing-content compatibility with <p>.+ expect(slot.tagName).toBe('SPAN');});test('restores the placeholder when src changes (e.g. AssetPreview switching assets)', () => {diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex f6b49dfcb..f548b8b96 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -1834,6 +1834,7 @@"U6wmNc": ["Sync paused"],"U88xbi": ["Failed to create the schema file"],"U8CD-l": ["Copy full path, No workspace"],+ "U8sPsM": ["Image failed to load: ", ["label"]],"U9tm58": ["Hide problem indicators"],"UBv8UK": ["Delete Permanently"],"UDFrWm": ["Checking GitHub connection..."],@@ -3128,6 +3129,7 @@"nGAFeH": ["Reports you've generated on this Mac. Retry a send, reveal a file, or delete one you no longer need."],+ "nL-HHD": ["Image failed to load"],"nMSYz5": ["This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 81e128f96..a129347bf 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -5586,6 +5586,14 @@ msgstr "Ignore patterns"msgid "Ignore patterns (raw text)"msgstr "Ignore patterns (raw text)"+#: src/components/ui/loading-image.tsx+msgid "Image failed to load"+msgstr "Image failed to load"++#: src/components/ui/loading-image.tsx+msgid "Image failed to load: {label}"+msgstr "Image failed to load: {label}"+#: src/components/ImportSkillForm.tsxmsgid "Import"msgstr "Import"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 6fd4c2fce..88e3f5369 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -1834,6 +1834,7 @@"U6wmNc": ["Śŷńć ƥàũśēď"],"U88xbi": ["Ƒàĩĺēď ţō ćŕēàţē ţĥē śćĥēḿà ƒĩĺē"],"U8CD-l": ["Ćōƥŷ ƒũĺĺ ƥàţĥ, Ńō ŵōŕķśƥàćē"],+ "U8sPsM": ["Ĩḿàĝē ƒàĩĺēď ţō ĺōàď: ", ["label"]],"U9tm58": ["Ĥĩďē ƥŕōƀĺēḿ ĩńďĩćàţōŕś"],"UBv8UK": ["Ďēĺēţē Ƥēŕḿàńēńţĺŷ"],"UDFrWm": ["Ćĥēćķĩńĝ ĜĩţĤũƀ ćōńńēćţĩōń..."],@@ -3128,6 +3129,7 @@"nGAFeH": ["Ŕēƥōŕţś ŷōũ'vē ĝēńēŕàţēď ōń ţĥĩś Ḿàć. Ŕēţŕŷ à śēńď, ŕēvēàĺ à ƒĩĺē, ōŕ ďēĺēţē ōńē ŷōũ ńō ĺōńĝēŕ ńēēď."],+ "nL-HHD": ["Ĩḿàĝē ƒàĩĺēď ţō ĺōàď"],"nMSYz5": ["Ţĥĩś ƥàţĥ ĩś ōń àń ēxţēŕńàĺ vōĺũḿē (/Vōĺũḿēś/...). ŌƥēńĶńōŵĺēďĝē ŵĩĺĺ ĺōśē ţŕàćķ ōƒ ƒĩĺēś ŵĥēń ţĥē ďŕĩvē ēĴēćţś."],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex f08bce771..946535060 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -5582,6 +5582,14 @@ msgstr ""msgid "Ignore patterns (raw text)"msgstr ""+#: src/components/ui/loading-image.tsx+msgid "Image failed to load"+msgstr ""++#: src/components/ui/loading-image.tsx+msgid "Image failed to load: {label}"+msgstr ""+#: src/components/ImportSkillForm.tsxmsgid "Import"msgstr ""diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.tsindex d7a845280..dfd95ef49 100644--- a/packages/core/src/bridge/bind-frontmatter-doc.ts+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts@@ -1,3 +1,4 @@+import type * as Y from 'yjs';import type { Err, Ok, Result } from '../config/result.ts';import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.tsindex 005627195..8bfdb40cd 100644--- a/packages/core/src/bridge/bridge-invariant.ts+++ b/packages/core/src/bridge/bridge-invariant.ts@@ -1,3 +1,4 @@+import { fnv1aDigest } from './hash-util.ts';export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex f4cc8a286..2a597ec3d 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,3 +1,4 @@+import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex a1dff381b..77794c9fc 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,3 +1,4 @@+import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';import { carriedEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.tsindex 9d9c244b0..463e89595 100644--- a/packages/core/src/bridge/growth-detect.ts+++ b/packages/core/src/bridge/growth-detect.ts@@ -1,3 +1,4 @@+const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.tsindex c43fdd7e7..0939885bb 100644--- a/packages/core/src/bridge/intraline-predicate.ts+++ b/packages/core/src/bridge/intraline-predicate.ts@@ -1,3 +1,4 @@+export function rawLineCounts(doc: string): Map<string, number> {const counts = new Map<string, number>();for (const line of doc.split('\n')) {diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.tsindex 251560a35..c0dc65705 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -65,6 +65,7 @@ export function tryLineLevelCombine(return { clean: true, merged };}+export type BridgeMergeContentLossSide = 'user' | 'agent';export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.tsindex 650461462..8dc0ec652 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,3 +1,4 @@+import { carriedEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.tsindex 754dc5cc2..0be5203e4 100644--- a/packages/core/src/bridge/pm-structural-equivalence.ts+++ b/packages/core/src/bridge/pm-structural-equivalence.ts@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };const BR_LITERAL_RE = /^<br\s*\/?>$/i;+interface DegradeEntry {readonly label: string;readonly severity: ToleranceClassSeverity;@@ -127,6 +128,7 @@ export interface ComparePmStructuralOptions {ignoreAttrs?: (attrKey: string) => boolean;}+/** Rebuild a node with `fn` applied to each child; identity when childless.* Shared by the degrade canonicalizers so none re-implements the walk. */function mapChildren(@@ -248,6 +250,7 @@ function applyDegrades(tree: PmStructuralNode): {return { normalized: current, fired };}+export function comparePmStructural(expected: PmStructuralNode,actual: PmStructuralNode,diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.tsindex af20de1e2..dca644141 100644--- a/packages/core/src/bridge/subsequence.ts+++ b/packages/core/src/bridge/subsequence.ts@@ -1,3 +1,4 @@+/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):* insertions in `haystack` are free; any dropped or substituted `needle` byte* fails. */diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.tsindex 83d47404a..a363dfd54 100644--- a/packages/core/src/markdown/callout-transformer.ts+++ b/packages/core/src/markdown/callout-transformer.ts@@ -1,3 +1,4 @@+import type { Blockquote, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.tsindex 9807a7e82..4499dbc92 100644--- a/packages/core/src/markdown/code-fence.ts+++ b/packages/core/src/markdown/code-fence.ts@@ -1,3 +1,4 @@+export function selectFenceChar(info: string): '`' | '~' {return info.includes('`') ? '~' : '`';}diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 7415c474a..34704165b 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.tsindex ece5c02a1..b6299a948 100644--- a/packages/core/src/markdown/dedent-block-jsx-close.ts+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts@@ -1,3 +1,4 @@+import { findFencedRegions, isInsideFence } from './fence-regions.ts';const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.tsindex 54774764a..acd398aa6 100644--- a/packages/core/src/markdown/details-accordion-promoter.ts+++ b/packages/core/src/markdown/details-accordion-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.tsindex 43ecdc709..ba9b56384 100644--- a/packages/core/src/markdown/div-align-promoter.ts+++ b/packages/core/src/markdown/div-align-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.tsindex 6d3f3643e..4513da9bb 100644--- a/packages/core/src/markdown/fence-regions.ts+++ b/packages/core/src/markdown/fence-regions.ts@@ -1,3 +1,4 @@+const FENCE_RE = /^(`{3,}|~{3,})/gm;export function findFencedRegions(src: string): Array<[number, number]> {diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.tsindex 00f5771ee..6931623c7 100644--- a/packages/core/src/markdown/fixtures/index.ts+++ b/packages/core/src/markdown/fixtures/index.ts@@ -1,3 +1,4 @@+import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {return resolve(FIXTURES_DIR, ...segments);}+interface GfmExample {section: string;markdown: string;@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];}+interface MdxCrashEntry {id: string;input: string;@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {) as LargeEmbedFixture[];}+export function loadPrd6955Before(): string {return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');}@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');}+export interface NgPinnedCase {id: string;name: string;@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {) as NgPinnedCase[];}+export function loadLargeRealistic(): string {return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');}diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.tsindex 8b1eb8519..daa3ef82b 100644--- a/packages/core/src/markdown/fixtures/perf/generate.ts+++ b/packages/core/src/markdown/fixtures/perf/generate.ts@@ -1,3 +1,4 @@+import { writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;const SEED = 0xf1de1117;+function mulberry32(seed: number): () => number {let a = seed >>> 0;return () => {@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {return items[items.length - 1][0];}+const WORDS = ['lorem','ipsum',@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;}+type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';const MIX: readonly [BlockKind, number][] = [@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {return `${blocks.join('\n\n')}\n`;}+function main(): void {for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {const doc = generateDocument(count, SEED);diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.tsindex 420dc0fe5..32c055c5b 100644--- a/packages/core/src/markdown/guard-flanking-matrix.ts+++ b/packages/core/src/markdown/guard-flanking-matrix.ts@@ -7,6 +7,7 @@ import {import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';+export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;export type FlankClass = 'whitespace' | 'punctuation' | 'other';diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.tsindex 2653473da..283913255 100644--- a/packages/core/src/markdown/handler-shadow-audit.ts+++ b/packages/core/src/markdown/handler-shadow-audit.ts@@ -1,3 +1,4 @@+export interface HandlerShadowWitness {input: string;expect: 'byte' | 'byte-and-reparse-type';diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.tsindex da0a81d23..5d1000cc4 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.tsindex 787315157..9681c0056 100644--- a/packages/core/src/markdown/html-to-mdast.ts+++ b/packages/core/src/markdown/html-to-mdast.ts@@ -1,3 +1,4 @@+import type { Element as HastElement, Root as HastRoot } from 'hast';import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';import rehypeParse from 'rehype-parse';@@ -128,7 +129,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRothrow new HtmlPayloadTooLargeError(html.length, maxBytes);}- const processor = unified().use(rehypeParse, { fragment: true });+ const processor = unified()+ .use(rehypeParse, { fragment: true });for (const plugin of cleanupPlugins) {processor.use(plugin);diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.tsindex 706fa9afb..994eb6917 100644--- a/packages/core/src/markdown/image-promoter.ts+++ b/packages/core/src/markdown/image-promoter.ts@@ -1,3 +1,4 @@+import type { Image, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex 9075aa7f1..69221627d 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromPmMark,@@ -206,6 +207,7 @@ export class MarkdownManager {}}+const registry = createRegistry();function destructureAttrs(@@ -254,6 +256,7 @@ function destructureAttrs(return result;}+function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -276,6 +279,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChecreturn freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;}+function isEmptyMdastParagraph(node: MdastNodes): boolean {if (node.type !== 'paragraph') return false;const children = node.children ?? [];@@ -344,6 +348,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}+import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -596,6 +601,7 @@ function buildMdastToPmHandlers(}));}+if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -676,6 +682,7 @@ function buildMdastToPmHandlers(}));}+if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -973,6 +980,7 @@ function buildMdastToPmHandlers(};}+const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1098,6 +1106,7 @@ function buildMdastToPmHandlers(return handlers as RemarkProseMirrorOptions['handlers'];}+function buildPmToMdastHandlers(schema: Schema,freshness: FreshnessCheckerHolder,diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.tsindex fa0be9e86..b79e9aef7 100644--- a/packages/core/src/markdown/lint/applies-to.ts+++ b/packages/core/src/markdown/lint/applies-to.ts@@ -1,3 +1,4 @@+import picomatch from 'picomatch';import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.tsindex 312c9c74b..94b34dee1 100644--- a/packages/core/src/markdown/lint/config-files.ts+++ b/packages/core/src/markdown/lint/config-files.ts@@ -1,3 +1,4 @@+const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set(['.markdownlint.json','.markdownlint.jsonc',diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.tsindex 0ba33b7d8..e413367ef 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -38,6 +38,7 @@ const fullPluginShape = Object.fromEntries(LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),) as z.ZodRawShape;+export const LinterConfigSchema = z.object({enabled: z.boolean(),plugins: z.object(fullPluginShape),diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.tsindex d48eea5e4..a51f2ffb0 100644--- a/packages/core/src/markdown/lint/default-config.ts+++ b/packages/core/src/markdown/lint/default-config.ts@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSettingMD013: false,};+export function resolveMarkdownlintConfig(rules: Record<string, MarkdownlintRuleSetting> | undefined,): Configuration {diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.tsindex ef478e268..9c9542661 100644--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts@@ -1,3 +1,4 @@+import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';export interface FrontmatterFieldConstraint {diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.tsindex 0d4c9a0df..b96d19182 100644--- a/packages/core/src/markdown/lint/frontmatter-validate.ts+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts@@ -1,3 +1,4 @@+import Ajv, { type ValidateFunction } from 'ajv';import Ajv2019 from 'ajv/dist/2019.js';import Ajv2020 from 'ajv/dist/2020.js';diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex 00d08265a..48d260ed6 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -1,3 +1,4 @@+import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';import type { LintDiagnostic } from './types.ts';diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsindex 5e832aa19..be5871ed9 100644--- a/packages/core/src/markdown/lint/plugins.ts+++ b/packages/core/src/markdown/lint/plugins.ts@@ -1,3 +1,4 @@+import { z } from 'zod';import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';import {@@ -13,6 +14,7 @@ import {type MarkdownlintSlice,} from './types.ts';+const MarkdownlintRuleSettingSchema = z.union([z.boolean(),z.enum(MARKDOWNLINT_RULE_SEVERITIES),diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex 3918e657c..833c3a727 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -1,3 +1,4 @@+export const LINT_PLUGIN_IDS = ['markdownlint', 'frontmatter'] as const;export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];@@ -71,6 +72,7 @@ export interface FrontmatterSlice {schemas: ResolvedFrontmatterSchemaEntry[];}+interface RuleOptionSpecBase {key: string;description: string;diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.tsindex 98238656e..437cc539a 100644--- a/packages/core/src/markdown/lint/validation-counts.ts+++ b/packages/core/src/markdown/lint/validation-counts.ts@@ -1,3 +1,4 @@+export interface ValidationSourceCounts {errorCount: number;warningCount: number;diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.tsindex a5b511f25..bd79424c7 100644--- a/packages/core/src/markdown/math-promoter.ts+++ b/packages/core/src/markdown/math-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { Math as MdastMath } from 'mdast-util-math';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.tsindex ed89371d0..00fbc0035 100644--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Properties } from 'hast';import type { FootnoteDefinition, FootnoteReference } from 'mdast';import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.tsindex 8ce2b2492..df788a80d 100644--- a/packages/core/src/markdown/mdast-to-html.ts+++ b/packages/core/src/markdown/mdast-to-html.ts@@ -1,3 +1,4 @@+import type { Element, Root as HastRoot, Text as HastText } from 'hast';import type { Root as MdastRoot, Text as MdastText } from 'mdast';import type { Handler } from 'mdast-util-to-hast';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex bfd7e3109..fa3cfcd86 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.tsindex 1a897fca8..17ed2b829 100644--- a/packages/core/src/markdown/mermaid-promoter.ts+++ b/packages/core/src/markdown/mermaid-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.tsindex d988f4b8b..4aa0490c4 100644--- a/packages/core/src/markdown/parse-with-fallback.ts+++ b/packages/core/src/markdown/parse-with-fallback.ts@@ -168,6 +168,7 @@ export function parseRecursive(}}+interface VFilePlace {offset?: number;start?: { offset?: number };@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {return undefined;}+interface Region {start: number;end: number;@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {return null;}+export interface TagEvent {kind: 'open' | 'close' | 'self-close';name: string;@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {return { start: blockStart, end: blockEnd };}+interface SourceBlock {src: string;start: number;@@ -452,6 +456,7 @@ function tryPerBlockFallback(};}+function wholeDocRawText(source: string): JSONContent {return {type: 'doc',diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.tsindex e6ab4fd57..43d420187 100644--- a/packages/core/src/markdown/parser-drop-closure.ts+++ b/packages/core/src/markdown/parser-drop-closure.ts@@ -1,3 +1,4 @@+export type DroppedTokenAdjudication =| {kind: 'format-dof-axis';diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 449e6f12f..5af2f05f5 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex 91cdf658f..ccf06e94d 100644--- a/packages/core/src/markdown/position-aware-join.ts+++ b/packages/core/src/markdown/position-aware-join.ts@@ -1,3 +1,4 @@+import type { Join } from 'mdast-util-to-markdown';import type { Position } from 'unist';import { isBlankLineParagraph } from './zero-emission-blocks.ts';diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.tsindex 0f399d34c..e5b4c9eba 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -1,3 +1,4 @@+import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';import type { VFile } from 'vfile';@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(const first = source[startOff];if (first !== '[' && first !== '<' && !node.title) {node.data.sourceStyle = 'gfm-autolink';- } else if (first === '[') {+ }+ else if (first === '[') {const slice = source.slice(startOff, endOff);const closeBracketIdx = slice.lastIndexOf('](');if (closeBracketIdx !== -1) {diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.tsindex db10fa54b..ca225ce9b 100644--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts@@ -1,3 +1,4 @@+import type { Comment, Element, Root, Text } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.tsindex 34068d103..3a2524a9a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.tsindex 93151d43b..2279a0189 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.tsindex 188f02d83..a0f467c42 100644--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.tsindex 4ba2c3418..4e8542a21 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.tsindex 1a74b1272..a3c96b24a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.tsindex de35e7b79..e95cf43d6 100644--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.tsindex b4be1b2ea..ffdb4d5b5 100644--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.tsindex 3c8d88b7c..e2a96d1a7 100644--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.tsindex cf2c9da8e..0389575ac 100644--- a/packages/core/src/markdown/resolve-image-url.ts+++ b/packages/core/src/markdown/resolve-image-url.ts@@ -1,3 +1,4 @@+import { isRelativeUrl } from './safe-url.ts';function isDevDiagnosticContext(): boolean {diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 4d3250d3a..8be632ba4 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,3 +1,4 @@+export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.tsindex 0dd54070e..96304e7a5 100644--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts@@ -1,3 +1,4 @@+import type { JSONContent } from '@tiptap/core';import type { Nodes } from 'mdast';import { expect } from 'vitest';diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.tsindex 7cac5b042..93798cf83 100644--- a/packages/core/src/markdown/serialize-helpers.ts+++ b/packages/core/src/markdown/serialize-helpers.ts@@ -1,3 +1,4 @@+import type { Node as PmNode } from '@tiptap/pm/model';import type {MdxJsxAttribute,diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.tsindex b012a5aff..8c08b7a04 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -1,3 +1,4 @@+import type { PhrasingContent, Root, Text } from 'mdast';import type { InlineMath } from 'mdast-util-math';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex 3e79f8cb6..959cc0bd2 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,3 +1,4 @@+import type { Nodes, Parents } from 'mdast';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { Handle, Info, State } from 'mdast-util-to-markdown';diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.tsindex 0f1b0f27d..6e6d73400 100644--- a/packages/core/src/markdown/underline-promoter.ts+++ b/packages/core/src/markdown/underline-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, Root } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.tsindex 1a082bda7..932d7d2a8 100644--- a/packages/core/src/markdown/unknown-mdast-guard.ts+++ b/packages/core/src/markdown/unknown-mdast-guard.ts@@ -1,3 +1,4 @@+import type { Root as MdastRoot } from 'mdast';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.tsindex d578476a7..ac9f5239b 100644--- a/packages/core/src/markdown/whitespace-char-ref.ts+++ b/packages/core/src/markdown/whitespace-char-ref.ts@@ -1,3 +1,4 @@+const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([[0x20, ' '],[0x09, '\t'],diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.tsindex 6dad26200..afd9936fe 100644--- a/packages/core/src/markdown/wiki-link-micromark.ts+++ b/packages/core/src/markdown/wiki-link-micromark.ts@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {}}+const CODE_BANG = 33; // !const CODE_LBRACKET = 91; // [const CODE_RBRACKET = 93; // ]@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {};}+function enterWikiLink(this: CompileContext, token: Token) {this.enter({@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {unsafe: [{ character: '[', inConstruct: ['phrasing'] }],};+const MICROMARK_EXT = wikiLinkSyntax();export function remarkWikiLink(this: Processor) {diff --git a/scripts/verify-native-config-in-packaged-dmg.mjs b/scripts/verify-native-config-in-packaged-dmg.mjsnew file mode 100644index 000000000..f37ab36e1--- /dev/null+++ b/scripts/verify-native-config-in-packaged-dmg.mjs@@ -0,0 +1,243 @@+#!/usr/bin/env node+/**+ * Packaged native-config bundle smoke driver.+ *+ * Usage:+ * node scripts/verify-native-config-in-packaged-dmg.mjs <dmg | app | dir>+ *+ * Proves the prebuilt `native-config` `.node` that the CLI bundles into+ * `dist/native/` actually loads and round-trips from the SHIPPED layout. Unlike+ * the keyring driver (which must launch Electron because the keychain ACL is a+ * macOS-runtime behavior), the toml_edit addon is pure computation over a napi+ * N-API surface that is ABI-stable across Node and Electron, so loading the+ * bundled loader under Node from the packaged path is a faithful check of the+ * bundle + layout + loadability. The remaining in-Electron-process confirmation+ * (hardened runtime, asar) is documented in tests/smoke/native-config-e2e.md and+ * deferred to a signed-DMG QA run.+ *+ * Accepts three input shapes so it runs both pre-package (point it at+ * `packages/cli/dist`) and post-package (a built `.app` or `.dmg`):+ * - a directory holding the bundle (`<dir>`, `<dir>/native`, `<dir>/dist/native`,+ * or `<dir>/cli/dist/native`);+ * - an `.app` bundle (`<app>/Contents/Resources/cli/dist/native`);+ * - a `.dmg` (mounted read-only, the first `.app` inside is resolved, detached).+ *+ * Exit codes:+ * 0 — the bundled addon loaded and round-tripped its parse/upsert/symlink surface+ * 1 — the addon was found but failed to load or round-trip+ * 2 — bad arguments+ * 3 — no bundled `dist/native` (loader) found in the input+ */++import { spawn } from 'node:child_process';+import { existsSync } from 'node:fs';+import { cp, mkdtemp, readdir, rm } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';++/** Candidate sub-paths under a directory input that may hold the napi loader. */+const DIR_CANDIDATES = ['.', 'native', 'dist/native', 'cli/dist/native'];++/** Where the electron-builder `from: ../cli/dist` rule lands the bundle in a `.app`. */+const APP_BUNDLE_SUBPATH = ['Contents', 'Resources', 'cli', 'dist', 'native'];++/**+ * Parse CLI args — single positional (dmg, app, or dir). Exported for tests.+ */+export function parseArgs(argv) {+ const positional = argv.slice(2).filter((a) => !a.startsWith('-'));+ if (positional.length !== 1 || !positional[0]) {+ throw new Error('Usage: verify-native-config-in-packaged-dmg.mjs <dmg | app | dir>');+ }+ return { inputPath: positional[0] };+}++/**+ * Classify the input path as `.dmg`, `.app`, or a plain directory. Exported for+ * tests.+ */+export function classifyInputPath(p) {+ const lower = p.toLowerCase();+ if (lower.endsWith('.dmg')) return 'dmg';+ if (lower.endsWith('.app')) return 'app';+ return 'dir';+}++/**+ * Resolve the directory that holds the napi loader (`index.js` + the platform+ * `.node`) inside a plain directory input. Returns null when none of the known+ * layouts contains a loader. Exported for tests.+ */+export function resolveBundledNativeDirInDir(dirPath, deps = {}) {+ const exists = deps.existsSync ?? existsSync;+ for (const candidate of DIR_CANDIDATES) {+ const dir = resolve(dirPath, candidate);+ if (exists(join(dir, 'index.js'))) return dir;+ }+ return null;+}++/**+ * Load the bundled addon from `nativeDir` and round-trip its full JS-facing+ * surface (parse, insert-only upsert, symlink resolution). Returns a structured+ * result. `deps.requireModule` is injectable so a test can drive the outcome+ * without a real `.node`.+ */+export function loadAndRoundTrip(nativeDir, deps = {}) {+ const requireModule = deps.requireModule ?? createRequire(import.meta.url);+ const now = deps.now ?? Date.now;+ const start = now();+ try {+ const mod = requireModule(join(nativeDir, 'index.js'));++ const parsed = JSON.parse(mod.parseTomlToJson('probe = 1'));+ if (parsed.probe !== 1) throw new Error('parseTomlToJson did not round-trip a scalar');++ const upsert = mod.upsertMcpServer('', 'open-knowledge', JSON.stringify({ command: 'probe' }));+ if (typeof upsert.text !== 'string') throw new Error('upsertMcpServer returned no text');++ const symlink = mod.resolveSymlinkWritePath(join(nativeDir, 'index.js'));+ if (typeof symlink.writePath !== 'string') {+ throw new Error('resolveSymlinkWritePath returned no writePath');+ }++ return { ok: true, backend: 'native', nativeDir, durationMs: now() - start };+ } catch (err) {+ return { ok: false, error: (err && err.message) || String(err), nativeDir };+ }+}++/**+ * Resolve a `.dmg`/`.app`/dir input to the bundled native dir plus a cleanup+ * handle. For `.dmg`, mount read-only, copy the first `.app` to a tmp dir,+ * detach, and resolve the app layout inside the copy.+ */+async function resolveNativeDir(inputPath, kind, deps = {}) {+ const exists = deps.existsSync ?? existsSync;++ if (kind === 'dir') {+ const nativeDir = resolveBundledNativeDirInDir(inputPath, deps);+ return { nativeDir, cleanup: async () => {} };+ }++ if (kind === 'app') {+ const nativeDir = resolve(inputPath, ...APP_BUNDLE_SUBPATH);+ return { nativeDir: exists(join(nativeDir, 'index.js')) ? nativeDir : null, cleanup: async () => {} };+ }++ // kind === 'dmg'+ const runCommand = deps.runCommand ?? defaultRunCommand;+ const mkdtempImpl = deps.mkdtemp ?? mkdtemp;+ const cpImpl = deps.cp ?? cp;+ const rmImpl = deps.rm ?? rm;+ const listAppsInMount = deps.listAppsInMount ?? defaultListAppsInMount;++ const abs = resolve(inputPath);+ const mountRoot = await mkdtempImpl(join(tmpdir(), 'ok-nc-mount-'));+ const appCopyRoot = await mkdtempImpl(join(tmpdir(), 'ok-nc-app-'));+ let detached = false;+ const detach = async () => {+ if (detached) return;+ detached = true;+ try {+ await runCommand('hdiutil', ['detach', '-quiet', mountRoot]);+ } catch {+ // best effort+ }+ };+ try {+ await runCommand('hdiutil', ['attach', '-nobrowse', '-readonly', '-mountpoint', mountRoot, abs]);+ const apps = await listAppsInMount(mountRoot);+ if (apps.length === 0) throw new Error(`No .app bundle found in mounted DMG: ${abs}`);+ const appCopyPath = join(appCopyRoot, apps[0]);+ await cpImpl(join(mountRoot, apps[0]), appCopyPath, { recursive: true });+ await detach();+ const nativeDir = resolve(appCopyPath, ...APP_BUNDLE_SUBPATH);+ return {+ nativeDir: exists(join(nativeDir, 'index.js')) ? nativeDir : null,+ cleanup: async () => {+ await detach();+ await rmImpl(appCopyRoot, { recursive: true, force: true });+ await rmImpl(mountRoot, { recursive: true, force: true });+ },+ };+ } catch (err) {+ await detach();+ await rmImpl(appCopyRoot, { recursive: true, force: true }).catch(() => {});+ await rmImpl(mountRoot, { recursive: true, force: true }).catch(() => {});+ throw err;+ }+}++/**+ * End-to-end orchestration. Returns the exit code for the driver process.+ * Exported so tests can assert exit-code behavior without the shebang entry.+ */+export async function runDriver(argv, deps = {}) {+ const writeStream = deps.writeStream ?? ((s) => process.stdout.write(s));+ const errStream = deps.errStream ?? ((s) => process.stderr.write(s));++ let args;+ try {+ args = parseArgs(argv);+ } catch (err) {+ errStream(`${err.message}\n`);+ return 2;+ }++ let resolved;+ try {+ const kind = classifyInputPath(args.inputPath);+ resolved = await resolveNativeDir(args.inputPath, kind, deps);++ if (!resolved.nativeDir) {+ errStream(+ `verify-native-config: no bundled native loader (dist/native/index.js) found in ${args.inputPath}. ` ++ 'Build the CLI (`bun run build`) so packages/cli/dist/native/ exists, or point at a packaged .app/.dmg.\n',+ );+ return 3;+ }++ const result = (deps.loadAndRoundTrip ?? loadAndRoundTrip)(resolved.nativeDir, deps);+ if (result.ok) {+ writeStream(+ `verify-native-config: OK — backend=${result.backend} nativeDir=${result.nativeDir} durationMs=${result.durationMs ?? '?'}\n`,+ );+ return 0;+ }++ errStream(+ `verify-native-config: bundled addon failed to load/round-trip from ${result.nativeDir} — ${result.error}\n`,+ );+ return 1;+ } catch (err) {+ errStream(`verify-native-config: driver error — ${err.message}\n`);+ return 1;+ } finally {+ await resolved?.cleanup().catch(() => {});+ }+}++async function defaultRunCommand(cmd, args) {+ return await new Promise((resolvePromise, rejectPromise) => {+ const child = spawn(cmd, args, { stdio: 'pipe' });+ const stderrBuf = [];+ child.stderr?.on('data', (d) => stderrBuf.push(d.toString('utf-8')));+ child.on('exit', (code) => {+ if (code === 0) resolvePromise();+ else rejectPromise(new Error(`${cmd} exited ${code}: ${stderrBuf.join('').trim()}`));+ });+ child.on('error', (err) => rejectPromise(err));+ });+}++async function defaultListAppsInMount(mountPath) {+ const entries = await readdir(mountPath);+ return entries.filter((e) => e.toLowerCase().endsWith('.app'));+}++// Shebang entry — run the driver when invoked directly.+if (import.meta.url === `file://${process.argv[1]}`) {+ runDriver(process.argv).then((code) => process.exit(code));+}