stream-announcer 0.1.0 → 0.1.6
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 +42 -0
- package/README.ko.md +5 -4
- package/README.md +13 -12
- package/dist/announcer.js +38 -2
- package/dist/markdown.d.ts +38 -0
- package/dist/markdown.js +251 -39
- package/dist/sentence-buffer.d.ts +7 -0
- package/dist/sentence-buffer.js +13 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,48 @@ All notable changes to this project are documented in this file.
|
|
|
4
4
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
5
5
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
6
|
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.1.6] - 2026-11-26
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
- Fenced code blocks and tables inside blockquotes (`> ```bash`, `> | a | b |`) are summarized instead of read aloud.
|
|
14
|
+
|
|
15
|
+
## [0.1.5] - 2026-11-26
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
|
|
19
|
+
- Test runner uses in-process threads with at most 2 workers and a longer teardown timeout, so the suite starts reliably on loaded machines. No change to the published package.
|
|
20
|
+
|
|
21
|
+
## [0.1.4] - 2026-11-25
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
|
|
25
|
+
- `MarkdownGuard` now recognizes a code fence indented under a list item (for example 4 spaces under `1. ` or 6 under a nested `- `), so the language name and code are no longer read aloud. Fences indented 4+ spaces outside a list are still not detected.
|
|
26
|
+
|
|
27
|
+
## [0.1.3] - 2026-11-14
|
|
28
|
+
|
|
29
|
+
### Fixed
|
|
30
|
+
|
|
31
|
+
- `MarkdownGuard` no longer counts a closing code fence without a trailing newline as a code line (a 1-line block was summarized as "2 lines").
|
|
32
|
+
|
|
33
|
+
## [0.1.2] - 2026-11-14
|
|
34
|
+
|
|
35
|
+
### Added
|
|
36
|
+
|
|
37
|
+
- `MarkdownGuard`: `releasePending()`, `holdsPossibleTable` and a `maxChars` option (default 200). `SentenceBuffer`: `nextLineStarted()`.
|
|
38
|
+
|
|
39
|
+
### Fixed
|
|
40
|
+
|
|
41
|
+
- `MarkdownGuard` now summarizes GFM tables written without a leading pipe (`a | b` then `--- | ---`).
|
|
42
|
+
|
|
43
|
+
## [0.1.1] - 2026-11-14
|
|
44
|
+
|
|
45
|
+
### Fixed
|
|
46
|
+
|
|
47
|
+
- `MarkdownGuard` now recognizes code fences and table rows in streams that use `\r\n` line endings (also when `\r` and `\n` arrive in separate chunks), so raw code is no longer announced.
|
|
48
|
+
|
|
7
49
|
## [0.1.0] - 2026-11-14
|
|
8
50
|
|
|
9
51
|
### Added
|
package/README.ko.md
CHANGED
|
@@ -137,8 +137,8 @@ flowchart LR
|
|
|
137
137
|
| `announcer.destroy()` | 타이머를 정리하고 자기가 만든 영역을 제거한다(공유 `region` 은 남기고 자기 대기 문구만 버린다). 이후 `destroy` 외 호출은 예외 | 없음 | `void` |
|
|
138
138
|
| `announcer.status` | `idle`, `generating`, `done`, `aborted`, `error` | 없음 | `AnnouncerStatus` |
|
|
139
139
|
| `createLiveRegion(options?)` | 화면에서 숨긴 `role="status"` 영역 하나를 만든다 | `document`, `politeness`(`polite`), `repeatDelayMs`(100), `spacingMs`(150) | `LiveRegion`(`element`, `announce`, `clear(owner?)`, `destroy`) |
|
|
140
|
-
| `SentenceBuffer` | 문장 분리기만 따로
|
|
141
|
-
| `MarkdownGuard` | 코드 펜스·표 감지기만 따로
|
|
140
|
+
| `SentenceBuffer` | 문장 분리기만 따로 쓴다. `nextLineStarted()` 는 호출 쪽이 새 줄을 보류하는 동안 줄바꿈으로 완성된 문장을 돌려준다 | `locale`, `minChars`, `maxChars`, `idleFlushMs`, `onIdle` | 클래스 |
|
|
141
|
+
| `MarkdownGuard` | 코드 펜스·표 감지기만 따로 쓴다. `holdsPossibleTable` 은 `\|` 가 나올지 몰라 텍스트를 보류하는 동안(앞 파이프 없는 표) true 이고, `releasePending()` 은 스트림이 조용해지면 그 텍스트를 내보낸다 | `messages`, `maxChars`(200) | 클래스 |
|
|
142
142
|
| `stripInlineMarkdown(text)` | `**`, `` ` ``, 링크 같은 기호를 없앤다 | `text: string` | `string` |
|
|
143
143
|
| `messages`, `pickLanguage(locale)`, `resolveMessages(locale, overrides)` | 내장 문구와 언어 선택 | `locale`, `overrides` | 문구 / `'en' \| 'ko'` |
|
|
144
144
|
|
|
@@ -350,6 +350,7 @@ npm run demo
|
|
|
350
350
|
- **개발 모드의 React StrictMode.** `useStreamAnnouncer` 는 announcer 를 생성·파기하는 쌍으로 다루므로 StrictMode 의 이중 마운트 뒤에도 영역은 정확히 하나입니다. 다만 `useAnnounceText` 를 처음부터 `submitted` 상태로 렌더하면, 개발 모드에서만 일어나는 이중 마운트 때문에 직접 만든 `sink` 로 시작 문구가 두 번 갑니다(영역은 여전히 하나). 보통 상태는 `idle` 이나 `ready` 로 시작하므로 영향이 없고, 프로덕션 빌드는 이중 마운트하지 않습니다.
|
|
351
351
|
- **문장 감지는 휴리스틱입니다.** `Intl.Segmenter` 는 약어(`Dr. Smith`)나 목록 번호(`1. First`) 뒤에서 끊을 수 있습니다. 짧은 조각은 합치고(`minChars`), 문장부호 없는 텍스트는 `idleFlushMs` 와 `maxChars` 로 내보냅니다.
|
|
352
352
|
- **들여쓰기 코드 블록은 감지하지 않습니다.** 펜스(```` ``` ```` 또는 `~~~`) 블록만 요약합니다.
|
|
353
|
+
- **앞 파이프 없는 표는 감지에 시간이 걸립니다.** `a | b` 다음에 `--- | ---` 가 오면 유효한 표이므로, `|` 가 든 줄(예: 인라인 코드 속 셸 파이프)은 줄이 끝날 때까지 보류됩니다. 그래서 그런 일반 줄은 한 줄 늦게 읽힙니다. 헤더와 구분선 사이에서 스트림이 `idleFlushMs` 이상 멈추면 헤더는 일반 텍스트로 읽힙니다. 첫 `|` 앞에서 문장이 이어지는 헤더(`Dr. Kim | Age`)는 표로 보지 않습니다.
|
|
353
354
|
- **`aria-busy` 는 힌트일 뿐입니다.** 낭독기마다 의미를 다르게 해석합니다.
|
|
354
355
|
- `useStreamAnnouncer` 의 옵션은 마운트 때 한 번만 읽습니다.
|
|
355
356
|
|
|
@@ -370,9 +371,9 @@ npm test
|
|
|
370
371
|
npm run build
|
|
371
372
|
```
|
|
372
373
|
|
|
373
|
-
`npm test` 는 jsdom 과 녹화된 청크로 9개 파일의 테스트
|
|
374
|
+
`npm test` 는 jsdom 과 녹화된 청크로 9개 파일의 테스트 148개를 실행합니다(소요 시간은 환경에 따라 다릅니다). 브라우저·키·네트워크가 필요 없습니다.
|
|
374
375
|
|
|
375
|
-

|
|
376
377
|
|
|
377
378
|
*테스트는 위에서 설명한 동작마다 낭독 순서를 단언합니다.*
|
|
378
379
|
|
package/README.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
# stream-announcer
|
|
2
2
|
|
|
3
|
-
**English** | [한국어](https://github.com/LeeGyeongPil/stream-announcer/blob/v0.1.
|
|
3
|
+
**English** | [한국어](https://github.com/LeeGyeongPil/stream-announcer/blob/v0.1.6/README.ko.md)
|
|
4
4
|
|
|
5
5
|
Screen reader announcements for streaming LLM chat. You feed it the text deltas of a streaming response; it tells screen reader users when generation started, reads finished sentences instead of half-written fragments, summarizes code blocks and tables, and says when the response is complete, stopped, or failed. A framework-neutral core, React hooks, and jsdom test helpers. TypeScript, no runtime dependencies.
|
|
6
6
|
|
|
7
|
-
 and what stream-announcer announces (right)](https://raw.githubusercontent.com/LeeGyeongPil/stream-announcer/v0.1.6/docs/images/demo-compare.png)
|
|
8
8
|
|
|
9
9
|
*The same recorded stream. Left: every chunk written straight to an `aria-live` element, including the raw code. Right: what stream-announcer announces (sentences, a code summary, one completion message).*
|
|
10
10
|
|
|
@@ -137,8 +137,8 @@ All of `stream-announcer`:
|
|
|
137
137
|
| `announcer.destroy()` | Clears timers and removes its own region (a shared `region` stays; only its own waiting texts are dropped); later calls other than `destroy` throw | none | `void` |
|
|
138
138
|
| `announcer.status` | `idle`, `generating`, `done`, `aborted`, `error` | none | `AnnouncerStatus` |
|
|
139
139
|
| `createLiveRegion(options?)` | Creates the single visually hidden `role="status"` region | `document`, `politeness` (`polite`), `repeatDelayMs` (100), `spacingMs` (150) | `LiveRegion` (`element`, `announce`, `clear(owner?)`, `destroy`) |
|
|
140
|
-
| `SentenceBuffer` | The sentence splitter on its own | `locale`, `minChars`, `maxChars`, `idleFlushMs`, `onIdle` | class |
|
|
141
|
-
| `MarkdownGuard` | The code-fence and table detector on its own | `messages` | class |
|
|
140
|
+
| `SentenceBuffer` | The sentence splitter on its own. `nextLineStarted()` returns the sentences a line break completes while the caller holds the new line back | `locale`, `minChars`, `maxChars`, `idleFlushMs`, `onIdle` | class |
|
|
141
|
+
| `MarkdownGuard` | The code-fence and table detector on its own. `holdsPossibleTable` is true while text waits for a possible `\|` (table without leading pipes); `releasePending()` lets that text go when the stream goes quiet | `messages`, `maxChars` (200) | class |
|
|
142
142
|
| `stripInlineMarkdown(text)` | Removes `**`, `` ` ``, links and similar marks | `text: string` | `string` |
|
|
143
143
|
| `messages`, `pickLanguage(locale)`, `resolveMessages(locale, overrides)` | Built-in texts and language choice | `locale`, `overrides` | texts / `'en' \| 'ko'` |
|
|
144
144
|
|
|
@@ -271,7 +271,7 @@ A screen reader would hear:
|
|
|
271
271
|
[complete] Response complete.
|
|
272
272
|
```
|
|
273
273
|
|
|
274
|
-

|
|
275
275
|
|
|
276
276
|
*The Node example prints the announcement order without a browser.*
|
|
277
277
|
|
|
@@ -283,7 +283,7 @@ error: --lang must be en or ko
|
|
|
283
283
|
exit code: 2
|
|
284
284
|
```
|
|
285
285
|
|
|
286
|
-

|
|
287
287
|
|
|
288
288
|
*An invalid language is rejected with exit code 2. The terminal merges the two streams, so the `exit code` line appears first in the image; the text block above shows the real order.*
|
|
289
289
|
|
|
@@ -307,15 +307,15 @@ Pick the mode, the recorded response and the speed, then press Replay. The left
|
|
|
307
307
|
|
|
308
308
|
The page can also start in a given state from the address: `?mode=on-complete|sentence|off`, `?fixture=en-basic|ko-basic|table`, `?speed=fast|slow`, `?lang=en|ko`, and `?autoplay=1` (replay once on load). Invalid values are ignored. For example `?mode=sentence&fixture=table&autoplay=1`.
|
|
309
309
|
|
|
310
|
-

|
|
311
311
|
|
|
312
312
|
*`on-complete` mode at slow speed (`?mode=on-complete&speed=slow&autoplay=1`): one start text, heartbeats during silence, and the body once at the end.*
|
|
313
313
|
|
|
314
|
-

|
|
315
315
|
|
|
316
316
|
*A table becomes a short summary (`?mode=sentence&fixture=table&autoplay=1`). Code blocks are summarized the same way, as in the first image; raw code is never announced.*
|
|
317
317
|
|
|
318
|
-

|
|
319
319
|
|
|
320
320
|
*The language menu and the other controls at the top of the demo page.*
|
|
321
321
|
|
|
@@ -352,6 +352,7 @@ What to listen for:
|
|
|
352
352
|
- **React StrictMode in development.** `useStreamAnnouncer` creates and destroys the announcer in pairs, so StrictMode's double mount leaves exactly one region. But if `useAnnounceText` is first rendered already with the status `submitted`, the development-only double mount sends the start text to a custom `sink` twice (still one region). Normally the status starts as `idle` or `ready`, which is not affected. Production builds do not double mount.
|
|
353
353
|
- **Sentence detection is heuristic.** `Intl.Segmenter` can cut after an abbreviation (`Dr. Smith`) or a list number (`1. First`). Short pieces (`minChars`) are merged, and text without punctuation is released by `idleFlushMs` and `maxChars`.
|
|
354
354
|
- **Indented code blocks are not detected**; only fenced blocks (```` ``` ```` or `~~~`) are summarized.
|
|
355
|
+
- **Tables without a leading pipe are detected with a delay.** Because `a | b` followed by `--- | ---` is a valid table, a line that contains `|` (a shell pipe in inline code, for example) is held until its line ends, so a normal line like that is spoken one line late. If the stream pauses for `idleFlushMs` or longer between the header and the separator line, the header is spoken as plain text. A header whose first sentence continues before the first `|` (`Dr. Kim | Age`) is not treated as a table.
|
|
355
356
|
- **`aria-busy` is only a hint.** Screen readers do not agree on what it means.
|
|
356
357
|
- Options of `useStreamAnnouncer` are read once at mount.
|
|
357
358
|
|
|
@@ -361,7 +362,7 @@ What to listen for:
|
|
|
361
362
|
|
|
362
363
|
## Versions
|
|
363
364
|
|
|
364
|
-
Follows [SemVer](https://semver.org/). While the version is 0.x, minor versions may change the API; changes are listed in [CHANGELOG.md](https://github.com/LeeGyeongPil/stream-announcer/blob/v0.1.
|
|
365
|
+
Follows [SemVer](https://semver.org/). While the version is 0.x, minor versions may change the API; changes are listed in [CHANGELOG.md](https://github.com/LeeGyeongPil/stream-announcer/blob/v0.1.6/CHANGELOG.md).
|
|
365
366
|
|
|
366
367
|
## Development
|
|
367
368
|
|
|
@@ -372,9 +373,9 @@ npm test
|
|
|
372
373
|
npm run build
|
|
373
374
|
```
|
|
374
375
|
|
|
375
|
-
`npm test` runs
|
|
376
|
+
`npm test` runs 148 tests in 9 files (the time varies by machine) with jsdom and recorded chunks; no browser, key or network is needed.
|
|
376
377
|
|
|
377
|
-

|
|
378
379
|
|
|
379
380
|
*The test suite asserts the announcement order for each behavior described above.*
|
|
380
381
|
|
package/dist/announcer.js
CHANGED
|
@@ -45,11 +45,35 @@ export function createStreamAnnouncer(options = {}) {
|
|
|
45
45
|
}
|
|
46
46
|
let status = 'idle';
|
|
47
47
|
let destroyed = false;
|
|
48
|
-
let guard =
|
|
48
|
+
let guard = newGuard();
|
|
49
49
|
let buffer = newBuffer();
|
|
50
50
|
let body = [];
|
|
51
51
|
let heartbeat = null;
|
|
52
52
|
let inReasoning = false;
|
|
53
|
+
// While the guard holds a line that may still become a table, this timer replaces the buffer's
|
|
54
|
+
// idle timer: when the stream goes quiet, the held line is released and read (sentence mode).
|
|
55
|
+
let guardIdle = null;
|
|
56
|
+
function stopGuardIdle() {
|
|
57
|
+
if (guardIdle !== null)
|
|
58
|
+
clearTimeout(guardIdle);
|
|
59
|
+
guardIdle = null;
|
|
60
|
+
}
|
|
61
|
+
function armGuardIdle() {
|
|
62
|
+
stopGuardIdle();
|
|
63
|
+
const ms = options.idleFlushMs ?? 1500;
|
|
64
|
+
if (mode !== 'sentence' || ms <= 0)
|
|
65
|
+
return;
|
|
66
|
+
guardIdle = setTimeout(() => {
|
|
67
|
+
guardIdle = null;
|
|
68
|
+
if (status !== 'generating')
|
|
69
|
+
return;
|
|
70
|
+
handle(guard.releasePending());
|
|
71
|
+
buffer.flush().forEach(addSentence);
|
|
72
|
+
}, ms);
|
|
73
|
+
}
|
|
74
|
+
function newGuard() {
|
|
75
|
+
return new MarkdownGuard({ messages, ...(options.maxChars !== undefined ? { maxChars: options.maxChars } : {}) });
|
|
76
|
+
}
|
|
53
77
|
function newBuffer() {
|
|
54
78
|
return new SentenceBuffer({
|
|
55
79
|
locale,
|
|
@@ -116,10 +140,11 @@ export function createStreamAnnouncer(options = {}) {
|
|
|
116
140
|
}
|
|
117
141
|
function reset() {
|
|
118
142
|
stopHeartbeat();
|
|
143
|
+
stopGuardIdle();
|
|
119
144
|
buffer.cancel();
|
|
120
145
|
// The previous response (finished or not) must not be read after the new one starts.
|
|
121
146
|
dropWaiting();
|
|
122
|
-
guard =
|
|
147
|
+
guard = newGuard();
|
|
123
148
|
buffer = newBuffer();
|
|
124
149
|
body = [];
|
|
125
150
|
inReasoning = false;
|
|
@@ -127,6 +152,7 @@ export function createStreamAnnouncer(options = {}) {
|
|
|
127
152
|
function finish(next, text, kind) {
|
|
128
153
|
status = next;
|
|
129
154
|
stopHeartbeat();
|
|
155
|
+
stopGuardIdle();
|
|
130
156
|
buffer.cancel();
|
|
131
157
|
setBusy(false);
|
|
132
158
|
// done() lets queued sentences finish before the completion; abort()/error() drop them,
|
|
@@ -159,6 +185,15 @@ export function createStreamAnnouncer(options = {}) {
|
|
|
159
185
|
return;
|
|
160
186
|
inReasoning = false;
|
|
161
187
|
handle(guard.push(delta));
|
|
188
|
+
if (guard.holdsPossibleTable) {
|
|
189
|
+
// The held line would have reached the buffer without the table check: the line before it
|
|
190
|
+
// is complete now, and the guard's idle timer takes over until the line is released.
|
|
191
|
+
buffer.nextLineStarted().forEach(addSentence);
|
|
192
|
+
armGuardIdle();
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
stopGuardIdle();
|
|
196
|
+
}
|
|
162
197
|
},
|
|
163
198
|
event(event) {
|
|
164
199
|
assertAlive();
|
|
@@ -202,6 +237,7 @@ export function createStreamAnnouncer(options = {}) {
|
|
|
202
237
|
if (destroyed)
|
|
203
238
|
return;
|
|
204
239
|
stopHeartbeat();
|
|
240
|
+
stopGuardIdle();
|
|
205
241
|
buffer.cancel();
|
|
206
242
|
setBusy(false);
|
|
207
243
|
if (ownRegion)
|
package/dist/markdown.d.ts
CHANGED
|
@@ -6,6 +6,8 @@ export declare function stripInlineMarkdown(text: string): string;
|
|
|
6
6
|
* Splits a Markdown stream into prose and summaries.
|
|
7
7
|
* Fenced code and tables are never released as text; each becomes one short summary.
|
|
8
8
|
* Detection works line by line, so a fence or table may be split across chunks anywhere.
|
|
9
|
+
* A line that may still be the header of a table without leading pipes ("a | b") is held until the
|
|
10
|
+
* next line shows whether a separator row follows; `releasePending()` lets it go when the stream goes quiet.
|
|
9
11
|
* Indented code blocks are not detected.
|
|
10
12
|
*/
|
|
11
13
|
export declare class MarkdownGuard {
|
|
@@ -13,15 +15,51 @@ export declare class MarkdownGuard {
|
|
|
13
15
|
private line;
|
|
14
16
|
private passthrough;
|
|
15
17
|
private fence;
|
|
18
|
+
/** Content column of the latest list item; fences indented from it count as fences. Null outside lists. */
|
|
19
|
+
private listCol;
|
|
20
|
+
/** The whole current line, kept even after its text was released as prose. */
|
|
21
|
+
private raw;
|
|
16
22
|
private table;
|
|
23
|
+
/** A complete line without a leading pipe that holds "|": a table header until the next line says otherwise. */
|
|
24
|
+
private candidate;
|
|
25
|
+
/** A trailing "\r" is held back until the next chunk shows whether it starts a "\r\n". */
|
|
26
|
+
private heldCr;
|
|
27
|
+
private readonly maxChars;
|
|
17
28
|
constructor(options: {
|
|
18
29
|
messages: Pick<AnnouncerMessages, 'codeBlock' | 'table'>;
|
|
30
|
+
maxChars?: number;
|
|
19
31
|
});
|
|
32
|
+
/**
|
|
33
|
+
* True while text is held only because a "|" may still make it part of a table without leading
|
|
34
|
+
* pipes (a possible header, the line after it, or the rows of such a table). Fences and rows that
|
|
35
|
+
* start with "|" are not counted: they always wait for the end of their line.
|
|
36
|
+
*/
|
|
37
|
+
get holdsPossibleTable(): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* The stream went quiet: release what is held only because a "|" might still come, so it can be
|
|
40
|
+
* read now. Fences, rows that start with "|", and a table waiting for its next row keep waiting.
|
|
41
|
+
* After this, the rest of a released line passes through as prose.
|
|
42
|
+
*/
|
|
43
|
+
releasePending(): GuardOutput[];
|
|
20
44
|
push(text: string): GuardOutput[];
|
|
21
45
|
/** The stream ended: close open fences and tables. */
|
|
22
46
|
flush(): GuardOutput[];
|
|
23
47
|
private partial;
|
|
48
|
+
/**
|
|
49
|
+
* Whether an unfinished line is worth holding because it may still become a header, separator
|
|
50
|
+
* or row of a table without leading pipes. Once a line is released, every longer version of it
|
|
51
|
+
* would be released too, so where the chunks were cut does not change the result.
|
|
52
|
+
*/
|
|
53
|
+
private mayStillBeTableLine;
|
|
24
54
|
private endLine;
|
|
55
|
+
/** Remember the content column of a list item; an unindented plain line ends the list. */
|
|
56
|
+
private trackList;
|
|
57
|
+
/** A confirmed table whose header has no leading pipe ("a | b"). Its rows may start with text. */
|
|
58
|
+
private inTableWithoutPipes;
|
|
59
|
+
/** Rows of an open table: "|" rows, or any line with "|" in a table without leading pipes. */
|
|
60
|
+
private isTableLine;
|
|
61
|
+
private isSeparator;
|
|
62
|
+
private releaseCandidate;
|
|
25
63
|
private closeFence;
|
|
26
64
|
private closeTable;
|
|
27
65
|
}
|
package/dist/markdown.js
CHANGED
|
@@ -14,24 +14,80 @@ export function stripInlineMarkdown(text) {
|
|
|
14
14
|
.replace(/\s+/g, ' ')
|
|
15
15
|
.trim();
|
|
16
16
|
}
|
|
17
|
-
const FENCE_LINE = /^
|
|
17
|
+
const FENCE_LINE = /^( *)(`{3,}|~{3,})[ \t]*([^\s]*)(.*)$/;
|
|
18
|
+
const LIST_MARKER = /^( *)(?:[-*+]|\d{1,9}[.)])( +|$)/;
|
|
19
|
+
/**
|
|
20
|
+
* Whether `indent` spaces may precede a fence: 0-3 anywhere, or 0-3 beyond the content column of
|
|
21
|
+
* the current list item (`listCol`, null outside a list).
|
|
22
|
+
*/
|
|
23
|
+
function fenceIndentOk(indent, listCol) {
|
|
24
|
+
return indent <= 3 || (listCol !== null && indent >= listCol && indent <= listCol + 3);
|
|
25
|
+
}
|
|
26
|
+
/** Content column of a list item line ("1. x" -> 3, " - x" -> 4), or null when the line is not one. */
|
|
27
|
+
function listContentColumn(line) {
|
|
28
|
+
const m = LIST_MARKER.exec(line);
|
|
29
|
+
if (!m)
|
|
30
|
+
return null;
|
|
31
|
+
const marker = line.slice(m[1]?.length ?? 0).match(/^(?:[-*+]|\d{1,9}[.)])/)?.[0] ?? '';
|
|
32
|
+
const gap = (m[2] ?? '').length;
|
|
33
|
+
// A marker followed by 5 or more spaces (or nothing) has its content one space after it.
|
|
34
|
+
const pad = gap === 0 || gap > 4 ? 1 : gap;
|
|
35
|
+
return (m[1]?.length ?? 0) + marker.length + pad;
|
|
36
|
+
}
|
|
37
|
+
/** Quote markers at the start of a line: "> ", ">", "> > " (0-3 spaces before each one). */
|
|
38
|
+
const QUOTE_PREFIX = /^ {0,3}> ?/;
|
|
39
|
+
/** Removes every leading blockquote marker; `quoted` tells whether there was one. */
|
|
40
|
+
function stripQuote(line) {
|
|
41
|
+
let text = line;
|
|
42
|
+
let quoted = false;
|
|
43
|
+
for (let m = QUOTE_PREFIX.exec(text); m; m = QUOTE_PREFIX.exec(text)) {
|
|
44
|
+
text = text.slice(m[0].length);
|
|
45
|
+
quoted = true;
|
|
46
|
+
}
|
|
47
|
+
return { text, quoted };
|
|
48
|
+
}
|
|
18
49
|
const TABLE_ROW = /^ {0,3}\|/;
|
|
19
50
|
const TABLE_SEPARATOR = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
|
|
20
|
-
|
|
51
|
+
/** Text that can still grow into a separator row ("--- | :-"). */
|
|
52
|
+
const SEPARATOR_START = /^[\s:|-]*$/;
|
|
53
|
+
/**
|
|
54
|
+
* A sentence ended and the next one began: "Hello. W", "晴れ。明".
|
|
55
|
+
* "No. | Name" does not match, because only "|" follows the period.
|
|
56
|
+
*/
|
|
57
|
+
const NEXT_SENTENCE = /(?:[.!?…]["'”’)\]」』]*\s+|[。!?]["'”’)\]」』]*\s*)[^\s|]/;
|
|
58
|
+
/**
|
|
59
|
+
* Line starts that always wait for the end of their line, as they did before tables without
|
|
60
|
+
* leading pipes were supported: blanks, (possible) fences and rows that start with "|".
|
|
61
|
+
*/
|
|
62
|
+
function waitsForLineEnd(line, listCol = null) {
|
|
63
|
+
const lead = /^ */.exec(line)?.[0].length ?? 0;
|
|
64
|
+
const rest = line.slice(lead);
|
|
65
|
+
const fenceOk = fenceIndentOk(lead, listCol);
|
|
66
|
+
return (/^ {0,3}$/.test(line) ||
|
|
67
|
+
(fenceOk && (rest === '' || /^(`{1,2}|~{1,2})$/.test(rest) || /^(`{3,}|~{3,})/.test(rest))) ||
|
|
68
|
+
/^ {0,3}(`{1,2}|~{1,2})$/.test(line) ||
|
|
69
|
+
/^ {0,3}(`{3,}|~{3,})/.test(line) ||
|
|
70
|
+
TABLE_ROW.test(line));
|
|
71
|
+
}
|
|
72
|
+
function matchOpenFence(line, listCol) {
|
|
21
73
|
const m = FENCE_LINE.exec(line);
|
|
22
|
-
const marker = m?.[
|
|
74
|
+
const marker = m?.[2];
|
|
23
75
|
if (!m || !marker)
|
|
24
76
|
return null;
|
|
25
|
-
|
|
26
|
-
if (marker.startsWith('`') && (m[2] ?? '').includes('`'))
|
|
77
|
+
if (!fenceIndentOk((m[1] ?? '').length, listCol))
|
|
27
78
|
return null;
|
|
79
|
+
// CommonMark: the info string of a backtick fence cannot contain backticks.
|
|
28
80
|
if (marker.startsWith('`') && (m[3] ?? '').includes('`'))
|
|
29
81
|
return null;
|
|
30
|
-
|
|
82
|
+
if (marker.startsWith('`') && (m[4] ?? '').includes('`'))
|
|
83
|
+
return null;
|
|
84
|
+
return { marker, lang: m[3] ?? '', listCol };
|
|
31
85
|
}
|
|
32
|
-
function isClosingFence(line, marker) {
|
|
33
|
-
const m = /^
|
|
34
|
-
|
|
86
|
+
function isClosingFence(line, marker, listCol = null) {
|
|
87
|
+
const m = /^( *)(`{3,}|~{3,})[ \t]*$/.exec(line);
|
|
88
|
+
if (!m || !fenceIndentOk((m[1] ?? '').length, listCol))
|
|
89
|
+
return false;
|
|
90
|
+
const found = m[2];
|
|
35
91
|
return found !== undefined && found[0] === marker[0] && found.length >= marker.length;
|
|
36
92
|
}
|
|
37
93
|
const countCells = (row) => row.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').length;
|
|
@@ -39,6 +95,8 @@ const countCells = (row) => row.trim().replace(/^\|/, '').replace(/\|$/, '').spl
|
|
|
39
95
|
* Splits a Markdown stream into prose and summaries.
|
|
40
96
|
* Fenced code and tables are never released as text; each becomes one short summary.
|
|
41
97
|
* Detection works line by line, so a fence or table may be split across chunks anywhere.
|
|
98
|
+
* A line that may still be the header of a table without leading pipes ("a | b") is held until the
|
|
99
|
+
* next line shows whether a separator row follows; `releasePending()` lets it go when the stream goes quiet.
|
|
42
100
|
* Indented code blocks are not detected.
|
|
43
101
|
*/
|
|
44
102
|
export class MarkdownGuard {
|
|
@@ -46,13 +104,64 @@ export class MarkdownGuard {
|
|
|
46
104
|
line = '';
|
|
47
105
|
passthrough = false;
|
|
48
106
|
fence = null;
|
|
107
|
+
/** Content column of the latest list item; fences indented from it count as fences. Null outside lists. */
|
|
108
|
+
listCol = null;
|
|
109
|
+
/** The whole current line, kept even after its text was released as prose. */
|
|
110
|
+
raw = '';
|
|
49
111
|
table = [];
|
|
112
|
+
/** A complete line without a leading pipe that holds "|": a table header until the next line says otherwise. */
|
|
113
|
+
candidate = null;
|
|
114
|
+
/** A trailing "\r" is held back until the next chunk shows whether it starts a "\r\n". */
|
|
115
|
+
heldCr = false;
|
|
116
|
+
maxChars;
|
|
50
117
|
constructor(options) {
|
|
51
118
|
this.options = options;
|
|
119
|
+
this.maxChars = options.maxChars ?? 200;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* True while text is held only because a "|" may still make it part of a table without leading
|
|
123
|
+
* pipes (a possible header, the line after it, or the rows of such a table). Fences and rows that
|
|
124
|
+
* start with "|" are not counted: they always wait for the end of their line.
|
|
125
|
+
*/
|
|
126
|
+
get holdsPossibleTable() {
|
|
127
|
+
if (this.fence || this.passthrough)
|
|
128
|
+
return false;
|
|
129
|
+
if (this.candidate !== null || this.inTableWithoutPipes())
|
|
130
|
+
return true;
|
|
131
|
+
return this.line.length > 0 && !waitsForLineEnd(stripQuote(this.line).text, this.listCol);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* The stream went quiet: release what is held only because a "|" might still come, so it can be
|
|
135
|
+
* read now. Fences, rows that start with "|", and a table waiting for its next row keep waiting.
|
|
136
|
+
* After this, the rest of a released line passes through as prose.
|
|
137
|
+
*/
|
|
138
|
+
releasePending() {
|
|
139
|
+
const out = [];
|
|
140
|
+
if (this.fence || this.passthrough)
|
|
141
|
+
return out;
|
|
142
|
+
// A possible header is read as the line it probably is.
|
|
143
|
+
this.releaseCandidate(out);
|
|
144
|
+
const line = this.line;
|
|
145
|
+
const text = stripQuote(line).text;
|
|
146
|
+
if (text.trim().length === 0 || waitsForLineEnd(text, this.listCol))
|
|
147
|
+
return out;
|
|
148
|
+
// A row of a table without leading pipes that already has its "|" waits like a "|" row.
|
|
149
|
+
if (this.inTableWithoutPipes() && text.includes('|'))
|
|
150
|
+
return out;
|
|
151
|
+
this.closeTable(out);
|
|
152
|
+
out.push({ kind: 'prose', text: line });
|
|
153
|
+
this.line = '';
|
|
154
|
+
this.passthrough = true;
|
|
155
|
+
return out;
|
|
52
156
|
}
|
|
53
157
|
push(text) {
|
|
54
158
|
const out = [];
|
|
55
|
-
|
|
159
|
+
// Treat "\r\n" as "\n", even when the "\r" and "\n" arrive in different chunks.
|
|
160
|
+
let rest = (this.heldCr ? '\r' : '') + text;
|
|
161
|
+
this.heldCr = rest.endsWith('\r');
|
|
162
|
+
if (this.heldCr)
|
|
163
|
+
rest = rest.slice(0, -1);
|
|
164
|
+
rest = rest.replace(/\r\n/g, '\n');
|
|
56
165
|
while (rest.length > 0) {
|
|
57
166
|
const nl = rest.indexOf('\n');
|
|
58
167
|
if (nl === -1) {
|
|
@@ -68,31 +177,54 @@ export class MarkdownGuard {
|
|
|
68
177
|
/** The stream ended: close open fences and tables. */
|
|
69
178
|
flush() {
|
|
70
179
|
const out = [];
|
|
180
|
+
this.heldCr = false;
|
|
181
|
+
this.raw = '';
|
|
182
|
+
this.listCol = null;
|
|
71
183
|
if (this.fence) {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
return out;
|
|
77
|
-
}
|
|
78
|
-
if (!this.passthrough && this.line.length > 0) {
|
|
79
|
-
if (TABLE_ROW.test(this.line)) {
|
|
80
|
-
this.table.push(this.line);
|
|
81
|
-
this.closeTable(out);
|
|
184
|
+
const q = stripQuote(this.line);
|
|
185
|
+
if (this.fence.quoted && !q.quoted && this.line.length > 0) {
|
|
186
|
+
// A quoted fence ends where the quote ends; the line itself is ordinary text.
|
|
187
|
+
this.closeFence(out);
|
|
82
188
|
}
|
|
83
189
|
else {
|
|
84
|
-
this.
|
|
85
|
-
|
|
190
|
+
const view = this.fence.quoted ? q.text : this.line;
|
|
191
|
+
// A closing fence without a final newline is not a code line.
|
|
192
|
+
if (view.trim().length > 0 && !isClosingFence(view, this.fence.marker, this.fence.listCol))
|
|
193
|
+
this.fence.lines += 1;
|
|
194
|
+
this.line = '';
|
|
195
|
+
this.closeFence(out);
|
|
196
|
+
return out;
|
|
86
197
|
}
|
|
87
198
|
}
|
|
88
|
-
|
|
89
|
-
|
|
199
|
+
const line = this.passthrough ? '' : this.line;
|
|
200
|
+
const text = stripQuote(line).text;
|
|
201
|
+
if (line.length > 0) {
|
|
202
|
+
if (this.candidate !== null && this.isSeparator(text, this.candidate)) {
|
|
203
|
+
// "a | b" + "--- | ---" at the very end: a table without rows.
|
|
204
|
+
this.table = [this.candidate, text];
|
|
205
|
+
this.candidate = null;
|
|
206
|
+
}
|
|
207
|
+
else {
|
|
208
|
+
// The possible header goes first, so the order stays the same as in the stream.
|
|
209
|
+
this.releaseCandidate(out);
|
|
210
|
+
if (this.isTableLine(text)) {
|
|
211
|
+
this.table.push(text);
|
|
212
|
+
}
|
|
213
|
+
else {
|
|
214
|
+
this.closeTable(out);
|
|
215
|
+
out.push({ kind: 'prose', text: line });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
90
218
|
}
|
|
219
|
+
this.closeTable(out);
|
|
220
|
+
this.releaseCandidate(out);
|
|
91
221
|
this.line = '';
|
|
92
222
|
this.passthrough = false;
|
|
93
223
|
return out;
|
|
94
224
|
}
|
|
95
225
|
partial(segment, out) {
|
|
226
|
+
if (!this.fence)
|
|
227
|
+
this.raw += segment;
|
|
96
228
|
if (this.fence) {
|
|
97
229
|
this.line += segment;
|
|
98
230
|
return;
|
|
@@ -102,46 +234,126 @@ export class MarkdownGuard {
|
|
|
102
234
|
return;
|
|
103
235
|
}
|
|
104
236
|
this.line += segment;
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
237
|
+
const line = this.line;
|
|
238
|
+
// Quote markers do not count: the rules below look at the content of the line.
|
|
239
|
+
const text = stripQuote(line).text;
|
|
240
|
+
// A possible header is released as soon as this line can no longer be its separator row.
|
|
241
|
+
if (this.candidate !== null && !SEPARATOR_START.test(text))
|
|
242
|
+
this.releaseCandidate(out);
|
|
243
|
+
// Blanks, fences and "|" rows wait for the end of the line, exactly as before.
|
|
244
|
+
if (waitsForLineEnd(text, this.listCol))
|
|
245
|
+
return;
|
|
246
|
+
// A table with leading pipes ends at the first line that is clearly not a "|" row.
|
|
247
|
+
if (!this.inTableWithoutPipes())
|
|
248
|
+
this.closeTable(out);
|
|
249
|
+
if (this.mayStillBeTableLine(text))
|
|
111
250
|
return;
|
|
112
251
|
this.closeTable(out);
|
|
113
|
-
|
|
252
|
+
this.releaseCandidate(out);
|
|
253
|
+
out.push({ kind: 'prose', text: line });
|
|
114
254
|
this.line = '';
|
|
115
255
|
this.passthrough = true;
|
|
116
256
|
}
|
|
257
|
+
/**
|
|
258
|
+
* Whether an unfinished line is worth holding because it may still become a header, separator
|
|
259
|
+
* or row of a table without leading pipes. Once a line is released, every longer version of it
|
|
260
|
+
* would be released too, so where the chunks were cut does not change the result.
|
|
261
|
+
*/
|
|
262
|
+
mayStillBeTableLine(line) {
|
|
263
|
+
const firstPipe = line.indexOf('|');
|
|
264
|
+
// No "|" within maxChars: too long to wait for.
|
|
265
|
+
if ((firstPipe === -1 ? line.length : firstPipe) > this.maxChars)
|
|
266
|
+
return false;
|
|
267
|
+
// A row of a table without leading pipes, or the line after a possible header: wait for the line end.
|
|
268
|
+
if (this.inTableWithoutPipes() || this.candidate !== null)
|
|
269
|
+
return true;
|
|
270
|
+
// A possible header ("a | b"): prose once a sentence ended before any "|" and the next one began.
|
|
271
|
+
const beforePipe = firstPipe === -1 ? line : line.slice(0, firstPipe);
|
|
272
|
+
return !NEXT_SENTENCE.test(beforePipe);
|
|
273
|
+
}
|
|
117
274
|
endLine(out) {
|
|
118
275
|
const line = this.line;
|
|
276
|
+
const raw = this.raw;
|
|
119
277
|
this.line = '';
|
|
278
|
+
this.raw = '';
|
|
120
279
|
if (this.passthrough) {
|
|
121
280
|
this.passthrough = false;
|
|
281
|
+
this.trackList(raw);
|
|
122
282
|
out.push({ kind: 'prose', text: '\n' });
|
|
123
283
|
return;
|
|
124
284
|
}
|
|
285
|
+
const q = stripQuote(line);
|
|
286
|
+
const text = q.text;
|
|
125
287
|
if (this.fence) {
|
|
126
|
-
if (
|
|
288
|
+
if (this.fence.quoted && !q.quoted) {
|
|
289
|
+
// The quote ended, so the quoted fence ends too (no lazy continuation); handle the line below.
|
|
127
290
|
this.closeFence(out);
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
291
|
+
}
|
|
292
|
+
else {
|
|
293
|
+
const view = this.fence.quoted ? text : line;
|
|
294
|
+
if (isClosingFence(view, this.fence.marker, this.fence.listCol))
|
|
295
|
+
this.closeFence(out);
|
|
296
|
+
else
|
|
297
|
+
this.fence.lines += 1;
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
131
300
|
}
|
|
132
|
-
const open = matchOpenFence(
|
|
301
|
+
const open = matchOpenFence(text, this.listCol);
|
|
133
302
|
if (open) {
|
|
134
303
|
this.closeTable(out);
|
|
135
|
-
this.
|
|
304
|
+
this.releaseCandidate(out);
|
|
305
|
+
this.fence = { ...open, lines: 0, quoted: q.quoted };
|
|
136
306
|
return;
|
|
137
307
|
}
|
|
138
|
-
|
|
139
|
-
|
|
308
|
+
this.trackList(raw);
|
|
309
|
+
if (this.candidate !== null) {
|
|
310
|
+
if (this.isSeparator(text, this.candidate)) {
|
|
311
|
+
this.table = [this.candidate, text];
|
|
312
|
+
this.candidate = null;
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
this.releaseCandidate(out);
|
|
316
|
+
}
|
|
317
|
+
if (this.isTableLine(text)) {
|
|
318
|
+
this.table.push(text);
|
|
140
319
|
return;
|
|
141
320
|
}
|
|
142
321
|
this.closeTable(out);
|
|
322
|
+
// A line with "|" but no leading pipe may be a header: decide when the next line shows its separator.
|
|
323
|
+
if (text.includes('|')) {
|
|
324
|
+
this.candidate = text;
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
143
327
|
out.push({ kind: 'prose', text: `${line}\n` });
|
|
144
328
|
}
|
|
329
|
+
/** Remember the content column of a list item; an unindented plain line ends the list. */
|
|
330
|
+
trackList(line) {
|
|
331
|
+
if (line.trim().length === 0)
|
|
332
|
+
return;
|
|
333
|
+
const col = listContentColumn(line);
|
|
334
|
+
if (col !== null)
|
|
335
|
+
this.listCol = col;
|
|
336
|
+
else if (!line.startsWith(' '))
|
|
337
|
+
this.listCol = null;
|
|
338
|
+
}
|
|
339
|
+
/** A confirmed table whose header has no leading pipe ("a | b"). Its rows may start with text. */
|
|
340
|
+
inTableWithoutPipes() {
|
|
341
|
+
const header = this.table[0];
|
|
342
|
+
return header !== undefined && !TABLE_ROW.test(header);
|
|
343
|
+
}
|
|
344
|
+
/** Rows of an open table: "|" rows, or any line with "|" in a table without leading pipes. */
|
|
345
|
+
isTableLine(line) {
|
|
346
|
+
return TABLE_ROW.test(line) || (this.inTableWithoutPipes() && line.includes('|'));
|
|
347
|
+
}
|
|
348
|
+
isSeparator(line, header) {
|
|
349
|
+
return line.includes('|') && TABLE_SEPARATOR.test(line) && countCells(line) === countCells(header);
|
|
350
|
+
}
|
|
351
|
+
releaseCandidate(out) {
|
|
352
|
+
if (this.candidate === null)
|
|
353
|
+
return;
|
|
354
|
+
out.push({ kind: 'prose', text: `${this.candidate}\n` });
|
|
355
|
+
this.candidate = null;
|
|
356
|
+
}
|
|
145
357
|
closeFence(out) {
|
|
146
358
|
if (!this.fence)
|
|
147
359
|
return;
|
|
@@ -31,6 +31,13 @@ export declare class SentenceBuffer {
|
|
|
31
31
|
flush(): string[];
|
|
32
32
|
/** Stop the idle timer. Pending text is kept. */
|
|
33
33
|
cancel(): void;
|
|
34
|
+
/**
|
|
35
|
+
* More text has started on the next line, but the caller holds it back for now (`MarkdownGuard`
|
|
36
|
+
* waits for a possible "|"). Returns the sentences that the line break completes, the same as
|
|
37
|
+
* pushing the first character of that line would. The idle timer stops: the caller flushes when
|
|
38
|
+
* the stream goes quiet.
|
|
39
|
+
*/
|
|
40
|
+
nextLineStarted(): string[];
|
|
34
41
|
private drain;
|
|
35
42
|
private armIdle;
|
|
36
43
|
}
|
package/dist/sentence-buffer.js
CHANGED
|
@@ -54,13 +54,24 @@ export class SentenceBuffer {
|
|
|
54
54
|
clearTimeout(this.timer);
|
|
55
55
|
this.timer = null;
|
|
56
56
|
}
|
|
57
|
-
|
|
57
|
+
/**
|
|
58
|
+
* More text has started on the next line, but the caller holds it back for now (`MarkdownGuard`
|
|
59
|
+
* waits for a possible "|"). Returns the sentences that the line break completes, the same as
|
|
60
|
+
* pushing the first character of that line would. The idle timer stops: the caller flushes when
|
|
61
|
+
* the stream goes quiet.
|
|
62
|
+
*/
|
|
63
|
+
nextLineStarted() {
|
|
64
|
+
this.cancel();
|
|
65
|
+
// Nothing can extend a segment that ends with a line break.
|
|
66
|
+
return this.drain(false, /\n\s*$/.test(this.text));
|
|
67
|
+
}
|
|
68
|
+
drain(final, lastIsComplete = false) {
|
|
58
69
|
const segments = [...this.segmenter.segment(this.text)].map((s) => s.segment);
|
|
59
70
|
const out = [];
|
|
60
71
|
let held = '';
|
|
61
72
|
for (let i = 0; i < segments.length; i++) {
|
|
62
73
|
held += segments[i];
|
|
63
|
-
if (!final && i === segments.length - 1)
|
|
74
|
+
if (!final && !lastIsComplete && i === segments.length - 1)
|
|
64
75
|
break;
|
|
65
76
|
// While a fragment is held, later segments join it so sentences never overtake it.
|
|
66
77
|
if (TERMINATED.test(held) && held.trim().length >= this.minChars) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stream-announcer",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"description": "Screen reader announcements for streaming LLM chat: sentence-level, completion-aware, framework-neutral core with React hooks and jsdom test helpers.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"accessibility",
|