@nbtca/prompt 1.5.13 → 1.5.15

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.
@@ -1,6 +1,14 @@
1
- import makeFetchCookie from 'fetch-cookie';
2
- import { CookieJar } from 'tough-cookie';
1
+ import { createCookieJar } from './cookie-jar.js';
3
2
  import { AuthError, SessionExpiredError } from './errors.js';
3
+ const MAX_REDIRECTS = 8;
4
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
5
+ const BODY_HEADERS = [
6
+ 'content-type',
7
+ 'content-length',
8
+ 'content-encoding',
9
+ 'content-language',
10
+ 'content-location',
11
+ ];
4
12
  const WEBVPN_HOST = 'webvpn.nbt.edu.cn';
5
13
  const AUTH_HOST = 'authserver-443.webvpn.nbt.edu.cn';
6
14
  export const JWXT_HOST = 'jwxt-443.webvpn.nbt.edu.cn';
@@ -117,25 +125,8 @@ function safeFetchError(error, stage) {
117
125
  return new AuthError('NETWORK', stage, 'The campus service request failed.', { retryable: true });
118
126
  }
119
127
  export function createCampusCookieSession(options = {}) {
120
- // Tough Cookie's secure defaults reject public suffixes and use strict
121
- // parsing while tolerating legacy prefix mistakes. The campus WebVPN relies
122
- // on its default special-domain handling during the CAS callback.
123
- const jar = options.jar ?? new CookieJar();
128
+ const jar = options.jar ?? createCookieJar();
124
129
  const baseFetch = options.baseFetch ?? globalThis.fetch;
125
- const guardedFetch = async (input, init) => {
126
- const url = new URL(input instanceof Request ? input.url : input.toString());
127
- assertAllowedCampusUrl(url);
128
- // Caller headers were checked before fetch-cookie received them. A Cookie
129
- // header at this layer was added by the private jar and is expected.
130
- const headers = new Headers(input instanceof Request ? input.headers : undefined);
131
- for (const [name, value] of new Headers(init?.headers))
132
- headers.set(name, value);
133
- if (headers.has('authorization') || headers.has('host')) {
134
- throw new AuthError('UNTRUSTED_URL', 'session', 'Authentication headers are not allowed.');
135
- }
136
- return baseFetch(input, init);
137
- };
138
- const cookieFetch = makeFetchCookie(guardedFetch, jar, false);
139
130
  const timeoutMs = options.timeoutMs ?? 15_000;
140
131
  async function request(url, init = {}, stage = 'session') {
141
132
  assertAllowedCampusUrl(url);
@@ -150,13 +141,43 @@ export function createCampusCookieSession(options = {}) {
150
141
  }, timeoutMs).unref();
151
142
  // Keep the timer running after the headers: the caller still has to read the body.
152
143
  const signal = init.signal ? AbortSignal.any([init.signal, timeout.signal]) : timeout.signal;
144
+ const headers = new Headers(safeHeaders(init.headers));
145
+ let method = init.method ?? 'GET';
146
+ let body = init.body ?? null;
153
147
  try {
154
- return await cookieFetch(url, {
155
- ...init,
156
- headers: safeHeaders(init.headers),
157
- signal,
158
- maxRedirect: 8,
159
- });
148
+ for (let redirects = 0;; redirects += 1) {
149
+ const cookie = jar.cookieHeader(url);
150
+ if (cookie)
151
+ headers.set('cookie', cookie);
152
+ else
153
+ headers.delete('cookie');
154
+ const response = await baseFetch(url, {
155
+ ...init,
156
+ method,
157
+ body,
158
+ headers,
159
+ signal,
160
+ redirect: 'manual',
161
+ });
162
+ const responseUrl = new URL(response.url || url);
163
+ jar.store(responseUrl, response.headers.getSetCookie());
164
+ const location = response.headers.get('location');
165
+ if (!REDIRECT_STATUSES.has(response.status) || location === null) {
166
+ Object.defineProperty(response, 'url', { value: responseUrl.href });
167
+ return response;
168
+ }
169
+ await response.body?.cancel();
170
+ if (redirects >= MAX_REDIRECTS)
171
+ throw new Error('Too many campus redirects.');
172
+ if (response.status === 303 || (method === 'POST' && response.status <= 302)) {
173
+ method = 'GET';
174
+ body = null;
175
+ for (const name of BODY_HEADERS)
176
+ headers.delete(name);
177
+ }
178
+ url = new URL(location, responseUrl);
179
+ assertAllowedCampusUrl(url);
180
+ }
160
181
  }
161
182
  catch (error) {
162
183
  throw safeFetchError(error, stage);
@@ -189,13 +210,16 @@ export function createCampusCookieSession(options = {}) {
189
210
  request,
190
211
  timetableTransport,
191
212
  serialize: () => jar.serialize(),
192
- close: () => jar.removeAllCookies(),
213
+ close: () => {
214
+ jar.clear();
215
+ return Promise.resolve();
216
+ },
193
217
  };
194
218
  }
195
- export async function cookieSessionFromSerialized(serialized, options = {}) {
219
+ export function cookieSessionFromSerialized(serialized, options = {}) {
196
220
  let jar;
197
221
  try {
198
- jar = await CookieJar.deserialize(serialized);
222
+ jar = createCookieJar(serialized);
199
223
  }
200
224
  catch {
201
225
  throw new SessionExpiredError();
@@ -0,0 +1,141 @@
1
+ const HIDDEN = /<!--[\s\S]*?(?:-->|$)|<(script|style|template|textarea|title|noscript|iframe|xmp|noembed|noframes)\b[\s\S]*?(?:<\/\1\s*>|$)/gi;
2
+ const VOID = new Set(['area', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'wbr']);
3
+ const TAG_NAME = /<(\/?)([a-zA-Z][^\t\n\f\r />]*)/y;
4
+ const ATTRIBUTE_NAME = /[^\t\n\f\r />=]+/y;
5
+ const SPACE = /[\t\n\f\r ]*/y;
6
+ const UNQUOTED = /[^\t\n\f\r >]*/y;
7
+ const ENTITY = /&(?:#[xX]([0-9a-fA-F]+);?|#([0-9]+);?|(amp|lt|gt|quot|apos|nbsp)(?:;|(?![\w=])))/g;
8
+ const NAMED = {
9
+ amp: '&',
10
+ lt: '<',
11
+ gt: '>',
12
+ quot: '"',
13
+ apos: "'",
14
+ nbsp: ' ',
15
+ };
16
+ function decode(text) {
17
+ return text.replace(ENTITY, (match, hex, decimal, name) => {
18
+ if (name)
19
+ return NAMED[name] ?? match;
20
+ const code = hex ? Number.parseInt(hex, 16) : Number(decimal);
21
+ return code > 0 && code <= 0x10ffff && (code < 0xd800 || code > 0xdfff)
22
+ ? String.fromCodePoint(code)
23
+ : '�';
24
+ });
25
+ }
26
+ function sticky(pattern, html, at) {
27
+ pattern.lastIndex = at;
28
+ return pattern.exec(html)?.[0] ?? '';
29
+ }
30
+ function* tags(html) {
31
+ let at = html.indexOf('<');
32
+ while (at >= 0) {
33
+ TAG_NAME.lastIndex = at;
34
+ const head = TAG_NAME.exec(html);
35
+ if (!head) {
36
+ at = html.indexOf('<', at + 1);
37
+ continue;
38
+ }
39
+ const attributes = new Map();
40
+ let cursor = at + head[0].length;
41
+ while (cursor < html.length && html[cursor] !== '>') {
42
+ cursor += sticky(SPACE, html, cursor).length;
43
+ if (html[cursor] === '/' || html[cursor] === '>') {
44
+ if (html[cursor] === '/')
45
+ cursor += 1;
46
+ continue;
47
+ }
48
+ const name = sticky(ATTRIBUTE_NAME, html, cursor);
49
+ cursor += Math.max(name.length, 1);
50
+ cursor += sticky(SPACE, html, cursor).length;
51
+ let value = '';
52
+ if (html[cursor] === '=') {
53
+ cursor += 1 + sticky(SPACE, html, cursor + 1).length;
54
+ const quote = html[cursor];
55
+ if (quote === '"' || quote === "'") {
56
+ const close = html.indexOf(quote, cursor + 1);
57
+ if (close < 0)
58
+ return;
59
+ value = html.slice(cursor + 1, close);
60
+ cursor = close + 1;
61
+ }
62
+ else {
63
+ value = sticky(UNQUOTED, html, cursor);
64
+ cursor += value.length;
65
+ }
66
+ }
67
+ const key = name.toLowerCase();
68
+ if (name && !attributes.has(key))
69
+ attributes.set(key, decode(value));
70
+ }
71
+ if (cursor >= html.length)
72
+ return;
73
+ yield {
74
+ name: (head[2] ?? '').toLowerCase(),
75
+ closing: head[1] === '/',
76
+ attributes,
77
+ start: at,
78
+ end: cursor + 1,
79
+ };
80
+ at = html.indexOf('<', cursor + 1);
81
+ }
82
+ }
83
+ function visible(html) {
84
+ return html.replace(/\r\n?/g, '\n').replace(HIDDEN, '');
85
+ }
86
+ export function readLoginForm(source) {
87
+ let action;
88
+ let execution;
89
+ let salt;
90
+ let inForm = false;
91
+ for (const tag of tags(visible(source))) {
92
+ const id = tag.attributes.get('id');
93
+ if (tag.name === 'form') {
94
+ if (tag.closing)
95
+ inForm = false;
96
+ else if (!inForm && id === 'pwdFromId') {
97
+ inForm = true;
98
+ action ??= tag.attributes.get('action');
99
+ }
100
+ continue;
101
+ }
102
+ if (!inForm || tag.closing)
103
+ continue;
104
+ const name = tag.attributes.get('name');
105
+ const value = tag.name === 'input' ? (tag.attributes.get('value')?.trim() ?? '') : '';
106
+ if (execution === undefined && (name === 'execution' || id === 'execution'))
107
+ execution = value;
108
+ if (salt === undefined && (id === 'pwdEncryptSalt' || name === 'pwdEncryptSalt'))
109
+ salt = value;
110
+ }
111
+ return { action, execution: execution ?? '', salt: salt ?? '' };
112
+ }
113
+ export function errorText(source, matches) {
114
+ const html = visible(source);
115
+ const parts = [];
116
+ let open;
117
+ let last = 0;
118
+ for (const tag of tags(html)) {
119
+ if (open) {
120
+ if (tag.name === open.name)
121
+ open.depth += tag.closing ? -1 : 1;
122
+ parts.push(html.slice(last, tag.start));
123
+ last = tag.end;
124
+ if (open.depth === 0)
125
+ open = undefined;
126
+ }
127
+ else if (!tag.closing && !VOID.has(tag.name) && matches(tag)) {
128
+ open = { name: tag.name, depth: 1 };
129
+ last = tag.end;
130
+ }
131
+ }
132
+ if (open)
133
+ parts.push(html.slice(last));
134
+ return decode(parts.join(''));
135
+ }
136
+ export function hasId(id) {
137
+ return (tag) => tag.attributes.get('id') === id;
138
+ }
139
+ export function hasClass(name) {
140
+ return (tag) => (tag.attributes.get('class') ?? '').split(/[\t\n\f\r ]+/).includes(name);
141
+ }
@@ -1,6 +1,6 @@
1
1
  import { createCipheriv, randomFillSync } from 'node:crypto';
2
- import { load } from 'cheerio';
3
2
  import { AuthError } from './errors.js';
3
+ import { errorText, hasClass, hasId, readLoginForm } from './login-page.js';
4
4
  import { JWXT_HOST, cookieSessionFromSerialized, createCampusCookieSession, } from './cookie-transport.js';
5
5
  const WEBVPN_ENTRY = new URL('https://webvpn.nbt.edu.cn/');
6
6
  const SSO_ENTRY = new URL(`https://${JWXT_HOST}/sso/jziotlogin`);
@@ -49,12 +49,8 @@ export function encryptCampusPassword(password, salt, source = secureRandomBytes
49
49
  }
50
50
  }
51
51
  function parseLoginForm(html, responseUrl) {
52
- const $ = load(html);
53
- const form = $('#pwdFromId');
54
- const execution = String(form.find('input[name="execution"], #execution').first().val() ?? '').trim();
55
- const salt = String(form.find('#pwdEncryptSalt, input[name="pwdEncryptSalt"]').first().val() ?? '').trim();
56
- const actionValue = form.attr('action');
57
- if (form.length === 0 || !execution || !salt || !actionValue) {
52
+ const { action: actionValue, execution, salt } = readLoginForm(html);
53
+ if (!execution || !salt || !actionValue) {
58
54
  throw new AuthError('LOGIN_PAGE_CHANGED', 'login-page', 'The campus login page changed unexpectedly.');
59
55
  }
60
56
  let current;
@@ -75,12 +71,11 @@ function hasLoginFingerprint(html) {
75
71
  return /(?:id=["']pwdFromId["']|id=["']pwdEncryptSalt["']|name=["']execution["'])/i.test(html);
76
72
  }
77
73
  function classifyRejectedLogin(html) {
78
- const $ = load(html);
79
74
  const visibleError = [
80
- $('#showErrorTip').text(),
81
- $('#showWarnTip').text(),
82
- $('#errorMsg').text(),
83
- $('.alert-danger').text(),
75
+ errorText(html, hasId('showErrorTip')),
76
+ errorText(html, hasId('showWarnTip')),
77
+ errorText(html, hasId('errorMsg')),
78
+ errorText(html, hasClass('alert-danger')),
84
79
  ]
85
80
  .join(' ')
86
81
  .replace(/\s+/g, ' ')
@@ -155,17 +150,17 @@ function createAuthenticatedSession(cookies, metadata) {
155
150
  return {
156
151
  accountHint: metadata.accountHint,
157
152
  timetableTransport: (url, init) => cookies.timetableTransport(url, init),
158
- async snapshot(validatedAt = new Date()) {
153
+ snapshot(validatedAt = new Date()) {
159
154
  const validatedAtText = validatedAt.toISOString();
160
- return {
155
+ return Promise.resolve({
161
156
  version: 1,
162
157
  provider: 'nbt-webvpn',
163
- jar: await cookies.serialize(),
158
+ jar: cookies.serialize(),
164
159
  ...(metadata.accountHint === undefined ? {} : { accountHint: metadata.accountHint }),
165
160
  authenticatedAt: metadata.authenticatedAt,
166
161
  validatedAt: validatedAtText,
167
162
  expiresAt: new Date(validatedAt.getTime() + SESSION_MAX_AGE_MS).toISOString(),
168
- };
163
+ });
169
164
  },
170
165
  close: () => cookies.close(),
171
166
  };
@@ -255,10 +250,11 @@ export async function loginWithStudentPassword(username, password, options = {})
255
250
  });
256
251
  }
257
252
  }
258
- export async function restoreNbtSession(persisted, options = {}) {
259
- const cookies = await cookieSessionFromSerialized(persisted.jar, options);
260
- return createAuthenticatedSession(cookies, {
261
- ...(persisted.accountHint === undefined ? {} : { accountHint: persisted.accountHint }),
262
- authenticatedAt: persisted.authenticatedAt,
253
+ export function restoreNbtSession(persisted, options = {}) {
254
+ return new Promise((resolve) => {
255
+ resolve(createAuthenticatedSession(cookieSessionFromSerialized(persisted.jar, options), {
256
+ ...(persisted.accountHint === undefined ? {} : { accountHint: persisted.accountHint }),
257
+ authenticatedAt: persisted.authenticatedAt,
258
+ }));
263
259
  });
264
260
  }
@@ -1,5 +1,6 @@
1
1
  import { glyph, type, space } from '../theme.js';
2
- import { visualWidth, padEndV, wrapAnsiToVisualWidth } from '../text.js';
2
+ import { visualWidth, padEndV, wrapAnsiToVisualWidth, clipAnsiToVisualWidth } from '../text.js';
3
+ import { pickIcon } from '../icons.js';
3
4
  import { createPainter } from './painter.js';
4
5
  import { startRawInput } from './input-session.js';
5
6
  import { t } from '../../i18n/index.js';
@@ -60,6 +61,12 @@ export function nextIndex(current, key, len, pageSize = 5) {
60
61
  return current;
61
62
  }
62
63
  }
64
+ export function menuColumns(options) {
65
+ return options.reduce((widths, option) => ({
66
+ label: Math.max(widths.label, visualWidth(option.label)),
67
+ hint: Math.max(widths.hint, option.hint ? visualWidth(option.hint) : 0),
68
+ }), { label: 0, hint: 0 });
69
+ }
63
70
  function normalizedWidth(cols) {
64
71
  return Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : Number.POSITIVE_INFINITY;
65
72
  }
@@ -69,7 +76,36 @@ function renderIndentedText(label, cols, style) {
69
76
  const contentWidth = Math.max(1, width - visualWidth(indent));
70
77
  return wrapAnsiToVisualWidth(style(label), contentWidth).map((line) => `${indent}${line}`);
71
78
  }
72
- export function renderMenuOption(option, selected, labelWidth = visualWidth(option.label), cols = Number.POSITIVE_INFINITY) {
79
+ const MIN_LABEL_COLUMN = 24;
80
+ function clipWithEllipsis(value, width) {
81
+ if (visualWidth(value) <= width)
82
+ return value;
83
+ const ellipsis = pickIcon('…', '~');
84
+ return clipAnsiToVisualWidth(value, width - visualWidth(ellipsis)) + ellipsis;
85
+ }
86
+ function fitColumns(columns, contentWidth) {
87
+ if (columns.label + 2 + columns.hint <= contentWidth)
88
+ return columns;
89
+ const hint = Math.min(columns.hint, Math.max(contentWidth - 2 - columns.label, Math.ceil(contentWidth / 3)));
90
+ const label = Math.min(columns.label, contentWidth - 2 - hint);
91
+ return label >= MIN_LABEL_COLUMN ? { label, hint } : undefined;
92
+ }
93
+ function optionCells(option, columns, contentWidth) {
94
+ const hint = option.hint ?? '';
95
+ if (option.hintColumn) {
96
+ const fitted = fitColumns(columns, contentWidth);
97
+ return fitted
98
+ ? {
99
+ label: padEndV(clipWithEllipsis(option.label, fitted.label), fitted.label),
100
+ hint: clipWithEllipsis(hint, fitted.hint),
101
+ }
102
+ : { label: option.label, hint: '' };
103
+ }
104
+ const hintWidth = hint ? 2 + visualWidth(hint) : 0;
105
+ const labelWidth = columns.label + hintWidth <= contentWidth ? columns.label : visualWidth(option.label);
106
+ return { label: padEndV(option.label, labelWidth), hint };
107
+ }
108
+ export function renderMenuOption(option, selected, columns = menuColumns([option]), cols = Number.POSITIVE_INFINITY) {
73
109
  const width = normalizedWidth(cols);
74
110
  const cursor = glyph.cursor();
75
111
  const gap = ' '.repeat(visualWidth(cursor));
@@ -78,18 +114,17 @@ export function renderMenuOption(option, selected, labelWidth = visualWidth(opti
78
114
  const prefix = prefixes.find((candidate) => visualWidth(candidate) < width) ?? '';
79
115
  const continuation = ' '.repeat(visualWidth(prefix));
80
116
  const contentWidth = Math.max(1, width - visualWidth(prefix));
81
- const hintWidth = option.hint ? 2 + visualWidth(option.hint) : 0;
82
- const paddedWidth = labelWidth + hintWidth <= contentWidth ? labelWidth : visualWidth(option.label);
83
- const padded = padEndV(option.label, paddedWidth);
84
- const label = selected ? type.active(padded) : type.body(padded);
85
- const hint = option.hint ? ` ${type.hint(option.hint)}` : '';
117
+ const cells = optionCells(option, columns, contentWidth);
118
+ const style = selected ? type.active : option.dim ? type.hint : type.body;
119
+ const hint = cells.hint ? ` ${type.hint(cells.hint)}` : '';
120
+ const label = style(cells.label);
86
121
  return wrapAnsiToVisualWidth(`${label}${hint}`, contentWidth).map((line, index) => `${index === 0 ? prefix : continuation}${line}`);
87
122
  }
88
123
  export function renderMenu(state, cols = Number.POSITIVE_INFINITY) {
89
- const labelWidth = state.options.reduce((width, option) => Math.max(width, visualWidth(option.label)), 0);
124
+ const columns = menuColumns(state.options);
90
125
  const lines = state.title ? [...renderIndentedText(state.title, cols, type.heading), ''] : [];
91
126
  state.options.forEach((option, index) => {
92
- lines.push(...renderMenuOption(option, index === state.selectedIndex, labelWidth, cols));
127
+ lines.push(...renderMenuOption(option, index === state.selectedIndex, columns, cols));
93
128
  });
94
129
  if (state.footer) {
95
130
  lines.push('');
package/dist/core/logo.js CHANGED
@@ -29,15 +29,7 @@ function dotmatrixFile() {
29
29
  return tier?.file ?? 'ca-dotmatrix-small.txt';
30
30
  }
31
31
  function paint(text, color) {
32
- if (!color)
33
- return text;
34
- const fn = brand;
35
- return typeof fn.multiline === 'function'
36
- ? fn.multiline(text)
37
- : text
38
- .split('\n')
39
- .map((line) => brand(line))
40
- .join('\n');
32
+ return color ? brand(text) : text;
41
33
  }
42
34
  function loadArt() {
43
35
  const art = useUnicodeIcons() ? readArt(dotmatrixFile()) : readArt('ascii-logo.txt');
@@ -61,6 +53,31 @@ export function buildLogoLines() {
61
53
  '',
62
54
  ];
63
55
  }
56
+ function skipOnKeypress() {
57
+ const controller = new AbortController();
58
+ const stdin = process.stdin;
59
+ if (!stdin.isTTY)
60
+ return { signal: controller.signal, release: () => undefined };
61
+ const onData = (chunk) => {
62
+ // Raw mode swallows SIGINT, so Ctrl+C has to exit by hand.
63
+ if (chunk.includes(0x03)) {
64
+ stdin.setRawMode(false);
65
+ process.exit(130);
66
+ }
67
+ controller.abort();
68
+ };
69
+ stdin.setRawMode(true);
70
+ stdin.on('data', onData);
71
+ stdin.resume();
72
+ return {
73
+ signal: controller.signal,
74
+ release() {
75
+ stdin.off('data', onData);
76
+ stdin.setRawMode(false);
77
+ stdin.pause();
78
+ },
79
+ };
80
+ }
64
81
  export async function runStartup() {
65
82
  if (!process.stdout.isTTY)
66
83
  return;
@@ -68,14 +85,16 @@ export async function runStartup() {
68
85
  if (!startupFitsTerminal(process.stdout.rows, process.stdout.columns, art))
69
86
  return;
70
87
  const color = !process.env['NO_COLOR'];
88
+ const skip = skipOnKeypress();
71
89
  process.stdout.write('\n');
72
- await materializeBraille(art, (s) => paint(s, color), {
73
- paintProgress: (s) => (color ? c.brand(s) : s),
74
- });
75
- await typeReveal([
76
- '',
77
- color ? brand(TAGLINE) : TAGLINE,
78
- chalk.dim(`@nbtca/prompt v${APP_INFO.version}`),
79
- '',
80
- ]);
90
+ try {
91
+ await materializeBraille(art, (s) => paint(s, color), {
92
+ paintProgress: (s) => (color ? c.brand(s) : s),
93
+ signal: skip.signal,
94
+ });
95
+ await typeReveal(['', color ? brand(TAGLINE) : TAGLINE, chalk.dim(`@nbtca/prompt v${APP_INFO.version}`), ''], { signal: skip.signal });
96
+ }
97
+ finally {
98
+ skip.release();
99
+ }
81
100
  }
@@ -1,8 +1,20 @@
1
1
  import { getCapabilities } from './capabilities.js';
2
2
  import { ansi } from './canvas.js';
3
3
  const GRAPHEME_SEGMENTER = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
4
- export function sleep(ms) {
5
- return new Promise((resolve) => setTimeout(resolve, ms));
4
+ export function sleep(ms, signal) {
5
+ return new Promise((resolve) => {
6
+ if (signal?.aborted) {
7
+ resolve();
8
+ return;
9
+ }
10
+ const timer = setTimeout(done, ms);
11
+ signal?.addEventListener('abort', done, { once: true });
12
+ function done() {
13
+ clearTimeout(timer);
14
+ signal?.removeEventListener('abort', done);
15
+ resolve();
16
+ }
17
+ });
6
18
  }
7
19
  export async function typeReveal(lines, opts = {}) {
8
20
  const write = opts.write ??
@@ -15,9 +27,13 @@ export async function typeReveal(lines, opts = {}) {
15
27
  return;
16
28
  }
17
29
  const stepMs = opts.stepMs ?? 45;
18
- for (const line of lines) {
30
+ for (const [index, line] of lines.entries()) {
31
+ if (opts.signal?.aborted) {
32
+ write(lines.slice(index).join('\n') + '\n');
33
+ return;
34
+ }
19
35
  write(line + '\n');
20
- await sleep(stepMs);
36
+ await sleep(stepMs, opts.signal);
21
37
  }
22
38
  }
23
39
  const BRAILLE_BASE = 0x2800;
@@ -72,6 +88,8 @@ export async function materializeBraille(art, paint, opts = {}) {
72
88
  const frameMs = opts.frameMs ?? 35;
73
89
  let shown = 0;
74
90
  for (let f = 1; f <= frameCount; f++) {
91
+ if (opts.signal?.aborted)
92
+ f = frameCount;
75
93
  const target = Math.round((dots.length * f) / frameCount);
76
94
  while (shown < target) {
77
95
  const d = dots[shown];
@@ -86,7 +104,7 @@ export async function materializeBraille(art, paint, opts = {}) {
86
104
  const painter = f === frameCount ? paint : (opts.paintProgress ?? paint);
87
105
  write(painter(renderFrame()) + '\n');
88
106
  if (f < frameCount) {
89
- await sleep(frameMs);
107
+ await sleep(frameMs, opts.signal);
90
108
  write(ansi.cursorUp(lines.length) + ansi.cursorToCol0 + ansi.eraseDown);
91
109
  }
92
110
  }
package/dist/core/text.js CHANGED
@@ -69,12 +69,12 @@ export function padEndV(str, width) {
69
69
  const pad = width - visualWidth(str);
70
70
  return pad > 0 ? str + ' '.repeat(pad) : str;
71
71
  }
72
- export function truncate(str, maxWidth) {
72
+ export function truncate(str, maxWidth, ellipsis = '...') {
73
73
  if (visualWidth(str) <= maxWidth)
74
74
  return str;
75
75
  if (maxWidth <= 0)
76
76
  return '';
77
- const marker = maxWidth >= 3 ? '...' : '.'.repeat(maxWidth);
77
+ const marker = visualWidth(ellipsis) <= maxWidth ? ellipsis : '.'.repeat(maxWidth);
78
78
  const available = maxWidth - visualWidth(marker);
79
79
  let w = 0;
80
80
  let value = '';
@@ -240,6 +240,9 @@ function applyKinsoku(tokens, start, end) {
240
240
  }
241
241
  return end;
242
242
  }
243
+ function isWideBoundary(tokens, index) {
244
+ return ((visibleAt(tokens, index)?.width ?? 0) > 1 || (visibleAt(tokens, index - 1)?.width ?? 0) > 1);
245
+ }
243
246
  export function wrapAnsiToVisualWidth(str, maxWidth, continuationWidth = maxWidth) {
244
247
  const widthLimit = Math.max(1, Math.floor(maxWidth));
245
248
  const nextLimit = Math.max(1, Math.floor(continuationWidth));
@@ -254,6 +257,8 @@ export function wrapAnsiToVisualWidth(str, maxWidth, continuationWidth = maxWidt
254
257
  let width = 0;
255
258
  let hasVisible = false;
256
259
  let lastWhitespace = -1;
260
+ let lastWideBoundary = -1;
261
+ let previousWide = false;
257
262
  let index = start;
258
263
  while (index < tokens.length) {
259
264
  const token = tokens[index];
@@ -263,11 +268,15 @@ export function wrapAnsiToVisualWidth(str, maxWidth, continuationWidth = maxWidt
263
268
  index += 1;
264
269
  continue;
265
270
  }
271
+ const wide = token.width > 1;
272
+ if (hasVisible && (wide || previousWide) && !token.whitespace)
273
+ lastWideBoundary = index;
266
274
  const limit = lines.length === 0 ? widthLimit : nextLimit;
267
275
  if (width + token.width > limit && hasVisible)
268
276
  break;
269
277
  width += token.width;
270
278
  hasVisible = true;
279
+ previousWide = wide;
271
280
  if (token.whitespace)
272
281
  lastWhitespace = index;
273
282
  index += 1;
@@ -279,9 +288,14 @@ export function wrapAnsiToVisualWidth(str, maxWidth, continuationWidth = maxWidt
279
288
  const overflow = tokens[index];
280
289
  let end = index;
281
290
  let next = index;
291
+ const wideBreak = lastWideBoundary > lastWhitespace + 1 ? applyKinsoku(tokens, start, lastWideBoundary) : -1;
282
292
  if (overflow?.whitespace) {
283
293
  next = index + 1;
284
294
  }
295
+ else if (wideBreak > lastWhitespace + 1 && isWideBoundary(tokens, wideBreak)) {
296
+ end = wideBreak;
297
+ next = wideBreak;
298
+ }
285
299
  else if (lastWhitespace >= start) {
286
300
  end = lastWhitespace;
287
301
  next = lastWhitespace + 1;
@@ -302,18 +316,6 @@ export function wrapAnsiToVisualWidth(str, maxWidth, continuationWidth = maxWidt
302
316
  }
303
317
  return lines.length > 0 ? lines : [''];
304
318
  }
305
- const LEADING_MARKER = /^(\s*)((?:[-*+•]|\d{1,3}[.)])\s+)?/u;
306
- export function wrapAnsiHanging(str, maxWidth) {
307
- const width = Number.isFinite(maxWidth)
308
- ? Math.max(1, Math.floor(maxWidth))
309
- : Number.POSITIVE_INFINITY;
310
- const match = LEADING_MARKER.exec(stripAnsi(str));
311
- const hang = visualWidth((match?.[1] ?? '') + (match?.[2] ?? ''));
312
- if (hang === 0 || hang >= width)
313
- return wrapAnsiToVisualWidth(str, width);
314
- const continuation = ' '.repeat(hang);
315
- return wrapAnsiToVisualWidth(str, width, width - hang).map((line, index) => index === 0 ? line : continuation + line);
316
- }
317
319
  export function wrapAnsiWithIndent(str, maxWidth, preferredIndent = '') {
318
320
  const width = Number.isFinite(maxWidth)
319
321
  ? Math.max(1, Math.floor(maxWidth))