@narumitw/pi-inline 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/LICENSE +21 -0
- package/README.md +129 -2
- package/package.json +47 -4
- package/src/badge.ts +67 -0
- package/src/filelinks.ts +199 -0
- package/src/hover-preview.ts +196 -0
- package/src/image-preview.ts +124 -0
- package/src/image-thumbnail-worker.mjs +27 -0
- package/src/index.ts +1 -0
- package/src/inline-markup-extension.ts +102 -0
- package/src/inline-markup.ts +186 -0
- package/src/prompt.ts +2 -0
- package/src/wikilink-index.ts +103 -0
- package/src/wikilinks.ts +182 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# @narumitw/pi-inline
|
|
2
|
+
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 0501c6c: Rename the package from `@narumitw/pi-inline-markup` to `@narumitw/pi-inline`. The `/inline-markup` command and rendering behavior are unchanged. To migrate, remove the old npm source and install the new one in the same scope (`-l` for project installs). For a local checkout, use `packages/pi-inline` instead. Do not load both copies.
|
|
8
|
+
|
|
9
|
+
## 0.2.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- 20ea0d0: Preview local PNG, JPEG, GIF, and WebP files by hovering over their Markdown links in Pi's fullscreen terminal UI. Image previews require Kitty graphics support and use the same workspace file restrictions as text previews. Previews use the original pixel dimensions and only scale down when the image does not fit in the available terminal space. There is no fixed source file size or pixel count limit. The overlay fits the image so it does not hide unrelated transcript content on the right.
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- c780a73: Style and preview explicit Markdown file links to hidden workspace paths such as `.github/workflows/ci.yml`. Wikilink lookup still skips hidden paths, and previews still exclude `node_modules`, symbolic links, and files outside the workspace.
|
|
18
|
+
|
|
19
|
+
## 0.1.1
|
|
20
|
+
|
|
21
|
+
### Patch Changes
|
|
22
|
+
|
|
23
|
+
- b4d2c30: Remove the extension name and identifier from the prompt guidance. Keep a generic badge label and a Markdown file citation example. Rendering and wikilink behavior are unchanged.
|
|
24
|
+
|
|
25
|
+
## 0.1.0
|
|
26
|
+
|
|
27
|
+
Package the former project-local extension for independent installation. Wikilinks
|
|
28
|
+
resolve in Pi's working directory rather than the extension's installation directory.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 narumiruna
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,130 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 🔖 pi-inline — Inline Badges and File Previews for Pi
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@narumitw/pi-inline) [](https://pi.dev) [](./LICENSE)
|
|
4
|
+
|
|
5
|
+
Style badges and preview local file citations in Pi's terminal transcript without changing stored messages.
|
|
6
|
+
`pi-inline` is inspired by [pi-emphasis](https://github.com/johnlindquist/pi-emphasis).
|
|
7
|
+
|
|
8
|
+
## ✨ Features
|
|
9
|
+
|
|
10
|
+
- Display decorative badges, linked badges, and local Markdown links in user and assistant messages.
|
|
11
|
+
- Hover over a file link in fullscreen mode to preview an image, a text file, or a range of source lines.
|
|
12
|
+
- Turn on filename lookup for wikilinks in the current session.
|
|
13
|
+
|
|
14
|
+
## 📦 Install
|
|
15
|
+
|
|
16
|
+
Pi extensions run with your user permissions. Load only code you trust.
|
|
17
|
+
|
|
18
|
+
Install from npm or try it for one Pi session:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pi install npm:@narumitw/pi-inline
|
|
22
|
+
pi -e npm:@narumitw/pi-inline
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
For a local checkout, install dependencies from the repository root and try the
|
|
26
|
+
extension without a build:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
npm install
|
|
30
|
+
pi -e ./packages/pi-inline
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
To keep this checkout installed, run `pi install ./packages/pi-inline`.
|
|
34
|
+
|
|
35
|
+
### Migrate from pi-inline-markup
|
|
36
|
+
|
|
37
|
+
`pi update` does not switch to the new npm name. Run
|
|
38
|
+
`pi remove npm:@narumitw/pi-inline-markup` in the original scope, then run
|
|
39
|
+
`pi install npm:@narumitw/pi-inline` in the same scope. Add `-l` to both commands
|
|
40
|
+
for a project install.
|
|
41
|
+
|
|
42
|
+
If you load the old checkout path, replace it with `./packages/pi-inline`.
|
|
43
|
+
Remove any explicit entry for the former `.pi/extensions/pi-inline-markup/`
|
|
44
|
+
extension. Do not load both copies. The `/inline-markup` command is unchanged.
|
|
45
|
+
|
|
46
|
+
## 🚀 Quick start
|
|
47
|
+
|
|
48
|
+
Start Pi in a directory with a `README.md` file. Send a message containing
|
|
49
|
+
`[README](./README.md)` to see a file icon next to the label. In fullscreen mode,
|
|
50
|
+
hover over the link to preview the file. If Pi detects Kitty graphics support,
|
|
51
|
+
hover over an image link such as `[Cat Photo](./cat.png)` to see the image.
|
|
52
|
+
|
|
53
|
+
## 💬 Commands
|
|
54
|
+
|
|
55
|
+
Run `/inline-markup` with no arguments in the terminal UI. Select **On** or **Off**
|
|
56
|
+
to toggle wikilinks immediately, or press Escape to leave the value unchanged.
|
|
57
|
+
Wikilinks start off in each new session and after `/reload`. Turning them off
|
|
58
|
+
stops file indexing and closes any open preview.
|
|
59
|
+
|
|
60
|
+
## 🔗 Link and badge syntax
|
|
61
|
+
|
|
62
|
+
```markdown
|
|
63
|
+
[[README]]
|
|
64
|
+
[[[README](./README.md)]]
|
|
65
|
+
[[[README]]](./README.md)
|
|
66
|
+
[`runTests()`](./scripts/run-tests.mjs#L12-L20)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
- `[[label]]` is decorative unless you enable wikilinks. With wikilinks off, the
|
|
70
|
+
badge does not look up, open, or preview a file.
|
|
71
|
+
- The two linked badge forms are equivalent. Both use standard local Markdown
|
|
72
|
+
destinations and support hover previews whether or not wikilinks are enabled.
|
|
73
|
+
- Ordinary Markdown links use a file icon (📄). Use a plain-text or inline-code
|
|
74
|
+
label and a path relative to Pi's working directory or an absolute path within
|
|
75
|
+
it. Hidden paths work too, for example `[CI workflow](./.github/workflows/ci.yml#L1)`.
|
|
76
|
+
Encode spaces as `%20`.
|
|
77
|
+
- Use `#L12` for one source line or `#L12-L20` for an inclusive range. Hover also
|
|
78
|
+
accepts `#L12-20`. These previews show literal source rather than rendered Markdown.
|
|
79
|
+
|
|
80
|
+
When wikilinks are on, `[[README]]` looks up files under Pi's working directory,
|
|
81
|
+
`[[README.md|Guide]]` sets a custom label, and `[[./README.md]]` selects an exact
|
|
82
|
+
path. If a bare filename matches several Markdown files, the badge previews up
|
|
83
|
+
to three. Clicking opens the file at the working directory root if present, or
|
|
84
|
+
the only match if the filename is unique. If there is no root match and several
|
|
85
|
+
files match, the badge previews files but is not clickable. Unresolved names
|
|
86
|
+
also stay non-clickable. The index skips hidden paths, starts on first lookup,
|
|
87
|
+
and refreshes five seconds after each scan.
|
|
88
|
+
|
|
89
|
+
## 🔒 Security and privacy
|
|
90
|
+
|
|
91
|
+
Previews are local. They exclude files outside Pi's working directory,
|
|
92
|
+
`node_modules`, and symbolic links. Hovering over an explicit Markdown link
|
|
93
|
+
can display a hidden workspace file, including dotfiles that may contain secrets.
|
|
94
|
+
The extension does not add file contents to the model context.
|
|
95
|
+
|
|
96
|
+
In the terminal UI, the extension adds a fixed system prompt hint about badge
|
|
97
|
+
labels and Markdown file citations. The hint uses a placeholder path and contains
|
|
98
|
+
no extension name or workspace data. Updating the hint does not rewrite existing
|
|
99
|
+
session history.
|
|
100
|
+
|
|
101
|
+
## 🚧 Limitations
|
|
102
|
+
|
|
103
|
+
- Rounded badges require a font with Powerline glyphs.
|
|
104
|
+
- Hover previews require fullscreen mode, OSC 8 hyperlinks, and mouse movement
|
|
105
|
+
reports without a button press. Pi does not request these reports in tmux,
|
|
106
|
+
Zellij, or GNU Screen.
|
|
107
|
+
- Text previews show up to 16 KiB of a regular UTF-8 file. For a line-anchored
|
|
108
|
+
preview, the first requested line must start within the first 256 KiB.
|
|
109
|
+
- Image previews require Kitty graphics and display a static PNG, JPEG, GIF, or
|
|
110
|
+
WebP image. The preview keeps the original pixel dimensions when the image fits
|
|
111
|
+
above or below its link. Otherwise, it scales down without changing the aspect
|
|
112
|
+
ratio. The extension has no fixed source size limit, but the image decoder
|
|
113
|
+
and available memory still set practical limits. If a preview is unavailable,
|
|
114
|
+
you can still open the link.
|
|
115
|
+
|
|
116
|
+
## 🗂️ Package layout
|
|
117
|
+
|
|
118
|
+
- `src/index.ts` forwards the extension factory to Pi. The rest of `src/` owns
|
|
119
|
+
transcript rendering, hover previews, and the wikilink index.
|
|
120
|
+
- `test/` covers rendering, session cleanup, file boundaries, and workspace lookups.
|
|
121
|
+
|
|
122
|
+
The package ships its TypeScript source and needs no build step.
|
|
123
|
+
|
|
124
|
+
## 🔎 Keywords
|
|
125
|
+
|
|
126
|
+
Pi extension, terminal Markdown, inline badges, wikilinks, file citations, hover previews.
|
|
127
|
+
|
|
128
|
+
## 📄 License
|
|
129
|
+
|
|
130
|
+
MIT. See [`LICENSE`](./LICENSE).
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-inline",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Style inline badges and preview local file links in Pi's terminal UI.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"private": false,
|
|
8
|
+
"keywords": [
|
|
9
|
+
"pi-package",
|
|
10
|
+
"pi-extension",
|
|
11
|
+
"markdown",
|
|
12
|
+
"wikilinks",
|
|
13
|
+
"file-preview"
|
|
14
|
+
],
|
|
15
|
+
"files": [
|
|
16
|
+
"src",
|
|
17
|
+
"README.md",
|
|
18
|
+
"CHANGELOG.md",
|
|
19
|
+
"LICENSE"
|
|
20
|
+
],
|
|
21
|
+
"pi": {
|
|
22
|
+
"extensions": [
|
|
23
|
+
"./src/index.ts"
|
|
24
|
+
]
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"check": "biome check . && npm run typecheck",
|
|
28
|
+
"format": "biome check --write .",
|
|
29
|
+
"typecheck": "tsc --noEmit"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
33
|
+
"@earendil-works/pi-tui": "*"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@earendil-works/pi-coding-agent": "1.5.0",
|
|
37
|
+
"@earendil-works/pi-tui": "1.5.0",
|
|
38
|
+
"@types/node": "26.6.6",
|
|
39
|
+
"typescript": "7.0.2"
|
|
40
|
+
},
|
|
41
|
+
"repository": {
|
|
42
|
+
"type": "git",
|
|
43
|
+
"url": "https://github.com/narumiruna/pi-extensions",
|
|
44
|
+
"directory": "packages/pi-inline"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"sharp": "0.35.5"
|
|
48
|
+
}
|
|
49
|
+
}
|
package/src/badge.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import {
|
|
4
|
+
backgroundAnsi,
|
|
5
|
+
type Color,
|
|
6
|
+
colorToRgb,
|
|
7
|
+
foregroundAnsi,
|
|
8
|
+
getCapabilities,
|
|
9
|
+
hyperlink,
|
|
10
|
+
rgbColor,
|
|
11
|
+
stripTerminalSequences,
|
|
12
|
+
} from "@earendil-works/pi-tui";
|
|
13
|
+
|
|
14
|
+
const palette: readonly ThemeColor[] = [
|
|
15
|
+
"accent",
|
|
16
|
+
"mdLink",
|
|
17
|
+
"success",
|
|
18
|
+
"mdHeading",
|
|
19
|
+
"error",
|
|
20
|
+
"syntaxString",
|
|
21
|
+
"syntaxVariable",
|
|
22
|
+
"thinkingXhigh",
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
function textColorForFill(fill: Color): Color {
|
|
26
|
+
// Compare black and white against the fill's relative luminance (WCAG 2.2).
|
|
27
|
+
const { r, g, b } = colorToRgb(fill);
|
|
28
|
+
const linear = (channel: number) => {
|
|
29
|
+
const srgb = Math.round(channel) / 255;
|
|
30
|
+
return srgb <= 0.04045 ? srgb / 12.92 : ((srgb + 0.055) / 1.055) ** 2.4;
|
|
31
|
+
};
|
|
32
|
+
const luminance = 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
|
|
33
|
+
const blackContrast = (luminance + 0.05) / 0.05;
|
|
34
|
+
const whiteContrast = 1.05 / (luminance + 0.05);
|
|
35
|
+
const channel = blackContrast >= whiteContrast ? 0 : 255;
|
|
36
|
+
return rgbColor(channel, channel, channel);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function cleanBadgeLabel(label: string): string {
|
|
40
|
+
return stripTerminalSequences(label)
|
|
41
|
+
.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/gu, " ")
|
|
42
|
+
.trim();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Renders a badge as ANSI text with an optional terminal link or hover target. */
|
|
46
|
+
export function renderBadge(
|
|
47
|
+
label: string,
|
|
48
|
+
theme: Theme,
|
|
49
|
+
userMessage: boolean,
|
|
50
|
+
href?: string,
|
|
51
|
+
groupId?: string,
|
|
52
|
+
): string {
|
|
53
|
+
const caps = getCapabilities();
|
|
54
|
+
const mode = caps.trueColor ? "truecolor" : "256color";
|
|
55
|
+
const key = createHash("sha256").update(label.normalize("NFC")).digest()[0];
|
|
56
|
+
const fill = theme.colors[palette[key % palette.length]];
|
|
57
|
+
const edge = foregroundAnsi(fill, mode);
|
|
58
|
+
const body = backgroundAnsi(fill, mode) + foregroundAnsi(textColorForFill(fill), mode);
|
|
59
|
+
const resetFill = (userMessage && theme.getBgAnsi("userMessageBg")) || "\x1b[49m";
|
|
60
|
+
const padded = `\u00a0${label.replaceAll(" ", "\u00a0")}\u00a0`;
|
|
61
|
+
// Rounded Powerline caps require glyph support from the terminal or its font.
|
|
62
|
+
const badge = `${edge}\uE0B6${body}${padded}${resetFill}${edge}\uE0B4\x1b[39m`;
|
|
63
|
+
if (!caps.hyperlinks) return badge;
|
|
64
|
+
// An empty group URL allows a preview without a click destination.
|
|
65
|
+
if (groupId) return `\x1b]8;id=${groupId};${href ?? ""}\x1b\\${badge}\x1b]8;;\x1b\\`;
|
|
66
|
+
return href ? hyperlink(badge, href) : badge;
|
|
67
|
+
}
|
package/src/filelinks.ts
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { lstat, open, realpath } from "node:fs/promises";
|
|
3
|
+
import { basename, isAbsolute, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { getMarkdownTheme, type Theme } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { Markdown, stripTerminalSequences, truncateToWidth } from "@earendil-works/pi-tui";
|
|
6
|
+
|
|
7
|
+
const MAX_BYTES = 16 * 1024;
|
|
8
|
+
const MAX_LINE_SCAN_BYTES = 256 * 1024;
|
|
9
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: OSC 8 uses ESC and BEL.
|
|
10
|
+
const OSC_8 = /\x1b\]8;[^\x07\x1b]*(?:\x07|\x1b\\)/g;
|
|
11
|
+
|
|
12
|
+
export interface LineRange {
|
|
13
|
+
start: number;
|
|
14
|
+
end: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface PreviewExcerpt {
|
|
18
|
+
filename: string;
|
|
19
|
+
text: string;
|
|
20
|
+
clipped: boolean;
|
|
21
|
+
lineRange?: LineRange;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function workspacePath(root: string, path: string): string | undefined {
|
|
25
|
+
const local = relative(root, path);
|
|
26
|
+
if (!local || isAbsolute(local) || local === ".." || local.startsWith(`..${sep}`)) return undefined;
|
|
27
|
+
if (local.split(sep).includes("node_modules")) return undefined;
|
|
28
|
+
return local;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function resolveLinkPath(root: string, href: string): string | undefined {
|
|
32
|
+
// Interpret Markdown destinations as filesystem paths, not as URLs to fetch.
|
|
33
|
+
// Leave URI schemes (including file:) and protocol-relative links to Pi.
|
|
34
|
+
const invalid = /[\\\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/u;
|
|
35
|
+
if (invalid.test(href)) return undefined;
|
|
36
|
+
const [encoded] = href.split(/[?#]/, 1);
|
|
37
|
+
try {
|
|
38
|
+
const path = decodeURIComponent(encoded);
|
|
39
|
+
if (!path || path.startsWith("//") || invalid.test(path)) return undefined;
|
|
40
|
+
if (/^[a-z][a-z\d+.-]*:/i.test(path) && !isAbsolute(path)) return undefined;
|
|
41
|
+
const target = resolve(root, path);
|
|
42
|
+
return workspacePath(root, target) ? target : undefined;
|
|
43
|
+
} catch {
|
|
44
|
+
return undefined; // Malformed percent escape.
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function parseLineRange(href: string): LineRange | undefined {
|
|
49
|
+
const match = /#L([1-9]\d*)(?:-L?([1-9]\d*))?$/.exec(href);
|
|
50
|
+
if (!match || match.index !== href.indexOf("#")) return undefined;
|
|
51
|
+
const start = Number(match[1]);
|
|
52
|
+
const end = match[2] ? Number(match[2]) : start;
|
|
53
|
+
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || end < start) return undefined;
|
|
54
|
+
return { start, end };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function selectLines(
|
|
58
|
+
bytes: Buffer,
|
|
59
|
+
{ start, end }: LineRange,
|
|
60
|
+
moreBytes: boolean,
|
|
61
|
+
): { bytes: Buffer; clipped: boolean } | undefined {
|
|
62
|
+
let line = 1;
|
|
63
|
+
let offset = 0;
|
|
64
|
+
let from = 0;
|
|
65
|
+
while (offset < bytes.length) {
|
|
66
|
+
const byte = bytes[offset++];
|
|
67
|
+
if (byte !== 10 && byte !== 13) continue;
|
|
68
|
+
if (byte === 13 && bytes[offset] === 10) offset++;
|
|
69
|
+
if (line === end) {
|
|
70
|
+
return { bytes: bytes.subarray(from, Math.min(offset, from + MAX_BYTES)), clipped: offset - from > MAX_BYTES };
|
|
71
|
+
}
|
|
72
|
+
if (++line === start) from = offset;
|
|
73
|
+
}
|
|
74
|
+
if (line < start || from === bytes.length) return undefined;
|
|
75
|
+
return {
|
|
76
|
+
bytes: bytes.subarray(from, from + MAX_BYTES),
|
|
77
|
+
clipped: moreBytes || bytes.length - from > MAX_BYTES,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Opens a regular workspace file without following symlinks. The caller owns the handle. */
|
|
82
|
+
export async function openPreviewFile(root: string, path: string, signal: AbortSignal) {
|
|
83
|
+
try {
|
|
84
|
+
const local = workspacePath(root, path);
|
|
85
|
+
if (!local || signal.aborted) return undefined;
|
|
86
|
+
const project = await realpath(root);
|
|
87
|
+
if (signal.aborted) return undefined;
|
|
88
|
+
const candidate = resolve(project, local);
|
|
89
|
+
if ((await realpath(candidate)) !== candidate || signal.aborted) return undefined;
|
|
90
|
+
if (!(await lstat(candidate)).isFile() || signal.aborted) return undefined;
|
|
91
|
+
|
|
92
|
+
const file = await open(candidate, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
93
|
+
let keepOpen = false;
|
|
94
|
+
try {
|
|
95
|
+
if (signal.aborted) return undefined;
|
|
96
|
+
const stat = await file.stat();
|
|
97
|
+
if (signal.aborted || !stat.isFile()) return undefined;
|
|
98
|
+
keepOpen = true;
|
|
99
|
+
return {
|
|
100
|
+
file,
|
|
101
|
+
size: stat.size,
|
|
102
|
+
filename: basename(candidate).replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/gu, " "),
|
|
103
|
+
};
|
|
104
|
+
} finally {
|
|
105
|
+
if (!keepOpen) await file.close();
|
|
106
|
+
}
|
|
107
|
+
} catch {
|
|
108
|
+
// A file can be missing or unreadable.
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function readExcerpt(
|
|
114
|
+
root: string,
|
|
115
|
+
path: string,
|
|
116
|
+
signal: AbortSignal,
|
|
117
|
+
lineRange?: LineRange,
|
|
118
|
+
): Promise<PreviewExcerpt | undefined> {
|
|
119
|
+
const source = await openPreviewFile(root, path, signal);
|
|
120
|
+
if (!source) return undefined;
|
|
121
|
+
const { file, size, filename } = source;
|
|
122
|
+
try {
|
|
123
|
+
if (signal.aborted) return undefined;
|
|
124
|
+
const buffer = Buffer.alloc(Math.min(size, lineRange ? MAX_LINE_SCAN_BYTES : MAX_BYTES));
|
|
125
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
|
126
|
+
if (signal.aborted) return undefined;
|
|
127
|
+
const bytes = buffer.subarray(0, bytesRead);
|
|
128
|
+
const moreBytes = size > bytesRead;
|
|
129
|
+
const excerpt = lineRange ? selectLines(bytes, lineRange, moreBytes) : { bytes, clipped: moreBytes };
|
|
130
|
+
if (!excerpt) return undefined;
|
|
131
|
+
const { clipped } = excerpt;
|
|
132
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(excerpt.bytes, { stream: clipped });
|
|
133
|
+
if (text.includes("\0")) return undefined;
|
|
134
|
+
const clean = stripTerminalSequences(text)
|
|
135
|
+
.replace(/\r\n?/g, "\n")
|
|
136
|
+
.replace(/[\p{Zl}\p{Zp}]/gu, " ")
|
|
137
|
+
.replace(/(?![\n\t])[\p{Cc}\p{Bidi_Control}]/gu, "");
|
|
138
|
+
return { filename, text: clean, clipped, lineRange };
|
|
139
|
+
} catch {
|
|
140
|
+
return undefined; // Unreadable file or invalid UTF-8.
|
|
141
|
+
} finally {
|
|
142
|
+
await file.close().catch(() => undefined);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function renderFilePreview(theme: Theme, excerpt: PreviewExcerpt, width: number, height: number): string[] {
|
|
147
|
+
if (width < 5 || height < 4) return [];
|
|
148
|
+
const contentWidth = width - 4;
|
|
149
|
+
// Anchors refer to source lines, not to the rendered Markdown document.
|
|
150
|
+
const markdown = !excerpt.lineRange && /\.(md|markdown)$/i.test(excerpt.filename);
|
|
151
|
+
const lines = markdown
|
|
152
|
+
? new Markdown(
|
|
153
|
+
excerpt.text,
|
|
154
|
+
0,
|
|
155
|
+
0,
|
|
156
|
+
{ ...getMarkdownTheme(), linkUrl: () => "", highlightCode: undefined },
|
|
157
|
+
{ color: (text) => theme.fg("text", text) },
|
|
158
|
+
{ renderLatex: false },
|
|
159
|
+
)
|
|
160
|
+
.render(contentWidth)
|
|
161
|
+
.map((line) => line.replace(OSC_8, ""))
|
|
162
|
+
: excerpt.text
|
|
163
|
+
.replace(/\n$/, "")
|
|
164
|
+
.split("\n")
|
|
165
|
+
.map((line) => line.replaceAll("\t", " "));
|
|
166
|
+
const limit = height - 3;
|
|
167
|
+
const body = lines.slice(0, limit);
|
|
168
|
+
if (excerpt.clipped || lines.length > limit) {
|
|
169
|
+
const last = body.pop() ?? "";
|
|
170
|
+
body.push(truncateToWidth(last, contentWidth - 1, "") + theme.fg("muted", "…"));
|
|
171
|
+
}
|
|
172
|
+
const { filename, lineRange } = excerpt;
|
|
173
|
+
const caption = lineRange
|
|
174
|
+
? `${filename}#L${lineRange.start}${lineRange.end === lineRange.start ? "" : `-L${lineRange.end}`}`
|
|
175
|
+
: filename;
|
|
176
|
+
return renderPreviewFrame(theme, [theme.fg("accent", caption), ...body], width, 1);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function renderPreviewFrame(
|
|
180
|
+
theme: Theme,
|
|
181
|
+
content: string[],
|
|
182
|
+
width: number,
|
|
183
|
+
padding: number,
|
|
184
|
+
rounded = false,
|
|
185
|
+
): string[] {
|
|
186
|
+
const border = (text: string) => theme.fg("borderMuted", text);
|
|
187
|
+
const edge = "─".repeat(width - 2);
|
|
188
|
+
const gap = " ".repeat(padding);
|
|
189
|
+
const contentWidth = width - 2 - 2 * padding;
|
|
190
|
+
const rows = content.map(
|
|
191
|
+
(text) => `${border("│")}${gap}${truncateToWidth(text, contentWidth, "…", true)}${gap}${border("│")}`,
|
|
192
|
+
);
|
|
193
|
+
const [topLeft, topRight, bottomLeft, bottomRight] = rounded ? "╭╮╰╯" : "┌┐└┘";
|
|
194
|
+
const background = theme.getBgAnsi("toolPendingBg");
|
|
195
|
+
// Truncation adds full SGR resets before the ellipsis and padding.
|
|
196
|
+
return [border(`${topLeft}${edge}${topRight}`), ...rows, border(`${bottomLeft}${edge}${bottomRight}`)].map((line) =>
|
|
197
|
+
theme.bg("toolPendingBg", line.replaceAll("\x1b[0m", `\x1b[0m${background}`)),
|
|
198
|
+
);
|
|
199
|
+
}
|