@iwascreatedtocreate/asciikit 0.1.1 → 0.2.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/dist/cli.js ADDED
@@ -0,0 +1,159 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, writeFileSync } from 'node:fs';
3
+ import { parseArgs } from 'node:util';
4
+ import { gradients } from './color.js';
5
+ import { ascii } from './compose.js';
6
+ import { boxStyles, toAnsi } from './effects.js';
7
+ import { toSVG } from './export.js';
8
+ import { critters, say } from './layout.js';
9
+ import { fancy, fancyStyles } from './text.js';
10
+ import { loadFont } from './fonts/lazy.js';
11
+ import { fontList } from './fonts/meta.js';
12
+ const HELP = `asciikit — ASCII art in your terminal
13
+
14
+ usage
15
+ asciikit <text> [options]
16
+ echo "text" | asciikit [options]
17
+
18
+ options
19
+ -f, --font <name> font id or name (default: standard) e.g. slant, "ANSI Shadow"
20
+ -l, --list list all fonts (combine with --preview to render each one)
21
+ --preview <text> sample text for --list
22
+ -w, --width <n> wrap at n columns (default: terminal width)
23
+ -a, --align <a> left | center | right
24
+ --layout <l> default | full | fitted | smush | universal-smush
25
+ --letter-spacing <n> extra columns between characters
26
+ -b, --border [style] ${Object.keys(boxStyles).join(' | ')}
27
+ --title <text> border title
28
+ -s, --shadow drop shadow
29
+ --fill <char> replace every visible character
30
+ -g, --gradient <g> preset (${Object.keys(gradients).join(', ')}) or colors "#f00,#00f"
31
+ -d, --direction <d> horizontal | vertical | diagonal | radial
32
+ -c, --color <color> single text color
33
+ --no-color plain text, no ANSI colors
34
+ --fancy <style> unicode text instead of a font: bold, script, fraktur, circled, smallCaps, upsideDown…
35
+ --say <critter> put the text in a speech bubble (${Object.keys(critters).join(' | ')})
36
+ --svg <file> also write an SVG image
37
+ -v, --version print version
38
+ -h, --help show this help
39
+
40
+ examples
41
+ asciikit hello
42
+ asciikit "deploy ok" -f slant -g sunset -b rounded
43
+ asciikit --list --preview Hi
44
+ asciikit "ship it" --say robot
45
+ asciikit hello --fancy fraktur
46
+ `;
47
+ function fail(message) {
48
+ process.stderr.write(`asciikit: ${message}\n`);
49
+ process.exit(1);
50
+ }
51
+ async function readStdin() {
52
+ if (process.stdin.isTTY)
53
+ return '';
54
+ const chunks = [];
55
+ for await (const c of process.stdin)
56
+ chunks.push(c);
57
+ return Buffer.concat(chunks).toString('utf8').replace(/\s+$/, '');
58
+ }
59
+ async function main() {
60
+ let parsed;
61
+ try {
62
+ parsed = parseArgs({
63
+ allowPositionals: true,
64
+ options: {
65
+ font: { type: 'string', short: 'f' },
66
+ list: { type: 'boolean', short: 'l' },
67
+ preview: { type: 'string' },
68
+ width: { type: 'string', short: 'w' },
69
+ align: { type: 'string', short: 'a' },
70
+ layout: { type: 'string' },
71
+ 'letter-spacing': { type: 'string' },
72
+ border: { type: 'string', short: 'b' },
73
+ title: { type: 'string' },
74
+ shadow: { type: 'boolean', short: 's' },
75
+ fill: { type: 'string' },
76
+ gradient: { type: 'string', short: 'g' },
77
+ direction: { type: 'string', short: 'd' },
78
+ color: { type: 'string', short: 'c' },
79
+ 'no-color': { type: 'boolean' },
80
+ fancy: { type: 'string' },
81
+ say: { type: 'string' },
82
+ svg: { type: 'string' },
83
+ version: { type: 'boolean', short: 'v' },
84
+ help: { type: 'boolean', short: 'h' },
85
+ },
86
+ });
87
+ }
88
+ catch (e) {
89
+ fail(`${e.message}\nrun "asciikit --help" for usage`);
90
+ }
91
+ const { values: o, positionals } = parsed;
92
+ if (o.help)
93
+ return void process.stdout.write(HELP);
94
+ if (o.version) {
95
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
96
+ return void process.stdout.write(`${pkg.version}\n`);
97
+ }
98
+ if (o.list) {
99
+ for (const meta of fontList) {
100
+ if (o.preview) {
101
+ const font = await loadFont(meta.id);
102
+ process.stdout.write(`\n${meta.name} (${meta.id})\n${ascii(o.preview, { font })}\n`);
103
+ }
104
+ else {
105
+ process.stdout.write(`${meta.id.padEnd(28)} ${meta.name}\n`);
106
+ }
107
+ }
108
+ return;
109
+ }
110
+ const text = positionals.length ? positionals.join(' ') : await readStdin();
111
+ if (!text)
112
+ return void process.stdout.write(HELP);
113
+ // these two skip FIGlet fonts entirely
114
+ if (o.fancy !== undefined || o.say !== undefined) {
115
+ if (o.fancy !== undefined && !fancyStyles.includes(o.fancy))
116
+ fail(`unknown --fancy style "${o.fancy}". Try: ${fancyStyles.join(', ')}`);
117
+ if (o.say && !Object.prototype.hasOwnProperty.call(critters, o.say))
118
+ fail(`unknown critter "${o.say}". Try: ${Object.keys(critters).join(', ')}`);
119
+ const styled = o.fancy !== undefined ? fancy(text, o.fancy) : text;
120
+ const out = o.say !== undefined ? say(styled, (o.say || 'cat')) : styled;
121
+ return void process.stdout.write(`${out}\n`);
122
+ }
123
+ let font;
124
+ try {
125
+ font = await loadFont(o.font ?? 'standard');
126
+ }
127
+ catch {
128
+ fail(`unknown font "${o.font}". Run "asciikit --list" to see all fonts.`);
129
+ }
130
+ const width = o.width ? Number(o.width) : process.stdout.isTTY ? process.stdout.columns : undefined;
131
+ if (o.width && !(width > 0))
132
+ fail('--width must be a positive number');
133
+ const options = {
134
+ font,
135
+ width,
136
+ align: o.align,
137
+ horizontalLayout: o.layout,
138
+ letterSpacing: o['letter-spacing'] ? Number(o['letter-spacing']) : undefined,
139
+ fill: o.fill,
140
+ shadow: o.shadow,
141
+ border: o.border !== undefined || o.title
142
+ ? { style: (o.border || 'single'), title: o.title, padding: { x: 2, y: 1 } }
143
+ : undefined,
144
+ };
145
+ const art = ascii(text, options);
146
+ const gradient = o.gradient
147
+ ? Object.prototype.hasOwnProperty.call(gradients, o.gradient)
148
+ ? o.gradient
149
+ : o.gradient.split(',').map((s) => s.trim()).filter(Boolean)
150
+ : undefined;
151
+ const direction = o.direction;
152
+ const useColor = !o['no-color'] && process.stdout.isTTY && !process.env.NO_COLOR;
153
+ process.stdout.write(`${useColor ? toAnsi(art, { gradient, direction, color: o.color }) : art}\n`);
154
+ if (o.svg) {
155
+ writeFileSync(o.svg, toSVG(art, { gradient, gradientDirection: direction, color: o.color, background: '#000' }));
156
+ process.stderr.write(`asciikit: wrote ${o.svg}\n`);
157
+ }
158
+ }
159
+ main().catch((e) => fail(e instanceof Error ? e.message : String(e)));
package/dist/color.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { own } from './util.js';
1
2
  const NAMED = {
2
3
  black: '#000000', white: '#ffffff', red: '#ff0000', green: '#00ff00', blue: '#0000ff',
3
4
  yellow: '#ffff00', cyan: '#00ffff', magenta: '#ff00ff', gray: '#808080', grey: '#808080',
@@ -6,13 +7,14 @@ const NAMED = {
6
7
  /** Parse `#rgb`, `#rrggbb`, `rgb(r,g,b)` or a basic color name. */
7
8
  export function parseColor(input) {
8
9
  let s = input.trim().toLowerCase();
9
- if (NAMED[s])
10
- s = NAMED[s];
10
+ s = own(NAMED, s) ?? s;
11
11
  const rgb = s.match(/^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/);
12
12
  if (rgb)
13
13
  return [+rgb[1], +rgb[2], +rgb[3]];
14
14
  if (s.startsWith('#'))
15
15
  s = s.slice(1);
16
+ if (!/^[0-9a-f]{3,8}$/.test(s))
17
+ return [255, 255, 255];
16
18
  if (s.length === 3 || s.length === 4)
17
19
  s = s.slice(0, 3).split('').map((c) => c + c).join('');
18
20
  const n = parseInt(s.slice(0, 6), 16);
package/dist/effects.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import { sampleGradient, gradients } from './color.js';
2
+ import { escapeHTML, own, safeCssColor } from './util.js';
3
+ import { cells, fixCells, stringWidth } from './width.js';
2
4
  export const toLines = (art) => (typeof art === 'string' ? art.split('\n') : [...art]);
3
5
  const out = (lines) => lines.join('\n');
4
- const chars = (s) => Array.from(s);
5
- const len = (s) => chars(s).length;
6
+ // One entry per display column (wide chars are followed by a '' placeholder).
7
+ const chars = (s) => cells(s);
8
+ const len = (s) => stringWidth(s);
6
9
  /** Width (in columns) of the widest row. */
7
10
  export function measure(art) {
8
11
  const lines = toLines(art);
@@ -83,7 +86,7 @@ function edge(fill, width, label, labelAlign = 'left') {
83
86
  const text = ` ${label} `;
84
87
  const tl = len(text);
85
88
  if (tl >= width)
86
- return chars(text).slice(0, width).join('');
89
+ return fixCells(chars(text).slice(0, width)).join('');
87
90
  const free = width - tl;
88
91
  const left = labelAlign === 'center' ? Math.floor(free / 2) : labelAlign === 'right' ? free - 1 : Math.min(1, free);
89
92
  return fill.repeat(left) + text + fill.repeat(free - left);
@@ -91,7 +94,7 @@ function edge(fill, width, label, labelAlign = 'left') {
91
94
  /** Draw a box (border) around the art. */
92
95
  export function box(art, options = {}) {
93
96
  const o = typeof options === 'string' ? { style: options } : options;
94
- const s = typeof o.style === 'object' ? o.style : boxStyles[o.style ?? 'single'];
97
+ const s = typeof o.style === 'object' ? o.style : (own(boxStyles, o.style ?? 'single') ?? boxStyles.single);
95
98
  let inner = pad(art, o.padding ?? { x: 1, y: 0 });
96
99
  if (o.width)
97
100
  inner = normalize(align(inner, o.align ?? 'left', o.width));
@@ -154,7 +157,18 @@ const V_MIRROR = {
154
157
  /** Mirror left-to-right, swapping directional characters. */
155
158
  export function flipHorizontal(art) {
156
159
  const lines = toLines(normalize(art));
157
- return out(lines.map((l) => chars(l).reverse().map((c) => H_MIRROR[c] ?? c).join('').replace(/\s+$/, '')));
160
+ return out(lines.map((l) => {
161
+ const row = chars(l).reverse();
162
+ // Reversing puts each wide char's placeholder in front of it; swap them back.
163
+ for (let i = 0; i < row.length - 1; i++) {
164
+ if (row[i] === '' && row[i + 1] !== '') {
165
+ row[i] = row[i + 1];
166
+ row[i + 1] = '';
167
+ i++;
168
+ }
169
+ }
170
+ return row.map((c) => H_MIRROR[c] ?? c).join('').replace(/\s+$/, '');
171
+ }));
158
172
  }
159
173
  /** Mirror top-to-bottom, swapping directional characters. */
160
174
  export function flipVertical(art) {
@@ -170,12 +184,12 @@ export function rotate(art, degrees) {
170
184
  const w = grid[0]?.length ?? 0;
171
185
  const res = [];
172
186
  for (let c = 0; c < w; c++) {
173
- let row = '';
187
+ const row = [];
174
188
  for (let r = 0; r < h; r++) {
175
189
  const ch = degrees === 90 ? grid[h - 1 - r][c] : grid[r][w - 1 - c];
176
- row += ROT90[ch] ?? ch;
190
+ row.push(ROT90[ch] ?? ch);
177
191
  }
178
- res.push(row.replace(/\s+$/, ''));
192
+ res.push(fixCells(row).join('').replace(/\s+$/, ''));
179
193
  }
180
194
  return out(res);
181
195
  }
@@ -235,7 +249,7 @@ export function overlay(base, top, x = 0, y = 0) {
235
249
  row[k + x] = c;
236
250
  });
237
251
  });
238
- return out(b.map((r) => r.join('')));
252
+ return out(b.map((r) => fixCells(r).join('')));
239
253
  }
240
254
  /** Pipe art through a sequence of transforms: `pipe(art, a => box(a), fill('#'))`. */
241
255
  export function pipe(art, ...fns) {
@@ -243,7 +257,8 @@ export function pipe(art, ...fns) {
243
257
  }
244
258
  /** Compute a per-character color grid for a gradient. */
245
259
  export function gradientCells(art, colors, direction = 'horizontal') {
246
- const stops = typeof colors === 'string' ? gradients[colors] : colors;
260
+ // A preset name, or any other string treated as a single color.
261
+ const stops = typeof colors === 'string' ? (own(gradients, colors) ?? [colors]) : colors;
247
262
  const lines = toLines(art).map(chars);
248
263
  const h = lines.length;
249
264
  const w = Math.max(1, ...lines.map((l) => l.length));
@@ -291,13 +306,14 @@ export function toAnsi(art, options = {}) {
291
306
  }
292
307
  /** Escape art for safe insertion into HTML. */
293
308
  export function toHTML(art, options = {}) {
294
- const esc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
295
309
  if (!options.gradient) {
296
- const style = options.color ? ` style="color:${options.color}"` : '';
297
- return `<pre${style}>${esc(typeof art === 'string' ? art : out([...art]))}</pre>`;
310
+ // Only well-formed CSS colors are emitted; anything else is dropped (prevents attribute injection).
311
+ const color = safeCssColor(options.color);
312
+ const style = color ? ` style="color:${escapeHTML(color)}"` : '';
313
+ return `<pre${style}>${escapeHTML(typeof art === 'string' ? art : out([...art]))}</pre>`;
298
314
  }
299
315
  const body = gradientCells(art, options.gradient, options.direction)
300
- .map((row) => row.map((c) => (c.color ? `<span style="color:${c.color}">${esc(c.char)}</span>` : c.char)).join(''))
316
+ .map((row) => row.map((c) => (c.color ? `<span style="color:${c.color}">${escapeHTML(c.char)}</span>` : escapeHTML(c.char))).join(''))
301
317
  .join('\n');
302
318
  return `<pre>${body}</pre>`;
303
319
  }
@@ -0,0 +1,37 @@
1
+ import { type GradientName } from './color.js';
2
+ import { type Art, type GradientDirection } from './effects.js';
3
+ export interface ImageExportOptions {
4
+ /** Font size in px (default 16). */
5
+ fontSize?: number;
6
+ /** Line height as a multiple of font size (default 1). */
7
+ lineHeight?: number;
8
+ /** Monospace font stack. */
9
+ fontFamily?: string;
10
+ /** Text color (default `#ededed`). Ignored when `gradient` is set. */
11
+ color?: string;
12
+ /** Gradient preset or color stops. */
13
+ gradient?: readonly string[] | GradientName;
14
+ gradientDirection?: GradientDirection;
15
+ /** Background color; omit for transparent. */
16
+ background?: string;
17
+ /** Space around the art in px (default 16). */
18
+ padding?: number;
19
+ /** Width of one character cell as a fraction of font size (default 0.6). */
20
+ cellWidth?: number;
21
+ }
22
+ /**
23
+ * Render art as a standalone SVG string — crisp at any size, perfect for
24
+ * OG images, READMEs, slides or `<img src="data:image/svg+xml,…">`.
25
+ * Each line is stretched to its exact column width, so alignment survives any font.
26
+ */
27
+ export declare function toSVG(art: Art, options?: ImageExportOptions): string;
28
+ /** Browser: draw the art onto a new canvas. `scale` defaults to devicePixelRatio. */
29
+ export declare function toCanvas(art: Art, options?: ImageExportOptions & {
30
+ scale?: number;
31
+ }): HTMLCanvasElement;
32
+ /** Browser: render the art to a PNG Blob (e.g. for a download button). */
33
+ export declare function toPNG(art: Art, options?: ImageExportOptions & {
34
+ scale?: number;
35
+ }): Promise<Blob>;
36
+ /** Browser: trigger a download of text, SVG or a Blob. */
37
+ export declare function downloadFile(filename: string, data: string | Blob, type?: string): void;
package/dist/export.js ADDED
@@ -0,0 +1,112 @@
1
+ import { gradients } from './color.js';
2
+ import { toLines } from './effects.js';
3
+ import { escapeHTML, own } from './util.js';
4
+ import { stringWidth } from './width.js';
5
+ const MONO = "ui-monospace, 'SFMono-Regular', 'JetBrains Mono', Menlo, Consolas, 'Liberation Mono', monospace";
6
+ function layout(art, o) {
7
+ const lines = toLines(art).map((l) => l.replace(/\s+$/, ''));
8
+ const fontSize = o.fontSize ?? 16;
9
+ const lineHeight = (o.lineHeight ?? 1) * fontSize;
10
+ const cell = (o.cellWidth ?? 0.6) * fontSize;
11
+ const padding = o.padding ?? 16;
12
+ const cols = lines.reduce((m, l) => Math.max(m, stringWidth(l)), 0);
13
+ const width = Math.ceil(cols * cell + padding * 2);
14
+ const height = Math.ceil(lines.length * lineHeight + padding * 2);
15
+ const stops = o.gradient
16
+ ? typeof o.gradient === 'string'
17
+ ? (own(gradients, o.gradient) ?? [o.gradient])
18
+ : o.gradient
19
+ : null;
20
+ return { lines, fontSize, lineHeight, cell, padding, width, height, stops };
21
+ }
22
+ /**
23
+ * Render art as a standalone SVG string — crisp at any size, perfect for
24
+ * OG images, READMEs, slides or `<img src="data:image/svg+xml,…">`.
25
+ * Each line is stretched to its exact column width, so alignment survives any font.
26
+ */
27
+ export function toSVG(art, options = {}) {
28
+ const L = layout(art, options);
29
+ const dir = options.gradientDirection ?? 'horizontal';
30
+ let defs = '';
31
+ let fill = escapeHTML(options.color ?? '#ededed');
32
+ if (L.stops && L.stops.length) {
33
+ const stopTags = L.stops
34
+ .map((c, i) => `<stop offset="${L.stops.length === 1 ? 0 : i / (L.stops.length - 1)}" stop-color="${escapeHTML(c)}"/>`)
35
+ .join('');
36
+ const [x2, y2] = dir === 'vertical' ? [0, 1] : dir === 'diagonal' ? [1, 1] : [1, 0];
37
+ defs =
38
+ dir === 'radial'
39
+ ? `<defs><radialGradient id="ak-g">${stopTags}</radialGradient></defs>`
40
+ : `<defs><linearGradient id="ak-g" x1="0" y1="0" x2="${x2}" y2="${y2}">${stopTags}</linearGradient></defs>`;
41
+ fill = 'url(#ak-g)';
42
+ }
43
+ const bg = options.background ? `<rect width="100%" height="100%" fill="${escapeHTML(options.background)}"/>` : '';
44
+ const text = L.lines
45
+ .map((line, i) => {
46
+ if (!line)
47
+ return '';
48
+ const y = L.padding + (i + 0.8) * L.lineHeight;
49
+ const len = (stringWidth(line) * L.cell).toFixed(2);
50
+ return `<text x="${L.padding}" y="${y.toFixed(2)}" textLength="${len}" lengthAdjust="spacingAndGlyphs">${escapeHTML(line)}</text>`;
51
+ })
52
+ .join('');
53
+ return (`<svg xmlns="http://www.w3.org/2000/svg" width="${L.width}" height="${L.height}" viewBox="0 0 ${L.width} ${L.height}">` +
54
+ `${defs}${bg}<g fill="${fill}" font-family="${escapeHTML(options.fontFamily ?? MONO)}" font-size="${L.fontSize}" xml:space="preserve">${text}</g></svg>`);
55
+ }
56
+ /** Browser: draw the art onto a new canvas. `scale` defaults to devicePixelRatio. */
57
+ export function toCanvas(art, options = {}) {
58
+ if (typeof document === 'undefined')
59
+ throw new Error('asciikit: toCanvas() needs a browser. Use toSVG() on the server.');
60
+ const L = layout(art, options);
61
+ const scale = options.scale ?? (typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1);
62
+ const canvas = document.createElement('canvas');
63
+ canvas.width = Math.ceil(L.width * scale);
64
+ canvas.height = Math.ceil(L.height * scale);
65
+ const ctx = canvas.getContext('2d');
66
+ ctx.scale(scale, scale);
67
+ if (options.background) {
68
+ ctx.fillStyle = options.background;
69
+ ctx.fillRect(0, 0, L.width, L.height);
70
+ }
71
+ ctx.font = `${L.fontSize}px ${options.fontFamily ?? MONO}`;
72
+ ctx.textBaseline = 'alphabetic';
73
+ if (L.stops && L.stops.length) {
74
+ const dir = options.gradientDirection ?? 'horizontal';
75
+ const g = dir === 'radial'
76
+ ? ctx.createRadialGradient(L.width / 2, L.height / 2, 0, L.width / 2, L.height / 2, Math.max(L.width, L.height) / 2)
77
+ : ctx.createLinearGradient(0, 0, dir === 'vertical' ? 0 : L.width, dir === 'horizontal' ? 0 : L.height);
78
+ L.stops.forEach((c, i) => g.addColorStop(L.stops.length === 1 ? 0 : i / (L.stops.length - 1), c));
79
+ ctx.fillStyle = g;
80
+ }
81
+ else {
82
+ ctx.fillStyle = options.color ?? '#ededed';
83
+ }
84
+ L.lines.forEach((line, i) => {
85
+ if (!line)
86
+ return;
87
+ const y = L.padding + (i + 0.8) * L.lineHeight;
88
+ const target = stringWidth(line) * L.cell;
89
+ const natural = ctx.measureText(line).width || target;
90
+ ctx.save();
91
+ ctx.translate(L.padding, y);
92
+ ctx.scale(target / natural, 1); // keep columns aligned whatever the font's advance width is
93
+ ctx.fillText(line, 0, 0);
94
+ ctx.restore();
95
+ });
96
+ return canvas;
97
+ }
98
+ /** Browser: render the art to a PNG Blob (e.g. for a download button). */
99
+ export function toPNG(art, options = {}) {
100
+ const canvas = toCanvas(art, options);
101
+ return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('asciikit: PNG encoding failed'))), 'image/png'));
102
+ }
103
+ /** Browser: trigger a download of text, SVG or a Blob. */
104
+ export function downloadFile(filename, data, type = 'text/plain;charset=utf-8') {
105
+ const blob = typeof data === 'string' ? new Blob([data], { type }) : data;
106
+ const url = URL.createObjectURL(blob);
107
+ const a = document.createElement('a');
108
+ a.href = url;
109
+ a.download = filename;
110
+ a.click();
111
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
112
+ }
@@ -340,7 +340,7 @@ const byLoose = new Map(Object.keys(fontLoaders).map((id) => [normalise(id), id]
340
340
  * Load a bundled font on demand by id ("ansi-shadow") or name ("ANSI Shadow").
341
341
  */
342
342
  export function loadFont(idOrName) {
343
- const id = (idOrName in fontLoaders ? idOrName : byLoose.get(normalise(idOrName)));
343
+ const id = (Object.prototype.hasOwnProperty.call(fontLoaders, idOrName) ? idOrName : byLoose.get(normalise(idOrName)));
344
344
  if (!id)
345
345
  return Promise.reject(new Error(`asciikit: unknown font "${idOrName}"`));
346
346
  let p = cache.get(id);
package/dist/image.d.ts CHANGED
@@ -1,3 +1,6 @@
1
+ /** Upper bounds for output size (characters), regardless of options. */
2
+ export declare const MAX_COLUMNS = 1000;
3
+ export declare const MAX_ROWS = 1000;
1
4
  /** Character ramps ordered from dark (empty) to bright (dense). */
2
5
  export declare const charsets: {
3
6
  standard: string;
package/dist/image.js CHANGED
@@ -1,3 +1,7 @@
1
+ import { clamp, own } from './util.js';
2
+ /** Upper bounds for output size (characters), regardless of options. */
3
+ export const MAX_COLUMNS = 1000;
4
+ export const MAX_ROWS = 1000;
1
5
  /** Character ramps ordered from dark (empty) to bright (dense). */
2
6
  export const charsets = {
3
7
  standard: ' .:-=+*#%@',
@@ -122,9 +126,10 @@ const BRAILLE_BITS = [
122
126
  */
123
127
  export function pixelsToAscii(src, options = {}) {
124
128
  const mode = options.mode ?? 'ramp';
125
- const cellAspect = options.cellAspect ?? 2;
126
- const cols = Math.max(1, Math.floor(options.columns ?? 80));
127
- const rows = Math.max(1, Math.floor(options.rows ?? Math.round((src.height / src.width) * cols / cellAspect)));
129
+ const cellAspect = clamp(options.cellAspect, 0.1, 10, 2);
130
+ // Hard limits keep a bad or hostile `columns`/`rows` from allocating hundreds of MB.
131
+ const cols = Math.floor(clamp(options.columns, 1, MAX_COLUMNS, 80));
132
+ const rows = Math.floor(clamp(options.rows ?? Math.round(((src.height || 1) / (src.width || 1)) * cols / cellAspect), 1, MAX_ROWS, 1));
128
133
  const threshold = options.threshold ?? 0.5;
129
134
  if (mode === 'braille') {
130
135
  const pc = cols * 2;
@@ -187,7 +192,10 @@ export function pixelsToAscii(src, options = {}) {
187
192
  }
188
193
  }
189
194
  else {
190
- const ramp = Array.from(charsets[options.charset] ?? options.charset ?? charsets.standard);
195
+ const preset = options.charset === undefined ? charsets.standard : own(charsets, options.charset);
196
+ let ramp = Array.from(preset ?? options.charset ?? charsets.standard);
197
+ if (ramp.length < 2)
198
+ ramp = Array.from(charsets.standard);
191
199
  const q = quantize(lum, cols, rows, ramp.length, options.dither ?? 'none');
192
200
  lines = [];
193
201
  for (let y = 0; y < rows; y++) {
@@ -225,9 +233,14 @@ export async function imageToAscii(source, options = {}) {
225
233
  img.crossOrigin = 'anonymous';
226
234
  img.decoding = 'async';
227
235
  img.src = url;
228
- await img.decode();
229
- if (typeof source !== 'string')
230
- URL.revokeObjectURL(url);
236
+ try {
237
+ await img.decode();
238
+ }
239
+ finally {
240
+ // Release the blob URL even when decoding fails.
241
+ if (typeof source !== 'string')
242
+ URL.revokeObjectURL(url);
243
+ }
231
244
  el = img;
232
245
  w = img.naturalWidth;
233
246
  h = img.naturalHeight;
package/dist/index.d.ts CHANGED
@@ -5,6 +5,12 @@ export { render, renderLines, textSync, horizontalMode, verticalMode } from './r
5
5
  export { ascii, transform, type AsciiOptions, type TransformOptions } from './compose.js';
6
6
  export { toLines, measure, normalize, pad, trim, align, box, boxStyles, shadow, fill, replaceChars, invert, flipHorizontal, flipVertical, rotate, scale, join, stack, overlay, pipe, gradientCells, toAnsi, toHTML, type Art, type Spacing, type BoxChars, type BoxStyle, type BoxOptions, type ShadowOptions, type JoinOptions, type GradientDirection, type ColorCell, } from './effects.js';
7
7
  export { parseColor, toHex, sampleGradient, gradients, type RGB, type GradientName } from './color.js';
8
- export { pixelsToAscii, imageToAscii, charsets, type CharsetName, type PixelSource, type ImageToAsciiOptions, type AsciiImageResult, } from './image.js';
8
+ export { pixelsToAscii, imageToAscii, MAX_COLUMNS, MAX_ROWS, charsets, type CharsetName, type PixelSource, type ImageToAsciiOptions, type AsciiImageResult, } from './image.js';
9
9
  export { animationFrame, continuousEffects, type AnimationEffect, type FrameOptions } from './animate.js';
10
10
  export { spinners, type Spinner, type SpinnerName } from './spinners.js';
11
+ export { toSVG, toCanvas, toPNG, downloadFile, type ImageExportOptions } from './export.js';
12
+ export { graphemes, charWidth, stringWidth, cells } from './width.js';
13
+ export { wrapText, truncate, fancy, fancyStyles, type FancyStyle, type WrapOptions } from './text.js';
14
+ export { table, tableStyles, tree, treeStyles, divider, speechBubble, say, critters, type TableChars, type TableStyle, type TableCell, type TableOptions, type TreeNode, type TreeInput, type TreeStyle, type DividerOptions, type BubbleOptions, type CritterName, } from './layout.js';
15
+ export { sparkline, barChart, lineChart, progressBar, progressStyles, type SparklineOptions, type BarChartOptions, type LineChartOptions, type ProgressOptions, type ProgressStyle, type ChartData, } from './charts.js';
16
+ export { AsciiCanvas, BrailleCanvas, type RectOptions } from './canvas.js';
package/dist/index.js CHANGED
@@ -4,6 +4,12 @@ export { render, renderLines, textSync, horizontalMode, verticalMode } from './r
4
4
  export { ascii, transform } from './compose.js';
5
5
  export { toLines, measure, normalize, pad, trim, align, box, boxStyles, shadow, fill, replaceChars, invert, flipHorizontal, flipVertical, rotate, scale, join, stack, overlay, pipe, gradientCells, toAnsi, toHTML, } from './effects.js';
6
6
  export { parseColor, toHex, sampleGradient, gradients } from './color.js';
7
- export { pixelsToAscii, imageToAscii, charsets, } from './image.js';
7
+ export { pixelsToAscii, imageToAscii, MAX_COLUMNS, MAX_ROWS, charsets, } from './image.js';
8
8
  export { animationFrame, continuousEffects } from './animate.js';
9
9
  export { spinners } from './spinners.js';
10
+ export { toSVG, toCanvas, toPNG, downloadFile } from './export.js';
11
+ export { graphemes, charWidth, stringWidth, cells } from './width.js';
12
+ export { wrapText, truncate, fancy, fancyStyles } from './text.js';
13
+ export { table, tableStyles, tree, treeStyles, divider, speechBubble, say, critters, } from './layout.js';
14
+ export { sparkline, barChart, lineChart, progressBar, progressStyles, } from './charts.js';
15
+ export { AsciiCanvas, BrailleCanvas } from './canvas.js';