Open History to see the last commit
1export type ComposerInlineToken =
2 | {
3 readonly type: "mention";
4 readonly value: string;
5 readonly source: string;
6 readonly start: number;
7 readonly end: number;
8 }
9 | {
10 readonly type: "skill";
11 readonly value: string;
12 readonly source: string;
13 readonly start: number;
14 readonly end: number;
15 };
16
17export interface CollectComposerInlineTokensOptions {
18 readonly preserveTrailingFrom?: ReadonlyArray<ComposerInlineToken>;
19}
20
21const SKILL_TOKEN_REGEX = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s)/g;
22const MENTION_TOKEN_REGEX = /(^|\s)@(?:"((?:\\.|[^"\\])*)"|([^\s@"]+))(?=\s)/g;
23/**
24 * The label body is bounded rather than `*`. Unbounded, every whitespace in
25 * the composer is a candidate start: the engine scans the rest of the text for
26 * a closing `]`, fails, and rescans from the next whitespace — quadratic on
27 * input like " [[[[[…". A cap makes each attempt constant-bounded.
28 *
29 * Only a basename ever survives the `label !== basename` check below, so this
30 * cannot reject a link a user could meaningfully write; the longest filename
31 * any common filesystem allows is 255.
32 */
33const MAX_FILE_LINK_LABEL_LENGTH = 512;
34const FILE_LINK_TOKEN_REGEX = new RegExp(
35 `(^|\\s)\\[((?:\\\\.|[^\\]\\\\]){0,${MAX_FILE_LINK_LABEL_LENGTH}})\\]\\(([^)\\s]+)\\)(?=\\s)`,
36 "g",
37);
38const URI_SCHEME_REGEX = /^[A-Za-z][A-Za-z0-9+.-]*:/;
39const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;
40// Autocomplete emits canonical file links, so ambiguous bare @scope/package text stays a package.
41const SCOPED_PACKAGE_REFERENCE_REGEX =
42 /^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*(?:\/[^\s@"]+)*$/;
43
44function collectMentionTokens(text: string): ComposerInlineToken[] {
45 const matches: ComposerInlineToken[] = [];
46
47 for (const match of text.matchAll(FILE_LINK_TOKEN_REGEX)) {
48 const fullMatch = match[0];
49 const prefix = match[1] ?? "";
50 const label = (match[2] ?? "").replace(/\\(.)/g, "$1");
51 const encodedPath = match[3] ?? "";
52 let path = encodedPath;
53 try {
54 path = decodeURIComponent(encodedPath);
55 } catch {
56 // Preserve malformed source rather than dropping a user-authored token.
57 }
58 const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
59 const basename = separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
60 const hasExternalScheme = URI_SCHEME_REGEX.test(path) && !WINDOWS_DRIVE_PATH_REGEX.test(path);
61 if (!path || hasExternalScheme || label !== basename) {
62 continue;
63 }
64 const start = (match.index ?? 0) + prefix.length;
65 const end = start + fullMatch.length - prefix.length;
66 matches.push({
67 type: "mention",
68 value: path,
69 source: text.slice(start, end),
70 start,
71 end,
72 });
73 }
74
75 for (const match of text.matchAll(MENTION_TOKEN_REGEX)) {
76 const fullMatch = match[0];
77 const prefix = match[1] ?? "";
78 const quotedPath = match[2];
79 const path = quotedPath !== undefined ? quotedPath.replace(/\\(.)/g, "$1") : (match[3] ?? "");
80 if (!path || (quotedPath === undefined && SCOPED_PACKAGE_REFERENCE_REGEX.test(path))) {
81 continue;
82 }
83 const start = (match.index ?? 0) + prefix.length;
84 const end = start + fullMatch.length - prefix.length;
85 matches.push({
86 type: "mention",
87 value: path,
88 source: text.slice(start, end),
89 start,
90 end,
91 });
92 }
93
94 return matches;
95}
96
97export function collectComposerInlineTokens(
98 text: string,
99 options: CollectComposerInlineTokensOptions = {},
100): ReadonlyArray<ComposerInlineToken> {
101 const matches = collectMentionTokens(text);
102
103 for (const match of text.matchAll(SKILL_TOKEN_REGEX)) {
104 const fullMatch = match[0];
105 const prefix = match[1] ?? "";
106 const value = match[2] ?? "";
107 if (!value) {
108 continue;
109 }
110 const start = (match.index ?? 0) + prefix.length;
111 const end = start + fullMatch.length - prefix.length;
112 matches.push({
113 type: "skill",
114 value,
115 source: text.slice(start, end),
116 start,
117 end,
118 });
119 }
120
121 for (const token of options.preserveTrailingFrom ?? []) {
122 if (
123 token.end === text.length &&
124 text.slice(token.start, token.end) === token.source &&
125 !matches.some(
126 (match) =>
127 match.type === token.type && match.start === token.start && match.end === token.end,
128 )
129 ) {
130 matches.push(token);
131 }
132 }
133
134 return [...matches].sort((left, right) => left.start - right.start);
135}