Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composerInlineTokens.ts

143 lines4.8 KB

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