@nbtca/prompt 1.5.16 → 1.5.17

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,5 @@
1
- import chalk from 'chalk';
2
1
  import { pickIcon } from '../core/icons.js';
3
- import { space, type } from '../core/theme.js';
2
+ import { c, space, type } from '../core/theme.js';
4
3
  import { t, getCurrentLanguage } from '../i18n/index.js';
5
4
  import { visualWidth } from '../core/text.js';
6
5
  function parseBucketDate(date) {
@@ -13,25 +12,39 @@ function parseBucketDate(date) {
13
12
  function utcDayToMonIndex(utcDay) {
14
13
  return (utcDay + 6) % 7;
15
14
  }
16
- function countToGlyph(count) {
17
- if (count <= 0)
18
- return pickIcon('·', ' ');
19
- if (count === 1)
20
- return pickIcon('░', '.');
21
- if (count === 2)
22
- return pickIcon('▒', ':');
23
- if (count === 3)
24
- return pickIcon('▓', '-');
25
- return pickIcon('█', '=');
26
- }
27
- const HEATMAP_RAMP = ['#1b4332', '#2d6a4f', '#40916c', '#52b788'];
15
+ const LEVEL_GLYPHS = [
16
+ ['·', ' '],
17
+ ['░', '.'],
18
+ ['▒', ':'],
19
+ ['▓', '-'],
20
+ ['█', '='],
21
+ ];
28
22
  const MAX_WEEK_COLUMNS = 53;
29
23
  const GRID_PREFIX_WIDTH = 6;
30
- function applyColor(glyph, count, useColor) {
31
- if (!useColor || count <= 0)
32
- return glyph;
33
- const level = Math.min(count, HEATMAP_RAMP.length) - 1;
34
- return chalk.hex(HEATMAP_RAMP[level])(glyph);
24
+ function levelCell(count, useColor) {
25
+ const level = Math.max(0, Math.min(count, LEVEL_GLYPHS.length - 1));
26
+ const [unicode, ascii] = LEVEL_GLYPHS[level] ?? LEVEL_GLYPHS[0];
27
+ const cell = pickIcon(unicode, ascii);
28
+ if (!useColor)
29
+ return cell;
30
+ return level === 0 ? type.hint(cell) : c.success(cell);
31
+ }
32
+ function placeMonthLabels(anchors, width, format, strict) {
33
+ let line = '';
34
+ for (const [index, anchor] of anchors.entries()) {
35
+ const label = format(anchor.date);
36
+ const end = anchor.start + visualWidth(label);
37
+ const used = visualWidth(line);
38
+ const gap = index === 0 ? 2 : 1;
39
+ const limit = (anchors[index + 1]?.start ?? width + gap) - gap;
40
+ if (anchor.start >= used + (used > 0 ? 1 : 0) && end <= limit) {
41
+ line += ' '.repeat(anchor.start - used) + label;
42
+ }
43
+ else if (strict && index > 0) {
44
+ return undefined;
45
+ }
46
+ }
47
+ return line;
35
48
  }
36
49
  export function renderHeatmap(buckets, today, options) {
37
50
  const useColor = options?.color === true;
@@ -78,30 +91,23 @@ export function renderHeatmap(buckets, today, options) {
78
91
  timeZone: 'UTC',
79
92
  });
80
93
  const cellsWidth = numCols * cellWidth;
81
- let monthLine = '';
94
+ const anchors = [];
82
95
  let prevMonth = -1;
83
- for (let col = 0; col < numCols; col++) {
84
- let labelDate = null;
85
- for (let row = 0; row < 7; row++) {
86
- const cell = columns[col]?.[row];
87
- if (cell !== null && cell !== undefined) {
88
- labelDate = parseBucketDate(cell.date);
89
- break;
90
- }
91
- }
92
- if (labelDate === null)
96
+ for (const [col, column] of columns.entries()) {
97
+ const cell = column.find((candidate) => candidate !== null);
98
+ if (!cell)
93
99
  continue;
94
- const month = labelDate.getUTCMonth();
95
- if (month !== prevMonth) {
96
- prevMonth = month;
97
- const label = monthFmt.format(labelDate);
98
- const start = col * cellWidth;
99
- const used = visualWidth(monthLine);
100
- if (start >= used + (used > 0 ? 1 : 0) && start + visualWidth(label) <= cellsWidth) {
101
- monthLine += ' '.repeat(start - used) + label;
102
- }
103
- }
100
+ const date = parseBucketDate(cell.date);
101
+ if (date.getUTCMonth() === prevMonth)
102
+ continue;
103
+ prevMonth = date.getUTCMonth();
104
+ anchors.push({ start: col * cellWidth, date });
104
105
  }
106
+ const monthNumber = (date) => String(date.getUTCMonth() + 1);
107
+ const monthLine = placeMonthLabels(anchors, cellsWidth, (date) => monthFmt.format(date), true) ??
108
+ placeMonthLabels(anchors, cellsWidth, monthNumber, true) ??
109
+ placeMonthLabels(anchors, cellsWidth, monthNumber, false) ??
110
+ '';
105
111
  const monthLabelLine = space.indent + weekdayLabel + monthLine;
106
112
  const weekdayNames = [
107
113
  trans.timetable.weekdayMon.slice(0, 2),
@@ -122,28 +128,12 @@ export function renderHeatmap(buckets, today, options) {
122
128
  const cell = col[row];
123
129
  if (cell === null || cell === undefined)
124
130
  return ' ';
125
- const glyph = countToGlyph(cell.count);
126
- return applyColor(glyph, cell.count, useColor);
131
+ return levelCell(cell.count, useColor);
127
132
  });
128
133
  lines.push(`${space.indent}${wdLabel} ${cells.join(cellWidth === 2 ? ' ' : '')}`);
129
134
  }
130
- const legendGlyphs = [
131
- pickIcon('·', ' '),
132
- pickIcon('░', '.'),
133
- pickIcon('▒', ':'),
134
- pickIcon('▓', '-'),
135
- pickIcon('█', '='),
136
- ];
137
- const legendColored = useColor
138
- ? [
139
- legendGlyphs[0] ?? '·',
140
- applyColor(legendGlyphs[1] ?? '░', 1, true),
141
- applyColor(legendGlyphs[2] ?? '▒', 2, true),
142
- applyColor(legendGlyphs[3] ?? '▓', 3, true),
143
- applyColor(legendGlyphs[4] ?? '█', 4, true),
144
- ]
145
- : legendGlyphs;
135
+ const legend = LEVEL_GLYPHS.map((_, level) => levelCell(level, useColor)).join('');
146
136
  lines.push('');
147
- lines.push(`${space.indent}${type.hint(trans.calendar.heatmap.legendLess)} ${legendColored.join('')} ${type.hint(trans.calendar.heatmap.legendMore)}`);
137
+ lines.push(`${space.indent}${type.hint(trans.calendar.heatmap.legendLess)} ${legend} ${type.hint(trans.calendar.heatmap.legendMore)}`);
148
138
  return lines.join('\n');
149
139
  }
@@ -22,7 +22,7 @@ export function eventEnd(event) {
22
22
  ? new Date(event.start.getFullYear(), event.start.getMonth(), event.start.getDate() + 1)
23
23
  : event.start));
24
24
  }
