Port devxoul's PR #821 feature to current codebase structure. Supports absolute, relative, ~/home paths with percent-encoding. Gracefully handles malformed URIs and missing files with warnings. Co-authored-by: devxoul <devxoul@gmail.com>
31 lines
949 B
TypeScript
31 lines
949 B
TypeScript
import { existsSync, readFileSync } from "node:fs"
|
|
import { homedir } from "node:os"
|
|
import { isAbsolute, resolve } from "node:path"
|
|
|
|
export function resolvePromptAppend(promptAppend: string, configDir?: string): string {
|
|
if (!promptAppend.startsWith("file://")) return promptAppend
|
|
|
|
const encoded = promptAppend.slice(7)
|
|
|
|
let filePath: string
|
|
try {
|
|
const decoded = decodeURIComponent(encoded)
|
|
const expanded = decoded.startsWith("~/") ? decoded.replace(/^~\//, `${homedir()}/`) : decoded
|
|
filePath = isAbsolute(expanded)
|
|
? expanded
|
|
: resolve(configDir ?? process.cwd(), expanded)
|
|
} catch {
|
|
return `[WARNING: Malformed file URI (invalid percent-encoding): ${promptAppend}]`
|
|
}
|
|
|
|
if (!existsSync(filePath)) {
|
|
return `[WARNING: Could not resolve file URI: ${promptAppend}]`
|
|
}
|
|
|
|
try {
|
|
return readFileSync(filePath, "utf8")
|
|
} catch {
|
|
return `[WARNING: Could not read file: ${promptAppend}]`
|
|
}
|
|
}
|