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

enrichedLinkPresentation.ts

195 lines6.8 KB

1import type { ComposerContextRecord, EnvironmentId, ThreadId } from "@t3tools/contracts";
2import {
3 composerChipSizeSuffix,
4 contextChipIcon,
5 contextChipPresentation,
6 contextRecordFileName,
7 type ContextChipIconRef,
8 UNAVAILABLE_CONTEXT_CHIP_PRESENTATION,
9} from "./composerChipPresentation";
10import { formatComposerModelMention } from "@t3tools/client-runtime/composer-model-mentions";
11import type {
12 SelectableMarkdownModel,
13 SelectableMarkdownSkill,
14} from "../native/SelectableMarkdownText.types";
15import {
16 formatComposerContextHref,
17 parseComposerContextHref,
18} from "@t3tools/shared/composerContextReferences";
19import { hasThreadLinks, parseThreadLinkHref } from "@t3tools/shared/threadLinks";
20​
21export function enrichedContextLinkPresentation(
22 href: string,
23 records?: ReadonlyArray<ComposerContextRecord>,
24): { accent?: string; icon: ContextChipIconRef; label?: string } | undefined {
25 const reference = parseComposerContextHref(href);
26 if (!reference) return undefined;
27 const record = records?.find((candidate) => candidate.contextId === reference.contextId);
28 const presentation =
29 records && !record
30 ? UNAVAILABLE_CONTEXT_CHIP_PRESENTATION
31 : contextChipPresentation(reference.kind, record);
32 const size = composerChipSizeSuffix(record);
33 return {
34 ...(presentation.accent ? { accent: presentation.accent } : {}),
35 icon: contextChipIcon(presentation, contextRecordFileName(record)),
36 ...(record && size ? { label: `${record.label} · ${size}` } : {}),
37 };
39​
40export function enrichedThreadLinkPresentation(
41 href: string,
42): { accent?: string; icon: ContextChipIconRef } | undefined {
43 if (!parseThreadLinkHref(href)) return undefined;
44 const presentation = contextChipPresentation("thread");
45 return {
46 ...(presentation.accent ? { accent: presentation.accent } : {}),
47 icon: contextChipIcon(presentation, ""),
48 };
50​
51export interface ThreadChipTarget {
52 readonly href: string;
53 readonly environmentId: EnvironmentId;
54 readonly threadId: ThreadId;
55 readonly link: boolean;
57​
58export function threadChipTargets(
59 environmentId: EnvironmentId,
60 markdown: string,
61 records?: ReadonlyArray<ComposerContextRecord>,
62): ReadonlyArray<ThreadChipTarget> {
63 const targets = new Map<string, ThreadChipTarget>();
64 if (hasThreadLinks(markdown)) {
65 for (const [, href = ""] of markdown.matchAll(/\]\(<?(t3-thread:\/\/v[12]\/[^\s>)]+)>?\)/g)) {
66 const link = parseThreadLinkHref(href);
67 if (link) {
68 targets.set(href, {
69 href,
70 environmentId: link.environmentId ?? environmentId,
71 threadId: link.threadId,
72 link: true,
73 });
74 }
75 }
76 }
77 for (const record of records ?? []) {
78 if (record.kind !== "thread" || !("threadId" in record)) continue;
79 const href = formatComposerContextHref("thread", record.contextId);
80 targets.set(href, {
81 href,
82 environmentId: record.environmentId,
83 threadId: record.threadId,
84 link: false,
85 });
86 }
87 return [...targets.values()];
89​
90export function enrichedLinkVariantPattern(url: string) {
91 return `^${url.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`;
93​
94export const ENRICHED_INLINE_FILE_LINK_REGEX =
95 /^(?!\S*:\/\/)(?:(?:\.{1,2}[\\/]|~[\\/]|\/(?:Users|home|tmp|var|etc|opt|mnt|Volumes|private|root|usr|bin|sbin|lib|lib64|srv|dev|proc|sys|run|boot|media|workspace|workspaces)\/|[A-Za-z]:[\\/])[^\s`]+|(?:[\p{L}\p{M}\p{N}._-]+[\\/])+[\p{L}\p{M}\p{N}._-]+\.[A-Za-z0-9_-]+(?::\d+(?::\d+|-\d+)?)?|[\p{L}\p{M}\p{N}._-]+\.[A-Za-z0-9_-]+:\d+(?::\d+|-\d+)?)$/u;
96​
97export function enrichedSkillLinkRegex(skills?: ReadonlyArray<SelectableMarkdownSkill>) {
98 const names = [...new Set(skills?.map((skill) => skill.name) ?? [])].filter(Boolean);
99 if (names.length === 0) return null;
100 names.sort((a, b) => b.length - a.length);
101 const alternatives = names.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
102 return new RegExp(
103 `(?<![A-Za-z0-9_-])(?<!\\p{Sc})\\p{Sc}(?:${alternatives.join("|")})(?![A-Za-z0-9_-])`,
104 "u",
105 );
107​
108export function enrichedSkillReference(
109 url: string,
110 skills?: ReadonlyArray<SelectableMarkdownSkill>,
111) {
112 const match = /^\p{Sc}(.+)$/u.exec(url);
113 return match ? skills?.find((skill) => skill.name === match[1]) : undefined;
115​
116export function enrichedSkillInstructionsPath(skill: SelectableMarkdownSkill) {
117 return skill.path && !/^[a-z][a-z\d+.-]*:\/\//i.test(skill.path) ? skill.path : undefined;
119​
120export function buildEnrichedModelReferences(
121 providers: ReadonlyArray<{
122 readonly instanceId: string;
123 readonly driver: string;
124 readonly displayName?: string | undefined;
125 readonly iconUrl?: string | undefined;
126 readonly models: ReadonlyArray<{
127 readonly slug: string;
128 readonly name: string;
129 readonly subProvider?: string | undefined;
130 }>;
131 }>,
132 sources?: ReadonlySet<string>,
133): ReadonlyArray<SelectableMarkdownModel> {
134 return providers.flatMap((provider) =>
135 provider.models
136 .filter(
137 (model) =>
138 !sources || sources.has(formatComposerModelMention(provider.instanceId, model.slug)),
139 )
140 .map((model) => {
141 const qualifier = model.subProvider?.trim();
142 const label = qualifier
143 ? model.name
144 .replace(
145 new RegExp(
146 `^${qualifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s*[.:/-]\\s*|\\s+)`,
147 "iu",
148 ),
149 "",
150 )
151 .trim() || model.name
152 : model.name;
153 return {
154 source: formatComposerModelMention(provider.instanceId, model.slug),
155 label,
156 providerLabel: qualifier || provider.displayName || provider.instanceId,
157 driver: provider.driver,
158 iconUrl: provider.iconUrl,
159 };
160 }),
161 );
163​
164export function enrichedModelLinkRegex(models?: ReadonlyArray<SelectableMarkdownModel>) {
165 if (!models?.length) return null;
166 const alternatives = models
167 .map((model) => model.source)
168 .sort((a, b) => b.length - a.length)
169 .map((source) => source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
170 return new RegExp(
171 `(?<![^\\s,(\\["'])(?:${alternatives.join("|")})(?=$|[\\s,"']|[.;:!?\\)\\]]+(?=$|[\\s,"']))`,
172 "u",
173 );
175​
176export function enrichedModelReference(
177 source: string,
178 models?: ReadonlyArray<SelectableMarkdownModel>,
179) {
180 return models?.find((model) => model.source === source);
182​
183export function enrichedModelDetails(model: SelectableMarkdownModel) {
184 return `${model.providerLabel}\n${model.source}`;
186​
187export function enrichedTextLinkRegex(
188 skills?: ReadonlyArray<SelectableMarkdownSkill>,
189 models?: ReadonlyArray<SelectableMarkdownModel>,
190) {
191 const patterns = [enrichedSkillLinkRegex(skills), enrichedModelLinkRegex(models)]
192 .filter((pattern) => pattern !== null)
193 .map((pattern) => `(?:${pattern.source})`);
194 return patterns.length ? new RegExp(patterns.join("|"), "u") : null;