openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,899 lines • 53.6 kB
JavaScript
import { P as resolveIntegerOption } from "./number-coercion-D6u-4YD8.mjs";
import { t as avoidTrailingHighSurrogateBreak } from "./utf16-slice-CuDyEXgS.mjs";
import { c as visibleWidth, d as eastAsianWidthType } from "./ansi-CZa2t0Hf.mjs";
import { r as skipWhitespaceGraphemes, t as findGraphemeChunkEnd } from "./grapheme-B63AW15X.mjs";
import { t as MarkdownItCallable } from "./markdown-it-CUTXHjwL.mjs";
import { t as scanParenAwareBreakpoints } from "./text-breakpoints-BMDWjk5t.mjs";
//#region node_modules/.pnpm/markdown-it-cjk-friendly@3.0.0_@types+markdown-it@14.2.0_markdown-it@15.0.3/node_modules/markdown-it-cjk-friendly/dist/index.js
function isEmoji(e) {
return /^\p{Emoji_Presentation}/u.test(String.fromCodePoint(e));
}
/**
* Check if `uc` is CJK. Deferred (returns `null`) if IVS.
*
* @param uc code point
* @returns `true` if `uc` is CJK, `false` if not, `null` if IVS
*/
function isCjkBase(e) {
if (e < 4352) return false;
switch (eastAsianWidthType(e)) {
case "fullwidth":
case "halfwidth": return true;
case "wide": return !isEmoji(e);
case "narrow": return false;
case "ambiguous": return null;
case "neutral": return /^\p{sc=Hangul}/u.test(String.fromCodePoint(e));
}
}
function is2PreviousCjk(e, t) {
return isCjkBase(e) ?? (t === 65025 && isQuotationMark(e));
function isQuotationMark(e) {
return e === 8216 || e === 8217 || e === 8220 || e === 8221;
}
}
function isPreviousCjk(e) {
return isCjkBase(e) ?? (917760 <= e && e <= 917999);
}
function isNextCjk(e) {
return isCjkBase(e) ?? false;
}
function nonEmojiGeneralUseVS(e) {
return e >= 65024 && e <= 65038;
}
function markdownItCjkFriendlyPlugin(e) {
const t = e.inline.State;
class CjkFriendlyState extends t {
scanDelims(t, n) {
const r = this.posMax;
const i = this.src.charCodeAt(t);
const [a, o] = getLastCharCode(this.src, t);
let s = a;
let c = null;
if (nonEmojiGeneralUseVS(a)) {
c = getLastCharCode(this.src, o)[0];
if (!/^\p{Zs}/u.test(String.fromCodePoint(c))) s = c;
}
let l = t;
while (l < r && this.src.charCodeAt(l) === i) l++;
const u = l - t;
const d = l < r ? this.src.codePointAt(l) : 32;
const f = e.utils.isWhiteSpace(s);
const p = e.utils.isWhiteSpace(d);
if (f || p) return {
can_open: !p,
can_close: !f,
length: u
};
const m = e.utils.isMdAsciiPunct(s) || e.utils.isPunctChar(String.fromCodePoint(s));
const h = e.utils.isMdAsciiPunct(d) || e.utils.isPunctChar(String.fromCodePoint(d));
let g = m;
let _ = h;
if (n) {
const e = isNextCjk(d) || (c !== null ? is2PreviousCjk(c, a) : isPreviousCjk(a));
g ||= e || !h;
_ ||= e || !m;
}
return {
can_open: g,
can_close: _,
length: u
};
function getLastCharCode(e, t) {
if (t <= 0) return [32, -1];
const n = e.charCodeAt(t - 1);
if ((n & 64512) !== 56320) return [n, t - 1];
const r = e.codePointAt(t - 2);
return r > 65535 ? [r, t - 2] : [n, t - 1];
}
}
}
e.inline.State = CjkFriendlyState;
}
//#endregion
//#region packages/markdown-core/src/assistant-transcript-headers.ts
const TRANSCRIPT_ROLES = [
"assistant",
"developer",
"system",
"user"
];
function isHorizontalWhitespace(e) {
return e === " " || e === " ";
}
function isLineTrailingWhitespace(e) {
return isHorizontalWhitespace(e) || e === "\r";
}
function skipHorizontalWhitespace(e, t, n) {
let r = t;
while (r < n && isHorizontalWhitespace(e[r])) r += 1;
return r;
}
function matchRoleAt(e, t, n) {
for (const r of TRANSCRIPT_ROLES) {
const i = t + r.length;
if (i <= n && e.slice(t, i).toLowerCase() === r) return {
role: r,
end: i
};
}
return null;
}
function findDelimitedEnd(e, t, n, r, i) {
const a = Math.min(n, t + 160 + 1);
for (let n = t; n < a; n += 1) {
const a = e[n];
if (a === "`") return null;
if (a === r) return n - t >= i ? n + 1 : null;
}
return null;
}
function isHeaderBoundary(e) {
return e === void 0 || isLineTrailingWhitespace(e) || e === ":" || e === ":";
}
function matchRoleHeader(e, t, n) {
const r = e[t];
let i = t;
if (r === "[") {
const r = findDelimitedEnd(e, t + 1, n, "]", 4);
if (!r) return null;
i = skipHorizontalWhitespace(e, r, n);
} else if (r === "<") i = skipHorizontalWhitespace(e, t + 1, n);
const a = matchRoleAt(e, i, n);
if (!a) return null;
let o;
let s;
if (r === "[") {
const t = skipHorizontalWhitespace(e, a.end, n);
if (e[t] !== ":" && e[t] !== ":") return null;
o = t + 1;
s = "timestamp_role_colon";
} else {
if (r === "<") {
const t = e[a.end];
if (t !== ">" && !isHorizontalWhitespace(t)) return null;
o = findDelimitedEnd(e, a.end, n, ">", 0);
s = "angle_role_header";
} else {
const t = skipHorizontalWhitespace(e, a.end, n);
if (e[t] !== "[") return null;
o = findDelimitedEnd(e, t + 1, n, "]", 1);
s = "role_timestamp_bracket";
}
if (!o || !isHeaderBoundary(e[o])) return null;
}
return {
start: t,
end: o,
kind: s,
role: a.role
};
}
function rangesOverlap$1(e, t) {
return e.start < t.end && e.end > t.start;
}
/** Finds supported transcript-role headers in parser-visible text. */
function findAssistantTranscriptRoleHeaderSpans(e, t = []) {
if (!e.includes("[") && !e.includes("<")) return [];
const n = [];
const r = t.toSorted((e, t) => e.start - t.start || e.end - t.end);
let i = 0;
let a = 0;
while (a < e.length) {
const t = e.indexOf("\n", a);
const o = t === -1 ? e.length : t;
const s = matchRoleHeader(e, skipHorizontalWhitespace(e, a, o), o);
if (s) {
for (;;) {
const e = r[i];
if (!e || e.end > s.start) break;
i += 1;
}
const e = r[i];
if (!e || !rangesOverlap$1(s, e)) n.push(s);
}
if (t === -1) break;
a = t + 1;
}
return n;
}
//#endregion
//#region packages/markdown-core/src/html-tags.ts
const MARKDOWN_HTML_TAG_RE = /^(?:<[A-Za-z][A-Za-z0-9-]*(?:\s+[a-zA-Z_:][a-zA-Z0-9:._-]*(?:\s*=\s*(?:[^"'=<>`\x00-\x20]+|'[^']*'|"[^"]*"))?)*\s*\/?>|<\/[A-Za-z][A-Za-z0-9-]*\s*>|<!---?>|<!--(?:[^-]|-[^-]|--[^>])*-->|<\?[\s\S]*?\?>|<![A-Za-z][^>]*>|<!\[CDATA\[[\s\S]*?\]\]>)/;
function matchMarkdownHtmlTag(e) {
return MARKDOWN_HTML_TAG_RE.exec(e)?.[0];
}
/** Tokenizes valid open/close HTML tags with Markdown-It's quote-aware grammar. */
function* tokenizeHtmlTags(e) {
let t = 0;
while (t < e.length) {
const n = e.indexOf("<", t);
if (n < 0) return;
const r = matchMarkdownHtmlTag(e.slice(n));
if (!r) {
t = n + 1;
continue;
}
const i = r.startsWith("</");
const a = n + r.length;
let o = i ? 2 : 1;
while (o < r.length) {
const e = r.charCodeAt(o);
if (!(e >= 65 && e <= 90 || e >= 97 && e <= 122) && !(e >= 48 && e <= 57) && e !== 45) break;
o += 1;
}
const s = r.slice(i ? 2 : 1, o).toLowerCase();
if (!s) {
t = a;
continue;
}
yield {
raw: r,
start: n,
end: a,
name: s,
closing: i,
selfClosing: !i && r.endsWith("/>")
};
t = a;
}
}
//#endregion
//#region packages/markdown-core/src/ir-metadata.ts
const RAW_HTML_TOKEN_TYPE = "markdown_core_html";
function defineMetadata(e, t, n) {
if (n !== void 0) Object.defineProperty(e, t, {
configurable: true,
enumerable: false,
value: n,
writable: true
});
}
function htmlTags(e) {
return e?.htmlTags;
}
/** A fragment cannot inherit a whole tag's meaning; spreads omit these parser-owned facts. */
function copyHtmlTags(e, t, n = 0, r = Number.POSITIVE_INFINITY) {
const i = [];
for (const t of htmlTags(e) ?? []) if (t.start >= n && t.end <= r) i.push({
...t,
start: t.start - n,
end: t.end - n
});
if (i.length) defineMetadata(t, "htmlTags", i);
return t;
}
/** Keep separate tag facts and fresh offsets so appending cannot mutate the source. */
function appendHtmlTags(e, t, n) {
const r = htmlTags(t);
if (!r?.length) return;
const i = htmlTags(e) ?? [];
for (const e of r) i.push({
...e,
start: n + e.start,
end: n + e.end
});
defineMetadata(e, "htmlTags", i);
}
/** Preserve the serialized marker shape while projecting rendered coordinates. */
function copyMarkdownListItem(e, t) {
const n = {
kind: e.kind,
...t.listMarker ? { listMarker: t.listMarker } : {},
...e.task ? { task: true } : {},
...t.taskMarker ? { taskMarker: t.taskMarker } : {},
...e.listId !== void 0 ? { listId: e.listId } : {},
...e.parentListId !== void 0 ? { parentListId: e.parentListId } : {},
...e.depth !== void 0 ? { depth: e.depth } : {},
...t.start !== void 0 ? { start: t.start } : {},
...t.end !== void 0 ? { end: t.end } : {}
};
defineMetadata(n, "contentStart", t.contentStart);
defineMetadata(n, "contentEnd", t.contentEnd);
defineMetadata(n, "markerOnly", t.markerOnly ? true : void 0);
for (const t of [
"sourceMarker",
"sourceContent",
"sourceIndent",
"sourceStartLine",
"sourceEndLine"
]) defineMetadata(n, t, e[t]);
return n;
}
function attachBlockMetadata(e, t) {
if (t.length > 0) defineMetadata(e, "blocks", t);
return e;
}
function sliceListMarker(e, t, n) {
const r = Math.max(e.start, t);
const i = Math.min(e.end, n);
return i > r ? {
start: r - t,
end: i - t
} : void 0;
}
//#endregion
//#region packages/markdown-core/src/assistant-transcript.ts
const ASSISTANT_TRANSCRIPT_ROLE_NODE_TYPE = "assistant_transcript_role_text";
const RAW_CODE_CONTAINER_TAGS = /* @__PURE__ */ new Set([
"code",
"pre",
"script",
"style",
"textarea"
]);
function findRawCodeContainerRanges(e) {
const t = [];
const n = [];
let r = -1;
for (const i of tokenizeHtmlTags(e)) {
if (!RAW_CODE_CONTAINER_TAGS.has(i.name)) continue;
if (i.closing) {
const e = n.lastIndexOf(i.name);
if (e !== -1) {
n.splice(e);
if (n.length === 0 && r !== -1) {
t.push({
start: r,
end: i.end
});
r = -1;
}
}
} else if (!i.selfClosing) {
if (n.length === 0) r = i.start;
n.push(i.name);
}
}
if (n.length > 0 && r !== -1) t.push({
start: r,
end: e.length
});
return t;
}
function visibleTokenProjection(e, t) {
if (e.type === "softbreak" || e.type === "hardbreak") return {
text: "\n",
excludedRanges: []
};
if (e.type === "html_inline" && t.isStructuralHtmlInline?.(e) === true) return null;
if (e.type === "text" || e.type === "html_inline") return {
text: e.content,
excludedRanges: []
};
if (e.type === "code_inline" || e.type === "markdown_core_html") return {
text: e.content,
excludedRanges: [{
start: 0,
end: e.content.length
}]
};
if (e.type === "image") return e.children && e.children.length > 0 ? combineVisibleTokenProjections(e.children.map((e) => visibleTokenProjection(e, t))) : {
text: e.content,
excludedRanges: []
};
return null;
}
function combineVisibleTokenProjections(e) {
let t = "";
const n = [];
for (const r of e) {
if (!r) continue;
const e = t.length;
t += r.text;
for (const t of r.excludedRanges) n.push({
start: e + t.start,
end: e + t.end
});
}
n.push(...findRawCodeContainerRanges(t));
return {
text: t,
excludedRanges: n
};
}
function cloneToken(e, t, n, r, i = t.type) {
const a = new e(i, i === "assistant_transcript_role_text" ? "" : t.tag, 0);
Object.assign(a, t);
a.type = i;
a.content = t.content.slice(n, r);
a.children = null;
return copyHtmlTags(t, a, n, r);
}
function sliceRoleHeaderSpans(e, t, n, r) {
const i = [];
for (let a = t; a < e.length; a += 1) {
const t = e[a];
if (!t || t.start >= r) break;
if (t.end > n) i.push({
...t,
start: Math.max(t.start, n) - n,
end: Math.min(t.end, r) - n
});
}
return i;
}
function splitVisibleToken(e, t, n) {
if (n.length === 0) return [t];
const r = [];
let i = 0;
for (const a of n) {
if (a.start > i) r.push(cloneToken(e, t, i, a.start));
if (a.end > a.start) {
const n = cloneToken(e, t, a.start, a.end, ASSISTANT_TRANSCRIPT_ROLE_NODE_TYPE);
n.meta = {
...t.meta && typeof t.meta === "object" ? t.meta : {},
assistantTranscriptRoleHeader: {
kind: a.kind,
role: a.role
}
};
r.push(n);
}
i = a.end;
}
if (i < t.content.length) r.push(cloneToken(e, t, i, t.content.length));
return r;
}
function removeLinksContainingAssistantTranscriptRoles(e) {
const t = [];
const n = /* @__PURE__ */ new Set();
for (const r of e) {
if (r.type === "link_open") {
t.push({
token: r,
containsRole: false
});
continue;
}
const e = r.meta?.assistantTranscriptRoleImage;
if (r.type === "assistant_transcript_role_text" || e?.spans.length) {
for (const e of t) e.containsRole = true;
continue;
}
if (r.type !== "link_close") continue;
const i = t.pop();
if (!i?.containsRole) continue;
n.add(i.token);
n.add(r);
}
const r = [];
for (const t of e) {
if (n.has(t)) continue;
const e = r.at(-1);
if (e?.type === "assistant_transcript_role_text" && t.type === "assistant_transcript_role_text") {
appendHtmlTags(e, t, e.content.length);
e.content += t.content;
continue;
}
r.push(t);
}
return r;
}
/** Adds semantic transcript-role tokens to assistant-authored Markdown only. */
function markdownItAssistantTranscriptRoles(e, t = {}) {
e.core.ruler.after("text_join", "assistant_transcript_roles", (e) => {
if (e.env?.assistantTranscriptRoleHeaders !== true) return;
const n = [];
const r = e.env?.assistantTranscriptRolePreserveLinks === true;
for (const i of e.tokens) {
if (i.type === "inline" && i.children) {
const a = e.Token;
const o = i.children;
const s = o.map((e) => visibleTokenProjection(e, t));
const c = combineVisibleTokenProjections(s);
const l = findAssistantTranscriptRoleHeaderSpans(c.text, c.excludedRanges);
if (l.length === 0) {
i.children = o;
n.push(i);
continue;
}
const u = [];
let d = 0;
let f = 0;
for (const [e, t] of o.entries()) {
const n = s[e];
if (!n) {
u.push(t);
continue;
}
const r = n.text;
for (;;) {
const e = l[f];
if (!e || e.end > d) break;
f += 1;
}
const i = d + r.length;
if (t.type === "text" || t.type === "html_inline") u.push(...splitVisibleToken(a, t, sliceRoleHeaderSpans(l, f, d, i)));
else if (t.type === "image") {
const e = sliceRoleHeaderSpans(l, f, d, i);
if (e.length > 0) t.meta = {
...t.meta && typeof t.meta === "object" ? t.meta : {},
assistantTranscriptRoleImage: {
text: r,
spans: e
}
};
u.push(t);
} else u.push(t);
d += r.length;
}
i.children = r ? u : removeLinksContainingAssistantTranscriptRoles(u);
n.push(i);
continue;
}
if (i.type === "html_block") {
const t = findAssistantTranscriptRoleHeaderSpans(i.content, findRawCodeContainerRanges(i.content));
n.push(...splitVisibleToken(e.Token, i, t));
continue;
}
n.push(i);
}
e.tokens = n;
});
}
//#endregion
//#region packages/markdown-core/src/chunk-text.ts
function normalizeChunkLimit(e) {
return Number.isFinite(e) && e > 0 ? resolveIntegerOption(e, 1, { min: 1 }) : e;
}
function findPreferredRangeEnd(e, t, n) {
const r = e.slice(t, n);
let i;
for (const e of r.matchAll(/\n[\t ]*\n+/g)) i = t + e.index + e[0].length;
if (i !== void 0) return i;
const a = r.lastIndexOf("\n");
if (a >= 0) return t + a + 1;
for (let r = n - 1; r > t; r -= 1) if (/\s/.test(e.charAt(r))) return r + 1;
}
/**
* Splits text into contiguous UTF-16 ranges without dropping separator whitespace.
* Preferred mode selects paragraph, newline, then whitespace boundaries.
*/
function chunkTextRanges(e, t) {
if (!e) return [];
const n = normalizeChunkLimit(t.limit);
if (n <= 0 || e.length <= n) return [{
start: 0,
end: e.length
}];
const r = [];
let i = 0;
while (i < e.length) {
const a = Math.min(e.length, i + n);
const o = t.mode === "preferred" && a < e.length ? findPreferredRangeEnd(e, i, a) : void 0;
const s = findGraphemeChunkEnd(e, i, a, o);
r.push({
start: i,
end: s
});
i = s;
}
return r;
}
/**
* Splits plain text into size-bounded chunks at readable boundaries.
*
* Returns the original text as one chunk when the limit is non-positive.
*/
function chunkText(e, t) {
const n = normalizeChunkLimit(t);
if (!e) return [];
if (n <= 0 || e.length <= n) return [e];
const r = [];
let i = 0;
while (i < e.length) {
if (e.length - i <= n) {
r.push(e.slice(i));
break;
}
const t = Math.min(e.length, i + n);
const a = e.slice(i, t);
const { lastNewline: o, lastWhitespace: s } = scanParenAwareBreakpoints(a, 0, a.length);
const c = findGraphemeChunkEnd(e, i, t, i + (o > 0 ? o : s));
r.push(e.slice(i, c));
i = skipWhitespaceGraphemes(e, c);
}
return r;
}
//#endregion
//#region packages/markdown-core/src/ir-spans.ts
/** Apply disjoint edits; equal-position insertions keep caller order and shift their boundary. */
function applyMarkdownTextEdits(e, t) {
let n = "";
let r = 0;
const i = t.toSorted((e, t) => e.start - t.start || e.end - t.end).map((t) => {
n += e.slice(r, t.start) + t.text;
r = t.end;
return {
end: t.end,
shift: n.length - r
};
});
return {
text: n + e.slice(r),
mapOffset: (e) => {
let t = 0;
let n = i.length;
while (t < n) {
const r = t + Math.floor((n - t) / 2);
if ((i[r]?.end ?? Number.POSITIVE_INFINITY) <= e) t = r + 1;
else n = r;
}
return e + (i[t - 1]?.shift ?? 0);
}
};
}
const MARKDOWN_STYLE_ORDER = [
"blockquote",
"code_block",
"code",
"heading_1",
"heading_2",
"heading_3",
"heading_4",
"heading_5",
"heading_6",
"bold",
"italic",
"underline",
"strikethrough",
"spoiler"
];
const autoLinkedMarkdownLinks = /* @__PURE__ */ new WeakSet();
/** Callers supply a fresh span; transforms copy before attaching provenance. */
function createMarkdownLinkSpan(e, t) {
if (t) autoLinkedMarkdownLinks.add(e);
return e;
}
function copyMarkdownLinkSpan(e, t) {
return createMarkdownLinkSpan({
...e,
...t
}, autoLinkedMarkdownLinks.has(e));
}
function isAutoLinkedMarkdownLink(e) {
return autoLinkedMarkdownLinks.has(e);
}
function createStyleSpan(e) {
const t = {
start: e.start,
end: e.end,
style: e.style
};
if (e.language) t.language = e.language;
return t;
}
function clipSpans(e, t, n, r) {
const i = [];
for (const a of e) {
const e = Math.max(a.start, t);
const o = Math.min(a.end, n);
if (o > e) {
const n = r(a);
n.start = e - t;
n.end = o - t;
i.push(n);
}
}
return i;
}
function mergeAnnotationSpans(e) {
const t = e.toSorted((e, t) => e.start - t.start || e.end - t.end);
const n = [];
for (const e of t) {
const t = n.at(-1);
if (t && t.end === e.start && t.kind === e.kind && t.role === e.role) {
t.end = e.end;
continue;
}
n.push({ ...e });
}
return n;
}
function mergeStyleSpans(e) {
const t = e.toSorted((e, t) => {
if (e.start !== t.start) return e.start - t.start;
if (e.end !== t.end) return e.end - t.end;
return e.style.localeCompare(t.style);
});
const n = [];
for (const e of t) {
const t = n.at(-1);
if (t && t.style === e.style && t.language === e.language && (e.start < t.end || e.start === t.end && e.style !== "blockquote")) {
t.end = Math.max(t.end, e.end);
continue;
}
n.push({ ...e });
}
return n;
}
function sliceStyleSpans(e, t, n) {
return mergeStyleSpans(clipSpans(e, t, n, createStyleSpan));
}
function sliceLinkSpans(e, t, n) {
return clipSpans(e, t, n, copyMarkdownLinkSpan);
}
function sliceAnnotationSpans(e, t, n) {
return mergeAnnotationSpans(clipSpans(e, t, n, (e) => ({ ...e })));
}
//#endregion
//#region packages/markdown-core/src/ir-annotations.ts
function rangesOverlap(e, t) {
return e.start < t.end && e.end > t.start;
}
/** Re-evaluate the first visible line after a transport creates a new message boundary. */
function annotateAssistantTranscriptRoleMessageBoundary(e) {
const t = e.text.indexOf("\n");
const n = t === -1 ? e.text : e.text.slice(0, t);
const r = e.styles.filter((e) => e.style === "code" || e.style === "code_block").filter((e) => e.start < n.length).map(({ start: e, end: t }) => ({
start: e,
end: Math.min(t, n.length)
}));
const i = findAssistantTranscriptRoleHeaderSpans(n, r)[0];
if (!i || (e.annotations ?? []).some((e) => rangesOverlap(e, i))) return e;
const a = {
...i,
type: "assistant_transcript_role"
};
return copyHtmlTags(e, {
...e,
links: e.links.filter((e) => !rangesOverlap(e, a)),
annotations: mergeAnnotationSpans([...e.annotations ?? [], a])
});
}
function appendAssistantTranscriptRoleText(e, t, n) {
if (!t) return;
const r = e.text.length;
e.text += t;
e.annotations.push({
start: r,
end: e.text.length,
type: "assistant_transcript_role",
kind: n.kind,
role: n.role
});
}
/** Image alternatives are plain text, including labels projected for annotations. */
function appendImageAlternative(e, t) {
if (!t.text) return;
const n = e.text.length;
e.text += t.text;
for (const r of t.spans) e.annotations.push({
...r,
start: n + r.start,
end: n + r.end,
type: "assistant_transcript_role"
});
}
//#endregion
//#region packages/markdown-core/src/ir-slice.ts
function normalizeSliceRange(e, t, n) {
const r = e.text.length;
const i = Math.trunc(t) || 0;
const a = Math.trunc(n) || 0;
let o = i < 0 ? Math.max(r + i, 0) : Math.min(i, r);
let s = a < 0 ? Math.max(r + a, 0) : Math.min(a, r);
if (o < s) {
const t = avoidTrailingHighSurrogateBreak(e.text, 0, o);
if (t !== o) o = t < o ? t : o - 1;
const n = avoidTrailingHighSurrogateBreak(e.text, 0, s);
if (n !== s) s = n > s ? n : s + 1;
}
return {
start: o,
end: s
};
}
function sliceMarkdownIR(e, t, n) {
return sliceNormalizedMarkdownIR(e, normalizeSliceRange(e, t, n));
}
function sliceNormalizedMarkdownIR(e, { start: t, end: n }) {
const r = e;
const i = sliceAnnotationSpans(e.annotations ?? [], t, n);
const a = (e.listItems ?? []).flatMap((e) => {
const r = e.listMarker ? sliceListMarker(e.listMarker, t, n) : void 0;
const i = e.taskMarker ? sliceListMarker(e.taskMarker, t, n) : void 0;
const a = e.contentStart !== void 0 && e.contentEnd !== void 0 ? sliceListMarker({
start: e.contentStart,
end: e.contentEnd
}, t, n) : void 0;
return r || i ? [copyMarkdownListItem(e, {
listMarker: r,
taskMarker: i,
start: e.start !== void 0 ? Math.max(e.start, t) - t : void 0,
end: e.end !== void 0 ? Math.min(e.end, n) - t : void 0,
contentStart: a?.start,
contentEnd: a?.end,
markerOnly: e.markerOnly
})] : [];
});
const o = (r.blocks ?? []).flatMap((e) => {
if (e.start === e.end) return (t === n ? e.start === t : e.start >= t && e.start < n) ? [{
...e,
start: e.start - t,
end: e.end - t
}] : [];
const r = sliceListMarker(e, t, n);
return r ? [{
...e,
...r
}] : [];
});
const s = {
text: e.text.slice(t, n),
styles: sliceStyleSpans(e.styles, t, n),
links: sliceLinkSpans(e.links, t, n),
...i.length > 0 ? { annotations: i } : {},
...a.length > 0 ? { listItems: a } : {}
};
return copyHtmlTags(e, attachBlockMetadata(s, o), t, n);
}
/** Chunkers supply ordered, disjoint ranges; metadata itself need not be sorted. */
function sliceMarkdownIRRanges(e, t) {
const n = t.map(({ start: t, end: n }) => ({
range: normalizeSliceRange(e, t, n),
metadata: {
text: e.text,
styles: [],
links: []
}
}));
function firstRangeEndingAtOrAfter(e) {
let t = 0;
let r = n.length;
while (t < r) {
const i = Math.floor((t + r) / 2);
const a = n[i];
if (a && a.range.end < e) t = i + 1;
else r = i;
}
return t;
}
function visitRanges(e, t, r) {
for (let i = firstRangeEndingAtOrAfter(e); i < n.length; i += 1) {
const e = n[i];
if (!e || e.range.start > t) break;
r(e.metadata, i);
}
}
for (const t of e.styles) visitRanges(t.start, t.end, (e) => e.styles.push(t));
for (const t of e.links) visitRanges(t.start, t.end, (e) => e.links.push(t));
for (const t of e.annotations ?? []) visitRanges(t.start, t.end, (e) => (e.annotations ??= []).push(t));
for (const t of e.listItems ?? []) {
const e = /* @__PURE__ */ new Set();
for (const n of [t.listMarker, t.taskMarker]) {
if (!n) continue;
visitRanges(n.start, n.end, (n, r) => {
if (!e.has(r)) {
e.add(r);
(n.listItems ??= []).push(t);
}
});
}
}
const r = e;
for (const e of r.blocks ?? []) visitRanges(e.start, e.end, (t) => (t.blocks ??= []).push(e));
for (const t of e.htmlTags ?? []) for (let e = firstRangeEndingAtOrAfter(t.end); e < n.length; e += 1) {
const r = n[e];
if (!r || r.range.start > t.start) break;
(r.metadata.htmlTags ??= []).push(t);
}
return n.map(({ metadata: e, range: t }) => sliceNormalizedMarkdownIR(e, t));
}
//#endregion
//#region packages/markdown-core/src/ir-source-spacing.ts
/** Prepare the next mapped block start for each token in one reverse pass. */
function computeNextMappedBlockStarts(e) {
const t = [];
let n;
for (let r = e.length - 1; r >= 0; r -= 1) {
t[r] = n;
const i = e[r]?.map?.[0];
if (i !== void 0) n = i;
}
return t;
}
function sourceBlockNewlineCount(e, t, n) {
if (!e || n === void 0) return;
return t === void 0 ? 0 : Math.max(1, t - n + 1);
}
//#endregion
//#region packages/markdown-core/src/table-layout.ts
/** Shared bullet layout, including the newline contributed by empty rows. */
function renderMarkdownTableBullets(e, t, n, r) {
const i = e.length > 1;
for (const a of t) {
if (i && a[0]?.text) {
r(a[0], true);
n("\n");
}
for (let t = i ? 1 : 0; t < a.length; t += 1) {
const o = a[t];
if (!o?.text) continue;
n("• ");
const s = e[t];
if (s?.text) {
r(s, false);
n(": ");
} else if (i) n(`Column ${t}: `);
r(o, false);
n("\n");
}
n("\n");
}
}
/** Render the existing aligned, plain-text representation without a Markdown fence. */
function renderMarkdownCodeTable(e, t) {
const n = [e, ...t].map((e) => e.map((e) => ({
text: e,
width: visibleWidth(e)
})));
const r = [];
for (const e of n) for (const [t, n] of e.entries()) r[t] = Math.max(r[t] ?? 3, n.width);
if (r.length === 0) return "";
const renderRow = (e) => `|${r.map((t, n) => ` ${e[n]?.text ?? ""}${" ".repeat(t - (e[n]?.width ?? 0))} |`).join("")}`;
const i = r.map((e) => ({
text: "-".repeat(e),
width: e
}));
n.splice(1, 0, i);
return [...n.map(renderRow), ""].join("\n");
}
//#endregion
//#region packages/markdown-core/src/ir.ts
const INLINE_STYLE_BY_TOKEN = /* @__PURE__ */ new Map([
["underline_open", "underline"],
["underline_close", "underline"],
["em_open", "italic"],
["em_close", "italic"],
["strong_open", "bold"],
["strong_close", "bold"],
["s_open", "strikethrough"],
["s_close", "strikethrough"],
["spoiler_open", "spoiler"],
["spoiler_close", "spoiler"]
]);
const HEADING_STYLE_BY_TAG = /* @__PURE__ */ new Map([
["h1", "heading_1"],
["h2", "heading_2"],
["h3", "heading_3"],
["h4", "heading_4"],
["h5", "heading_5"],
["h6", "heading_6"]
]);
/** Private source coordinates do not change the serialized native-table payload. */
function getMarkdownTableSource(e) {
return e.source;
}
function appendHeadingSeparator(e, t) {
const n = sourceBlockNewlineCount(e.preserveSourceBlockSpacing, t, e.headingLineEnd);
if (n === void 0) {
appendParagraphSeparator(e, void 0, t);
return;
}
if (n > 0) e.text += "\n".repeat(n);
e.headingLineEnd = void 0;
}
const markdownParsers = /* @__PURE__ */ new Map();
function createMarkdownIt(e) {
const t = (e.linkify ?? true ? 1 : 0) | (e.preserveDunderIdentifiers ? 2 : 0) | (e.enableTaskLists ? 4 : 0) | (e.enableHtmlUnderline ? 8 : 0) | (e.enableSpoilers ? 16 : 0) | (e.tableMode && e.tableMode !== "off" ? 32 : 0) | (e.autolink === false ? 64 : 0) | (e.allowAllLinkSchemes ? 128 : 0);
const n = markdownParsers.get(t);
if (n) return n;
const r = new MarkdownItCallable({
html: false,
linkify: e.linkify ?? true,
breaks: false,
typographer: false
});
r.linkify.set({ fuzzyLink: true });
r.use(markdownItCjkFriendlyPlugin);
r.use(markdownItAssistantTranscriptRoles);
if (e.preserveDunderIdentifiers) r.inline.ruler.before("emphasis", "markdown_core_dunder_identifiers", preserveDunderIdentifier);
if (e.enableTaskLists) r.core.ruler.before("inline", "markdown_core_task_lists", protectTaskListMarkers);
const i = e.enableHtmlUnderline === true;
r.inline.ruler.before("html_inline", RAW_HTML_TOKEN_TYPE, (e, t) => parseHtmlLexeme(e, t, i));
if (e.enableSpoilers) r.core.ruler.before("assistant_transcript_roles", "markdown_core_spoilers", (e) => {
applySpoilerTokens(e.tokens);
});
r.enable("strikethrough");
if (e.tableMode && e.tableMode !== "off") {
r.enable("table");
r.block.ruler.before("table", "markdown_core_table_source", (e, t, n, r) => {
const i = e.env;
if (!r && i.tableSourceColumns) {
const n = (e.bMarks[t] ?? 0) + (e.tShift[t] ?? 0);
i.tableSourceColumns.set(t, n - e.src.lastIndexOf("\n", n - 1) - 1);
}
return false;
});
} else r.disable("table");
if (e.autolink === false) r.disable("autolink");
if (e.allowAllLinkSchemes) r.validateLink = () => true;
markdownParsers.set(t, r);
return r;
}
/** Count fenced code body characters using the same block grammar as rendering. */
function countMarkdownFencedCodeChars(e) {
if (!e.includes("```") && !e.includes("~~~")) return 0;
const t = createMarkdownIt({
linkify: false,
autolink: false,
tableMode: "bullets"
});
let n = 0;
for (const r of t.parse(e, {})) if (r.type === "fence") n += r.content.length - (r.content.endsWith("\n") ? 1 : 0);
return n;
}
/** Locate table source ranges using the same block grammar as table rendering. */
function findMarkdownTableRanges(e) {
if (!e.includes("|")) return [];
const t = createMarkdownIt({
linkify: false,
autolink: false,
tableMode: "block"
}).parse(e, {}).flatMap((e) => e.type === "table_open" && e.map ? [e.map] : []);
if (t.length === 0) return [];
const { lines: n, starts: r } = indexSourceLines(e);
return t.map(([e, t]) => ({
start: r[e] ?? 0,
end: (r[t - 1] ?? 0) + (n[t - 1]?.length ?? 0)
}));
}
function preserveDunderIdentifier(e, t) {
const n = /^__[\p{L}_][\p{L}\p{N}_]*__/u.exec(e.src.slice(e.pos, e.posMax));
if (!n) return false;
const r = n[0];
const i = e.pos + r.length;
const a = e.src[e.pos - 1];
const o = e.src[e.pos - 2];
const s = i < e.posMax ? e.src[i] : void 0;
const c = a === ".";
const l = s === "(";
const u = a === "(" && /[\p{L}\p{N}_]/u.test(o ?? "");
if (!c && !l && !u && !(s === "[")) return false;
if (!t) e.push("text", "", 0).content = r;
e.pos = i;
return true;
}
function protectTaskListMarkers(e) {
const t = [];
for (const n of e.tokens) {
if (n.type === "list_item_open") {
t.push({ contentStarted: false });
continue;
}
if (n.type === "list_item_close") {
t.pop();
continue;
}
const e = t.at(-1);
if (!e || e.contentStarted) continue;
if (n.type === "inline") {
e.contentStarted = true;
if (/^\[[ xX]\](?:[ \t]|\n|$)/u.test(n.content ?? "")) {
n.taskListMarker = true;
n.content = `\\${n.content}`;
}
continue;
}
if (n.type !== "paragraph_open") e.contentStarted = true;
}
}
function parseHtmlLexeme(e, t, n) {
if (e.src.charCodeAt(e.pos) !== 60) return false;
const r = matchMarkdownHtmlTag(e.src.slice(e.pos));
if (!r) return false;
const i = tokenizeHtmlTags(r).next().value;
const a = n && i && (i.name === "u" || i.name === "ins") ? i : void 0;
if (!t) {
const t = e.push(!a || a.selfClosing ? RAW_HTML_TOKEN_TYPE : a.closing ? "underline_close" : "underline_open", "", 0);
if (!a || a.selfClosing) {
t.content = r;
if (i) defineMetadata(t, "htmlTags", [i]);
}
}
e.pos += r.length;
return true;
}
function getAttr(e, t) {
return e.attrGet ? e.attrGet(t) : e.attrs?.find(([e]) => e === t)?.[1] ?? null;
}
function markdownTableAlignmentFromToken(e) {
const t = getAttr(e, "style") ?? "";
if (/text-align\s*:\s*left/i.test(t)) return "left";
if (/text-align\s*:\s*center/i.test(t)) return "center";
if (/text-align\s*:\s*right/i.test(t)) return "right";
}
function createTextToken(e, t) {
return {
...e,
type: "text",
content: t,
children: void 0
};
}
function applySpoilerTokens(e) {
for (const t of e) if (t.children && t.children.length > 0) t.children = injectSpoilersIntoInline(t.children);
}
function injectSpoilersIntoInline(e) {
let t = 0;
for (const n of e) {
if (n.type !== "text") continue;
const e = n.content ?? "";
let r = 0;
while (r < e.length) {
const n = e.indexOf("||", r);
if (n === -1) break;
t += 1;
r = n + 2;
}
}
if (t < 2) return e;
const n = t - t % 2;
const r = [];
let i = false;
let a = 0;
for (const t of e) {
if (t.type !== "text") {
r.push(t);
continue;
}
const e = t.content ?? "";
if (!e.includes("||")) {
r.push(t);
continue;
}
let o = 0;
while (o < e.length) {
const s = e.indexOf("||", o);
if (s === -1) {
r.push(createTextToken(t, e.slice(o)));
break;
}
if (a >= n) {
r.push(createTextToken(t, e.slice(o)));
break;
}
if (s > o) r.push(createTextToken(t, e.slice(o, s)));
a += 1;
i = !i;
r.push({ type: i ? "spoiler_open" : "spoiler_close" });
o = s + 2;
}
}
return r;
}
function initRenderTarget() {
return {
text: "",
styles: [],
openStyles: [],
links: [],
linkStack: [],
annotations: []
};
}
function resolveRenderTarget(e) {
return e.table?.currentCell ?? e;
}
function appendText(e, t, n) {
if (!t) return;
const r = resolveRenderTarget(e);
appendHtmlTags(r, n, r.text.length);
r.text += t;
}
function openStyle(e, t) {
const n = resolveRenderTarget(e);
n.openStyles.push({
style: t,
start: n.text.length
});
}
function closeStyle(e, t, n) {
const r = resolveRenderTarget(e);
for (let e = r.openStyles.length - 1; e >= 0; e -= 1) {
const i = r.openStyles.at(e);
if (i?.style === t) {
const a = i.start;
r.openStyles.splice(e, 1);
const o = n ?? r.text.length;
if (o > a) r.styles.push({
start: a,
end: o,
style: t
});
return;
}
}
}
function appendParagraphSeparator(e, t, n) {
if (e.table) return;
if (e.env.listStack.length > 0) {
const r = (e.env.listStack[e.env.listStack.length - 1]?.openLevel ?? 0) + 2;
const i = e.openListItems.at(-1)?.sourceEndLine;
if (!(n !== void 0 && i !== void 0 && n < i) && (t?.type !== "paragraph_close" || t.hidden || t.level !== r)) return;
}
e.text += t?.hidden ? "\n" : "\n\n";
}
function appendTopLevelListSeparator(e) {
if (!e.text.endsWith("\n\n")) e.text += "\n";
}
function appendNestedListSeparator(e) {
if (!e.text.endsWith("\n")) e.text += "\n";
}
function appendListPrefix(e, t) {
const n = e.env.listStack;
const r = n[n.length - 1];
if (!r) return;
r.index += 1;
const i = e.text.length;
const a = " ".repeat(Math.max(0, n.length - 1));
const o = r.type === "ordered" ? `${r.index}. ` : "• ";
e.text += a;
const s = e.text.length;
e.text += o;
return {
kind: r.type,
listMarker: {
start: s,
end: e.text.length
},
listId: r.id,
...r.parentId !== void 0 ? { parentListId: r.parentId } : {},
depth: n.length - 1,
start: i,
...t ? { task: true } : {}
};
}
function recordTaskMarker(e, t) {
const n = e.openListItems.at(-1);
if (!n?.task || n.taskMarker) return;
const r = /^\[[ xX]\][ \t]?/u.exec(t)?.[0];
if (r) {
const t = resolveRenderTarget(e).text.length;
n.taskMarker = {
start: t,
end: t + r.length
};
}
}
function recordListSourceMetadata(e, t, n) {
if (!n.map) return;
const { lines: r, starts: i, openedByLine: a } = e.sourceIndex ??= indexSourceLines(e.source);
const [o, s] = n.map;
t.sourceStartLine = o;
t.sourceEndLine = s;
const c = r[o] ?? "";
const l = [...c.matchAll(/(?:^|[\t >])([-*+]|\d{1,9}[.)])(?=[\t ]|$)/gu)];
const u = a.get(o) ?? 0;
a.set(o, u + 1);
const d = l[Math.min(u, l.length - 1)];
const f = d?.[1];
if (!d || !f) return;
const p = d.index + d[0].lastIndexOf(f);
const m = p + f.length;
let h = m;
while (h < c.length && /[\t ]/u.test(c[h] ?? "")) h += 1;
const g = markdownSourceColumn(c.slice(0, m));
const _ = markdownSourceColumn(c.slice(0, h)) - g;
t.sourceIndent = g + (_ === 0 || _ > 4 ? 1 : _);
const v = _ > 4 ? Math.min(m + 1, h) : h;
const y = i[o] ?? 0;
t.sourceMarker = {
start: y + p,
end: y + p + f.length
};
t.sourceContent = {
start: y + v,
end: i[s] ?? e.source.length
};
if (!c.slice(v).replace(/[ \t\r\n]/gu, "")) t.markerOnly = true;
}
function renderInlineCode(e, t) {
if (!t) return;
const n = resolveRenderTarget(e);
const r = n.text.length;
n.text += t;
n.styles.push({
start: r,
end: r + t.length,
style: "code"
});
}
function renderCodeBlock(e, t, n, r, i, a, o) {
let s = t;
if (!s.endsWith("\n")) s = `${s}\n`;
const c = resolveRenderTarget(e);
const l = c.text.length;
const u = n?.trim().split(/\s+/, 1)[0] || void 0;
c.text += s;
c.styles.push(createStyleSpan({
start: l,
end: l + s.length,
style: "code_block",
language: u
}));
e.blocks.push({
kind: "code_block",
start: l,
end: l + s.length,
depth: e.env.listStack.length + e.blockquoteStack.length + 1,
blockquoteDepth: e.blockquoteStack.length,
codeOrigin: i,
...o !== void 0 ? { codeClosed: o } : {},
...u ? { language: u } : {},
...a ? {
sourceStartLine: a[0],
sourceEndLine: a[1]
} : {}
});
if (e.env.listStack.length === 0) {
const e = r === void 0 ? 1 : Math.max(0, r - 1);
c.text += "\n".repeat(e);
}
}
function isFenceClosed(e) {
const t = (e.map?.[1] ?? 0) - (e.map?.[0] ?? 0);
const n = e.content ?? "";
return t >= (n.match(/\n/gu)?.length ?? 0) + (n && !n.endsWith("\n") ? 1 : 0) + 2;
}
function markdownSourceColumn(e) {
let t = 0;
for (const n of e) t += n === " " ? 4 - t % 4 : 1;
return t;
}
function handleLinkClose(e) {
const t = resolveRenderTarget(e);
const n = t.linkStack.pop();
if (!n?.href) return;
const r = n.href.trim();
if (!r) return;
const i = n.labelStart;
const a = t.text.length;
const o = createMarkdownLinkSpan({
start: i,
end: a,
href: r
}, n.autoLinked);
t.links.push(o);
}
function initTableState() {
return {
sourceHeaders: [],
sourceRows: [],
currentSourceRow: [],
headers: [],
rows: [],
aligns: [],
currentRow: [],
currentCell: null,
inHeader: false
};
}
function finishTableCell(e) {
closeRemainingStyles(e);
return copyHtmlTags(e, {
text: e.text,
styles: e.styles,
links: e.links,
...e.annotations.length > 0 ? { annotations: e.annotations } : {}
});
}
function trimCell(e) {
const t = e.text;
let n = t.length - t.trimStart().length;
let r = t.trimEnd().length;
for (const t of e.styles) if (t.style === "code") {
n = Math.min(n, t.start);
r = Math.max(r, t.end);
}
return n === 0 && r === t.length ? e : sliceMarkdownIR(e, n, r);
}
function appendCell(e, t) {
if (!t.text) return;
appendMarkdownIR(e, copyHtmlTags(t, {
text: t.text,
styles: t.styles.map(({ start: e, end: t, style: n }) => ({
start: e,
end: t,
style: n
})),
links: t.links.map((e) => copyMarkdownLinkSpan(e)),
annotations: t.annotations?.map((e) => ({ ...e }))
}));
}
function collectTableBlock(e, t, n, r) {
const i = {
headers: n.map((e) => e.text),
rows: r.map((e) => e.map((e) => e.text)),
headerCells: n,
rowCells: r,
placeholderOffset: e.text.length,
...t.aligns.some(Boolean) ? { aligns: [...t.aligns] } : {}
};
e.collectedTables.push(i);
if (t.sourceLines) {
const [n, r] = t.sourceLines;
const { lines: a, starts: o } = e.sourceIndex ??= indexSourceLines(e.source);
const s = e.env.tableSourceColumns?.get(n) ?? 0;
defineMetadata(i, "source", {
start: (o[n] ?? 0) + s,
end: (o[r - 1] ?? 0) + (a[r - 1]?.length ?? 0),
prefix: (a[n] ?? "").slice(0, s).replace(/[^\t >]/gu, " "),
headers: t.sourceHeaders,
rows: t.sourceRows
});
}
}
function renderTable(e) {
const t = e.table;
if (!t || ![
"block",
"bullets",
"code"
].includes(e.tableMode)) return;
const n = t.headers.map(trimCell);
const r = t.rows.map((e) => e.map(trimCell));
if (e.tableMode === "block") {
collectTableBlock(e, t, n, r);
e.text += "\n";
return;
}
if (e.tableMode === "bullets") renderMarkdownTableBullets(n, r, (t) => {
e.text += t;
}, (t, n) => {
const r = e.text.length;
appendCell(e, t);
if (n) e.styles.push({
start: r,
end: e.text.length,
style: "bold"
});
});
else {
const t = renderMarkdownCodeTable(n.map((e) => e.text), r.map((e) => e.map((e) => e.text)));
if (t) {
const n = e.text.length;
e.text += t;
e.styles.push({
start: n,
end: e.text.length,
style: "code_block"
});
if (e.env.listStack.length === 0) e.text += "\n";
}
}
}
function renderTokens(e, t) {
const n = computeNextMappedBlockStarts(e);
for (const [r, i] of e.entries()) {
const a = INLINE_STYLE_BY_TOKEN.get(i.type);
if (a) {
if (a !== "spoiler" || t.enableSpoilers) {
if (i.type.endsWith("_open")) openStyle(t, a);
else closeStyle(t, a);
}
continue;
}
switch (i.type) {
case "inline":
if (t.table?.currentCell) t.table.currentSourceRow.push(i.content ?? "");
if (i.children) renderTokens(i.children, t);
break;
case "text":
recordTaskMarker(t, i.content ?? "");
appendText(t, i.content ?? "", i);
break;
case ASSISTANT_TRANSCRIPT_ROLE_NODE_TYPE: {
const e = i.meta?.assistantTranscriptRoleHeader;
if (e) {
const n = resolveRenderTarget(t);
appendHtmlTags(n, i, n.text.length);
appendAssistantTranscriptRoleText(n, i.content ?? "", e);
} else appendText(t, i.content ?? "", i);
break;
}
case "code_inline":
renderInlineCode(t, i.content ?? "");
break;
case "link_open": {
const e = resolveRenderTarget(t);
const n = getAttr(i, "href") ?? "";
e.linkStack.push({
href: n,
labelStart: e.text.length,
autoLinked: i.markup === "linkify"
});
break;
}
case "link_close":
handleLinkClose(t);
break;
case "image": {
const e = i.meta?.assistantTranscriptRoleImage;
appendImageAlternative(resolveRenderTarget(t), e ?? {
text: i.content ?? "",
spans: []
});
break;
}
case "softbreak":
case "hardbreak":
appendText(t, "\n");
break;
case "paragraph_close":
appendParagraphSeparator(t, i, n[r]);
break;
case "heading_open":
t.headingLineEnd = i.map?.[1];
t.headingBlock = {
kind: "heading",
start: t.text.length,
end: t.text.length,
depth: t.env.listStack.length + t.blockquoteStack.length + 1,
blockquoteDepth: t.blockquoteStack.length,
headingLevel: Number.parseInt(i.tag?.slice(1) ?? "", 10),
headingOrigin: i.markup?.startsWith("#") ? "atx" : "setext",
...i.map ? {
sourceStartLine: i.map[0],
sourceEndLine: i.map[1]
} : {}
};
if (t.headingStyle === "bold") openStyle(t, "bold");
else if (t.headingStyle === "rich") {
const e = HEADING_STYLE_BY_TAG.get(i.tag ?? "");
if (e) openStyle(t, e);
}
break;
case "heading_close":
if (t.headingStyle === "bold") closeStyle(t, "bold");
else if (t.headingStyle === "rich") {
const e = HEADING_STYLE_BY_TAG.get(i.tag ?? "");
if (e) closeStyle(t, e);
}
if (t.headingBlock) t.blocks.push({
...t.headingBlock,
end: t.text.length
});
t.headingBlock = void 0;
appendHeadingSeparator(t, n[r]);
break;
case "blockquote_open":
if (t.blockquotePrefix) t.text += t.blockquotePrefix;
t.blockquoteStack.push({
start: t.text.length,
depth: t.env.listStack.length + t.blockquoteStack.length + 1,
blockquoteDepth: t.blockquoteStack.length + 1,
...i.map ? {
sourceStartLine: i.map[0],
sourceEndLine: i.map[1]
} : {}
});
openStyle(t, "blockquote");
break;
case "blockquote_close": {
const e = t.blockquoteStack.pop();
const n = Math.max(e?.start ?? 0, t.text.endsWith("\n\n") ? t.text.length - 2 : t.text.length, (t.collectedTables.at(-1)?.placeholderOffset ?? -1) + 1);
closeStyle(t, "blockquote", n);
if (e) t.blocks.push({
kind: "blockquote",
...e,
end: n
});
break;
}
case "bullet_list_open":
case "ordered_list_open": {
if (t.env.listStack.length > 0) appendNestedListSeparator(t);
const e = i.type === "ordered_list_open";
t.env.listStack.push({
type: e ? "ordered" : "bullet",
index: e ? Number(getAttr(i, "start") ?? "1") - 1 : 0,
openLevel: i.level ?? 0,
id: t.nextListId++,
...t.env.listStack.at(-1)?.id !== void 0 ? { parentId: t.env.listStack.at(-1)?.id } : {}
});
break;
}
case "bullet_list_close":
case "ordered_list_close":
t.env.listStack.pop();
if (t.env.listStack.length === 0) appendTopLevelListSeparator(t);
break;
case "list_item_open": {
const n = e[r + 1]?.type === "paragraph_open" ? e[r + 2] : void 0;
const a = appendListPrefix(t, n?.type === "inline" && n.taskListMarker === true);
if (a) {
recordListSourceMetadata(t, a, i);
t.openListItems.push(a);
}
break;
}
case "list_item_close": {
const e = t.openListItems.pop();
if (e) {
const n = t.text.length;
const r = e.listMarker?.end ?? e.start ?? n;
let i = r;
while (i < n && /[ \t\r\n]/u.test(t.text[i] ?? "")) i += 1;
let a = n;
while (a > i && /[ \t\r\n]/u.test(t.text[a - 1] ?? "")) a -= 1;
const o = t.text.indexOf("\n", r);
const s = o === -1 ? n : Math.min(o, n);
const c = !t.text.slice(r, s).replace(/[ \t\r\n]/gu, "");
t.listItems.push(copyMarkdownListItem(e, {
listMarker: e.listMarker,
taskMarker: e.taskMarker,
start: e.start,
end: n,
...a > i ? {
contentStart: i,
contentEnd: a
} : {},
markerOnly: (e.sourceMarker ? e.markerOnly : c) ? true : void 0
}));
}
if (!t.text.endsWith("\n")) t.text += "\n";
break;
}
case "code_block":
case "fence":
renderCodeBlock(t, i.content ?? "", i.info, sourceBlockNewlineCount(t.preserveSourceBlockSpacing, n[r], i.map?.[1]), i.type === "fence" ? "fenced" : "indented", i.map, i.type === "fence" ? isFenceClosed(i) : void 0);
break;
case "html_block":
case "html_inline":
case RAW_HTML_TOKEN_TYPE:
appendText(t, i.content ?? "", i);
break;
case "table_open":
if (t.tableMode !== "off") {
t.table = initTableState();
t.table.sourceLines = i.map ?? void 0;
t.hasTables = true;
}
break;
case "table_close":
renderTable(t);
t.table = null;
break;
case "thead_open":
if (t.table) t.table.inHeader = true;
break;
case "thead_close":
if (t.table) t.table.inHeader = false;
break;
case "tbody_open":
case "tbody_close": break;
case "tr_open":
if (t.table) {
t.table.currentRow = [];
t.table.currentSourceRow = [];
}
break;
case "tr_close":
if (t.table) {
if (t.table.inHeader) {
t.table.headers = t.table.currentRow;
t.table.sourceHeaders = t.table.currentSourceRow;
} else {
t.table.rows.push(t.table.currentRow);
t.table.sourceRows.push(t.table.currentSourceRow);
}
t.table.currentRow = [];
}
break;
case "th_open":
case "td_open":
if (t.table) {
t.table.currentCell = initRenderTarget();
if (i.type === "th_open" && t.table.inHeader) t.table.aligns[t.table.currentRow.length] = markdownTableAlignmentFromToken(i);
}
break;
case "th_close":
case "td_close":
if (t.table?.currentCell) {
t.table.currentRow.push(finishTableCell(t.table.currentCell));
t.table.currentCell = null;
}
break;
case "hr":
{
const e = t.text.length;
if (t.horizontalRuleText) t.text += `${t.horizontalRuleText}\n\n`;
t.blocks.push({
kind: "thematic_break",
start: e,
end: e + t.horizontalRuleText.length,
depth: t.env.listStack.length + t.blockquoteStack.length + 1,
blockquoteDepth: t.blockquoteStack.length,
...i.map ? {
sourceStartLine: i.map[0],
sourceEndLine: i.map[1]
} : {}
});
}
break;
default: if (i.children) renderTokens(i.children, t);
}
}
}
function closeRemainingStyles(e) {
for (const t of e.openStyles.toReversed()) {
const n = e.text.length;
if (n > t.start) e.styles.push({
start: t.start,
end: n,
style: t.style
});
}
e.openStyles = [];
}
function appendSpans(e, t, n) {
for (const r of t) {
r.start += n;
r.end += n;
e.push(r);
}
}
/** Transfers a separately owned IR slice, including its metadata, into an accumulator. */
function appendMarkdownIR(e, t) {
const n = e.text.length;
appendHtmlTags(e, t, n);
e.text += t.text;
appendSpans(e.styles, t.styles, n);
appendSpans(e.links, t.links, n);
if (t.annotations?.length) appendSpans(e.annotations ??= [], t.annotations, n);
const r = t.listItems ?? [];
for (const t of r) {
for (const e of [t.listMarker, t.taskMarker]) if (e) {
e.start += n;
e.end += n;
}
for (const e of [
"start",
"end",
"contentStart",
"contentEnd"
]) {
const r = t[e];
if (r !== void 0) t[e] = r + n;
}
(e.listItems ??= []).push(t);
}
const i = t;
if (i.blocks?.length) {
const t = e.blocks ?? [];
appendSpans(t, i.blocks, n);
attachBlockMetadata(e, t);
}
}
function markdownToIR(e, t = {}) {
return markdownToIRWithMeta(e, t).ir;
}
function indexSourceLines(e) {
const t = [];
const n = [];
let r = 0;
for (let i = 0; i < e.length; i += 1) {
const a = e[i];
if (a !== "\r" && a !== "\n") continue;
n.push(r);
t.push(e.slice(r, i));
if (a === "\r" && e[i + 1] === "\n") i += 1;
r = i + 1;
}
n.push(r);
t.push(e.slice(r));
return {
lines: t,
starts: n,
openedByLine: /* @__PURE__ */ new Map()
};
}
function markdownToIRWithMeta(e, t = {}) {
const n = e ?? "";
const r = {
listStack: [],
...t.tableMode === "block" ? { tableSourceColumns: /* @__PURE__ */ new Map() } : {},
assistantTranscriptRoleHeaders: t.assistantTranscriptRoleHeaders === true,
assistantTranscriptRolePreserveLinks: t.assistantTranscriptRoleHeaders === true
};
const i = createMarkdownIt(t).parse(n, r);
const a = t.tableMode ?? "off";
const o = {
...initRenderTarget(),
env: r,
headingStyle: t.headingStyle ?? "none",
blockquotePrefix: t.blockquotePrefix ?? "",
enableSpoilers: t.enableSpoilers ?? false,
tableMode: a,
table: null,
hasTables: false,
collectedTables: [],
horizontalRuleText: t.horizontalRuleText ?? "───",
preserveSourceBlockSpacing: t.preserveSourceBlockSpacing ?? false,
headingLineEnd: void 0,
listItems: [],
openListItems: [],
nextListId: 0,
blocks: [],
headingBlock: void 0,
blockquoteStack: [],
source: n,
sourceIndex: void 0
};
renderTokens(i, o);
closeRemainingStyles(o);
const s = o.text.trimEnd().length;
let c = 0;
for (const e of o.styles) {
if (e.style !== "code" && e.style !== "code_block") continue;
c = Math.max(c, e.end);
}
const l = Math.max(s, c, (o.collectedTables.at(-1)?.placeholderOffset ?? -1) + 1);
const u = l === o.text.length ? o.text : o.text.slice(0, l);
const d = sliceAnnotationSpans(o.annotations, 0, l);
const f = o.listItems.flatMap((e) => {
const t = e.listMarker ? sliceListMarker(e.listMarker, 0, l) : void 0;
const n = e.taskMarker ? sliceListMarker(e.taskMarker, 0, l) : void 0;
return t || n ? [copyMarkdownListItem(e, {
listMarker: t,
taskMarker: n,
start: e.start !== void 0 ? Math.min(e.start, l) : void 0,
end: e.end !== void 0 ? Math.min(e.end, l) : void 0,
contentStart: e.contentStart !== void 0 ? Math.min(e.contentStart, l) : void 0,
contentEnd: e.contentEnd !== void 0 ? Math.min(e.contentEnd, l) : void 0,
markerOnly: e.markerOnly
})] : [];
});
const p = o.blocks.map((e) => {
const t = Math.min(e.start, l);
const n = Math.min(e.end, l);
return {
...e,
start: t,
end: n
};
}).toSorted((e, t) => e.start - t.start || e.end - t.end || e.depth - t.depth || e.kind.localeCompare(t.kind));
const m = {
text: u,
styles: sliceStyleSpans(o.styles, 0, l),
links: sliceLinkSpans(o.links, 0, l),
...d.length > 0 ? { annotations: d } : {},
...f.length > 0 ? { listItems: f } : {}
};
attachBlockMetadata(m, p);
copyHtmlTags(o, m, 0, l);
return {
ir: m,
hasTables: o.hasTables,
tables: o.collectedTables.map((e) => Object.assign(e, { placeholderOffset: Math.min(e.placeholderOffset, l) }))
};
}
function chunkMarkdownIR(e, t) {
if (!e.text) return [];
if (t <= 0 || e.text.length <= t) return [e];
const n = chunkText(e.text, t);
const r = [];
const i = [];
let a = 0;
n.forEach((t, n) => {
if (!t) return;
if (n > 0) while (a < e.text.length && /\s/.test(e.text[a] ?? "")) a += 1;
const o = a;
const s = Math.min(e.text.length, o + t.length);
r.push({
start: o,
end: s
});
i.push(t);
a = s;
});
return sliceMarkdownIRRanges(e, r).map((e, t) => {
e.text = i[t] ?? e.text;
return e;
});
}
//#endregion
export { tokenizeHtmlTags as C, matchMarkdownHtmlTag as S, isAutoLinkedMarkdownLink as _, getMarkdownTableSource as a, chunkTextRanges as b, renderMarkdownCodeTable as c, sliceMarkdownIRRanges as d, annotateAssistantTranscriptRoleMessageBoundary as f, createStyleSpan as g, copyMarkdownLinkSpan as h, findMarkdownTableRanges as i, renderMarkdownTableBullets as l, applyMarkdownTextEdits as m, chunkMarkdownIR as n, markdownToIR as o, MARKDOWN_STYLE_ORDER as p, countMarkdownFencedCodeChars as r, markdownToIRWithMeta as s, appendMarkdownIR as t, sliceMarkdownIR as u, mergeAnnotationSpans as v, findAssistantTranscriptRoleHeaderSpans as w, copyHtmlTags as x, mergeStyleSpans as y };