Files
opencode-manager/frontend/src/lib/markdownLinks.ts
T
Chris Scott 59ffe6c586 Merge pull request #420 from chriswritescode-dev/feat/sandboxed-html-artifacts
feat(artifacts): render agent HTML files inline in the session chat
2026-10-13 09:30:59 -04:00

71 lines
2.6 KiB
TypeScript

const URL_SCHEME = /^[a-z][a-z\d+.-]*:/i
/**
* Extracts the local file path a markdown link points at, decoded and without query or fragment.
* Returns null for anchors, protocol-relative URLs, links with a URL scheme, and malformed encodings.
*/
export function getLocalLinkPath(href: string | undefined): string | null {
if (!href || href.startsWith('#') || href.startsWith('//') || URL_SCHEME.test(href)) {
return null
}
try {
const linkPath = decodeURIComponent(href.split(/[?#]/)[0]).replace(/(.)\/+$/, '$1')
return linkPath || null
} catch {
return null
}
}
/**
* Resolves a local link path against the workspace path of the file that contains it.
* Absolute link paths are returned unchanged for the files API to validate. Leading parent segments
* are kept for relative bases, while an absolute base keeps its leading slash and never climbs above root.
*/
export function resolvePathFromFile(fromFilePath: string, linkPath: string): string | null {
if (linkPath.startsWith('/')) {
return linkPath
}
const isAbsolute = fromFilePath.startsWith('/')
const segments = fromFilePath.split('/').filter(Boolean).slice(0, -1)
for (const segment of linkPath.split('/')) {
if (segment === '' || segment === '.') continue
if (segment !== '..') {
segments.push(segment)
} else if (segments.length === 0) {
if (!isAbsolute) segments.push(segment)
} else if (isAbsolute || segments[segments.length - 1] !== '..') {
segments.pop()
} else {
segments.push(segment)
}
}
const resolved = segments.join('/')
return isAbsolute ? `/${resolved}` : resolved || null
}
/**
* Maps a file path referenced from a working directory to the path the file browser opens.
* Relative paths resolve against the directory, and paths inside the repo root become repo-local workspace paths.
*/
export function getWorkspaceFilePath(
filePath: string,
workspace: { directory?: string; repoFullPath?: string; repoLocalPath?: string },
): string {
const { directory, repoFullPath, repoLocalPath } = workspace
const baseDirectory = directory?.replace(/\/+$/, '')
const absolutePath = filePath.startsWith('/') || !directory
? filePath
: `${baseDirectory}/${filePath.replace(/^\.\//, '')}`
return repoFullPath && repoLocalPath && absolutePath.startsWith(`${repoFullPath}/`)
? `${repoLocalPath}/${absolutePath.slice(repoFullPath.length + 1)}`
: absolutePath
}
/** Returns whether a link targets an external http(s) page. */
export function isExternalLink(href: string | undefined): boolean {
return !!href && /^https?:\/\//i.test(href)
}