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