mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-16 16:46:09 -08:00
Compare commits
32
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ecaec34b2
|
||
|
|
5c778a9442
|
||
|
|
47d31e9628
|
||
|
|
4c6bfaa22e
|
||
|
|
7db247ef5b
|
||
|
|
dd0307cf75
|
||
|
|
df3fd96808
|
||
|
|
c07ba665ba
|
||
|
|
30f79857d8
|
||
|
|
36cd19794e
|
||
|
|
1eb7f73b3b
|
||
|
|
ebab843ce5
|
||
|
|
45ca02a7d8
|
||
|
|
23d790d8f2
|
||
|
|
f51ecb69d1
|
||
|
|
5a44a4f39d
|
||
|
|
62758bf9cb
|
||
|
|
b528440d48
|
||
|
|
a34c3e95c5
|
||
|
|
e72d38a4eb
|
||
|
|
c1e6e44025
|
||
|
|
07a97fd64c
|
||
|
|
f3840e1f4c
|
||
|
|
301714777a
|
||
|
|
ca5fc341cb
|
||
|
|
ee08512988
|
||
|
|
dbdf578c68 | ||
|
|
441ecf3c04 | ||
|
|
a0dde4ee3e
|
||
|
|
fe4dacc1e7 | ||
|
|
b08cd0db35 | ||
|
|
bffb1c5982 |
No files matched your search
@@ -1,5 +1,23 @@
|
||||
# Changelog
|
||||
|
||||
## v0.19.2 (2026-08-04)
|
||||
|
||||
### Changed
|
||||
- Subsync: The sync modal now lets you choose both the reference subtitle (correct timing) and the out-of-sync subtitle to retime, for both alass and ffsubsync. alass can also use the loaded video's audio as a reference for local files. Retiming the secondary track now reloads the result into the secondary slot instead of overwriting the primary subtitle.
|
||||
|
||||
### Fixed
|
||||
- Streaming Subtitle Tokenization: Jellyfin streams now seed subtitle tokenization directly from the downloaded subtitle file instead of relying on an mpv event that could be missed, and prefetching now runs to the end of the file and clears between episodes. The tokenization cache was raised from 256 to 2500 lines, and parsed cues are no longer lost when the active subtitle track briefly can't be resolved (e.g. switching to an embedded track). Together these prevent episodes from falling back to slow, line-by-line tokenization during playback.
|
||||
- Overlay: Subtitle lines now appear immediately at their cue time even on a tokenization cache miss, upgrading in place once tokens and annotations are ready, instead of waiting on a line still being processed. A failed tokenization is no longer cached as plain text, so repeated lines get another chance at annotations.
|
||||
- Background Logging: Background startup now respects the configured logging level when no explicit log level is passed.
|
||||
|
||||
<details>
|
||||
<summary>Internal changes</summary>
|
||||
|
||||
### Internal
|
||||
- Patched three high-severity dependency advisories (`undici`, `brace-expansion`, `fast-uri`).
|
||||
|
||||
</details>
|
||||
|
||||
## v0.19.1 (2026-08-01)
|
||||
|
||||
### Added
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
"eslint": "^10.8.0",
|
||||
"prettier": "^3.8.1",
|
||||
"typescript": "^5.9.3",
|
||||
"undici": "7.28.0",
|
||||
"undici": "7.29.0",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -36,8 +36,9 @@
|
||||
"overrides": {
|
||||
"@xmldom/xmldom": "0.8.13",
|
||||
"app-builder-lib": "26.15.3",
|
||||
"brace-expansion": "5.0.8",
|
||||
"brace-expansion": "5.0.9",
|
||||
"electron-builder-squirrel-windows": "26.15.3",
|
||||
"fast-uri": "3.1.5",
|
||||
"form-data": "4.0.6",
|
||||
"ip-address": "10.2.0",
|
||||
"js-yaml": "4.3.0",
|
||||
@@ -46,6 +47,7 @@
|
||||
"picomatch": "4.0.4",
|
||||
"tar": "7.5.21",
|
||||
"tmp": "0.2.7",
|
||||
"undici": "7.29.0",
|
||||
},
|
||||
"packages": {
|
||||
"@discordjs/collection": ["@discordjs/collection@2.1.1", "", {}, "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg=="],
|
||||
@@ -266,7 +268,7 @@
|
||||
|
||||
"boolean": ["boolean@3.2.0", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="],
|
||||
|
||||
"brace-expansion": ["brace-expansion@5.0.8", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg=="],
|
||||
"brace-expansion": ["brace-expansion@5.0.9", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg=="],
|
||||
|
||||
"buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],
|
||||
|
||||
@@ -404,7 +406,7 @@
|
||||
|
||||
"fast-levenshtein": ["fast-levenshtein@2.0.6", "", {}, "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw=="],
|
||||
|
||||
"fast-uri": ["fast-uri@3.1.4", "", {}, "sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw=="],
|
||||
"fast-uri": ["fast-uri@3.1.5", "", {}, "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw=="],
|
||||
|
||||
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
|
||||
|
||||
@@ -714,7 +716,7 @@
|
||||
|
||||
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
|
||||
|
||||
"undici": ["undici@7.28.0", "", {}, "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA=="],
|
||||
"undici": ["undici@7.29.0", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
|
||||
|
||||
"undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
|
||||
|
||||
@@ -754,8 +756,6 @@
|
||||
|
||||
"@discordjs/rest/discord-api-types": ["discord-api-types@0.38.43", "", {}, "sha512-sSoBf/nK6m7BGtw65mi+QBuvEWaHE8MMziFLqWL+gT6ME/BLg34dRSVKS3Husx40uU06bvxUc3/X+D9Y6/zAbw=="],
|
||||
|
||||
"@discordjs/rest/undici": ["undici@6.27.0", "", {}, "sha512-YmfV3YnEDzXRC5lZ2jWtWWHKGUm1zIt8AhesR1tens+HTNv+YZlN/dp6G727LOvMJ8xjP9Be7Y2Sdr96LDm+pg=="],
|
||||
|
||||
"@discordjs/util/discord-api-types": ["discord-api-types@0.38.43", "", {}, "sha512-sSoBf/nK6m7BGtw65mi+QBuvEWaHE8MMziFLqWL+gT6ME/BLg34dRSVKS3Husx40uU06bvxUc3/X+D9Y6/zAbw=="],
|
||||
|
||||
"@electron/asar/commander": ["commander@5.1.0", "", {}, "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg=="],
|
||||
@@ -808,8 +808,6 @@
|
||||
|
||||
"node-gyp/env-paths": ["env-paths@2.2.1", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="],
|
||||
|
||||
"node-gyp/undici": ["undici@6.27.0", "", {}, "sha512-YmfV3YnEDzXRC5lZ2jWtWWHKGUm1zIt8AhesR1tens+HTNv+YZlN/dp6G727LOvMJ8xjP9Be7Y2Sdr96LDm+pg=="],
|
||||
|
||||
"node-gyp/which": ["which@6.0.1", "", { "dependencies": { "isexe": "^4.0.0" }, "bin": { "node-which": "bin/which.js" } }, "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg=="],
|
||||
|
||||
"pkijs/@noble/hashes": ["@noble/hashes@1.4.0", "", {}, "sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg=="],
|
||||
|
||||
@@ -28,3 +28,4 @@ area: anime
|
||||
- Episodes already watched are dimmed and marked in the episode list, with a watched count in the header. The marks come from the stats history playback already writes (an episode is marked once a session passes the completion threshold), so they match the stats window and survive the stream URL changing between playbacks. They refresh when the browser window comes back to the front, and stay empty when immersion tracking is disabled.
|
||||
- Right-clicking an episode opens a menu for marking it watched or unwatched by hand, plus "Mark this and N below watched/unwatched" for the episode and every episode listed under it. Sources list newest first, so a span covers the back catalogue, which is how a series watched elsewhere gets caught up. A filter never narrows what a span covers, and the status bar reports how many episodes were touched.
|
||||
- Marking an episode that was never played creates its stats row, carrying the same series, season and episode fields playback would have recorded. Both stats library views join the lifetime tables, so a manual mark does not show up there as watch time nobody spent, and clearing a mark creates nothing.
|
||||
- Episodes can be queued instead of replacing what is playing. Every episode row has **Play** and **Queue** buttons (clicking the row still plays now), the right-click menu offers the same two, and a queued episode shows its place in line ("next up", "#2 in queue") with a queue count and **Clear queue** in the episode header. The queue spans anime, so episodes from different series can be lined up together, and it starts the next episode when the current one ends — resolving its stream at that point, so a signed stream URL cannot expire while it waits. Queueing with nothing playing just plays. mpv's `keep-open` is held off while the queue waits, since it otherwise pauses at the end of a file forever, and the setting is restored once the queue empties.
|
||||
@@ -0,0 +1,7 @@
|
||||
type: added
|
||||
area: overlay
|
||||
|
||||
- Added an in-app changelog modal, opened from the tray ("View Changelog") or the "What's New" button on the update-available notification, which now stays on screen so "Update" is still reachable after reading the notes. It renders inside the player bounds when a video is playing and in its own window otherwise, the same as the help modal.
|
||||
- The changelog is fetched from the newest published release, so release notes for versions newer than the installed build are visible; a failed download falls back to the changelog bundled with the install and says so in the modal.
|
||||
- Versions are foldable: the current `0.x` line is expanded and older lines are folded, matching the docs-site changelog. A badge marks the installed version and newer versions are tagged "New".
|
||||
- Keyboard: `J`/`K` or arrows move between versions, `Enter` folds/unfolds, `R` refetches, `Esc` closes.
|
||||
@@ -0,0 +1,4 @@
|
||||
type: fixed
|
||||
area: subsync
|
||||
|
||||
- Subsync no longer fails with `Protocol "file:" not supported` on a subtitle that was dropped onto mpv. mpv reports such a track as a percent-encoded `file://` URL, which subsync read as a stream and tried to fetch over HTTP; the URL is now decoded back to its path, so both the retimed target and an alass reference work. A `file://` video path is treated as local too, which restores the video reference and ffsubsync for a dropped file.
|
||||
@@ -1,7 +0,0 @@
|
||||
type: changed
|
||||
area: subsync
|
||||
|
||||
- The subsync modal now lets you pick both sides of an alass run: the reference subtitle (correct timing, defaults to the loaded secondary subtitle track) and the out-of-sync subtitle that gets retimed (defaults to the active primary track).
|
||||
- alass can now use the loaded video file itself as the reference (audio-based, local files only). It is offered in the reference list but is never the default.
|
||||
- The out-of-sync subtitle picker also applies to ffsubsync, so a track other than the active primary one can be retimed.
|
||||
- Retiming the secondary subtitle track now reloads the synced result back into the secondary slot and leaves the primary track selected, instead of replacing the primary subtitle.
|
||||
@@ -0,0 +1,20 @@
|
||||
type: changed
|
||||
area: subtitles
|
||||
|
||||
- Subtitle tokenization no longer runs a duplicate full `parseText` pass per line: the termsFind scanner walk is now the only tokenizer and emits its own hoverable filler runs for unmatched text (parseText is kept only as an error fallback). This roughly halves the dictionary work per line.
|
||||
- The Yomitan scanning helpers are now installed once per parser window (`__subminerYomitanScan`) instead of re-shipping and re-parsing a ~500-line script for every subtitle line; each line only evaluates a tiny call.
|
||||
- termsFind lookups are cached across subtitle lines in a window-persistent LRU keyed by substring, so repeated particles and verb forms stop costing backend round trips. The cache invalidates on dictionary/settings changes and window reloads.
|
||||
- The scanner walk now skips lookups at punctuation and whitespace positions (latin letters and digits still look up, e.g. Tシャツ). The shrinking-window retry ladder keeps following the consumed lengths the backend reports, and only blind guesses (windows the backend consumed whole, which tell it nothing) are capped at four per position. A line that hits that cap escalates to a single `parseText` for the whole line, so a hard line still resolves to dictionary tokens instead of an unparsed run, without letting the ladder run to one lookup per window length.
|
||||
- Tokenizer runtime dependencies are built once instead of per line, fixing a JLPT lookup cache that never hit (it was keyed on a per-call closure identity and leaked a Map per line) and a `which mecab` availability check that re-ran synchronously on every line when MeCab is absent.
|
||||
- Subtitle changes no longer restart the prefetch run per line (which discarded in-flight tokenization work); prefetch now only pauses for the live line and restarts on real seeks, cache invalidation, or option changes. Prefetch also stays paused for the whole time the subtitle processing controller is working on the line, including the provisional raw emit that precedes tokenization, so it never competes with the on-screen line for the parser window. The pause is released when the controller reports it has settled, which also covers the lines that finish without an emit (a suppressed duplicate or a failed tokenization) and used to leave prefetching paused indefinitely.
|
||||
- Added per-stage debug timings (`scanMs`, `mecabMs`, `frequencyMs`, `annotateMs`) to the subtitle tokenization pipeline log.
|
||||
- Fixed a reading that stopped covering its surface when an unmatched kana run extended the preceding token (for example a trailing る on 待ち合わせ), which silently disabled the known-word reading fallback for those tokens.
|
||||
- Subtitle prefetching no longer stays paused for the rest of a cue when the same subtitle text is reported twice and there is nothing to tokenize. This covers the startup and overlay priming paths as well as ordinary subtitle changes.
|
||||
- Character name and image lookups are now refreshed centrally whenever a character dictionary sync changes its content, so a newly added name can no longer be skipped by a stale candidate list.
|
||||
- A subtitle that was on screen when its annotations were invalidated (by mining a card, for example) is now re-annotated instead of staying plain for the rest of the line.
|
||||
- Character name annotations no longer cost a dictionary lookup at every position in a line. The scanner now knows which name forms the current title's character dictionary actually contains and only checks where one can start, which removes the whole overhead of having the character dictionary enabled (measured: 21 lookups per line down to 10, the same as with it disabled). Titles with no cached character data keep the previous exhaustive scan, so a missing snapshot costs speed rather than a missing name.
|
||||
- The cross-line termsFind cache is now bounded by the number of retained dictionary entries as well as by key count, so a run of lookups that each carry hundreds of entries with full glossaries cannot grow the parser window's memory without limit. The budget is re-checked when a lookup resolves, so a single oversized response is dropped rather than parked in the cache and reused.
|
||||
- The unnamed-mob disambiguator filter (Girl A / Girl B) now only drops a single letter or digit split off a name, instead of every one-character term: a name that is genuinely one character keeps its terms whatever the script (𠮷, あ, 별 김, ア・ベ). The character dictionary and the scanner's name pre-pass also share one Han code-point table now, so a name the dictionary accepts is a name the scanner will look for.
|
||||
- A character name written in halfwidth katakana takes part in the greedy name pre-pass again, so a longer generic word can no longer swallow the start of it, and it now carries a reading (it used to come out blank, which disables known-word matching and frequency lookups for the token). Voiced halfwidth kana compose properly, so ガク reads ガク rather than ガク, and kana normalization folds halfwidth throughout so those tokens compare equal to the same word written fullwidth. Because the fold makes halfwidth text indexable, the character-name prefilter now judges halfwidth spellings like any other, and a position only bypasses it when an unfoldable voiced mark sits inside the lookup window. That covers a name that starts on a kanji and turns halfwidth later (山ガク), and one stretched out with emphatic characters in between (山ーーーーーーガク).
|
||||
- Dictionary-entry classification (source dictionaries, character-dictionary media ids) is memoized per entry object for as long as the entry is cached, instead of being recomputed for every headword comparison and every retry window.
|
||||
- Autoplay priming no longer broadcasts the plain subtitle twice: it tells the processing controller the line has already been painted, so the controller goes straight to the annotated payload.
|
||||
@@ -58,6 +58,12 @@ Extensions your repositories offer but you do not have appear under
|
||||
**Available**, each with **Install**. Repositories are stored in config under
|
||||
`anime.repos`, so you can also manage them there and keep them in a dotfile.
|
||||
|
||||
Every row carries the extension's icon, as the repository publishes it, so a
|
||||
site is recognisable before you read the name. A repository row shows its host's
|
||||
favicon instead. Icons are the only part of a row that is fetched from the
|
||||
network, and a row whose icon is missing falls back to the first letter of its
|
||||
name rather than an empty box.
|
||||
|
||||
A repository index lists every language it knows about, which is far more than
|
||||
any one person reads, so the **Available** list has a language chip row above
|
||||
it. Pick one or more languages to narrow it, or **All** to clear the filter;
|
||||
@@ -72,7 +78,8 @@ The Extensions tab opens with an **Installed** section listing everything in the
|
||||
extensions directory, with the sources each one provides and a **Remove**
|
||||
button. It is built from the directory rather than from a repository, so an
|
||||
extension you dropped in by hand — or one whose repository you have since
|
||||
removed — is still listed and still removable.
|
||||
removed — is still listed and still removable. An installed extension borrows
|
||||
its icon from the catalogue, so one no repository carries shows its monogram.
|
||||
|
||||
**Update** appears next to an extension a configured repository still carries;
|
||||
it downloads the current version over the existing APK.
|
||||
|
||||
@@ -75,8 +75,8 @@ src/
|
||||
renderer/ # Overlay renderer (modularized UI/runtime)
|
||||
handlers/ # Keyboard/mouse/gamepad interaction modules
|
||||
modals/ # Modal flows (Jimaku, Kiku, subsync, runtime options, session help,
|
||||
# character dictionary, playlist browser, subtitle sidebar,
|
||||
# YouTube track picker, controller config/debug/select)
|
||||
# changelog, character dictionary, playlist browser, subtitle
|
||||
# sidebar, YouTube track picker, controller config/debug/select)
|
||||
positioning/ # Subtitle position controller (drag-to-reposition)
|
||||
settings/ # Settings window UI (model, controls, markup)
|
||||
types/ # Domain type modules (anki, config, integrations, ...)
|
||||
|
||||
@@ -1,5 +1,23 @@
|
||||
# Changelog
|
||||
|
||||
## v0.19.2 (2026-08-04)
|
||||
|
||||
**Changed**
|
||||
- Subsync: The sync modal now lets you choose both the reference subtitle (correct timing) and the out-of-sync subtitle to retime, for both alass and ffsubsync. alass can also use the loaded video's audio as a reference for local files. Retiming the secondary track now reloads the result into the secondary slot instead of overwriting the primary subtitle.
|
||||
|
||||
**Fixed**
|
||||
- Streaming Subtitle Tokenization: Jellyfin streams now seed subtitle tokenization directly from the downloaded subtitle file instead of relying on an mpv event that could be missed, and prefetching now runs to the end of the file and clears between episodes. The tokenization cache was raised from 256 to 2500 lines, and parsed cues are no longer lost when the active subtitle track briefly can't be resolved (e.g. switching to an embedded track). Together these prevent episodes from falling back to slow, line-by-line tokenization during playback.
|
||||
- Overlay: Subtitle lines now appear immediately at their cue time even on a tokenization cache miss, upgrading in place once tokens and annotations are ready, instead of waiting on a line still being processed. A failed tokenization is no longer cached as plain text, so repeated lines get another chance at annotations.
|
||||
- Background Logging: Background startup now respects the configured logging level when no explicit log level is passed.
|
||||
|
||||
<details>
|
||||
<summary>Internal changes</summary>
|
||||
|
||||
**Internal**
|
||||
- Patched three high-severity dependency advisories (`undici`, `brace-expansion`, `fast-uri`).
|
||||
|
||||
</details>
|
||||
|
||||
## v0.19.1 (2026-08-01)
|
||||
|
||||
**Added**
|
||||
|
||||
+5
-1
@@ -147,11 +147,13 @@ The tray menu includes `Export Logs`, which creates the same sanitized local-dat
|
||||
|
||||
Once Jellyfin is configured, the tray menu includes `Jellyfin Discovery` for starting or stopping cast discovery in the current app session without changing config.
|
||||
|
||||
The tray menu also includes `View Changelog`, which opens the in-app changelog modal. It fetches the changelog from the newest published release, so you see release notes for versions newer than the one you run; if the download fails it falls back to the changelog bundled with your install and says so. Versions in the current `0.x` line are expanded by default and older lines are folded, matching this site's [Changelog](/changelog). A badge marks the version you have installed, and newer versions are tagged `New`. The same modal opens from the `What's New` button on the update-available overlay notification.
|
||||
|
||||
### Logging and App Mode
|
||||
|
||||
- `--log-level` controls logger verbosity.
|
||||
- `--dev` and `--debug` are app/dev-mode switches; they are not log-level aliases.
|
||||
- `--background` defaults to quieter logging (`warn`) unless `--log-level` is set.
|
||||
- `--background` starts at the default quieter logging level (`warn`), then follows `logging.level` after config loads. An explicit `--log-level` remains the override.
|
||||
- `--background` launched from a terminal detaches and returns the prompt; stop it with tray Quit or `SubMiner.AppImage --stop` (`SubMiner.exe --stop` on Windows).
|
||||
- Linux desktop launcher starts SubMiner with `--background` by default (via electron-builder `linux.executableArgs`).
|
||||
- On Hyprland and other Wayland compositors, the tray icon appears only when your panel provides a StatusNotifier/AppIndicator tray host.
|
||||
@@ -370,6 +372,8 @@ Press `V` to cycle the primary SubMiner subtitle bar through hidden → visible
|
||||
|
||||
`Ctrl/Cmd+/` opens the session help modal with the current overlay and mpv keybindings. The same help view is also available through the `y-h` chord in mpv.
|
||||
|
||||
The changelog modal (tray > `View Changelog`) works the same way: it renders over mpv when a video is playing and in its own window otherwise. Use `J`/`K` or the arrow keys to move between versions, `Enter` to fold or unfold one, `R` to refetch, and `Esc` to close.
|
||||
|
||||
Hovering over subtitle text pauses mpv by default; leaving resumes it. Yomitan popups also pause playback by default. Set `subtitleStyle.autoPauseVideoOnHover: false` or `subtitleStyle.autoPauseVideoOnYomitanPopup: false` to disable either behavior.
|
||||
|
||||
### Drag-and-Drop
|
||||
|
||||
@@ -64,7 +64,7 @@ Use the basic subtitle websocket when you only need the current subtitle line as
|
||||
- **Client auth:** none
|
||||
- **Reconnects:** client-managed
|
||||
|
||||
When a client connects, SubMiner immediately sends the latest subtitle payload if one is available. After that, it pushes a new message each time the current subtitle changes.
|
||||
When a client connects, SubMiner immediately sends the latest subtitle payload if one is available. After that, it pushes a new message each time the current subtitle changes. Annotation-only upgrades do not repeat the same line on this basic stream.
|
||||
|
||||
#### Message shape
|
||||
|
||||
@@ -96,6 +96,8 @@ Use the annotation websocket for custom clients that want the same structured to
|
||||
|
||||
In practice, if you are building a new client, prefer `annotationWebsocket` unless you specifically need compatibility with an existing `websocket` consumer.
|
||||
|
||||
On a tokenization cache miss, this stream first sends the cue as plain text with an empty `tokens` array, then sends the annotated replacement when tokenization finishes. Treat each message as the complete current state, replacing the previous payload.
|
||||
|
||||
#### Message shape
|
||||
|
||||
```json
|
||||
|
||||
@@ -30,7 +30,9 @@ Read when: you need to find the owner module for a behavior or test surface
|
||||
- Anime browser: extension bridge client, sidecar, and stream handling in `src/anime-bridge/`;
|
||||
browser window UI in `src/animeui/` (preload `src/preload-animeui.ts`); runtime wiring in
|
||||
`src/main/runtime/anime-browser-runtime.ts`, `src/main/runtime/anime-browser-ipc-handlers.ts`,
|
||||
`src/main/runtime/anime-bridge-installer.ts`, `src/main/runtime/stream-playback-metadata.ts`
|
||||
`src/main/runtime/anime-bridge-installer.ts`, `src/main/runtime/stream-playback-metadata.ts`.
|
||||
The play queue is app-level rather than an mpv playlist (`src/main/runtime/anime-browser-queue.ts`):
|
||||
a queued episode is resolved when its turn comes, driven off mpv's `end-file`
|
||||
- Window trackers: `src/window-trackers/`
|
||||
- Stats HTTP app: `src/core/services/stats-server.ts`, with route groups and shared route support
|
||||
in `src/core/services/stats-server/`
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
# Subtitle Overlay Priming
|
||||
|
||||
Status: active
|
||||
Last verified: 2026-06-14
|
||||
Last verified: 2026-08-04
|
||||
Owner: Kyle Yasuda
|
||||
Read when: debugging subtitle state or blank Linux/X11 overlay windows when the visible overlay is shown or recreated
|
||||
|
||||
@@ -47,18 +47,43 @@ subtitles do not draw.
|
||||
`emitSubtitle(payload)` and `refreshCurrentSubtitle(text)`, then prime secondary subtitles.
|
||||
6. Tokenization cache hit: call `consumeCachedSubtitle(text)`, `onSubtitleChange(text)`, and
|
||||
`emitSubtitle(cachedPayload)`, then prime secondary subtitles.
|
||||
7. Cache miss: call `refreshCurrentSubtitle(text)` and let normal tokenization emit the final
|
||||
payload.
|
||||
7. Cache miss: call `refreshCurrentSubtitle(text)`. Normal processing emits a plain payload
|
||||
synchronously, then replaces it with the tokenized payload when ready.
|
||||
|
||||
In `src/main.ts`, both `onSubtitleChange` and `refreshCurrentSubtitle` pause
|
||||
`subtitlePrefetchService`, notify it with `onSeek(lastObservedTimePos)`, and then call the matching
|
||||
`subtitleProcessingController` method. This gives the visible overlay priority over background
|
||||
prefetch work and re-centers prefetch around the live playback time.
|
||||
Both `onSubtitleChange` and `refreshCurrentSubtitle` pause `subtitlePrefetchService` and then call
|
||||
the matching `subtitleProcessingController` method, giving the visible overlay priority over
|
||||
background prefetch work. Prefetch is not re-centered here: restarting the run per line
|
||||
(`onSeek`) discarded the in-flight tokenization every time the subtitle changed, so only real
|
||||
seeks restart it (see `onTimePosUpdate` in `src/main.ts`).
|
||||
|
||||
On an uncached autoplay prime the raw payload is emitted here and reported to the controller with
|
||||
`notePlainSubtitleEmitted`, so the controller skips its own plain emit for that line and the
|
||||
overlay receives one plain payload followed by the annotated one.
|
||||
|
||||
The pause is released by the controller's `onProcessingSettled` callback, which fires once it has
|
||||
no work left. Emits do not release it: the first emit for an uncached line is the plain payload
|
||||
that precedes tokenization, and a run can finish without emitting at all (a suppressed duplicate,
|
||||
a failed tokenization). Both controller methods return whether processing is now pending, and the
|
||||
caller resumes immediately when it is not — a repeated subtitle schedules no work, so no settle is
|
||||
coming and prefetching would otherwise idle for the rest of the cue.
|
||||
|
||||
## Live Cue Delivery
|
||||
|
||||
- A tokenization cache miss emits the plain cue synchronously. Tokenization remains serialized so
|
||||
live work does not contend for Yomitan state.
|
||||
- If a newer cue arrives while an older line is still tokenizing, the newer plain cue or empty
|
||||
clear payload is emitted immediately. The older tokenization result is dropped before it can
|
||||
replace the current cue.
|
||||
- The current cue upgrades in place when its tokens and annotations are ready. This can reflow text
|
||||
or character images, but cue visibility does not wait for that work.
|
||||
|
||||
## Emitted State
|
||||
|
||||
- `emitSubtitle(payload)` maps to `emitSubtitlePayload(payload)`, which sends the normal
|
||||
annotated subtitle payload to overlay windows and subtitle websocket listeners.
|
||||
- `emitSubtitle(payload)` maps to `emitSubtitlePayload(payload)`. Overlay windows and annotation
|
||||
websocket listeners receive both the immediate plain cue and its later annotation upgrade.
|
||||
- The basic subtitle websocket receives the immediate plain cue only. Because its serialized
|
||||
payload discards annotations, the later upgrade would be an identical duplicate and is skipped
|
||||
when text and cue timing match.
|
||||
- Secondary priming reads mpv `secondary-sub-text`, stores it in
|
||||
`mpvClient.currentSecondarySubText`, and broadcasts `secondary-subtitle:set` to overlay windows.
|
||||
- If secondary `requestProperty` fails, the primary flow stays complete and only a debug line is
|
||||
|
||||
+10
-4
@@ -2,7 +2,7 @@
|
||||
"name": "subminer",
|
||||
"productName": "SubMiner",
|
||||
"desktopName": "SubMiner.desktop",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
|
||||
"packageManager": "bun@1.3.5",
|
||||
"main": "dist/main-entry.js",
|
||||
@@ -85,8 +85,9 @@
|
||||
"overrides": {
|
||||
"@xmldom/xmldom": "0.8.13",
|
||||
"app-builder-lib": "26.15.3",
|
||||
"brace-expansion": "5.0.8",
|
||||
"brace-expansion": "5.0.9",
|
||||
"electron-builder-squirrel-windows": "26.15.3",
|
||||
"fast-uri": "3.1.5",
|
||||
"form-data": "4.0.6",
|
||||
"ip-address": "10.2.0",
|
||||
"js-yaml": "4.3.0",
|
||||
@@ -94,7 +95,8 @@
|
||||
"minimatch": "10.2.5",
|
||||
"picomatch": "4.0.4",
|
||||
"tar": "7.5.21",
|
||||
"tmp": "0.2.7"
|
||||
"tmp": "0.2.7",
|
||||
"undici": "7.29.0"
|
||||
},
|
||||
"keywords": [
|
||||
"anki",
|
||||
@@ -126,7 +128,7 @@
|
||||
"@types/ws": "^8.18.1",
|
||||
"electron": "42.6.0",
|
||||
"electron-builder": "26.15.3",
|
||||
"undici": "7.28.0",
|
||||
"undici": "7.29.0",
|
||||
"esbuild": "^0.25.12",
|
||||
"eslint": "^10.8.0",
|
||||
"prettier": "^3.8.1",
|
||||
@@ -259,6 +261,10 @@
|
||||
{
|
||||
"from": "dist/launcher/subminer",
|
||||
"to": "launcher/subminer"
|
||||
},
|
||||
{
|
||||
"from": "CHANGELOG.md",
|
||||
"to": "CHANGELOG.md"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -2,6 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import type { spawn as spawnType, ChildProcess } from 'node:child_process';
|
||||
import { allocatePort, startSidecar } from './sidecar-process';
|
||||
import type { BundleBinaries } from './sidecar-bundle';
|
||||
@@ -92,7 +93,6 @@ test('an early exit is reported with its code rather than waiting out the deadli
|
||||
});
|
||||
|
||||
test('onExit reports a death after readiness, including to late subscribers', async () => {
|
||||
const port = await allocatePort();
|
||||
// Fake the bridge's capabilities endpoint so startSidecar reports ready.
|
||||
const server = http.createServer((_req, res) => {
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
@@ -100,7 +100,10 @@ test('onExit reports a death after readiness, including to late subscribers', as
|
||||
JSON.stringify({ mangatanMihonBridge: 1, sourceFactory: true, preferenceCallbacks: true }),
|
||||
);
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));
|
||||
// Bind first and take the port the OS assigned: allocating one up front and
|
||||
// binding it after leaves a window for another listener to claim it.
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const { port } = server.address() as AddressInfo;
|
||||
const child = fakeChild();
|
||||
const spawnImpl = (() => child) as unknown as typeof spawnType;
|
||||
|
||||
|
||||
@@ -149,6 +149,10 @@ export function startStreamStripProxy(
|
||||
attempt: number,
|
||||
): void {
|
||||
const mayRetry = req.method === 'GET' && attempt === 0;
|
||||
// Once the response is handed off, its headers (and often part of its body)
|
||||
// are already on the wire: a later upstream error can only be reported by
|
||||
// killing the connection, never by retrying or writing a 502.
|
||||
let handedOff = false;
|
||||
const retry = (): void => {
|
||||
setTimeout(
|
||||
() => requestUpstream(req, res, upstreamUrl, requestHeaders, attempt + 1),
|
||||
@@ -172,6 +176,7 @@ export function startStreamStripProxy(
|
||||
}
|
||||
log(`[stream-proxy] upstream ${status} for ${upstreamUrl.pathname}`);
|
||||
}
|
||||
handedOff = true;
|
||||
handleUpstreamResponse(req, res, upstream);
|
||||
},
|
||||
);
|
||||
@@ -180,6 +185,11 @@ export function startStreamStripProxy(
|
||||
upstreamRequest.destroy(new Error(`upstream silent for ${UPSTREAM_TIMEOUT_MS}ms`));
|
||||
});
|
||||
upstreamRequest.on('error', (error) => {
|
||||
if (handedOff) {
|
||||
log(`[stream-proxy] upstream failed mid-response: ${String(error)}`);
|
||||
res.destroy();
|
||||
return;
|
||||
}
|
||||
if (mayRetry) {
|
||||
log(`[stream-proxy] upstream request failed: ${String(error)}; retrying once`);
|
||||
retry();
|
||||
@@ -214,7 +224,19 @@ export function startStreamStripProxy(
|
||||
|
||||
if (isPlaylist) {
|
||||
const chunks: Buffer[] = [];
|
||||
upstream.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
let buffered = 0;
|
||||
upstream.on('data', (chunk: Buffer) => {
|
||||
buffered += chunk.length;
|
||||
// A playlist is text and small; anything this large is not one, and it
|
||||
// has to be held whole in memory to be rewritten.
|
||||
if (buffered > DECISION_BYTES) {
|
||||
log(`[stream-proxy] playlist body over ${DECISION_BYTES} bytes; dropping`);
|
||||
upstream.destroy();
|
||||
res.destroy();
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
upstream.on('end', () => {
|
||||
const body = rewritePlaylistOrigins(
|
||||
Buffer.concat(chunks).toString('utf8'),
|
||||
|
||||
@@ -405,8 +405,15 @@ loadMoreButton.addEventListener('click', () => void loadNextPage());
|
||||
|
||||
api.onBridgeState(renderBridgeState);
|
||||
|
||||
// The queue changes without this window asking: it advances by itself when an
|
||||
// episode ends, whether or not anyone is looking at the browser.
|
||||
api.onQueueState((state) => detailPanel.setQueue(state));
|
||||
|
||||
void (async () => {
|
||||
renderBridgeState({ stage: 'idle', progress: null, message: null });
|
||||
// A queue survives the window being closed and reopened, so start from what
|
||||
// the main process already holds rather than from empty.
|
||||
void api.getQueue().then((state) => detailPanel.setQueue(state));
|
||||
try {
|
||||
const state = await api.ensureBridge();
|
||||
renderBridgeState(state);
|
||||
|
||||
@@ -96,5 +96,7 @@ export function createDetailPanel({ api, setStatus }: DetailPanelOptions) {
|
||||
open,
|
||||
close,
|
||||
isOpen: (): boolean => !detail.classList.contains('hidden'),
|
||||
/** The queue outlives the open anime, so it is pushed in from outside. */
|
||||
setQueue: episodeList.setQueue,
|
||||
};
|
||||
}
|
||||
+93
-1
@@ -124,6 +124,19 @@
|
||||
color: var(--ok);
|
||||
}
|
||||
|
||||
/* Everything lined up behind the episode playing now, across every anime. */
|
||||
.episodes-queued {
|
||||
font-family: var(--mono);
|
||||
font-size: 11px;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.episodes-queue-clear {
|
||||
padding: 3px 9px;
|
||||
font-size: 11px;
|
||||
border-radius: 7px;
|
||||
}
|
||||
|
||||
/* Pushed to the far end so the counters stay next to the heading. */
|
||||
.episodes-filter {
|
||||
margin-left: auto;
|
||||
@@ -155,6 +168,17 @@
|
||||
background: var(--line);
|
||||
}
|
||||
|
||||
/*
|
||||
* The row is the cue plus the two things you can do with it. The cue still
|
||||
* fills the row and still plays on click; the actions sit over its trailing
|
||||
* edge, so a row with nothing hovered looks exactly as it did before them.
|
||||
*/
|
||||
.cue-row {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.cue {
|
||||
position: relative;
|
||||
display: grid;
|
||||
@@ -162,7 +186,9 @@
|
||||
gap: 26px;
|
||||
align-items: baseline;
|
||||
width: 100%;
|
||||
padding: 9px 10px 9px 0;
|
||||
/* Room at the trailing edge for the actions that sit over it, kept whether or
|
||||
* not they are showing, so a hover never slides them across the title. */
|
||||
padding: 9px 132px 9px 0;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: none;
|
||||
@@ -243,6 +269,72 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/*
|
||||
* Hidden until the row is hovered or something inside it has focus, so the
|
||||
* rail stays a list of episodes rather than a grid of buttons. Queued rows keep
|
||||
* theirs on: that button is the only way back out of the queue.
|
||||
*/
|
||||
.cue-actions {
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.14s ease;
|
||||
}
|
||||
|
||||
.cue-row:hover .cue-actions,
|
||||
.cue-row:focus-within .cue-actions,
|
||||
.cue-row[data-queued='true'] .cue-actions {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.cue-action {
|
||||
padding: 4px 10px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--panel-elevated);
|
||||
color: var(--faint);
|
||||
font: inherit;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
cursor: pointer;
|
||||
backdrop-filter: blur(6px);
|
||||
transition:
|
||||
color 0.14s ease,
|
||||
border-color 0.14s ease;
|
||||
}
|
||||
|
||||
.cue-action:hover {
|
||||
color: var(--text);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.cue-action[data-active='true'] {
|
||||
color: var(--accent);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
/* The badge says where in line it is; the button beside it says it can leave. */
|
||||
.cue-queued {
|
||||
margin-left: 10px;
|
||||
font-family: var(--mono);
|
||||
font-size: 10px;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--accent);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cue[data-queued='true']::after {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.cue[data-state='loading'] {
|
||||
background: var(--panel-elevated);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ import { describe, el } from './dom';
|
||||
import { closeContextMenu, showContextMenu, type ContextMenuItem } from './context-menu';
|
||||
import { filterEpisodes } from './episode-filter';
|
||||
import { describeMarkCount, episodesInScope } from './episode-marks';
|
||||
import { describeQueuePosition } from './episode-queue';
|
||||
import { createEpisodeQueueControls } from './episode-queue-controls';
|
||||
import type { AnimeBrowserAPI, AnimeBrowserEpisode } from '../types/anime-browser';
|
||||
|
||||
export interface SelectedAnime {
|
||||
@@ -67,6 +69,25 @@ export function createEpisodeList({ api, setStatus, selectedAnime }: EpisodeList
|
||||
}
|
||||
}
|
||||
|
||||
const queue = createEpisodeQueueControls({
|
||||
api,
|
||||
setStatus,
|
||||
selectedAnime,
|
||||
playEpisode: (episode) => playEpisode(episode),
|
||||
onChange: () => paint(),
|
||||
onAdvance: (entry) => {
|
||||
// The queue started this one, so the cue this window was holding belongs
|
||||
// to an episode that has finished. The new one only earns the cue when it
|
||||
// is an episode of the anime on screen.
|
||||
const anime = selectedAnime();
|
||||
const mine =
|
||||
anime !== null && anime.sourceId === entry.sourceId && anime.url === entry.animeUrl;
|
||||
cueState = mine ? { url: entry.episodeUrl, state: 'playing' } : null;
|
||||
applyCueState();
|
||||
setStatus(`Queue started ${entry.episodeName}.`, 'ok');
|
||||
},
|
||||
});
|
||||
|
||||
async function playEpisode(episode: AnimeBrowserEpisode) {
|
||||
const anime = selectedAnime();
|
||||
if (!anime) return;
|
||||
@@ -116,6 +137,7 @@ export function createEpisodeList({ api, setStatus, selectedAnime }: EpisodeList
|
||||
function createRow(item: ListedEpisode): HTMLLIElement {
|
||||
const { episode } = item;
|
||||
const row = document.createElement('li');
|
||||
row.className = 'cue-row';
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'cue';
|
||||
@@ -138,6 +160,17 @@ export function createEpisodeList({ api, setStatus, selectedAnime }: EpisodeList
|
||||
mark.textContent = '✓ watched';
|
||||
name.append(mark);
|
||||
}
|
||||
const position = queue.positionOf(episode);
|
||||
if (position !== undefined) {
|
||||
button.dataset.queued = 'true';
|
||||
// On the row too, so the actions can stay visible without asking the CSS
|
||||
// to look inside for a queued cue.
|
||||
row.dataset.queued = 'true';
|
||||
const mark = document.createElement('span');
|
||||
mark.className = 'cue-queued';
|
||||
mark.textContent = describeQueuePosition(position);
|
||||
name.append(mark);
|
||||
}
|
||||
if (episode.uploadedAt !== null) {
|
||||
const uploaded = safeUploadDate(episode.uploadedAt);
|
||||
if (uploaded) {
|
||||
@@ -154,10 +187,45 @@ export function createEpisodeList({ api, setStatus, selectedAnime }: EpisodeList
|
||||
event.preventDefault();
|
||||
openRowMenu(event, item);
|
||||
});
|
||||
row.append(button);
|
||||
|
||||
// The row itself plays, which leaves the other choice — after this one, not
|
||||
// instead of it — with nothing to click. These two spell both out, and a
|
||||
// right-click on the row says the same thing in words.
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'cue-actions';
|
||||
actions.append(
|
||||
createRowAction('Play', `Play ${episode.name} now`, () => void playEpisode(episode)),
|
||||
createRowAction(
|
||||
position === undefined ? 'Queue' : 'Queued',
|
||||
position === undefined
|
||||
? `Play ${episode.name} after the current episode`
|
||||
: `Take ${episode.name} out of the queue`,
|
||||
() => void queue.toggle(episode),
|
||||
position !== undefined,
|
||||
),
|
||||
);
|
||||
|
||||
row.append(button, actions);
|
||||
return row;
|
||||
}
|
||||
|
||||
function createRowAction(
|
||||
label: string,
|
||||
title: string,
|
||||
onClick: () => void,
|
||||
active = false,
|
||||
): HTMLButtonElement {
|
||||
const action = document.createElement('button');
|
||||
action.type = 'button';
|
||||
action.className = 'cue-action';
|
||||
action.textContent = label;
|
||||
action.title = title;
|
||||
action.setAttribute('aria-label', title);
|
||||
if (active) action.dataset.active = 'true';
|
||||
action.addEventListener('click', onClick);
|
||||
return action;
|
||||
}
|
||||
|
||||
/**
|
||||
* The right-click menu on one episode: this episode, or this one and every
|
||||
* episode listed below it, which for a newest-first source is everything
|
||||
@@ -169,8 +237,17 @@ export function createEpisodeList({ api, setStatus, selectedAnime }: EpisodeList
|
||||
const isWatched = watched.has(item.episode.url);
|
||||
const below = episodesInScope(listed, index, 'below');
|
||||
const items: ContextMenuItem[] = [
|
||||
{
|
||||
label: 'Play now',
|
||||
onSelect: () => void playEpisode(item.episode),
|
||||
},
|
||||
{
|
||||
label: queue.isQueued(item.episode) ? 'Remove from queue' : 'Play after current',
|
||||
onSelect: () => void queue.toggle(item.episode),
|
||||
},
|
||||
{
|
||||
label: isWatched ? 'Mark unwatched' : 'Mark watched',
|
||||
separated: true,
|
||||
onSelect: () => void applyMark([item], !isWatched),
|
||||
},
|
||||
];
|
||||
@@ -335,5 +412,5 @@ export function createEpisodeList({ api, setStatus, selectedAnime }: EpisodeList
|
||||
});
|
||||
window.addEventListener('focus', () => void refreshWatchState());
|
||||
|
||||
return { render, clear, refreshWatchState };
|
||||
return { render, clear, refreshWatchState, setQueue: queue.setState };
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import { capture } from './browse-state';
|
||||
import { describe, el } from './dom';
|
||||
import { describeQueuePosition, queueKey, queuePositions } from './episode-queue';
|
||||
import type { SelectedAnime } from './episode-list';
|
||||
import type {
|
||||
AnimeBrowserAPI,
|
||||
AnimeBrowserEpisode,
|
||||
AnimeBrowserQueueEntry,
|
||||
AnimeBrowserQueueState,
|
||||
} from '../types/anime-browser';
|
||||
|
||||
interface EpisodeQueueControlsOptions {
|
||||
api: AnimeBrowserAPI;
|
||||
setStatus: (message: string, tone?: 'info' | 'ok' | 'error') => void;
|
||||
/** The anime the open detail page belongs to, or null once it is closed. */
|
||||
selectedAnime: () => SelectedAnime | null;
|
||||
/** Play now, with the cue states and status line the episode list owns. */
|
||||
playEpisode: (episode: AnimeBrowserEpisode) => Promise<void>;
|
||||
/** Repaint the rows; their badges and buttons read from this queue. */
|
||||
onChange: () => void;
|
||||
/** The queue started this episode by itself, so nothing else is playing now. */
|
||||
onAdvance: (entry: AnimeBrowserQueueEntry) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The play queue as this window sees it.
|
||||
*
|
||||
* The queue itself lives in the main process — it has to, since it advances
|
||||
* when an episode ends whether or not this window is open. Everything here is a
|
||||
* view of what it pushes back, plus the two calls that change it.
|
||||
*/
|
||||
export function createEpisodeQueueControls(options: EpisodeQueueControlsOptions) {
|
||||
const { api, setStatus, selectedAnime, playEpisode, onChange, onAdvance } = options;
|
||||
const queuedLabel = el<HTMLSpanElement>('episodes-queued');
|
||||
const clearButton = el<HTMLButtonElement>('episodes-queue-clear');
|
||||
|
||||
let queue: AnimeBrowserQueueState = {
|
||||
entries: [],
|
||||
lastError: null,
|
||||
advances: 0,
|
||||
lastStarted: null,
|
||||
};
|
||||
let positions = new Map<string, number>();
|
||||
|
||||
function positionOf(episode: AnimeBrowserEpisode): number | undefined {
|
||||
const anime = selectedAnime();
|
||||
return anime ? positions.get(queueKey(anime.sourceId, episode.url)) : undefined;
|
||||
}
|
||||
|
||||
function isQueued(episode: AnimeBrowserEpisode): boolean {
|
||||
return positionOf(episode) !== undefined;
|
||||
}
|
||||
|
||||
/** The queue as the main process now holds it, from a call or from a push. */
|
||||
function setState(next: AnimeBrowserQueueState): void {
|
||||
const previousError = queue.lastError;
|
||||
const advanced = next.advances > queue.advances;
|
||||
queue = next;
|
||||
positions = queuePositions(next.entries);
|
||||
paintHeader();
|
||||
onChange();
|
||||
// The episode this window had marked playing has ended, whether or not the
|
||||
// one that replaced it is in the list on screen.
|
||||
if (advanced && next.lastStarted) onAdvance(next.lastStarted);
|
||||
// An advance that failed happened with nobody watching this window, so it
|
||||
// is reported once rather than on every repaint after it.
|
||||
if (next.lastError && next.lastError !== previousError) {
|
||||
setStatus(`Queue stopped — ${next.lastError}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The queue spans every anime, so it is counted whole even when none of its
|
||||
* episodes are in the list on screen.
|
||||
*/
|
||||
function paintHeader(): void {
|
||||
const queued = queue.entries.length;
|
||||
queuedLabel.textContent = queued > 0 ? `Queue · ${queued}` : '';
|
||||
queuedLabel.classList.toggle('hidden', queued === 0);
|
||||
clearButton.classList.toggle('hidden', queued === 0);
|
||||
}
|
||||
|
||||
/** Queue the episode, or take it back out when it is already in line. */
|
||||
async function toggle(episode: AnimeBrowserEpisode): Promise<void> {
|
||||
const anime = selectedAnime();
|
||||
if (!anime) return;
|
||||
|
||||
const queued = isQueued(episode);
|
||||
// Queueing behind nothing would wait for an end that never comes, so with
|
||||
// an idle player the second option collapses into the first.
|
||||
if (!queued) {
|
||||
const playing = await capture(() => api.isPlaying());
|
||||
if (playing.ok && !playing.value) {
|
||||
setStatus('Nothing was playing, so this starts now.');
|
||||
await playEpisode(episode);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const attempt = await capture(() =>
|
||||
queued
|
||||
? api.dequeueEpisode(anime.sourceId, episode.url)
|
||||
: api.queueEpisode({
|
||||
sourceId: anime.sourceId,
|
||||
animeUrl: anime.url,
|
||||
animeTitle: anime.title,
|
||||
episodeUrl: episode.url,
|
||||
episodeName: episode.name,
|
||||
episodeNumber: episode.number,
|
||||
}),
|
||||
);
|
||||
if (!attempt.ok) {
|
||||
setStatus(describe(attempt.error), 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// Applied from what the call returned rather than waited for on the push
|
||||
// channel, so the row settles on the click that changed it.
|
||||
setState(attempt.value);
|
||||
const position = positionOf(episode);
|
||||
setStatus(
|
||||
position === undefined
|
||||
? `${episode.name} left the queue.`
|
||||
: `${episode.name} is ${describeQueuePosition(position)}.`,
|
||||
'ok',
|
||||
);
|
||||
}
|
||||
|
||||
async function clear(): Promise<void> {
|
||||
const attempt = await capture(() => api.clearQueue());
|
||||
if (!attempt.ok) {
|
||||
setStatus(describe(attempt.error), 'error');
|
||||
return;
|
||||
}
|
||||
setState(attempt.value);
|
||||
setStatus('Queue cleared.', 'ok');
|
||||
}
|
||||
|
||||
clearButton.addEventListener('click', () => void clear());
|
||||
|
||||
return { positionOf, isQueued, setState, toggle };
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { describeQueuePosition, queueKey, queuePositions } from './episode-queue';
|
||||
import type { AnimeBrowserQueueEntry } from '../types/anime-browser';
|
||||
|
||||
function entry(overrides: Partial<AnimeBrowserQueueEntry> = {}): AnimeBrowserQueueEntry {
|
||||
return {
|
||||
sourceId: 'source',
|
||||
animeUrl: '/anime',
|
||||
animeTitle: 'Anime',
|
||||
episodeUrl: '/episode-1',
|
||||
episodeName: 'Episode 1',
|
||||
episodeNumber: 1,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test('positions count across the whole queue, not within one anime', () => {
|
||||
const positions = queuePositions([
|
||||
entry(),
|
||||
entry({ animeUrl: '/other', episodeUrl: '/other-1' }),
|
||||
entry({ episodeUrl: '/episode-2' }),
|
||||
]);
|
||||
|
||||
assert.equal(positions.get(queueKey('source', '/episode-1')), 1);
|
||||
assert.equal(positions.get(queueKey('source', '/other-1')), 2);
|
||||
assert.equal(positions.get(queueKey('source', '/episode-2')), 3);
|
||||
});
|
||||
|
||||
test('the same episode url on two sources keeps two positions', () => {
|
||||
const positions = queuePositions([entry(), entry({ sourceId: 'other' })]);
|
||||
|
||||
assert.equal(positions.get(queueKey('source', '/episode-1')), 1);
|
||||
assert.equal(positions.get(queueKey('other', '/episode-1')), 2);
|
||||
});
|
||||
|
||||
test('the episode about to play is named rather than numbered', () => {
|
||||
assert.equal(describeQueuePosition(1), 'next up');
|
||||
assert.equal(describeQueuePosition(4), '#4 in queue');
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { AnimeBrowserQueueEntry } from '../types/anime-browser';
|
||||
|
||||
/**
|
||||
* Where each queued episode sits in line, keyed by source and episode url.
|
||||
*
|
||||
* The position is counted across the whole queue rather than within one anime:
|
||||
* "3rd up" has to mean the same thing on every detail page, or the number is
|
||||
* worse than no number at all.
|
||||
*/
|
||||
export function queuePositions(entries: AnimeBrowserQueueEntry[]): Map<string, number> {
|
||||
const positions = new Map<string, number>();
|
||||
entries.forEach((entry, index) => {
|
||||
const key = queueKey(entry.sourceId, entry.episodeUrl);
|
||||
// A duplicate should never reach the renderer, but if one did, the earlier
|
||||
// position is the one that will actually play.
|
||||
if (!positions.has(key)) positions.set(key, index + 1);
|
||||
});
|
||||
return positions;
|
||||
}
|
||||
|
||||
export function queueKey(sourceId: string, episodeUrl: string): string {
|
||||
return `${sourceId} ${episodeUrl}`;
|
||||
}
|
||||
|
||||
/** "Next up" reads better than "#1" for the episode about to play. */
|
||||
export function describeQueuePosition(position: number): string {
|
||||
return position === 1 ? 'next up' : `#${position} in queue`;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { buildIconIndex, iconMonogram, isSafeIconUrl, repoFaviconUrl } from './extension-icons';
|
||||
|
||||
test('buildIconIndex maps packages to their icon, skipping empty URLs', () => {
|
||||
const index = buildIconIndex([
|
||||
{ pkg: 'a.b.c', iconUrl: 'https://repo.example/icon/a.b.c.png' },
|
||||
{ pkg: 'd.e.f', iconUrl: '' },
|
||||
]);
|
||||
assert.equal(index.get('a.b.c'), 'https://repo.example/icon/a.b.c.png');
|
||||
assert.equal(index.has('d.e.f'), false);
|
||||
});
|
||||
|
||||
test('isSafeIconUrl accepts https only', () => {
|
||||
assert.equal(isSafeIconUrl('https://repo.example/icon/x.png'), true);
|
||||
assert.equal(isSafeIconUrl('http://repo.example/icon/x.png'), false);
|
||||
assert.equal(isSafeIconUrl('javascript:alert(1)'), false);
|
||||
assert.equal(isSafeIconUrl(null), false);
|
||||
assert.equal(isSafeIconUrl(undefined), false);
|
||||
});
|
||||
|
||||
test('repoFaviconUrl points at the index host, https only', () => {
|
||||
assert.equal(
|
||||
repoFaviconUrl(' https://raw.githubusercontent.com/u/r/main/index.min.json '),
|
||||
'https://raw.githubusercontent.com/favicon.ico',
|
||||
);
|
||||
assert.equal(repoFaviconUrl('http://repo.example/index.json'), null);
|
||||
assert.equal(repoFaviconUrl('not a url'), null);
|
||||
});
|
||||
|
||||
test('iconMonogram takes the first letter or digit, uppercased', () => {
|
||||
assert.equal(iconMonogram('AllAnime'), 'A');
|
||||
assert.equal(iconMonogram(' gogoanime'), 'G');
|
||||
assert.equal(iconMonogram('» Foo'), 'F');
|
||||
assert.equal(iconMonogram('9anime'), '9');
|
||||
assert.equal(iconMonogram('アニメ'), 'ア');
|
||||
});
|
||||
|
||||
test('iconMonogram falls back to a placeholder for a nameless row', () => {
|
||||
assert.equal(iconMonogram(''), '?');
|
||||
assert.equal(iconMonogram('---'), '?');
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Icons for the extension rows.
|
||||
*
|
||||
* An Aniyomi repository publishes each extension's icon — the streaming site's
|
||||
* own favicon — next to its APK, so the repository index is the only place an
|
||||
* icon can come from. Installed extensions are listed from disk and carry no
|
||||
* icon of their own; they borrow the one their package has in the catalogue,
|
||||
* which means an extension whose repository was removed, or one dropped in by
|
||||
* hand, falls back to a monogram.
|
||||
*/
|
||||
|
||||
interface IconSource {
|
||||
pkg: string;
|
||||
iconUrl: string;
|
||||
}
|
||||
|
||||
/** Package name to icon URL, for looking up an installed extension's icon. */
|
||||
export function buildIconIndex(extensions: IconSource[]): Map<string, string> {
|
||||
const index = new Map<string, string>();
|
||||
for (const extension of extensions) {
|
||||
if (typeof extension.iconUrl === 'string' && extension.iconUrl.length > 0) {
|
||||
index.set(extension.pkg, extension.iconUrl);
|
||||
}
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
/** Only https icons are loaded; a repo index is content the user pointed us at. */
|
||||
export function isSafeIconUrl(url: string | null | undefined): url is string {
|
||||
return typeof url === 'string' && /^https:\/\/\S+$/.test(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* The favicon of the host serving a repository index.
|
||||
*
|
||||
* A repository publishes no icon for itself, so the host's own favicon stands
|
||||
* in. Nothing depends on it: a host that serves none simply leaves the row on
|
||||
* its monogram.
|
||||
*/
|
||||
export function repoFaviconUrl(indexUrl: string): string | null {
|
||||
try {
|
||||
const url = new URL(indexUrl.trim());
|
||||
if (url.protocol !== 'https:') return null;
|
||||
return `https://${url.host}/favicon.ico`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The letter shown while an icon loads, or in place of one that never does.
|
||||
*
|
||||
* Leading punctuation and whitespace are skipped, and a name that carries no
|
||||
* letter or digit at all still gets a placeholder rather than an empty box.
|
||||
*/
|
||||
export function iconMonogram(name: string): string {
|
||||
for (const char of name.trim()) {
|
||||
if (/[\p{L}\p{N}]/u.test(char)) return char.toUpperCase();
|
||||
}
|
||||
return '?';
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, el } from './dom';
|
||||
import { buildIconIndex, iconMonogram, isSafeIconUrl, repoFaviconUrl } from './extension-icons';
|
||||
import { describeInstalled } from './format';
|
||||
import {
|
||||
collectLanguages,
|
||||
@@ -39,14 +40,40 @@ interface RowAction {
|
||||
interface RowOptions {
|
||||
name: string;
|
||||
sub: string;
|
||||
/** Repository-published icon for the row, when there is one. */
|
||||
iconUrl?: string | null;
|
||||
tags?: Array<{ text: string; className: string }>;
|
||||
actions?: RowAction[];
|
||||
isError?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The row's avatar: the extension's icon, with the name's first letter behind
|
||||
* it. Repositories do not always publish an icon for every package, so the
|
||||
* monogram shows until the image loads and stays put if it never does.
|
||||
*/
|
||||
function extensionIcon(name: string, iconUrl: string | null | undefined): HTMLSpanElement {
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'ext-icon';
|
||||
badge.setAttribute('aria-hidden', 'true');
|
||||
badge.textContent = iconMonogram(name);
|
||||
if (!isSafeIconUrl(iconUrl)) return badge;
|
||||
|
||||
const image = document.createElement('img');
|
||||
image.className = 'ext-icon-img';
|
||||
image.loading = 'lazy';
|
||||
image.alt = '';
|
||||
image.addEventListener('load', () => badge.classList.add('has-icon'));
|
||||
image.addEventListener('error', () => image.remove());
|
||||
image.src = iconUrl;
|
||||
badge.append(image);
|
||||
return badge;
|
||||
}
|
||||
|
||||
function extensionRow(options: RowOptions): HTMLDivElement {
|
||||
const row = document.createElement('div');
|
||||
row.className = options.isError ? 'ext-row is-error' : 'ext-row';
|
||||
row.append(extensionIcon(options.name, options.iconUrl));
|
||||
|
||||
const main = document.createElement('div');
|
||||
main.className = 'ext-main';
|
||||
@@ -106,6 +133,8 @@ export function createExtensionsPanel(options: ExtensionsPanelOptions) {
|
||||
// What the last refresh found, kept so toggling a language chip re-renders
|
||||
// the list without re-fetching every repository index.
|
||||
let installable: AvailableExtension[] = [];
|
||||
/** Package to icon URL, so installed rows can borrow the catalogue's icon. */
|
||||
let iconsByPkg = new Map<string, string>();
|
||||
let repoFailures: Array<{ name: string; error: string }> = [];
|
||||
let hasRepos = false;
|
||||
/** Selected language codes; empty means "All". */
|
||||
@@ -168,6 +197,7 @@ export function createExtensionsPanel(options: ExtensionsPanelOptions) {
|
||||
return extensionRow({
|
||||
name: view.name,
|
||||
sub: view.error ?? describeInstalled(view),
|
||||
iconUrl: iconsByPkg.get(view.pkg) ?? null,
|
||||
isError: view.error !== null,
|
||||
tags: view.error === null ? [] : [{ text: 'failed', className: 'nsfw' }],
|
||||
actions,
|
||||
@@ -182,6 +212,7 @@ export function createExtensionsPanel(options: ExtensionsPanelOptions) {
|
||||
extensionRow({
|
||||
name: repoUrl.replace(/^https:\/\//, '').replace(/\/[^/]*\.json$/, ''),
|
||||
sub: repoUrl,
|
||||
iconUrl: repoFaviconUrl(repoUrl),
|
||||
actions: [
|
||||
{
|
||||
label: 'Remove',
|
||||
@@ -258,6 +289,7 @@ export function createExtensionsPanel(options: ExtensionsPanelOptions) {
|
||||
extensionRow({
|
||||
name: extension.name,
|
||||
sub: `${languageLabel(extension.lang)} · v${extension.version}`,
|
||||
iconUrl: extension.iconUrl,
|
||||
tags: extension.nsfw ? [{ text: '18+', className: 'nsfw' }] : [],
|
||||
actions: [
|
||||
{
|
||||
@@ -311,6 +343,9 @@ export function createExtensionsPanel(options: ExtensionsPanelOptions) {
|
||||
}
|
||||
|
||||
const offeredPkgs = new Set(available.extensions.map((extension) => extension.pkg));
|
||||
// The catalogue is the only source of icons, so an installed extension can
|
||||
// only show one while a repository still carries its package.
|
||||
iconsByPkg = buildIconIndex(available.extensions);
|
||||
renderInstalled(snapshot.installed, offeredPkgs, snapshot.extensionsDir);
|
||||
// Installed extensions have their own section; leaving them here too would
|
||||
// list every one of them twice.
|
||||
|
||||
@@ -152,6 +152,14 @@
|
||||
<h3 class="episodes-title">Episodes</h3>
|
||||
<span class="episodes-count" id="episodes-count"></span>
|
||||
<span class="episodes-watched hidden" id="episodes-watched"></span>
|
||||
<span class="episodes-queued hidden" id="episodes-queued"></span>
|
||||
<button
|
||||
class="ghost-button episodes-queue-clear hidden"
|
||||
id="episodes-queue-clear"
|
||||
type="button"
|
||||
>
|
||||
Clear queue
|
||||
</button>
|
||||
<input
|
||||
class="text-input episodes-filter hidden"
|
||||
id="episodes-filter"
|
||||
|
||||
@@ -211,6 +211,47 @@
|
||||
border-color: rgba(237, 135, 150, 0.45);
|
||||
}
|
||||
|
||||
/*
|
||||
* Avatar for an extension row. The monogram is the box's own text, so it shows
|
||||
* while the icon loads and stays put when a repository publishes none; a loaded
|
||||
* icon covers it.
|
||||
*/
|
||||
.ext-icon {
|
||||
position: relative;
|
||||
flex: none;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--ctp-surface0);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--faint);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* A loaded icon replaces the monogram; transparent PNGs must not show it. */
|
||||
.ext-icon.has-icon {
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
color: transparent;
|
||||
}
|
||||
|
||||
.ext-icon-img {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.ext-icon.has-icon .ext-icon-img {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.ext-main {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
export { Texthooker } from './texthooker';
|
||||
export { hasMpvWebsocketPlugin, SubtitleWebSocket } from './subtitle-ws';
|
||||
export {
|
||||
hasMpvWebsocketPlugin,
|
||||
isSubtitleAnnotationUpgrade,
|
||||
SubtitleWebSocket,
|
||||
} from './subtitle-ws';
|
||||
export { registerGlobalShortcuts } from './shortcut';
|
||||
export { createIpcDepsRuntime, registerIpcHandlers } from './ipc';
|
||||
export { shortcutMatchesInputForLocalFallback } from './shortcut-fallback';
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import electron from 'electron';
|
||||
import type { BrowserWindow as ElectronBrowserWindow, IpcMainEvent } from 'electron';
|
||||
import type {
|
||||
ChangelogSnapshot,
|
||||
CompiledSessionBinding,
|
||||
ControllerConfigUpdate,
|
||||
PlaylistBrowserMutationResult,
|
||||
@@ -122,6 +123,7 @@ export interface IpcServiceDeps {
|
||||
removeCharacterDictionaryManagedEntry?: (mediaId: number) => Promise<unknown>;
|
||||
moveCharacterDictionaryManagedEntry?: (mediaId: number, direction: 1 | -1) => Promise<unknown>;
|
||||
appendClipboardVideoToQueue: () => { ok: boolean; message: string };
|
||||
getChangelogSnapshot?: (options?: { refresh?: boolean }) => Promise<ChangelogSnapshot>;
|
||||
getPlaylistBrowserSnapshot: () => Promise<PlaylistBrowserSnapshot>;
|
||||
appendPlaylistBrowserFile: (filePath: string) => Promise<PlaylistBrowserMutationResult>;
|
||||
playPlaylistBrowserIndex: (index: number) => Promise<PlaylistBrowserMutationResult>;
|
||||
@@ -297,6 +299,7 @@ export interface IpcDepsRuntimeOptions {
|
||||
removeCharacterDictionaryManagedEntry?: (mediaId: number) => Promise<unknown>;
|
||||
moveCharacterDictionaryManagedEntry?: (mediaId: number, direction: 1 | -1) => Promise<unknown>;
|
||||
appendClipboardVideoToQueue: () => { ok: boolean; message: string };
|
||||
getChangelogSnapshot?: (options?: { refresh?: boolean }) => Promise<ChangelogSnapshot>;
|
||||
getPlaylistBrowserSnapshot: () => Promise<PlaylistBrowserSnapshot>;
|
||||
appendPlaylistBrowserFile: (filePath: string) => Promise<PlaylistBrowserMutationResult>;
|
||||
playPlaylistBrowserIndex: (index: number) => Promise<PlaylistBrowserMutationResult>;
|
||||
@@ -418,6 +421,7 @@ export function createIpcDepsRuntime(options: IpcDepsRuntimeOptions): IpcService
|
||||
entries: [],
|
||||
})),
|
||||
appendClipboardVideoToQueue: options.appendClipboardVideoToQueue,
|
||||
getChangelogSnapshot: options.getChangelogSnapshot,
|
||||
getPlaylistBrowserSnapshot: options.getPlaylistBrowserSnapshot,
|
||||
appendPlaylistBrowserFile: options.appendPlaylistBrowserFile,
|
||||
playPlaylistBrowserIndex: options.playPlaylistBrowserIndex,
|
||||
@@ -820,6 +824,17 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
|
||||
return deps.appendClipboardVideoToQueue();
|
||||
});
|
||||
|
||||
ipc.handle(IPC_CHANNELS.request.getChangelogSnapshot, async (_event, payload: unknown) => {
|
||||
const refresh =
|
||||
typeof payload === 'object' && payload !== null && 'refresh' in payload
|
||||
? (payload as { refresh?: unknown }).refresh === true
|
||||
: false;
|
||||
if (!deps.getChangelogSnapshot) {
|
||||
throw new Error('Changelog service is unavailable.');
|
||||
}
|
||||
return await deps.getChangelogSnapshot({ refresh });
|
||||
});
|
||||
|
||||
ipc.handle(IPC_CHANNELS.request.getPlaylistBrowserSnapshot, async () => {
|
||||
return await deps.getPlaylistBrowserSnapshot();
|
||||
});
|
||||
|
||||
@@ -206,7 +206,7 @@ test('runStartupBootstrapRuntime skips lifecycle when generate-config flow handl
|
||||
assert.deepEqual(calls, ['setLog:warn:cli', 'forceX11', 'enforceWayland']);
|
||||
});
|
||||
|
||||
test('runStartupBootstrapRuntime enables quiet background mode by default', () => {
|
||||
test('runStartupBootstrapRuntime lets config govern background log level by default', () => {
|
||||
const calls: string[] = [];
|
||||
const args = makeArgs({ background: true });
|
||||
|
||||
@@ -223,7 +223,7 @@ test('runStartupBootstrapRuntime enables quiet background mode by default', () =
|
||||
});
|
||||
|
||||
assert.equal(result.backgroundMode, true);
|
||||
assert.deepEqual(calls, ['setLog:warn:cli', 'forceX11', 'enforceWayland', 'startLifecycle']);
|
||||
assert.deepEqual(calls, ['forceX11', 'enforceWayland', 'startLifecycle']);
|
||||
});
|
||||
|
||||
test('runStartupBootstrapRuntime enables quiet update mode by default', () => {
|
||||
|
||||
@@ -45,7 +45,7 @@ export function runStartupBootstrapRuntime(
|
||||
|
||||
if (initialArgs.logLevel) {
|
||||
deps.setLogLevel(initialArgs.logLevel, 'cli');
|
||||
} else if (initialArgs.background || initialArgs.update) {
|
||||
} else if (initialArgs.update) {
|
||||
deps.setLogLevel('warn', 'cli');
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
codecToExtension,
|
||||
fileExists,
|
||||
MpvTrack,
|
||||
resolveLocalMediaPath,
|
||||
runCommand,
|
||||
summarizeCommandFailure,
|
||||
} from '../../subsync/utils';
|
||||
@@ -148,10 +149,12 @@ export async function extractSubtitleTrackToFile(
|
||||
input: SubtitleExtractionInput,
|
||||
): Promise<FileExtractionResult> {
|
||||
if (input.track.external) {
|
||||
const externalPath = input.track['external-filename'];
|
||||
if (typeof externalPath !== 'string' || externalPath.length === 0) {
|
||||
const externalFilename = input.track['external-filename'];
|
||||
if (typeof externalFilename !== 'string' || externalFilename.length === 0) {
|
||||
throw new Error('External subtitle track has no file path');
|
||||
}
|
||||
// A dropped subtitle arrives as a `file://` URL, which is local, not remote.
|
||||
const externalPath = resolveLocalMediaPath(externalFilename);
|
||||
if (isRemoteMediaPath(externalPath)) {
|
||||
return downloadRemoteSubtitleTrack(externalPath, input.httpHeaders);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as fs from 'fs';
|
||||
import * as http from 'http';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import { pathToFileURL } from 'url';
|
||||
import { runSubsyncManual } from './subsync';
|
||||
import type { TriggerSubsyncFromConfigDeps } from './subsync';
|
||||
|
||||
@@ -122,3 +123,97 @@ test('runSubsyncManual syncs stream subtitle tracks served over http', async (t)
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Dropping a subtitle onto mpv hands it a `file://` URL, and mpv reports that
|
||||
* URL back as the track's `external-filename`. Reading it as a stream made the
|
||||
* run die with `Protocol "file:" not supported. Expected "http:"`.
|
||||
*/
|
||||
test('runSubsyncManual retimes a dropped file:// track against a stream reference', async (t) => {
|
||||
if (process.platform === 'win32') {
|
||||
t.skip('stub shell scripts are not executable on Windows');
|
||||
return;
|
||||
}
|
||||
|
||||
const host = await startStubHost();
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-file-url-'));
|
||||
const alassLogPath = path.join(tmpDir, 'alass-args.log');
|
||||
const alassPath = path.join(tmpDir, 'alass.sh');
|
||||
fs.writeFileSync(
|
||||
alassPath,
|
||||
`#!/bin/sh\n: > "${alassLogPath}"\nfor arg in "$@"; do printf '%s\\n' "$arg" >> "${alassLogPath}"; done\ncp "$2" "${tmpDir}/target.copy"\nprintf '%s' "retimed" > "$3"\nexit 0\n`,
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
|
||||
// Percent-encoded on purpose: the space and the CJK are what a naive
|
||||
// "strip file://" would leave mangled.
|
||||
const targetPath = path.join(tmpDir, 'ワンピース sdh.srt');
|
||||
const targetBody = '1\n00:00:03,000 --> 00:00:04,000\nドロップ\n';
|
||||
fs.writeFileSync(targetPath, targetBody);
|
||||
const referenceUrl = host.url('/subs/en.srt');
|
||||
const sentCommands: Array<Array<string | number>> = [];
|
||||
|
||||
const deps: Pick<TriggerSubsyncFromConfigDeps, 'getMpvClient' | 'getResolvedConfig'> = {
|
||||
getMpvClient: () => ({
|
||||
connected: true,
|
||||
currentAudioStreamIndex: null,
|
||||
send: (payload) => {
|
||||
sentCommands.push(payload.command);
|
||||
},
|
||||
requestProperty: async (name: string) => {
|
||||
if (name === 'path') return host.url('/stream/video.m3u8');
|
||||
if (name === 'sid') return 2;
|
||||
if (name === 'secondary-sid') return null;
|
||||
if (name === 'track-list') {
|
||||
return [
|
||||
{
|
||||
id: 1,
|
||||
type: 'sub',
|
||||
selected: true,
|
||||
external: true,
|
||||
lang: 'en',
|
||||
'external-filename': referenceUrl,
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
type: 'sub',
|
||||
selected: true,
|
||||
external: true,
|
||||
lang: 'ja',
|
||||
'external-filename': pathToFileURL(targetPath).href,
|
||||
},
|
||||
];
|
||||
}
|
||||
return null;
|
||||
},
|
||||
}),
|
||||
getResolvedConfig: () => ({
|
||||
alassPath,
|
||||
ffsubsyncPath: '',
|
||||
ffmpegPath: path.join(tmpDir, 'no-such-ffmpeg'),
|
||||
replace: true,
|
||||
}),
|
||||
};
|
||||
|
||||
try {
|
||||
const result = await runSubsyncManual(
|
||||
{ engine: 'alass', referenceTrackId: 1, targetTrackId: 2 },
|
||||
deps,
|
||||
);
|
||||
|
||||
assert.equal(result.ok, true, result.message);
|
||||
|
||||
const alassArgs = fs.readFileSync(alassLogPath, 'utf8').trim().split('\n');
|
||||
// The dropped file went in as-is, decoded, and was retimed in place.
|
||||
assert.equal(alassArgs[1], targetPath);
|
||||
assert.equal(fs.readFileSync(path.join(tmpDir, 'target.copy'), 'utf8'), targetBody);
|
||||
assert.equal(alassArgs[2], targetPath);
|
||||
assert.equal(fs.readFileSync(targetPath, 'utf8'), 'retimed');
|
||||
|
||||
const loadCommand = sentCommands.find((command) => command[0] === 'sub-add');
|
||||
assert.equal(loadCommand?.[1], targetPath);
|
||||
} finally {
|
||||
await host.close();
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
formatTrackLabel,
|
||||
getTrackById,
|
||||
MpvTrack,
|
||||
resolveLocalMediaPath,
|
||||
runCommand,
|
||||
summarizeCommandFailure,
|
||||
SubsyncContext,
|
||||
@@ -136,7 +137,9 @@ async function gatherSubsyncContext(client: MpvClientLike): Promise<SubsyncConte
|
||||
client.requestProperty('track-list'),
|
||||
]);
|
||||
|
||||
const videoPath = typeof videoPathRaw === 'string' ? videoPathRaw : '';
|
||||
// A dropped file is reported as a `file://` URL; alass, ffsubsync and ffmpeg
|
||||
// all need the plain path, and the stream checks must not read it as remote.
|
||||
const videoPath = typeof videoPathRaw === 'string' ? resolveLocalMediaPath(videoPathRaw) : '';
|
||||
if (!videoPath) {
|
||||
throw new Error('No video is currently loaded');
|
||||
}
|
||||
|
||||
@@ -74,7 +74,6 @@ test('prefetch service tokenizes priority window cues and caches them', async ()
|
||||
preCacheTokenization: (text, data) => {
|
||||
cached.set(text, data);
|
||||
},
|
||||
isCacheFull: () => false,
|
||||
priorityWindowSize: 3,
|
||||
});
|
||||
|
||||
@@ -91,32 +90,38 @@ test('prefetch service tokenizes priority window cues and caches them', async ()
|
||||
assert.ok(cached.has('line-2'));
|
||||
});
|
||||
|
||||
test('prefetch service stops when cache is full', async () => {
|
||||
test('prefetch service warms every cue even when the cache evicts along the way', async () => {
|
||||
const cues = makeCues(20);
|
||||
let tokenizeCalls = 0;
|
||||
let cacheSize = 0;
|
||||
const tokenized: string[] = [];
|
||||
// Stand-in for the LRU: only the last 5 entries survive, so later cues evict earlier ones.
|
||||
const cache = new Set<string>();
|
||||
|
||||
const service = createSubtitlePrefetchService({
|
||||
cues,
|
||||
tokenizeSubtitle: async (text) => {
|
||||
tokenizeCalls += 1;
|
||||
tokenized.push(text);
|
||||
return { text, tokens: [] };
|
||||
},
|
||||
preCacheTokenization: () => {
|
||||
cacheSize += 1;
|
||||
preCacheTokenization: (text) => {
|
||||
cache.add(text);
|
||||
while (cache.size > 5) {
|
||||
const oldest = cache.values().next().value;
|
||||
if (oldest === undefined) break;
|
||||
cache.delete(oldest);
|
||||
}
|
||||
},
|
||||
isCacheFull: () => cacheSize >= 5,
|
||||
hasCachedTokenization: (text) => cache.has(text),
|
||||
priorityWindowSize: 3,
|
||||
});
|
||||
|
||||
service.start(0);
|
||||
for (let i = 0; i < 30; i += 1) {
|
||||
for (let i = 0; i < 60; i += 1) {
|
||||
await flushMicrotasks();
|
||||
}
|
||||
service.stop();
|
||||
|
||||
// Should have stopped at 5 (cache full), not tokenized all 20
|
||||
assert.ok(tokenizeCalls <= 6, `Expected <= 6 tokenize calls, got ${tokenizeCalls}`);
|
||||
assert.equal(tokenized.length, 20, `Expected all 20 cues warmed, got ${tokenized.length}`);
|
||||
assert.equal(new Set(tokenized).size, 20, 'Each cue is tokenized at most once per run');
|
||||
});
|
||||
|
||||
test('prefetch service can be stopped mid-flight', async () => {
|
||||
@@ -130,7 +135,6 @@ test('prefetch service can be stopped mid-flight', async () => {
|
||||
return { text, tokens: [] };
|
||||
},
|
||||
preCacheTokenization: () => {},
|
||||
isCacheFull: () => false,
|
||||
priorityWindowSize: 3,
|
||||
});
|
||||
|
||||
@@ -159,7 +163,6 @@ test('prefetch service onSeek re-prioritizes from new position', async () => {
|
||||
preCacheTokenization: (text) => {
|
||||
cachedTexts.push(text);
|
||||
},
|
||||
isCacheFull: () => false,
|
||||
priorityWindowSize: 3,
|
||||
});
|
||||
|
||||
@@ -183,7 +186,7 @@ test('prefetch service onSeek re-prioritizes from new position', async () => {
|
||||
assert.ok(hasPostSeekCue, 'Should have cached cues after seek position');
|
||||
});
|
||||
|
||||
test('prefetch service still warms the priority window when cache is full', async () => {
|
||||
test('prefetch service warms the priority window ahead of the rest of the file', async () => {
|
||||
const cues = makeCues(20);
|
||||
const cachedTexts: string[] = [];
|
||||
|
||||
@@ -193,7 +196,6 @@ test('prefetch service still warms the priority window when cache is full', asyn
|
||||
preCacheTokenization: (text) => {
|
||||
cachedTexts.push(text);
|
||||
},
|
||||
isCacheFull: () => true,
|
||||
priorityWindowSize: 3,
|
||||
});
|
||||
|
||||
@@ -217,7 +219,6 @@ test('prefetch service pause/resume halts and continues tokenization', async ()
|
||||
return { text, tokens: [] };
|
||||
},
|
||||
preCacheTokenization: () => {},
|
||||
isCacheFull: () => false,
|
||||
priorityWindowSize: 3,
|
||||
});
|
||||
|
||||
@@ -255,7 +256,6 @@ test('prefetch service skips cues already present in tokenization cache', async
|
||||
},
|
||||
preCacheTokenization: () => {},
|
||||
hasCachedTokenization: (text) => text === 'line-0' || text === 'line-1',
|
||||
isCacheFull: () => false,
|
||||
priorityWindowSize: 3,
|
||||
});
|
||||
|
||||
@@ -285,7 +285,6 @@ test('prefetch service deduplicates repeated cue text within a run', async () =>
|
||||
return { text, tokens: [] };
|
||||
},
|
||||
preCacheTokenization: () => {},
|
||||
isCacheFull: () => false,
|
||||
priorityWindowSize: 3,
|
||||
});
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ export interface SubtitlePrefetchServiceDeps {
|
||||
tokenizeSubtitle: (text: string) => Promise<SubtitleData | null>;
|
||||
preCacheTokenization: (text: string, data: SubtitleData) => void;
|
||||
hasCachedTokenization?: (text: string) => boolean;
|
||||
isCacheFull: () => boolean;
|
||||
priorityWindowSize?: number;
|
||||
}
|
||||
|
||||
@@ -57,11 +56,14 @@ export function createSubtitlePrefetchService(
|
||||
let paused = false;
|
||||
let currentRunId = 0;
|
||||
|
||||
// A run is a single bounded pass over one file's cues, deduped by `warmedKeys` and by
|
||||
// `hasCachedTokenization`, so the worst case is one tokenization per cue. The cache is
|
||||
// an LRU and bounds its own memory, so a full cache is not a reason to stop warming;
|
||||
// stopping there used to leave the tail of longer media permanently uncached.
|
||||
async function tokenizeCueList(
|
||||
cuesToProcess: SubtitleCue[],
|
||||
runId: number,
|
||||
warmedKeys: Set<string>,
|
||||
options: { allowWhenCacheFull?: boolean } = {},
|
||||
): Promise<void> {
|
||||
for (const cue of cuesToProcess) {
|
||||
if (stopped || runId !== currentRunId) {
|
||||
@@ -77,10 +79,6 @@ export function createSubtitlePrefetchService(
|
||||
return;
|
||||
}
|
||||
|
||||
if (!options.allowWhenCacheFull && deps.isCacheFull()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cacheKey = normalizeSubtitleCacheKey(cue.text);
|
||||
if (!cacheKey || warmedKeys.has(cacheKey) || deps.hasCachedTokenization?.(cue.text)) {
|
||||
if (cacheKey) {
|
||||
@@ -110,7 +108,7 @@ export function createSubtitlePrefetchService(
|
||||
|
||||
// Phase 1: Priority window
|
||||
const priorityCues = computePriorityWindow(cues, currentTimeSeconds, windowSize);
|
||||
await tokenizeCueList(priorityCues, runId, warmedKeys, { allowWhenCacheFull: true });
|
||||
await tokenizeCueList(priorityCues, runId, warmedKeys);
|
||||
|
||||
if (stopped || runId !== currentRunId) {
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { SubtitleData } from '../../types';
|
||||
import { createSubtitleProcessingController } from './subtitle-processing-controller';
|
||||
|
||||
function flushMicrotasks(): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
test('new subtitle emits plain immediately without parallel tokenization or a stale overwrite', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
const resolvers = new Map<string, (value: SubtitleData | null) => void>();
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) =>
|
||||
await new Promise<SubtitleData | null>((resolve) => {
|
||||
resolvers.set(text, resolve);
|
||||
}),
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
controller.onSubtitleChange('first');
|
||||
controller.onSubtitleChange('second');
|
||||
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: 'first', tokens: null },
|
||||
{ text: 'second', tokens: null },
|
||||
]);
|
||||
assert.equal(resolvers.has('second'), false);
|
||||
|
||||
const resolveFirst = resolvers.get('first');
|
||||
assert.ok(resolveFirst);
|
||||
resolveFirst({ text: 'first', tokens: [] });
|
||||
await flushMicrotasks();
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: 'first', tokens: null },
|
||||
{ text: 'second', tokens: null },
|
||||
]);
|
||||
assert.equal(resolvers.has('second'), true);
|
||||
|
||||
const resolveSecond = resolvers.get('second');
|
||||
assert.ok(resolveSecond);
|
||||
resolveSecond({ text: 'second', tokens: [] });
|
||||
await flushMicrotasks();
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: 'first', tokens: null },
|
||||
{ text: 'second', tokens: null },
|
||||
{ text: 'second', tokens: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
test('subtitle clears immediately while previous tokenization remains pending', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
let resolveTokenization: ((value: SubtitleData | null) => void) | undefined;
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async () =>
|
||||
await new Promise<SubtitleData | null>((resolve) => {
|
||||
resolveTokenization = resolve;
|
||||
}),
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
controller.onSubtitleChange('first');
|
||||
controller.onSubtitleChange('');
|
||||
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: 'first', tokens: null },
|
||||
{ text: '', tokens: null },
|
||||
]);
|
||||
|
||||
assert.ok(resolveTokenization);
|
||||
resolveTokenization({ text: 'first', tokens: [] });
|
||||
await flushMicrotasks();
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: 'first', tokens: null },
|
||||
{ text: '', tokens: null },
|
||||
]);
|
||||
});
|
||||
|
||||
test('returning to an uncached completed line emits it while another line is pending', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
let resolvePending: ((value: SubtitleData | null) => void) | undefined;
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => {
|
||||
if (text === 'A') {
|
||||
return { text, tokens: [] };
|
||||
}
|
||||
return await new Promise<SubtitleData | null>((resolve) => {
|
||||
resolvePending = resolve;
|
||||
});
|
||||
},
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
controller.onSubtitleChange('A');
|
||||
await flushMicrotasks();
|
||||
controller.invalidateTokenizationCache();
|
||||
controller.onSubtitleChange('B');
|
||||
controller.onSubtitleChange('A');
|
||||
|
||||
assert.deepEqual(emitted.at(-1), { text: 'A', tokens: null });
|
||||
assert.ok(resolvePending);
|
||||
resolvePending({ text: 'B', tokens: [] });
|
||||
});
|
||||
|
||||
test('ABA subtitle changes reuse the matching first tokenization only after A is current again', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
const tokenizeCalls: string[] = [];
|
||||
const resolvers: Array<(value: SubtitleData | null) => void> = [];
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => {
|
||||
tokenizeCalls.push(text);
|
||||
return await new Promise<SubtitleData | null>((resolve) => {
|
||||
resolvers.push(resolve);
|
||||
});
|
||||
},
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
controller.onSubtitleChange('A');
|
||||
controller.onSubtitleChange('B');
|
||||
controller.onSubtitleChange('A');
|
||||
const resolveFirst = resolvers[0];
|
||||
assert.ok(resolveFirst);
|
||||
resolveFirst({ text: 'A', tokens: [{ value: 1 } as never] });
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.deepEqual(tokenizeCalls, ['A']);
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: 'A', tokens: null },
|
||||
{ text: 'B', tokens: null },
|
||||
{ text: 'A', tokens: null },
|
||||
{ text: 'A', tokens: [{ value: 1 } as never] },
|
||||
]);
|
||||
});
|
||||
|
||||
test('cached next subtitle does not downgrade to plain while processing is busy', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
let resolveTokenization: ((value: SubtitleData | null) => void) | undefined;
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) =>
|
||||
await new Promise<SubtitleData | null>((resolve) => {
|
||||
resolveTokenization = () => resolve({ text, tokens: [] });
|
||||
}),
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
controller.preCacheTokenization('cached', { text: 'cached', tokens: [] });
|
||||
controller.onSubtitleChange('pending');
|
||||
controller.onSubtitleChange('cached');
|
||||
|
||||
assert.deepEqual(emitted, [{ text: 'pending', tokens: null }]);
|
||||
assert.ok(resolveTokenization);
|
||||
resolveTokenization({ text: 'pending', tokens: [] });
|
||||
await flushMicrotasks();
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: 'pending', tokens: null },
|
||||
{ text: 'cached', tokens: [] },
|
||||
]);
|
||||
});
|
||||
@@ -7,18 +7,138 @@ function flushMicrotasks(): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
test('subtitle processing emits tokenized payload when tokenization succeeds', async () => {
|
||||
test('subtitle processing emits plain payload immediately on cache miss, then tokenized payload', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => ({ text, tokens: [] }),
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
controller.onSubtitleChange('字幕');
|
||||
assert.deepEqual(emitted, [{ text: '字幕', tokens: null }]);
|
||||
await flushMicrotasks();
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: '字幕', tokens: null },
|
||||
{ text: '字幕', tokens: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
test('cache invalidation during pending tokenization does not re-emit the plain payload', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
const resolvers: Array<(value: SubtitleData | null) => void> = [];
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) =>
|
||||
await new Promise<SubtitleData | null>((resolve) => {
|
||||
resolvers.push(() => resolve({ text, tokens: [{ value: resolvers.length } as never] }));
|
||||
}),
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
controller.onSubtitleChange('行');
|
||||
assert.deepEqual(emitted, [{ text: '行', tokens: null }]);
|
||||
|
||||
controller.invalidateTokenizationCache();
|
||||
resolvers[0]?.({ text: '行', tokens: [] });
|
||||
await flushMicrotasks();
|
||||
// Retry for the new generation is now pending; still no duplicate plain emit.
|
||||
assert.deepEqual(emitted, [{ text: '行', tokens: null }]);
|
||||
|
||||
resolvers[1]?.({ text: '行', tokens: [] });
|
||||
await flushMicrotasks();
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: '行', tokens: null },
|
||||
{ text: '行', tokens: [{ value: 2 } as never] },
|
||||
]);
|
||||
});
|
||||
|
||||
test('failed refresh does not downgrade an already emitted tokenized subtitle', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
let tokenizeCalls = 0;
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => {
|
||||
tokenizeCalls += 1;
|
||||
if (tokenizeCalls > 1) {
|
||||
throw new Error('tokenizer gone');
|
||||
}
|
||||
return { text, tokens: [] };
|
||||
},
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
controller.onSubtitleChange('行');
|
||||
await flushMicrotasks();
|
||||
controller.invalidateTokenizationCache();
|
||||
controller.refreshCurrentSubtitle();
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(tokenizeCalls, 2);
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: '行', tokens: null },
|
||||
{ text: '行', tokens: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
test('null-tokenization refresh does not downgrade an already emitted tokenized subtitle', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
let tokenizeCalls = 0;
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => {
|
||||
tokenizeCalls += 1;
|
||||
return tokenizeCalls > 1 ? null : { text, tokens: [] };
|
||||
},
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
controller.onSubtitleChange('行');
|
||||
await flushMicrotasks();
|
||||
controller.invalidateTokenizationCache();
|
||||
controller.refreshCurrentSubtitle();
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(tokenizeCalls, 2);
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: '行', tokens: null },
|
||||
{ text: '行', tokens: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
test('subtitle processing does not emit plain payload for cached lines', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => ({ text, tokens: [] }),
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
controller.preCacheTokenization('字幕', { text: '字幕', tokens: [] });
|
||||
controller.onSubtitleChange('字幕');
|
||||
await flushMicrotasks();
|
||||
assert.deepEqual(emitted, [{ text: '字幕', tokens: [] }]);
|
||||
});
|
||||
|
||||
test('subtitle processing shows plain line while tokenization is still pending', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
let resolveTokenization: ((value: SubtitleData | null) => void) | undefined;
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) =>
|
||||
await new Promise<SubtitleData | null>((resolve) => {
|
||||
resolveTokenization = () => resolve({ text, tokens: [] });
|
||||
}),
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
controller.onSubtitleChange('遅い行');
|
||||
await flushMicrotasks();
|
||||
assert.deepEqual(emitted, [{ text: '遅い行', tokens: null }]);
|
||||
|
||||
assert.ok(resolveTokenization);
|
||||
resolveTokenization({ text: '遅い行', tokens: [] });
|
||||
await flushMicrotasks();
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: '遅い行', tokens: null },
|
||||
{ text: '遅い行', tokens: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
test('subtitle processing drops stale tokenization and delivers latest subtitle only once', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
let firstResolve: ((value: SubtitleData | null) => void) | undefined;
|
||||
@@ -41,7 +161,11 @@ test('subtitle processing drops stale tokenization and delivers latest subtitle
|
||||
await flushMicrotasks();
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.deepEqual(emitted, [{ text: 'second', tokens: [] }]);
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: 'first', tokens: null },
|
||||
{ text: 'second', tokens: null },
|
||||
{ text: 'second', tokens: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
test('subtitle processing skips duplicate subtitle emission', async () => {
|
||||
@@ -60,7 +184,10 @@ test('subtitle processing skips duplicate subtitle emission', async () => {
|
||||
controller.onSubtitleChange('same');
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(emitted.length, 1);
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: 'same', tokens: null },
|
||||
{ text: 'same', tokens: [] },
|
||||
]);
|
||||
assert.equal(tokenizeCalls, 1);
|
||||
});
|
||||
|
||||
@@ -84,7 +211,9 @@ test('subtitle processing reuses cached tokenization for repeated subtitle text'
|
||||
|
||||
assert.equal(tokenizeCalls, 2);
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: 'first', tokens: null },
|
||||
{ text: 'first', tokens: [] },
|
||||
{ text: 'second', tokens: null },
|
||||
{ text: 'second', tokens: [] },
|
||||
{ text: 'first', tokens: [] },
|
||||
]);
|
||||
@@ -100,7 +229,48 @@ test('subtitle processing falls back to plain subtitle when tokenization returns
|
||||
controller.onSubtitleChange('fallback');
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.deepEqual(
|
||||
emitted,
|
||||
[{ text: 'fallback', tokens: null }],
|
||||
'plain payload should not be re-emitted when tokenization yields nothing new',
|
||||
);
|
||||
});
|
||||
|
||||
test('null tokenization is not cached and a later cue retries tokenization', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
const callsByText = new Map<string, number>();
|
||||
let failNext = true;
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => {
|
||||
callsByText.set(text, (callsByText.get(text) ?? 0) + 1);
|
||||
if (text === 'fallback' && failNext) {
|
||||
failNext = false;
|
||||
return null;
|
||||
}
|
||||
return { text, tokens: [] };
|
||||
},
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
controller.onSubtitleChange('fallback');
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(callsByText.get('fallback'), 1);
|
||||
assert.equal(
|
||||
controller.hasCachedSubtitle('fallback'),
|
||||
false,
|
||||
'plain fallback must not be cached when tokenization yields nothing',
|
||||
);
|
||||
assert.deepEqual(emitted, [{ text: 'fallback', tokens: null }]);
|
||||
|
||||
controller.onSubtitleChange('other');
|
||||
await flushMicrotasks();
|
||||
controller.onSubtitleChange('fallback');
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(callsByText.get('fallback'), 2, 'later cue should retry tokenization');
|
||||
assert.equal(controller.hasCachedSubtitle('fallback'), true);
|
||||
assert.deepEqual(emitted.at(-1), { text: 'fallback', tokens: [] });
|
||||
});
|
||||
|
||||
test('subtitle processing ignores duplicate current subtitle refresh without cache invalidation', async () => {
|
||||
@@ -120,7 +290,10 @@ test('subtitle processing ignores duplicate current subtitle refresh without cac
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(tokenizeCalls, 1);
|
||||
assert.deepEqual(emitted, [{ text: 'same', tokens: [] }]);
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: 'same', tokens: null },
|
||||
{ text: 'same', tokens: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
test('subtitle processing coalesces refresh requests while current subtitle is processing', async () => {
|
||||
@@ -146,7 +319,10 @@ test('subtitle processing coalesces refresh requests while current subtitle is p
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(tokenizeCalls, 1);
|
||||
assert.deepEqual(emitted, [{ text: 'same', tokens: [] }]);
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: 'same', tokens: null },
|
||||
{ text: 'same', tokens: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
test('subtitle processing refresh re-tokenizes after cache invalidation', async () => {
|
||||
@@ -168,6 +344,7 @@ test('subtitle processing refresh re-tokenizes after cache invalidation', async
|
||||
|
||||
assert.equal(tokenizeCalls, 2);
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: 'same', tokens: null },
|
||||
{ text: 'same', tokens: [{ value: 1 } as never] },
|
||||
{ text: 'same', tokens: [{ value: 2 } as never] },
|
||||
]);
|
||||
@@ -183,7 +360,10 @@ test('subtitle processing refresh can use explicit text override', async () => {
|
||||
controller.refreshCurrentSubtitle('initial');
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.deepEqual(emitted, [{ text: 'initial', tokens: [] }]);
|
||||
assert.deepEqual(emitted, [
|
||||
{ text: 'initial', tokens: null },
|
||||
{ text: 'initial', tokens: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
test('subtitle processing cache invalidation only affects future subtitle events', async () => {
|
||||
@@ -205,10 +385,10 @@ test('subtitle processing cache invalidation only affects future subtitle events
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(callsByText.get('same'), 1);
|
||||
assert.equal(emitted.length, 3);
|
||||
assert.equal(emitted.length, 5);
|
||||
|
||||
controller.invalidateTokenizationCache();
|
||||
assert.equal(emitted.length, 3);
|
||||
assert.equal(emitted.length, 5);
|
||||
|
||||
controller.onSubtitleChange('different');
|
||||
await flushMicrotasks();
|
||||
@@ -308,25 +488,176 @@ test('hasCachedSubtitle checks prefetched entries without consuming them', async
|
||||
assert.equal(controller.hasCachedSubtitle('猫\nです'), false);
|
||||
});
|
||||
|
||||
test('isCacheFull returns false when cache is below limit', () => {
|
||||
test('cache keeps every entry while below the limit', () => {
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => ({ text, tokens: null }),
|
||||
tokenizeSubtitle: async (text) => ({ text, tokens: [] }),
|
||||
emitSubtitle: () => {},
|
||||
cacheLimit: 8,
|
||||
});
|
||||
|
||||
assert.equal(controller.isCacheFull(), false);
|
||||
for (let i = 0; i < 8; i += 1) {
|
||||
controller.preCacheTokenization(`line-${i}`, { text: `line-${i}`, tokens: [] });
|
||||
}
|
||||
|
||||
assert.deepEqual(
|
||||
Array.from({ length: 8 }, (_, i) => controller.hasCachedSubtitle(`line-${i}`)),
|
||||
Array.from({ length: 8 }, () => true),
|
||||
);
|
||||
});
|
||||
|
||||
test('isCacheFull returns true when cache reaches limit', async () => {
|
||||
test('cache evicts least recently used entries once the limit is reached', () => {
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => ({ text, tokens: [] }),
|
||||
emitSubtitle: () => {},
|
||||
cacheLimit: 3,
|
||||
});
|
||||
|
||||
for (const line of ['a', 'b', 'c']) {
|
||||
controller.preCacheTokenization(line, { text: line, tokens: [] });
|
||||
}
|
||||
// Touching 'a' makes 'b' the eviction candidate.
|
||||
controller.consumeCachedSubtitle('a');
|
||||
controller.preCacheTokenization('d', { text: 'd', tokens: [] });
|
||||
|
||||
assert.equal(controller.hasCachedSubtitle('b'), false);
|
||||
assert.deepEqual(
|
||||
['a', 'c', 'd'].map((line) => controller.hasCachedSubtitle(line)),
|
||||
[true, true, true],
|
||||
);
|
||||
});
|
||||
|
||||
test('default cache limit covers a full-length title without evicting', () => {
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => ({ text, tokens: [] }),
|
||||
emitSubtitle: () => {},
|
||||
});
|
||||
|
||||
// Fill cache to the 256 limit
|
||||
for (let i = 0; i < 256; i += 1) {
|
||||
for (let i = 0; i < 2000; i += 1) {
|
||||
controller.preCacheTokenization(`line-${i}`, { text: `line-${i}`, tokens: [] });
|
||||
}
|
||||
|
||||
assert.equal(controller.isCacheFull(), true);
|
||||
assert.equal(controller.hasCachedSubtitle('line-0'), true);
|
||||
assert.equal(controller.hasCachedSubtitle('line-1999'), true);
|
||||
});
|
||||
|
||||
test('onSubtitleChange reports whether processing was scheduled', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => ({ text, tokens: [] }),
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
// New text schedules work, so an emit (and anything gated on it) will follow.
|
||||
assert.equal(controller.onSubtitleChange('字幕'), true);
|
||||
await flushMicrotasks();
|
||||
|
||||
// A repeat emits nothing, so callers must not wait on an emit that is never
|
||||
// coming (subtitle prefetching would stay paused for the rest of the cue).
|
||||
const emittedCount = emitted.length;
|
||||
assert.equal(controller.onSubtitleChange('字幕'), false);
|
||||
await flushMicrotasks();
|
||||
assert.equal(emitted.length, emittedCount);
|
||||
});
|
||||
|
||||
test('refreshCurrentSubtitle reports the empty-text emit that an in-flight run will deliver', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
let resolveFirst: ((value: SubtitleData | null) => void) | undefined;
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => {
|
||||
if (text === '字幕') {
|
||||
return await new Promise<SubtitleData | null>((resolve) => {
|
||||
resolveFirst = resolve;
|
||||
});
|
||||
}
|
||||
return { text, tokens: [] };
|
||||
},
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
controller.onSubtitleChange('字幕');
|
||||
await flushMicrotasks();
|
||||
|
||||
// Clearing the subtitle while tokenization is in flight: the running loop
|
||||
// picks the empty text up and emits it, so callers gated on that emit (the
|
||||
// prefetch pause) must be told one is coming.
|
||||
assert.equal(controller.refreshCurrentSubtitle(''), true);
|
||||
|
||||
resolveFirst?.({ text: '字幕', tokens: [] });
|
||||
await flushMicrotasks();
|
||||
await flushMicrotasks();
|
||||
// '字幕' is the provisional plain emit the in-flight run already made before
|
||||
// the refresh; '' is the emit the refresh promised.
|
||||
assert.deepEqual(
|
||||
emitted.map((payload) => payload.text),
|
||||
['字幕', ''],
|
||||
);
|
||||
});
|
||||
|
||||
test('onProcessingSettled fires once after the queue drains, including runs that emit nothing', async () => {
|
||||
const events: string[] = [];
|
||||
let resolveFirst: ((value: SubtitleData | null) => void) | undefined;
|
||||
let tokenizationFails = false;
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => {
|
||||
if (tokenizationFails) {
|
||||
return null;
|
||||
}
|
||||
if (text === '一行目') {
|
||||
return await new Promise<SubtitleData | null>((resolve) => {
|
||||
resolveFirst = resolve;
|
||||
});
|
||||
}
|
||||
return { text, tokens: [] };
|
||||
},
|
||||
emitSubtitle: (payload) => events.push(`emit:${payload.text}`),
|
||||
onProcessingSettled: () => events.push('settled'),
|
||||
});
|
||||
|
||||
controller.onSubtitleChange('一行目');
|
||||
await flushMicrotasks();
|
||||
// A second line arrives before the first finishes: the controller still has
|
||||
// work, so it must not report itself settled between the two.
|
||||
controller.onSubtitleChange('二行目');
|
||||
resolveFirst?.({ text: '一行目', tokens: [] });
|
||||
await flushMicrotasks();
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.deepEqual(events, ['emit:一行目', 'emit:二行目', 'emit:二行目', 'settled']);
|
||||
|
||||
// Tokenization failure on a line already shown plain: nothing is emitted, and
|
||||
// the settle signal is the only way a caller learns the work is over.
|
||||
events.length = 0;
|
||||
tokenizationFails = true;
|
||||
controller.invalidateTokenizationCache();
|
||||
assert.equal(controller.refreshCurrentSubtitle('二行目'), true);
|
||||
await flushMicrotasks();
|
||||
await flushMicrotasks();
|
||||
assert.deepEqual(events, ['settled']);
|
||||
});
|
||||
|
||||
test('notePlainSubtitleEmitted suppresses the controller repeat of a payload already shown', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => ({ text, tokens: [] }),
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
// Autoplay priming paints the plain line itself, then asks for tokenization.
|
||||
controller.notePlainSubtitleEmitted('字幕');
|
||||
controller.refreshCurrentSubtitle('字幕');
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.deepEqual(emitted, [{ text: '字幕', tokens: [] }]);
|
||||
});
|
||||
|
||||
test('refreshCurrentSubtitle reports no emit for empty text when nothing is running', async () => {
|
||||
const emitted: SubtitleData[] = [];
|
||||
const controller = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (text) => ({ text, tokens: [] }),
|
||||
emitSubtitle: (payload) => emitted.push(payload),
|
||||
});
|
||||
|
||||
assert.equal(controller.refreshCurrentSubtitle(''), false);
|
||||
await flushMicrotasks();
|
||||
assert.deepEqual(emitted, []);
|
||||
});
|
||||
@@ -3,18 +3,48 @@ import type { SubtitleData } from '../../types';
|
||||
export interface SubtitleProcessingControllerDeps {
|
||||
tokenizeSubtitle: (text: string) => Promise<SubtitleData | null>;
|
||||
emitSubtitle: (payload: SubtitleData) => void;
|
||||
/**
|
||||
* Fires when the controller runs out of work: every scheduled line has been
|
||||
* processed, whether it ended in an emit, a suppressed duplicate, or a
|
||||
* tokenizer failure. Callers that hold a resource for the duration of
|
||||
* processing (prefetch pausing) release it here rather than on an emit,
|
||||
* which is not guaranteed to happen.
|
||||
*/
|
||||
onProcessingSettled?: () => void;
|
||||
logDebug?: (message: string) => void;
|
||||
now?: () => number;
|
||||
cacheLimit?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure memory bound on the LRU, not a coverage limit: prefetching runs to the end of a
|
||||
* file regardless of cache pressure. Sized to hold a feature-length title (a 24-minute
|
||||
* episode runs 300-400 lines, a 2-hour film ~2000) plus room for lines that repeat across
|
||||
* episodes of a series, so openings and endings stay warm between titles.
|
||||
*/
|
||||
export const DEFAULT_SUBTITLE_TOKENIZATION_CACHE_LIMIT = 2500;
|
||||
|
||||
export interface SubtitleProcessingController {
|
||||
onSubtitleChange: (text: string) => void;
|
||||
refreshCurrentSubtitle: (textOverride?: string) => void;
|
||||
/**
|
||||
* Returns whether processing is now scheduled or already in flight for this
|
||||
* event. A false return means the controller is idle and will do nothing, so
|
||||
* onProcessingSettled will not fire; callers that pause work for the duration
|
||||
* of processing (such as subtitle prefetching) must release it themselves.
|
||||
*/
|
||||
onSubtitleChange: (text: string) => boolean;
|
||||
/** Same contract as onSubtitleChange: whether processing is pending. */
|
||||
refreshCurrentSubtitle: (textOverride?: string) => boolean;
|
||||
/**
|
||||
* Records that this exact text has already been shown plain by someone else
|
||||
* (autoplay priming paints its first frame before scheduling tokenization),
|
||||
* so the controller does not repeat that payload on its way to the tokenized
|
||||
* one.
|
||||
*/
|
||||
notePlainSubtitleEmitted: (text: string) => void;
|
||||
invalidateTokenizationCache: () => void;
|
||||
preCacheTokenization: (text: string, data: SubtitleData) => void;
|
||||
consumeCachedSubtitle: (text: string) => SubtitleData | null;
|
||||
hasCachedSubtitle: (text: string) => boolean;
|
||||
isCacheFull: () => boolean;
|
||||
}
|
||||
|
||||
export function normalizeSubtitleCacheKey(text: string): string {
|
||||
@@ -24,9 +54,15 @@ export function normalizeSubtitleCacheKey(text: string): string {
|
||||
export function createSubtitleProcessingController(
|
||||
deps: SubtitleProcessingControllerDeps,
|
||||
): SubtitleProcessingController {
|
||||
const SUBTITLE_TOKENIZATION_CACHE_LIMIT = 256;
|
||||
const SUBTITLE_TOKENIZATION_CACHE_LIMIT =
|
||||
deps.cacheLimit && deps.cacheLimit > 0
|
||||
? deps.cacheLimit
|
||||
: DEFAULT_SUBTITLE_TOKENIZATION_CACHE_LIMIT;
|
||||
let latestText = '';
|
||||
let lastEmittedText = '';
|
||||
// Tracks the latest provisional plain emit across rapid changes and loop retries
|
||||
// so the same line is never shown plain twice.
|
||||
let lastPlainEmittedText: string | null = null;
|
||||
let cacheGeneration = 0;
|
||||
let lastEmittedGeneration = 0;
|
||||
let processing = false;
|
||||
@@ -70,9 +106,12 @@ export function createSubtitleProcessingController(
|
||||
const startedAtMs = now();
|
||||
|
||||
if (!text.trim()) {
|
||||
deps.emitSubtitle({ text, tokens: null });
|
||||
if (lastPlainEmittedText !== text) {
|
||||
deps.emitSubtitle({ text, tokens: null });
|
||||
}
|
||||
lastEmittedText = text;
|
||||
lastEmittedGeneration = generation;
|
||||
lastPlainEmittedText = null;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -82,11 +121,25 @@ export function createSubtitleProcessingController(
|
||||
if (cachedTokenized) {
|
||||
output = cachedTokenized;
|
||||
} else {
|
||||
// Cache miss: show the plain line on time; the tokenized payload
|
||||
// upgrades it once ready. Skipped on refreshes of an already
|
||||
// emitted line so downstream consumers never see a downgrade.
|
||||
if (text !== lastEmittedText && text !== lastPlainEmittedText) {
|
||||
deps.emitSubtitle({ text, tokens: null });
|
||||
lastPlainEmittedText = text;
|
||||
}
|
||||
const tokenized = await deps.tokenizeSubtitle(text);
|
||||
// A null result is a transient tokenizer failure, not a verdict on
|
||||
// the line: caching the plain fallback would pin it untokenized for
|
||||
// every later occurrence.
|
||||
if (tokenized) {
|
||||
output = tokenized;
|
||||
// A result computed before an invalidation must not repopulate the
|
||||
// fresh cache, or the retry below would serve the stale entry.
|
||||
if (generation === cacheGeneration) {
|
||||
setCachedTokenization(text, tokenized);
|
||||
}
|
||||
}
|
||||
setCachedTokenization(text, output);
|
||||
}
|
||||
} catch (error) {
|
||||
deps.logDebug?.(`Subtitle tokenization failed: ${(error as Error).message}`);
|
||||
@@ -107,9 +160,16 @@ export function createSubtitleProcessingController(
|
||||
continue;
|
||||
}
|
||||
|
||||
deps.emitSubtitle(output);
|
||||
// An untokenized result adds nothing when this line was already shown,
|
||||
// either provisionally or as an earlier full emit (failed refresh) —
|
||||
// emitting it would duplicate or downgrade what is on screen.
|
||||
const plainAlreadyShown = lastPlainEmittedText === text || lastEmittedText === text;
|
||||
if (!(output.tokens === null && output.text === text && plainAlreadyShown)) {
|
||||
deps.emitSubtitle(output);
|
||||
}
|
||||
lastEmittedText = text;
|
||||
lastEmittedGeneration = generation;
|
||||
lastPlainEmittedText = null;
|
||||
deps.logDebug?.(
|
||||
`Subtitle tokenization delivered; elapsed=${now() - startedAtMs}ms, staleDrops=${staleDropCount}`,
|
||||
);
|
||||
@@ -126,32 +186,53 @@ export function createSubtitleProcessingController(
|
||||
(latestText.trim() && cacheGeneration !== lastEmittedGeneration)
|
||||
) {
|
||||
processLatest();
|
||||
return;
|
||||
}
|
||||
// Nothing left to do: signal completion even when this run emitted
|
||||
// nothing (suppressed duplicate, tokenizer failure), or callers waiting
|
||||
// on the controller would wait forever.
|
||||
deps.onProcessingSettled?.();
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
onSubtitleChange: (text: string) => {
|
||||
if (text === latestText) {
|
||||
return;
|
||||
// A run already in flight for this text will still emit for it.
|
||||
return processing;
|
||||
}
|
||||
latestText = text;
|
||||
if (
|
||||
processing &&
|
||||
text !== lastPlainEmittedText &&
|
||||
!tokenizationCache.has(normalizeSubtitleCacheKey(text))
|
||||
) {
|
||||
deps.emitSubtitle({ text, tokens: null });
|
||||
lastPlainEmittedText = text;
|
||||
}
|
||||
processLatest();
|
||||
return true;
|
||||
},
|
||||
refreshCurrentSubtitle: (textOverride?: string) => {
|
||||
if (typeof textOverride === 'string') {
|
||||
latestText = textOverride;
|
||||
}
|
||||
if (!latestText.trim()) {
|
||||
return;
|
||||
// A run in flight will pick this up and emit the empty subtitle, so
|
||||
// the caller is still waiting on an emit.
|
||||
return processing;
|
||||
}
|
||||
if (
|
||||
processing ||
|
||||
(latestText === lastEmittedText && cacheGeneration === lastEmittedGeneration)
|
||||
) {
|
||||
return;
|
||||
if (processing) {
|
||||
return true;
|
||||
}
|
||||
if (latestText === lastEmittedText && cacheGeneration === lastEmittedGeneration) {
|
||||
return false;
|
||||
}
|
||||
processLatest();
|
||||
return true;
|
||||
},
|
||||
notePlainSubtitleEmitted: (text: string) => {
|
||||
lastPlainEmittedText = text;
|
||||
},
|
||||
invalidateTokenizationCache: () => {
|
||||
tokenizationCache.clear();
|
||||
@@ -169,13 +250,11 @@ export function createSubtitleProcessingController(
|
||||
latestText = text;
|
||||
lastEmittedText = text;
|
||||
lastEmittedGeneration = cacheGeneration;
|
||||
lastPlainEmittedText = null;
|
||||
return cached;
|
||||
},
|
||||
hasCachedSubtitle: (text: string) => {
|
||||
return tokenizationCache.has(normalizeSubtitleCacheKey(text));
|
||||
},
|
||||
isCacheFull: () => {
|
||||
return tokenizationCache.size >= SUBTITLE_TOKENIZATION_CACHE_LIMIT;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
isSubtitleAnnotationUpgrade,
|
||||
serializeInitialSubtitleWebsocketMessage,
|
||||
serializeSubtitleMarkup,
|
||||
serializeSubtitleWebsocketMessage,
|
||||
@@ -13,6 +14,40 @@ const frequencyOptions = {
|
||||
mode: 'banded' as const,
|
||||
};
|
||||
|
||||
test('annotation upgrade requires matching text and cue timing', () => {
|
||||
const current: SubtitleData = {
|
||||
text: '字幕',
|
||||
tokens: null,
|
||||
startTime: 10,
|
||||
endTime: 12,
|
||||
};
|
||||
|
||||
assert.equal(
|
||||
isSubtitleAnnotationUpgrade(current, {
|
||||
...current,
|
||||
tokens: [],
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isSubtitleAnnotationUpgrade(current, {
|
||||
...current,
|
||||
tokens: [],
|
||||
startTime: 11,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isSubtitleAnnotationUpgrade(current, {
|
||||
...current,
|
||||
text: '次の字幕',
|
||||
tokens: [],
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(isSubtitleAnnotationUpgrade(current, current), false);
|
||||
});
|
||||
|
||||
test('serializeSubtitleMarkup escapes plain text and preserves line breaks', () => {
|
||||
const payload: SubtitleData = {
|
||||
text: 'a < b\nx & y',
|
||||
|
||||
@@ -20,6 +20,20 @@ export type SubtitleWebsocketFrequencyOptions = {
|
||||
|
||||
export type SubtitleWebsocketPayloadMode = 'plain' | 'annotated';
|
||||
|
||||
export function isSubtitleAnnotationUpgrade(
|
||||
current: SubtitleData | null,
|
||||
next: SubtitleData,
|
||||
): boolean {
|
||||
return (
|
||||
current !== null &&
|
||||
current.tokens === null &&
|
||||
next.tokens !== null &&
|
||||
current.text === next.text &&
|
||||
current.startTime === next.startTime &&
|
||||
current.endTime === next.endTime
|
||||
);
|
||||
}
|
||||
|
||||
type SubtitleWebsocketMessageOptions = {
|
||||
payloadMode?: SubtitleWebsocketPayloadMode;
|
||||
};
|
||||
|
||||
@@ -2934,44 +2934,12 @@ test('tokenizeSubtitle preserves Yomitan compound token when MeCab components ar
|
||||
return [];
|
||||
}
|
||||
|
||||
if (script.includes('parseText')) {
|
||||
return [
|
||||
{
|
||||
source: 'scanning-parser',
|
||||
index: 0,
|
||||
content: [
|
||||
[
|
||||
{
|
||||
text: '取り組んで',
|
||||
reading: 'とりくんで',
|
||||
headwords: [[{ term: '取り組む' }]],
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
text: 'もらいます',
|
||||
reading: 'もらいます',
|
||||
headwords: [[{ term: 'もらう' }]],
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
surface: '取り',
|
||||
reading: 'とり',
|
||||
headword: '取る',
|
||||
surface: '取り組んで',
|
||||
reading: 'とりくんで',
|
||||
headword: '取り組む',
|
||||
startPos: 0,
|
||||
endPos: 2,
|
||||
},
|
||||
{
|
||||
surface: '組んで',
|
||||
reading: 'くんで',
|
||||
headword: '組む',
|
||||
startPos: 2,
|
||||
endPos: 5,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -70,6 +70,7 @@ export interface TokenizerServiceDeps {
|
||||
getNameMatchImagesEnabled?: () => boolean;
|
||||
getCharacterNameImage?: (term: string) => CharacterNameImage | null;
|
||||
getCurrentCharacterDictionaryMediaId?: () => number | null;
|
||||
getCharacterNameCandidates?: () => { key: string; forms: string[] } | null;
|
||||
getFrequencyDictionaryEnabled?: () => boolean;
|
||||
getFrequencyDictionaryMatchMode?: () => FrequencyDictionaryMatchMode;
|
||||
getFrequencyRank?: FrequencyDictionaryLookup;
|
||||
@@ -106,6 +107,7 @@ export interface TokenizerDepsRuntimeOptions {
|
||||
getNameMatchImagesEnabled?: () => boolean;
|
||||
getCharacterNameImage?: (term: string) => CharacterNameImage | null;
|
||||
getCurrentCharacterDictionaryMediaId?: () => number | null;
|
||||
getCharacterNameCandidates?: () => { key: string; forms: string[] } | null;
|
||||
getFrequencyDictionaryEnabled?: () => boolean;
|
||||
getFrequencyDictionaryMatchMode?: () => FrequencyDictionaryMatchMode;
|
||||
getFrequencyRank?: FrequencyDictionaryLookup;
|
||||
@@ -266,6 +268,7 @@ export function createTokenizerDepsRuntime(
|
||||
getNameMatchImagesEnabled: options.getNameMatchImagesEnabled,
|
||||
getCharacterNameImage: options.getCharacterNameImage,
|
||||
getCurrentCharacterDictionaryMediaId: options.getCurrentCharacterDictionaryMediaId,
|
||||
getCharacterNameCandidates: options.getCharacterNameCandidates,
|
||||
getFrequencyDictionaryEnabled: options.getFrequencyDictionaryEnabled,
|
||||
getFrequencyDictionaryMatchMode: options.getFrequencyDictionaryMatchMode ?? (() => 'headword'),
|
||||
getFrequencyRank: options.getFrequencyRank,
|
||||
@@ -716,15 +719,30 @@ function getAnnotationOptions(deps: TokenizerServiceDeps): TokenizerAnnotationOp
|
||||
};
|
||||
}
|
||||
|
||||
// Per-line stage durations for the pipeline debug log; every field is filled in
|
||||
// by the stage that awaits the corresponding work.
|
||||
interface TokenizationStageTimings {
|
||||
scanMs?: number;
|
||||
mecabMs?: number;
|
||||
frequencyMs?: number;
|
||||
annotateMs?: number;
|
||||
}
|
||||
|
||||
async function parseWithYomitanInternalParser(
|
||||
text: string,
|
||||
deps: TokenizerServiceDeps,
|
||||
options: TokenizerAnnotationOptions,
|
||||
stageTimings?: TokenizationStageTimings,
|
||||
): Promise<MergedToken[] | null> {
|
||||
const scanStartedAtMs = Date.now();
|
||||
const selectedTokens = await requestYomitanScanTokens(text, deps, logger, {
|
||||
includeNameMatchMetadata: options.nameMatchEnabled,
|
||||
currentCharacterDictionaryMediaId: deps.getCurrentCharacterDictionaryMediaId?.() ?? null,
|
||||
nameCandidates: deps.getCharacterNameCandidates?.() ?? null,
|
||||
});
|
||||
if (stageTimings) {
|
||||
stageTimings.scanMs = Date.now() - scanStartedAtMs;
|
||||
}
|
||||
if (!selectedTokens || selectedTokens.length === 0) {
|
||||
return null;
|
||||
}
|
||||
@@ -757,6 +775,7 @@ async function parseWithYomitanInternalParser(
|
||||
|
||||
const frequencyRankPromise: Promise<YomitanFrequencyIndex> = options.frequencyEnabled
|
||||
? (async () => {
|
||||
const frequencyStartedAtMs = Date.now();
|
||||
const frequencyMatchMode = options.frequencyMatchMode;
|
||||
const termReadingList = buildYomitanFrequencyTermReadingList(
|
||||
normalizedSelectedTokens,
|
||||
@@ -767,12 +786,17 @@ async function parseWithYomitanInternalParser(
|
||||
deps,
|
||||
logger,
|
||||
);
|
||||
return buildYomitanFrequencyIndex(yomitanFrequencies);
|
||||
const frequencyIndex = buildYomitanFrequencyIndex(yomitanFrequencies);
|
||||
if (stageTimings) {
|
||||
stageTimings.frequencyMs = Date.now() - frequencyStartedAtMs;
|
||||
}
|
||||
return frequencyIndex;
|
||||
})()
|
||||
: Promise.resolve({ byPair: new Map(), byTerm: new Map() });
|
||||
|
||||
const mecabEnrichmentPromise: Promise<MergedToken[]> = needsMecabPosEnrichment(options)
|
||||
? (async () => {
|
||||
const mecabStartedAtMs = Date.now();
|
||||
try {
|
||||
const mecabTokens = await deps.tokenizeWithMecab(text);
|
||||
const enrichTokensWithMecab = deps.enrichTokensWithMecab ?? enrichTokensWithMecabAsync;
|
||||
@@ -786,6 +810,10 @@ async function parseWithYomitanInternalParser(
|
||||
`textLength=${text.length}`,
|
||||
);
|
||||
return normalizedSelectedTokens;
|
||||
} finally {
|
||||
if (stageTimings) {
|
||||
stageTimings.mecabMs = Date.now() - mecabStartedAtMs;
|
||||
}
|
||||
}
|
||||
})()
|
||||
: Promise.resolve(normalizedSelectedTokens);
|
||||
@@ -876,15 +904,35 @@ export async function tokenizeSubtitle(
|
||||
const annotationOptions = getAnnotationOptions(deps);
|
||||
annotationOptions.sourceText = tokenizeText;
|
||||
|
||||
const yomitanTokens = await parseWithYomitanInternalParser(tokenizeText, deps, annotationOptions);
|
||||
const stageTimings: TokenizationStageTimings = {};
|
||||
const startedAtMs = Date.now();
|
||||
const logStageTimings = (tokenCount: number): void => {
|
||||
logger.debug(
|
||||
`Subtitle tokenization stages; textLength=${tokenizeText.length}, tokenCount=${tokenCount}, ` +
|
||||
`scanMs=${stageTimings.scanMs ?? '-'}, mecabMs=${stageTimings.mecabMs ?? '-'}, ` +
|
||||
`frequencyMs=${stageTimings.frequencyMs ?? '-'}, annotateMs=${stageTimings.annotateMs ?? '-'}, ` +
|
||||
`totalMs=${Date.now() - startedAtMs}`,
|
||||
);
|
||||
};
|
||||
|
||||
const yomitanTokens = await parseWithYomitanInternalParser(
|
||||
tokenizeText,
|
||||
deps,
|
||||
annotationOptions,
|
||||
stageTimings,
|
||||
);
|
||||
if (yomitanTokens && yomitanTokens.length > 0) {
|
||||
const annotateStartedAtMs = Date.now();
|
||||
const annotatedTokens = await applyAnnotationStage(yomitanTokens, deps, annotationOptions);
|
||||
stageTimings.annotateMs = Date.now() - annotateStartedAtMs;
|
||||
const renderedTokens = applyCharacterNameImages(annotatedTokens, deps, annotationOptions);
|
||||
logStageTimings(renderedTokens.length);
|
||||
return {
|
||||
text: displayText,
|
||||
tokens: renderedTokens.length > 0 ? renderedTokens : null,
|
||||
};
|
||||
}
|
||||
|
||||
logStageTimings(0);
|
||||
return { text: displayText, tokens: null };
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Title prefix of the dictionaries SubMiner generates per media. Lives on its
|
||||
// own because both the main process and the injected scan runtime match on it,
|
||||
// and the injected fragments interpolate it into their own source.
|
||||
export const CHARACTER_DICTIONARY_TITLE_PREFIX = 'SubMiner Character Dictionary';
|
||||
@@ -366,8 +366,11 @@ export function createReplayMessageStore(messages: GoldenRecordedMessage[]): Rep
|
||||
};
|
||||
}
|
||||
|
||||
async function runInjectedScriptInVm(script: string, store: ReplayMessageStore): Promise<unknown> {
|
||||
return await vm.runInNewContext(script, {
|
||||
// One persistent context per fixture, matching the real parser window: the
|
||||
// scan runtime installs itself once into globalThis and later per-line call
|
||||
// scripts reuse it.
|
||||
function createInjectedScriptVm(store: ReplayMessageStore): (script: string) => Promise<unknown> {
|
||||
const context = vm.createContext({
|
||||
chrome: {
|
||||
runtime: {
|
||||
lastError: null,
|
||||
@@ -393,6 +396,7 @@ async function runInjectedScriptInVm(script: string, store: ReplayMessageStore):
|
||||
Set,
|
||||
String,
|
||||
});
|
||||
return async (script: string) => await vm.runInContext(script, context);
|
||||
}
|
||||
|
||||
export function createReplayTokenizerDeps(fixture: GoldenFixture): TokenizerServiceDeps {
|
||||
@@ -400,13 +404,14 @@ export function createReplayTokenizerDeps(fixture: GoldenFixture): TokenizerServ
|
||||
const scriptResults = new Map(
|
||||
fixture.recording.scripts.map((entry) => [entry.sha256, entry] as const),
|
||||
);
|
||||
const runInjectedScriptInVm = createInjectedScriptVm(store);
|
||||
|
||||
const parserWindow = {
|
||||
isDestroyed: () => false,
|
||||
webContents: {
|
||||
executeJavaScript: async (script: string) => {
|
||||
try {
|
||||
return await runInjectedScriptInVm(script, store);
|
||||
return await runInjectedScriptInVm(script);
|
||||
} catch (vmError) {
|
||||
const recorded = scriptResults.get(hashInjectedScript(script));
|
||||
if (recorded) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
isKanaChar,
|
||||
isKanaOnlyText,
|
||||
isTokenPos2Excluded,
|
||||
normalizeKana,
|
||||
} from './token-classification';
|
||||
|
||||
const POS1_EXCLUSIONS = new Set(['助詞']);
|
||||
@@ -29,6 +30,26 @@ function makeNoun(surface: string): MergedToken {
|
||||
};
|
||||
}
|
||||
|
||||
test('kana normalization folds halfwidth kana, composing the voiced pairs', () => {
|
||||
// カ + ゙ is two code points for one character: without composing them, a
|
||||
// halfwidth word counts as longer than the reading that spells it, which
|
||||
// disqualifies the reading from known-word matching.
|
||||
assert.equal(normalizeKana('ガク'), normalizeKana('ガク'));
|
||||
assert.equal(normalizeKana('パン'), normalizeKana('パン'));
|
||||
assert.equal(normalizeKana('ミナト'), 'みなと');
|
||||
assert.ok(isKanaOnlyText('ガク'));
|
||||
});
|
||||
|
||||
test('kana normalization leaves characters other than halfwidth kana alone', () => {
|
||||
// The composition is scoped to the halfwidth runs: applied to the whole
|
||||
// string, NFKC would also rewrite these into something the dictionary, the
|
||||
// known-word list, and the frequency data were never keyed on.
|
||||
assert.equal(normalizeKana('①ガ'), '①が');
|
||||
assert.equal(normalizeKana('Aガ'), 'Aが');
|
||||
assert.equal(normalizeKana('㍑ガ'), '㍑が');
|
||||
assert.equal(normalizeKana('fiガ'), 'fiが');
|
||||
});
|
||||
|
||||
test('kana classification excludes the katakana-hiragana double hyphen', () => {
|
||||
assert.equal(isKanaChar('゠'), false);
|
||||
assert.equal(isKanaOnlyText('゠'), false);
|
||||
|
||||
@@ -4,8 +4,20 @@ const KATAKANA_TO_HIRAGANA_OFFSET = 0x60;
|
||||
const KATAKANA_CODEPOINT_START = 0x30a1;
|
||||
const KATAKANA_CODEPOINT_END = 0x30f6;
|
||||
|
||||
// No `u` flag: the range is entirely BMP so it changes nothing here, and
|
||||
// Bun's unicode-mode matcher mis-handles this class next to certain ligatures.
|
||||
const HALFWIDTH_KANA_RUN = /[\uff66-\uff9f]+/g;
|
||||
|
||||
// NFKC over the halfwidth kana only, never the whole string: it composes the
|
||||
// voiced pairs (カ + ゙) into single characters so ガク compares equal to ガク
|
||||
// instead of counting one character longer than the word it spells, but run
|
||||
// over everything it would also rewrite unrelated text (① → 1, ㍑ → リットル).
|
||||
function composeHalfwidthKana(text: string): string {
|
||||
return text.replace(HALFWIDTH_KANA_RUN, (run) => run.normalize('NFKC'));
|
||||
}
|
||||
|
||||
export function normalizeKana(text: string): string {
|
||||
const raw = text.trim();
|
||||
const raw = composeHalfwidthKana(text).trim();
|
||||
if (!raw) {
|
||||
return '';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
// Dictionary classification for the injected scan runtime: which dictionaries
|
||||
// an entry came from, and whether it is a SubMiner character entry for the
|
||||
// media being watched. Both walk nested entry data, so both are memoized on the
|
||||
// entry object by the runtime that hosts them.
|
||||
|
||||
import { CHARACTER_DICTIONARY_TITLE_PREFIX } from './character-dictionary-title';
|
||||
|
||||
// The prefix is interpolated into generated regex source, so metacharacters in
|
||||
// it would change what the pattern matches (or fail to compile).
|
||||
const ESCAPED_TITLE_PREFIX = CHARACTER_DICTIONARY_TITLE_PREFIX.replace(
|
||||
/[.*+?^${}()|[\]\\]/g,
|
||||
'\\$&',
|
||||
);
|
||||
const TITLE_MEDIA_ID_PATTERN = ESCAPED_TITLE_PREFIX + String.raw`[^\d]*(?:AniList\s*)?(\d+)`;
|
||||
|
||||
export const YOMITAN_DICTIONARY_CLASSIFICATION_HELPERS = String.raw`
|
||||
function normalizeWordClasses(headword) {
|
||||
if (!Array.isArray(headword?.wordClasses)) { return undefined; }
|
||||
const classes = headword.wordClasses.filter((wordClass) => typeof wordClass === "string" && wordClass.trim().length > 0);
|
||||
return classes.length > 0 ? classes : undefined;
|
||||
}
|
||||
function appendDictionaryNames(target, value) {
|
||||
if (!value || typeof value !== 'object') {
|
||||
return;
|
||||
}
|
||||
const candidates = [
|
||||
value.dictionary,
|
||||
value.dictionaryName,
|
||||
value.name,
|
||||
value.title,
|
||||
value.dictionaryTitle,
|
||||
value.dictionaryAlias
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
if (typeof candidate === 'string' && candidate.trim().length > 0) {
|
||||
target.push(candidate.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
// Memoized on the entry object: termsFind results are cached across
|
||||
// lines, so the same entries come back for every repeated lookup, and
|
||||
// each one is classified several times per scan (name pre-pass,
|
||||
// headword preference, every retry window).
|
||||
function getDictionaryEntryNames(entry) {
|
||||
if (!entry || typeof entry !== 'object') { return []; }
|
||||
const cached = dictionaryEntryNamesCache.get(entry);
|
||||
if (cached !== undefined) { return cached; }
|
||||
const names = [];
|
||||
appendDictionaryNames(names, entry);
|
||||
for (const definition of entry?.definitions || []) {
|
||||
appendDictionaryNames(names, definition);
|
||||
}
|
||||
for (const frequency of entry?.frequencies || []) {
|
||||
appendDictionaryNames(names, frequency);
|
||||
}
|
||||
for (const pronunciation of entry?.pronunciations || []) {
|
||||
appendDictionaryNames(names, pronunciation);
|
||||
}
|
||||
dictionaryEntryNamesCache.set(entry, names);
|
||||
return names;
|
||||
}
|
||||
// Cached per scan rather than per runtime: the answer depends on
|
||||
// includeNameMatchMetadata, which is a per-call parameter.
|
||||
const nameDictionaryEntryCache = new WeakMap();
|
||||
function isNameDictionaryEntry(entry) {
|
||||
if (!includeNameMatchMetadata || !entry || typeof entry !== 'object') {
|
||||
return false;
|
||||
}
|
||||
const cached = nameDictionaryEntryCache.get(entry);
|
||||
if (cached !== undefined) { return cached; }
|
||||
const isName = getDictionaryEntryNames(entry).some((name) => name.startsWith(${JSON.stringify(CHARACTER_DICTIONARY_TITLE_PREFIX)}));
|
||||
nameDictionaryEntryCache.set(entry, isName);
|
||||
return isName;
|
||||
}
|
||||
const TITLE_MEDIA_ID_REGEX = new RegExp(${JSON.stringify(TITLE_MEDIA_ID_PATTERN)}, 'i');
|
||||
function parseSubMinerMediaIdFromString(value) {
|
||||
const imageMatch = value.match(/\bimg\/m(\d+)-/i);
|
||||
if (imageMatch) {
|
||||
const parsed = Number.parseInt(imageMatch[1], 10);
|
||||
if (Number.isSafeInteger(parsed) && parsed > 0) { return parsed; }
|
||||
}
|
||||
const titleMatch = value.match(TITLE_MEDIA_ID_REGEX);
|
||||
if (titleMatch) {
|
||||
const parsed = Number.parseInt(titleMatch[1], 10);
|
||||
if (Number.isSafeInteger(parsed) && parsed > 0) { return parsed; }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function parseSubMinerMediaIdCandidate(value) {
|
||||
if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
|
||||
const parsed = Number.parseInt(value.trim(), 10);
|
||||
if (Number.isSafeInteger(parsed) && parsed > 0) { return parsed; }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function collectSubMinerMediaIds(value, target) {
|
||||
if (typeof value === 'string') {
|
||||
const parsed = parseSubMinerMediaIdFromString(value);
|
||||
if (parsed !== null) { target.add(parsed); }
|
||||
return;
|
||||
}
|
||||
if (!value || typeof value !== 'object') {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) { collectSubMinerMediaIds(item, target); }
|
||||
return;
|
||||
}
|
||||
const mediaIdCandidates = [
|
||||
value.subminerMediaId,
|
||||
value.subMinerMediaId,
|
||||
value.characterDictionaryMediaId,
|
||||
value.data?.subminerMediaId,
|
||||
value.data?.subMinerMediaId,
|
||||
value.data?.characterDictionaryMediaId
|
||||
];
|
||||
for (const candidate of mediaIdCandidates) {
|
||||
const parsed = parseSubMinerMediaIdCandidate(candidate);
|
||||
if (parsed !== null) { target.add(parsed); }
|
||||
}
|
||||
for (const child of Object.values(value)) {
|
||||
collectSubMinerMediaIds(child, target);
|
||||
}
|
||||
}
|
||||
// Walking an entry collects media ids from every nested value, so this
|
||||
// is the most expensive classification step; memoized on the entry for
|
||||
// the same reason as the dictionary names above.
|
||||
function getSubMinerMediaIds(entry) {
|
||||
if (!entry || typeof entry !== 'object') { return EMPTY_MEDIA_ID_SET; }
|
||||
const cached = subMinerMediaIdsCache.get(entry);
|
||||
if (cached !== undefined) { return cached; }
|
||||
const mediaIds = new Set();
|
||||
collectSubMinerMediaIds(entry, mediaIds);
|
||||
subMinerMediaIdsCache.set(entry, mediaIds);
|
||||
return mediaIds;
|
||||
}
|
||||
function isCurrentMediaNameDictionaryEntry(entry) {
|
||||
if (!isNameDictionaryEntry(entry)) {
|
||||
return false;
|
||||
}
|
||||
if (currentCharacterDictionaryMediaId === null) {
|
||||
return true;
|
||||
}
|
||||
const mediaIds = getSubMinerMediaIds(entry);
|
||||
return mediaIds.size === 0 || mediaIds.has(currentCharacterDictionaryMediaId);
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,135 @@
|
||||
// Frequency-rank resolution for the injected scan runtime: reads the many
|
||||
// shapes a Yomitan frequency entry can take and picks the best rank for a
|
||||
// headword, honouring per-dictionary priority and occurrence-vs-rank mode.
|
||||
|
||||
export const YOMITAN_FREQUENCY_HELPERS = String.raw`
|
||||
function parsePositiveFrequencyNumber(value) {
|
||||
if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
|
||||
return Math.max(1, Math.floor(value));
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
const numericMatch = value.trim().match(/[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?/)?.[0];
|
||||
if (!numericMatch) { return null; }
|
||||
const parsed = Number.parseFloat(numericMatch);
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) { return null; }
|
||||
return Math.max(1, Math.floor(parsed));
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
const parsed = parsePositiveFrequencyNumber(item);
|
||||
if (parsed !== null) { return parsed; }
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function parseDisplayFrequencyNumber(value) {
|
||||
if (typeof value === 'string') {
|
||||
const leadingDigits = value.trim().match(/^\d+/)?.[0];
|
||||
if (!leadingDigits) { return null; }
|
||||
const parsed = Number.parseInt(leadingDigits, 10);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
||||
}
|
||||
return parsePositiveFrequencyNumber(value);
|
||||
}
|
||||
function getFrequencyDictionaryName(frequency) {
|
||||
const candidates = [
|
||||
frequency?.dictionary,
|
||||
frequency?.dictionaryName,
|
||||
frequency?.name,
|
||||
frequency?.title,
|
||||
frequency?.dictionaryTitle,
|
||||
frequency?.dictionaryAlias
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
if (typeof candidate === 'string' && candidate.trim().length > 0) {
|
||||
return candidate.trim();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function getBestFrequencyRank(dictionaryEntry, headwordIndex, dictionaryPriorityByName, dictionaryFrequencyModeByName) {
|
||||
let best = null;
|
||||
const headwordCount = Array.isArray(dictionaryEntry?.headwords) ? dictionaryEntry.headwords.length : 0;
|
||||
for (const frequency of dictionaryEntry?.frequencies || []) {
|
||||
if (!frequency || typeof frequency !== 'object') { continue; }
|
||||
const frequencyHeadwordIndex = frequency.headwordIndex;
|
||||
if (typeof frequencyHeadwordIndex === 'number') {
|
||||
if (frequencyHeadwordIndex !== headwordIndex) { continue; }
|
||||
} else if (headwordCount > 1) {
|
||||
continue;
|
||||
}
|
||||
const dictionary = getFrequencyDictionaryName(frequency);
|
||||
if (!dictionary) { continue; }
|
||||
if (dictionaryFrequencyModeByName[dictionary] === 'occurrence-based') { continue; }
|
||||
const rank =
|
||||
parseDisplayFrequencyNumber(frequency.displayValue) ??
|
||||
parsePositiveFrequencyNumber(frequency.frequency);
|
||||
if (rank === null) { continue; }
|
||||
const priorityRaw = dictionaryPriorityByName[dictionary];
|
||||
const fallbackPriority =
|
||||
typeof frequency.dictionaryIndex === 'number' && Number.isFinite(frequency.dictionaryIndex)
|
||||
? Math.max(0, Math.floor(frequency.dictionaryIndex))
|
||||
: Number.MAX_SAFE_INTEGER;
|
||||
const priority =
|
||||
typeof priorityRaw === 'number' && Number.isFinite(priorityRaw)
|
||||
? Math.max(0, Math.floor(priorityRaw))
|
||||
: fallbackPriority;
|
||||
if (best === null || priority < best.priority || (priority === best.priority && rank < best.rank)) {
|
||||
best = { priority, rank };
|
||||
}
|
||||
}
|
||||
return best?.rank ?? null;
|
||||
}
|
||||
function hasExactSource(headword, token, requirePrimary) {
|
||||
for (const src of headword?.sources || []) {
|
||||
if (src.originalText !== token) { continue; }
|
||||
if (requirePrimary && !src.isPrimary) { continue; }
|
||||
if (src.matchType !== 'exact') { continue; }
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function collectExactHeadwordMatches(dictionaryEntries, token, requirePrimary) {
|
||||
const matches = [];
|
||||
for (const dictionaryEntry of dictionaryEntries || []) {
|
||||
const headwords = Array.isArray(dictionaryEntry?.headwords) ? dictionaryEntry.headwords : [];
|
||||
for (let headwordIndex = 0; headwordIndex < headwords.length; headwordIndex += 1) {
|
||||
const headword = headwords[headwordIndex];
|
||||
if (!hasExactSource(headword, token, requirePrimary)) { continue; }
|
||||
matches.push({ dictionaryEntry, headword, headwordIndex });
|
||||
}
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
function sameHeadword(match, preferredMatch) {
|
||||
if (!match || !preferredMatch) {
|
||||
return false;
|
||||
}
|
||||
if (match.headword?.term !== preferredMatch.headword?.term) {
|
||||
return false;
|
||||
}
|
||||
const matchReading = typeof match.headword?.reading === 'string' ? match.headword.reading : '';
|
||||
const preferredReading =
|
||||
typeof preferredMatch.headword?.reading === 'string' ? preferredMatch.headword.reading : '';
|
||||
if (!matchReading || !preferredReading) {
|
||||
return true;
|
||||
}
|
||||
return matchReading === preferredReading;
|
||||
}
|
||||
function getBestFrequencyRankForMatches(matches, dictionaryPriorityByName, dictionaryFrequencyModeByName) {
|
||||
let best = null;
|
||||
for (const match of matches) {
|
||||
const rank = getBestFrequencyRank(
|
||||
match.dictionaryEntry,
|
||||
match.headwordIndex,
|
||||
dictionaryPriorityByName,
|
||||
dictionaryFrequencyModeByName
|
||||
);
|
||||
if (rank === null) { continue; }
|
||||
if (best === null || rank < best) {
|
||||
best = rank;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,170 @@
|
||||
// Furigana distribution for the injected scan runtime: splits a headword and
|
||||
// its reading into the segments a token carries, including the inflected case
|
||||
// where the matched source text differs from the dictionary form.
|
||||
|
||||
export const YOMITAN_FURIGANA_HELPERS = String.raw`
|
||||
function createFuriganaSegment(text, reading) { return {text, reading}; }
|
||||
function getSegmentReadingContribution(segment) {
|
||||
if (typeof segment.reading === "string" && segment.reading.length > 0) { return segment.reading; }
|
||||
const segmentText = typeof segment.text === "string" ? segment.text : "";
|
||||
const isKanaOnly = segmentText.length > 0 && [...segmentText].every((char) => isCodePointKana(char.codePointAt(0)));
|
||||
return isKanaOnly ? convertHalfwidthKanaToKatakana(segmentText) : "";
|
||||
}
|
||||
function getProlongedHiragana(previousCharacter) {
|
||||
switch (previousCharacter) {
|
||||
case "あ": case "か": case "が": case "さ": case "ざ": case "た": case "だ": case "な": case "は": case "ば": case "ぱ": case "ま": case "や": case "ら": case "わ": case "ぁ": case "ゃ": case "ゎ": return "あ";
|
||||
case "い": case "き": case "ぎ": case "し": case "じ": case "ち": case "ぢ": case "に": case "ひ": case "び": case "ぴ": case "み": case "り": case "ぃ": return "い";
|
||||
case "う": case "く": case "ぐ": case "す": case "ず": case "つ": case "づ": case "ぬ": case "ふ": case "ぶ": case "ぷ": case "む": case "ゆ": case "る": case "ぅ": case "ゅ": return "う";
|
||||
case "え": case "け": case "げ": case "せ": case "ぜ": case "て": case "で": case "ね": case "へ": case "べ": case "ぺ": case "め": case "れ": case "ぇ": return "え";
|
||||
case "お": case "こ": case "ご": case "そ": case "ぞ": case "と": case "ど": case "の": case "ほ": case "ぼ": case "ぽ": case "も": case "よ": case "ろ": case "を": case "ぉ": case "ょ": return "う";
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
function getFuriganaKanaSegments(text, reading) {
|
||||
const newSegments = [];
|
||||
let start = 0;
|
||||
let state = (reading[0] === text[0]);
|
||||
for (let i = 1; i < text.length; ++i) {
|
||||
const newState = (reading[i] === text[i]);
|
||||
if (state === newState) { continue; }
|
||||
newSegments.push(createFuriganaSegment(text.substring(start, i), state ? '' : reading.substring(start, i)));
|
||||
state = newState;
|
||||
start = i;
|
||||
}
|
||||
newSegments.push(createFuriganaSegment(text.substring(start), state ? '' : reading.substring(start)));
|
||||
return newSegments;
|
||||
}
|
||||
function convertKatakanaToHiragana(text, keepProlongedSoundMarks = false) {
|
||||
let result = '';
|
||||
const offset = (HIRAGANA_CONVERSION_RANGE[0] - KATAKANA_CONVERSION_RANGE[0]);
|
||||
for (let char of text) {
|
||||
const codePoint = char.codePointAt(0);
|
||||
switch (codePoint) {
|
||||
case KATAKANA_SMALL_KA_CODE_POINT:
|
||||
case KATAKANA_SMALL_KE_CODE_POINT:
|
||||
break;
|
||||
case KANA_PROLONGED_SOUND_MARK_CODE_POINT:
|
||||
case HALFWIDTH_KANA_PROLONGED_SOUND_MARK_CODE_POINT:
|
||||
char = "ー";
|
||||
if (!keepProlongedSoundMarks && result.length > 0) {
|
||||
const char2 = getProlongedHiragana(result[result.length - 1]);
|
||||
if (char2 !== null) { char = char2; }
|
||||
}
|
||||
break;
|
||||
default:
|
||||
if (isCodePointInRange(codePoint, KATAKANA_CONVERSION_RANGE)) {
|
||||
char = String.fromCodePoint(codePoint + offset);
|
||||
break;
|
||||
}
|
||||
// Halfwidth katakana folds too, or a name written that way would
|
||||
// match neither a candidate form nor its own reading.
|
||||
const halfwidthHiragana = convertHalfwidthKanaCodePointToHiragana(codePoint);
|
||||
if (halfwidthHiragana !== null) { char = halfwidthHiragana; }
|
||||
break;
|
||||
}
|
||||
result += char;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function segmentizeFurigana(reading, readingNormalized, groups, groupsStart) {
|
||||
const groupCount = groups.length - groupsStart;
|
||||
if (groupCount <= 0) { return reading.length === 0 ? [] : null; }
|
||||
const group = groups[groupsStart];
|
||||
const {isKana, text} = group;
|
||||
if (isKana) {
|
||||
if (group.textNormalized !== null && readingNormalized.startsWith(group.textNormalized)) {
|
||||
const segments = segmentizeFurigana(reading.substring(text.length), readingNormalized.substring(text.length), groups, groupsStart + 1);
|
||||
if (segments !== null) {
|
||||
if (reading.startsWith(text)) { segments.unshift(createFuriganaSegment(text, '')); }
|
||||
else { segments.unshift(...getFuriganaKanaSegments(text, reading)); }
|
||||
return segments;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
let result = null;
|
||||
for (let i = reading.length; i >= text.length; --i) {
|
||||
const segments = segmentizeFurigana(reading.substring(i), readingNormalized.substring(i), groups, groupsStart + 1);
|
||||
if (segments !== null) {
|
||||
if (result !== null) { return null; }
|
||||
segments.unshift(createFuriganaSegment(text, reading.substring(0, i)));
|
||||
result = segments;
|
||||
}
|
||||
if (groupCount === 1) { break; }
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function distributeFurigana(term, reading) {
|
||||
if (reading === term) { return [createFuriganaSegment(term, '')]; }
|
||||
const groups = [];
|
||||
let groupPre = null;
|
||||
let isKanaPre = null;
|
||||
for (const c of term) {
|
||||
const isKana = isCodePointKana(c.codePointAt(0));
|
||||
if (isKana === isKanaPre) { groupPre.text += c; }
|
||||
else {
|
||||
groupPre = {isKana, text: c, textNormalized: null};
|
||||
groups.push(groupPre);
|
||||
isKanaPre = isKana;
|
||||
}
|
||||
}
|
||||
for (const group of groups) {
|
||||
if (group.isKana) { group.textNormalized = convertKatakanaToHiragana(group.text); }
|
||||
}
|
||||
const segments = segmentizeFurigana(reading, convertKatakanaToHiragana(reading), groups, 0);
|
||||
return segments !== null ? segments : [createFuriganaSegment(term, reading)];
|
||||
}
|
||||
function getStemLength(text1, text2) {
|
||||
const minLength = Math.min(text1.length, text2.length);
|
||||
if (minLength === 0) { return 0; }
|
||||
let i = 0;
|
||||
while (true) {
|
||||
const char1 = text1.codePointAt(i);
|
||||
const char2 = text2.codePointAt(i);
|
||||
if (char1 !== char2) { break; }
|
||||
const charLength = String.fromCodePoint(char1).length;
|
||||
i += charLength;
|
||||
if (i >= minLength) {
|
||||
if (i > minLength) { i -= charLength; }
|
||||
break;
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
function distributeFuriganaInflected(term, reading, source) {
|
||||
const termNormalized = convertKatakanaToHiragana(term);
|
||||
const readingNormalized = convertKatakanaToHiragana(reading);
|
||||
const sourceNormalized = convertKatakanaToHiragana(source);
|
||||
let mainText = term;
|
||||
let stemLength = getStemLength(termNormalized, sourceNormalized);
|
||||
const readingStemLength = getStemLength(readingNormalized, sourceNormalized);
|
||||
if (readingStemLength > 0 && readingStemLength >= stemLength) {
|
||||
mainText = reading;
|
||||
stemLength = readingStemLength;
|
||||
reading = source.substring(0, stemLength) + reading.substring(stemLength);
|
||||
}
|
||||
const segments = [];
|
||||
if (stemLength > 0) {
|
||||
mainText = source.substring(0, stemLength) + mainText.substring(stemLength);
|
||||
const segments2 = distributeFurigana(mainText, reading);
|
||||
let consumed = 0;
|
||||
for (const segment of segments2) {
|
||||
const start = consumed;
|
||||
consumed += segment.text.length;
|
||||
if (consumed < stemLength) { segments.push(segment); }
|
||||
else if (consumed === stemLength) { segments.push(segment); break; }
|
||||
else {
|
||||
if (start < stemLength) { segments.push(createFuriganaSegment(mainText.substring(start, stemLength), '')); }
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stemLength < source.length) {
|
||||
const remainder = source.substring(stemLength);
|
||||
const last = segments[segments.length - 1];
|
||||
if (last && last.reading.length === 0) { last.text += remainder; }
|
||||
else { segments.push(createFuriganaSegment(remainder, '')); }
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,45 @@
|
||||
// Kana classification and normalization for the injected scan runtime: the
|
||||
// code-point ranges the walk tests every character against, and the folds that
|
||||
// let halfwidth and katakana spellings compare equal to their dictionary form.
|
||||
import { HAN_CODE_POINT_RANGES } from '../../text/han-code-points';
|
||||
|
||||
export const YOMITAN_KANA_HELPERS = String.raw`
|
||||
const HIRAGANA_CONVERSION_RANGE = [0x3041, 0x3096];
|
||||
const KATAKANA_CONVERSION_RANGE = [0x30a1, 0x30f6];
|
||||
const KANA_PROLONGED_SOUND_MARK_CODE_POINT = 0x30fc;
|
||||
const KATAKANA_SMALL_KA_CODE_POINT = 0x30f5;
|
||||
const KATAKANA_SMALL_KE_CODE_POINT = 0x30f6;
|
||||
const KANA_RANGES = [[0x3040, 0x309f], [0x30a0, 0x30ff], [0xff66, 0xff9f]];
|
||||
const HALFWIDTH_KATAKANA_RANGE = [0xff66, 0xff9d];
|
||||
const HALFWIDTH_KANA_PROLONGED_SOUND_MARK_CODE_POINT = 0xff70;
|
||||
// Folded one code point to one, so every index into a normalized string
|
||||
// still lines up with the original text — the name-candidate prefilter
|
||||
// and the furigana stem matching both index back into it. The standalone
|
||||
// voiced marks (゙ ゚) have no one-character equivalent and stay as they are.
|
||||
const HALFWIDTH_KATAKANA_TO_HIRAGANA = "をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわん";
|
||||
function convertHalfwidthKanaCodePointToHiragana(codePoint) {
|
||||
if (codePoint < HALFWIDTH_KATAKANA_RANGE[0] || codePoint > HALFWIDTH_KATAKANA_RANGE[1]) { return null; }
|
||||
return HALFWIDTH_KATAKANA_TO_HIRAGANA[codePoint - HALFWIDTH_KATAKANA_RANGE[0]] || null;
|
||||
}
|
||||
// Halfwidth katakana is kana here but not to the rest of the pipeline
|
||||
// (known-word matching and frequency lookups only fold fullwidth), so a
|
||||
// reading taken from halfwidth text is written the way the fullwidth
|
||||
// katakana path already writes it. NFKC rather than the per-code-point
|
||||
// table: this is the one place where nothing indexes back into the
|
||||
// result, so a voiced pair (カ + ゙) can compose into the single ガ it
|
||||
// means instead of leaving a stray combining mark in the reading. Scoped
|
||||
// to the halfwidth runs, because NFKC over everything else rewrites
|
||||
// characters that have nothing to do with kana (① → 1, ㍑ → リットル).
|
||||
function convertHalfwidthKanaToKatakana(text) {
|
||||
return text.replace(/[ヲ-゚]+/g, (run) => run.normalize("NFKC"));
|
||||
}
|
||||
// Han ranges come from the shared table so the scan walk and the character
|
||||
// dictionary agree on what a kanji is (supplementary planes included).
|
||||
// Halfwidth katakana counts as Japanese text: a name written that way has
|
||||
// to reach the greedy pre-pass, which has its own handling for it.
|
||||
const JAPANESE_RANGES = [[0x3040, 0x30ff], [0xff66, 0xff9f], ...${JSON.stringify(HAN_CODE_POINT_RANGES)}];
|
||||
function isCodePointInRange(codePoint, range) { return codePoint >= range[0] && codePoint <= range[1]; }
|
||||
function isCodePointInRanges(codePoint, ranges) { return ranges.some((range) => isCodePointInRange(codePoint, range)); }
|
||||
function isCodePointKana(codePoint) { return isCodePointInRanges(codePoint, KANA_RANGES); }
|
||||
function isCodePointJapanese(codePoint) { return isCodePointInRanges(codePoint, JAPANESE_RANGES); }
|
||||
`;
|
||||
@@ -0,0 +1,79 @@
|
||||
// Match selection for the injected scan runtime: picks the headword a position
|
||||
// tokenizes to, and the longest name or generic match in a window, which is how
|
||||
// the greedy name pre-pass decides what to reserve.
|
||||
|
||||
export const YOMITAN_MATCH_SELECTION_HELPERS = String.raw`
|
||||
function findLongestNameMatch(dictionaryEntries, textWindow) {
|
||||
let best = null;
|
||||
for (const dictionaryEntry of dictionaryEntries || []) {
|
||||
if (!isCurrentMediaNameDictionaryEntry(dictionaryEntry)) { continue; }
|
||||
const headwords = Array.isArray(dictionaryEntry?.headwords) ? dictionaryEntry.headwords : [];
|
||||
for (let headwordIndex = 0; headwordIndex < headwords.length; headwordIndex += 1) {
|
||||
const headword = headwords[headwordIndex];
|
||||
for (const src of headword?.sources || []) {
|
||||
if (src.matchType !== 'exact' || src.isPrimary !== true) { continue; }
|
||||
const originalText = typeof src.originalText === 'string' ? src.originalText : '';
|
||||
if (!originalText || !textWindow.startsWith(originalText)) { continue; }
|
||||
if (best === null || originalText.length > best.sourceLength) {
|
||||
best = { dictionaryEntry, headword, headwordIndex, sourceLength: originalText.length };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
function findLongestGenericMatchLength(dictionaryEntries, textWindow) {
|
||||
let best = 0;
|
||||
for (const dictionaryEntry of dictionaryEntries || []) {
|
||||
if (isNameDictionaryEntry(dictionaryEntry)) { continue; }
|
||||
const headwords = Array.isArray(dictionaryEntry?.headwords) ? dictionaryEntry.headwords : [];
|
||||
for (const headword of headwords) {
|
||||
for (const src of headword?.sources || []) {
|
||||
if (src.matchType !== 'exact' || src.isPrimary !== true) { continue; }
|
||||
const originalText = typeof src.originalText === 'string' ? src.originalText : '';
|
||||
if (!originalText || !textWindow.startsWith(originalText)) { continue; }
|
||||
if (originalText.length > best) { best = originalText.length; }
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
function getPreferredHeadword(dictionaryEntries, token, dictionaryPriorityByName, dictionaryFrequencyModeByName) {
|
||||
const currentMediaDictionaryEntries =
|
||||
currentCharacterDictionaryMediaId === null
|
||||
? (dictionaryEntries || [])
|
||||
: (dictionaryEntries || []).filter((entry) => {
|
||||
if (!isNameDictionaryEntry(entry)) { return true; }
|
||||
return isCurrentMediaNameDictionaryEntry(entry);
|
||||
});
|
||||
const exactPrimaryMatches = collectExactHeadwordMatches(currentMediaDictionaryEntries, token, true);
|
||||
let matchedNameDictionary = false;
|
||||
if (includeNameMatchMetadata) {
|
||||
// Every match already comes from currentMediaDictionaryEntries, so
|
||||
// classifying its own entry is enough.
|
||||
for (const match of exactPrimaryMatches) {
|
||||
if (!isCurrentMediaNameDictionaryEntry(match.dictionaryEntry)) { continue; }
|
||||
matchedNameDictionary = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const preferredMatch = exactPrimaryMatches[0];
|
||||
if (preferredMatch) {
|
||||
const exactFrequencyMatches = collectExactHeadwordMatches(currentMediaDictionaryEntries, token, false)
|
||||
.filter((match) => sameHeadword(match, preferredMatch));
|
||||
return {
|
||||
term: preferredMatch.headword.term,
|
||||
reading: preferredMatch.headword.reading,
|
||||
wordClasses: normalizeWordClasses(preferredMatch.headword),
|
||||
isNameMatch:
|
||||
matchedNameDictionary || isCurrentMediaNameDictionaryEntry(preferredMatch.dictionaryEntry),
|
||||
frequencyRank: getBestFrequencyRankForMatches(
|
||||
exactFrequencyMatches.length > 0 ? exactFrequencyMatches : exactPrimaryMatches,
|
||||
dictionaryPriorityByName,
|
||||
dictionaryFrequencyModeByName
|
||||
)
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
`;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,14 @@ import * as fs from 'fs';
|
||||
import * as http from 'http';
|
||||
import * as path from 'path';
|
||||
import { selectYomitanParseTokens } from './parser-selection-stage';
|
||||
import {
|
||||
buildYomitanScanCallScript,
|
||||
buildYomitanScanNameCandidatesScript,
|
||||
CHARACTER_DICTIONARY_TITLE_PREFIX,
|
||||
YOMITAN_SCAN_RUNTIME_INSTALL_SCRIPT,
|
||||
YOMITAN_SCAN_RUNTIME_MISSING_SENTINEL,
|
||||
type YomitanFrequencyMode,
|
||||
} from './yomitan-scan-runtime-script';
|
||||
|
||||
interface LoggerLike {
|
||||
error: (message: string, ...args: unknown[]) => void;
|
||||
@@ -22,8 +30,6 @@ interface YomitanParserRuntimeDeps {
|
||||
createYomitanExtensionWindow?: (pageName: string) => Promise<BrowserWindow | null>;
|
||||
}
|
||||
|
||||
type YomitanFrequencyMode = 'occurrence-based' | 'rank-based';
|
||||
|
||||
export interface YomitanDictionaryInfo {
|
||||
title: string;
|
||||
revision?: string | number;
|
||||
@@ -74,13 +80,19 @@ export interface YomitanAddNoteResult {
|
||||
}
|
||||
|
||||
const DEFAULT_YOMITAN_SCAN_LENGTH = 40;
|
||||
const CHARACTER_DICTIONARY_TITLE_PREFIX = 'SubMiner Character Dictionary';
|
||||
const yomitanProfileMetadataByWindow = new WeakMap<BrowserWindow, YomitanProfileMetadata>();
|
||||
const yomitanProfileDiagnosticsLoggedByWindow = new WeakSet<BrowserWindow>();
|
||||
const yomitanFrequencyCacheByWindow = new WeakMap<
|
||||
BrowserWindow,
|
||||
Map<string, YomitanTermFrequency[]>
|
||||
>();
|
||||
// Epoch passed with every scan request; the in-window termsFind cache clears
|
||||
// itself when the epoch changes (dictionary imports, settings changes).
|
||||
const yomitanScanCacheEpochByWindow = new WeakMap<BrowserWindow, number>();
|
||||
|
||||
function getYomitanScanCacheEpoch(window: BrowserWindow): number {
|
||||
return yomitanScanCacheEpochByWindow.get(window) ?? 0;
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value && typeof value === 'object');
|
||||
@@ -99,6 +111,7 @@ function isScanTokenArray(value: unknown): value is YomitanScanToken[] {
|
||||
typeof entry.startPos === 'number' &&
|
||||
typeof entry.endPos === 'number' &&
|
||||
(entry.isNameMatch === undefined || typeof entry.isNameMatch === 'boolean') &&
|
||||
(entry.isUnparsedRun === undefined || typeof entry.isUnparsedRun === 'boolean') &&
|
||||
(entry.frequencyRank === undefined || typeof entry.frequencyRank === 'number') &&
|
||||
(entry.wordClasses === undefined ||
|
||||
(Array.isArray(entry.wordClasses) &&
|
||||
@@ -107,13 +120,9 @@ function isScanTokenArray(value: unknown): value is YomitanScanToken[] {
|
||||
);
|
||||
}
|
||||
|
||||
function scanTokenSpanKey(token: YomitanScanToken): string {
|
||||
return `${token.startPos}:${token.endPos}:${token.surface}`;
|
||||
}
|
||||
|
||||
// Maps a parse-selected token to the scanner-token shape carried out of the
|
||||
// parser runtime. Shared by both selectYomitanParseTokens fallback paths so the
|
||||
// projected fields stay in sync as the shape changes.
|
||||
// parser runtime, used by the parseText fallback path when the in-window
|
||||
// scanner is unavailable.
|
||||
function toYomitanScanToken(token: {
|
||||
surface: string;
|
||||
reading: string;
|
||||
@@ -132,66 +141,6 @@ function toYomitanScanToken(token: {
|
||||
};
|
||||
}
|
||||
|
||||
// parseText segmentation is authoritative (it emits filler chunks for text the
|
||||
// termsFind scanner skips), but only the termsFind scanner carries annotation
|
||||
// metadata (isNameMatch, frequencyRank, headwordReading, wordClasses). Graft
|
||||
// scanner tokens onto the parseText segmentation per matching span so one
|
||||
// unmatched chunk degrades only itself instead of dropping the whole line's
|
||||
// metadata.
|
||||
//
|
||||
// Exception: character-name tokens. The greedy name scan can re-segment text
|
||||
// around a name (e.g. とヨータ → と + ヨータ instead of とヨー + タ), so
|
||||
// parseText segmentation cannot be authoritative there. Each name span is
|
||||
// expanded until it aligns with token boundaries in both segmentations, then
|
||||
// the parse tokens inside are replaced with the scanner tokens.
|
||||
function mergeScannerTokensIntoParseTokens(
|
||||
parseScanTokens: YomitanScanToken[],
|
||||
scannerTokens: YomitanScanToken[],
|
||||
): YomitanScanToken[] {
|
||||
const scannerTokensBySpan = new Map<string, YomitanScanToken>();
|
||||
for (const token of scannerTokens) {
|
||||
scannerTokensBySpan.set(scanTokenSpanKey(token), token);
|
||||
}
|
||||
const graftedTokens = parseScanTokens.map(
|
||||
(token) => scannerTokensBySpan.get(scanTokenSpanKey(token)) ?? token,
|
||||
);
|
||||
|
||||
const nameTokens = scannerTokens.filter((token) => token.isNameMatch === true);
|
||||
if (nameTokens.length === 0) {
|
||||
return graftedTokens;
|
||||
}
|
||||
|
||||
const regions = nameTokens.map((token) => ({ start: token.startPos, end: token.endPos }));
|
||||
const allTokens = [...parseScanTokens, ...scannerTokens];
|
||||
let expanded = true;
|
||||
while (expanded) {
|
||||
expanded = false;
|
||||
for (const region of regions) {
|
||||
for (const token of allTokens) {
|
||||
const overlaps = token.startPos < region.end && token.endPos > region.start;
|
||||
const extendsBeyond = token.startPos < region.start || token.endPos > region.end;
|
||||
if (overlaps && extendsBeyond) {
|
||||
region.start = Math.min(region.start, token.startPos);
|
||||
region.end = Math.max(region.end, token.endPos);
|
||||
expanded = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const isInsideNameRegion = (token: YomitanScanToken): boolean =>
|
||||
regions.some((region) => token.startPos >= region.start && token.endPos <= region.end);
|
||||
|
||||
const merged = graftedTokens.filter((token) => !isInsideNameRegion(token));
|
||||
for (const token of scannerTokens) {
|
||||
if (isInsideNameRegion(token)) {
|
||||
merged.push(token);
|
||||
}
|
||||
}
|
||||
merged.sort((a, b) => a.startPos - b.startPos || a.endPos - b.endPos);
|
||||
return merged;
|
||||
}
|
||||
|
||||
function makeTermReadingCacheKey(term: string, reading: string | null): string {
|
||||
return `${term}\u0000${reading ?? ''}`;
|
||||
}
|
||||
@@ -208,6 +157,7 @@ function getWindowFrequencyCache(window: BrowserWindow): Map<string, YomitanTerm
|
||||
function clearWindowCaches(window: BrowserWindow): void {
|
||||
yomitanProfileMetadataByWindow.delete(window);
|
||||
yomitanFrequencyCacheByWindow.delete(window);
|
||||
yomitanScanCacheEpochByWindow.set(window, getYomitanScanCacheEpoch(window) + 1);
|
||||
}
|
||||
export function clearYomitanParserCachesForWindow(window: BrowserWindow): void {
|
||||
clearWindowCaches(window);
|
||||
@@ -704,6 +654,10 @@ async function ensureYomitanParserWindow(
|
||||
if (readyPromise) {
|
||||
await readyPromise;
|
||||
}
|
||||
// Eagerly install the scan runtime so the first subtitle line does not
|
||||
// pay the install round trip; failures fall back to the per-request
|
||||
// install-and-retry path.
|
||||
await installYomitanScanRuntime(parserWindow).catch(() => {});
|
||||
|
||||
return true;
|
||||
} catch (err) {
|
||||
@@ -877,668 +831,42 @@ async function serveDictionaryZipOnce<T>(
|
||||
}
|
||||
}
|
||||
|
||||
const YOMITAN_SCANNING_HELPERS = String.raw`
|
||||
const HIRAGANA_CONVERSION_RANGE = [0x3041, 0x3096];
|
||||
const KATAKANA_CONVERSION_RANGE = [0x30a1, 0x30f6];
|
||||
const KANA_PROLONGED_SOUND_MARK_CODE_POINT = 0x30fc;
|
||||
const KATAKANA_SMALL_KA_CODE_POINT = 0x30f5;
|
||||
const KATAKANA_SMALL_KE_CODE_POINT = 0x30f6;
|
||||
const KANA_RANGES = [[0x3040, 0x309f], [0x30a0, 0x30ff]];
|
||||
const JAPANESE_RANGES = [[0x3040, 0x30ff], [0x3400, 0x9fff]];
|
||||
function isCodePointInRange(codePoint, range) { return codePoint >= range[0] && codePoint <= range[1]; }
|
||||
function isCodePointInRanges(codePoint, ranges) { return ranges.some((range) => isCodePointInRange(codePoint, range)); }
|
||||
function isCodePointKana(codePoint) { return isCodePointInRanges(codePoint, KANA_RANGES); }
|
||||
function isCodePointJapanese(codePoint) { return isCodePointInRanges(codePoint, JAPANESE_RANGES); }
|
||||
function createFuriganaSegment(text, reading) { return {text, reading}; }
|
||||
function getSegmentReadingContribution(segment) {
|
||||
if (typeof segment.reading === "string" && segment.reading.length > 0) { return segment.reading; }
|
||||
const segmentText = typeof segment.text === "string" ? segment.text : "";
|
||||
const isKanaOnly = segmentText.length > 0 && [...segmentText].every((char) => isCodePointKana(char.codePointAt(0)));
|
||||
return isKanaOnly ? segmentText : "";
|
||||
}
|
||||
function getProlongedHiragana(previousCharacter) {
|
||||
switch (previousCharacter) {
|
||||
case "あ": case "か": case "が": case "さ": case "ざ": case "た": case "だ": case "な": case "は": case "ば": case "ぱ": case "ま": case "や": case "ら": case "わ": case "ぁ": case "ゃ": case "ゎ": return "あ";
|
||||
case "い": case "き": case "ぎ": case "し": case "じ": case "ち": case "ぢ": case "に": case "ひ": case "び": case "ぴ": case "み": case "り": case "ぃ": return "い";
|
||||
case "う": case "く": case "ぐ": case "す": case "ず": case "つ": case "づ": case "ぬ": case "ふ": case "ぶ": case "ぷ": case "む": case "ゆ": case "る": case "ぅ": case "ゅ": return "う";
|
||||
case "え": case "け": case "げ": case "せ": case "ぜ": case "て": case "で": case "ね": case "へ": case "べ": case "ぺ": case "め": case "れ": case "ぇ": return "え";
|
||||
case "お": case "こ": case "ご": case "そ": case "ぞ": case "と": case "ど": case "の": case "ほ": case "ぼ": case "ぽ": case "も": case "よ": case "ろ": case "を": case "ぉ": case "ょ": return "う";
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
function getFuriganaKanaSegments(text, reading) {
|
||||
const newSegments = [];
|
||||
let start = 0;
|
||||
let state = (reading[0] === text[0]);
|
||||
for (let i = 1; i < text.length; ++i) {
|
||||
const newState = (reading[i] === text[i]);
|
||||
if (state === newState) { continue; }
|
||||
newSegments.push(createFuriganaSegment(text.substring(start, i), state ? '' : reading.substring(start, i)));
|
||||
state = newState;
|
||||
start = i;
|
||||
}
|
||||
newSegments.push(createFuriganaSegment(text.substring(start), state ? '' : reading.substring(start)));
|
||||
return newSegments;
|
||||
}
|
||||
function convertKatakanaToHiragana(text, keepProlongedSoundMarks = false) {
|
||||
let result = '';
|
||||
const offset = (HIRAGANA_CONVERSION_RANGE[0] - KATAKANA_CONVERSION_RANGE[0]);
|
||||
for (let char of text) {
|
||||
const codePoint = char.codePointAt(0);
|
||||
switch (codePoint) {
|
||||
case KATAKANA_SMALL_KA_CODE_POINT:
|
||||
case KATAKANA_SMALL_KE_CODE_POINT:
|
||||
break;
|
||||
case KANA_PROLONGED_SOUND_MARK_CODE_POINT:
|
||||
if (!keepProlongedSoundMarks && result.length > 0) {
|
||||
const char2 = getProlongedHiragana(result[result.length - 1]);
|
||||
if (char2 !== null) { char = char2; }
|
||||
}
|
||||
break;
|
||||
default:
|
||||
if (isCodePointInRange(codePoint, KATAKANA_CONVERSION_RANGE)) {
|
||||
char = String.fromCodePoint(codePoint + offset);
|
||||
}
|
||||
break;
|
||||
}
|
||||
result += char;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function segmentizeFurigana(reading, readingNormalized, groups, groupsStart) {
|
||||
const groupCount = groups.length - groupsStart;
|
||||
if (groupCount <= 0) { return reading.length === 0 ? [] : null; }
|
||||
const group = groups[groupsStart];
|
||||
const {isKana, text} = group;
|
||||
if (isKana) {
|
||||
if (group.textNormalized !== null && readingNormalized.startsWith(group.textNormalized)) {
|
||||
const segments = segmentizeFurigana(reading.substring(text.length), readingNormalized.substring(text.length), groups, groupsStart + 1);
|
||||
if (segments !== null) {
|
||||
if (reading.startsWith(text)) { segments.unshift(createFuriganaSegment(text, '')); }
|
||||
else { segments.unshift(...getFuriganaKanaSegments(text, reading)); }
|
||||
return segments;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
let result = null;
|
||||
for (let i = reading.length; i >= text.length; --i) {
|
||||
const segments = segmentizeFurigana(reading.substring(i), readingNormalized.substring(i), groups, groupsStart + 1);
|
||||
if (segments !== null) {
|
||||
if (result !== null) { return null; }
|
||||
segments.unshift(createFuriganaSegment(text, reading.substring(0, i)));
|
||||
result = segments;
|
||||
}
|
||||
if (groupCount === 1) { break; }
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function distributeFurigana(term, reading) {
|
||||
if (reading === term) { return [createFuriganaSegment(term, '')]; }
|
||||
const groups = [];
|
||||
let groupPre = null;
|
||||
let isKanaPre = null;
|
||||
for (const c of term) {
|
||||
const isKana = isCodePointKana(c.codePointAt(0));
|
||||
if (isKana === isKanaPre) { groupPre.text += c; }
|
||||
else {
|
||||
groupPre = {isKana, text: c, textNormalized: null};
|
||||
groups.push(groupPre);
|
||||
isKanaPre = isKana;
|
||||
}
|
||||
}
|
||||
for (const group of groups) {
|
||||
if (group.isKana) { group.textNormalized = convertKatakanaToHiragana(group.text); }
|
||||
}
|
||||
const segments = segmentizeFurigana(reading, convertKatakanaToHiragana(reading), groups, 0);
|
||||
return segments !== null ? segments : [createFuriganaSegment(term, reading)];
|
||||
}
|
||||
function getStemLength(text1, text2) {
|
||||
const minLength = Math.min(text1.length, text2.length);
|
||||
if (minLength === 0) { return 0; }
|
||||
let i = 0;
|
||||
while (true) {
|
||||
const char1 = text1.codePointAt(i);
|
||||
const char2 = text2.codePointAt(i);
|
||||
if (char1 !== char2) { break; }
|
||||
const charLength = String.fromCodePoint(char1).length;
|
||||
i += charLength;
|
||||
if (i >= minLength) {
|
||||
if (i > minLength) { i -= charLength; }
|
||||
break;
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
function distributeFuriganaInflected(term, reading, source) {
|
||||
const termNormalized = convertKatakanaToHiragana(term);
|
||||
const readingNormalized = convertKatakanaToHiragana(reading);
|
||||
const sourceNormalized = convertKatakanaToHiragana(source);
|
||||
let mainText = term;
|
||||
let stemLength = getStemLength(termNormalized, sourceNormalized);
|
||||
const readingStemLength = getStemLength(readingNormalized, sourceNormalized);
|
||||
if (readingStemLength > 0 && readingStemLength >= stemLength) {
|
||||
mainText = reading;
|
||||
stemLength = readingStemLength;
|
||||
reading = source.substring(0, stemLength) + reading.substring(stemLength);
|
||||
}
|
||||
const segments = [];
|
||||
if (stemLength > 0) {
|
||||
mainText = source.substring(0, stemLength) + mainText.substring(stemLength);
|
||||
const segments2 = distributeFurigana(mainText, reading);
|
||||
let consumed = 0;
|
||||
for (const segment of segments2) {
|
||||
const start = consumed;
|
||||
consumed += segment.text.length;
|
||||
if (consumed < stemLength) { segments.push(segment); }
|
||||
else if (consumed === stemLength) { segments.push(segment); break; }
|
||||
else {
|
||||
if (start < stemLength) { segments.push(createFuriganaSegment(mainText.substring(start, stemLength), '')); }
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stemLength < source.length) {
|
||||
const remainder = source.substring(stemLength);
|
||||
const last = segments[segments.length - 1];
|
||||
if (last && last.reading.length === 0) { last.text += remainder; }
|
||||
else { segments.push(createFuriganaSegment(remainder, '')); }
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
function parsePositiveFrequencyNumber(value) {
|
||||
if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
|
||||
return Math.max(1, Math.floor(value));
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
const numericMatch = value.trim().match(/[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?/)?.[0];
|
||||
if (!numericMatch) { return null; }
|
||||
const parsed = Number.parseFloat(numericMatch);
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) { return null; }
|
||||
return Math.max(1, Math.floor(parsed));
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
const parsed = parsePositiveFrequencyNumber(item);
|
||||
if (parsed !== null) { return parsed; }
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function parseDisplayFrequencyNumber(value) {
|
||||
if (typeof value === 'string') {
|
||||
const leadingDigits = value.trim().match(/^\d+/)?.[0];
|
||||
if (!leadingDigits) { return null; }
|
||||
const parsed = Number.parseInt(leadingDigits, 10);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
||||
}
|
||||
return parsePositiveFrequencyNumber(value);
|
||||
}
|
||||
function getFrequencyDictionaryName(frequency) {
|
||||
const candidates = [
|
||||
frequency?.dictionary,
|
||||
frequency?.dictionaryName,
|
||||
frequency?.name,
|
||||
frequency?.title,
|
||||
frequency?.dictionaryTitle,
|
||||
frequency?.dictionaryAlias
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
if (typeof candidate === 'string' && candidate.trim().length > 0) {
|
||||
return candidate.trim();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function getBestFrequencyRank(dictionaryEntry, headwordIndex, dictionaryPriorityByName, dictionaryFrequencyModeByName) {
|
||||
let best = null;
|
||||
const headwordCount = Array.isArray(dictionaryEntry?.headwords) ? dictionaryEntry.headwords.length : 0;
|
||||
for (const frequency of dictionaryEntry?.frequencies || []) {
|
||||
if (!frequency || typeof frequency !== 'object') { continue; }
|
||||
const frequencyHeadwordIndex = frequency.headwordIndex;
|
||||
if (typeof frequencyHeadwordIndex === 'number') {
|
||||
if (frequencyHeadwordIndex !== headwordIndex) { continue; }
|
||||
} else if (headwordCount > 1) {
|
||||
continue;
|
||||
}
|
||||
const dictionary = getFrequencyDictionaryName(frequency);
|
||||
if (!dictionary) { continue; }
|
||||
if (dictionaryFrequencyModeByName[dictionary] === 'occurrence-based') { continue; }
|
||||
const rank =
|
||||
parseDisplayFrequencyNumber(frequency.displayValue) ??
|
||||
parsePositiveFrequencyNumber(frequency.frequency);
|
||||
if (rank === null) { continue; }
|
||||
const priorityRaw = dictionaryPriorityByName[dictionary];
|
||||
const fallbackPriority =
|
||||
typeof frequency.dictionaryIndex === 'number' && Number.isFinite(frequency.dictionaryIndex)
|
||||
? Math.max(0, Math.floor(frequency.dictionaryIndex))
|
||||
: Number.MAX_SAFE_INTEGER;
|
||||
const priority =
|
||||
typeof priorityRaw === 'number' && Number.isFinite(priorityRaw)
|
||||
? Math.max(0, Math.floor(priorityRaw))
|
||||
: fallbackPriority;
|
||||
if (best === null || priority < best.priority || (priority === best.priority && rank < best.rank)) {
|
||||
best = { priority, rank };
|
||||
}
|
||||
}
|
||||
return best?.rank ?? null;
|
||||
}
|
||||
function hasExactSource(headword, token, requirePrimary) {
|
||||
for (const src of headword.sources || []) {
|
||||
if (src.originalText !== token) { continue; }
|
||||
if (requirePrimary && !src.isPrimary) { continue; }
|
||||
if (src.matchType !== 'exact') { continue; }
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function collectExactHeadwordMatches(dictionaryEntries, token, requirePrimary) {
|
||||
const matches = [];
|
||||
for (const dictionaryEntry of dictionaryEntries || []) {
|
||||
const headwords = Array.isArray(dictionaryEntry?.headwords) ? dictionaryEntry.headwords : [];
|
||||
for (let headwordIndex = 0; headwordIndex < headwords.length; headwordIndex += 1) {
|
||||
const headword = headwords[headwordIndex];
|
||||
if (!hasExactSource(headword, token, requirePrimary)) { continue; }
|
||||
matches.push({ dictionaryEntry, headword, headwordIndex });
|
||||
}
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
function sameHeadword(match, preferredMatch) {
|
||||
if (!match || !preferredMatch) {
|
||||
return false;
|
||||
}
|
||||
if (match.headword?.term !== preferredMatch.headword?.term) {
|
||||
return false;
|
||||
}
|
||||
const matchReading = typeof match.headword?.reading === 'string' ? match.headword.reading : '';
|
||||
const preferredReading =
|
||||
typeof preferredMatch.headword?.reading === 'string' ? preferredMatch.headword.reading : '';
|
||||
if (!matchReading || !preferredReading) {
|
||||
return true;
|
||||
}
|
||||
return matchReading === preferredReading;
|
||||
}
|
||||
function getBestFrequencyRankForMatches(matches, dictionaryPriorityByName, dictionaryFrequencyModeByName) {
|
||||
let best = null;
|
||||
for (const match of matches) {
|
||||
const rank = getBestFrequencyRank(
|
||||
match.dictionaryEntry,
|
||||
match.headwordIndex,
|
||||
dictionaryPriorityByName,
|
||||
dictionaryFrequencyModeByName
|
||||
);
|
||||
if (rank === null) { continue; }
|
||||
if (best === null || rank < best) {
|
||||
best = rank;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
function normalizeWordClasses(headword) {
|
||||
if (!Array.isArray(headword?.wordClasses)) { return undefined; }
|
||||
const classes = headword.wordClasses.filter((wordClass) => typeof wordClass === "string" && wordClass.trim().length > 0);
|
||||
return classes.length > 0 ? classes : undefined;
|
||||
}
|
||||
function appendDictionaryNames(target, value) {
|
||||
if (!value || typeof value !== 'object') {
|
||||
return;
|
||||
}
|
||||
const candidates = [
|
||||
value.dictionary,
|
||||
value.dictionaryName,
|
||||
value.name,
|
||||
value.title,
|
||||
value.dictionaryTitle,
|
||||
value.dictionaryAlias
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
if (typeof candidate === 'string' && candidate.trim().length > 0) {
|
||||
target.push(candidate.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
function getDictionaryEntryNames(entry) {
|
||||
const names = [];
|
||||
appendDictionaryNames(names, entry);
|
||||
for (const definition of entry?.definitions || []) {
|
||||
appendDictionaryNames(names, definition);
|
||||
}
|
||||
for (const frequency of entry?.frequencies || []) {
|
||||
appendDictionaryNames(names, frequency);
|
||||
}
|
||||
for (const pronunciation of entry?.pronunciations || []) {
|
||||
appendDictionaryNames(names, pronunciation);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
function isNameDictionaryEntry(entry) {
|
||||
if (!includeNameMatchMetadata || !entry || typeof entry !== 'object') {
|
||||
return false;
|
||||
}
|
||||
return getDictionaryEntryNames(entry).some((name) => name.startsWith(${JSON.stringify(CHARACTER_DICTIONARY_TITLE_PREFIX)}));
|
||||
}
|
||||
function parseSubMinerMediaIdFromString(value) {
|
||||
const imageMatch = value.match(/\bimg\/m(\d+)-/i);
|
||||
if (imageMatch) {
|
||||
const parsed = Number.parseInt(imageMatch[1], 10);
|
||||
if (Number.isSafeInteger(parsed) && parsed > 0) { return parsed; }
|
||||
}
|
||||
const titleMatch = value.match(/${CHARACTER_DICTIONARY_TITLE_PREFIX}[^\d]*(?:AniList\s*)?(\d+)/i);
|
||||
if (titleMatch) {
|
||||
const parsed = Number.parseInt(titleMatch[1], 10);
|
||||
if (Number.isSafeInteger(parsed) && parsed > 0) { return parsed; }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function parseSubMinerMediaIdCandidate(value) {
|
||||
if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
|
||||
const parsed = Number.parseInt(value.trim(), 10);
|
||||
if (Number.isSafeInteger(parsed) && parsed > 0) { return parsed; }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function collectSubMinerMediaIds(value, target) {
|
||||
if (typeof value === 'string') {
|
||||
const parsed = parseSubMinerMediaIdFromString(value);
|
||||
if (parsed !== null) { target.add(parsed); }
|
||||
return;
|
||||
}
|
||||
if (!value || typeof value !== 'object') {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) { collectSubMinerMediaIds(item, target); }
|
||||
return;
|
||||
}
|
||||
const mediaIdCandidates = [
|
||||
value.subminerMediaId,
|
||||
value.subMinerMediaId,
|
||||
value.characterDictionaryMediaId,
|
||||
value.data?.subminerMediaId,
|
||||
value.data?.subMinerMediaId,
|
||||
value.data?.characterDictionaryMediaId
|
||||
];
|
||||
for (const candidate of mediaIdCandidates) {
|
||||
const parsed = parseSubMinerMediaIdCandidate(candidate);
|
||||
if (parsed !== null) { target.add(parsed); }
|
||||
}
|
||||
for (const child of Object.values(value)) {
|
||||
collectSubMinerMediaIds(child, target);
|
||||
}
|
||||
}
|
||||
function getSubMinerMediaIds(entry) {
|
||||
const mediaIds = new Set();
|
||||
collectSubMinerMediaIds(entry, mediaIds);
|
||||
return mediaIds;
|
||||
}
|
||||
function isCurrentMediaNameDictionaryEntry(entry) {
|
||||
if (!isNameDictionaryEntry(entry)) {
|
||||
return false;
|
||||
}
|
||||
if (currentCharacterDictionaryMediaId === null) {
|
||||
return true;
|
||||
}
|
||||
const mediaIds = getSubMinerMediaIds(entry);
|
||||
return mediaIds.size === 0 || mediaIds.has(currentCharacterDictionaryMediaId);
|
||||
}
|
||||
function findLongestNameMatch(dictionaryEntries, textWindow) {
|
||||
let best = null;
|
||||
for (const dictionaryEntry of dictionaryEntries || []) {
|
||||
if (!isCurrentMediaNameDictionaryEntry(dictionaryEntry)) { continue; }
|
||||
const headwords = Array.isArray(dictionaryEntry?.headwords) ? dictionaryEntry.headwords : [];
|
||||
for (let headwordIndex = 0; headwordIndex < headwords.length; headwordIndex += 1) {
|
||||
const headword = headwords[headwordIndex];
|
||||
for (const src of headword?.sources || []) {
|
||||
if (src.matchType !== 'exact' || src.isPrimary !== true) { continue; }
|
||||
const originalText = typeof src.originalText === 'string' ? src.originalText : '';
|
||||
if (!originalText || !textWindow.startsWith(originalText)) { continue; }
|
||||
if (best === null || originalText.length > best.sourceLength) {
|
||||
best = { dictionaryEntry, headword, headwordIndex, sourceLength: originalText.length };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
function findLongestGenericMatchLength(dictionaryEntries, textWindow) {
|
||||
let best = 0;
|
||||
for (const dictionaryEntry of dictionaryEntries || []) {
|
||||
if (isNameDictionaryEntry(dictionaryEntry)) { continue; }
|
||||
const headwords = Array.isArray(dictionaryEntry?.headwords) ? dictionaryEntry.headwords : [];
|
||||
for (const headword of headwords) {
|
||||
for (const src of headword?.sources || []) {
|
||||
if (src.matchType !== 'exact' || src.isPrimary !== true) { continue; }
|
||||
const originalText = typeof src.originalText === 'string' ? src.originalText : '';
|
||||
if (!originalText || !textWindow.startsWith(originalText)) { continue; }
|
||||
if (originalText.length > best) { best = originalText.length; }
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
function getPreferredHeadword(dictionaryEntries, token, dictionaryPriorityByName, dictionaryFrequencyModeByName) {
|
||||
const currentMediaDictionaryEntries =
|
||||
currentCharacterDictionaryMediaId === null
|
||||
? (dictionaryEntries || [])
|
||||
: (dictionaryEntries || []).filter((entry) => {
|
||||
if (!isNameDictionaryEntry(entry)) { return true; }
|
||||
return isCurrentMediaNameDictionaryEntry(entry);
|
||||
});
|
||||
const exactPrimaryMatches = collectExactHeadwordMatches(currentMediaDictionaryEntries, token, true);
|
||||
let matchedNameDictionary = false;
|
||||
if (includeNameMatchMetadata) {
|
||||
for (const dictionaryEntry of currentMediaDictionaryEntries || []) {
|
||||
if (!isCurrentMediaNameDictionaryEntry(dictionaryEntry)) { continue; }
|
||||
for (const match of exactPrimaryMatches) {
|
||||
if (match.dictionaryEntry !== dictionaryEntry) { continue; }
|
||||
matchedNameDictionary = true;
|
||||
break;
|
||||
}
|
||||
if (matchedNameDictionary) { break; }
|
||||
}
|
||||
}
|
||||
const preferredMatch = exactPrimaryMatches[0];
|
||||
if (preferredMatch) {
|
||||
const exactFrequencyMatches = collectExactHeadwordMatches(currentMediaDictionaryEntries, token, false)
|
||||
.filter((match) => sameHeadword(match, preferredMatch));
|
||||
return {
|
||||
term: preferredMatch.headword.term,
|
||||
reading: preferredMatch.headword.reading,
|
||||
wordClasses: normalizeWordClasses(preferredMatch.headword),
|
||||
isNameMatch:
|
||||
matchedNameDictionary || isCurrentMediaNameDictionaryEntry(preferredMatch.dictionaryEntry),
|
||||
frequencyRank: getBestFrequencyRankForMatches(
|
||||
exactFrequencyMatches.length > 0 ? exactFrequencyMatches : exactPrimaryMatches,
|
||||
dictionaryPriorityByName,
|
||||
dictionaryFrequencyModeByName
|
||||
)
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
`;
|
||||
async function installYomitanScanRuntime(parserWindow: BrowserWindow): Promise<void> {
|
||||
await parserWindow.webContents.executeJavaScript(YOMITAN_SCAN_RUNTIME_INSTALL_SCRIPT, true);
|
||||
// A fresh runtime has no candidate list; force the next scan to reinstall it.
|
||||
yomitanScanNameCandidateKeyByWindow.delete(parserWindow);
|
||||
}
|
||||
|
||||
function buildYomitanScanningScript(
|
||||
text: string,
|
||||
profileIndex: number,
|
||||
scanLength: number,
|
||||
includeNameMatchMetadata: boolean,
|
||||
greedyNameScanEnabled: boolean,
|
||||
currentCharacterDictionaryMediaId: number | null,
|
||||
dictionaryPriorityByName: Record<string, number>,
|
||||
dictionaryFrequencyModeByName: Partial<Record<string, YomitanFrequencyMode>>,
|
||||
): string {
|
||||
return `
|
||||
(async () => {
|
||||
const invoke = (action, params) =>
|
||||
new Promise((resolve, reject) => {
|
||||
chrome.runtime.sendMessage({ action, params }, (response) => {
|
||||
if (chrome.runtime.lastError) {
|
||||
reject(new Error(chrome.runtime.lastError.message));
|
||||
return;
|
||||
}
|
||||
if (!response || typeof response !== "object") {
|
||||
reject(new Error("Invalid response from Yomitan backend"));
|
||||
return;
|
||||
}
|
||||
if (response.error) {
|
||||
reject(new Error(response.error.message || "Yomitan backend error"));
|
||||
return;
|
||||
}
|
||||
resolve(response.result);
|
||||
});
|
||||
});
|
||||
${YOMITAN_SCANNING_HELPERS}
|
||||
const includeNameMatchMetadata = ${includeNameMatchMetadata ? 'true' : 'false'};
|
||||
const greedyNameScanEnabled = ${greedyNameScanEnabled ? 'true' : 'false'};
|
||||
const currentCharacterDictionaryMediaId = ${
|
||||
currentCharacterDictionaryMediaId !== null
|
||||
? String(currentCharacterDictionaryMediaId)
|
||||
: 'null'
|
||||
};
|
||||
const dictionaryPriorityByName = ${JSON.stringify(dictionaryPriorityByName)};
|
||||
const dictionaryFrequencyModeByName = ${JSON.stringify(dictionaryFrequencyModeByName)};
|
||||
const text = ${JSON.stringify(text)};
|
||||
const details = {matchType: "exact", deinflect: true};
|
||||
const tokens = [];
|
||||
const termsFindCache = new Map();
|
||||
async function termsFindAt(position, windowLength) {
|
||||
const cacheKey = position + ":" + windowLength;
|
||||
const cached = termsFindCache.get(cacheKey);
|
||||
if (cached) { return cached; }
|
||||
const substring = text.substring(position, position + windowLength);
|
||||
const result = await invoke("termsFind", { text: substring, details, optionsContext: { index: ${profileIndex} } });
|
||||
termsFindCache.set(cacheKey, result);
|
||||
return result;
|
||||
}
|
||||
function buildScanToken(position, source, preferredHeadword) {
|
||||
const reading = typeof preferredHeadword.reading === "string" ? preferredHeadword.reading : "";
|
||||
const segments = distributeFuriganaInflected(preferredHeadword.term, reading, source);
|
||||
const tokenPayload = {
|
||||
surface: segments.map((segment) => segment.text).join("") || source,
|
||||
reading: segments.map(getSegmentReadingContribution).join(""),
|
||||
headword: preferredHeadword.term,
|
||||
headwordReading: reading || undefined,
|
||||
startPos: position,
|
||||
endPos: position + source.length,
|
||||
isNameMatch: includeNameMatchMetadata && preferredHeadword.isNameMatch === true,
|
||||
frequencyRank:
|
||||
typeof preferredHeadword.frequencyRank === "number" && Number.isFinite(preferredHeadword.frequencyRank)
|
||||
? Math.max(1, Math.floor(preferredHeadword.frequencyRank))
|
||||
: undefined,
|
||||
};
|
||||
if (Array.isArray(preferredHeadword.wordClasses) && preferredHeadword.wordClasses.length > 0) {
|
||||
tokenPayload.wordClasses = preferredHeadword.wordClasses;
|
||||
}
|
||||
return tokenPayload;
|
||||
}
|
||||
async function findTokenAt(position, windowLength) {
|
||||
const codePoint = text.codePointAt(position);
|
||||
const character = String.fromCodePoint(codePoint);
|
||||
const result = await termsFindAt(position, windowLength);
|
||||
const dictionaryEntries = Array.isArray(result?.dictionaryEntries) ? result.dictionaryEntries : [];
|
||||
const originalTextLength = typeof result?.originalTextLength === "number" ? result.originalTextLength : 0;
|
||||
if (dictionaryEntries.length === 0 || originalTextLength <= 0 || (originalTextLength === character.length && !isCodePointJapanese(codePoint))) {
|
||||
return { token: null, matchedLength: 0 };
|
||||
}
|
||||
const source = text.substring(position, position + originalTextLength);
|
||||
const preferredHeadword = getPreferredHeadword(
|
||||
dictionaryEntries,
|
||||
source,
|
||||
dictionaryPriorityByName,
|
||||
dictionaryFrequencyModeByName
|
||||
);
|
||||
if (!preferredHeadword || typeof preferredHeadword.term !== "string") {
|
||||
return { token: null, matchedLength: originalTextLength };
|
||||
}
|
||||
return { token: buildScanToken(position, source, preferredHeadword), matchedLength: originalTextLength };
|
||||
}
|
||||
// Greedy name pre-pass: character-name matches claim their spans before
|
||||
// the left-to-right walk, so a longer generic match starting earlier
|
||||
// (e.g. とヨー → 渡洋) cannot swallow the start of a name (ヨータ).
|
||||
const nameTokens = [];
|
||||
if (greedyNameScanEnabled) {
|
||||
let namePos = 0;
|
||||
while (namePos < text.length) {
|
||||
const codePoint = text.codePointAt(namePos);
|
||||
if (!isCodePointJapanese(codePoint)) {
|
||||
namePos += String.fromCodePoint(codePoint).length;
|
||||
continue;
|
||||
}
|
||||
const result = await termsFindAt(namePos, ${scanLength});
|
||||
const dictionaryEntries = Array.isArray(result?.dictionaryEntries) ? result.dictionaryEntries : [];
|
||||
const textWindow = text.substring(namePos, namePos + ${scanLength});
|
||||
const nameMatch = findLongestNameMatch(dictionaryEntries, textWindow);
|
||||
// A name only claims its span when no strictly longer generic word
|
||||
// starts at the same position (a character named 空 must not split
|
||||
// 空気). Ties go to the name. Generic matches that start earlier and
|
||||
// overlap the name are still blocked by the reservation.
|
||||
if (
|
||||
!nameMatch ||
|
||||
findLongestGenericMatchLength(dictionaryEntries, textWindow) > nameMatch.sourceLength
|
||||
) {
|
||||
namePos += String.fromCodePoint(codePoint).length;
|
||||
continue;
|
||||
}
|
||||
const source = text.substring(namePos, namePos + nameMatch.sourceLength);
|
||||
nameTokens.push(buildScanToken(namePos, source, {
|
||||
term: nameMatch.headword.term,
|
||||
reading: nameMatch.headword.reading,
|
||||
wordClasses: normalizeWordClasses(nameMatch.headword),
|
||||
isNameMatch: true,
|
||||
frequencyRank: getBestFrequencyRank(
|
||||
nameMatch.dictionaryEntry,
|
||||
nameMatch.headwordIndex,
|
||||
dictionaryPriorityByName,
|
||||
dictionaryFrequencyModeByName
|
||||
)
|
||||
}));
|
||||
namePos += nameMatch.sourceLength;
|
||||
}
|
||||
}
|
||||
let i = 0;
|
||||
let nameIndex = 0;
|
||||
while (i < text.length) {
|
||||
while (nameIndex < nameTokens.length && nameTokens[nameIndex].startPos < i) { nameIndex += 1; }
|
||||
const nextNameToken = nameIndex < nameTokens.length ? nameTokens[nameIndex] : null;
|
||||
if (nextNameToken && nextNameToken.startPos === i) {
|
||||
tokens.push(nextNameToken);
|
||||
i = nextNameToken.endPos;
|
||||
nameIndex += 1;
|
||||
continue;
|
||||
}
|
||||
// Cap the window at the next reserved name span so a generic match
|
||||
// cannot consume into it.
|
||||
const windowLength = nextNameToken ? Math.min(${scanLength}, nextNameToken.startPos - i) : ${scanLength};
|
||||
let attempt = await findTokenAt(i, windowLength);
|
||||
// Yomitan text normalization can consume characters (whitespace,
|
||||
// punctuation) beyond the matched term, leaving no headword whose
|
||||
// source equals the consumed text. Retry with shorter windows so a
|
||||
// valid prefix term (e.g. a character name before a paren) still
|
||||
// tokenizes instead of the position being skipped.
|
||||
let retryLength = Math.min(attempt.matchedLength, windowLength) - 1;
|
||||
while (!attempt.token && retryLength >= 1) {
|
||||
const retry = await findTokenAt(i, retryLength);
|
||||
if (retry.token) {
|
||||
attempt = retry;
|
||||
break;
|
||||
}
|
||||
retryLength = Math.min(retryLength - 1, retry.matchedLength - 1);
|
||||
}
|
||||
if (attempt.token) {
|
||||
tokens.push(attempt.token);
|
||||
i += attempt.matchedLength;
|
||||
continue;
|
||||
}
|
||||
i += String.fromCodePoint(text.codePointAt(i)).length;
|
||||
}
|
||||
return tokens;
|
||||
})();
|
||||
`;
|
||||
// Key of the character-name candidate list currently installed in each parser
|
||||
// window, so an unchanged list costs nothing per line.
|
||||
const yomitanScanNameCandidateKeyByWindow = new WeakMap<BrowserWindow, string>();
|
||||
|
||||
async function ensureYomitanScanNameCandidates(
|
||||
parserWindow: BrowserWindow,
|
||||
nameCandidates: { key: string; forms: string[] } | null,
|
||||
logger: LoggerLike,
|
||||
): Promise<void> {
|
||||
const installedKey = yomitanScanNameCandidateKeyByWindow.get(parserWindow);
|
||||
const nextKey = nameCandidates?.key ?? '';
|
||||
if (installedKey === nextKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await parserWindow.webContents.executeJavaScript(
|
||||
buildYomitanScanNameCandidatesScript(nameCandidates),
|
||||
true,
|
||||
);
|
||||
yomitanScanNameCandidateKeyByWindow.set(parserWindow, nextKey);
|
||||
} catch (err) {
|
||||
// The scan falls back to checking every position when the list is absent,
|
||||
// so a failed install costs speed, never a missed name.
|
||||
logger.warn?.(
|
||||
'Failed to install Yomitan character-name scan candidates:',
|
||||
(err as Error).message,
|
||||
);
|
||||
yomitanScanNameCandidateKeyByWindow.delete(parserWindow);
|
||||
}
|
||||
}
|
||||
|
||||
export async function requestYomitanParseResults(
|
||||
@@ -1635,6 +963,20 @@ export async function requestYomitanParseResults(
|
||||
}
|
||||
}
|
||||
|
||||
// parseText fallback for when the in-window scanner cannot run (script eval
|
||||
// failure, unexpected payload). The scanner walk is the primary tokenizer and
|
||||
// emits its own filler runs, so this extra full parse only happens on errors.
|
||||
async function requestYomitanParseFallbackTokens(
|
||||
text: string,
|
||||
deps: YomitanParserRuntimeDeps,
|
||||
logger: LoggerLike,
|
||||
): Promise<YomitanScanToken[] | null> {
|
||||
const parseResults = await requestYomitanParseResults(text, deps, logger);
|
||||
const selectedTokens = selectYomitanParseTokens(parseResults, () => false, 'headword');
|
||||
const parseScanTokens = selectedTokens?.map(toYomitanScanToken) ?? null;
|
||||
return parseScanTokens && parseScanTokens.length > 0 ? parseScanTokens : null;
|
||||
}
|
||||
|
||||
export async function requestYomitanScanTokens(
|
||||
text: string,
|
||||
deps: YomitanParserRuntimeDeps,
|
||||
@@ -1642,6 +984,7 @@ export async function requestYomitanScanTokens(
|
||||
options?: {
|
||||
includeNameMatchMetadata?: boolean;
|
||||
currentCharacterDictionaryMediaId?: number | null;
|
||||
nameCandidates?: { key: string; forms: string[] } | null;
|
||||
},
|
||||
): Promise<YomitanScanToken[] | null> {
|
||||
const yomitanExt = deps.getYomitanExt();
|
||||
@@ -1655,10 +998,6 @@ export async function requestYomitanScanTokens(
|
||||
return null;
|
||||
}
|
||||
|
||||
const parseResults = await requestYomitanParseResults(text, deps, logger);
|
||||
const selectedParseTokens = selectYomitanParseTokens(parseResults, () => false, 'headword');
|
||||
const parseScanTokens = selectedParseTokens?.map(toYomitanScanToken) ?? null;
|
||||
|
||||
const metadata = await requestYomitanProfileMetadata(parserWindow, logger);
|
||||
const profileIndex = metadata?.profileIndex ?? 0;
|
||||
const scanLength = metadata?.scanLength ?? DEFAULT_YOMITAN_SCAN_LENGTH;
|
||||
@@ -1669,44 +1008,63 @@ export async function requestYomitanScanTokens(
|
||||
name.startsWith(CHARACTER_DICTIONARY_TITLE_PREFIX),
|
||||
);
|
||||
|
||||
// Candidate name forms let the in-page pre-pass skip positions where no
|
||||
// character name can start. Installed only when it changes (per media), so
|
||||
// the per-line call stays a single tiny script.
|
||||
const nameCandidates = greedyNameScanEnabled ? (options?.nameCandidates ?? null) : null;
|
||||
await ensureYomitanScanNameCandidates(parserWindow, nameCandidates, logger);
|
||||
|
||||
const callScript = buildYomitanScanCallScript({
|
||||
text,
|
||||
profileIndex,
|
||||
scanLength,
|
||||
includeNameMatchMetadata,
|
||||
greedyNameScanEnabled,
|
||||
currentCharacterDictionaryMediaId:
|
||||
typeof options?.currentCharacterDictionaryMediaId === 'number' &&
|
||||
Number.isFinite(options.currentCharacterDictionaryMediaId) &&
|
||||
options.currentCharacterDictionaryMediaId > 0
|
||||
? Math.floor(options.currentCharacterDictionaryMediaId)
|
||||
: null,
|
||||
dictionaryPriorityByName: metadata?.dictionaryPriorityByName ?? {},
|
||||
dictionaryFrequencyModeByName: metadata?.dictionaryFrequencyModeByName ?? {},
|
||||
cacheEpoch: getYomitanScanCacheEpoch(parserWindow),
|
||||
nameCandidateKey: nameCandidates?.key ?? null,
|
||||
});
|
||||
|
||||
try {
|
||||
const rawResult = await parserWindow.webContents.executeJavaScript(
|
||||
buildYomitanScanningScript(
|
||||
text,
|
||||
profileIndex,
|
||||
scanLength,
|
||||
includeNameMatchMetadata,
|
||||
greedyNameScanEnabled,
|
||||
typeof options?.currentCharacterDictionaryMediaId === 'number' &&
|
||||
Number.isFinite(options.currentCharacterDictionaryMediaId) &&
|
||||
options.currentCharacterDictionaryMediaId > 0
|
||||
? Math.floor(options.currentCharacterDictionaryMediaId)
|
||||
: null,
|
||||
metadata?.dictionaryPriorityByName ?? {},
|
||||
metadata?.dictionaryFrequencyModeByName ?? {},
|
||||
),
|
||||
true,
|
||||
);
|
||||
if (isScanTokenArray(rawResult)) {
|
||||
if (parseScanTokens && parseScanTokens.length > 0) {
|
||||
return mergeScannerTokensIntoParseTokens(parseScanTokens, rawResult);
|
||||
let rawResult = await parserWindow.webContents.executeJavaScript(callScript, true);
|
||||
if (rawResult === YOMITAN_SCAN_RUNTIME_MISSING_SENTINEL) {
|
||||
// First request for this window, or the page reloaded and dropped the
|
||||
// installed runtime: install and retry once. The candidate list lives in
|
||||
// the same page state, so it has to be reinstalled alongside it.
|
||||
await installYomitanScanRuntime(parserWindow);
|
||||
await ensureYomitanScanNameCandidates(parserWindow, nameCandidates, logger);
|
||||
rawResult = await parserWindow.webContents.executeJavaScript(callScript, true);
|
||||
}
|
||||
// The scanner reports a line where a position ran out of shrinking-window
|
||||
// retries: it stopped short of windows an uncapped ladder would have tried,
|
||||
// so a real term may be sitting in an unparsed run. One parseText for the
|
||||
// line is the bounded way to get the exhaustive answer back (this is the
|
||||
// parse the scanner replaced, and it only runs for these rare lines).
|
||||
if (isObject(rawResult) && rawResult.retryBudgetExhausted === true) {
|
||||
logger.info?.('Yomitan scanner exhausted its retry budget; parsing the line as a fallback.');
|
||||
const fallbackTokens = await requestYomitanParseFallbackTokens(text, deps, logger);
|
||||
if (fallbackTokens) {
|
||||
return fallbackTokens;
|
||||
}
|
||||
return rawResult;
|
||||
rawResult = rawResult.tokens;
|
||||
}
|
||||
if (Array.isArray(rawResult)) {
|
||||
const selectedTokens = selectYomitanParseTokens(rawResult, () => false, 'headword');
|
||||
return selectedTokens?.map(toYomitanScanToken) ?? null;
|
||||
if (isScanTokenArray(rawResult)) {
|
||||
// Filler-only results carry no dictionary match; keep the historical
|
||||
// contract of returning null so callers fall back to raw text.
|
||||
return rawResult.some((token) => token.isUnparsedRun !== true) ? rawResult : null;
|
||||
}
|
||||
if (parseScanTokens && parseScanTokens.length > 0) {
|
||||
return parseScanTokens;
|
||||
}
|
||||
return null;
|
||||
logger.error('Yomitan scanner returned an unexpected payload; using parseText fallback.');
|
||||
return await requestYomitanParseFallbackTokens(text, deps, logger);
|
||||
} catch (err) {
|
||||
if (parseScanTokens && parseScanTokens.length > 0) {
|
||||
return parseScanTokens;
|
||||
}
|
||||
logger.error('Yomitan scanner request failed:', (err as Error).message);
|
||||
return null;
|
||||
return await requestYomitanParseFallbackTokens(text, deps, logger);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,563 @@
|
||||
// In-page Yomitan scan runtime: the scan walk that gets installed once per
|
||||
// parser window as globalThis.__subminerYomitanScan, plus the tiny per-line
|
||||
// call script. Kept separate from the host runtime module so the injected
|
||||
// script text (which is data, not executed here) does not dominate that file;
|
||||
// the helper bundle it embeds is composed in yomitan-scanning-helpers-script.ts
|
||||
// from the yomitan-*-script.ts fragments.
|
||||
import { YOMITAN_SCANNING_HELPERS } from './yomitan-scanning-helpers-script';
|
||||
|
||||
export { CHARACTER_DICTIONARY_TITLE_PREFIX } from './yomitan-scanning-helpers-script';
|
||||
|
||||
export type YomitanFrequencyMode = 'occurrence-based' | 'rank-based';
|
||||
|
||||
// Bump whenever the install script below changes so already-loaded parser
|
||||
// windows re-install the new scan runtime instead of running the stale one.
|
||||
export const YOMITAN_SCAN_RUNTIME_VERSION = 12;
|
||||
export const YOMITAN_SCAN_RUNTIME_MISSING_SENTINEL = '__subminer-yomitan-scan-runtime-missing__';
|
||||
|
||||
export interface YomitanScanRequestParams {
|
||||
text: string;
|
||||
profileIndex: number;
|
||||
scanLength: number;
|
||||
includeNameMatchMetadata: boolean;
|
||||
greedyNameScanEnabled: boolean;
|
||||
currentCharacterDictionaryMediaId: number | null;
|
||||
dictionaryPriorityByName: Record<string, number>;
|
||||
dictionaryFrequencyModeByName: Partial<Record<string, YomitanFrequencyMode>>;
|
||||
cacheEpoch: number;
|
||||
/**
|
||||
* Key of the character-name candidate list installed for the current media,
|
||||
* or null to scan every Japanese position (see the pre-pass prefilter).
|
||||
*/
|
||||
nameCandidateKey: string | null;
|
||||
}
|
||||
|
||||
// Installed once per parser window (and re-installed after in-page reloads):
|
||||
// keeps V8 from re-parsing the helper bundle on every subtitle line, and hosts
|
||||
// the cross-line termsFind cache. Each subtitle line then only evaluates a tiny
|
||||
// call into globalThis.__subminerYomitanScan.
|
||||
export const YOMITAN_SCAN_RUNTIME_INSTALL_SCRIPT = String.raw`
|
||||
(() => {
|
||||
if (globalThis.__subminerYomitanScanVersion === ${YOMITAN_SCAN_RUNTIME_VERSION}) {
|
||||
return true;
|
||||
}
|
||||
const invoke = (action, params) =>
|
||||
new Promise((resolve, reject) => {
|
||||
chrome.runtime.sendMessage({ action, params }, (response) => {
|
||||
if (chrome.runtime.lastError) {
|
||||
reject(new Error(chrome.runtime.lastError.message));
|
||||
return;
|
||||
}
|
||||
if (!response || typeof response !== "object") {
|
||||
reject(new Error("Invalid response from Yomitan backend"));
|
||||
return;
|
||||
}
|
||||
if (response.error) {
|
||||
reject(new Error(response.error.message || "Yomitan backend error"));
|
||||
return;
|
||||
}
|
||||
resolve(response.result);
|
||||
});
|
||||
});
|
||||
// Cross-line termsFind LRU keyed by profile + substring: subtitle lines
|
||||
// repeat particles and inflections constantly, so most lookups hit here.
|
||||
// Entries hold in-flight promises so concurrent identical lookups dedupe.
|
||||
const termsFindCache = new Map();
|
||||
// Two bounds. The key count keeps the map itself small; the accumulated
|
||||
// dictionary-entry count stands in for retained bytes, because a single
|
||||
// lookup over a common prefix can hold hundreds of entries with their full
|
||||
// glossaries and a key-count cap alone would not bound that.
|
||||
const TERMS_FIND_CACHE_LIMIT = 2000;
|
||||
const TERMS_FIND_CACHE_DICTIONARY_ENTRY_LIMIT = 20000;
|
||||
let termsFindCacheDictionaryEntries = 0;
|
||||
let termsFindCacheEpoch = -1;
|
||||
function dropCachedTermsFind(cacheKey, entry) {
|
||||
if (termsFindCache.get(cacheKey) !== entry) { return; }
|
||||
termsFindCache.delete(cacheKey);
|
||||
termsFindCacheDictionaryEntries -= entry.dictionaryEntryCount;
|
||||
}
|
||||
// Runs on insert and again once a lookup resolves: an entry is only worth
|
||||
// its estimated weight of 1 until then, so a single oversized response
|
||||
// would otherwise sit in the cache forever, over the limit and reused.
|
||||
function evictOverflowingTermsFindEntries() {
|
||||
while (
|
||||
termsFindCache.size > TERMS_FIND_CACHE_LIMIT ||
|
||||
termsFindCacheDictionaryEntries > TERMS_FIND_CACHE_DICTIONARY_ENTRY_LIMIT
|
||||
) {
|
||||
const oldest = termsFindCache.entries().next().value;
|
||||
if (oldest === undefined) { break; }
|
||||
dropCachedTermsFind(oldest[0], oldest[1]);
|
||||
}
|
||||
}
|
||||
// Classification of a dictionary entry (which dictionaries it came from,
|
||||
// which media ids it mentions) depends only on the entry object, so it is
|
||||
// memoized for as long as that object lives. Entries are shared with the
|
||||
// termsFind cache above, which is what makes this worth keeping: the same
|
||||
// objects come back for every repeated lookup, on every line.
|
||||
const dictionaryEntryNamesCache = new WeakMap();
|
||||
const subMinerMediaIdsCache = new WeakMap();
|
||||
const EMPTY_MEDIA_ID_SET = new Set();
|
||||
// Only blind ladder steps are capped (see the retry loop): those are the
|
||||
// ones that would otherwise degrade into O(scanLength) lookups at a single
|
||||
// position. Steps the backend guides by reporting a shorter consumed length
|
||||
// stay uncapped, so a valid prefix term is still found on lines where
|
||||
// normalization eats a long tail.
|
||||
const MAX_BLIND_SHRINKING_WINDOW_RETRIES = 4;
|
||||
// Character-name candidate forms for the current media, installed
|
||||
// separately from the per-line scan call so the per-line script stays tiny.
|
||||
// Stored raw here; the normalized lookup index is built inside the scan,
|
||||
// where the kana-normalization helper is in scope, and reused by key.
|
||||
let rawNameCandidates = null;
|
||||
let nameCandidateIndex = null;
|
||||
globalThis.__subminerYomitanScanSetNameCandidates = (key, forms) => {
|
||||
if (!key || !Array.isArray(forms) || forms.length === 0) {
|
||||
rawNameCandidates = null;
|
||||
nameCandidateIndex = null;
|
||||
return false;
|
||||
}
|
||||
rawNameCandidates = { key, forms };
|
||||
nameCandidateIndex = null;
|
||||
return true;
|
||||
};
|
||||
globalThis.__subminerYomitanScanVersion = ${YOMITAN_SCAN_RUNTIME_VERSION};
|
||||
globalThis.__subminerYomitanScan = async (scanParams) => {
|
||||
const {
|
||||
text,
|
||||
profileIndex,
|
||||
scanLength,
|
||||
includeNameMatchMetadata,
|
||||
greedyNameScanEnabled,
|
||||
currentCharacterDictionaryMediaId,
|
||||
dictionaryPriorityByName,
|
||||
dictionaryFrequencyModeByName,
|
||||
cacheEpoch,
|
||||
nameCandidateKey
|
||||
} = scanParams;
|
||||
if (cacheEpoch !== termsFindCacheEpoch) {
|
||||
termsFindCache.clear();
|
||||
termsFindCacheDictionaryEntries = 0;
|
||||
termsFindCacheEpoch = cacheEpoch;
|
||||
}
|
||||
${YOMITAN_SCANNING_HELPERS}
|
||||
const CAPTION_OPENING_BRACKETS = new Set(["(", "(", "[", "[", "{", "{", "「", "『", "【", "〈", "《", "≪", "<", "<"]);
|
||||
function shouldEmitUnparsedRunAsToken(runText) {
|
||||
if (!/[\p{L}\p{N}]/u.test(runText)) { return false; }
|
||||
const firstChar = Array.from(runText.trim())[0];
|
||||
return firstChar !== undefined && !CAPTION_OPENING_BRACKETS.has(firstChar);
|
||||
}
|
||||
function isLookupWorthyCodePoint(codePoint) {
|
||||
if (isCodePointJapanese(codePoint)) { return true; }
|
||||
return /[\p{L}\p{N}]/u.test(String.fromCodePoint(codePoint));
|
||||
}
|
||||
function isKanaOnlyRunText(runText) {
|
||||
const chars = Array.from(runText);
|
||||
return chars.length > 0 && chars.every((char) => isCodePointKana(char.codePointAt(0)));
|
||||
}
|
||||
const details = {matchType: "exact", deinflect: true};
|
||||
const tokens = [];
|
||||
async function termsFindAt(position, windowLength) {
|
||||
const substring = text.substring(position, position + windowLength);
|
||||
const cacheKey = profileIndex + "\u0000" + substring;
|
||||
const cached = termsFindCache.get(cacheKey);
|
||||
if (cached !== undefined) {
|
||||
termsFindCache.delete(cacheKey);
|
||||
termsFindCache.set(cacheKey, cached);
|
||||
return await cached.promise;
|
||||
}
|
||||
// An in-flight lookup counts as one entry until it resolves; the real
|
||||
// weight replaces that estimate once the result is known.
|
||||
const entry = { promise: null, dictionaryEntryCount: 1 };
|
||||
entry.promise = invoke("termsFind", { text: substring, details, optionsContext: { index: profileIndex } })
|
||||
.then((result) => {
|
||||
const resolvedCount =
|
||||
1 + (Array.isArray(result?.dictionaryEntries) ? result.dictionaryEntries.length : 0);
|
||||
const isCached = termsFindCache.get(cacheKey) === entry;
|
||||
if (isCached) {
|
||||
termsFindCacheDictionaryEntries += resolvedCount - entry.dictionaryEntryCount;
|
||||
}
|
||||
entry.dictionaryEntryCount = resolvedCount;
|
||||
// The real weight can push the cache over its budget, and a single
|
||||
// response can exceed it on its own, so re-check here.
|
||||
if (isCached) { evictOverflowingTermsFindEntries(); }
|
||||
return result;
|
||||
});
|
||||
termsFindCache.set(cacheKey, entry);
|
||||
termsFindCacheDictionaryEntries += entry.dictionaryEntryCount;
|
||||
evictOverflowingTermsFindEntries();
|
||||
try {
|
||||
return await entry.promise;
|
||||
} catch (error) {
|
||||
dropCachedTermsFind(cacheKey, entry);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
// Text the walk skips accumulates into unparsed runs, mirroring the
|
||||
// filler chunks the parseText segmentation used to provide: runs stay
|
||||
// hoverable (flagged isUnparsedRun) unless they are punctuation-only or
|
||||
// caption-style asides, and kana continuations of a longer headword
|
||||
// extend the previous token instead.
|
||||
function flushUnparsedRun(runStart, runEnd) {
|
||||
if (runStart === null || runEnd <= runStart) { return; }
|
||||
const runText = text.substring(runStart, runEnd);
|
||||
const previousToken = tokens[tokens.length - 1];
|
||||
if (
|
||||
previousToken &&
|
||||
previousToken.endPos === runStart &&
|
||||
isKanaOnlyRunText(runText) &&
|
||||
typeof previousToken.headword === "string" &&
|
||||
previousToken.headword.length > previousToken.surface.length &&
|
||||
previousToken.headword.startsWith(previousToken.surface + runText)
|
||||
) {
|
||||
previousToken.surface += runText;
|
||||
// The run is kana-only, so its reading is itself: append it or the
|
||||
// reading stops covering the surface, which disables the known-word
|
||||
// reading fallback (isCompleteReadingForSurface) downstream.
|
||||
previousToken.reading += runText;
|
||||
// The run is kana-only, so its reading is itself: append it or the
|
||||
// reading stops covering the surface, which disables the known-word
|
||||
// reading fallback (isCompleteReadingForSurface) downstream.
|
||||
previousToken.endPos = runEnd;
|
||||
return;
|
||||
}
|
||||
if (!shouldEmitUnparsedRunAsToken(runText)) { return; }
|
||||
tokens.push({
|
||||
surface: runText,
|
||||
reading: "",
|
||||
headword: runText,
|
||||
startPos: runStart,
|
||||
endPos: runEnd,
|
||||
isUnparsedRun: true
|
||||
});
|
||||
}
|
||||
function buildScanToken(position, source, preferredHeadword) {
|
||||
const reading = typeof preferredHeadword.reading === "string" ? preferredHeadword.reading : "";
|
||||
const segments = distributeFuriganaInflected(preferredHeadword.term, reading, source);
|
||||
const tokenPayload = {
|
||||
surface: segments.map((segment) => segment.text).join("") || source,
|
||||
reading: segments.map(getSegmentReadingContribution).join(""),
|
||||
headword: preferredHeadword.term,
|
||||
headwordReading: reading || undefined,
|
||||
startPos: position,
|
||||
endPos: position + source.length,
|
||||
isNameMatch: includeNameMatchMetadata && preferredHeadword.isNameMatch === true,
|
||||
frequencyRank:
|
||||
typeof preferredHeadword.frequencyRank === "number" && Number.isFinite(preferredHeadword.frequencyRank)
|
||||
? Math.max(1, Math.floor(preferredHeadword.frequencyRank))
|
||||
: undefined,
|
||||
};
|
||||
if (Array.isArray(preferredHeadword.wordClasses) && preferredHeadword.wordClasses.length > 0) {
|
||||
tokenPayload.wordClasses = preferredHeadword.wordClasses;
|
||||
}
|
||||
return tokenPayload;
|
||||
}
|
||||
// findTokenAt plus the shrinking-window ladder below it: Yomitan text
|
||||
// normalization can consume characters (whitespace, punctuation) beyond
|
||||
// the matched term, leaving no headword whose source equals the consumed
|
||||
// text. Retry with shorter windows so a valid prefix term (e.g. a
|
||||
// character name before a paren) still tokenizes instead of the position
|
||||
// being skipped.
|
||||
// Every window at or above the consumed length repeats the same result,
|
||||
// so the next informative window sits just below it. A lookup that
|
||||
// consumed its whole window reports nothing to aim at, and the step down
|
||||
// from it is a blind guess: only those are budgeted.
|
||||
// The window can run past the end of the line, so blindness is judged
|
||||
// against the text the lookup actually saw.
|
||||
// Set when a position stopped short of windows an uncapped ladder would
|
||||
// still have tried; the line then escalates to parseText at the end.
|
||||
let blindRetryBudgetExhausted = false;
|
||||
async function resolveTokenAt(position, windowLength) {
|
||||
let attempt = await findTokenAt(position, windowLength);
|
||||
const scannedLength = Math.min(windowLength, text.length - position);
|
||||
let retryLength = Math.min(attempt.matchedLength, scannedLength) - 1;
|
||||
let stepIsBlind = attempt.matchedLength >= scannedLength;
|
||||
let blindRetriesRemaining = MAX_BLIND_SHRINKING_WINDOW_RETRIES;
|
||||
while (!attempt.token && retryLength >= 1) {
|
||||
if (stepIsBlind) {
|
||||
if (blindRetriesRemaining <= 0) {
|
||||
blindRetryBudgetExhausted = true;
|
||||
break;
|
||||
}
|
||||
blindRetriesRemaining -= 1;
|
||||
}
|
||||
const retry = await findTokenAt(position, retryLength);
|
||||
if (retry.token) { return retry; }
|
||||
const guidedLength = retry.matchedLength - 1;
|
||||
stepIsBlind = guidedLength >= retryLength - 1;
|
||||
retryLength = Math.min(retryLength - 1, guidedLength);
|
||||
}
|
||||
return attempt;
|
||||
}
|
||||
async function findTokenAt(position, windowLength) {
|
||||
const codePoint = text.codePointAt(position);
|
||||
const character = String.fromCodePoint(codePoint);
|
||||
const result = await termsFindAt(position, windowLength);
|
||||
const dictionaryEntries = Array.isArray(result?.dictionaryEntries) ? result.dictionaryEntries : [];
|
||||
const originalTextLength = typeof result?.originalTextLength === "number" ? result.originalTextLength : 0;
|
||||
if (dictionaryEntries.length === 0 || originalTextLength <= 0 || (originalTextLength === character.length && !isCodePointJapanese(codePoint))) {
|
||||
return { token: null, matchedLength: 0 };
|
||||
}
|
||||
const source = text.substring(position, position + originalTextLength);
|
||||
const preferredHeadword = getPreferredHeadword(
|
||||
dictionaryEntries,
|
||||
source,
|
||||
dictionaryPriorityByName,
|
||||
dictionaryFrequencyModeByName
|
||||
);
|
||||
if (!preferredHeadword || typeof preferredHeadword.term !== "string") {
|
||||
return { token: null, matchedLength: originalTextLength };
|
||||
}
|
||||
return { token: buildScanToken(position, source, preferredHeadword), matchedLength: originalTextLength };
|
||||
}
|
||||
// Kana normalization folds halfwidth katakana one code point to one, so an
|
||||
// unvoiced halfwidth spelling prefix-matches a candidate form like any
|
||||
// other. What it cannot fold is a voiced pair: カ + ゙ stays two characters
|
||||
// where the candidate form carries the single が, so the comparison fails
|
||||
// at that character. That break can sit anywhere inside the name, not
|
||||
// just at its first character (山ガク starts on a kanji), so the bypass is
|
||||
// keyed on the region a candidate could cover, not on how it starts.
|
||||
function isHalfwidthKanaVoicedMarkCodePoint(codePoint) {
|
||||
return codePoint === 0xff9e || codePoint === 0xff9f;
|
||||
}
|
||||
// Build (once per candidate list) a first-character bucket index of the
|
||||
// normalized name forms, so the pre-pass can reject a position with a
|
||||
// single map hit instead of a backend round trip.
|
||||
if (rawNameCandidates && nameCandidateIndex?.key !== rawNameCandidates.key) {
|
||||
const byFirstChar = new Map();
|
||||
for (const form of rawNameCandidates.forms) {
|
||||
const normalized = typeof form === "string" ? convertKatakanaToHiragana(form.trim()) : "";
|
||||
if (!normalized) { continue; }
|
||||
const bucket = byFirstChar.get(normalized[0]);
|
||||
if (bucket) { bucket.push(normalized); } else { byFirstChar.set(normalized[0], [normalized]); }
|
||||
}
|
||||
nameCandidateIndex = byFirstChar.size > 0 ? { key: rawNameCandidates.key, byFirstChar } : null;
|
||||
} else if (!rawNameCandidates) {
|
||||
nameCandidateIndex = null;
|
||||
}
|
||||
// Only meaningful when the installed list matches the media this scan is
|
||||
// for; otherwise fall back to scanning every position.
|
||||
const activeNameCandidateIndex =
|
||||
nameCandidateKey !== null && nameCandidateIndex?.key === nameCandidateKey
|
||||
? nameCandidateIndex
|
||||
: null;
|
||||
const normalizedText = activeNameCandidateIndex ? convertKatakanaToHiragana(text) : "";
|
||||
// Yomitan collapses emphatic sequences before matching (すっっごーーい →
|
||||
// すごい), so a stretched name still resolves to its entry. Skipping these
|
||||
// characters keeps such spellings candidates; the filter only ever grows
|
||||
// the probe set, so a false positive costs one lookup, never a name.
|
||||
const EMPHATIC_SKIP_CHARS = new Set(["ぁ", "ぃ", "ぅ", "ぇ", "ぉ", "っ", "ゃ", "ゅ", "ょ", "ー"]);
|
||||
function matchesCandidateFormAt(form, position) {
|
||||
let textIndex = position;
|
||||
for (let formIndex = 0; formIndex < form.length; formIndex += 1) {
|
||||
while (
|
||||
textIndex < normalizedText.length &&
|
||||
normalizedText[textIndex] !== form[formIndex] &&
|
||||
EMPHATIC_SKIP_CHARS.has(normalizedText[textIndex])
|
||||
) {
|
||||
textIndex += 1;
|
||||
}
|
||||
if (normalizedText[textIndex] !== form[formIndex]) { return false; }
|
||||
textIndex += 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Where the folding gives up, listed once per line. Matching may skip any
|
||||
// number of emphatic characters on its way through a form (山ーーーーーーガク),
|
||||
// so there is no shorter honest bound than the window a name lookup
|
||||
// covers: scanLength. The list is almost always empty, which is what
|
||||
// keeps the check below free on ordinary lines.
|
||||
const halfwidthVoicedMarkPositions = [];
|
||||
if (activeNameCandidateIndex) {
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
if (isHalfwidthKanaVoicedMarkCodePoint(text.charCodeAt(index))) {
|
||||
halfwidthVoicedMarkPositions.push(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
function hasHalfwidthVoicedMarkInScanWindow(position) {
|
||||
const end = position + scanLength;
|
||||
for (const markPosition of halfwidthVoicedMarkPositions) {
|
||||
if (markPosition >= position && markPosition < end) { return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// A name written ガ... folds to か + ゙, so its first character never leads
|
||||
// to the が bucket the candidate form is filed under. Nothing else can
|
||||
// find it, so such a position is always worth a probe.
|
||||
function startsHalfwidthVoicedPair(position, codePoint) {
|
||||
if (codePoint < 0xff66 || codePoint > 0xff9d) { return false; }
|
||||
return isHalfwidthKanaVoicedMarkCodePoint(text.charCodeAt(position + 1));
|
||||
}
|
||||
function couldNameStartAt(position, codePoint) {
|
||||
// Nothing starts with a combining voiced mark, whether or not the
|
||||
// prefilter is active.
|
||||
if (isHalfwidthKanaVoicedMarkCodePoint(codePoint)) { return false; }
|
||||
if (!activeNameCandidateIndex) { return true; }
|
||||
const bucket = activeNameCandidateIndex.byFirstChar.get(normalizedText[position]);
|
||||
if (!bucket) {
|
||||
// No candidate begins with this character, and the window search
|
||||
// below would only ever say yes to positions like this one, so an
|
||||
// unrelated ガ elsewhere in the line must not drag them in.
|
||||
return startsHalfwidthVoicedPair(position, codePoint);
|
||||
}
|
||||
for (const form of bucket) {
|
||||
if (matchesCandidateFormAt(form, position)) { return true; }
|
||||
}
|
||||
// A candidate does start here but did not match: an unfoldable voiced
|
||||
// pair anywhere in the window is a reason the comparison could not see
|
||||
// it (山ガク, 山ーーーーーーガク), so probe rather than drop the name.
|
||||
return hasHalfwidthVoicedMarkInScanWindow(position);
|
||||
}
|
||||
// Greedy name pre-pass: character-name matches claim their spans before
|
||||
// the left-to-right walk, so a longer generic match starting earlier
|
||||
// (e.g. とヨー → 渡洋) cannot swallow the start of a name (ヨータ).
|
||||
const nameTokens = [];
|
||||
if (greedyNameScanEnabled) {
|
||||
let namePos = 0;
|
||||
while (namePos < text.length) {
|
||||
const codePoint = text.codePointAt(namePos);
|
||||
if (!isCodePointJapanese(codePoint) || !couldNameStartAt(namePos, codePoint)) {
|
||||
namePos += String.fromCodePoint(codePoint).length;
|
||||
continue;
|
||||
}
|
||||
const result = await termsFindAt(namePos, scanLength);
|
||||
const dictionaryEntries = Array.isArray(result?.dictionaryEntries) ? result.dictionaryEntries : [];
|
||||
const textWindow = text.substring(namePos, namePos + scanLength);
|
||||
const nameMatch = findLongestNameMatch(dictionaryEntries, textWindow);
|
||||
// A name only claims its span when no strictly longer generic word
|
||||
// starts at the same position (a character named 空 must not split
|
||||
// 空気). Ties go to the name. Generic matches that start earlier and
|
||||
// overlap the name are still blocked by the reservation.
|
||||
if (
|
||||
!nameMatch ||
|
||||
findLongestGenericMatchLength(dictionaryEntries, textWindow) > nameMatch.sourceLength
|
||||
) {
|
||||
namePos += String.fromCodePoint(codePoint).length;
|
||||
continue;
|
||||
}
|
||||
const source = text.substring(namePos, namePos + nameMatch.sourceLength);
|
||||
nameTokens.push(buildScanToken(namePos, source, {
|
||||
term: nameMatch.headword.term,
|
||||
reading: nameMatch.headword.reading,
|
||||
wordClasses: normalizeWordClasses(nameMatch.headword),
|
||||
isNameMatch: true,
|
||||
frequencyRank: getBestFrequencyRank(
|
||||
nameMatch.dictionaryEntry,
|
||||
nameMatch.headwordIndex,
|
||||
dictionaryPriorityByName,
|
||||
dictionaryFrequencyModeByName
|
||||
)
|
||||
}));
|
||||
namePos += nameMatch.sourceLength;
|
||||
}
|
||||
}
|
||||
// First reserved name span that a match ending at endPos would leave
|
||||
// half-consumed. Spans the match covers entirely are not returned: those
|
||||
// lose to the longer word instead of splitting it.
|
||||
function findSplitNameToken(startIndex, endPos) {
|
||||
for (let index = startIndex; index < nameTokens.length; index += 1) {
|
||||
const nameToken = nameTokens[index];
|
||||
if (nameToken.startPos >= endPos) { return null; }
|
||||
if (nameToken.endPos > endPos) { return nameToken; }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
let i = 0;
|
||||
let nameIndex = 0;
|
||||
let unparsedRunStart = null;
|
||||
while (i < text.length) {
|
||||
while (nameIndex < nameTokens.length && nameTokens[nameIndex].startPos < i) { nameIndex += 1; }
|
||||
const nextNameToken = nameIndex < nameTokens.length ? nameTokens[nameIndex] : null;
|
||||
if (nextNameToken && nextNameToken.startPos === i) {
|
||||
flushUnparsedRun(unparsedRunStart, i);
|
||||
unparsedRunStart = null;
|
||||
tokens.push(nextNameToken);
|
||||
i = nextNameToken.endPos;
|
||||
nameIndex += 1;
|
||||
continue;
|
||||
}
|
||||
const codePoint = text.codePointAt(i);
|
||||
// Punctuation and whitespace can never start a token: skip the backend
|
||||
// round trip entirely. Latin letters and digits stay lookup-worthy
|
||||
// (terms like Tシャツ start on an ASCII letter).
|
||||
if (!isLookupWorthyCodePoint(codePoint)) {
|
||||
if (unparsedRunStart === null) { unparsedRunStart = i; }
|
||||
i += String.fromCodePoint(codePoint).length;
|
||||
continue;
|
||||
}
|
||||
// A reservation only outranks generic matches that would cut into it.
|
||||
// Look the position up unrestricted first: a generic word that starts
|
||||
// earlier and covers the whole name span (写真 over a character named
|
||||
// 真) is the better reading, so the reservation yields rather than
|
||||
// splitting the word. Only a match that ends inside a name span gets
|
||||
// re-run against a window capped at that span.
|
||||
let attempt = await resolveTokenAt(i, scanLength);
|
||||
if (attempt.token) {
|
||||
const splitNameToken = findSplitNameToken(nameIndex, attempt.token.endPos);
|
||||
if (splitNameToken) {
|
||||
attempt = await resolveTokenAt(i, splitNameToken.startPos - i);
|
||||
}
|
||||
}
|
||||
if (attempt.token) {
|
||||
flushUnparsedRun(unparsedRunStart, i);
|
||||
unparsedRunStart = null;
|
||||
tokens.push(attempt.token);
|
||||
i += attempt.matchedLength;
|
||||
continue;
|
||||
}
|
||||
if (unparsedRunStart === null) { unparsedRunStart = i; }
|
||||
i += String.fromCodePoint(text.codePointAt(i)).length;
|
||||
}
|
||||
flushUnparsedRun(unparsedRunStart, text.length);
|
||||
if (blindRetryBudgetExhausted) {
|
||||
// A position gave up with shorter windows still worth trying. The walk
|
||||
// is the only tokenizer now, so stopping there would leave a real term
|
||||
// as an unparsed run; report it so the host can spend one parseText on
|
||||
// the line instead of letting the ladder run to O(scanLength) lookups.
|
||||
return { tokens, retryBudgetExhausted: true };
|
||||
}
|
||||
return tokens;
|
||||
};
|
||||
return true;
|
||||
})();
|
||||
`;
|
||||
|
||||
// Installs (or clears) the character-name candidate forms for the current
|
||||
// media. Runs only when the list changes, not per line. Passing null restores
|
||||
// the exhaustive every-position pre-pass.
|
||||
export function buildYomitanScanNameCandidatesScript(
|
||||
nameCandidates: { key: string; forms: string[] } | null,
|
||||
): string {
|
||||
if (!nameCandidates) {
|
||||
return `
|
||||
(() => {
|
||||
if (typeof globalThis.__subminerYomitanScanSetNameCandidates !== "function") {
|
||||
return false;
|
||||
}
|
||||
return globalThis.__subminerYomitanScanSetNameCandidates(null, null);
|
||||
})();
|
||||
`;
|
||||
}
|
||||
|
||||
return `
|
||||
(() => {
|
||||
if (typeof globalThis.__subminerYomitanScanSetNameCandidates !== "function") {
|
||||
return false;
|
||||
}
|
||||
return globalThis.__subminerYomitanScanSetNameCandidates(
|
||||
${JSON.stringify(nameCandidates.key)},
|
||||
${JSON.stringify(nameCandidates.forms)}
|
||||
);
|
||||
})();
|
||||
`;
|
||||
}
|
||||
|
||||
export function buildYomitanScanCallScript(params: YomitanScanRequestParams): string {
|
||||
return `
|
||||
(async () => {
|
||||
if (typeof globalThis.__subminerYomitanScan !== "function") {
|
||||
return ${JSON.stringify(YOMITAN_SCAN_RUNTIME_MISSING_SENTINEL)};
|
||||
}
|
||||
return await globalThis.__subminerYomitanScan(${JSON.stringify(params)});
|
||||
})();
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { requestYomitanScanTokens } from './yomitan-parser-runtime';
|
||||
import {
|
||||
countTermsFindLookups,
|
||||
createNameScanDeps,
|
||||
NAME_SCAN_WORDS,
|
||||
} from './yomitan-scan-test-harness';
|
||||
|
||||
// Behaviour of the in-page scan runtime around character names and kana:
|
||||
// which positions the greedy pre-pass probes, and what the walk makes of
|
||||
// halfwidth spellings. Driven end to end through requestYomitanScanTokens
|
||||
// because the runtime only exists inside the parser window.
|
||||
|
||||
const NAME_SCAN_LINE = 'ミナトはまだ学校にいない';
|
||||
|
||||
test('requestYomitanScanTokens skips name pre-pass lookups where no candidate name can start', async () => {
|
||||
const exhaustiveLookups: string[] = [];
|
||||
const exhaustive = await requestYomitanScanTokens(
|
||||
NAME_SCAN_LINE,
|
||||
createNameScanDeps(exhaustiveLookups),
|
||||
{ error: () => undefined },
|
||||
{ includeNameMatchMetadata: true },
|
||||
);
|
||||
|
||||
const prefilteredLookups: string[] = [];
|
||||
const prefiltered = await requestYomitanScanTokens(
|
||||
NAME_SCAN_LINE,
|
||||
createNameScanDeps(prefilteredLookups),
|
||||
{ error: () => undefined },
|
||||
{
|
||||
includeNameMatchMetadata: true,
|
||||
currentCharacterDictionaryMediaId: 1,
|
||||
// Terms and readings the generated dictionary exposes for this media.
|
||||
nameCandidates: { key: 'media-1', forms: ['ミナト', 'みなと'] },
|
||||
},
|
||||
);
|
||||
|
||||
// Same tokenization, including the name match, with fewer round trips.
|
||||
assert.deepEqual(prefiltered, exhaustive);
|
||||
assert.equal(prefiltered?.[0]?.surface, 'ミナト');
|
||||
assert.equal(prefiltered?.[0]?.isNameMatch, true);
|
||||
assert.ok(
|
||||
prefilteredLookups.length < exhaustiveLookups.length,
|
||||
`expected fewer lookups with candidates (${prefilteredLookups.length} vs ${exhaustiveLookups.length})`,
|
||||
);
|
||||
// Mid-token positions are exactly what the pre-pass used to probe (a name can
|
||||
// start mid-token); with candidates they cost nothing, while the main walk's
|
||||
// own token-start lookups are unaffected.
|
||||
assert.ok(countTermsFindLookups(exhaustiveLookups, '校に') > 0);
|
||||
assert.equal(countTermsFindLookups(prefilteredLookups, '校に'), 0);
|
||||
});
|
||||
|
||||
test('requestYomitanScanTokens matches a katakana name from its kana-normalized candidate form', async () => {
|
||||
const lookups: string[] = [];
|
||||
const result = await requestYomitanScanTokens(
|
||||
NAME_SCAN_LINE,
|
||||
createNameScanDeps(lookups),
|
||||
{ error: () => undefined },
|
||||
{
|
||||
includeNameMatchMetadata: true,
|
||||
currentCharacterDictionaryMediaId: 1,
|
||||
// Only the hiragana reading is listed; the katakana surface in the line
|
||||
// must still be found through kana normalization.
|
||||
nameCandidates: { key: 'media-1', forms: ['みなと'] },
|
||||
},
|
||||
);
|
||||
|
||||
assert.equal(result?.[0]?.surface, 'ミナト');
|
||||
assert.equal(result?.[0]?.isNameMatch, true);
|
||||
});
|
||||
|
||||
// Kana normalization folds halfwidth katakana, so a name written that way does
|
||||
// prefix-match a candidate form — but only if the position counts as Japanese
|
||||
// in the first place. The generic word here reaches into the name, so only a
|
||||
// pre-pass reservation can keep the name whole.
|
||||
const HALFWIDTH_NAME_SCAN_WORDS: Array<[string, string, string, boolean]> = [
|
||||
['ネコ', 'ネコ', 'ねこ', false],
|
||||
['まだミ', 'まだミ', 'まだみ', false],
|
||||
['まだ', 'まだ', 'まだ', false],
|
||||
['ミナト', 'ミナト', 'みなと', true],
|
||||
];
|
||||
|
||||
test('requestYomitanScanTokens probes halfwidth katakana positions during the name pre-pass', async () => {
|
||||
const lookups: string[] = [];
|
||||
const result = await requestYomitanScanTokens(
|
||||
'ネコまだミナト',
|
||||
createNameScanDeps(lookups, HALFWIDTH_NAME_SCAN_WORDS),
|
||||
{ error: () => undefined },
|
||||
{
|
||||
includeNameMatchMetadata: true,
|
||||
currentCharacterDictionaryMediaId: 1,
|
||||
// Fullwidth forms only, as the generated dictionary stores them.
|
||||
nameCandidates: { key: 'media-1', forms: ['ミナト', 'みなと'] },
|
||||
},
|
||||
);
|
||||
|
||||
assert.equal(countTermsFindLookups(lookups, 'ミナト'), 1);
|
||||
// コ is mid-token, so only the pre-pass would ever look it up, and it matches
|
||||
// no candidate: folding halfwidth made those positions indexable, so they no
|
||||
// longer cost a round trip apiece.
|
||||
assert.equal(countTermsFindLookups(lookups, 'コ'), 0);
|
||||
assert.deepEqual(
|
||||
result?.map((token) => token.surface),
|
||||
['ネコ', 'まだ', 'ミナト'],
|
||||
);
|
||||
assert.equal(result?.[2]?.isNameMatch, true);
|
||||
// The reading is written the way the fullwidth katakana path writes it
|
||||
// (surface spelling, fullwidth): halfwidth kana is not kana to the known-word
|
||||
// and frequency code downstream, and an empty reading there disables the
|
||||
// reading fallback entirely.
|
||||
assert.equal(result?.[2]?.reading, 'ミナト');
|
||||
assert.equal(result?.[2]?.headwordReading, 'みなと');
|
||||
});
|
||||
|
||||
test('a voiced halfwidth name still bypasses the candidate prefilter', async () => {
|
||||
const lookups: string[] = [];
|
||||
const result = await requestYomitanScanTokens(
|
||||
'まだガク',
|
||||
createNameScanDeps(lookups, [
|
||||
['まだカ', 'まだカ', 'まだか', false],
|
||||
['まだ', 'まだ', 'まだ', false],
|
||||
['ガク', 'ガク', 'がく', true],
|
||||
]),
|
||||
{ error: () => undefined },
|
||||
{
|
||||
includeNameMatchMetadata: true,
|
||||
currentCharacterDictionaryMediaId: 1,
|
||||
nameCandidates: { key: 'media-1', forms: ['ガク', 'がく'] },
|
||||
},
|
||||
);
|
||||
|
||||
// カ + ゙ folds to か + ゙, which cannot prefix-match が, so the prefilter would
|
||||
// drop this position; the voiced-mark bypass is what keeps the name.
|
||||
assert.deepEqual(
|
||||
result?.map((token) => token.surface),
|
||||
['まだ', 'ガク'],
|
||||
);
|
||||
assert.equal(result?.[1]?.isNameMatch, true);
|
||||
});
|
||||
|
||||
test('an unrelated halfwidth voiced word does not restore the exhaustive pre-pass', async () => {
|
||||
const baseline: string[] = [];
|
||||
await requestYomitanScanTokens(
|
||||
NAME_SCAN_LINE,
|
||||
createNameScanDeps(baseline),
|
||||
{ error: () => undefined },
|
||||
{
|
||||
includeNameMatchMetadata: true,
|
||||
currentCharacterDictionaryMediaId: 1,
|
||||
nameCandidates: { key: 'media-1', forms: ['ミナト', 'みなと'] },
|
||||
},
|
||||
);
|
||||
|
||||
const withVoicedTail: string[] = [];
|
||||
await requestYomitanScanTokens(
|
||||
`${NAME_SCAN_LINE}ガ`,
|
||||
createNameScanDeps(withVoicedTail),
|
||||
{ error: () => undefined },
|
||||
{
|
||||
includeNameMatchMetadata: true,
|
||||
currentCharacterDictionaryMediaId: 1,
|
||||
nameCandidates: { key: 'media-1', forms: ['ミナト', 'みなと'] },
|
||||
},
|
||||
);
|
||||
|
||||
// Mid-token positions are the ones only the pre-pass would ever probe. A ガ
|
||||
// anywhere in the line used to drag every position within scanLength of it
|
||||
// back in; now only the voiced pair itself, which the fold cannot index, is
|
||||
// added to what the line already looked up.
|
||||
for (const midTokenPrefix of ['ナト', 'だ学', '校に', 'ない']) {
|
||||
assert.equal(countTermsFindLookups(baseline, midTokenPrefix), 0, midTokenPrefix);
|
||||
assert.equal(countTermsFindLookups(withVoicedTail, midTokenPrefix), 0, midTokenPrefix);
|
||||
}
|
||||
assert.ok(
|
||||
withVoicedTail.length - baseline.length <= 3,
|
||||
`expected the ガ tail to add only its own lookups, saw ${JSON.stringify(withVoicedTail)}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('a mixed-width voiced name survives the candidate prefilter', async () => {
|
||||
const lookups: string[] = [];
|
||||
const result = await requestYomitanScanTokens(
|
||||
'まだ山ガク',
|
||||
createNameScanDeps(lookups, [
|
||||
['まだ山', 'まだ山', 'まだやま', false],
|
||||
['まだ', 'まだ', 'まだ', false],
|
||||
['山ガク', '山ガク', 'やまがく', true],
|
||||
]),
|
||||
{ error: () => undefined },
|
||||
{
|
||||
includeNameMatchMetadata: true,
|
||||
currentCharacterDictionaryMediaId: 1,
|
||||
nameCandidates: { key: 'media-1', forms: ['山ガク', 'やまがく'] },
|
||||
},
|
||||
);
|
||||
|
||||
// The name starts on a kanji, so the fold only breaks mid-name: 山ガク
|
||||
// normalizes to 山がく, which still cannot match the candidate 山がく. The
|
||||
// bypass is keyed on the scan window rather than the first character, so the
|
||||
// position is still probed and the generic まだ山 cannot swallow the 山.
|
||||
assert.deepEqual(
|
||||
result?.map((token) => token.surface),
|
||||
['まだ', '山ガク'],
|
||||
);
|
||||
assert.equal(result?.[1]?.isNameMatch, true);
|
||||
});
|
||||
|
||||
test('a stretched mixed-width voiced name survives the candidate prefilter', async () => {
|
||||
const lookups: string[] = [];
|
||||
const result = await requestYomitanScanTokens(
|
||||
'まだ山ーーーーーーガク',
|
||||
createNameScanDeps(lookups, [
|
||||
['まだ山', 'まだ山', 'まだやま', false],
|
||||
['まだ', 'まだ', 'まだ', false],
|
||||
['山ーーーーーーガク', '山ガク', 'やまがく', true],
|
||||
]),
|
||||
{ error: () => undefined },
|
||||
{
|
||||
includeNameMatchMetadata: true,
|
||||
currentCharacterDictionaryMediaId: 1,
|
||||
nameCandidates: { key: 'media-1', forms: ['山ガク', 'やまがく'] },
|
||||
},
|
||||
);
|
||||
|
||||
// Matching skips any number of emphatic characters, so the voiced mark that
|
||||
// defeats the fold can sit arbitrarily far into the name: the search for it
|
||||
// has to cover the whole lookup window, not a multiple of the form length.
|
||||
assert.deepEqual(
|
||||
result?.map((token) => token.surface),
|
||||
['まだ', '山ーーーーーーガク'],
|
||||
);
|
||||
assert.equal(result?.[1]?.isNameMatch, true);
|
||||
});
|
||||
|
||||
test('halfwidth voiced kana compose into the reading instead of leaving a stray mark', async () => {
|
||||
const lookups: string[] = [];
|
||||
const result = await requestYomitanScanTokens(
|
||||
'ガク パン',
|
||||
createNameScanDeps(lookups, [
|
||||
['ガク', 'ガク', 'がく', false],
|
||||
['パン', 'パン', 'ぱん', false],
|
||||
]),
|
||||
{ error: () => undefined },
|
||||
{ includeNameMatchMetadata: true },
|
||||
);
|
||||
|
||||
// The name pre-pass runs over every position here (no candidate list), but a
|
||||
// standalone voiced mark can never start a name, so it costs no lookup.
|
||||
assert.equal(countTermsFindLookups(lookups, '゙'), 0);
|
||||
assert.equal(countTermsFindLookups(lookups, '゚'), 0);
|
||||
const readings = (result ?? [])
|
||||
.filter((token) => token.isUnparsedRun !== true)
|
||||
.map((token) => [token.surface, token.reading]);
|
||||
assert.deepEqual(readings, [
|
||||
['ガク', 'ガク'],
|
||||
['パン', 'パン'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('requestYomitanScanTokens falls back to the exhaustive name scan without candidates', async () => {
|
||||
const withoutLookups: string[] = [];
|
||||
const withoutCandidates = await requestYomitanScanTokens(
|
||||
NAME_SCAN_LINE,
|
||||
createNameScanDeps(withoutLookups),
|
||||
{ error: () => undefined },
|
||||
{ includeNameMatchMetadata: true, currentCharacterDictionaryMediaId: 1, nameCandidates: null },
|
||||
);
|
||||
|
||||
assert.equal(withoutCandidates?.[0]?.isNameMatch, true);
|
||||
// No candidate list means every Japanese position is probed, as before.
|
||||
assert.ok(countTermsFindLookups(withoutLookups, '校に') > 0);
|
||||
});
|
||||
|
||||
test('requestYomitanScanTokens reinstalls name candidates when the media changes', async () => {
|
||||
const lookups: string[] = [];
|
||||
const deps = createNameScanDeps(lookups);
|
||||
|
||||
// First media's candidates cannot match this line's name.
|
||||
const otherMedia = await requestYomitanScanTokens(
|
||||
NAME_SCAN_LINE,
|
||||
deps,
|
||||
{ error: () => undefined },
|
||||
{
|
||||
includeNameMatchMetadata: true,
|
||||
currentCharacterDictionaryMediaId: 2,
|
||||
nameCandidates: { key: 'media-2', forms: ['カズマ'] },
|
||||
},
|
||||
);
|
||||
assert.equal(otherMedia?.[0]?.isNameMatch, undefined);
|
||||
|
||||
const correctMedia = await requestYomitanScanTokens(
|
||||
NAME_SCAN_LINE,
|
||||
deps,
|
||||
{ error: () => undefined },
|
||||
{
|
||||
includeNameMatchMetadata: true,
|
||||
currentCharacterDictionaryMediaId: 1,
|
||||
nameCandidates: { key: 'media-1', forms: ['ミナト'] },
|
||||
},
|
||||
);
|
||||
assert.equal(correctMedia?.[0]?.surface, 'ミナト');
|
||||
assert.equal(correctMedia?.[0]?.isNameMatch, true);
|
||||
});
|
||||
@@ -0,0 +1,166 @@
|
||||
// Shared harness for the Yomitan parser-runtime and scan-runtime tests: fake
|
||||
// parser-window deps whose injected scripts run in a vm context, plus the
|
||||
// backend stubs the scanner tests drive them with. Kept out of the test files
|
||||
// so the runtime tests and the in-page scanner tests can share one setup.
|
||||
import * as vm from 'node:vm';
|
||||
|
||||
export function createDeps(
|
||||
executeJavaScript: (script: string) => Promise<unknown>,
|
||||
options?: {
|
||||
createYomitanExtensionWindow?: (pageName: string) => Promise<unknown>;
|
||||
},
|
||||
) {
|
||||
const parserWindow = {
|
||||
isDestroyed: () => false,
|
||||
webContents: {
|
||||
executeJavaScript: async (script: string) => await executeJavaScript(script),
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
getYomitanExt: () => ({ id: 'ext-id' }) as never,
|
||||
getYomitanParserWindow: () => parserWindow as never,
|
||||
setYomitanParserWindow: () => undefined,
|
||||
getYomitanParserReadyPromise: () => null,
|
||||
setYomitanParserReadyPromise: () => undefined,
|
||||
getYomitanParserInitPromise: () => null,
|
||||
setYomitanParserInitPromise: () => undefined,
|
||||
createYomitanExtensionWindow: options?.createYomitanExtensionWindow as never,
|
||||
};
|
||||
}
|
||||
|
||||
function createYomitanScriptSandbox(handler: (action: string, params: unknown) => unknown) {
|
||||
return {
|
||||
chrome: {
|
||||
runtime: {
|
||||
lastError: null,
|
||||
sendMessage: (
|
||||
payload: { action?: string; params?: unknown },
|
||||
callback: (response: { result?: unknown; error?: { message?: string } }) => void,
|
||||
) => {
|
||||
try {
|
||||
callback({ result: handler(payload.action ?? '', payload.params) });
|
||||
} catch (error) {
|
||||
callback({ error: { message: (error as Error).message } });
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
Array,
|
||||
Error,
|
||||
JSON,
|
||||
Map,
|
||||
Math,
|
||||
Number,
|
||||
Object,
|
||||
Promise,
|
||||
RegExp,
|
||||
Set,
|
||||
String,
|
||||
};
|
||||
}
|
||||
|
||||
export async function runInjectedYomitanScript(
|
||||
script: string,
|
||||
handler: (action: string, params: unknown) => unknown,
|
||||
): Promise<unknown> {
|
||||
return await vm.runInNewContext(script, createYomitanScriptSandbox(handler));
|
||||
}
|
||||
|
||||
// Persistent page context shared across executeJavaScript calls, matching the
|
||||
// real parser window: the scan runtime is installed once via
|
||||
// globalThis.__subminerYomitanScan and per-line calls reuse it (and its
|
||||
// cross-line termsFind cache).
|
||||
function createPersistentYomitanScriptRunner(
|
||||
handler: (action: string, params: unknown) => unknown,
|
||||
): (script: string) => Promise<unknown> {
|
||||
const context = vm.createContext(createYomitanScriptSandbox(handler));
|
||||
return async (script: string) => await vm.runInContext(script, context);
|
||||
}
|
||||
|
||||
// Deps whose parser window executes every injected script (profile metadata,
|
||||
// scan runtime install, per-line scan calls, parseText fallback) inside one
|
||||
// persistent vm context, dispatching backend actions to `handler`.
|
||||
export function createScanDeps(
|
||||
handler: (action: string, params: unknown) => unknown,
|
||||
options?: { onScript?: (script: string) => void },
|
||||
) {
|
||||
const runScript = createPersistentYomitanScriptRunner(handler);
|
||||
return createDeps(async (script) => {
|
||||
options?.onScript?.(script);
|
||||
return await runScript(script);
|
||||
});
|
||||
}
|
||||
|
||||
export function countTermsFindLookups(lookups: string[], prefix: string): number {
|
||||
return lookups.filter((lookupText) => lookupText.startsWith(prefix)).length;
|
||||
}
|
||||
|
||||
// Backend stub for the greedy name pre-pass: one character name (ミナト) in a
|
||||
// line of ordinary words, with the SubMiner character dictionary enabled.
|
||||
export const NAME_SCAN_WORDS: Array<[string, string, string, boolean]> = [
|
||||
['ミナト', 'ミナト', 'みなと', true],
|
||||
['は', 'は', 'は', false],
|
||||
['まだ', 'まだ', 'まだ', false],
|
||||
['学校', '学校', 'がっこう', false],
|
||||
['に', 'に', 'に', false],
|
||||
['いない', 'いる', 'いる', false],
|
||||
];
|
||||
|
||||
export function createNameScanDeps(
|
||||
lookups: string[],
|
||||
words: Array<[string, string, string, boolean]> = NAME_SCAN_WORDS,
|
||||
) {
|
||||
return createScanDeps((action, params) => {
|
||||
if (action === 'optionsGetFull') {
|
||||
return {
|
||||
profileCurrent: 0,
|
||||
profiles: [
|
||||
{
|
||||
options: {
|
||||
scanning: { length: 40 },
|
||||
dictionaries: [
|
||||
{ name: 'JMdict', enabled: true, id: 0 },
|
||||
{
|
||||
name: 'SubMiner Character Dictionary (AniList 1)',
|
||||
enabled: true,
|
||||
id: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (action === 'getDictionaryInfo') {
|
||||
return [];
|
||||
}
|
||||
if (action !== 'termsFind') {
|
||||
throw new Error(`unexpected action: ${action}`);
|
||||
}
|
||||
const text = (params as { text?: string } | undefined)?.text ?? '';
|
||||
lookups.push(text);
|
||||
for (const [surface, term, reading, isName] of words) {
|
||||
if (text.startsWith(surface)) {
|
||||
return {
|
||||
originalTextLength: surface.length,
|
||||
dictionaryEntries: [
|
||||
{
|
||||
headwords: [
|
||||
{
|
||||
term,
|
||||
reading,
|
||||
sources: [{ originalText: surface, isPrimary: true, matchType: 'exact' }],
|
||||
},
|
||||
],
|
||||
definitions: [
|
||||
{ dictionary: isName ? 'SubMiner Character Dictionary (AniList 1)' : 'JMdict' },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
return { originalTextLength: 0, dictionaryEntries: [] };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Helper bundle for the in-page Yomitan scan runtime, composed from the
|
||||
// fragments below. Injected as text into the parser window by
|
||||
// yomitan-scan-runtime-script.ts, so it is data here, not code this process
|
||||
// runs. The fragments are concatenated into a single function body and share
|
||||
// one lexical scope: every function in them is hoisted, but the constants are
|
||||
// not, so kana stays first — the later fragments read its ranges as they run.
|
||||
import { YOMITAN_DICTIONARY_CLASSIFICATION_HELPERS } from './yomitan-dictionary-classification-script';
|
||||
import { YOMITAN_FREQUENCY_HELPERS } from './yomitan-frequency-script';
|
||||
import { YOMITAN_FURIGANA_HELPERS } from './yomitan-furigana-script';
|
||||
import { YOMITAN_KANA_HELPERS } from './yomitan-kana-script';
|
||||
import { YOMITAN_MATCH_SELECTION_HELPERS } from './yomitan-match-selection-script';
|
||||
|
||||
export { CHARACTER_DICTIONARY_TITLE_PREFIX } from './character-dictionary-title';
|
||||
|
||||
export const YOMITAN_SCANNING_HELPERS = [
|
||||
YOMITAN_KANA_HELPERS,
|
||||
YOMITAN_FURIGANA_HELPERS,
|
||||
YOMITAN_FREQUENCY_HELPERS,
|
||||
YOMITAN_DICTIONARY_CLASSIFICATION_HELPERS,
|
||||
YOMITAN_MATCH_SELECTION_HELPERS,
|
||||
].join('\n');
|
||||
@@ -0,0 +1,54 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { HAN_CODE_POINT_RANGES, HAN_REGEXP_CLASS_BODY, isHanCodePoint } from './han-code-points';
|
||||
|
||||
test('every range boundary is inside the table', () => {
|
||||
for (const [start, end] of HAN_CODE_POINT_RANGES) {
|
||||
for (const codePoint of [start, end]) {
|
||||
assert.ok(isHanCodePoint(codePoint), `expected U+${codePoint.toString(16)} to be Han`);
|
||||
}
|
||||
}
|
||||
|
||||
// Extension J (Unicode 17) and the Compatibility blocks are the ones a
|
||||
// BMP-only table used to miss.
|
||||
assert.ok(isHanCodePoint(0x323b0));
|
||||
assert.ok(isHanCodePoint(0x33479));
|
||||
assert.ok(isHanCodePoint(0xf900));
|
||||
assert.ok(isHanCodePoint(0x2f800));
|
||||
});
|
||||
|
||||
test('no unified ideograph the runtime knows about falls outside the table', () => {
|
||||
// One direction only: a runtime with older Unicode data simply checks fewer
|
||||
// code points, where asserting the reverse would fail on Extension J.
|
||||
const unifiedIdeograph = /\p{Unified_Ideograph}/u;
|
||||
|
||||
for (let codePoint = 0x3000; codePoint <= 0x40000; codePoint += 1) {
|
||||
if (unifiedIdeograph.test(String.fromCodePoint(codePoint))) {
|
||||
assert.ok(
|
||||
isHanCodePoint(codePoint),
|
||||
`expected unified ideograph U+${codePoint.toString(16)} to be in the table`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('code points just outside the table are rejected', () => {
|
||||
for (const codePoint of [0x33ff, 0x4dc0, 0xa000, 0x1f000, 0x3347a]) {
|
||||
assert.equal(
|
||||
isHanCodePoint(codePoint),
|
||||
false,
|
||||
`expected U+${codePoint.toString(16)} not to be Han`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('the regexp class body matches the same code points as the predicate', () => {
|
||||
const classRegExp = new RegExp(`^[${HAN_REGEXP_CLASS_BODY}]$`, 'u');
|
||||
|
||||
for (const codePoint of [0x3400, 0x4e00, 0x9fff, 0xf900, 0x20000, 0x323b0, 0x33479]) {
|
||||
assert.match(String.fromCodePoint(codePoint), classRegExp);
|
||||
}
|
||||
for (const codePoint of [0x3040, 0x30ff, 0x33fa, 0x3347a]) {
|
||||
assert.doesNotMatch(String.fromCodePoint(codePoint), classRegExp);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
// Single source of truth for "this code point is a Han character", shared by
|
||||
// the main-process character dictionary and the in-page Yomitan scan runtime.
|
||||
// The two used to carry separate range lists, and they drifted: a name written
|
||||
// with a supplementary-plane kanji could enter the generated dictionary while
|
||||
// the scanner's greedy name pre-pass refused to probe the position.
|
||||
//
|
||||
// Ranges rather than \p{Script=Han}: the scan walk tests one code point per
|
||||
// character of every subtitle line, where an integer compare beats building a
|
||||
// string for a regex, and the script is injected as text into a page where a
|
||||
// shared helper cannot be imported.
|
||||
export const HAN_CODE_POINT_RANGES: ReadonlyArray<readonly [number, number]> = [
|
||||
[0x3400, 0x4dbf], // Extension A
|
||||
[0x4e00, 0x9fff], // CJK Unified Ideographs
|
||||
[0xf900, 0xfaff], // Compatibility Ideographs
|
||||
[0x20000, 0x2a6df], // Extension B
|
||||
[0x2a700, 0x2ebef], // Extensions C-F
|
||||
[0x2ebf0, 0x2ee5f], // Extension I
|
||||
[0x2f800, 0x2fa1f], // Compatibility Ideographs Supplement
|
||||
[0x30000, 0x3134f], // Extension G
|
||||
[0x31350, 0x323af], // Extension H
|
||||
[0x323b0, 0x33479], // Extension J (Unicode 17)
|
||||
];
|
||||
|
||||
export function isHanCodePoint(codePoint: number): boolean {
|
||||
return HAN_CODE_POINT_RANGES.some(([start, end]) => codePoint >= start && codePoint <= end);
|
||||
}
|
||||
|
||||
/** The same ranges as a regular expression character class body (needs the `u` flag). */
|
||||
export const HAN_REGEXP_CLASS_BODY = HAN_CODE_POINT_RANGES.map(
|
||||
([start, end]) => `\\u{${start.toString(16)}}-\\u{${end.toString(16)}}`,
|
||||
).join('');
|
||||
@@ -0,0 +1,203 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
|
||||
import { parseChangelog, resolveChangelogGroupKey } from './changelog-parse';
|
||||
|
||||
const SAMPLE = `# Changelog
|
||||
|
||||
## v0.19.2 (2026-08-04)
|
||||
|
||||
### Changed
|
||||
- Subsync: picks both tracks now.
|
||||
|
||||
### Fixed
|
||||
- Overlay: shows the plain line immediately.
|
||||
|
||||
<details>
|
||||
<summary>Internal changes</summary>
|
||||
|
||||
### Internal
|
||||
- Patched \`undici\`.
|
||||
|
||||
</details>
|
||||
|
||||
## v0.19.1 (2026-08-01)
|
||||
|
||||
### Added
|
||||
- **Word Card Type:**
|
||||
- Adds a setting.
|
||||
- Flags clear each other.
|
||||
|
||||
## v0.18.0 (2026-07-01)
|
||||
|
||||
### Fixed
|
||||
- Something older.
|
||||
`;
|
||||
|
||||
test('changelog parser reads versions, dates, and sections in file order', () => {
|
||||
const entries = parseChangelog(SAMPLE);
|
||||
|
||||
assert.deepEqual(
|
||||
entries.map((entry) => `${entry.version}@${entry.date}`),
|
||||
['0.19.2@2026-08-04', '0.19.1@2026-08-01', '0.18.0@2026-07-01'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
entries[0]?.sections.map((section) => section.heading),
|
||||
['Changed', 'Fixed', 'Internal'],
|
||||
);
|
||||
assert.deepEqual(entries[0]?.sections[1]?.items, [
|
||||
{ text: 'Overlay: shows the plain line immediately.', children: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
test('changelog parser flags sections inside the details block as internal', () => {
|
||||
const entries = parseChangelog(SAMPLE);
|
||||
const sections = entries[0]?.sections ?? [];
|
||||
|
||||
assert.deepEqual(
|
||||
sections.map((section) => section.internal),
|
||||
[false, false, true],
|
||||
);
|
||||
assert.deepEqual(sections[2]?.items, [{ text: 'Patched `undici`.', children: [] }]);
|
||||
});
|
||||
|
||||
test('changelog parser groups entries by major.minor', () => {
|
||||
const entries = parseChangelog(SAMPLE);
|
||||
|
||||
assert.deepEqual(
|
||||
entries.map((entry) => entry.groupKey),
|
||||
['0.19', '0.19', '0.18'],
|
||||
);
|
||||
assert.equal(resolveChangelogGroupKey('1.2.3'), '1.2');
|
||||
});
|
||||
|
||||
test('changelog parser keeps bullets that precede any section heading', () => {
|
||||
const entries = parseChangelog('## v0.1.0 (2025-01-01)\n\n- Initial release.\n');
|
||||
|
||||
assert.deepEqual(entries[0]?.sections, [
|
||||
{
|
||||
heading: 'Changes',
|
||||
items: [{ text: 'Initial release.', children: [] }],
|
||||
internal: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('changelog parser drops empty sections and tolerates missing dates', () => {
|
||||
const entries = parseChangelog('## v0.2.0\n\n### Added\n\n### Fixed\n- One fix.\n');
|
||||
|
||||
assert.equal(entries[0]?.date, '');
|
||||
assert.deepEqual(
|
||||
entries[0]?.sections.map((section) => section.heading),
|
||||
['Fixed'],
|
||||
);
|
||||
});
|
||||
|
||||
test('changelog parser keeps indented sub-bullets nested under their lead bullet', () => {
|
||||
const entries = parseChangelog(SAMPLE);
|
||||
const added = entries[1]?.sections.find((section) => section.heading === 'Added');
|
||||
|
||||
assert.deepEqual(added?.items, [
|
||||
{
|
||||
text: '**Word Card Type:**',
|
||||
children: [
|
||||
{ text: 'Adds a setting.', children: [] },
|
||||
{ text: 'Flags clear each other.', children: [] },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('changelog parser nests three bullet levels and rejoins wrapped lines', () => {
|
||||
const entries = parseChangelog(
|
||||
[
|
||||
'## v0.9.0 (2025-05-05)',
|
||||
'',
|
||||
'### Added',
|
||||
'- Top level',
|
||||
' - Second level',
|
||||
' - Third level',
|
||||
' continued on the next line',
|
||||
' - Back to second level',
|
||||
'- Another top level',
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
|
||||
assert.deepEqual(entries[0]?.sections[0]?.items, [
|
||||
{
|
||||
text: 'Top level',
|
||||
children: [
|
||||
{
|
||||
text: 'Second level',
|
||||
children: [{ text: 'Third level continued on the next line', children: [] }],
|
||||
},
|
||||
{ text: 'Back to second level', children: [] },
|
||||
],
|
||||
},
|
||||
{ text: 'Another top level', children: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
test('changelog parser reads prerelease and build metadata version headings', () => {
|
||||
const entries = parseChangelog(
|
||||
[
|
||||
'## v0.16.0 (2026-06-01)',
|
||||
'',
|
||||
'### Added',
|
||||
'- New in 0.16.',
|
||||
'',
|
||||
'## v0.15.0-rc.1+build.2 (2026-05-29)',
|
||||
'',
|
||||
'### Added',
|
||||
'- Release candidate note.',
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
|
||||
// The prerelease heading has to become its own entry. Asserting the exact
|
||||
// version list is what catches the failure mode: a heading the regex misses
|
||||
// is not skipped, its notes silently fold into the release above it.
|
||||
assert.deepEqual(
|
||||
entries.map((entry) => entry.version),
|
||||
['0.16.0', '0.15.0-rc.1+build.2'],
|
||||
);
|
||||
assert.equal(entries[1]?.date, '2026-05-29');
|
||||
assert.equal(entries[1]?.groupKey, '0.15');
|
||||
assert.equal(entries[0]?.sections.length, 1);
|
||||
// The prerelease body has to land on its own entry, not fold into 0.16.0.
|
||||
assert.deepEqual(entries[1]?.sections, [
|
||||
{
|
||||
heading: 'Added',
|
||||
items: [{ text: 'Release candidate note.', children: [] }],
|
||||
internal: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('changelog parser handles the repo CHANGELOG.md', () => {
|
||||
const markdown = fs.readFileSync(path.join(process.cwd(), 'CHANGELOG.md'), 'utf8');
|
||||
const entries = parseChangelog(markdown);
|
||||
|
||||
assert.ok(entries.length > 3);
|
||||
for (const entry of entries) {
|
||||
assert.match(entry.version, /^\d+\.\d+\.\d+/);
|
||||
assert.ok(entry.sections.length > 0, `expected sections for v${entry.version}`);
|
||||
for (const section of entry.sections) {
|
||||
for (const item of section.items) {
|
||||
assert.ok(item.text.length > 0, `empty bullet in v${entry.version}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Older entries group notes under a bold lead bullet; nesting must survive.
|
||||
const breaking = entries
|
||||
.find((entry) => entry.version === '0.15.0')
|
||||
?.sections.find((section) => section.heading === 'Breaking Changes');
|
||||
assert.deepEqual(
|
||||
breaking?.items.map((item) => `${item.text}:${item.children.length}`),
|
||||
['**Subsync:**:2', '**N+1 Highlighting:**:2'],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import type { ChangelogEntry, ChangelogItem, ChangelogSection } from '../../types/changelog';
|
||||
|
||||
// Prerelease and build metadata are matched separately: a single `[-+]`-led
|
||||
// group cannot span `-rc.1+build.2`, and an unmatched heading silently folds
|
||||
// that release's notes into the previous entry.
|
||||
const VERSION_HEADING =
|
||||
/^##\s+v(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)\s*(?:\(([^)]*)\))?\s*$/;
|
||||
const SECTION_HEADING = /^###\s+(.+?)\s*$/;
|
||||
const BULLET = /^(\s*)[-*]\s+(.*)$/;
|
||||
|
||||
/**
|
||||
* Entries are grouped by `major.minor` so the whole current minor line renders
|
||||
* expanded, matching how docs-site/changelog.md splits current vs previous.
|
||||
*/
|
||||
export function resolveChangelogGroupKey(version: string): string {
|
||||
const match = version.match(/^(\d+)\.(\d+)/);
|
||||
if (!match) return version;
|
||||
return `${match[1]}.${match[2]}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the repo CHANGELOG.md into version entries. Bullets keep their inline
|
||||
* markdown and their nesting: older entries group related notes under a bold
|
||||
* lead bullet with indented children, and flattening them loses that structure.
|
||||
*/
|
||||
export function parseChangelog(markdown: string): ChangelogEntry[] {
|
||||
const entries: ChangelogEntry[] = [];
|
||||
let entry: ChangelogEntry | null = null;
|
||||
let section: ChangelogSection | null = null;
|
||||
let internal = false;
|
||||
// Open bullets from outermost to innermost, used to place the next bullet.
|
||||
let openItems: Array<{ indent: number; item: ChangelogItem }> = [];
|
||||
|
||||
function startSection(heading: string): void {
|
||||
section = { heading, items: [], internal };
|
||||
openItems = [];
|
||||
entry?.sections.push(section);
|
||||
}
|
||||
|
||||
function addBullet(indent: number, text: string): void {
|
||||
if (!section) {
|
||||
// Bullets before any "###" heading (older entries) land in a generic group.
|
||||
startSection('Changes');
|
||||
}
|
||||
const item: ChangelogItem = { text, children: [] };
|
||||
|
||||
while (openItems.length > 0 && (openItems[openItems.length - 1]?.indent ?? 0) >= indent) {
|
||||
openItems.pop();
|
||||
}
|
||||
const parent = openItems[openItems.length - 1];
|
||||
if (parent) {
|
||||
parent.item.children.push(item);
|
||||
} else {
|
||||
section?.items.push(item);
|
||||
}
|
||||
openItems.push({ indent, item });
|
||||
}
|
||||
|
||||
function appendContinuation(text: string): void {
|
||||
const current = openItems[openItems.length - 1];
|
||||
if (!current) return;
|
||||
current.item.text = `${current.item.text} ${text}`;
|
||||
}
|
||||
|
||||
for (const rawLine of markdown.split(/\r?\n/)) {
|
||||
const line = rawLine.trimEnd();
|
||||
const trimmed = line.trim();
|
||||
|
||||
const versionMatch = trimmed.match(VERSION_HEADING);
|
||||
if (versionMatch) {
|
||||
const version = versionMatch[1] ?? '';
|
||||
entry = {
|
||||
version,
|
||||
date: versionMatch[2]?.trim() ?? '',
|
||||
groupKey: resolveChangelogGroupKey(version),
|
||||
sections: [],
|
||||
};
|
||||
entries.push(entry);
|
||||
section = null;
|
||||
internal = false;
|
||||
openItems = [];
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!entry) continue;
|
||||
|
||||
if (trimmed.startsWith('<details')) {
|
||||
internal = true;
|
||||
section = null;
|
||||
openItems = [];
|
||||
continue;
|
||||
}
|
||||
if (trimmed.startsWith('</details')) {
|
||||
internal = false;
|
||||
section = null;
|
||||
openItems = [];
|
||||
continue;
|
||||
}
|
||||
if (trimmed.startsWith('<summary')) continue;
|
||||
|
||||
const sectionMatch = trimmed.match(SECTION_HEADING);
|
||||
if (sectionMatch) {
|
||||
startSection(sectionMatch[1] ?? '');
|
||||
continue;
|
||||
}
|
||||
|
||||
const bulletMatch = line.match(BULLET);
|
||||
if (bulletMatch) {
|
||||
addBullet((bulletMatch[1] ?? '').length, bulletMatch[2] ?? '');
|
||||
continue;
|
||||
}
|
||||
|
||||
// An indented non-bullet line continues the bullet above it, including
|
||||
// across a blank line: that is CommonMark's continuation paragraph, and
|
||||
// dropping the open bullets here would silently discard the text.
|
||||
if (!trimmed) {
|
||||
continue;
|
||||
}
|
||||
if (/^\s/.test(line)) {
|
||||
appendContinuation(trimmed);
|
||||
}
|
||||
}
|
||||
|
||||
return entries.map((item) => ({
|
||||
...item,
|
||||
sections: item.sections.filter((entrySection) => entrySection.items.length > 0),
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Loose semver ordering shared by the updater and the changelog UI.
|
||||
* Returns >0 when `a` is newer, <0 when older, 0 when equal.
|
||||
*/
|
||||
export function compareSemverLike(a: string, b: string): number {
|
||||
const parse = (
|
||||
value: string,
|
||||
): {
|
||||
core: number[];
|
||||
prerelease: Array<number | string>;
|
||||
} => {
|
||||
// Build metadata ("+build.2") is not part of precedence per semver, and
|
||||
// leaving it attached makes it leak into the prerelease comparison.
|
||||
const normalized = value.replace(/^v/i, '').split('+', 1)[0] ?? '';
|
||||
const [coreText = '', ...prereleaseParts] = normalized.split('-');
|
||||
const core = coreText
|
||||
.split('.')
|
||||
.slice(0, 3)
|
||||
.map((part) => Number.parseInt(part, 10) || 0);
|
||||
while (core.length < 3) core.push(0);
|
||||
const prereleaseText = prereleaseParts.join('-');
|
||||
return {
|
||||
core,
|
||||
prerelease: prereleaseText
|
||||
? prereleaseText.split('.').map((part) => {
|
||||
const numeric = Number.parseInt(part, 10);
|
||||
return /^\d+$/.test(part) ? numeric : part;
|
||||
})
|
||||
: [],
|
||||
};
|
||||
};
|
||||
const left = parse(a);
|
||||
const right = parse(b);
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
const diff = (left.core[i] ?? 0) - (right.core[i] ?? 0);
|
||||
if (diff !== 0) return diff;
|
||||
}
|
||||
|
||||
if (left.prerelease.length === 0 && right.prerelease.length === 0) return 0;
|
||||
if (left.prerelease.length === 0) return 1;
|
||||
if (right.prerelease.length === 0) return -1;
|
||||
|
||||
const length = Math.max(left.prerelease.length, right.prerelease.length);
|
||||
for (let i = 0; i < length; i += 1) {
|
||||
const leftPart = left.prerelease[i];
|
||||
const rightPart = right.prerelease[i];
|
||||
if (leftPart === undefined && rightPart === undefined) return 0;
|
||||
if (leftPart === undefined) return -1;
|
||||
if (rightPart === undefined) return 1;
|
||||
if (leftPart === rightPart) continue;
|
||||
if (typeof leftPart === 'number' && typeof rightPart === 'number') {
|
||||
return leftPart - rightPart;
|
||||
}
|
||||
if (typeof leftPart === 'number') return -1;
|
||||
if (typeof rightPart === 'number') return 1;
|
||||
return leftPart > rightPart ? 1 : -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
+99
-13
@@ -295,6 +295,7 @@ import {
|
||||
importYomitanDictionaryFromZip,
|
||||
initializeOverlayAnkiIntegration as initializeOverlayAnkiIntegrationCore,
|
||||
initializeOverlayRuntime as initializeOverlayRuntimeCore,
|
||||
isSubtitleAnnotationUpgrade,
|
||||
isOverlayWindowContentReady,
|
||||
jellyfinTicksToSecondsRuntime,
|
||||
listJellyfinItemsRuntime,
|
||||
@@ -469,6 +470,8 @@ import { openJimakuModal as openJimakuModalRuntime } from './main/runtime/jimaku
|
||||
import { openTsukihimeModal as openTsukihimeModalRuntime } from './main/runtime/tsukihime-open';
|
||||
import { openSubsyncManualModal as openSubsyncManualModalRuntime } from './main/runtime/subsync-open';
|
||||
import { openSessionHelpModal as openSessionHelpModalRuntime } from './main/runtime/session-help-open';
|
||||
import { openChangelogModal as openChangelogModalRuntime } from './main/runtime/changelog-open';
|
||||
import { createChangelogRuntime } from './main/runtime/changelog/changelog-runtime';
|
||||
import { openCharacterDictionaryManagerModal as openCharacterDictionaryManagerModalRuntime } from './main/runtime/character-dictionary-open';
|
||||
import { openControllerSelectModal as openControllerSelectModalRuntime } from './main/runtime/controller-select-open';
|
||||
import { openControllerDebugModal as openControllerDebugModalRuntime } from './main/runtime/controller-debug-open';
|
||||
@@ -494,6 +497,7 @@ import { createOverlayVisibilityRuntimeService } from './main/overlay-visibility
|
||||
import { createDiscordPresenceRuntime } from './main/runtime/discord-presence-runtime';
|
||||
import { createCharacterDictionaryRuntimeService } from './main/character-dictionary-runtime';
|
||||
import { createCharacterDictionaryImageLookup } from './main/character-dictionary-runtime/image-lookup';
|
||||
import { createCharacterNameCandidateLookup } from './main/character-dictionary-runtime/name-candidates';
|
||||
import {
|
||||
createCharacterDictionaryAutoSyncRuntimeService,
|
||||
getCharacterDictionaryManagerSnapshot,
|
||||
@@ -513,6 +517,7 @@ import { createStartupOsdSequencer } from './main/runtime/startup-osd-sequencer'
|
||||
import {
|
||||
INSTALL_UPDATE_ACTION_ID,
|
||||
UPDATE_AVAILABLE_NOTIFICATION_ID,
|
||||
VIEW_CHANGELOG_ACTION_ID,
|
||||
} from './main/runtime/update/update-notifications';
|
||||
import { createOverlayNotificationsRuntime } from './main/runtime/overlay-notifications-runtime';
|
||||
import {
|
||||
@@ -1827,8 +1832,10 @@ function withCurrentSubtitleTiming(payload: SubtitleData): SubtitleData {
|
||||
endTime: appState.mpvClient?.currentSubEnd ?? null,
|
||||
};
|
||||
}
|
||||
function emitSubtitlePayload(payload: SubtitleData): void {
|
||||
function emitSubtitlePayload(payload: SubtitleData, options?: { resumePrefetch?: boolean }): void {
|
||||
const timedPayload = withCurrentSubtitleTiming(payload);
|
||||
const currentSubtitleData = appState.currentSubtitleData;
|
||||
const isAnnotationUpgrade = isSubtitleAnnotationUpgrade(currentSubtitleData, timedPayload);
|
||||
const frequencyDictionary = configService.getConfig().subtitleStyle.frequencyDictionary;
|
||||
const frequencyOptions = {
|
||||
enabled: frequencyDictionary.enabled,
|
||||
@@ -1837,10 +1844,18 @@ function emitSubtitlePayload(payload: SubtitleData): void {
|
||||
};
|
||||
appState.currentSubtitleData = timedPayload;
|
||||
overlayManager.broadcastToOverlayWindows('subtitle:set', timedPayload);
|
||||
subtitleWsService.broadcast(timedPayload, frequencyOptions);
|
||||
if (!isAnnotationUpgrade) {
|
||||
subtitleWsService.broadcast(timedPayload, frequencyOptions);
|
||||
}
|
||||
annotationSubtitleWsService.broadcast(timedPayload, frequencyOptions);
|
||||
autoplayReadyGate.maybeSignalPluginAutoplayReady(timedPayload, { forceWhilePaused: true });
|
||||
subtitlePrefetchService?.resume();
|
||||
// resumePrefetch: false marks an emit that is not the end of the work for
|
||||
// this line; prefetch stays paused until the subtitle processing controller
|
||||
// settles so it does not compete with the on-screen line for the single
|
||||
// Yomitan parser window.
|
||||
if (options?.resumePrefetch !== false) {
|
||||
subtitlePrefetchService?.resume();
|
||||
}
|
||||
}
|
||||
function getCurrentAutoplaySubtitlePayload(): SubtitleData | null {
|
||||
const payload = appState.currentSubtitleData;
|
||||
@@ -1896,7 +1911,17 @@ const buildSubtitleProcessingControllerMainDepsHandler =
|
||||
createBuildSubtitleProcessingControllerMainDepsHandler({
|
||||
tokenizeSubtitle: async (text: string) =>
|
||||
tokenizeSubtitleDeferred ? await tokenizeSubtitleDeferred(text) : { text, tokens: null },
|
||||
emitSubtitle: (payload) => emitSubtitlePayload(payload),
|
||||
// Controller emits never release the prefetch pause: the first emit for an
|
||||
// uncached line is the provisional plain payload, sent before tokenization
|
||||
// starts, so resuming on it would put prefetch back in contention with the
|
||||
// on-screen line for the single parser window.
|
||||
emitSubtitle: (payload) => emitSubtitlePayload(payload, { resumePrefetch: false }),
|
||||
// The pause is released once the controller has no work left, which covers
|
||||
// the runs that end without an emit (suppressed duplicate, failed
|
||||
// tokenization) as well as the ones that deliver a payload.
|
||||
onProcessingSettled: () => {
|
||||
subtitlePrefetchService?.resume();
|
||||
},
|
||||
logDebug: (message) => {
|
||||
logger.debug(`[subtitle-processing] ${message}`);
|
||||
},
|
||||
@@ -1933,7 +1958,7 @@ const autoplaySubtitlePrimingRuntime = createAutoplaySubtitlePrimingRuntime({
|
||||
appState.activeParsedSubtitleMediaPath = mediaPath;
|
||||
},
|
||||
subtitleProcessingController,
|
||||
emitSubtitlePayload: (payload) => emitSubtitlePayload(payload),
|
||||
emitSubtitlePayload: (payload, options) => emitSubtitlePayload(payload, options),
|
||||
getSubtitlePrefetchService: () => subtitlePrefetchService,
|
||||
getLastObservedTimePos: () => lastObservedTimePos,
|
||||
getVisibleOverlayVisible: () => overlayManager.getVisibleOverlayVisible(),
|
||||
@@ -1967,7 +1992,6 @@ const subtitlePrefetchInitController = createSubtitlePrefetchInitController({
|
||||
subtitleProcessingController.preCacheTokenization(text, data);
|
||||
},
|
||||
hasCachedTokenization: (text) => subtitleProcessingController.hasCachedSubtitle(text),
|
||||
isCacheFull: () => subtitleProcessingController.isCacheFull(),
|
||||
logInfo: (message) => logger.info(message),
|
||||
logWarn: (message) => logger.warn(message),
|
||||
onParsedSubtitleCuesChanged: (cues, sourceKey) => {
|
||||
@@ -1994,15 +2018,22 @@ const resolveActiveSubtitleSidebarSourceHandler = createResolveActiveSubtitleSid
|
||||
getFfmpegPath: () => configService.getConfig().subsync.ffmpeg_path.trim() || 'ffmpeg',
|
||||
extractInternalSubtitleTrack: (ffmpegPath, videoPath, track) =>
|
||||
extractInternalSubtitleTrackToTempFile(ffmpegPath, videoPath, track),
|
||||
logDebug: (message) => logger.debug(message),
|
||||
});
|
||||
|
||||
const refreshSubtitlePrefetchFromActiveTrackHandler =
|
||||
createRefreshSubtitlePrefetchFromActiveTrackHandler({
|
||||
getMpvClient: () => appState.mpvClient,
|
||||
getLastObservedTimePos: () => lastObservedTimePos,
|
||||
shouldKeepExistingCuesOnMissingSource: (videoPath) => isYoutubeMediaPath(videoPath),
|
||||
// Remote media has no extractable on-disk track to fall back to, so a transient
|
||||
// resolve miss (sid briefly 'no', a cycle onto an embedded stream track) would
|
||||
// otherwise drop a working cue list for the rest of the episode.
|
||||
shouldKeepExistingCuesOnMissingSource: (videoPath) =>
|
||||
isYoutubeMediaPath(videoPath) || isRemoteMediaPath(videoPath),
|
||||
subtitlePrefetchInitController,
|
||||
resolveActiveSubtitleSidebarSource: (input) => resolveActiveSubtitleSidebarSourceHandler(input),
|
||||
logDebug: (message) => logger.debug(message),
|
||||
logWarn: (message) => logger.warn(message),
|
||||
});
|
||||
|
||||
const subtitlePrefetchRuntime = {
|
||||
@@ -2563,6 +2594,10 @@ const characterDictionaryAutoSyncRuntime = createCharacterDictionaryAutoSyncRunt
|
||||
},
|
||||
{
|
||||
hasParserWindow: () => Boolean(appState.yomitanParserWindow),
|
||||
invalidateCharacterDictionaryLookups: () => {
|
||||
characterDictionaryImageLookup.invalidate();
|
||||
characterNameCandidateLookup.invalidate();
|
||||
},
|
||||
clearParserCaches: () => {
|
||||
if (appState.yomitanParserWindow) {
|
||||
clearYomitanParserCachesForWindow(appState.yomitanParserWindow);
|
||||
@@ -2588,6 +2623,13 @@ const characterDictionaryImageLookup = createCharacterDictionaryImageLookup({
|
||||
getCurrentMediaId: () => characterDictionaryAutoSyncRuntime.getCurrentMediaId(),
|
||||
});
|
||||
|
||||
// Lets the Yomitan scan runtime skip name lookups at positions where no
|
||||
// character name can start; absent candidates just mean the exhaustive scan.
|
||||
const characterNameCandidateLookup = createCharacterNameCandidateLookup({
|
||||
userDataPath: USER_DATA_PATH,
|
||||
getCurrentMediaId: () => characterDictionaryAutoSyncRuntime.getCurrentMediaId(),
|
||||
});
|
||||
|
||||
const overlayVisibilityRuntime = createOverlayVisibilityRuntimeService(
|
||||
createBuildOverlayVisibilityRuntimeMainDepsHandler({
|
||||
getMainWindow: () => overlayManager.getMainWindow(),
|
||||
@@ -2859,6 +2901,14 @@ function openSessionHelpOverlay(): void {
|
||||
);
|
||||
}
|
||||
|
||||
function openChangelogOverlay(): void {
|
||||
openOverlayHostedModalWithOsd(
|
||||
openChangelogModalRuntime,
|
||||
'Changelog overlay unavailable.',
|
||||
'Failed to open changelog overlay.',
|
||||
);
|
||||
}
|
||||
|
||||
function openCharacterDictionaryManagerOverlay(): void {
|
||||
openCharacterDictionaryManagerWithConfigGate({
|
||||
isCharacterDictionaryEnabled: () => configService.getConfig().subtitleStyle.nameMatchEnabled,
|
||||
@@ -3037,6 +3087,8 @@ const {
|
||||
streamIndex,
|
||||
delaySeconds,
|
||||
}),
|
||||
initSubtitlePrefetch: (sourcePath) =>
|
||||
subtitlePrefetchRuntime.refreshSubtitleSidebarFromSource(sourcePath),
|
||||
logDebug: (message, error) => {
|
||||
logger.debug(message, error);
|
||||
},
|
||||
@@ -3327,6 +3379,12 @@ const animeBrowserRuntime = createAnimeBrowserRuntime({
|
||||
window.webContents.send(IPC_CHANNELS.event.animeBrowserSearchUpdate, update);
|
||||
}
|
||||
},
|
||||
onQueueState: (state) => {
|
||||
const window = appState.animeBrowserWindow;
|
||||
if (window && !window.isDestroyed()) {
|
||||
window.webContents.send(IPC_CHANNELS.event.animeBrowserQueueState, state);
|
||||
}
|
||||
},
|
||||
log: (message) => logger.info(message),
|
||||
});
|
||||
|
||||
@@ -4132,7 +4190,10 @@ const refreshCurrentSubtitleAfterKnownWordUpdate = (): void => {
|
||||
}
|
||||
subtitleProcessingController.invalidateTokenizationCache();
|
||||
subtitlePrefetchService?.onSeek(lastObservedTimePos);
|
||||
subtitleProcessingController.refreshCurrentSubtitle(appState.currentSubText);
|
||||
if (!subtitleProcessingController.refreshCurrentSubtitle(appState.currentSubText)) {
|
||||
// Idle controller: no settle is coming to release the pause above.
|
||||
subtitlePrefetchService?.resume();
|
||||
}
|
||||
};
|
||||
let hasAttemptedImmersionTrackerStartup = false;
|
||||
const ensureImmersionTrackerStarted = (): void => {
|
||||
@@ -4533,13 +4594,20 @@ const {
|
||||
emitSubtitlePayload(payload);
|
||||
},
|
||||
onSubtitleChange: (text) => {
|
||||
// Pause only; restarting the prefetch run here would discard in-flight
|
||||
// tokenization work on every line. Real seeks restart via onTimePosUpdate.
|
||||
subtitlePrefetchService?.pause();
|
||||
subtitlePrefetchService?.onSeek(lastObservedTimePos);
|
||||
subtitleProcessingController.onSubtitleChange(text);
|
||||
if (!subtitleProcessingController.onSubtitleChange(text)) {
|
||||
// Repeat of the current text: the controller is idle, so no settle is
|
||||
// coming to release the pause. Resume now instead of idling prefetch
|
||||
// for the rest of the cue.
|
||||
subtitlePrefetchService?.resume();
|
||||
}
|
||||
},
|
||||
refreshDiscordPresence: () => {
|
||||
discordPresenceRuntime.publishDiscordPresence();
|
||||
},
|
||||
logSubtitleProcessingDebug: (message: string) => logger.debug(message),
|
||||
ensureImmersionTrackerInitialized: () => {
|
||||
ensureImmersionTrackerStarted();
|
||||
},
|
||||
@@ -4778,6 +4846,7 @@ const {
|
||||
getCharacterNameImage: (term) => characterDictionaryImageLookup.get(term),
|
||||
getCurrentCharacterDictionaryMediaId: () =>
|
||||
characterDictionaryAutoSyncRuntime.getCurrentMediaId(),
|
||||
getCharacterNameCandidates: () => characterNameCandidateLookup.get(),
|
||||
getFrequencyDictionaryEnabled: () =>
|
||||
getRuntimeBooleanOption(
|
||||
'subtitle.annotation.frequency',
|
||||
@@ -5255,6 +5324,18 @@ flushPendingMpvLogWrites = () => {
|
||||
void flushMpvLog();
|
||||
};
|
||||
|
||||
const { getChangelogSnapshot } = createChangelogRuntime({
|
||||
getInstalledVersion: () => app.getVersion(),
|
||||
getUpdateChannel: () => configService.getConfig().updates.channel,
|
||||
resourcesPath: process.resourcesPath,
|
||||
appPath: app.getAppPath(),
|
||||
dirname: __dirname,
|
||||
joinPath: (...parts) => path.join(...parts),
|
||||
fileExists: (candidate) => fs.existsSync(candidate),
|
||||
readFile: (candidate) => fs.readFileSync(candidate, 'utf8'),
|
||||
logWarn: (message) => logger.warn(message),
|
||||
});
|
||||
|
||||
const { getUpdateService } = createUpdateServiceRuntime({
|
||||
userDataPath: USER_DATA_PATH,
|
||||
getUpdatesConfig: () => configService.getConfig().updates,
|
||||
@@ -5623,6 +5704,12 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
|
||||
logger.warn('Failed to install update from overlay notification action:', error);
|
||||
});
|
||||
}
|
||||
if (
|
||||
notificationId === UPDATE_AVAILABLE_NOTIFICATION_ID &&
|
||||
actionId === VIEW_CHANGELOG_ACTION_ID
|
||||
) {
|
||||
openChangelogOverlay();
|
||||
}
|
||||
if (actionId === OPEN_ANKI_CARD_ACTION_ID && noteId !== undefined) {
|
||||
void openAnkiCardFromNotification(noteId).catch((error) => {
|
||||
logger.warn('Failed to open Anki card from overlay notification action:', error);
|
||||
@@ -5832,7 +5919,6 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
|
||||
if (result.ok && result.rebuildRequired) {
|
||||
try {
|
||||
await characterDictionaryAutoSyncRuntime.runSyncNow();
|
||||
characterDictionaryImageLookup.invalidate();
|
||||
} catch (error) {
|
||||
logger.warn('Failed to rebuild character dictionary after manager override:', error);
|
||||
}
|
||||
@@ -5863,7 +5949,6 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
|
||||
if (result.ok && result.rebuildRequired) {
|
||||
try {
|
||||
await characterDictionaryAutoSyncRuntime.runSyncNow();
|
||||
characterDictionaryImageLookup.invalidate();
|
||||
} catch (error) {
|
||||
logger.warn('Failed to rebuild character dictionary after manager removal:', error);
|
||||
}
|
||||
@@ -5880,7 +5965,6 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
|
||||
if (result.ok && result.rebuildRequired) {
|
||||
try {
|
||||
await characterDictionaryAutoSyncRuntime.runSyncNow();
|
||||
characterDictionaryImageLookup.invalidate();
|
||||
} catch (error) {
|
||||
logger.warn('Failed to rebuild character dictionary after manager reorder:', error);
|
||||
}
|
||||
@@ -5888,6 +5972,7 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
|
||||
return result;
|
||||
},
|
||||
appendClipboardVideoToQueue: () => appendClipboardVideoToQueueHandler(),
|
||||
getChangelogSnapshot: (options) => getChangelogSnapshot(options),
|
||||
...playlistBrowserMainDeps,
|
||||
getImmersionTracker: () => appState.immersionTracker,
|
||||
},
|
||||
@@ -6284,6 +6369,7 @@ const { ensureTray: ensureTrayHandler, destroyTray: destroyTrayHandler } =
|
||||
initializeOverlayRuntime: () => initializeOverlayRuntime(),
|
||||
isOverlayRuntimeInitialized: () => appState.overlayRuntimeInitialized,
|
||||
openSessionHelpModal: () => openSessionHelpOverlay(),
|
||||
openChangelogModal: () => openChangelogOverlay(),
|
||||
openTexthookerInBrowser: () =>
|
||||
handleCliCommand(parseArgs(['--texthooker', '--open-browser'])),
|
||||
showTexthookerPage: () => shouldShowTexthookerTrayEntry(configService.getConfig()),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
export const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
|
||||
export const ANILIST_REQUEST_DELAY_MS = 2000;
|
||||
export const CHARACTER_IMAGE_DOWNLOAD_DELAY_MS = 250;
|
||||
export const CHARACTER_DICTIONARY_FORMAT_VERSION = 19;
|
||||
export const CHARACTER_DICTIONARY_FORMAT_VERSION = 20;
|
||||
export const CHARACTER_DICTIONARY_MERGED_TITLE = 'SubMiner Character Dictionary';
|
||||
|
||||
export const HONORIFIC_SUFFIXES = [
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import test from 'node:test';
|
||||
import { CHARACTER_DICTIONARY_FORMAT_VERSION } from './constants';
|
||||
import { createCharacterNameCandidateLookup } from './name-candidates';
|
||||
|
||||
function writeSnapshot(outputDir: string, mediaId: number, entries: Array<[string, string]>): void {
|
||||
const snapshotsDir = path.join(outputDir, 'snapshots');
|
||||
fs.mkdirSync(snapshotsDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(snapshotsDir, `anilist-${mediaId}.json`),
|
||||
JSON.stringify({
|
||||
formatVersion: CHARACTER_DICTIONARY_FORMAT_VERSION,
|
||||
mediaId,
|
||||
mediaTitle: `title-${mediaId}`,
|
||||
entryCount: entries.length,
|
||||
updatedAt: 1,
|
||||
termEntries: entries.map(([term, reading]) => [
|
||||
term,
|
||||
reading,
|
||||
'name main',
|
||||
'',
|
||||
100,
|
||||
[],
|
||||
0,
|
||||
'',
|
||||
]),
|
||||
images: [],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function withTempDir<T>(run: (dir: string) => T): T {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-name-candidates-'));
|
||||
try {
|
||||
return run(dir);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
test('collects terms and readings for the current media', () => {
|
||||
withTempDir((dir) => {
|
||||
writeSnapshot(dir, 1, [
|
||||
['ミナト', 'みなと'],
|
||||
['湊', 'みなと'],
|
||||
]);
|
||||
writeSnapshot(dir, 2, [['カズマ', 'かずま']]);
|
||||
|
||||
const lookup = createCharacterNameCandidateLookup({
|
||||
outputDir: dir,
|
||||
getCurrentMediaId: () => 1,
|
||||
});
|
||||
const candidates = lookup.get();
|
||||
|
||||
assert.ok(candidates);
|
||||
assert.deepEqual([...candidates.forms].sort(), ['みなと', 'ミナト', '湊'].sort());
|
||||
// Deduplicated: both entries share the みなと reading.
|
||||
assert.equal(candidates.forms.length, 3);
|
||||
});
|
||||
});
|
||||
|
||||
test('returns null without a media scope so the scanner stays exhaustive', () => {
|
||||
withTempDir((dir) => {
|
||||
writeSnapshot(dir, 1, [['ミナト', 'みなと']]);
|
||||
|
||||
const lookup = createCharacterNameCandidateLookup({
|
||||
outputDir: dir,
|
||||
getCurrentMediaId: () => null,
|
||||
});
|
||||
|
||||
assert.equal(lookup.get(), null);
|
||||
});
|
||||
});
|
||||
|
||||
test('returns null for a media with no cached snapshot', () => {
|
||||
withTempDir((dir) => {
|
||||
writeSnapshot(dir, 1, [['ミナト', 'みなと']]);
|
||||
|
||||
const lookup = createCharacterNameCandidateLookup({
|
||||
outputDir: dir,
|
||||
getCurrentMediaId: () => 999,
|
||||
});
|
||||
|
||||
assert.equal(lookup.get(), null);
|
||||
});
|
||||
});
|
||||
|
||||
test('key changes when the snapshot content changes', () => {
|
||||
withTempDir((dir) => {
|
||||
writeSnapshot(dir, 1, [['ミナト', 'みなと']]);
|
||||
const lookup = createCharacterNameCandidateLookup({
|
||||
outputDir: dir,
|
||||
getCurrentMediaId: () => 1,
|
||||
});
|
||||
const first = lookup.get();
|
||||
|
||||
writeSnapshot(dir, 1, [
|
||||
['ミナト', 'みなと'],
|
||||
['アクア', 'あくあ'],
|
||||
]);
|
||||
lookup.invalidate();
|
||||
const second = lookup.get();
|
||||
|
||||
assert.ok(first && second);
|
||||
assert.notEqual(first.key, second.key);
|
||||
assert.equal(second.forms.length, 4);
|
||||
});
|
||||
});
|
||||
|
||||
// The lookup runs once per subtitle line, so it must not stat the snapshot
|
||||
// directory every call. Asserted behaviorally: an unannounced on-disk change is
|
||||
// invisible until the recheck interval elapses, which can only be true if the
|
||||
// filesystem is not consulted per lookup.
|
||||
test('does not re-read the snapshot directory on every lookup', () => {
|
||||
withTempDir((dir) => {
|
||||
writeSnapshot(dir, 1, [['ミナト', 'みなと']]);
|
||||
let nowMs = 1_000_000;
|
||||
const lookup = createCharacterNameCandidateLookup({
|
||||
outputDir: dir,
|
||||
getCurrentMediaId: () => 1,
|
||||
now: () => nowMs,
|
||||
});
|
||||
|
||||
assert.equal(lookup.get()?.forms.length, 2);
|
||||
|
||||
writeSnapshot(dir, 1, [
|
||||
['ミナト', 'みなと'],
|
||||
['アクア', 'あくあ'],
|
||||
]);
|
||||
|
||||
nowMs += 1000;
|
||||
assert.equal(lookup.get()?.forms.length, 2, 'expected the cached list within the interval');
|
||||
|
||||
nowMs += 10_000;
|
||||
assert.equal(lookup.get()?.forms.length, 4, 'expected a refresh past the interval');
|
||||
});
|
||||
});
|
||||
|
||||
test('invalidate picks up a snapshot change immediately', () => {
|
||||
withTempDir((dir) => {
|
||||
writeSnapshot(dir, 1, [['ミナト', 'みなと']]);
|
||||
let nowMs = 1_000_000;
|
||||
const lookup = createCharacterNameCandidateLookup({
|
||||
outputDir: dir,
|
||||
getCurrentMediaId: () => 1,
|
||||
now: () => nowMs,
|
||||
});
|
||||
|
||||
assert.equal(lookup.get()?.forms.length, 2);
|
||||
|
||||
writeSnapshot(dir, 1, [
|
||||
['ミナト', 'みなと'],
|
||||
['アクア', 'あくあ'],
|
||||
]);
|
||||
nowMs += 1;
|
||||
lookup.invalidate();
|
||||
|
||||
assert.equal(lookup.get()?.forms.length, 4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { readCachedSnapshots } from './cache';
|
||||
import type { CharacterDictionarySnapshot } from './types';
|
||||
|
||||
// Candidate name forms for the greedy name pre-pass in the Yomitan scan
|
||||
// runtime. The scanner otherwise has to ask the backend at every Japanese
|
||||
// position, because a character name can start mid-token; knowing which forms
|
||||
// exist lets it look up only where a name can actually begin.
|
||||
//
|
||||
// A form is any string Yomitan could match a character entry by: the term and
|
||||
// its reading. Both come from the dictionary SubMiner generated, so the pair is
|
||||
// the complete matchable set for an entry. Callers treat a missing list as
|
||||
// "scan every position", so a stale or absent snapshot costs speed, never a
|
||||
// missed name.
|
||||
|
||||
function getSnapshotsDir(outputDir: string): string {
|
||||
return path.join(outputDir, 'snapshots');
|
||||
}
|
||||
|
||||
function collectSnapshotNameForms(snapshot: CharacterDictionarySnapshot): string[] {
|
||||
const forms = new Set<string>();
|
||||
for (const entry of snapshot.termEntries) {
|
||||
const term = typeof entry[0] === 'string' ? entry[0].trim() : '';
|
||||
if (term) {
|
||||
forms.add(term);
|
||||
}
|
||||
const reading = typeof entry[1] === 'string' ? entry[1].trim() : '';
|
||||
if (reading) {
|
||||
forms.add(reading);
|
||||
}
|
||||
}
|
||||
return [...forms];
|
||||
}
|
||||
|
||||
// The signature grows with the size of the dictionary library, and it rides
|
||||
// along in every per-line scan call, so it is folded into a fixed-width digest
|
||||
// first. Collisions only matter against the immediately previous signature (the
|
||||
// runtime compares keys for equality), and FNV-1a over the file list is far
|
||||
// beyond what that needs.
|
||||
function digestSnapshotDirectorySignature(signature: string): string {
|
||||
let hash = 0x811c9dc5;
|
||||
for (let index = 0; index < signature.length; index += 1) {
|
||||
hash ^= signature.charCodeAt(index);
|
||||
hash = Math.imul(hash, 0x01000193);
|
||||
}
|
||||
return (hash >>> 0).toString(36);
|
||||
}
|
||||
|
||||
function getSnapshotDirectorySignature(outputDir: string): string {
|
||||
let entries: fs.Dirent[] = [];
|
||||
try {
|
||||
entries = fs.readdirSync(getSnapshotsDir(outputDir), { withFileTypes: true });
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
|
||||
const parts: string[] = [];
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile() || !/^anilist-\d+\.json$/.test(entry.name)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const stat = fs.statSync(path.join(getSnapshotsDir(outputDir), entry.name));
|
||||
parts.push(`${entry.name}:${stat.mtimeMs}:${stat.size}`);
|
||||
} catch {
|
||||
// Ignore files that disappear during a refresh; the next lookup rebuilds.
|
||||
}
|
||||
}
|
||||
return parts.sort().join('|');
|
||||
}
|
||||
|
||||
export interface CharacterNameCandidateSet {
|
||||
/** Identifies this exact form list, so the scan runtime can cache it. */
|
||||
key: string;
|
||||
forms: string[];
|
||||
}
|
||||
|
||||
// This lookup is consulted once per subtitle line, so it must not stat the
|
||||
// snapshot directory every time. Dictionary writes are rare and always call
|
||||
// invalidate(), which forces the next lookup to re-read; the interval only
|
||||
// bounds staleness from changes made behind our back.
|
||||
const SNAPSHOT_SIGNATURE_RECHECK_INTERVAL_MS = 5000;
|
||||
|
||||
export function createCharacterNameCandidateLookup(deps: {
|
||||
userDataPath?: string;
|
||||
outputDir?: string;
|
||||
getCurrentMediaId?: () => number | null | undefined;
|
||||
now?: () => number;
|
||||
}): {
|
||||
get: (mediaId?: number | null) => CharacterNameCandidateSet | null;
|
||||
invalidate: () => void;
|
||||
} {
|
||||
const outputDir =
|
||||
deps.outputDir ??
|
||||
(deps.userDataPath ? path.join(deps.userDataPath, 'character-dictionaries') : '');
|
||||
const now = deps.now ?? (() => Date.now());
|
||||
let signature: string | null = null;
|
||||
let lastSignatureCheckAtMs = 0;
|
||||
let formsByMediaId = new Map<number, string[]>();
|
||||
|
||||
function refreshIfNeeded(): void {
|
||||
if (!outputDir) {
|
||||
formsByMediaId = new Map<number, string[]>();
|
||||
signature = '';
|
||||
return;
|
||||
}
|
||||
const nowMs = now();
|
||||
if (
|
||||
signature !== null &&
|
||||
nowMs - lastSignatureCheckAtMs < SNAPSHOT_SIGNATURE_RECHECK_INTERVAL_MS
|
||||
) {
|
||||
return;
|
||||
}
|
||||
lastSignatureCheckAtMs = nowMs;
|
||||
const nextSignature = getSnapshotDirectorySignature(outputDir);
|
||||
if (nextSignature === signature) {
|
||||
return;
|
||||
}
|
||||
signature = nextSignature;
|
||||
formsByMediaId = new Map<number, string[]>();
|
||||
for (const snapshot of readCachedSnapshots(outputDir)) {
|
||||
const forms = collectSnapshotNameForms(snapshot);
|
||||
if (forms.length > 0) {
|
||||
formsByMediaId.set(snapshot.mediaId, forms);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
get(mediaId?: number | null): CharacterNameCandidateSet | null {
|
||||
refreshIfNeeded();
|
||||
const rawMediaId = mediaId ?? deps.getCurrentMediaId?.() ?? null;
|
||||
const normalizedMediaId =
|
||||
typeof rawMediaId === 'number' && Number.isFinite(rawMediaId) && rawMediaId > 0
|
||||
? Math.floor(rawMediaId)
|
||||
: null;
|
||||
|
||||
// Without a media scope the pre-pass would need every character of every
|
||||
// cached title, which is both slow to match and pointless: report no
|
||||
// candidates so the scanner keeps its exhaustive behavior.
|
||||
if (normalizedMediaId === null) {
|
||||
return null;
|
||||
}
|
||||
const forms = formsByMediaId.get(normalizedMediaId);
|
||||
if (!forms || forms.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
key: `${digestSnapshotDirectorySignature(signature ?? '')}:${normalizedMediaId}`,
|
||||
forms,
|
||||
};
|
||||
},
|
||||
invalidate(): void {
|
||||
signature = null;
|
||||
lastSignatureCheckAtMs = 0;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isHanCodePoint } from '../../core/text/han-code-points';
|
||||
import { HONORIFIC_SUFFIXES } from './constants';
|
||||
import type { JapaneseNameParts, NameReadings, ResolvedNameSplits } from './types';
|
||||
|
||||
@@ -26,10 +27,12 @@ export function buildReading(term: string): string {
|
||||
return katakanaToHiragana(compact);
|
||||
}
|
||||
|
||||
// Code points, not code units: a supplementary-plane kanji (𠮷, U+20BB7) is a
|
||||
// surrogate pair, and reading only the high surrogate would classify a real
|
||||
// single-character name as non-kanji and drop it.
|
||||
export function containsKanji(value: string): boolean {
|
||||
for (const char of value) {
|
||||
const code = char.charCodeAt(0);
|
||||
if ((code >= 0x4e00 && code <= 0x9fff) || (code >= 0x3400 && code <= 0x4dbf)) {
|
||||
if (isHanCodePoint(char.codePointAt(0) ?? 0)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,3 +36,134 @@ test('buildNameTerms adds surname honorifics from Japanese localized aliases', (
|
||||
assert.ok(terms.includes('馬渕さん'));
|
||||
assert.ok(!terms.includes('송치'));
|
||||
});
|
||||
|
||||
test('buildNameTerms drops the disambiguator letter of a mob character name', () => {
|
||||
const terms = buildNameTerms(
|
||||
characterRecord({
|
||||
firstNameHint: '',
|
||||
lastNameHint: '',
|
||||
fullName: 'Joshi A',
|
||||
nativeName: '女子A',
|
||||
}),
|
||||
);
|
||||
|
||||
// ア would match every あ〜 in the subtitles; the letter is a disambiguator
|
||||
// (Girl A / Girl B), not a name.
|
||||
assert.ok(!terms.includes('ア'));
|
||||
assert.ok(!terms.includes('アさん'));
|
||||
assert.ok(terms.includes('女子A'));
|
||||
assert.ok(terms.includes('ジョシア'));
|
||||
});
|
||||
|
||||
test('buildNameTerms keeps a character whose whole name is one kana', () => {
|
||||
const terms = buildNameTerms(
|
||||
characterRecord({
|
||||
firstNameHint: '',
|
||||
lastNameHint: '',
|
||||
fullName: 'A',
|
||||
nativeName: 'あ',
|
||||
}),
|
||||
);
|
||||
|
||||
// The mob-label rule only judges parts a name was split into; a name the
|
||||
// source gives us whole is the character's actual name.
|
||||
assert.ok(terms.includes('あ'));
|
||||
assert.ok(terms.includes('あさん'));
|
||||
// Romanized forms are never lookup targets (the subtitles are Japanese), and
|
||||
// the single-kana alias "A" transliterates to is dropped as a collision.
|
||||
assert.ok(!terms.includes('A'));
|
||||
assert.ok(!terms.includes('ア'));
|
||||
});
|
||||
|
||||
test('buildNameTerms keeps a one-character name written in another script', () => {
|
||||
const terms = buildNameTerms(
|
||||
characterRecord({
|
||||
firstNameHint: '',
|
||||
lastNameHint: '',
|
||||
fullName: 'Byeol',
|
||||
nativeName: '별',
|
||||
alternativeNames: ['Я'],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.ok(terms.includes('별'));
|
||||
assert.ok(terms.includes('별さん'));
|
||||
assert.ok(terms.includes('Я'));
|
||||
});
|
||||
|
||||
test('buildNameTerms yields nothing for a character whose only name is a bare letter', () => {
|
||||
// Documented policy rather than an oversight: a romanized name is never a
|
||||
// term on its own (the subtitles are Japanese), and the single kana a bare
|
||||
// letter transliterates to would match every あ〜 in the line.
|
||||
assert.deepEqual(
|
||||
buildNameTerms(
|
||||
characterRecord({
|
||||
firstNameHint: '',
|
||||
lastNameHint: '',
|
||||
fullName: 'A',
|
||||
nativeName: '',
|
||||
}),
|
||||
),
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
test('buildNameTerms keeps one-character split parts that are not mob labels', () => {
|
||||
const hangul = buildNameTerms(
|
||||
characterRecord({
|
||||
firstNameHint: '',
|
||||
lastNameHint: '',
|
||||
fullName: 'Byeol Kim',
|
||||
nativeName: '별 김',
|
||||
}),
|
||||
);
|
||||
|
||||
assert.ok(hangul.includes('별'));
|
||||
assert.ok(hangul.includes('김'));
|
||||
|
||||
const middleDot = buildNameTerms(
|
||||
characterRecord({
|
||||
firstNameHint: '',
|
||||
lastNameHint: '',
|
||||
fullName: 'A Be',
|
||||
nativeName: 'ア・ベ',
|
||||
}),
|
||||
);
|
||||
|
||||
assert.ok(middleDot.includes('ア'));
|
||||
assert.ok(middleDot.includes('ベ'));
|
||||
});
|
||||
|
||||
test('buildNameTerms keeps a single-kanji name part', () => {
|
||||
// The name is an alias, not the native name, so the parts come from the
|
||||
// space split rather than from the native-name split.
|
||||
const terms = buildNameTerms(
|
||||
characterRecord({
|
||||
firstNameHint: 'Sora',
|
||||
lastNameHint: 'Yamada',
|
||||
fullName: 'Sora Yamada',
|
||||
nativeName: '',
|
||||
alternativeNames: ['山田 空'],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.ok(terms.includes('山田'));
|
||||
assert.ok(terms.includes('空'));
|
||||
});
|
||||
|
||||
test('buildNameTerms keeps a single supplementary-plane kanji name part', () => {
|
||||
// 𠮷 (U+20BB7) is a surrogate pair: a code-unit kanji check reads only the
|
||||
// high surrogate and drops the part as if it were a mob disambiguator.
|
||||
const terms = buildNameTerms(
|
||||
characterRecord({
|
||||
firstNameHint: 'Tsukasa',
|
||||
lastNameHint: 'Yoshi',
|
||||
fullName: 'Tsukasa Yoshi',
|
||||
nativeName: '',
|
||||
alternativeNames: ['𠮷 司'],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.ok(terms.includes('𠮷'));
|
||||
assert.ok(terms.includes('司'));
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { HAN_REGEXP_CLASS_BODY } from '../../core/text/han-code-points';
|
||||
import { HONORIFIC_SUFFIXES } from './constants';
|
||||
import {
|
||||
addRomanizedKanaAliases,
|
||||
@@ -42,11 +43,29 @@ export function expandRawNameVariants(rawName: string): string[] {
|
||||
return [...variants];
|
||||
}
|
||||
|
||||
// The label AniList appends to unnamed mob characters: one letter or digit,
|
||||
// halfwidth or fullwidth (女子A / "Joshi A" / 女子1). Nothing else qualifies —
|
||||
// a one-character part in any script is a real name part (별 김, ア・ベ, 山田 空).
|
||||
const SINGLE_LABEL_CHARACTER = /^[0-9A-Za-z\uff10-\uff19\uff21-\uff3a\uff41-\uff5a]$/u;
|
||||
|
||||
// Judged on split parts only: a name the source gives us whole in a script the
|
||||
// subtitles can contain is kept whatever it looks like, because a character
|
||||
// really can be called あ or 별. (A romanized name is a separate matter: it is
|
||||
// never a term on its own, only a source of kana aliases. See below.)
|
||||
function isUsableNameSplitPart(part: string): boolean {
|
||||
return !SINGLE_LABEL_CHARACTER.test(part);
|
||||
}
|
||||
|
||||
// Kana, Han (shared ranges), and the marks that only ever appear inside a
|
||||
// Japanese name: iteration marks and the small ka/ke used in place names.
|
||||
const JAPANESE_NAME_CHARACTERS = new RegExp(
|
||||
`^[\\u3040-\\u30ff${HAN_REGEXP_CLASS_BODY}\u3005\u3006\u30f5\u30f6\u30fc]+$`,
|
||||
'u',
|
||||
);
|
||||
|
||||
export function isJapaneseNameSplitCandidate(name: string): boolean {
|
||||
const compact = name.replace(/[\s\u3000・・·•]/g, '');
|
||||
return (
|
||||
containsKanji(compact) && /^[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff々〆ヵヶー]+$/.test(compact)
|
||||
);
|
||||
return containsKanji(compact) && JAPANESE_NAME_CHARACTERS.test(compact);
|
||||
}
|
||||
|
||||
function addJapaneseNameParts(
|
||||
@@ -97,8 +116,11 @@ export function buildNameTerms(
|
||||
|
||||
const split = name.split(/[\s\u3000]+/).filter((part) => part.trim().length > 0);
|
||||
if (split.length === 2) {
|
||||
target.add(split[0]!);
|
||||
target.add(split[1]!);
|
||||
for (const part of split) {
|
||||
if (isUsableNameSplitPart(part)) {
|
||||
target.add(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const splitByMiddleDot = name
|
||||
@@ -107,7 +129,9 @@ export function buildNameTerms(
|
||||
.filter((part) => part.length > 0);
|
||||
if (splitByMiddleDot.length >= 2) {
|
||||
for (const part of splitByMiddleDot) {
|
||||
target.add(part);
|
||||
if (isUsableNameSplitPart(part)) {
|
||||
target.add(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,7 +141,15 @@ export function buildNameTerms(
|
||||
}
|
||||
}
|
||||
|
||||
// Romanized names never become terms themselves — the subtitles are Japanese,
|
||||
// so "Joshi A" would never appear in one — they only contribute the kana a
|
||||
// Japanese writer would spell them with.
|
||||
for (const alias of addRomanizedKanaAliases(romanizedBase)) {
|
||||
// Except when the whole name is one letter: it transliterates to a single
|
||||
// kana (A → ア) that matches every あ〜 in the subtitles. A character whose
|
||||
// only recorded name is a bare letter therefore yields no terms at all,
|
||||
// which is the intended outcome: those are unnamed mob characters.
|
||||
if ([...alias].length === 1) continue;
|
||||
base.add(alias);
|
||||
}
|
||||
|
||||
|
||||
@@ -109,6 +109,7 @@ export interface MainIpcRuntimeServiceDepsParams {
|
||||
removeCharacterDictionaryManagedEntry?: IpcDepsRuntimeOptions['removeCharacterDictionaryManagedEntry'];
|
||||
moveCharacterDictionaryManagedEntry?: IpcDepsRuntimeOptions['moveCharacterDictionaryManagedEntry'];
|
||||
appendClipboardVideoToQueue: IpcDepsRuntimeOptions['appendClipboardVideoToQueue'];
|
||||
getChangelogSnapshot?: IpcDepsRuntimeOptions['getChangelogSnapshot'];
|
||||
getPlaylistBrowserSnapshot: IpcDepsRuntimeOptions['getPlaylistBrowserSnapshot'];
|
||||
appendPlaylistBrowserFile: IpcDepsRuntimeOptions['appendPlaylistBrowserFile'];
|
||||
playPlaylistBrowserIndex: IpcDepsRuntimeOptions['playPlaylistBrowserIndex'];
|
||||
@@ -303,6 +304,7 @@ export function createMainIpcRuntimeServiceDeps(
|
||||
removeCharacterDictionaryManagedEntry: params.removeCharacterDictionaryManagedEntry,
|
||||
moveCharacterDictionaryManagedEntry: params.moveCharacterDictionaryManagedEntry,
|
||||
appendClipboardVideoToQueue: params.appendClipboardVideoToQueue,
|
||||
getChangelogSnapshot: params.getChangelogSnapshot,
|
||||
getPlaylistBrowserSnapshot: params.getPlaylistBrowserSnapshot,
|
||||
appendPlaylistBrowserFile: params.appendPlaylistBrowserFile,
|
||||
playPlaylistBrowserIndex: params.playPlaylistBrowserIndex,
|
||||
|
||||
@@ -176,6 +176,29 @@ test('subtitle sidebar media path tag is assigned after prefetch succeeds', () =
|
||||
);
|
||||
});
|
||||
|
||||
test('remote media keeps parsed cues when the active subtitle source cannot be resolved', () => {
|
||||
const source = readMainSource();
|
||||
const actionBlock = source.match(
|
||||
/createRefreshSubtitlePrefetchFromActiveTrackHandler\(\{(?<body>[\s\S]*?)\n \}\);/,
|
||||
)?.groups?.body;
|
||||
|
||||
assert.ok(actionBlock);
|
||||
assert.match(actionBlock, /isYoutubeMediaPath\(videoPath\) \|\| isRemoteMediaPath\(videoPath\)/);
|
||||
});
|
||||
|
||||
test('jellyfin subtitle preload seeds the tokenization prefetch directly', () => {
|
||||
const source = readMainSource();
|
||||
const actionBlock = source.match(
|
||||
/preloadJellyfinExternalSubtitlesMainDeps:\s*\{(?<body>[\s\S]*?)\n \},/,
|
||||
)?.groups?.body;
|
||||
|
||||
assert.ok(actionBlock);
|
||||
assert.match(
|
||||
actionBlock,
|
||||
/initSubtitlePrefetch: \(sourcePath\) =>\s*subtitlePrefetchRuntime\.refreshSubtitleSidebarFromSource\(sourcePath\),/,
|
||||
);
|
||||
});
|
||||
|
||||
test('update overlay notification action triggers install flow', () => {
|
||||
const source = readMainSource();
|
||||
const runtimeSource = readSource('src/main/runtime/overlay-notifications-runtime.ts');
|
||||
@@ -200,7 +223,7 @@ test('update overlay notification action triggers install flow', () => {
|
||||
assert.match(runtimeSource, /fallbackClient\.openNoteInBrowser\(noteId\)/);
|
||||
});
|
||||
|
||||
test('subtitle change re-prioritizes prefetch around live playback before tokenizing current line', () => {
|
||||
test('subtitle change pauses prefetch without restarting its run before tokenizing current line', () => {
|
||||
const source = readMainSource();
|
||||
const actionBlock = source.match(
|
||||
/onSubtitleChange:\s*\(text\)\s*=>\s*\{(?<body>[\s\S]*?)\n \},\n refreshDiscordPresence:/,
|
||||
@@ -208,15 +231,19 @@ test('subtitle change re-prioritizes prefetch around live playback before tokeni
|
||||
|
||||
assert.ok(actionBlock);
|
||||
assert.match(actionBlock, /subtitlePrefetchService\?\.pause\(\);/);
|
||||
assert.match(actionBlock, /subtitlePrefetchService\?\.onSeek\(lastObservedTimePos\);/);
|
||||
assert.match(actionBlock, /subtitleProcessingController\.onSubtitleChange\(text\);/);
|
||||
// Restarting the run per line (onSeek) discards in-flight prefetch work;
|
||||
// only real seeks restart via onTimePosUpdate.
|
||||
assert.doesNotMatch(actionBlock, /subtitlePrefetchService\?\.onSeek\(/);
|
||||
assert.match(actionBlock, /subtitleProcessingController\.onSubtitleChange\(text\)/);
|
||||
assert.ok(
|
||||
actionBlock.indexOf('subtitlePrefetchService?.pause();') <
|
||||
actionBlock.indexOf('subtitlePrefetchService?.onSeek(lastObservedTimePos);'),
|
||||
actionBlock.indexOf('subtitleProcessingController.onSubtitleChange(text)'),
|
||||
);
|
||||
assert.ok(
|
||||
actionBlock.indexOf('subtitlePrefetchService?.onSeek(lastObservedTimePos);') <
|
||||
actionBlock.indexOf('subtitleProcessingController.onSubtitleChange(text);'),
|
||||
// A repeated subtitle emits nothing, so the pause has to be released here or
|
||||
// prefetching idles until the next distinct line.
|
||||
assert.match(
|
||||
actionBlock,
|
||||
/if \(!subtitleProcessingController\.onSubtitleChange\(text\)\) \{[\s\S]*?subtitlePrefetchService\?\.resume\(\);/,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -466,16 +493,35 @@ test('known-word updates invalidate prefetched tokenizations before refreshing c
|
||||
assert.match(actionBlock, /subtitlePrefetchService\?\.onSeek\(lastObservedTimePos\);/);
|
||||
assert.match(
|
||||
actionBlock,
|
||||
/subtitleProcessingController\.refreshCurrentSubtitle\(appState\.currentSubText\);/,
|
||||
/if \(!subtitleProcessingController\.refreshCurrentSubtitle\(appState\.currentSubText\)\) \{[\s\S]*?subtitlePrefetchService\?\.resume\(\);/,
|
||||
);
|
||||
assert.ok(
|
||||
actionBlock.indexOf('subtitleProcessingController.invalidateTokenizationCache();') <
|
||||
actionBlock.indexOf(
|
||||
'subtitleProcessingController.refreshCurrentSubtitle(appState.currentSubText);',
|
||||
'subtitleProcessingController.refreshCurrentSubtitle(appState.currentSubText)',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('subtitle processing controller resumes prefetch on settle, not on its emits', () => {
|
||||
const source = readMainSource();
|
||||
const depsBlock = source.match(
|
||||
/createBuildSubtitleProcessingControllerMainDepsHandler\(\{(?<body>[\s\S]*?)\n \}\);/,
|
||||
)?.groups?.body;
|
||||
|
||||
assert.ok(depsBlock);
|
||||
// A controller emit can be the provisional plain payload sent before the
|
||||
// scan runs, so it must not release the prefetch pause.
|
||||
assert.match(
|
||||
depsBlock,
|
||||
/emitSubtitle: \(payload\) => emitSubtitlePayload\(payload, \{ resumePrefetch: false \}\),/,
|
||||
);
|
||||
assert.match(
|
||||
depsBlock,
|
||||
/onProcessingSettled: \(\) => \{\s+subtitlePrefetchService\?\.resume\(\);/,
|
||||
);
|
||||
});
|
||||
|
||||
test('manual visible overlay changes notify mpv plugin visibility state', () => {
|
||||
const source = readMainSource();
|
||||
const setBlock = source.match(
|
||||
@@ -570,7 +616,7 @@ test('YouTube media cache lifecycle routes through configured status notificatio
|
||||
test('subtitle broadcasts share one frequency options snapshot per emitted payload', () => {
|
||||
const source = readMainSource();
|
||||
const emitBlock = source.match(
|
||||
/function emitSubtitlePayload\(payload: SubtitleData\): void \{(?<body>[\s\S]*?)\n\}/,
|
||||
/function emitSubtitlePayload\([\s\S]*?\): void \{(?<body>[\s\S]*?)\n\}/,
|
||||
)?.groups?.body;
|
||||
const frequencyOptionsSnapshot = emitBlock?.match(
|
||||
/const frequencyDictionary = configService\.getConfig\(\)\.subtitleStyle\.frequencyDictionary;(?<body>[\s\S]*?)\n \};/,
|
||||
@@ -590,6 +636,35 @@ test('subtitle broadcasts share one frequency options snapshot per emitted paylo
|
||||
);
|
||||
});
|
||||
|
||||
test('annotation upgrades skip the duplicate basic websocket event', () => {
|
||||
const source = readMainSource();
|
||||
const emitBlock = source.match(
|
||||
/function emitSubtitlePayload\([\s\S]*?\): void \{(?<body>[\s\S]*?)\n\}/,
|
||||
)?.groups?.body;
|
||||
|
||||
assert.ok(emitBlock);
|
||||
assert.match(
|
||||
emitBlock,
|
||||
/const isAnnotationUpgrade = isSubtitleAnnotationUpgrade\(currentSubtitleData, timedPayload\);/,
|
||||
);
|
||||
assert.match(
|
||||
emitBlock,
|
||||
/if \(!isAnnotationUpgrade\) \{\s+subtitleWsService\.broadcast\(timedPayload, frequencyOptions\);\s+\}/,
|
||||
);
|
||||
assert.equal(
|
||||
(emitBlock.match(/overlayManager\.broadcastToOverlayWindows\('subtitle:set'/g) ?? []).length,
|
||||
1,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
emitBlock.match(
|
||||
/annotationSubtitleWsService\.broadcast\(timedPayload, frequencyOptions\)/g,
|
||||
) ?? []
|
||||
).length,
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
test('websocket frequency options callbacks each read one configuration snapshot', () => {
|
||||
const source = readMainSource();
|
||||
const subtitleBlock = source.match(
|
||||
|
||||
@@ -21,6 +21,18 @@ export type InstallStage = 'locating' | 'downloading' | 'verifying' | 'extractin
|
||||
/** Neither call has a default deadline, so a hung network would stall install. */
|
||||
const RELEASES_TIMEOUT_MS = 30_000;
|
||||
const DOWNLOAD_TIMEOUT_MS = 300_000;
|
||||
/**
|
||||
* Hard ceiling on the buffered bundle. The real asset is a JRE plus a jar, well
|
||||
* under this; the cap only stops a wrong or hostile URL from filling memory.
|
||||
*/
|
||||
const MAX_BUNDLE_BYTES = 512 * 1024 * 1024;
|
||||
|
||||
function oversizedBundle(): Error {
|
||||
return new Error(
|
||||
`The anime bridge bundle exceeded ${Math.round(MAX_BUNDLE_BYTES / (1024 * 1024))} MB; ` +
|
||||
'the download was stopped.',
|
||||
);
|
||||
}
|
||||
|
||||
export interface InstallProgress {
|
||||
stage: InstallStage;
|
||||
@@ -78,7 +90,11 @@ async function downloadWithProgress(
|
||||
): Promise<Uint8Array> {
|
||||
const declared = Number(response.headers.get('content-length') ?? '0');
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) return new Uint8Array(await response.arrayBuffer());
|
||||
if (!reader) {
|
||||
const buffer = await response.arrayBuffer();
|
||||
if (buffer.byteLength > MAX_BUNDLE_BYTES) throw oversizedBundle();
|
||||
return new Uint8Array(buffer);
|
||||
}
|
||||
|
||||
const chunks: Uint8Array[] = [];
|
||||
let received = 0;
|
||||
@@ -86,6 +102,12 @@ async function downloadWithProgress(
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (value) {
|
||||
// Checked against the bytes actually read, not content-length: a lying
|
||||
// (or absent) header must not let the bundle allocate without bound.
|
||||
if (received + value.length > MAX_BUNDLE_BYTES) {
|
||||
await reader.cancel().catch(() => {});
|
||||
throw oversizedBundle();
|
||||
}
|
||||
chunks.push(value);
|
||||
received += value.length;
|
||||
if (declared > 0) onProgress?.(Math.min(1, received / declared));
|
||||
|
||||
@@ -60,8 +60,17 @@ export function registerAnimeBrowserIpcHandlers(deps: AnimeBrowserIpcDeps): void
|
||||
handle(channels.animeBrowserAddRepo, (_event, url) => runtime.addRepo(String(url)));
|
||||
handle(channels.animeBrowserRemoveRepo, (_event, url) => runtime.removeRepo(String(url)));
|
||||
handle(channels.animeBrowserPlayEpisode, (_event, request) =>
|
||||
runtime.playEpisode(request as AnimeBrowserPlayRequest),
|
||||
runtime.playEpisode(toPlayRequest(request)),
|
||||
);
|
||||
handle(channels.animeBrowserQueueEpisode, (_event, request) =>
|
||||
runtime.queueEpisode(toPlayRequest(request)),
|
||||
);
|
||||
handle(channels.animeBrowserDequeueEpisode, (_event, sourceId, episodeUrl) =>
|
||||
runtime.dequeueEpisode(String(sourceId ?? ''), String(episodeUrl ?? '')),
|
||||
);
|
||||
handle(channels.animeBrowserClearQueue, () => runtime.clearQueue());
|
||||
handle(channels.animeBrowserGetQueue, () => runtime.getQueue());
|
||||
handle(channels.animeBrowserIsPlaying, () => runtime.isPlaying());
|
||||
handle(channels.animeBrowserGetPreferences, (_event, sourceId) =>
|
||||
runtime.getPreferences(String(sourceId)),
|
||||
);
|
||||
@@ -70,6 +79,24 @@ export function registerAnimeBrowserIpcHandlers(deps: AnimeBrowserIpcDeps): void
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce a play (or queue) request. A queued request is held until its turn
|
||||
* comes, so a bad field would surface long after the click that sent it.
|
||||
*/
|
||||
function toPlayRequest(value: unknown): AnimeBrowserPlayRequest {
|
||||
const request = (value ?? {}) as Partial<AnimeBrowserPlayRequest>;
|
||||
return {
|
||||
sourceId: String(request.sourceId ?? ''),
|
||||
animeUrl: String(request.animeUrl ?? ''),
|
||||
animeTitle: String(request.animeTitle ?? ''),
|
||||
episodeUrl: String(request.episodeUrl ?? ''),
|
||||
episodeName: String(request.episodeName ?? ''),
|
||||
// NaN and Infinity are numbers as far as typeof is concerned, and either
|
||||
// one would reach the stats row as a nonsense episode number.
|
||||
episodeNumber: Number.isFinite(request.episodeNumber) ? request.episodeNumber! : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Coerce a watch-state request; the renderer's arrays arrive untyped. */
|
||||
function toWatchStateRequest(value: unknown): AnimeBrowserWatchStateRequest {
|
||||
const request = (value ?? {}) as Partial<AnimeBrowserWatchStateRequest>;
|
||||
|
||||
@@ -183,6 +183,9 @@ export function createAnimeBrowserPlayback(options: AnimeBrowserPlaybackOptions)
|
||||
}
|
||||
|
||||
async function dispose(): Promise<void> {
|
||||
// Bumping the generation makes any in-flight playEpisode stale, so a cache
|
||||
// it is still writing gets removed by that call instead of outliving us.
|
||||
playbackGeneration += 1;
|
||||
const cacheDir = subtitleCacheDir;
|
||||
subtitleCacheDir = null;
|
||||
await removeSubtitleCache(cacheDir, deps.subtitleCacheIo);
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { PlaybackEndFileEvent } from '../../anime-bridge/playback-outcome';
|
||||
import type { AnimeBrowserPlayRequest, AnimeBrowserQueueState } from '../../types/anime-browser';
|
||||
import { createAnimeBrowserQueue, type AnimeBrowserQueueDeps } from './anime-browser-queue';
|
||||
|
||||
function makeRequest(overrides: Partial<AnimeBrowserPlayRequest> = {}): AnimeBrowserPlayRequest {
|
||||
return {
|
||||
sourceId: 'source',
|
||||
animeUrl: '/anime',
|
||||
animeTitle: 'Anime',
|
||||
episodeUrl: '/episode-1',
|
||||
episodeName: 'Episode 1',
|
||||
episodeNumber: 1,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
interface Harness {
|
||||
deps: AnimeBrowserQueueDeps;
|
||||
played: AnimeBrowserPlayRequest[];
|
||||
commands: Array<Array<string | number>>;
|
||||
states: AnimeBrowserQueueState[];
|
||||
osd: string[];
|
||||
endFile: (event: PlaybackEndFileEvent) => void;
|
||||
/** How many listeners are subscribed right now. */
|
||||
listenerCount: () => number;
|
||||
}
|
||||
|
||||
function makeHarness(
|
||||
options: {
|
||||
play?: (request: AnimeBrowserPlayRequest) => Promise<{
|
||||
ok: boolean;
|
||||
error: string | null;
|
||||
quality: string | null;
|
||||
}>;
|
||||
keepOpen?: unknown;
|
||||
withEndFile?: boolean;
|
||||
} = {},
|
||||
): Harness {
|
||||
const played: AnimeBrowserPlayRequest[] = [];
|
||||
const commands: Array<Array<string | number>> = [];
|
||||
const states: AnimeBrowserQueueState[] = [];
|
||||
const osd: string[] = [];
|
||||
const listeners = new Set<(event: PlaybackEndFileEvent) => void>();
|
||||
|
||||
const deps: AnimeBrowserQueueDeps = {
|
||||
play: async (request) => {
|
||||
played.push(request);
|
||||
return options.play
|
||||
? await options.play(request)
|
||||
: { ok: true, error: null, quality: '1080p' };
|
||||
},
|
||||
sendMpvCommand: (command) => void commands.push(command),
|
||||
onQueueState: (state) => void states.push(state),
|
||||
showMpvOsd: (message) => void osd.push(message),
|
||||
log: () => undefined,
|
||||
};
|
||||
if (options.withEndFile !== false) {
|
||||
deps.onPlaybackEndFile = (listener) => {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
if (options.keepOpen !== undefined) {
|
||||
deps.readMpvProperty = async (name) => {
|
||||
if (name !== 'keep-open') throw new Error(`unexpected property ${name}`);
|
||||
return options.keepOpen;
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
deps,
|
||||
played,
|
||||
commands,
|
||||
states,
|
||||
osd,
|
||||
endFile: (event) => {
|
||||
for (const listener of [...listeners]) listener(event);
|
||||
},
|
||||
listenerCount: () => listeners.size,
|
||||
};
|
||||
}
|
||||
|
||||
const EOF: PlaybackEndFileEvent = { reason: 'eof', fileError: null };
|
||||
|
||||
test('an episode that runs to its end hands the queue its turn', async () => {
|
||||
const harness = makeHarness();
|
||||
const queue = createAnimeBrowserQueue(harness.deps);
|
||||
|
||||
queue.enqueue(makeRequest());
|
||||
queue.enqueue(makeRequest({ episodeUrl: '/episode-2', episodeName: 'Episode 2' }));
|
||||
harness.endFile(EOF);
|
||||
await new Promise(setImmediate);
|
||||
|
||||
assert.deepEqual(
|
||||
harness.played.map((request) => request.episodeUrl),
|
||||
['/episode-1'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
queue.getState().entries.map((entry) => entry.episodeUrl),
|
||||
['/episode-2'],
|
||||
);
|
||||
});
|
||||
|
||||
test('only a file that ended by itself advances the queue', async () => {
|
||||
const harness = makeHarness();
|
||||
const queue = createAnimeBrowserQueue(harness.deps);
|
||||
|
||||
queue.enqueue(makeRequest());
|
||||
harness.endFile({ reason: 'stop', fileError: null });
|
||||
harness.endFile({ reason: 'quit', fileError: null });
|
||||
harness.endFile({ reason: 'error', fileError: 'dead host' });
|
||||
await new Promise(setImmediate);
|
||||
|
||||
assert.deepEqual(harness.played, []);
|
||||
assert.equal(queue.getState().entries.length, 1);
|
||||
});
|
||||
|
||||
test('queueing the same episode twice leaves one entry', () => {
|
||||
const harness = makeHarness();
|
||||
const queue = createAnimeBrowserQueue(harness.deps);
|
||||
|
||||
queue.enqueue(makeRequest());
|
||||
const state = queue.enqueue(makeRequest());
|
||||
|
||||
assert.equal(state.entries.length, 1);
|
||||
});
|
||||
|
||||
test('an advance is counted and names the episode it started', async () => {
|
||||
const harness = makeHarness();
|
||||
const queue = createAnimeBrowserQueue(harness.deps);
|
||||
|
||||
queue.enqueue(makeRequest());
|
||||
assert.equal(queue.getState().advances, 0);
|
||||
harness.endFile(EOF);
|
||||
await new Promise(setImmediate);
|
||||
|
||||
const state = queue.getState();
|
||||
assert.equal(state.advances, 1);
|
||||
assert.equal(state.lastStarted?.episodeUrl, '/episode-1');
|
||||
});
|
||||
|
||||
test('an episode dequeues by its own source and url', () => {
|
||||
const harness = makeHarness();
|
||||
const queue = createAnimeBrowserQueue(harness.deps);
|
||||
|
||||
queue.enqueue(makeRequest());
|
||||
queue.enqueue(makeRequest({ sourceId: 'other' }));
|
||||
const state = queue.dequeue('source', '/episode-1');
|
||||
|
||||
assert.deepEqual(
|
||||
state.entries.map((entry) => entry.sourceId),
|
||||
['other'],
|
||||
);
|
||||
});
|
||||
|
||||
test('a queued episode that will not play stops the queue and reports why', async () => {
|
||||
const harness = makeHarness({
|
||||
play: async () => ({
|
||||
ok: false,
|
||||
error: 'That source returned no playable video.',
|
||||
quality: null,
|
||||
}),
|
||||
});
|
||||
const queue = createAnimeBrowserQueue(harness.deps);
|
||||
|
||||
queue.enqueue(makeRequest());
|
||||
queue.enqueue(makeRequest({ episodeUrl: '/episode-2', episodeName: 'Episode 2' }));
|
||||
harness.endFile(EOF);
|
||||
await new Promise(setImmediate);
|
||||
|
||||
const state = queue.getState();
|
||||
assert.equal(state.lastError, 'Episode 1: That source returned no playable video.');
|
||||
// The failed episode is gone; the rest is still the user's queue.
|
||||
assert.deepEqual(
|
||||
state.entries.map((entry) => entry.episodeUrl),
|
||||
['/episode-2'],
|
||||
);
|
||||
assert.equal(harness.osd.length, 1);
|
||||
});
|
||||
|
||||
test('a second end-file while an advance is resolving does not double-load', async () => {
|
||||
let release = (): void => undefined;
|
||||
const started = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const harness = makeHarness({
|
||||
play: async () => {
|
||||
await started;
|
||||
return { ok: true, error: null, quality: null };
|
||||
},
|
||||
});
|
||||
const queue = createAnimeBrowserQueue(harness.deps);
|
||||
|
||||
queue.enqueue(makeRequest());
|
||||
queue.enqueue(makeRequest({ episodeUrl: '/episode-2', episodeName: 'Episode 2' }));
|
||||
harness.endFile(EOF);
|
||||
harness.endFile(EOF);
|
||||
release();
|
||||
await new Promise(setImmediate);
|
||||
|
||||
assert.deepEqual(
|
||||
harness.played.map((request) => request.episodeUrl),
|
||||
['/episode-1'],
|
||||
);
|
||||
});
|
||||
|
||||
test('mpv is told not to hold the last file open while the queue waits', async () => {
|
||||
const harness = makeHarness({ keepOpen: 'yes' });
|
||||
const queue = createAnimeBrowserQueue(harness.deps);
|
||||
|
||||
queue.enqueue(makeRequest());
|
||||
await new Promise(setImmediate);
|
||||
assert.deepEqual(harness.commands, [['set_property', 'keep-open', 'no']]);
|
||||
|
||||
queue.clear();
|
||||
assert.deepEqual(harness.commands[1], ['set_property', 'keep-open', 'yes']);
|
||||
});
|
||||
|
||||
test('mpv that already lets files end is left alone', async () => {
|
||||
const harness = makeHarness({ keepOpen: 'no' });
|
||||
const queue = createAnimeBrowserQueue(harness.deps);
|
||||
|
||||
queue.enqueue(makeRequest());
|
||||
await new Promise(setImmediate);
|
||||
queue.clear();
|
||||
|
||||
assert.deepEqual(harness.commands, []);
|
||||
});
|
||||
|
||||
test('the last queued episode plays under the user own keep-open setting', async () => {
|
||||
const harness = makeHarness({ keepOpen: 'always' });
|
||||
const queue = createAnimeBrowserQueue(harness.deps);
|
||||
|
||||
queue.enqueue(makeRequest());
|
||||
await new Promise(setImmediate);
|
||||
harness.endFile(EOF);
|
||||
await new Promise(setImmediate);
|
||||
|
||||
assert.deepEqual(harness.commands, [
|
||||
['set_property', 'keep-open', 'no'],
|
||||
['set_property', 'keep-open', 'always'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('playback started outside the queue re-points the end-file listener', async () => {
|
||||
const harness = makeHarness();
|
||||
const queue = createAnimeBrowserQueue(harness.deps);
|
||||
|
||||
queue.enqueue(makeRequest());
|
||||
queue.handlePlaybackStarted();
|
||||
queue.handlePlaybackStarted();
|
||||
|
||||
// Each re-arm replaces the previous subscription rather than stacking on it,
|
||||
// so one end-file cannot advance the queue several times over.
|
||||
assert.equal(harness.listenerCount(), 1);
|
||||
harness.endFile(EOF);
|
||||
await new Promise(setImmediate);
|
||||
assert.equal(harness.played.length, 1);
|
||||
});
|
||||
|
||||
test('an emptied queue stops listening for the end of the file', () => {
|
||||
const harness = makeHarness();
|
||||
const queue = createAnimeBrowserQueue(harness.deps);
|
||||
|
||||
queue.enqueue(makeRequest());
|
||||
assert.equal(harness.listenerCount(), 1);
|
||||
queue.dequeue('source', '/episode-1');
|
||||
assert.equal(harness.listenerCount(), 0);
|
||||
});
|
||||
|
||||
test('the queue still accepts episodes when mpv reports no events', () => {
|
||||
const harness = makeHarness({ withEndFile: false });
|
||||
const queue = createAnimeBrowserQueue(harness.deps);
|
||||
|
||||
assert.equal(queue.enqueue(makeRequest()).entries.length, 1);
|
||||
});
|
||||
Binary file not shown.
@@ -11,7 +11,11 @@ import type { SubtitleCacheIo } from '../../anime-bridge/subtitle-cache';
|
||||
import type { BundleBinaries } from '../../anime-bridge/sidecar-bundle';
|
||||
import { startSidecar } from '../../anime-bridge/sidecar-process';
|
||||
import { startStreamStripProxy } from '../../anime-bridge/stream-strip-proxy';
|
||||
import type { AnimeBrowserBridgeState, AnimeBrowserSearchUpdate } from '../../types/anime-browser';
|
||||
import type {
|
||||
AnimeBrowserBridgeState,
|
||||
AnimeBrowserQueueState,
|
||||
AnimeBrowserSearchUpdate,
|
||||
} from '../../types/anime-browser';
|
||||
import type { InstallProgress } from './anime-bridge-installer';
|
||||
|
||||
export interface AnimeBrowserRuntimeDeps {
|
||||
@@ -53,6 +57,8 @@ export interface AnimeBrowserRuntimeDeps {
|
||||
/** Overrides the filesystem/network the subtitle cache uses. Tests only. */
|
||||
subtitleCacheIo?: SubtitleCacheIo;
|
||||
onBridgeState: (state: AnimeBrowserBridgeState) => void;
|
||||
/** Pushes the play queue to the browser window, advances included. */
|
||||
onQueueState?: (state: AnimeBrowserQueueState) => void;
|
||||
/** Streams per-source progress while a search invoke is pending. */
|
||||
onSearchUpdate?: (update: AnimeBrowserSearchUpdate) => void;
|
||||
preferredQuality?: () => string | undefined;
|
||||
|
||||
@@ -37,6 +37,9 @@ import type {
|
||||
AnimeBrowserEntry,
|
||||
AnimeBrowserEpisode,
|
||||
AnimeBrowserEpisodeWatchState,
|
||||
AnimeBrowserPlayRequest,
|
||||
AnimeBrowserPlayResult,
|
||||
AnimeBrowserQueueState,
|
||||
AnimeBrowserSetWatchedRequest,
|
||||
AnimeBrowserWatchStateRequest,
|
||||
AnimeBrowserSearchResult,
|
||||
@@ -47,6 +50,7 @@ import type {
|
||||
} from '../../types/anime-browser';
|
||||
import type { BridgeAnimePage, BridgePreference } from '../../anime-bridge/types';
|
||||
import { createAnimeBrowserPlayback } from './anime-browser-playback';
|
||||
import { createAnimeBrowserQueue } from './anime-browser-queue';
|
||||
import type { AnimeBrowserRuntimeDeps } from './anime-browser-runtime-deps';
|
||||
export type { AnimeBrowserRuntimeDeps } from './anime-browser-runtime-deps';
|
||||
|
||||
@@ -350,6 +354,16 @@ export function createAnimeBrowserRuntime(deps: AnimeBrowserRuntimeDeps) {
|
||||
stripProxy: () => stripProxy,
|
||||
});
|
||||
|
||||
const queue = createAnimeBrowserQueue({
|
||||
play: (request) => playback.playEpisode(request),
|
||||
onPlaybackEndFile: deps.onPlaybackEndFile,
|
||||
readMpvProperty: deps.readMpvProperty,
|
||||
sendMpvCommand: deps.sendMpvCommand,
|
||||
onQueueState: deps.onQueueState,
|
||||
showMpvOsd: deps.showMpvOsd,
|
||||
log: deps.log,
|
||||
});
|
||||
|
||||
return {
|
||||
getSnapshot(): AnimeBrowserSnapshot {
|
||||
return {
|
||||
@@ -389,6 +403,7 @@ export function createAnimeBrowserRuntime(deps: AnimeBrowserRuntimeDeps) {
|
||||
version: extension.version,
|
||||
nsfw: extension.nsfw,
|
||||
repoUrl: extension.repoUrl,
|
||||
iconUrl: extension.iconUrl,
|
||||
sourceNames: extension.sourceNames,
|
||||
installed: installedPkgs.has(extension.pkg),
|
||||
})),
|
||||
@@ -572,7 +587,45 @@ export function createAnimeBrowserRuntime(deps: AnimeBrowserRuntimeDeps) {
|
||||
});
|
||||
},
|
||||
|
||||
playEpisode: playback.playEpisode,
|
||||
/**
|
||||
* Play now, replacing whatever mpv has. The queue is left standing and
|
||||
* re-armed behind this file, so an episode played by hand mid-queue is a
|
||||
* detour rather than a reset.
|
||||
*/
|
||||
async playEpisode(request: AnimeBrowserPlayRequest): Promise<AnimeBrowserPlayResult> {
|
||||
const result = await playback.playEpisode(request);
|
||||
if (result.ok) queue.handlePlaybackStarted();
|
||||
return result;
|
||||
},
|
||||
|
||||
queueEpisode(request: AnimeBrowserPlayRequest): AnimeBrowserQueueState {
|
||||
return queue.enqueue(request);
|
||||
},
|
||||
|
||||
dequeueEpisode(sourceId: string, episodeUrl: string): AnimeBrowserQueueState {
|
||||
return queue.dequeue(sourceId, episodeUrl);
|
||||
},
|
||||
|
||||
clearQueue(): AnimeBrowserQueueState {
|
||||
return queue.clear();
|
||||
},
|
||||
|
||||
getQueue(): AnimeBrowserQueueState {
|
||||
return queue.getState();
|
||||
},
|
||||
|
||||
/**
|
||||
* Whether mpv has a file open. An mpv that is not running cannot answer,
|
||||
* and there is nothing playing in it either, so both read as false.
|
||||
*/
|
||||
async isPlaying(): Promise<boolean> {
|
||||
if (!deps.readMpvProperty) return false;
|
||||
try {
|
||||
return (await deps.readMpvProperty('idle-active')) !== true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
const handle = sidecar;
|
||||
@@ -581,6 +634,7 @@ export function createAnimeBrowserRuntime(deps: AnimeBrowserRuntimeDeps) {
|
||||
stripProxy = null;
|
||||
starting = null;
|
||||
setState(IDLE_STATE);
|
||||
queue.dispose();
|
||||
await playback.dispose();
|
||||
await proxy?.close();
|
||||
await handle?.stop();
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createSubtitleProcessingController } from '../../core/services/subtitle-processing-controller';
|
||||
import type { SubtitleData } from '../../types';
|
||||
import {
|
||||
createAutoplaySubtitlePrimingRuntime,
|
||||
setMpvCurrentSecondarySubText,
|
||||
@@ -42,8 +44,9 @@ test('scheduleSubtitlePrefetchRefresh logs refresh failures from timer callback'
|
||||
setActiveParsedSubtitleMediaPath: () => {},
|
||||
subtitleProcessingController: {
|
||||
consumeCachedSubtitle: () => null,
|
||||
onSubtitleChange: () => {},
|
||||
refreshCurrentSubtitle: () => {},
|
||||
onSubtitleChange: () => true,
|
||||
refreshCurrentSubtitle: () => true,
|
||||
notePlainSubtitleEmitted: () => {},
|
||||
},
|
||||
emitSubtitlePayload: () => {},
|
||||
getSubtitlePrefetchService: () => null,
|
||||
@@ -93,13 +96,25 @@ test('primeCurrentSubtitleForAutoplay refreshes active subtitle cues when mpv su
|
||||
setActiveParsedSubtitleMediaPath: () => {},
|
||||
subtitleProcessingController: {
|
||||
consumeCachedSubtitle: () => null,
|
||||
onSubtitleChange: (text) => calls.push(`change:${text}`),
|
||||
refreshCurrentSubtitle: (text) => calls.push(`refresh:${text ?? ''}`),
|
||||
onSubtitleChange: (text) => {
|
||||
calls.push(`change:${text}`);
|
||||
return true;
|
||||
},
|
||||
refreshCurrentSubtitle: (text) => {
|
||||
calls.push(`refresh:${text ?? ''}`);
|
||||
return true;
|
||||
},
|
||||
notePlainSubtitleEmitted: () => {},
|
||||
},
|
||||
emitSubtitlePayload: (payload) => calls.push(`emit:${payload.text}`),
|
||||
emitSubtitlePayload: (payload, options) =>
|
||||
calls.push(`emit:${payload.text}:resume=${options?.resumePrefetch !== false}`),
|
||||
getSubtitlePrefetchService: () => ({
|
||||
pause: () => calls.push('prefetch:pause'),
|
||||
onSeek: (timePos) => calls.push(`prefetch:seek:${timePos}`),
|
||||
pause: () => {
|
||||
calls.push('prefetch:pause');
|
||||
},
|
||||
resume: () => {
|
||||
calls.push('prefetch:resume');
|
||||
},
|
||||
}),
|
||||
getLastObservedTimePos: () => 12,
|
||||
getVisibleOverlayVisible: () => true,
|
||||
@@ -120,8 +135,10 @@ test('primeCurrentSubtitleForAutoplay refreshes active subtitle cues when mpv su
|
||||
'request:time-pos',
|
||||
'set:起動字幕',
|
||||
'prefetch:pause',
|
||||
'emit:起動字幕',
|
||||
'change:起動字幕',
|
||||
'emit:起動字幕:resume=false',
|
||||
// Uncached priming refreshes rather than announcing a change, so an
|
||||
// invalidated-but-unchanged line is still re-tokenized.
|
||||
'refresh:起動字幕',
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -151,13 +168,25 @@ test('primeCurrentSubtitleForAutoplay emits raw first paint on cache miss before
|
||||
setActiveParsedSubtitleMediaPath: () => {},
|
||||
subtitleProcessingController: {
|
||||
consumeCachedSubtitle: () => null,
|
||||
onSubtitleChange: (text) => calls.push(`change:${text}`),
|
||||
refreshCurrentSubtitle: (text) => calls.push(`refresh:${text ?? ''}`),
|
||||
onSubtitleChange: (text) => {
|
||||
calls.push(`change:${text}`);
|
||||
return true;
|
||||
},
|
||||
refreshCurrentSubtitle: (text) => {
|
||||
calls.push(`refresh:${text ?? ''}`);
|
||||
return true;
|
||||
},
|
||||
notePlainSubtitleEmitted: () => {},
|
||||
},
|
||||
emitSubtitlePayload: (payload) => calls.push(`emit:${payload.text}`),
|
||||
emitSubtitlePayload: (payload, options) =>
|
||||
calls.push(`emit:${payload.text}:resume=${options?.resumePrefetch !== false}`),
|
||||
getSubtitlePrefetchService: () => ({
|
||||
pause: () => calls.push('prefetch:pause'),
|
||||
onSeek: (timePos) => calls.push(`prefetch:seek:${timePos}`),
|
||||
pause: () => {
|
||||
calls.push('prefetch:pause');
|
||||
},
|
||||
resume: () => {
|
||||
calls.push('prefetch:resume');
|
||||
},
|
||||
}),
|
||||
getLastObservedTimePos: () => 12,
|
||||
getVisibleOverlayVisible: () => true,
|
||||
@@ -175,7 +204,228 @@ test('primeCurrentSubtitleForAutoplay emits raw first paint on cache miss before
|
||||
'request:sub-text',
|
||||
'set:起動字幕',
|
||||
'prefetch:pause',
|
||||
'emit:起動字幕',
|
||||
'change:起動字幕',
|
||||
'emit:起動字幕:resume=false',
|
||||
// Uncached priming refreshes rather than announcing a change, so an
|
||||
// invalidated-but-unchanged line is still re-tokenized.
|
||||
'refresh:起動字幕',
|
||||
]);
|
||||
});
|
||||
|
||||
// Driven by the real processing controller rather than a stub: the failure this
|
||||
// covers is a disagreement between the priming path and the controller's own
|
||||
// staleness rules, which a hand-written stub cannot reproduce.
|
||||
function createPrimingRuntimeWithRealController(options: {
|
||||
text: string;
|
||||
calls: string[];
|
||||
onTokenize: () => void;
|
||||
tokenize?: (text: string) => SubtitleData | null | Promise<SubtitleData | null>;
|
||||
cacheLimit?: number;
|
||||
}) {
|
||||
const { text, calls } = options;
|
||||
let currentSubText = '';
|
||||
let currentSubtitleData: SubtitleData | null = null;
|
||||
const mediaPath = '/media/video.mkv';
|
||||
|
||||
const prefetchService = {
|
||||
pause: () => calls.push('prefetch:pause'),
|
||||
resume: () => calls.push('prefetch:resume'),
|
||||
};
|
||||
// Mirrors main.ts emitSubtitlePayload: an emit resumes prefetching unless it
|
||||
// is explicitly marked as not the end of the work for the line, and every
|
||||
// controller emit is so marked.
|
||||
const emitSubtitlePayload = (
|
||||
payload: SubtitleData,
|
||||
emitOptions?: { resumePrefetch?: boolean },
|
||||
): void => {
|
||||
currentSubtitleData = payload;
|
||||
calls.push(
|
||||
emitOptions?.resumePrefetch === false
|
||||
? `emit-raw:${payload.text}`
|
||||
: `emit-direct:${payload.text}`,
|
||||
);
|
||||
if (emitOptions?.resumePrefetch !== false) {
|
||||
prefetchService.resume();
|
||||
}
|
||||
};
|
||||
|
||||
const subtitleProcessingController = createSubtitleProcessingController({
|
||||
tokenizeSubtitle: async (subtitleText) => {
|
||||
options.onTokenize();
|
||||
return options.tokenize ? options.tokenize(subtitleText) : { text: subtitleText, tokens: [] };
|
||||
},
|
||||
// main.ts routes controller emits through emitSubtitlePayload with
|
||||
// resumePrefetch: false, so they never release the pause on their own.
|
||||
emitSubtitle: (payload) => {
|
||||
currentSubtitleData = payload;
|
||||
calls.push(`emit:${payload.text}:tokens=${payload.tokens === null ? 'none' : 'yes'}`);
|
||||
},
|
||||
onProcessingSettled: () => {
|
||||
prefetchService.resume();
|
||||
},
|
||||
...(options.cacheLimit === undefined ? {} : { cacheLimit: options.cacheLimit }),
|
||||
});
|
||||
|
||||
const runtime = createAutoplaySubtitlePrimingRuntime({
|
||||
getCurrentMediaPath: () => mediaPath,
|
||||
getMpvClient: () => ({
|
||||
connected: true,
|
||||
currentVideoPath: mediaPath,
|
||||
requestProperty: async (name) => (name === 'sub-text' ? text : null),
|
||||
}),
|
||||
setCurrentSubText: (value) => {
|
||||
currentSubText = value;
|
||||
},
|
||||
getCurrentSubText: () => currentSubText,
|
||||
getCurrentSubtitleData: () => currentSubtitleData,
|
||||
getActiveParsedSubtitleCues: () => [],
|
||||
setActiveParsedSubtitleMediaPath: () => {},
|
||||
subtitleProcessingController,
|
||||
emitSubtitlePayload,
|
||||
getSubtitlePrefetchService: () => prefetchService,
|
||||
getLastObservedTimePos: () => 12,
|
||||
getVisibleOverlayVisible: () => true,
|
||||
emitSecondarySubtitle: () => {},
|
||||
initSubtitlePrefetch: async () => {},
|
||||
refreshSubtitlePrefetchFromActiveTrack: async () => {},
|
||||
logDebug: () => {},
|
||||
});
|
||||
|
||||
return { runtime, subtitleProcessingController, mediaPath };
|
||||
}
|
||||
|
||||
test('primeCurrentSubtitleForAutoplay re-tokenizes text whose cached annotation was invalidated', async () => {
|
||||
const calls: string[] = [];
|
||||
let tokenizations = 0;
|
||||
const text = '起動字幕';
|
||||
const { runtime, subtitleProcessingController, mediaPath } =
|
||||
createPrimingRuntimeWithRealController({
|
||||
text,
|
||||
calls,
|
||||
onTokenize: () => {
|
||||
tokenizations += 1;
|
||||
},
|
||||
});
|
||||
|
||||
// The line was already tokenized and cached during normal playback.
|
||||
subtitleProcessingController.onSubtitleChange(text);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
const tokenizationsBeforeInvalidation = tokenizations;
|
||||
|
||||
// Mining a card drops every cached tokenization.
|
||||
subtitleProcessingController.invalidateTokenizationCache();
|
||||
calls.length = 0;
|
||||
|
||||
await runtime.primeCurrentSubtitleForAutoplay(mediaPath);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
// The cache miss must schedule fresh work, or the line stays unannotated for
|
||||
// as long as it is on screen.
|
||||
assert.equal(
|
||||
tokenizations,
|
||||
tokenizationsBeforeInvalidation + 1,
|
||||
'expected the invalidated subtitle to be tokenized again',
|
||||
);
|
||||
assert.ok(
|
||||
calls.includes(`emit:${text}:tokens=yes`),
|
||||
`expected an annotated emit, saw ${JSON.stringify(calls)}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('primeCurrentSubtitleForAutoplay releases the prefetch pause when nothing is scheduled', async () => {
|
||||
const calls: string[] = [];
|
||||
const text = '起動字幕';
|
||||
const { runtime, subtitleProcessingController, mediaPath } =
|
||||
createPrimingRuntimeWithRealController({
|
||||
text,
|
||||
calls,
|
||||
onTokenize: () => {},
|
||||
cacheLimit: 1,
|
||||
});
|
||||
|
||||
// Emitted at the current cache generation, then evicted from the one-entry
|
||||
// cache: priming misses the cache but the controller has nothing to redo, so
|
||||
// no emit is coming and the pause must be released here.
|
||||
subtitleProcessingController.onSubtitleChange(text);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
subtitleProcessingController.preCacheTokenization('別の字幕', {
|
||||
text: '別の字幕',
|
||||
tokens: [],
|
||||
});
|
||||
calls.length = 0;
|
||||
|
||||
await runtime.primeCurrentSubtitleForAutoplay(mediaPath);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
assert.deepEqual(calls, ['prefetch:pause', `emit-raw:${text}`, 'prefetch:resume']);
|
||||
});
|
||||
|
||||
test('primeCurrentSubtitleForAutoplay releases the prefetch pause when tokenization emits nothing', async () => {
|
||||
const calls: string[] = [];
|
||||
const text = '起動字幕';
|
||||
const { runtime, subtitleProcessingController, mediaPath } =
|
||||
createPrimingRuntimeWithRealController({
|
||||
text,
|
||||
calls,
|
||||
onTokenize: () => {},
|
||||
// Transient tokenizer failure: the controller falls back to plain text it
|
||||
// has already shown, so it suppresses the emit entirely.
|
||||
tokenize: () => null,
|
||||
});
|
||||
|
||||
subtitleProcessingController.onSubtitleChange(text);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
subtitleProcessingController.invalidateTokenizationCache();
|
||||
calls.length = 0;
|
||||
|
||||
await runtime.primeCurrentSubtitleForAutoplay(mediaPath);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
assert.ok(
|
||||
!calls.some((call) => call.startsWith('emit:')),
|
||||
`expected no controller emit, saw ${JSON.stringify(calls)}`,
|
||||
);
|
||||
assert.equal(
|
||||
calls.filter((call) => call === 'prefetch:resume').length,
|
||||
1,
|
||||
`expected the prefetch pause to be released, saw ${JSON.stringify(calls)}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('prefetch stays paused until tokenization of an uncached line completes', async () => {
|
||||
const calls: string[] = [];
|
||||
const text = '起動字幕';
|
||||
let finishTokenization = (): void => {};
|
||||
const tokenizationGate = new Promise<void>((resolve) => {
|
||||
finishTokenization = resolve;
|
||||
});
|
||||
const { runtime, mediaPath } = createPrimingRuntimeWithRealController({
|
||||
text,
|
||||
calls,
|
||||
onTokenize: () => {},
|
||||
tokenize: async (subtitleText) => {
|
||||
await tokenizationGate;
|
||||
return { text: subtitleText, tokens: [] };
|
||||
},
|
||||
});
|
||||
|
||||
// Driven through the priming path, which is what takes the pause out.
|
||||
await runtime.primeCurrentSubtitleForAutoplay(mediaPath);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
// Neither the priming emit nor the controller's provisional plain emit may
|
||||
// release the pause: the expensive scan is still ahead of them and would
|
||||
// compete with prefetching for the parser.
|
||||
// One plain payload, not two: priming paints it and tells the controller, so
|
||||
// the controller goes straight for the tokenized one. And it does not resume
|
||||
// prefetch, because the expensive scan is still ahead of it.
|
||||
assert.deepEqual(calls, ['prefetch:pause', `emit-raw:${text}`]);
|
||||
|
||||
finishTokenization();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
assert.deepEqual(calls, [
|
||||
'prefetch:pause',
|
||||
`emit-raw:${text}`,
|
||||
`emit:${text}:tokens=yes`,
|
||||
'prefetch:resume',
|
||||
]);
|
||||
});
|
||||
@@ -17,7 +17,7 @@ type AutoplaySubtitlePrimingMpvClient = {
|
||||
|
||||
type AutoplaySubtitlePrimingPrefetchService = {
|
||||
pause: () => void;
|
||||
onSeek: (timePos: number) => void;
|
||||
resume: () => void;
|
||||
};
|
||||
|
||||
export interface AutoplaySubtitlePrimingRuntimeDeps {
|
||||
@@ -30,10 +30,12 @@ export interface AutoplaySubtitlePrimingRuntimeDeps {
|
||||
setActiveParsedSubtitleMediaPath: (mediaPath: string | null) => void;
|
||||
subtitleProcessingController: {
|
||||
consumeCachedSubtitle: (text: string) => SubtitleData | null;
|
||||
onSubtitleChange: (text: string) => void;
|
||||
refreshCurrentSubtitle: (text: string) => void;
|
||||
// Both report whether processing is pending; see pausePrefetchUntilProcessed.
|
||||
onSubtitleChange: (text: string) => boolean;
|
||||
refreshCurrentSubtitle: (text: string) => boolean;
|
||||
notePlainSubtitleEmitted: (text: string) => void;
|
||||
};
|
||||
emitSubtitlePayload: (payload: SubtitleData) => void;
|
||||
emitSubtitlePayload: (payload: SubtitleData, options?: { resumePrefetch?: boolean }) => void;
|
||||
getSubtitlePrefetchService: () => AutoplaySubtitlePrimingPrefetchService | null;
|
||||
getLastObservedTimePos: () => number;
|
||||
getVisibleOverlayVisible: () => boolean;
|
||||
@@ -64,6 +66,19 @@ export function setMpvCurrentSecondarySubText(
|
||||
export function createAutoplaySubtitlePrimingRuntime(deps: AutoplaySubtitlePrimingRuntimeDeps) {
|
||||
const { subtitleProcessingController, emitSubtitlePayload } = deps;
|
||||
|
||||
// Prefetching is paused so the on-screen line gets the parser to itself; the
|
||||
// resume rides on the controller settling (see onProcessingSettled), not on
|
||||
// an emit, which a suppressed duplicate or a failed tokenization never sends.
|
||||
// When the controller reports it has nothing scheduled, no settle is coming
|
||||
// either, so release the pause here or prefetching idles indefinitely.
|
||||
function pausePrefetchUntilProcessed(scheduleTokenization: () => boolean): void {
|
||||
const prefetch = deps.getSubtitlePrefetchService();
|
||||
prefetch?.pause();
|
||||
if (!scheduleTokenization()) {
|
||||
prefetch?.resume();
|
||||
}
|
||||
}
|
||||
|
||||
let subtitlePrefetchRefreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let autoplaySubtitlePrimedMediaPath: string | null = null;
|
||||
let visibleOverlaySubtitleRefreshAfterFirstPaintTimer: ReturnType<typeof setTimeout> | null =
|
||||
@@ -104,12 +119,25 @@ export function createAutoplaySubtitlePrimingRuntime(deps: AutoplaySubtitlePrimi
|
||||
const cachedPayload = subtitleProcessingController.consumeCachedSubtitle(text);
|
||||
if (cachedPayload) {
|
||||
subtitleProcessingController.onSubtitleChange(text);
|
||||
// This emit resumes prefetching, so no pause is left outstanding.
|
||||
emitSubtitlePayload(cachedPayload);
|
||||
return true;
|
||||
}
|
||||
|
||||
emitSubtitlePayload({ text, tokens: null });
|
||||
subtitleProcessingController.onSubtitleChange(text);
|
||||
// Provisional raw emit: keep prefetch paused until the processing
|
||||
// controller is done with this line, and tell it this line has already been
|
||||
// painted plain so it does not broadcast the same payload again.
|
||||
emitSubtitlePayload({ text, tokens: null }, { resumePrefetch: false });
|
||||
subtitleProcessingController.notePlainSubtitleEmitted(text);
|
||||
// refreshCurrentSubtitle, not onSubtitleChange: the cache miss above can be
|
||||
// an invalidation (mining a card) on text the controller still holds, and
|
||||
// onSubtitleChange treats unchanged text as nothing to do, which would
|
||||
// leave this line permanently unannotated. refreshCurrentSubtitle also
|
||||
// re-tokenizes for a new cache generation.
|
||||
if (!subtitleProcessingController.refreshCurrentSubtitle(text)) {
|
||||
// Nothing scheduled, so no settle is coming to release the pause.
|
||||
deps.getSubtitlePrefetchService()?.resume();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -153,14 +181,12 @@ export function createAutoplaySubtitlePrimingRuntime(deps: AutoplaySubtitlePrimi
|
||||
getCurrentSubtitleData: () => deps.getCurrentSubtitleData(),
|
||||
consumeCachedSubtitle: (text) => subtitleProcessingController.consumeCachedSubtitle(text),
|
||||
onSubtitleChange: (text) => {
|
||||
deps.getSubtitlePrefetchService()?.pause();
|
||||
deps.getSubtitlePrefetchService()?.onSeek(deps.getLastObservedTimePos());
|
||||
subtitleProcessingController.onSubtitleChange(text);
|
||||
pausePrefetchUntilProcessed(() => subtitleProcessingController.onSubtitleChange(text));
|
||||
},
|
||||
refreshCurrentSubtitle: (text) => {
|
||||
deps.getSubtitlePrefetchService()?.pause();
|
||||
deps.getSubtitlePrefetchService()?.onSeek(deps.getLastObservedTimePos());
|
||||
subtitleProcessingController.refreshCurrentSubtitle(text);
|
||||
pausePrefetchUntilProcessed(() =>
|
||||
subtitleProcessingController.refreshCurrentSubtitle(text),
|
||||
);
|
||||
},
|
||||
deferUncachedRefresh: true,
|
||||
emitSubtitle: (payload) => emitSubtitlePayload(payload),
|
||||
@@ -204,9 +230,7 @@ export function createAutoplaySubtitlePrimingRuntime(deps: AutoplaySubtitlePrimi
|
||||
if (!text.trim()) {
|
||||
return;
|
||||
}
|
||||
deps.getSubtitlePrefetchService()?.pause();
|
||||
deps.getSubtitlePrefetchService()?.onSeek(deps.getLastObservedTimePos());
|
||||
subtitleProcessingController.refreshCurrentSubtitle(text);
|
||||
pausePrefetchUntilProcessed(() => subtitleProcessingController.refreshCurrentSubtitle(text));
|
||||
}, VISIBLE_OVERLAY_SUBTITLE_REFRESH_AFTER_FIRST_PAINT_DELAY_MS);
|
||||
visibleOverlaySubtitleRefreshAfterFirstPaintTimer.unref?.();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { OverlayHostedModal } from '../../shared/ipc/contracts';
|
||||
import { IPC_CHANNELS } from '../../shared/ipc/contracts';
|
||||
import { openOverlayHostedModal, retryOverlayModalOpen } from './overlay-hosted-modal-open';
|
||||
|
||||
const CHANGELOG_MODAL: OverlayHostedModal = 'changelog';
|
||||
const CHANGELOG_OPEN_TIMEOUT_MS = 1500;
|
||||
|
||||
export async function openChangelogModal(deps: {
|
||||
ensureOverlayStartupPrereqs: () => void;
|
||||
ensureOverlayWindowsReadyForVisibilityActions: () => void;
|
||||
sendToActiveOverlayWindow: (
|
||||
channel: string,
|
||||
payload?: unknown,
|
||||
runtimeOptions?: {
|
||||
restoreOnModalClose?: OverlayHostedModal;
|
||||
preferModalWindow?: boolean;
|
||||
},
|
||||
) => boolean;
|
||||
waitForModalOpen: (modal: OverlayHostedModal, timeoutMs: number) => Promise<boolean>;
|
||||
logWarn: (message: string) => void;
|
||||
}): Promise<boolean> {
|
||||
return await retryOverlayModalOpen(
|
||||
{
|
||||
waitForModalOpen: deps.waitForModalOpen,
|
||||
logWarn: deps.logWarn,
|
||||
},
|
||||
{
|
||||
modal: CHANGELOG_MODAL,
|
||||
timeoutMs: CHANGELOG_OPEN_TIMEOUT_MS,
|
||||
retryWarning:
|
||||
'Changelog modal did not acknowledge modal open on first attempt; retrying dedicated modal window.',
|
||||
sendOpen: () =>
|
||||
openOverlayHostedModal(
|
||||
{
|
||||
ensureOverlayStartupPrereqs: deps.ensureOverlayStartupPrereqs,
|
||||
ensureOverlayWindowsReadyForVisibilityActions:
|
||||
deps.ensureOverlayWindowsReadyForVisibilityActions,
|
||||
sendToActiveOverlayWindow: deps.sendToActiveOverlayWindow,
|
||||
},
|
||||
{
|
||||
channel: IPC_CHANNELS.event.changelogOpen,
|
||||
modal: CHANGELOG_MODAL,
|
||||
preferModalWindow: true,
|
||||
},
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { readBundledChangelog, resolveBundledChangelogPath } from './bundled-changelog';
|
||||
|
||||
test('bundled changelog path prefers the packaged resources copy', () => {
|
||||
const resolved = resolveBundledChangelogPath({
|
||||
resourcesPath: '/res',
|
||||
appPath: '/app',
|
||||
dirname: '/app/dist/main',
|
||||
joinPath: (...parts) => parts.join('/'),
|
||||
fileExists: (candidate) => candidate === '/res/CHANGELOG.md',
|
||||
});
|
||||
|
||||
assert.equal(resolved, '/res/CHANGELOG.md');
|
||||
});
|
||||
|
||||
test('bundled changelog path falls back to the repo root during development', () => {
|
||||
const resolved = resolveBundledChangelogPath({
|
||||
resourcesPath: '/res',
|
||||
appPath: '/app',
|
||||
dirname: '/repo/dist/main',
|
||||
joinPath: (...parts) => parts.join('/'),
|
||||
fileExists: (candidate) => candidate === '/repo/dist/main/../../CHANGELOG.md',
|
||||
});
|
||||
|
||||
assert.equal(resolved, '/repo/dist/main/../../CHANGELOG.md');
|
||||
});
|
||||
|
||||
test('bundled changelog returns null when no copy is installed', () => {
|
||||
const result = readBundledChangelog({
|
||||
resolvePath: () => null,
|
||||
readFile: () => {
|
||||
throw new Error('should not read');
|
||||
},
|
||||
logWarn: () => {},
|
||||
});
|
||||
|
||||
assert.equal(result, null);
|
||||
});
|
||||
|
||||
test('bundled changelog logs and returns null when the file cannot be read', () => {
|
||||
const warnings: string[] = [];
|
||||
const result = readBundledChangelog({
|
||||
resolvePath: () => '/res/CHANGELOG.md',
|
||||
readFile: () => {
|
||||
throw new Error('EACCES');
|
||||
},
|
||||
logWarn: (message) => warnings.push(message),
|
||||
});
|
||||
|
||||
assert.equal(result, null);
|
||||
assert.equal(warnings.length, 1);
|
||||
assert.match(warnings[0] ?? '', /EACCES/);
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
export function resolveBundledChangelogPath(deps: {
|
||||
resourcesPath: string;
|
||||
appPath: string;
|
||||
dirname: string;
|
||||
joinPath: (...parts: string[]) => string;
|
||||
fileExists: (path: string) => boolean;
|
||||
}): string | null {
|
||||
const candidates = [
|
||||
deps.joinPath(deps.resourcesPath, 'CHANGELOG.md'),
|
||||
deps.joinPath(deps.appPath, 'CHANGELOG.md'),
|
||||
deps.joinPath(deps.dirname, '..', 'CHANGELOG.md'),
|
||||
deps.joinPath(deps.dirname, '..', '..', 'CHANGELOG.md'),
|
||||
];
|
||||
|
||||
return candidates.find((candidate) => deps.fileExists(candidate)) ?? null;
|
||||
}
|
||||
|
||||
export function readBundledChangelog(deps: {
|
||||
resolvePath: () => string | null;
|
||||
readFile: (path: string) => string;
|
||||
logWarn: (message: string) => void;
|
||||
}): string | null {
|
||||
const changelogPath = deps.resolvePath();
|
||||
if (!changelogPath) return null;
|
||||
try {
|
||||
return deps.readFile(changelogPath);
|
||||
} catch (error) {
|
||||
deps.logWarn(
|
||||
`Failed to read bundled changelog at ${changelogPath}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
CHANGELOG_REQUEST_TIMEOUT_MS,
|
||||
createChangelogRuntime,
|
||||
withRequestTimeout,
|
||||
} from './changelog-runtime';
|
||||
import type { FetchLike, FetchResponseLike } from '../update/release-assets';
|
||||
import { createCurlFetch } from '../update/fetch-adapter';
|
||||
|
||||
function okResponse(body: string): FetchResponseLike {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => JSON.parse(body),
|
||||
text: async () => body,
|
||||
arrayBuffer: async () => new ArrayBuffer(0),
|
||||
};
|
||||
}
|
||||
|
||||
test('request timeout wrapper attaches an abort signal to every request', async () => {
|
||||
const seen: Array<{ url: string; init?: Record<string, unknown> }> = [];
|
||||
const wrapped = withRequestTimeout(async (url, init) => {
|
||||
seen.push({ url, init });
|
||||
return okResponse('body');
|
||||
}, 1_234);
|
||||
|
||||
await wrapped('https://example.test/a');
|
||||
await wrapped('https://example.test/b', { headers: { 'User-Agent': 'SubMiner' } });
|
||||
|
||||
assert.equal(seen.length, 2);
|
||||
for (const request of seen) {
|
||||
assert.ok(request.init?.signal instanceof AbortSignal, 'each request carries a signal');
|
||||
assert.equal((request.init?.signal as AbortSignal).aborted, false);
|
||||
}
|
||||
// Existing init is preserved rather than replaced.
|
||||
assert.deepEqual(seen[1]?.init?.headers, { 'User-Agent': 'SubMiner' });
|
||||
});
|
||||
|
||||
test('request timeout wrapper aborts a request that never settles', async () => {
|
||||
let observed: AbortSignal | undefined;
|
||||
const wrapped = withRequestTimeout((_url, init) => {
|
||||
observed = init?.signal as AbortSignal;
|
||||
return new Promise<FetchResponseLike>(() => {
|
||||
// Never resolves, standing in for a stalled connection.
|
||||
});
|
||||
}, 10);
|
||||
|
||||
void wrapped('https://example.test/stalled');
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
|
||||
assert.equal(observed?.aborted, true);
|
||||
});
|
||||
|
||||
test('changelog runtime times out both requests instead of hanging the modal', async () => {
|
||||
const signals: AbortSignal[] = [];
|
||||
// Stays pending until the deadline fires, standing in for a stalled server.
|
||||
const stalling: FetchLike = (_url, init) => {
|
||||
const signal = init?.signal as AbortSignal;
|
||||
signals.push(signal);
|
||||
return new Promise((_resolve, reject) => {
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
||||
});
|
||||
};
|
||||
|
||||
const runtime = createChangelogRuntime({
|
||||
getInstalledVersion: () => '0.19.2',
|
||||
getUpdateChannel: () => 'stable',
|
||||
resourcesPath: '/res',
|
||||
appPath: '/app',
|
||||
dirname: '/app/dist/main',
|
||||
joinPath: (...parts) => parts.join('/'),
|
||||
fileExists: () => false,
|
||||
readFile: () => '',
|
||||
logWarn: () => {},
|
||||
createFetch: () => withRequestTimeout(stalling, 10),
|
||||
});
|
||||
|
||||
const snapshot = await runtime.getChangelogSnapshot();
|
||||
|
||||
// Release lookup and changelog download both hit the deadline rather than hang.
|
||||
assert.equal(signals.length, 2);
|
||||
assert.ok(
|
||||
signals.every((signal) => signal.aborted),
|
||||
'every stalled request was aborted',
|
||||
);
|
||||
// No bundled copy is readable here, so the timeout surfaces as an error state
|
||||
// that does not claim a bundled changelog is on screen.
|
||||
assert.match(snapshot.error ?? '', /^Changelog unavailable: /);
|
||||
assert.match(snapshot.error ?? '', /timed out|timeout|abort/i);
|
||||
assert.deepEqual(snapshot.entries, []);
|
||||
});
|
||||
|
||||
test('changelog timeout reaches the curl transport, not just global fetch', async () => {
|
||||
// The POSIX transport is curl, whose own --max-time is 60s; the changelog
|
||||
// deadline is shorter, so the signal has to actually terminate the process.
|
||||
let killed: string | undefined;
|
||||
const curlFetch = createCurlFetch({
|
||||
execFile: ((
|
||||
_file: string,
|
||||
_args: readonly string[],
|
||||
_options: unknown,
|
||||
_callback: unknown,
|
||||
) => ({
|
||||
kill: (signal?: string) => {
|
||||
killed = signal;
|
||||
return true;
|
||||
},
|
||||
})) as never,
|
||||
});
|
||||
|
||||
const wrapped = withRequestTimeout(curlFetch, 10);
|
||||
await assert.rejects(wrapped('https://example.test/stalled'));
|
||||
|
||||
assert.equal(killed, 'SIGKILL', 'the stalled curl process is killed at the changelog deadline');
|
||||
});
|
||||
|
||||
test('changelog request timeout is finite', () => {
|
||||
assert.ok(Number.isFinite(CHANGELOG_REQUEST_TIMEOUT_MS));
|
||||
assert.ok(CHANGELOG_REQUEST_TIMEOUT_MS > 0);
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { ChangelogSnapshot } from '../../../types/changelog';
|
||||
import type { UpdateChannel } from '../../../types/config';
|
||||
import { createCurlFetch, createGlobalFetch } from '../update/fetch-adapter';
|
||||
import { fetchLatestStableRelease, type FetchLike } from '../update/release-assets';
|
||||
import { readBundledChangelog, resolveBundledChangelogPath } from './bundled-changelog';
|
||||
import { createChangelogSource } from './changelog-source';
|
||||
|
||||
export interface ChangelogRuntimeDeps {
|
||||
getInstalledVersion: () => string;
|
||||
getUpdateChannel: () => UpdateChannel;
|
||||
resourcesPath: string;
|
||||
appPath: string;
|
||||
dirname: string;
|
||||
joinPath: (...parts: string[]) => string;
|
||||
fileExists: (path: string) => boolean;
|
||||
readFile: (path: string) => string;
|
||||
logWarn: (message: string) => void;
|
||||
/** Injected in tests; production picks curl on POSIX and global fetch on Windows. */
|
||||
createFetch?: () => FetchLike;
|
||||
}
|
||||
|
||||
/**
|
||||
* curl enforces its own `--max-time`, but the global-fetch transport has no
|
||||
* deadline: without this a stalled connection leaves the modal on "Loading
|
||||
* changelog..." with no way back except closing it.
|
||||
*/
|
||||
export const CHANGELOG_REQUEST_TIMEOUT_MS = 30_000;
|
||||
|
||||
export function withRequestTimeout(fetchImpl: FetchLike, timeoutMs: number): FetchLike {
|
||||
return (url, init) => {
|
||||
if (typeof AbortSignal?.timeout !== 'function') return fetchImpl(url, init);
|
||||
return fetchImpl(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
|
||||
};
|
||||
}
|
||||
|
||||
export function createChangelogRuntime(deps: ChangelogRuntimeDeps): {
|
||||
getChangelogSnapshot: (options?: { refresh?: boolean }) => Promise<ChangelogSnapshot>;
|
||||
} {
|
||||
// curl matches the updater's transport choice: Electron's global fetch is
|
||||
// unreliable for GitHub on some Linux builds.
|
||||
const fetchImpl = withRequestTimeout(
|
||||
deps.createFetch?.() ??
|
||||
(process.platform === 'win32' ? createGlobalFetch() : createCurlFetch()),
|
||||
CHANGELOG_REQUEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
const source = createChangelogSource({
|
||||
fetchLatestReleaseTag: async () => {
|
||||
const release = await fetchLatestStableRelease({
|
||||
fetch: fetchImpl,
|
||||
channel: deps.getUpdateChannel(),
|
||||
});
|
||||
return release?.tag_name ?? null;
|
||||
},
|
||||
fetchText: async (url) => {
|
||||
const response = await fetchImpl(url, {
|
||||
headers: { 'User-Agent': 'SubMiner changelog' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Changelog request failed with ${response.status}`);
|
||||
}
|
||||
return await response.text();
|
||||
},
|
||||
readBundledChangelog: () =>
|
||||
readBundledChangelog({
|
||||
resolvePath: () =>
|
||||
resolveBundledChangelogPath({
|
||||
resourcesPath: deps.resourcesPath,
|
||||
appPath: deps.appPath,
|
||||
dirname: deps.dirname,
|
||||
joinPath: deps.joinPath,
|
||||
fileExists: deps.fileExists,
|
||||
}),
|
||||
readFile: deps.readFile,
|
||||
logWarn: deps.logWarn,
|
||||
}),
|
||||
getInstalledVersion: deps.getInstalledVersion,
|
||||
now: () => Date.now(),
|
||||
logWarn: deps.logWarn,
|
||||
});
|
||||
|
||||
return {
|
||||
getChangelogSnapshot: (options?: { refresh?: boolean }) => source.getSnapshot(options),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { ChangelogSnapshot, ChangelogSourceKind } from '../../../types/changelog';
|
||||
import { parseChangelog } from '../../../core/utils/changelog-parse';
|
||||
import { compareSemverLike } from '../update/release-assets';
|
||||
|
||||
export function buildChangelogSnapshot(
|
||||
markdown: string,
|
||||
options: {
|
||||
installedVersion: string;
|
||||
source: ChangelogSourceKind;
|
||||
releaseTag?: string;
|
||||
warning?: string;
|
||||
},
|
||||
): ChangelogSnapshot {
|
||||
const entries = parseChangelog(markdown);
|
||||
const latest = entries.reduce<string | null>(
|
||||
(best, entry) =>
|
||||
best === null || compareSemverLike(entry.version, best) > 0 ? entry.version : best,
|
||||
null,
|
||||
);
|
||||
const latestEntry = entries.find((entry) => entry.version === latest) ?? entries[0] ?? null;
|
||||
|
||||
return {
|
||||
entries,
|
||||
installedVersion: options.installedVersion,
|
||||
latestVersion: latest,
|
||||
expandedGroupKey: latestEntry?.groupKey ?? null,
|
||||
source: options.source,
|
||||
...(options.releaseTag ? { releaseTag: options.releaseTag } : {}),
|
||||
...(options.warning ? { warning: options.warning } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildEmptyChangelogSnapshot(options: {
|
||||
installedVersion: string;
|
||||
error: string;
|
||||
}): ChangelogSnapshot {
|
||||
return {
|
||||
entries: [],
|
||||
installedVersion: options.installedVersion,
|
||||
latestVersion: null,
|
||||
expandedGroupKey: null,
|
||||
source: 'bundled',
|
||||
error: options.error,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { buildRawChangelogUrl, createChangelogSource } from './changelog-source';
|
||||
import { buildChangelogSnapshot } from './changelog-snapshot';
|
||||
|
||||
const REMOTE = `# Changelog
|
||||
|
||||
## v0.20.0 (2026-09-01)
|
||||
|
||||
### Added
|
||||
- Remote only entry.
|
||||
|
||||
## v0.19.2 (2026-08-04)
|
||||
|
||||
### Fixed
|
||||
- Installed entry.
|
||||
`;
|
||||
|
||||
const BUNDLED = `# Changelog
|
||||
|
||||
## v0.19.2 (2026-08-04)
|
||||
|
||||
### Fixed
|
||||
- Installed entry.
|
||||
`;
|
||||
|
||||
function createDeps(overrides: Partial<Parameters<typeof createChangelogSource>[0]> = {}) {
|
||||
return {
|
||||
fetchLatestReleaseTag: async () => 'v0.20.0',
|
||||
fetchText: async () => REMOTE,
|
||||
readBundledChangelog: () => BUNDLED,
|
||||
getInstalledVersion: () => '0.19.2',
|
||||
now: () => 1_000,
|
||||
logWarn: () => {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test('changelog source reads the changelog at the latest release tag', async () => {
|
||||
const urls: string[] = [];
|
||||
const source = createChangelogSource(
|
||||
createDeps({
|
||||
fetchText: async (url: string) => {
|
||||
urls.push(url);
|
||||
return REMOTE;
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const snapshot = await source.getSnapshot();
|
||||
|
||||
assert.deepEqual(urls, [
|
||||
'https://raw.githubusercontent.com/ksyasuda/SubMiner/v0.20.0/CHANGELOG.md',
|
||||
]);
|
||||
assert.equal(snapshot.source, 'remote');
|
||||
assert.equal(snapshot.releaseTag, 'v0.20.0');
|
||||
assert.equal(snapshot.latestVersion, '0.20.0');
|
||||
assert.equal(snapshot.installedVersion, '0.19.2');
|
||||
assert.equal(snapshot.expandedGroupKey, '0.20');
|
||||
});
|
||||
|
||||
test('changelog source falls back to the default branch when no release tag resolves', async () => {
|
||||
const urls: string[] = [];
|
||||
const source = createChangelogSource(
|
||||
createDeps({
|
||||
fetchLatestReleaseTag: async () => null,
|
||||
fetchText: async (url: string) => {
|
||||
urls.push(url);
|
||||
return REMOTE;
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const snapshot = await source.getSnapshot();
|
||||
|
||||
assert.deepEqual(urls, ['https://raw.githubusercontent.com/ksyasuda/SubMiner/main/CHANGELOG.md']);
|
||||
assert.equal(snapshot.source, 'remote');
|
||||
assert.equal(snapshot.releaseTag, undefined);
|
||||
});
|
||||
|
||||
test('changelog source falls back to the bundled changelog when the download fails', async () => {
|
||||
const warnings: string[] = [];
|
||||
const source = createChangelogSource(
|
||||
createDeps({
|
||||
fetchText: async () => {
|
||||
throw new Error('offline');
|
||||
},
|
||||
logWarn: (message: string) => warnings.push(message),
|
||||
}),
|
||||
);
|
||||
|
||||
const snapshot = await source.getSnapshot();
|
||||
|
||||
assert.equal(snapshot.source, 'bundled');
|
||||
assert.match(snapshot.warning ?? '', /offline/);
|
||||
assert.equal(snapshot.latestVersion, '0.19.2');
|
||||
assert.equal(warnings.length, 1);
|
||||
});
|
||||
|
||||
test('changelog source reports an error when no changelog can be loaded', async () => {
|
||||
const source = createChangelogSource(
|
||||
createDeps({
|
||||
fetchText: async () => {
|
||||
throw new Error('offline');
|
||||
},
|
||||
readBundledChangelog: () => null,
|
||||
}),
|
||||
);
|
||||
|
||||
const snapshot = await source.getSnapshot();
|
||||
|
||||
assert.deepEqual(snapshot.entries, []);
|
||||
assert.match(snapshot.error ?? '', /offline/);
|
||||
// Nothing is rendered, so the message must not promise a bundled changelog.
|
||||
assert.match(snapshot.error ?? '', /^Changelog unavailable: /);
|
||||
assert.doesNotMatch(snapshot.error ?? '', /Showing the bundled changelog/);
|
||||
assert.equal(snapshot.installedVersion, '0.19.2');
|
||||
});
|
||||
|
||||
test('changelog source caches remote results and refreshes on demand', async () => {
|
||||
let fetches = 0;
|
||||
let clock = 0;
|
||||
const source = createChangelogSource(
|
||||
createDeps({
|
||||
now: () => clock,
|
||||
fetchText: async () => {
|
||||
fetches += 1;
|
||||
return REMOTE;
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await source.getSnapshot();
|
||||
await source.getSnapshot();
|
||||
assert.equal(fetches, 1);
|
||||
|
||||
await source.getSnapshot({ refresh: true });
|
||||
assert.equal(fetches, 2);
|
||||
|
||||
clock = 11 * 60 * 1000;
|
||||
await source.getSnapshot();
|
||||
assert.equal(fetches, 3);
|
||||
});
|
||||
|
||||
test('changelog source retries the network after a bundled fallback', async () => {
|
||||
let fetches = 0;
|
||||
const source = createChangelogSource(
|
||||
createDeps({
|
||||
fetchText: async () => {
|
||||
fetches += 1;
|
||||
throw new Error('offline');
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await source.getSnapshot();
|
||||
await source.getSnapshot();
|
||||
|
||||
assert.equal(fetches, 2);
|
||||
});
|
||||
|
||||
test('changelog source treats an empty remote changelog as a failure', async () => {
|
||||
const source = createChangelogSource(createDeps({ fetchText: async () => ' ' }));
|
||||
|
||||
const snapshot = await source.getSnapshot();
|
||||
|
||||
assert.equal(snapshot.source, 'bundled');
|
||||
});
|
||||
|
||||
test('changelog source falls back when the remote body parses to no releases', () => {
|
||||
const warnings: string[] = [];
|
||||
const source = createChangelogSource(
|
||||
createDeps({
|
||||
// A 200 that is not a changelog, e.g. a redirect landing page.
|
||||
fetchText: async () => '<!doctype html><html><body>Moved</body></html>',
|
||||
logWarn: (message: string) => warnings.push(message),
|
||||
}),
|
||||
);
|
||||
|
||||
return source.getSnapshot().then((snapshot) => {
|
||||
assert.equal(snapshot.source, 'bundled');
|
||||
assert.equal(snapshot.entries.length, 1);
|
||||
assert.match(snapshot.warning ?? '', /no releases/);
|
||||
assert.equal(warnings.length, 1);
|
||||
});
|
||||
});
|
||||
|
||||
test('raw changelog urls encode the release ref', () => {
|
||||
assert.equal(
|
||||
buildRawChangelogUrl('v1.0.0', 'owner', 'repo'),
|
||||
'https://raw.githubusercontent.com/owner/repo/v1.0.0/CHANGELOG.md',
|
||||
);
|
||||
});
|
||||
|
||||
test('snapshot expansion uses the newest version even when file order is unsorted', () => {
|
||||
const snapshot = buildChangelogSnapshot(
|
||||
'## v0.18.0 (2026-01-01)\n\n### Fixed\n- Old.\n\n## v0.19.0 (2026-02-01)\n\n### Fixed\n- New.\n',
|
||||
{ installedVersion: '0.18.0', source: 'bundled' },
|
||||
);
|
||||
|
||||
assert.equal(snapshot.latestVersion, '0.19.0');
|
||||
assert.equal(snapshot.expandedGroupKey, '0.19');
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { ChangelogSnapshot } from '../../../types/changelog';
|
||||
import { buildChangelogSnapshot, buildEmptyChangelogSnapshot } from './changelog-snapshot';
|
||||
|
||||
const DEFAULT_OWNER = 'ksyasuda';
|
||||
const DEFAULT_REPO = 'SubMiner';
|
||||
const DEFAULT_CACHE_TTL_MS = 10 * 60 * 1000;
|
||||
|
||||
export interface ChangelogSourceDeps {
|
||||
/** Resolves the release the changelog should be read from, or null when unknown. */
|
||||
fetchLatestReleaseTag: () => Promise<string | null>;
|
||||
fetchText: (url: string) => Promise<string>;
|
||||
/** Reads the CHANGELOG.md shipped with the install; null when unavailable. */
|
||||
readBundledChangelog: () => string | null;
|
||||
getInstalledVersion: () => string;
|
||||
now: () => number;
|
||||
logWarn: (message: string) => void;
|
||||
owner?: string;
|
||||
repo?: string;
|
||||
cacheTtlMs?: number;
|
||||
}
|
||||
|
||||
export function buildRawChangelogUrl(ref: string, owner: string, repo: string): string {
|
||||
return `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(ref)}/CHANGELOG.md`;
|
||||
}
|
||||
|
||||
function summarize(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
export function createChangelogSource(deps: ChangelogSourceDeps): {
|
||||
getSnapshot: (options?: { refresh?: boolean }) => Promise<ChangelogSnapshot>;
|
||||
} {
|
||||
const owner = deps.owner ?? DEFAULT_OWNER;
|
||||
const repo = deps.repo ?? DEFAULT_REPO;
|
||||
const cacheTtlMs = deps.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
|
||||
|
||||
let cached: { snapshot: ChangelogSnapshot; fetchedAt: number } | null = null;
|
||||
let inFlight: Promise<ChangelogSnapshot> | null = null;
|
||||
|
||||
/** `reason` is the raw failure; each branch phrases it for what it can show. */
|
||||
function fallbackToBundled(reason: string): ChangelogSnapshot {
|
||||
const bundled = deps.readBundledChangelog();
|
||||
if (bundled === null) {
|
||||
// Nothing is on screen, so promising a bundled changelog would be a lie.
|
||||
return buildEmptyChangelogSnapshot({
|
||||
installedVersion: deps.getInstalledVersion(),
|
||||
error: `Changelog unavailable: ${reason}`,
|
||||
});
|
||||
}
|
||||
return buildChangelogSnapshot(bundled, {
|
||||
installedVersion: deps.getInstalledVersion(),
|
||||
source: 'bundled',
|
||||
warning: `Showing the bundled changelog: ${reason}`,
|
||||
});
|
||||
}
|
||||
|
||||
async function loadSnapshot(): Promise<ChangelogSnapshot> {
|
||||
let releaseTag: string | null = null;
|
||||
try {
|
||||
releaseTag = await deps.fetchLatestReleaseTag();
|
||||
} catch (error) {
|
||||
deps.logWarn(`Changelog release lookup failed: ${summarize(error)}`);
|
||||
}
|
||||
|
||||
// Without a release tag the default branch still gives the newest published
|
||||
// changelog, so try it before falling back to the bundled copy.
|
||||
const ref = releaseTag ?? 'main';
|
||||
try {
|
||||
const markdown = await deps.fetchText(buildRawChangelogUrl(ref, owner, repo));
|
||||
if (markdown.trim().length === 0) {
|
||||
throw new Error('Remote changelog was empty.');
|
||||
}
|
||||
const snapshot = buildChangelogSnapshot(markdown, {
|
||||
installedVersion: deps.getInstalledVersion(),
|
||||
source: 'remote',
|
||||
...(releaseTag ? { releaseTag } : {}),
|
||||
});
|
||||
// A 200 that isn't a changelog (a redirect landing page, a renamed repo)
|
||||
// parses to nothing; the bundled copy beats showing an empty modal.
|
||||
if (snapshot.entries.length === 0) {
|
||||
throw new Error('Remote changelog contained no releases.');
|
||||
}
|
||||
return snapshot;
|
||||
} catch (error) {
|
||||
const message = summarize(error);
|
||||
deps.logWarn(`Changelog download failed (${ref}): ${message}`);
|
||||
return fallbackToBundled(message);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
async getSnapshot(options?: { refresh?: boolean }): Promise<ChangelogSnapshot> {
|
||||
const refresh = options?.refresh === true;
|
||||
if (!refresh && cached && deps.now() - cached.fetchedAt < cacheTtlMs) {
|
||||
return cached.snapshot;
|
||||
}
|
||||
if (inFlight) return await inFlight;
|
||||
|
||||
inFlight = loadSnapshot()
|
||||
.then((snapshot) => {
|
||||
// Only a successful remote read is worth caching; a bundled fallback
|
||||
// should retry the network on the next open.
|
||||
if (snapshot.source === 'remote') {
|
||||
cached = { snapshot, fetchedAt: deps.now() };
|
||||
} else {
|
||||
cached = null;
|
||||
}
|
||||
return snapshot;
|
||||
})
|
||||
.finally(() => {
|
||||
inFlight = null;
|
||||
});
|
||||
|
||||
return await inFlight;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -53,3 +53,52 @@ test('character dictionary sync completion refreshes subtitle state when diction
|
||||
'log:[dictionary:auto-sync] refreshed current subtitle after sync (AniList 1, changed=yes, title=Frieren)',
|
||||
]);
|
||||
});
|
||||
|
||||
test('character dictionary sync completion drops cached dictionary reads before refreshing', () => {
|
||||
const calls: string[] = [];
|
||||
|
||||
handleCharacterDictionaryAutoSyncComplete(
|
||||
{
|
||||
mediaId: 1,
|
||||
mediaTitle: 'Frieren',
|
||||
changed: true,
|
||||
},
|
||||
{
|
||||
hasParserWindow: () => true,
|
||||
invalidateCharacterDictionaryLookups: () => calls.push('invalidate-dictionary-lookups'),
|
||||
clearParserCaches: () => calls.push('clear-parser'),
|
||||
invalidateTokenizationCache: () => calls.push('invalidate'),
|
||||
refreshSubtitlePrefetch: () => calls.push('prefetch'),
|
||||
refreshCurrentSubtitle: () => calls.push('refresh-subtitle'),
|
||||
logInfo: () => {},
|
||||
},
|
||||
);
|
||||
|
||||
// Must run before the refreshes, or they re-tokenize against the character
|
||||
// names and images from the previous dictionary build.
|
||||
assert.equal(calls[0], 'invalidate-dictionary-lookups');
|
||||
assert.ok(calls.indexOf('invalidate-dictionary-lookups') < calls.indexOf('refresh-subtitle'));
|
||||
});
|
||||
|
||||
test('character dictionary sync completion leaves cached dictionary reads alone when unchanged', () => {
|
||||
const calls: string[] = [];
|
||||
|
||||
handleCharacterDictionaryAutoSyncComplete(
|
||||
{
|
||||
mediaId: 1,
|
||||
mediaTitle: 'Frieren',
|
||||
changed: false,
|
||||
},
|
||||
{
|
||||
hasParserWindow: () => true,
|
||||
invalidateCharacterDictionaryLookups: () => calls.push('invalidate-dictionary-lookups'),
|
||||
clearParserCaches: () => calls.push('clear-parser'),
|
||||
invalidateTokenizationCache: () => calls.push('invalidate'),
|
||||
refreshSubtitlePrefetch: () => calls.push('prefetch'),
|
||||
refreshCurrentSubtitle: () => calls.push('refresh-subtitle'),
|
||||
logInfo: () => {},
|
||||
},
|
||||
);
|
||||
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
@@ -7,6 +7,12 @@ export function handleCharacterDictionaryAutoSyncComplete(
|
||||
deps: {
|
||||
hasParserWindow: () => boolean;
|
||||
clearParserCaches: () => void;
|
||||
/**
|
||||
* Drops cached reads of the generated dictionary (character images, and the
|
||||
* name candidates the scanner uses to skip lookups). Runs before the
|
||||
* refreshes below so they re-tokenize against the new dictionary content.
|
||||
*/
|
||||
invalidateCharacterDictionaryLookups?: () => void;
|
||||
invalidateTokenizationCache: () => void;
|
||||
refreshSubtitlePrefetch: () => void;
|
||||
refreshCurrentSubtitle: () => void;
|
||||
@@ -14,6 +20,7 @@ export function handleCharacterDictionaryAutoSyncComplete(
|
||||
},
|
||||
): void {
|
||||
if (completion.changed) {
|
||||
deps.invalidateCharacterDictionaryLookups?.();
|
||||
if (deps.hasParserWindow()) {
|
||||
deps.clearParserCaches();
|
||||
}
|
||||
|
||||
@@ -225,24 +225,35 @@ export function composeMpvRuntimeHandlers<
|
||||
}
|
||||
return tokenizationWarmupInFlight;
|
||||
};
|
||||
// Built once and reused for every tokenization: per-call rebuilds create
|
||||
// fresh closures, which defeats identity-keyed caches downstream (the JLPT
|
||||
// lookup cache keys on the getJlptLevel function, and the mecab availability
|
||||
// WeakSet keys on the runtime deps instance).
|
||||
let cachedTokenizerRuntimeDeps: TTokenizerRuntimeDeps | null = null;
|
||||
const getTokenizerRuntimeDeps = (): TTokenizerRuntimeDeps => {
|
||||
if (cachedTokenizerRuntimeDeps) {
|
||||
return cachedTokenizerRuntimeDeps;
|
||||
}
|
||||
const tokenizerMainDeps = buildTokenizerDepsHandler();
|
||||
const baseOnTokenizationReady = tokenizerMainDeps.onTokenizationReady;
|
||||
tokenizerMainDeps.onTokenizationReady = (tokenizedText: string): void => {
|
||||
if (!shouldWarmupAnnotationDictionaries()) {
|
||||
baseOnTokenizationReady?.(tokenizedText);
|
||||
return;
|
||||
}
|
||||
markTokenizationPlaybackReady();
|
||||
baseOnTokenizationReady?.(tokenizedText);
|
||||
if (!tokenizationWarmupCompleted) {
|
||||
void prewarmSubtitleDictionaries({ showLoadingOsd: true }).catch(() => {});
|
||||
}
|
||||
};
|
||||
cachedTokenizerRuntimeDeps = options.tokenizer.createTokenizerRuntimeDeps(tokenizerMainDeps);
|
||||
return cachedTokenizerRuntimeDeps;
|
||||
};
|
||||
const tokenizeSubtitle = async (text: string): Promise<TTokenizedSubtitle> => {
|
||||
if (!tokenizationWarmupCompleted) void startTokenizationWarmups();
|
||||
await ensureTokenizationPrerequisites();
|
||||
const tokenizerMainDeps = buildTokenizerDepsHandler();
|
||||
if (shouldWarmupAnnotationDictionaries()) {
|
||||
const onTokenizationReady = tokenizerMainDeps.onTokenizationReady;
|
||||
tokenizerMainDeps.onTokenizationReady = (tokenizedText: string): void => {
|
||||
markTokenizationPlaybackReady();
|
||||
onTokenizationReady?.(tokenizedText);
|
||||
if (!tokenizationWarmupCompleted) {
|
||||
void prewarmSubtitleDictionaries({ showLoadingOsd: true }).catch(() => {});
|
||||
}
|
||||
};
|
||||
}
|
||||
return options.tokenizer.tokenizeSubtitle(
|
||||
text,
|
||||
options.tokenizer.createTokenizerRuntimeDeps(tokenizerMainDeps),
|
||||
);
|
||||
return options.tokenizer.tokenizeSubtitle(text, getTokenizerRuntimeDeps());
|
||||
};
|
||||
|
||||
const launchBackgroundWarmupTask = createLaunchBackgroundWarmupTaskFromStartup(
|
||||
|
||||
@@ -28,6 +28,9 @@ export function createBuildPreloadJellyfinExternalSubtitlesMainDepsHandler(
|
||||
? (itemId, streamIndex, delaySeconds) =>
|
||||
deps.saveSubtitleDelay!(itemId, streamIndex, delaySeconds)
|
||||
: undefined,
|
||||
initSubtitlePrefetch: deps.initSubtitlePrefetch
|
||||
? (sourcePath) => deps.initSubtitlePrefetch!(sourcePath)
|
||||
: undefined,
|
||||
logDebug: (message: string, error: unknown) => deps.logDebug(message, error),
|
||||
});
|
||||
}
|
||||
@@ -40,6 +40,9 @@ function makeDeps(overrides: {
|
||||
>[0]['setActiveSubtitleDelayKey'];
|
||||
loadSubtitleSourceText?: (source: string) => Promise<string>;
|
||||
saveSubtitleDelay?: (itemId: string, streamIndex: number, delaySeconds: number) => void;
|
||||
initSubtitlePrefetch?: Parameters<
|
||||
typeof createPreloadJellyfinExternalSubtitlesHandler
|
||||
>[0]['initSubtitlePrefetch'];
|
||||
logDebug?: Parameters<typeof createPreloadJellyfinExternalSubtitlesHandler>[0]['logDebug'];
|
||||
}) {
|
||||
return {
|
||||
@@ -58,6 +61,7 @@ function makeDeps(overrides: {
|
||||
setActiveSubtitleDelayKey: overrides.setActiveSubtitleDelayKey,
|
||||
loadSubtitleSourceText: overrides.loadSubtitleSourceText,
|
||||
saveSubtitleDelay: overrides.saveSubtitleDelay,
|
||||
initSubtitlePrefetch: overrides.initSubtitlePrefetch,
|
||||
logDebug: overrides.logDebug ?? (() => {}),
|
||||
};
|
||||
}
|
||||
@@ -134,6 +138,92 @@ test('preload jellyfin subtitles caches external tracks locally and chooses japa
|
||||
]);
|
||||
});
|
||||
|
||||
test('preload jellyfin subtitles starts prefetch for the selected japanese track', async () => {
|
||||
const prefetched: string[] = [];
|
||||
const preload = createPreloadJellyfinExternalSubtitlesHandler(
|
||||
makeDeps({
|
||||
listJellyfinSubtitleTracks: async () => [
|
||||
{ index: 0, language: 'jpn', title: 'Japanese', deliveryUrl: 'https://sub/a.srt' },
|
||||
{ index: 1, language: 'eng', title: 'English', deliveryUrl: 'https://sub/b.srt' },
|
||||
],
|
||||
getMpvClient: () => ({
|
||||
requestProperty: async () => [
|
||||
{
|
||||
type: 'sub',
|
||||
id: 5,
|
||||
lang: 'jpn',
|
||||
title: 'Japanese',
|
||||
external: true,
|
||||
'external-filename': '/tmp/subminer-jellyfin-subtitles/0.srt',
|
||||
},
|
||||
{
|
||||
type: 'sub',
|
||||
id: 6,
|
||||
lang: 'eng',
|
||||
title: 'English',
|
||||
external: true,
|
||||
'external-filename': '/tmp/subminer-jellyfin-subtitles/1.srt',
|
||||
},
|
||||
],
|
||||
}),
|
||||
cacheSubtitleTrack: async (track) => ({
|
||||
path: `/tmp/subminer-jellyfin-subtitles/${track.index}.srt`,
|
||||
cleanupDir: '/tmp/subminer-jellyfin-subtitles',
|
||||
}),
|
||||
initSubtitlePrefetch: (sourcePath) => {
|
||||
prefetched.push(sourcePath);
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await preload({ session, clientInfo, itemId: 'item-1' });
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
assert.deepEqual(prefetched, ['/tmp/subminer-jellyfin-subtitles/0.srt']);
|
||||
});
|
||||
|
||||
test('preload jellyfin subtitles survives prefetch start failures', async () => {
|
||||
const logs: string[] = [];
|
||||
const commands: Array<Array<string | number>> = [];
|
||||
const preload = createPreloadJellyfinExternalSubtitlesHandler(
|
||||
makeDeps({
|
||||
listJellyfinSubtitleTracks: async () => [
|
||||
{ index: 0, language: 'jpn', title: 'Japanese', deliveryUrl: 'https://sub/a.srt' },
|
||||
],
|
||||
getMpvClient: () => ({
|
||||
requestProperty: async () => [
|
||||
{
|
||||
type: 'sub',
|
||||
id: 5,
|
||||
lang: 'jpn',
|
||||
title: 'Japanese',
|
||||
external: true,
|
||||
'external-filename': '/tmp/subminer-jellyfin-subtitles/0.srt',
|
||||
},
|
||||
],
|
||||
}),
|
||||
sendMpvCommand: (command) => commands.push(command),
|
||||
cacheSubtitleTrack: async (track) => ({
|
||||
path: `/tmp/subminer-jellyfin-subtitles/${track.index}.srt`,
|
||||
cleanupDir: '/tmp/subminer-jellyfin-subtitles',
|
||||
}),
|
||||
initSubtitlePrefetch: async () => {
|
||||
throw new Error('parse failed');
|
||||
},
|
||||
logDebug: (message) => logs.push(message),
|
||||
}),
|
||||
);
|
||||
|
||||
await preload({ session, clientInfo, itemId: 'item-1' });
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
assert.deepEqual(logs, ['Failed to start subtitle prefetch for Jellyfin subtitle']);
|
||||
assert.ok(
|
||||
commands.some((command) => command[0] === 'set_property' && command[1] === 'sid'),
|
||||
'subtitle selection still happens when prefetch start fails',
|
||||
);
|
||||
});
|
||||
|
||||
test('preload jellyfin subtitles stages tracks without temporary subtitle selection', async () => {
|
||||
const commands: Array<Array<string | number>> = [];
|
||||
const preload = createPreloadJellyfinExternalSubtitlesHandler(
|
||||
|
||||
@@ -320,6 +320,7 @@ export function createPreloadJellyfinExternalSubtitlesHandler(deps: {
|
||||
setActiveSubtitleDelayKey?: (key: JellyfinSubtitleDelayKey | null) => void;
|
||||
loadSubtitleSourceText?: (source: string) => Promise<string>;
|
||||
saveSubtitleDelay?: (itemId: string, streamIndex: number, delaySeconds: number) => boolean | void;
|
||||
initSubtitlePrefetch?: (sourcePath: string) => void | Promise<void>;
|
||||
logDebug: (message: string, error: unknown) => void;
|
||||
}): PreloadJellyfinExternalSubtitlesHandler {
|
||||
const activeCacheDirs = new Set<string>();
|
||||
@@ -329,6 +330,18 @@ export function createPreloadJellyfinExternalSubtitlesHandler(deps: {
|
||||
deps.sendMpvCommand(['set_property', 'sub-delay', 0]);
|
||||
}
|
||||
|
||||
// mpv's sid property-change is the only thing that normally starts prefetching, so a
|
||||
// coalesced or missed event leaves the whole episode uncached. The downloaded path is
|
||||
// known here, so seed the pipeline directly instead of waiting on the observer.
|
||||
function startSubtitlePrefetchForCachedTrack(sourcePath: string): void {
|
||||
if (!deps.initSubtitlePrefetch) return;
|
||||
void Promise.resolve()
|
||||
.then(() => deps.initSubtitlePrefetch!(sourcePath))
|
||||
.catch((error) => {
|
||||
deps.logDebug('Failed to start subtitle prefetch for Jellyfin subtitle', error);
|
||||
});
|
||||
}
|
||||
|
||||
function cleanupActiveCache(): void {
|
||||
const dirs = [...activeCacheDirs];
|
||||
if (dirs.length === 0) return;
|
||||
@@ -438,6 +451,7 @@ export function createPreloadJellyfinExternalSubtitlesHandler(deps: {
|
||||
}
|
||||
}
|
||||
deps.sendMpvCommand(['set_property', 'sid', japanesePrimaryId]);
|
||||
startSubtitlePrefetchForCachedTrack(selectedCachedTrack.path);
|
||||
} else {
|
||||
deps.setActiveSubtitleDelayKey?.(null);
|
||||
resetManagedSubtitleDelay();
|
||||
|
||||
@@ -70,6 +70,24 @@ test('subtitle change handler broadcasts cached annotated payload immediately wh
|
||||
]);
|
||||
});
|
||||
|
||||
test('subtitle change handler logs debug when a cached payload is emitted immediately', () => {
|
||||
const debugs: string[] = [];
|
||||
const handler = createHandleMpvSubtitleChangeHandler({
|
||||
setCurrentSubText: () => {},
|
||||
getImmediateSubtitlePayload: (text) => (text ? { text, tokens: [] } : null),
|
||||
broadcastSubtitle: () => {},
|
||||
onSubtitleChange: () => {},
|
||||
refreshDiscordPresence: () => {},
|
||||
logDebug: (message) => debugs.push(message),
|
||||
});
|
||||
|
||||
handler({ text: 'キャッシュ済みの行' });
|
||||
handler({ text: '' });
|
||||
|
||||
assert.equal(debugs.length, 1);
|
||||
assert.match(debugs[0]!, /cached subtitle/);
|
||||
});
|
||||
|
||||
test('subtitle change handler emits cached annotation after forwarding the subtitle change', () => {
|
||||
const calls: string[] = [];
|
||||
const handler = createHandleMpvSubtitleChangeHandler({
|
||||
|
||||
@@ -20,11 +20,15 @@ export function createHandleMpvSubtitleChangeHandler(deps: {
|
||||
broadcastSubtitle: (payload: SubtitleData) => void;
|
||||
onSubtitleChange: (text: string) => void;
|
||||
refreshDiscordPresence: () => void;
|
||||
logDebug?: (message: string) => void;
|
||||
}) {
|
||||
return ({ text }: { text: string }): void => {
|
||||
deps.setCurrentSubText(text);
|
||||
const immediatePayload = deps.getImmediateSubtitlePayload?.(text) ?? null;
|
||||
if (immediatePayload) {
|
||||
deps.logDebug?.(
|
||||
`[subtitle-processing] emitted cached subtitle immediately (${text.length} chars)`,
|
||||
);
|
||||
deps.onSubtitleChange(text);
|
||||
(deps.emitImmediateSubtitle ?? deps.broadcastSubtitle)(immediatePayload);
|
||||
} else {
|
||||
|
||||
@@ -47,6 +47,7 @@ export function createBindMpvMainEventHandlersHandler(deps: {
|
||||
emitImmediateSubtitle?: (payload: SubtitleData) => void;
|
||||
broadcastSubtitle: (payload: SubtitleData) => void;
|
||||
onSubtitleChange: (text: string) => void;
|
||||
logSubtitleProcessingDebug?: (message: string) => void;
|
||||
refreshDiscordPresence: () => void;
|
||||
|
||||
setCurrentSubAssText: (text: string) => void;
|
||||
@@ -123,6 +124,9 @@ export function createBindMpvMainEventHandlersHandler(deps: {
|
||||
: undefined,
|
||||
broadcastSubtitle: (payload) => deps.broadcastSubtitle(payload),
|
||||
onSubtitleChange: (text) => deps.onSubtitleChange(text),
|
||||
logDebug: deps.logSubtitleProcessingDebug
|
||||
? (message) => deps.logSubtitleProcessingDebug?.(message)
|
||||
: undefined,
|
||||
refreshDiscordPresence: () => deps.refreshDiscordPresence(),
|
||||
});
|
||||
const handleMpvSubtitleAssChange = createHandleMpvSubtitleAssChangeHandler({
|
||||
|
||||
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user