Open History to see the last commit
1import { directiveFromMarkdown } from "mdast-util-directive";
2import { directive } from "micromark-extension-directive";
3import {
4 markdownLineEnding,
5 unicodePunctuation,
6 unicodeWhitespace,
7} from "micromark-util-character";
8import type { Construct, Extension, Tokenizer } from "micromark-util-types";
9import remarkParse from "remark-parse";
10import { unified, type Processor } from "unified";
11
12import {
13 codexArtifactTemplatePresentationLabel,
14 resolveCodexArtifactTemplate,
15 type CodexArtifactTemplate,
16} from "./codexArtifactTemplates.ts";
17import { codexFileCitationMarkdown, resolveCodexFileCitationLink } from "./codexFileCitations.ts";
18
19const COLON = 58;
20const DASH = 45;
21const UNDERSCORE = 95;
22const CODEX_FILE_CITATION_NAME = "codex-file-citation";
23const CODEX_FOLLOW_UP_NAME = "codex-followup";
24const CODEX_ARTIFACT_TEMPLATE_NAME = "artifact-template";
25
26interface MarkdownPosition {
27 readonly start: { readonly offset?: number };
28 readonly end: { readonly offset?: number };
29}
30
31interface MarkdownAstNode {
32 type?: string;
33 name?: string;
34 value?: string;
35 url?: string;
36 attributes?: Readonly<Record<string, string | null>>;
37 position?: MarkdownPosition;
38 data?: {
39 codexArtifactTemplate?: CodexArtifactTemplate;
40 codexFileCitationMarkdown?: string;
41 codexFollowUp?: true;
42 hName?: string;
43 hProperties?: Record<string, unknown>;
44 };
45 children?: MarkdownAstNode[];
46}
47
48interface MarkdownFile {
49 readonly value: unknown;
50}
51
52export type CodexArtifactTemplateMarkdownSegment =
53 | { readonly kind: "markdown"; readonly markdown: string; readonly sourceOffset: number }
54 | {
55 readonly kind: "artifact-template";
56 readonly sourceOffset: number;
57 readonly template: CodexArtifactTemplate;
58 };
59
60function asConstruct(value: Construct | Construct[] | undefined, label: string): Construct {
61 const construct = Array.isArray(value) ? value[0] : value;
62 if (!construct) throw new Error(`Missing ${label} directive construct`);
63 return construct;
64}
65
66function directiveNameEnds(code: number | null): boolean {
67 return (
68 code === null ||
69 markdownLineEnding(code) ||
70 unicodeWhitespace(code) ||
71 (unicodePunctuation(code) && code !== DASH && code !== UNDERSCORE)
72 );
73}
74
75function directiveNameGate(markerCount: number, name: string): Construct {
76 const tokenize: Tokenizer = (effects, ok, nok) => {
77 let markerIndex = 0;
78 let nameIndex = 0;
79
80 return marker;
81
82 function marker(code: number | null) {
83 if (code !== COLON) return nok(code);
84 if (markerIndex === 0) effects.enter("data");
85 effects.consume(code);
86 markerIndex += 1;
87 return markerIndex === markerCount ? nameCharacter : marker;
88 }
89
90 function nameCharacter(code: number | null) {
91 if (code !== name.charCodeAt(nameIndex)) return nok(code);
92 effects.consume(code);
93 nameIndex += 1;
94 return nameIndex === name.length ? afterName : nameCharacter;
95 }
96
97 function afterName(code: number | null) {
98 effects.exit("data");
99 return directiveNameEnds(code) ? ok(code) : nok(code);
100 }
101 };
102
103 return { partial: true, tokenize };
104}
105
106function restrictedDirective(construct: Construct, markerCount: number, name: string): Construct {
107 const gate = directiveNameGate(markerCount, name);
108 return {
109 ...construct,
110 tokenize(effects, ok, nok) {
111 return effects.check(gate, construct.tokenize.call(this, effects, ok, nok), nok);
112 },
113 };
114}
115
116function codexDirectiveSyntax(): Extension {
117 const genericSyntax = directive();
118 const textDirective = asConstruct(genericSyntax.text?.[COLON], CODEX_FILE_CITATION_NAME);
119 const flowDirectives = genericSyntax.flow?.[COLON];
120 const leafDirective = Array.isArray(flowDirectives)
121 ? flowDirectives.find((construct) => construct.concrete !== true)
122 : flowDirectives;
123 if (!leafDirective)
124 throw new Error(`Missing ${CODEX_ARTIFACT_TEMPLATE_NAME} directive construct`);
125
126 return {
127 text: {
128 [COLON]: [
129 restrictedDirective(textDirective, 1, CODEX_FILE_CITATION_NAME),
130 restrictedDirective(textDirective, 1, CODEX_FOLLOW_UP_NAME),
131 ],
132 },
133 flow: {
134 [COLON]: restrictedDirective(leafDirective, 2, CODEX_ARTIFACT_TEMPLATE_NAME),
135 },
136 };
137}
138
139const CODEX_DIRECTIVE_SYNTAX = codexDirectiveSyntax();
140const CODEX_DIRECTIVE_FROM_MARKDOWN = directiveFromMarkdown();
141
142function sourceForNode(node: MarkdownAstNode, source: string): string {
143 const start = node.position?.start.offset;
144 const end = node.position?.end.offset;
145 return start === undefined || end === undefined ? "" : source.slice(start, end);
146}
147
148function textContent(node: MarkdownAstNode): string {
149 return node.value ?? (node.children ?? []).map(textContent).join("");
150}
151
152function sourceForDirective(node: MarkdownAstNode, source: string, marker: ":" | "::"): string {
153 const prefix = `${marker}${node.name ?? ""}`;
154 const slicedSource = sourceForNode(node, source);
155 if (slicedSource.startsWith(prefix)) return slicedSource;
156
157 const label = node.children?.length ? `[${textContent(node)}]` : "";
158 const attributes = Object.entries(node.attributes ?? {}).map(([name, value]) =>
159 value === null ? name : `${name}=${JSON.stringify(value)}`,
160 );
161 return `${prefix}${label}${attributes.length === 0 ? "" : `{${attributes.join(" ")}}`}`;
162}
163
164function restoreTextDirective(node: MarkdownAstNode, source: string): void {
165 node.type = "text";
166 node.value = sourceForDirective(node, source, ":");
167 delete node.name;
168 delete node.attributes;
169 delete node.url;
170 delete node.data;
171 delete node.children;
172}
173
174function restoreLeafDirective(node: MarkdownAstNode, source: string): void {
175 const value = sourceForDirective(node, source, "::");
176 node.type = "paragraph";
177 node.children = [
178 { type: "text", value, ...(node.position === undefined ? {} : { position: node.position }) },
179 ];
180 delete node.name;
181 delete node.attributes;
182 delete node.value;
183 delete node.url;
184 delete node.data;
185}
186
187function renderFileCitation(node: MarkdownAstNode, source: string, insideLink: boolean): void {
188 const citation = resolveCodexFileCitationLink(node.attributes);
189 if (!citation || insideLink) {
190 restoreTextDirective(node, source);
191 return;
192 }
193
194 node.type = "link";
195 node.url = citation.href;
196 node.children = [{ type: "text", value: citation.label }];
197 node.data = { codexFileCitationMarkdown: codexFileCitationMarkdown(citation) };
198 delete node.name;
199 delete node.attributes;
200 delete node.value;
201}
202
203function renderFollowUp(node: MarkdownAstNode, source: string): void {
204 if (!node.attributes?.prompt?.trim() || !textContent(node).trim()) {
205 restoreTextDirective(node, source);
206 return;
207 }
208
209 node.data = { codexFollowUp: true, hName: "span" };
210 delete node.name;
211 delete node.attributes;
212}
213
214function renderArtifactTemplate(node: MarkdownAstNode, source: string): void {
215 const template = resolveCodexArtifactTemplate(node.attributes);
216 if (!template) {
217 restoreLeafDirective(node, source);
218 return;
219 }
220
221 node.type = "paragraph";
222 node.children = [];
223 node.data = {
224 codexArtifactTemplate: template,
225 hName: "div",
226 hProperties: {
227 dataCodexArtifactTemplate: "true",
228 dataArtifactKind: template.artifactKind,
229 dataDisplayName: template.displayName,
230 ...(template.galleryKind === undefined ? {} : { dataGalleryKind: template.galleryKind }),
231 dataSkillDirectory: template.skillDirectory,
232 dataSkillName: template.skillName,
233 },
234 };
235 delete node.name;
236 delete node.attributes;
237 delete node.value;
238 delete node.url;
239}
240
241function transformCodexDirectives(node: MarkdownAstNode, source: string, insideLink = false): void {
242 if (node.type === "textDirective" && node.name === CODEX_FILE_CITATION_NAME) {
243 renderFileCitation(node, source, insideLink);
244 return;
245 }
246 if (node.type === "textDirective" && node.name === CODEX_FOLLOW_UP_NAME) {
247 renderFollowUp(node, source);
248 }
249 if (node.type === "leafDirective" && node.name === CODEX_ARTIFACT_TEMPLATE_NAME) {
250 renderArtifactTemplate(node, source);
251 return;
252 }
253
254 const childrenInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
255 for (const child of node.children ?? []) {
256 transformCodexDirectives(child, source, childrenInsideLink);
257 }
258}
259
260// Remark consumes one leading BOM and excludes it from AST offsets, so the
261// transform slices a once-stripped source and matches shift back past the BOM.
262const bomLength = (markdown: string) => (markdown.startsWith("\uFEFF") ? 1 : 0);
263
264function attachCodexDirectives(this: Processor) {
265 const data = this.data();
266 const micromarkExtensions = data.micromarkExtensions ?? (data.micromarkExtensions = []);
267 const fromMarkdownExtensions = data.fromMarkdownExtensions ?? (data.fromMarkdownExtensions = []);
268 micromarkExtensions.push(CODEX_DIRECTIVE_SYNTAX);
269 fromMarkdownExtensions.push(CODEX_DIRECTIVE_FROM_MARKDOWN);
270
271 return (tree: unknown, file: MarkdownFile) => {
272 const source = String(file.value);
273 transformCodexDirectives(tree as MarkdownAstNode, source.slice(bomLength(source)));
274 };
275}
276
277export const remarkCodexDirectives = attachCodexDirectives;
278
279const directiveParser = unified().use(remarkParse).use(remarkCodexDirectives).freeze();
280
281function parseCodexMarkdown(markdown: string): MarkdownAstNode {
282 return directiveParser.runSync(directiveParser.parse(markdown), {
283 value: markdown,
284 }) as MarkdownAstNode;
285}
286
287interface DirectiveMatch {
288 readonly start: number;
289 readonly end: number;
290 readonly markdown?: string;
291 readonly template?: CodexArtifactTemplate;
292 readonly labelRange?: readonly [start: number, end: number];
293}
294
295function collectDirectiveMatches(node: MarkdownAstNode, matches: DirectiveMatch[], shift: number) {
296 const at = (offset?: number) => (offset === undefined ? undefined : offset + shift);
297 const start = at(node.position?.start.offset);
298 const end = at(node.position?.end.offset);
299 if (start !== undefined && end !== undefined) {
300 if (node.data?.codexFileCitationMarkdown !== undefined) {
301 matches.push({ start, end, markdown: node.data.codexFileCitationMarkdown });
302 return;
303 }
304 if (node.data?.codexArtifactTemplate !== undefined) {
305 matches.push({ start, end, template: node.data.codexArtifactTemplate });
306 return;
307 }
308 const labelStart = at(node.children?.[0]?.position?.start.offset);
309 const labelEnd = at(node.children?.at(-1)?.position?.end.offset);
310 if (node.data?.codexFollowUp && labelStart !== undefined && labelEnd !== undefined) {
311 matches.push({ start, end, labelRange: [labelStart, labelEnd] });
312 return;
313 }
314 }
315 for (const child of node.children ?? []) collectDirectiveMatches(child, matches, shift);
316}
317
318function renderDirectiveMatches(
319 markdown: string,
320 replacementFor: (match: DirectiveMatch) => string | undefined,
321): string {
322 const matches: DirectiveMatch[] = [];
323 collectDirectiveMatches(parseCodexMarkdown(markdown), matches, bomLength(markdown));
324 let rendered = markdown;
325 for (const match of matches.sort((left, right) => right.start - left.start)) {
326 const replacement = match.labelRange
327 ? markdown.slice(...match.labelRange)
328 : replacementFor(match);
329 if (replacement !== undefined) {
330 rendered = rendered.slice(0, match.start) + replacement + rendered.slice(match.end);
331 }
332 }
333 return rendered;
334}
335
336export function renderCodexInlineDirectivesAsMarkdown(markdown: string): string {
337 if (
338 !markdown.includes(`:${CODEX_FILE_CITATION_NAME}`) &&
339 !markdown.includes(`:${CODEX_FOLLOW_UP_NAME}`)
340 ) {
341 return markdown;
342 }
343
344 return renderDirectiveMatches(markdown, (match) => match.markdown);
345}
346
347export function renderCodexDirectivesForCopy(markdown: string): string {
348 if (
349 !markdown.includes(`:${CODEX_FILE_CITATION_NAME}`) &&
350 !markdown.includes(`:${CODEX_FOLLOW_UP_NAME}`) &&
351 !markdown.includes(`::${CODEX_ARTIFACT_TEMPLATE_NAME}`)
352 ) {
353 return markdown;
354 }
355
356 return renderDirectiveMatches(markdown, (match) => {
357 if (match.markdown !== undefined) return match.markdown;
358 if (match.template === undefined) return undefined;
359 return `${match.template.displayName} (${codexArtifactTemplatePresentationLabel(match.template.artifactKind)})`;
360 });
361}
362
363export function splitCodexArtifactTemplateMarkdown(
364 markdown: string,
365): ReadonlyArray<CodexArtifactTemplateMarkdownSegment> {
366 if (!markdown.includes(`::${CODEX_ARTIFACT_TEMPLATE_NAME}`)) {
367 return [{ kind: "markdown", markdown, sourceOffset: 0 }];
368 }
369
370 const matches: DirectiveMatch[] = [];
371 collectDirectiveMatches(parseCodexMarkdown(markdown), matches, bomLength(markdown));
372 const templates = matches
373 .filter(
374 (match): match is DirectiveMatch & { readonly template: CodexArtifactTemplate } =>
375 match.template !== undefined,
376 )
377 .sort((left, right) => left.start - right.start);
378 if (templates.length === 0) {
379 return [{ kind: "markdown", markdown, sourceOffset: 0 }];
380 }
381
382 const segments: CodexArtifactTemplateMarkdownSegment[] = [];
383 let cursor = 0;
384 for (const match of templates) {
385 if (match.start > cursor) {
386 segments.push({
387 kind: "markdown",
388 markdown: markdown.slice(cursor, match.start),
389 sourceOffset: cursor,
390 });
391 }
392 segments.push({
393 kind: "artifact-template",
394 sourceOffset: match.start,
395 template: match.template,
396 });
397 cursor = match.end;
398 }
399 if (cursor < markdown.length) {
400 segments.push({ kind: "markdown", markdown: markdown.slice(cursor), sourceOffset: cursor });
401 }
402 return segments;
403}