repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/lsp/src/source.ts
Rawimport { constants } from "node:fs";
import { open, realpath, stat } from "node:fs/promises";
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import type { Position, Range } from "vscode-languageserver-protocol/node.js";
export function check(signal: AbortSignal): void {
if (signal.aborted) throw signal.reason;
}
export async function bounded<T>(
work: Promise<T>,
signal: AbortSignal,
): Promise<T> {
let abort: (() => void) | undefined;
try {
return await Promise.race([
work,
new Promise<never>((_, reject) => {
abort = () => reject(signal.reason);
signal.addEventListener("abort", abort, { once: true });
if (signal.aborted) abort();
}),
]);
} finally {
if (abort) signal.removeEventListener("abort", abort);
}
}
export const MAX_FILE_BYTES: number = 512 * 1024;
export type Encoding = "utf-8" | "utf-16" | "utf-32";
export class LspFailure extends Error {
constructor(
public readonly status: string,
message: string,
) {
super(message);
}
}
export function within(root: string, file: string): boolean {
const rel = relative(root, file);
return (
rel === "" ||
(rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))
);
}
export async function snapshot(
file: string,
signal?: AbortSignal,
): Promise<string> {
signal?.throwIfAborted();
const info = await stat(file);
signal?.throwIfAborted();
if (!info.isFile() || info.size > MAX_FILE_BYTES)
throw new LspFailure(
"invalid_input",
"Source must be a regular file ≤512 KiB.",
);
// Nonblocking open also closes the stat/open FIFO replacement race on POSIX.
const handle = await open(file, constants.O_RDONLY | constants.O_NONBLOCK);
try {
const info = await handle.stat();
if (!info.isFile() || info.size > MAX_FILE_BYTES)
throw new LspFailure(
"invalid_input",
"Source must be a regular file ≤512 KiB.",
);
const buffer = Buffer.alloc(MAX_FILE_BYTES + 1);
let size = 0;
while (size < buffer.length) {
signal?.throwIfAborted();
const chunk = await handle.read(buffer, size, buffer.length - size, size);
if (!chunk.bytesRead) break;
size += chunk.bytesRead;
}
if (size > MAX_FILE_BYTES)
throw new LspFailure("resource_limit", "Source grew beyond 512 KiB.");
signal?.throwIfAborted();
return new TextDecoder("utf-8", { fatal: true }).decode(
buffer.subarray(0, size),
);
} finally {
await handle.close();
}
}
// Match /\r?\n/ line boundaries without splitting the entire source per position.
export function sourceLine(text: string, line: number): string | undefined {
if (!Number.isSafeInteger(line) || line < 0) return undefined;
let start = 0;
for (let index = 0; index < line; index++) {
const end = text.indexOf("\n", start);
if (end < 0) return undefined;
start = end + 1;
}
const end = text.indexOf("\n", start);
return text.slice(
start,
end < 0 ? undefined : text[end - 1] === "\r" ? end - 1 : end,
);
}
export function toPosition(
text: string,
line: number,
column: number,
encoding: Encoding,
): Position {
if (
!Number.isSafeInteger(line) ||
line < 1 ||
!Number.isSafeInteger(column) ||
column < 1
)
throw new LspFailure(
"invalid_input",
"line and column must be positive integers.",
);
const row = sourceLine(text, line - 1);
if (row === undefined || column > [...row].length + 1)
throw new LspFailure("invalid_input", "Position outside disk snapshot.");
const prefix = [...row].slice(0, column - 1).join("");
return {
line: line - 1,
character:
encoding === "utf-8"
? Buffer.byteLength(prefix)
: encoding === "utf-32"
? column - 1
: prefix.length,
};
}
export function fromPosition(
text: string,
pos: Position,
encoding: Encoding,
): { line: number; column: number } {
const row = sourceLine(text, pos.line);
if (
!Number.isSafeInteger(pos.line) ||
pos.line < 0 ||
!Number.isSafeInteger(pos.character) ||
pos.character < 0 ||
row === undefined
)
throw new LspFailure("server_failure", "Invalid server position.");
let units = 0;
let scalars = 0;
for (const scalar of row) {
if (units === pos.character) break;
units +=
encoding === "utf-8"
? Buffer.byteLength(scalar)
: encoding === "utf-32"
? 1
: scalar.length;
scalars++;
}
if (units !== pos.character)
throw new LspFailure(
"server_failure",
"Server position not on a source scalar boundary.",
);
return { line: pos.line + 1, column: scalars + 1 };
}
export function convertRange(
text: string,
range: Range,
encoding: Encoding,
): {
start: { line: number; column: number };
end: { line: number; column: number };
} {
if (
range.end.line < range.start.line ||
(range.end.line === range.start.line &&
range.end.character < range.start.character)
)
throw new LspFailure(
"server_failure",
"Server range ends before it starts.",
);
return {
start: fromPosition(text, range.start, encoding),
end: fromPosition(text, range.end, encoding),
};
}
export function uri(file: string): string {
return pathToFileURL(file).href;
}
export function localPath(value: string): string {
try {
return fileURLToPath(value);
} catch {
throw new LspFailure(
"server_failure",
"Server returned a non-local source URI.",
);
}
}
export async function target(
cwd: string,
file: string,
workspace?: string,
markers: string[] = ["go.work", "go.mod"],
): Promise<{ file: string; root: string }> {
if (!file || file.length > 4096 || (workspace?.length ?? 0) > 4096)
throw new LspFailure("invalid_input", "Provide a bounded local file path.");
const canonical = await realpath(resolve(cwd, file));
const boundary = await realpath(resolve(cwd, workspace ?? "."));
if (!within(boundary, canonical))
throw new LspFailure(
"invalid_input",
"File must be inside workspace (default: Pi cwd).",
);
if (!(await stat(boundary)).isDirectory())
throw new LspFailure("invalid_input", "Workspace must be a directory.");
if (workspace) return { file: canonical, root: boundary };
const roots: string[] = [];
let dir = dirname(canonical);
for (let depth = 0; depth < 64; depth++) {
for (const marker of markers) {
try {
if ((await stat(resolve(dir, marker))).isFile() && !roots.includes(dir))
roots.push(dir);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
}
}
if (dir === boundary) break;
const parent = dirname(dir);
if (parent === dir || !within(boundary, parent)) break;
dir = parent;
}
if (roots.length !== 1)
throw new LspFailure(
roots.length ? "ambiguous" : "invalid_input",
roots.length
? `Multiple roots: ${roots.join(", ")}. Specify workspace.`
: `No ${markers.join("/")} root found within Pi cwd; specify workspace.`,
);
const root = roots[0];
if (!root) throw new LspFailure("invalid_input", "No workspace root.");
return { file: canonical, root };
}