-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
202 lines (179 loc) · 4.98 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import os from "node:os";
import childProcess from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import readline from "node:readline";
import { stdin, stdout } from "node:process";
import Jimp from "jimp";
const rl = readline.createInterface(stdin);
const IMAGE_REGEX = /_Gi=69[;,]OK/g;
const LOCAL_REGEX = /_Gi=31[;,]OK/g;
export async function hasImageSupport(): Promise<boolean> {
stdin.setRawMode(true);
stdin.resume();
let data = "";
stdin.on("data", function (chunk) {
data += chunk.toString();
});
const subprocess = childProcess.spawn(
`printf`,
[`\\033_Gi=69,s=1,v=1,a=q,t=d,f=24;AAAA\\033\\\\\\033[c`],
{
stdio: [stdin, stdout, "pipe"],
}
);
const all = await new Promise<string>((resolve) => {
setTimeout(() => {
resolve(data);
stdin.pause();
subprocess.kill();
}, 20);
});
// clear line
rl.write("", { ctrl: true, name: "u" });
return IMAGE_REGEX.test(all);
}
export async function hasLocalSupport(): Promise<boolean> {
// create a temp file that will hold a 1x1 image
const image = new Jimp(1, 1, "#00000077");
const tmpFilePath = path.join(
os.tmpdir(),
`.tmp.kitty.${Math.random().toString().slice(2) || "0"}`
);
image.write(tmpFilePath);
stdin.setRawMode(true);
stdin.resume();
let data = "";
stdin.on("data", function (chunk) {
data += chunk.toString();
});
const subprocess = childProcess.spawn(
`printf`,
[
`${`\\033_Gi=31,s=1,v=1,a=q,t=t;${Buffer.from(tmpFilePath).toString(
"base64"
)}\\033\\\\`}`,
],
{
stdio: [stdin, stdout, "pipe"],
}
);
const all = await new Promise<string>((resolve) => {
setTimeout(() => {
resolve(data);
stdin.pause();
subprocess.kill();
}, 20);
});
// clear line
rl.write("", { ctrl: true, name: "u" });
return LOCAL_REGEX.test(all);
}
export async function drawImageFromUrl(pngBuffer: Buffer): Promise<void> {
const tmpFilePath = path.join(
os.tmpdir(),
`.tmp.kitty.${Math.random().toString().slice(2) || "0"}.png`
);
fs.writeFileSync(tmpFilePath, pngBuffer);
const subprocess = childProcess.spawn(
`printf`,
[
`\\033_Gf=100,t=t,a=T,X=4,Y=4;${Buffer.from(tmpFilePath).toString(
"base64"
)}\\033\\\\`,
],
{
stdio: ["pipe", "inherit", "pipe"],
}
);
await new Promise((resolve) => {
setTimeout(() => {
childProcess.spawnSync(`printf`, [`\n`], {
stdio: ["pipe", "inherit", "pipe"],
});
resolve(undefined);
subprocess.kill();
}, 20);
});
}
export async function drawImageFromBuffer(pngBuffer: Buffer): Promise<void> {
const asBase64 = pngBuffer.toString("base64");
const chunks: string[] = [];
for (let i = 0; i < asBase64.length; i += 256) {
chunks.push(asBase64.slice(i, i + 256));
}
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i];
childProcess.spawnSync(
`printf`,
[
`\\033_Gf=100,m=${
i === chunks.length - 1 ? 0 : 1
},a=T,X=4,Y=4;${chunk}\\033\\\\`,
],
{
stdio: ["pipe", "inherit", "pipe"],
}
);
}
childProcess.spawnSync(`printf`, [`\n`], {
stdio: "inherit",
});
}
/// Returns the terminal's support for the Kitty graphics protocol.
export type KittySupport = "local" | "remote" | "none";
let kittySupport: KittySupport | undefined;
export const getKittySupport = async (): Promise<KittySupport> => {
if (kittySupport === undefined) {
kittySupport = (await hasImageSupport())
? (await hasLocalSupport())
? "local"
: "remote"
: "none";
}
stdin.destroy();
return kittySupport;
};
type Options<T = never> = {
width: number;
height: number;
preserveAspectRatio: boolean;
fallback: () => T;
};
export class UnsupportedTerminalError extends Error {
constructor() {
super("Terminal must support Kitty graphics protocol");
this.name = "UnsupportedTerminalError";
}
}
function unsupported(): never {
throw new UnsupportedTerminalError();
}
export const terminalKittyImage = async <T = never>(
image: string | Buffer,
options: Partial<Options<T>> = {}
): Promise<undefined | T> => {
const fallback = options.fallback ?? unsupported;
const kittySupport: KittySupport = await getKittySupport();
const imagePath = path.resolve(process.cwd(), image.toString());
let pngBuffer: Buffer;
if (typeof image === "string") {
const image = await Jimp.read(imagePath);
if (options?.preserveAspectRatio === false) {
image.resize(options.width ?? Jimp.AUTO, options.height ?? Jimp.AUTO);
} else {
image.scaleToFit(options.width ?? 600, options.height ?? 600);
}
pngBuffer = await image.getBufferAsync("image/png");
} else {
pngBuffer = image;
}
if (kittySupport === "local" && typeof image === "string") {
await drawImageFromUrl(pngBuffer);
return;
} else if (kittySupport !== "none") {
await drawImageFromBuffer(pngBuffer);
return;
}
return fallback();
};