25
- function hasEnded(event, now) {
25
+ export function hasEnded(event, now) {
26
26
  return event.start < now && eventEnd(event) <= now;
27
27
  }
28
28
  export function currentEvents(calendar, now) {
@@ -5,7 +5,7 @@ import { pickIcon } from '../core/icons.js';
5
5
  import { padEndV, sanitizeTerminalLine, sanitizeTerminalText, truncate, visualWidth, wrapAnsiWithIndent, wrapAnsiToVisualWidth, } from '../core/text.js';
6
6
  import { t } from '../i18n/index.js';
7
7
  import { localDayDifference } from '../core/calendar-day.js';
8
- import { countdownParts, isCountdownUrgent, buildExportFilename, formatDuration, pastYearRange, } from './calendar-query.js';
8
+ import { countdownParts, eventEnd, isCountdownUrgent, buildExportFilename, formatDuration, pastYearRange, } from './calendar-query.js';
9
9
  import { loadFeedCache, saveFeedCache, touchFeedCache } from './calendar-store.js';
10
10
  import { writeFileSync, existsSync } from 'fs';
11
11
  import { join } from 'path';
@@ -88,6 +88,22 @@ export function toDisplayEvent(e) {
88
88
  uid: e.uid,
89
89
  };
90
90
  }
91
+ export function eventTimeRange(e) {
92
+ const dash = pickIcon('–', '-');
93
+ const startDate = formatDate(e.start);
94
+ if (e.isAllDay) {
95
+ const lastDay = new Date(eventEnd(e).getTime() - 1);
96
+ const endDate = formatDate(lastDay);
97
+ return endDate === startDate ? startDate : `${startDate} ${dash} ${endDate}`;
98
+ }
99
+ const start = `${startDate} ${formatTime(e.start)}`;
100
+ if (!e.end || e.end <= e.start)
101
+ return start;
102
+ const endDate = formatDate(e.end);
103
+ return endDate === startDate
104
+ ? `${start}${dash}${formatTime(e.end)}`
105
+ : `${start} ${dash} ${endDate} ${formatTime(e.end)}`;
106
+ }
91
107
  export async function loadCalendarOrCache(signal) {
92
108
  try {
93
109
  return { calendar: await loadCalendarOrThrow(signal), stale: false };
@@ -222,7 +238,7 @@ export function renderCountdownBanner(event, now, cols = Number.POSITIVE_INFINIT
222
238
  const whenStyled = isCountdownUrgent(p) ? c.warn(when) : type.hint(when);
223
239
  const dot = pickIcon('·', '-');
224
240
  const content = `${type.label(trans.calendar.next)} ${dot} ${type.body(event.title)} ${dot} ${whenStyled}`;
225
- return hangingLines(type.active(glyph.cursor()), content, cols).join('\n');
241
+ return hangingLines(type.active(glyph.dot()), content, cols).join('\n');
226
242
  }
227
243
  export function exportEventIcs(event, dir = process.cwd()) {
228
244
  const base = buildExportFilename(event);
@@ -1,5 +1,6 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import { createDocsClient, parseDoc } from '@nbtca/docs';
3
+ import { URLS } from '../config/data.js';
3
4
  import { createDocsStore } from './docs-store.js';
4
5
  const contextKey = Symbol.for('@nbtca/prompt/docs-fetch-context/v2');
5
6
  const globalWithContext = globalThis;
@@ -160,7 +161,8 @@ function beginDocsFetch() {
160
161
  };
161
162
  }
162
163
  const store = createDocsStore();
163
- const defaultClient = createDocsClient({ store });
164
+ const options = { store, mirror: `${URLS.docs}/docs-api` };
165
+ const defaultClient = createDocsClient(options);
164
166
  const clientsBySignal = new WeakMap();
165
167
  const clients = new Set([defaultClient]);
166
168
  function clientFor(signal) {
@@ -169,7 +171,7 @@ function clientFor(signal) {
169
171
  const existing = clientsBySignal.get(signal);
170
172
  if (existing)
171
173
  return existing;
172
- const client = createDocsClient({ store });
174
+ const client = createDocsClient(options);
173
175
  clientsBySignal.set(signal, client);
174
176
  clients.add(client);
175
177
  signal.addEventListener('abort', () => {
@@ -26,38 +26,30 @@ const CJK_SOFT_BREAK = new RegExp(`(?<=${CJK})[ \\t]*\\n[ \\t]*(?=${CJK})`, 'gu'
26
26
  function joinSoftBreaks(text) {
27
27
  return text.replace(CJK_SOFT_BREAK, '').replace(/[ \t]*\n[ \t]*/g, ' ');
28
28
  }
29
- function renderInline(tokens, hrefs) {
30
- return (tokens ?? []).map((token) => renderInlineToken(token, hrefs)).join('');
29
+ function renderInline(tokens) {
30
+ return (tokens ?? []).map((token) => renderInlineToken(token)).join('');
31
31
  }
32
- function renderLink(token, hrefs) {
33
- const text = renderInline(token.tokens, hrefs);
34
- const bare = (href) => href.replace(/^(?:https?:\/\/|mailto:)/, '').replace(/\/$/, '');
35
- const selfLabelled = bare(stripAnsi(text)) === bare(token.href);
36
- if (isInternalHref(token.href) || token.href.startsWith('#') || selfLabelled) {
37
- return chalk.underline(c.accent(text));
38
- }
39
- return hrefs ? `${c.accent(text)} ${c.url(`(${token.href})`)}` : c.accent(text);
32
+ function renderLink(token) {
33
+ return chalk.underline(c.accent(renderInline(token.tokens)));
40
34
  }
41
- function renderInlineToken(token, hrefs) {
35
+ function renderInlineToken(token) {
42
36
  switch (token.type) {
43
37
  case 'text':
44
- return token.tokens
45
- ? renderInline(token.tokens, hrefs)
46
- : joinSoftBreaks(decodeEntities(token.text));
38
+ return token.tokens ? renderInline(token.tokens) : joinSoftBreaks(decodeEntities(token.text));
47
39
  case 'escape':
48
40
  return token.text;
49
41
  case 'strong':
50
- return chalk.bold(renderInline(token.tokens, hrefs));
42
+ return chalk.bold(renderInline(token.tokens));
51
43
  case 'em':
52
- return chalk.italic(renderInline(token.tokens, hrefs));
44
+ return chalk.italic(renderInline(token.tokens));
53
45
  case 'del':
54
- return chalk.strikethrough(c.muted(renderInline(token.tokens, hrefs)));
46
+ return chalk.strikethrough(c.muted(renderInline(token.tokens)));
55
47
  case 'codespan':
56
48
  return c.code(token.text);
57
49
  case 'br':
58
50
  return '\n';
59
51
  case 'link':
60
- return renderLink(token, hrefs);
52
+ return renderLink(token);
61
53
  case 'image':
62
54
  return `${pickIcon('🖼️', '[image]')} ${token.text || 'image'}`;
63
55
  case 'html':
@@ -94,7 +86,7 @@ function styleHeading(text, depth) {
94
86
  return chalk.bold(text);
95
87
  }
96
88
  function renderHeading(token, width) {
97
- const lines = wrap(styleHeading(renderInline(token.tokens, false), token.depth), width);
89
+ const lines = wrap(styleHeading(renderInline(token.tokens), token.depth), width);
98
90
  if (token.depth !== 2)
99
91
  return lines;
100
92
  const underline = Math.min(width, Math.max(...lines.map(visualWidth)));
@@ -173,8 +165,8 @@ function renderRecords(header, rows, width) {
173
165
  return lines;
174
166
  }
175
167
  function renderTable(token, width) {
176
- const header = token.header.map((cell) => renderInline(cell.tokens, false));
177
- const rows = token.rows.map((row) => row.map((cell) => renderInline(cell.tokens, false)));
168
+ const header = token.header.map((cell) => renderInline(cell.tokens));
169
+ const rows = token.rows.map((row) => row.map((cell) => renderInline(cell.tokens)));
178
170
  const natural = header.map((label, column) => Math.max(cellWidth(label), ...rows.map((row) => cellWidth(row[column] ?? ''))));
179
171
  const available = width - (3 * header.length + 1);
180
172
  const floor = natural.map((columnWidth) => Math.min(columnWidth, MIN_COLUMN));
@@ -216,9 +208,9 @@ function renderBlock(token, width, depth) {
216
208
  case 'heading':
217
209
  return renderHeading(token, width);
218
210
  case 'paragraph':
219
- return wrap(renderInline(token.tokens, true), width);
211
+ return wrap(renderInline(token.tokens), width);
220
212
  case 'text':
221
- return wrap(renderInlineToken(token, true), width);
213
+ return wrap(renderInlineToken(token), width);
222
214
  case 'code':
223
215
  return renderCode(token, width);
224
216
  case 'blockquote':
@@ -245,7 +237,7 @@ function renderBlock(token, width, depth) {
245
237
  case 'image':
246
238
  case 'link':
247
239
  case 'strong':
248
- return wrap(renderInlineToken(token, true), width);
240
+ return wrap(renderInlineToken(token), width);
249
241
  }
250
242
  }
251
243
  function renderBlocks(tokens, width, depth, tight) {
@@ -59,7 +59,7 @@ const RENDER_CACHE_MAX = 50;
59
59
  const renderCache = new Map();
60
60
  const METADATA_CACHE_TTL_MS = 10 * 60 * 1000;
61
61
  const METADATA_CACHE_MAX = 200;
62
- const METADATA_CONCURRENCY = 4;
62
+ const METADATA_CONCURRENCY = 6;
63
63
  const metadataCache = new Map();
64
64
  let cacheGeneration = 0;
65
65
  function getFreshRender(key) {
@@ -481,13 +481,16 @@ function hasMarkdownTable(content) {
481
481
  function hasMermaidBlock(content) {
482
482
  return /^```mermaid\b/m.test(content);
483
483
  }
484
- function extractInternalLinks(markdown) {
484
+ function isExternalHref(href) {
485
+ return /^https?:\/\//i.test(href);
486
+ }
487
+ function extractLinks(markdown) {
485
488
  const links = [];
486
- const re = /\[([^\]]+)\]\(([^)]+)\)/g;
489
+ const re = /\[([^\]]+)\]\(([^)\s]+)[^)]*\)/g;
487
490
  let m;
488
491
  while ((m = re.exec(markdown))) {
489
492
  const href = m[2] ?? '';
490
- if (isInternalHref(href))
493
+ if (isInternalHref(href) || isExternalHref(href))
491
494
  links.push({ text: m[1] ?? '', href });
492
495
  }
493
496
  return links;
@@ -521,12 +524,15 @@ export async function loadDocForReader(filePath, signal) {
521
524
  const { renderedDoc } = await loadRenderedDoc(filePath, signal);
522
525
  const seen = new Set();
523
526
  const links = [];
524
- for (const raw of extractInternalLinks(renderedDoc.cleaned)) {
525
- const resolved = resolveInternalHref(raw.href, filePath);
526
- if (seen.has(resolved))
527
+ for (const raw of extractLinks(renderedDoc.cleaned)) {
528
+ const external = isExternalHref(raw.href);
529
+ const href = external
530
+ ? sanitizeTerminalLine(raw.href)
531
+ : resolveInternalHref(raw.href, filePath);
532
+ if (seen.has(href))
527
533
  continue;
528
- seen.add(resolved);
529
- links.push({ text: sanitizeTerminalLine(raw.text), href: resolved });
534
+ seen.add(href);
535
+ links.push({ text: sanitizeTerminalLine(raw.text), href, ...(external ? { external } : {}) });
530
536
  }
531
537
  return {
532
538
  path: filePath,
@@ -562,11 +568,14 @@ function listedDoc(item, metadata) {
562
568
  return {
563
569
  ...item,
564
570
  name: sanitizeTerminalLine(item.name),
565
- title: displayDocTitle(item.name, metadata?.title),
571
+ title: metadata ? displayDocTitle(item.name, metadata.title) : '',
566
572
  summary: sanitizeTerminalLine(metadata?.summary ?? ''),
567
573
  };
568
574
  }
569
- export async function fetchDocMetadata(items, signal) {
575
+ export function withFileNameTitle(doc) {
576
+ return doc.title ? doc : { ...doc, title: displayDocTitle(doc.name) };
577
+ }
578
+ export async function fetchDocMetadata(items, signal, onDoc) {
570
579
  const results = items.map((item) => listedDoc(item));
571
580
  let nextIndex = 0;
572
581
  async function worker() {
@@ -589,8 +598,9 @@ export async function fetchDocMetadata(items, signal) {
589
598
  catch (error) {
590
599
  if (signal?.aborted)
591
600
  throw error;
592
- results[index] = listedDoc(item);
601
+ results[index] = withFileNameTitle(listedDoc(item));
593
602
  }
603
+ onDoc?.(index, results[index]);
594
604
  }
595
605
  }
596
606
  const workerCount = Math.min(METADATA_CONCURRENCY, items.length);
@@ -601,31 +611,44 @@ export function peekListedDocs(items) {
601
611
  let complete = true;
602
612
  const docs = items.map((item) => {
603
613
  const metadata = peekDocMetadata(item);
604
- if (metadata)
605
- return listedDoc(item, metadata);
606
- complete = false;
607
- return item;
614
+ if (!metadata)
615
+ complete = false;
616
+ return listedDoc(item, metadata);
608
617
  });
609
618
  return { docs, complete };
610
619
  }
611
- export async function fetchSectionMetadata(section, signal) {
612
- const files = await fetchDocMetadata(section.files, signal);
620
+ export async function fetchSectionMetadata(section, signal, onDoc) {
621
+ const files = await fetchDocMetadata(section.files, signal, onDoc);
613
622
  return { ...section, count: files.length, files };
614
623
  }
624
+ function withoutLeadingTitle(excerpt, title) {
625
+ const text = excerpt.trim();
626
+ return title && text.startsWith(title) ? text.slice(title.length).trimStart() : text;
627
+ }
615
628
  function searchDoc(result) {
629
+ const title = displayDocTitle(result.name, result.title);
616
630
  return {
617
631
  name: sanitizeTerminalLine(result.name),
618
632
  path: result.path,
619
633
  type: 'file',
620
- title: displayDocTitle(result.name, result.title),
634
+ title,
621
635
  summary: sanitizeTerminalLine(result.summary),
622
- excerpt: sanitizeTerminalLine(result.excerpt),
636
+ excerpt: withoutLeadingTitle(sanitizeTerminalLine(result.excerpt), title),
623
637
  route: result.route,
624
638
  score: result.score,
625
639
  section: result.section,
626
640
  };
627
641
  }
628
- export async function searchDocuments(query, signal) {
642
+ export async function searchDocuments(query, signal, onProgress) {
643
+ if (onProgress) {
644
+ const items = await fetchAllDocs(signal);
645
+ let done = 0;
646
+ onProgress(done, items.length);
647
+ await fetchDocMetadata(items, signal, () => {
648
+ done += 1;
649
+ onProgress(done, items.length);
650
+ });
651
+ }
629
652
  return (await runDocsClientOperation(signal, (client) => client.search(query, { limit: 20 }))).map(searchDoc);
630
653
  }
631
654
  export function buildSections(all) {