diff --git a/AGENTS.md b/AGENTS.md index 6041275..063ae2b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -110,7 +110,8 @@ site/ documentation site + playground (Astro + Starlight, Gi src/content/docs/ the pages (Markdown/MDX, JS + Python + Rust tabs on every example); reference/spec.md is generated from spec/SPEC.md src/components/ HeroDemo, Playground (runs js/ in the browser), Feature, Stats - src/lib/ trackview.ts (highlight + field rendering), icons.ts (Lucide SVG strings) + src/lib/ trackview.ts (highlight + field rendering), icons.ts (Lucide SVG strings), + lang.ts (one language choice for docs tabs, install switch, playground) scripts/sync-spec.mjs copies spec/SPEC.md into the docs at build time scripts/compare-ports.mjs every fixture through js/dist, the Python port and the Rust crate, diffs the full outputs (parseTracklist and applyEdits included); @@ -127,7 +128,7 @@ scripts/dump_py.py Python side of compare-ports (JSONL in, to_dict() JSON pr-title.yml (conventional PR titles) .github/release-notes/ optional hand-written highlights prepended to a GitHub Release release-please-config.json, .release-please-manifest.json release automation (never hand-edit the manifest) -js/CHANGELOG.md, spec/CHANGELOG.md, python/CHANGELOG.md generated by release-please from commit messages +js/CHANGELOG.md, spec/CHANGELOG.md, python/CHANGELOG.md, rust/CHANGELOG.md generated by release-please ``` ## Golden rule @@ -197,7 +198,8 @@ Every port must produce byte-identical output. The full text is SPEC.md R0; in s - **Iterate by code point** (R0.5), not UTF-16 unit or byte. No offsets in the output. - *Digit* means ASCII `0`–`9` only. - **Total** (R0.8): any string returns a ParsedTrack. Never throw or panic, including on bad - options. No backtracking blowups: a 10,000-code-point input finishes well under 100 ms. + options. No backtracking blowups: a 10,000-code-point input takes tens of milliseconds in JS and Rust + and well under a second in Python (the suites enforce 1 s, Rust 2 s). ## Commands @@ -385,6 +387,92 @@ icons or gradients, data colours only for parsed output) are written at the top changed pages with `pnpm docs`. Site-only commits (`docs(site)`, `fix(site)`, `feat(site)`) don't trigger a release; changes under `js/`, `python/` or `spec/` do, even `docs:` ones. +### What the docs may and may not claim + +Each of these was written wrong at least once and caught in review. Check them when you touch docs. + +| Don't write | Write instead, and why | +|---|---| +| "linear time" | Hand-written scanners, no regex backtracking. The R9.2 dedup in JS and Python is quadratic on thousands of repeated `feat.` credits (Rust is near-linear). | +| "under 100 ms" for every port | True for JS (10 to 70 ms on 10,000 code points) and Rust (under 20 ms, release build). Python takes 40 to 170 ms. The suites enforce 1 s (JS, Python) and 2 s (Rust). | +| "identical output for any input" | Identical on every fixture input. The Rust crate takes NFC from `unicode-normalization` (Unicode 18), Node 24 has Unicode 17, so 32 new combining marks can be ordered differently. Link `project/ports/#what-the-rust-port-taught`. | +| "zero dependencies" for the project | Zero in JS and Python. Rust has one, `unicode-normalization`. | +| a size in mixed units | Core: about 18 kB gzip. Tracklist entry: about 8.4 KiB (8,607 B), budget 9 KiB. Re-measure with `pnpm --filter trackparse build && pnpm --filter trackparse size`. | +| every suite checks "no word goes missing" | Only `rust/tests/properties.rs` has that test today. | +| "Neuropunk" on the site | "a private corpus of real podcast tracklists". Fixture file names and `source` values keep the name; the site and READMEs don't. | + +Numbers that appear in many files (grep all of them when one changes): fixture counts (13,130 = +1,203 handwritten + 11,927 generated), test counts (vitest 1,352, pytest 1,342), CI matrices +(Node 22/24 + 18/20, Python 3.9 to 3.14, Rust stable + 1.74), the 27 version types, the sizes +above. `spec/generator/README.md` links the site anchor `#generated-11927-cases`, which changes +with the count. + +### Checking examples and links + +- **Run every block, in every language.** A harness that extracts the fenced `js` / `python` / + `rust` blocks per file, runs them and compares each `expr // output` line takes minutes to write + and has caught every wrong output so far. JS runs against `js/dist` after a build, Python with + `uv run python`, Rust in a scratch cargo project with a path dependency (`features = ["serde"]`, + plus `serde_json`). +- **Rust blocks must compile as written, in page order.** A bare `value;` moves a non-`Copy` + value, so a later line that uses it fails (E0382, E0507). Borrow instead: `&track.artists;`, + `&list.warnings;`, `&parse(…).versions[0];`. Type listings (`pub struct …`) go in their own block, + apart from runnable code. +- **`rust/README.md` is compiled.** `lib.rs` includes it as crate docs, so every Rust block in it is + a doc test: run `cargo test --doc --all-features` after editing it. +- **Python examples need their imports** (`from trackparse import ParsedTrack`). Functions that + take a string raise `TypeError` on other input; `format_track` and `all_artists` take a + `ParsedTrack` unchecked. +- **Links.** Package READMEs use full `https://` URLs. Check site URLs against the built HTML + (`site/dist`), ids included. `curl` gets 403 from npmjs.com and 404 from crates.io pages without + `Accept: text/html`: use `registry.npmjs.org/trackparse` and `crates.io/api/v1/crates/trackparse`. + Shields badges can lag a release by some hours. +- **Renaming a heading breaks published links.** Keep the old id with an `` alias, as + `reference/parse.mdx` does for `serialising-to-json` and `json-and-python-objects`. +- **Spelling** in docs is American (`normalize`, `serialize`, `recognize`, `catalog`), except + "behaviour", which the spec uses throughout. + +### Site internals worth knowing + +- **One language choice.** `site/src/lib/lang.ts` reads and writes Starlight's own + `starlight-synced-tabs__lang` localStorage entry (the value is the tab label). The docs tabs, the + install switch (`Install.astro`) and the playground code panels all follow it. It must keep + working when storage is blocked. +- **Playground state is in the URL hash** (input, mode, options, `known`, edits), so a docs page can + link to a prefilled example. Look at an existing link before writing one. +- **Warning names link to `reference/warnings`** with a text fragment + (`#tracklist-warnings:~:text=`); dashes in the code are encoded as `%2D`. The section ids + are `track-warnings`, `tracklist-warnings` and `edit-warnings`. +- **Astro 7's Markdown processor rejects rehype plugins.** Small DOM fixes are head scripts in + `astro.config.mjs` (the `nowrap` class on space-free code in tables). +- **Building somewhere else.** `astro build --outDir` into `/tmp` fails with `EXDEV` (rename across + filesystems). Build into a folder under `site/node_modules/.cache/` when `site/dist` is in use. +- `pnpm lint` covers `js/` only, and `astro check` stops at an install prompt. The build and a + browser are the checks for the site. Look at 1280 and 375 px, light and dark; a headless Chrome + over the DevTools protocol is enough. + +## Working with several agents + +- Give each agent its own files and say so. The split that worked for a docs pass: root README; + the package READMEs and `spec/**/README.md`; `site/src/content/docs/**`; components, `lib/`, + styles, `index.mdx` and `playground.mdx`. Then one reviewer that edits nothing, then one fixer. +- Agents never commit, push or switch branches. The session that started them commits. +- Two agents building the site at once must not share `site/dist`. +- Timings measured while other agents run are too high, and + `test_ten_thousand_lines_are_fast` in the Python suite can fail on a busy machine. Re-run it alone + before believing it. +- A reviewer should run the examples, not read them. Ask for file, line and the concrete fix. + +## Known gaps (not yet fixed) + +- R9.2 dedup is quadratic in JS and Python on thousands of repeated credits (Rust already fixed). +- `format(track, { feat: "nope" })` drops the featured artists in JS and Python instead of falling + back to the default, unlike other bad options. Needs a spec decision and a fixture first. +- Python tracklist types have `to_dict()` but no `from_dict()`; `ParsedTrack` has both. +- JS and Python do not test invariant 6 ("no word goes missing"); only Rust does. +- The npm and PyPI publish jobs use actions by tag; the crates.io job pins its auth action by SHA. +- The playground's Rust snippet is a whole program, the JS and Python ones are bare expressions. + ## Porting guide (Rust, others) A port is done when it passes every fixture and every invariant. The Python and Rust ports are done @@ -527,6 +615,18 @@ Version rules: `gh workflow run release.yml -f python_tag=python-vX.Y.Z` (PyPI) or `-f rust_tag=rust-vX.Y.Z` (crates.io). The npm job always republishes from a fresh release; a failed npm publish needs the same treatment by hand. +- **Things the 0.5.0 release taught:** + - The release PR is opened with `GITHUB_TOKEN`, so no CI runs on it and GitHub shows it as + `UNSTABLE`. That is expected; `main` was green when it was generated. + - A `docs:` commit under `js/`, `python/` or `rust/` (a package README) opens a release PR. A + commit that touches only the root README, `AGENTS.md`, `site/` or `.github/` does not. + - A component's first changelog lists every commit that ever touched its folder, because there + is no earlier tag to start from. + - crates.io refuses to publish until the account has a verified email address. + - After a release, check all three registries by API, not by badge: `registry.npmjs.org`, + `pypi.org/pypi/trackparse/json`, `crates.io/api/v1/crates/trackparse`. + - Don't force-push a PR branch to pick up `main`: GitHub's rebase-merge rebases it when there + are no conflicts. - **Agents never merge release PRs, publish, push tags or bump versions on their own initiative.** Merging the release PR is the maintainer's publish decision. diff --git a/README.md b/README.md index ec0be90..7391078 100644 --- a/README.md +++ b/README.md @@ -6,18 +6,19 @@ [![npm](https://img.shields.io/npm/v/trackparse?color=cb3837&logo=npm)](https://www.npmjs.com/package/trackparse) [![PyPI](https://img.shields.io/pypi/v/trackparse?color=3775a9&logo=pypi&logoColor=white)](https://pypi.org/project/trackparse/) -[![Python versions](https://img.shields.io/pypi/pyversions/trackparse?logo=python&logoColor=white)](https://pypi.org/project/trackparse/) +[![crates.io](https://img.shields.io/crates/v/trackparse?color=e6822a&logo=rust&logoColor=white)](https://crates.io/crates/trackparse) +[![docs.rs](https://img.shields.io/docsrs/trackparse?logo=docsdotrs&logoColor=white)](https://docs.rs/trackparse) +
[![js](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/js.yml?branch=main&label=js&logo=github)](https://github.com/4matic/trackparse/actions/workflows/js.yml) [![python](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/python.yml?branch=main&label=python&logo=github)](https://github.com/4matic/trackparse/actions/workflows/python.yml) +[![rust](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/rust.yml?branch=main&label=rust&logo=github)](https://github.com/4matic/trackparse/actions/workflows/rust.yml) [![spec](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/spec.yml?branch=main&label=spec&logo=github)](https://github.com/4matic/trackparse/actions/workflows/spec.yml) -[![fixtures](https://img.shields.io/badge/fixtures-12%2C965%20passing-2ea44f)](spec/fixtures) -[![dependencies](https://img.shields.io/badge/dependencies-0-2ea44f)](js/package.json) -[![gzip](https://img.shields.io/badge/gzip-17%20kB-informational)](https://www.npmjs.com/package/trackparse) -[![types](https://img.shields.io/npm/types/trackparse)](js/src/types.ts) +
+[![fixtures](https://img.shields.io/badge/fixtures-13%2C130%20passing-2ea44f)](#how-its-tested) [![license](https://img.shields.io/badge/license-MIT-blue)](LICENSE) [![docs](https://img.shields.io/badge/docs-4matic.github.io%2Ftrackparse-6a3fd6)](https://4matic.github.io/trackparse/) -**[Documentation](https://4matic.github.io/trackparse/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** · [Install](#install) · [Quick start](#quick-start) · [What it understands](#what-it-understands) · [Tracklists](#tracklists) · [How it's tested](#how-its-tested) · [API](#api) · [Spec](spec/SPEC.md) +**[Documentation](https://4matic.github.io/trackparse/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** · [Install](#install) · [Quick start](#quick-start) · [What it understands](#what-it-understands) · [Tracklists](#tracklists) · [API](#api) · [How it's tested](#how-its-tested) · [Ports](#ports) · [Spec](spec/SPEC.md) @@ -31,11 +32,17 @@ ``` Most title parsers give you `["Wilkinson ft. Becky Hill & Tom Cane", "Afterglow (Sub Focus VIP Remix)"]` -and call it a day. Or they "clean" the string and throw the feat and the remix away. Neither -tells you that Becky Hill is featured, that Sub Focus did the remix, or that it's a VIP. +and stop there. Others "clean" the string and throw the feat and the remix away. Neither tells you +that Becky Hill is featured, that Sub Focus did the remix, or that it's a VIP. -trackparse keeps all of it. Its one rule is **extract, don't delete**: everything it recognises -goes into a field, and anything it doesn't recognise stays in the title, word for word. +trackparse keeps all of it. Its one rule is **extract, don't delete**: everything it recognizes +goes into a field, and anything it doesn't recognize stays in the title, word for word. + +It comes as an npm package, a PyPI package and a Rust crate, all named `trackparse`. One +[spec](spec/SPEC.md) and one set of fixtures define the behaviour. The three pass the same fixtures +and give the same output on every fixture input. The example below is JavaScript; [Quick start](#quick-start) has the +same calls in Python and Rust, and you can try any string in the +[playground](https://4matic.github.io/trackparse/playground/). ```js import { parse } from "trackparse"; @@ -89,50 +96,60 @@ track.position; // { raw: '01', number: 1 } } ``` -Every key is always present. When a guess was involved, `warnings` says which one. +Every key is always present. When a guess was involved, `warnings` says which one. Python's +`to_dict()` and Rust's `to_json()` give this same JSON. ## At a glance -**Docs:** [What it understands](https://4matic.github.io/trackparse/guides/what-it-understands/) +**Docs:** [Introduction](https://4matic.github.io/trackparse/start/introduction/) · [How it's tested](https://4matic.github.io/trackparse/project/testing/) · [Ports](https://4matic.github.io/trackparse/project/ports/) | Number | What it means | |---|---| | **13,130** shared fixtures | 1,203 written by hand, 11,927 generated from combinations. 100% pass in JS, Python and Rust, nothing skipped. | -| **1,239** of them on tracklists | 303 handwritten, 936 generated. Line splitting, times, bullets and Markdown, warnings, edits | -| **1,352** JS tests | every fixture, a schema check on every output, property-based tests of the spec invariants, API tests | -| **27** version types | remix, VIP, bootleg, extended, radio, original, live, remaster, sped up, … | -| **0** dependencies | ESM + CJS + TypeScript types, about 17 kB gzipped. `trackparse/tracklist` adds about 8.3 KiB, only if you import it | +| **1,239** of them on tracklists | 303 handwritten, 936 generated. They cover line splitting, times, bullets and Markdown, warnings and edits | +| **1,352** JS tests | Every fixture, a schema check on every output, property-based tests of the spec invariants, API tests | +| **27** version types | Remix, VIP, bootleg, extended, radio, original, live, remaster, sped up and more | +| **0** dependencies in JS and Python | The Rust crate has one, `unicode-normalization`. The JS package is ESM + CJS with TypeScript types, about 18 kB gzipped. `trackparse/tracklist` adds about 8.4 KiB, only if you import it | | **Node 18+** | CI runs the full suite on 22 and 24, and every fixture against the built package on 18 and 20 | | **Python 3.9+** | 1,342 pytest tests on 3.9 to 3.14, plus every fixture against the built wheel. Output is byte-identical to JS | -| **Rust 1.74+** | every fixture, the tracklist invariants and the typed API tests on stable and on 1.74. Output is byte-identical to JS on every fixture and on about 790,000 random inputs | +| **Rust 1.74+** | Every fixture, the tracklist invariants and the typed API tests on stable and on 1.74. Output is byte-identical to JS on every fixture and on about 790,000 random inputs | | **5,031** real tracklist lines | 117 podcast tracklists the tracklist rules were checked against. Every line round-trips byte for byte | -| **1 spec** | [`spec/SPEC.md`](spec/SPEC.md) defines the behaviour; the Python and Rust ports pass the same fixtures | +| **1** spec | [`spec/SPEC.md`](spec/SPEC.md) defines the behaviour. The three packages share its version (0.5.0 today) and are released together | ## Install +**Docs:** [Getting started](https://4matic.github.io/trackparse/start/getting-started/) + +JavaScript and TypeScript ([npm](https://www.npmjs.com/package/trackparse), [package README](js/README.md)). +Node 18+ or any runtime with ES2020, no dependencies: + ```sh npm install trackparse # or: pnpm add / yarn add / bun add trackparse ``` -Works in Node 18+ and any runtime with ES2020. +Python ([PyPI](https://pypi.org/project/trackparse/), [package README](python/README.md)). +Python 3.9+, no dependencies: ```sh pip install trackparse # or: uv add trackparse ``` -Python 3.9+, no dependencies. +Rust ([crates.io](https://crates.io/crates/trackparse), [docs.rs](https://docs.rs/trackparse), +[crate README](rust/README.md)). Rust 1.74+, one dependency (`unicode-normalization`): ```sh -cargo add trackparse +cargo add trackparse # add --features serde for Serialize / Deserialize on the types ``` -Rust 1.74+, one dependency (`unicode-normalization`), `serde` as an optional feature. See [Ports](#ports). - ## Quick start -**Docs:** [Getting started](https://4matic.github.io/trackparse/start/getting-started/) +**Docs:** [Getting started](https://4matic.github.io/trackparse/start/getting-started/) · [Introduction](https://4matic.github.io/trackparse/start/introduction/) + +The three examples parse the same strings. The comments show what each expression evaluates to. + +### JavaScript ```js import { parse, parseArtists, format } from "trackparse"; @@ -141,7 +158,8 @@ parse("Noisia feat. Foreign Beggars - Shellshock").artists.map((a) => a.name); // [ 'Noisia', 'Foreign Beggars' ] (Foreign Beggars has role 'featured') parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)").versions[0]; -// { type: 'live', year: 1986, descriptor: 'at Wembley', … } +// { type: 'live', raw: 'Live at Wembley 1986', artists: [], modifiers: [], +// descriptor: 'at Wembley', year: 1986, unknownArtist: false, delimiter: '(' } parseArtists("Sub Focus, Wilkinson & Dimension feat. Kojo").map((a) => `${a.name}:${a.role}`); // [ 'Sub Focus:primary', 'Wilkinson:primary', 'Dimension:primary', 'Kojo:featured' ] @@ -150,12 +168,13 @@ format(parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)"), { feat: // 'Wilkinson - Afterglow (feat. Becky Hill) (Sub Focus Remix)' ``` -CommonJS works too: `const { parse } = require("trackparse")`. +CommonJS works too: `const { parse } = require("trackparse")`. The full JavaScript API, with the +TypeScript types, is in [`js/README.md`](js/README.md). ### Python -Same parser, same output. Functions are snake_case, results are frozen dataclasses, and -`to_dict()` gives the spec's JSON with camelCase keys, identical to what the JS package returns. +Functions are snake_case and results are frozen dataclasses. `to_dict()` gives the spec's JSON +with camelCase keys, the same as the JS package returns. ```python from trackparse import format_track, parse, parse_artists @@ -184,18 +203,18 @@ full Python API is in [`python/README.md`](python/README.md). ### Rust -The same parser again. Functions are snake_case, results are structs with public fields and enums -for roles, types and kinds, and `to_json()` writes the spec's JSON, identical to the JS output. +Results are structs with public fields, and roles, version types and junk kinds are enums. +`to_json()` writes the spec's JSON, byte for byte what `JSON.stringify` gives in JS. ```rust use trackparse::{format_track_with, parse, parse_artists, FeatPlacement, FormatOptions, JoinerStyle}; let track = parse("Noisia feat. Foreign Beggars - Shellshock"); -track.artists; +&track.artists; // [Artist { name: "Noisia", role: Primary, joiner: None, source: Artist }, // Artist { name: "Foreign Beggars", role: Featured, joiner: Some("feat."), source: Artist }] -parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)").versions[0]; +&parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)").versions[0]; // Version { version_type: Live, raw: "Live at Wembley 1986", artists: [], modifiers: [], // descriptor: Some("at Wembley"), year: Some(1986), unknown_artist: false, delimiter: Paren } @@ -212,21 +231,26 @@ track.artists[1].to_json(); ``` Options are builders passed to the `_with` form of a function: -`parse_with(s, &ParseOptions::new().known_artists(["Chase & Status"]))`. Tracklists are in -`trackparse::tracklist`. Every example on the [documentation site](https://4matic.github.io/trackparse/) -has a Rust tab. +`parse_with(s, &ParseOptions::new().known_artists(["Chase & Status"]))`. The full Rust API is in +[`rust/README.md`](rust/README.md) and on [docs.rs](https://docs.rs/trackparse). + +Every example on the [documentation site](https://4matic.github.io/trackparse/) has JavaScript, +Python and Rust tabs. > [!TIP] > `&` is a joiner, so `Chase & Status` comes out as two artists. There's no built-in artist > database. Pass the names you know instead: `parse(s, { knownArtists: ["Chase & Status"] })` in > JS, `parse(s, known_artists=["Chase & Status"])` in Python, > `parse_with(s, &ParseOptions::new().known_artists(["Chase & Status"]))` in Rust. +> See [knownArtists](https://4matic.github.io/trackparse/guides/artists/#knownartists). ## What it understands **Docs:** [What it understands](https://4matic.github.io/trackparse/guides/what-it-understands/) · [Artists and credits](https://4matic.github.io/trackparse/guides/artists/) · [Versions and remixes](https://4matic.github.io/trackparse/guides/versions/) · [Junk, flags and prefixes](https://4matic.github.io/trackparse/guides/junk-and-flags/) -These are real outputs of `parse(input)` with default options, unless noted. +These are real outputs of `parse(input)` with default options, unless noted. They are the same in +all three languages. To try your own strings, use the +[playground](https://4matic.github.io/trackparse/playground/). | Input | Artists | Title | Versions / other | |---|---|---|---| @@ -250,8 +274,8 @@ These are real outputs of `parse(input)` with default options, unless noted. | `01. Aphex Twin - Xtal` | Aphex Twin | `Xtal` | position 1 | | `[12:34] Noisia - Stigma` | Noisia | `Stigma` | timestamp 754 s | | `07_Burial_-_Archangel.mp3` | Burial | `Archangel` | filename mode, position 7 | -| `"Numb" by Linkin Park` *(youtube)* | Linkin Park | `Numb` | ⚠ bySplit | -| `Blink-182-All The Small Things` *(youtube)* | Blink-182 | `All The Small Things` | ⚠ unspacedDashSplit | +| `"Numb" by Linkin Park` *(youtube)* | Linkin Park | `Numb` | warning `bySplit` | +| `Blink-182-All The Small Things` *(youtube)* | Blink-182 | `All The Small Things` | warning `unspacedDashSplit` | | `Кино - Группа крови (Remastered 2019)` | Кино | `Группа крови` | remaster, 2019 | | `ID - ID (ID Remix)` | | `ID` | unknown artist, title and remixer | | `AC/DC - Back In Black` | AC/DC | `Back In Black` | | @@ -264,9 +288,10 @@ These are real outputs of `parse(input)` with default options, unless noted. **Docs:** [Tracklists](https://4matic.github.io/trackparse/guides/tracklists/) · [Editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/) · [Tracklist API](https://4matic.github.io/trackparse/reference/tracklist/) Mixes and podcasts come with a tracklist: a block of text, one track per line, usually with a start -time in front. `trackparse/tracklist` reads the whole block. Each line gets its kind, its time and a -full `ParsedTrack`. The list as a whole gets checks with line numbers, and edits rewrite only the -lines you name. +time in front. The tracklist module reads the whole block: `trackparse/tracklist` in JavaScript, +`trackparse.tracklist` in Python, `trackparse::tracklist` in Rust. Each line gets its kind, its time +and a full `ParsedTrack`. The list as a whole gets checks with line numbers, and edits rewrite only +the lines you name. Nothing is thrown away here either. Every line comes back with its original text and its own line ending, so joining `raw + eol` over the entries gives you the input byte for byte. CRLF, LF and CR @@ -343,16 +368,34 @@ hour, so it became `01:00:16` to match the list's other hour times, and the edit (missing line, line without a time, `NaN`) changes nothing and warns `edit-invalid`. Neither function throws. -Python has the same functions, snake_case, with frozen dataclasses: +Python and Rust have the same two functions. Here `text` is the tracklist from the JavaScript +example. In Python an edit is a plain dict with the same keys as in JS: ```python from trackparse.tracklist import apply_edits, parse_tracklist -# text: the same tracklist as in the JS example above parse_tracklist(text).warnings[1].suggestion # Suggestion(line=8, raw='01:11:02', seconds=4262) -apply_edits(text, [{"op": "set-time", "line": 8, "seconds": 4262}]).changed -# (8,) + +result = apply_edits(text, [ + {"op": "set-time", "line": 8, "seconds": 4262}, + {"op": "shift", "seconds": 45, "from": 5}, +]) +result.changed # (5, 6, 7, 8, 9) +result.warnings # (EditWarning(code='style-upgraded', edit=1, line=5),) +``` + +In Rust an edit is an `Edit` value, and seconds are `f64`: + +```rust +use trackparse::tracklist::{apply_edits, parse_tracklist, Edit}; + +&parse_tracklist(&text).warnings[1].suggestion; +// Some(Suggestion { line: 8, raw: "01:11:02", seconds: 4262.0 }) + +let result = apply_edits(&text, &[Edit::set_time(8, 4262.0), Edit::shift_from(45.0, 5)]); +result.changed; // [5, 6, 7, 8, 9] +result.warnings; // [EditWarning { code: StyleUpgraded, edit: 1, line: Some(5) }] ``` Lists pasted from Discord, Reddit, Telegram or YouTube comments often keep their list bullets and @@ -371,8 +414,8 @@ text starts with `w/` is `layered`: a track played over the previous one Inside a tracklist the first ` - ` is the artist/title separator on practically every line. A single track string doesn't get that benefit of the doubt, so `parse()` sometimes reads the part after the dash as a version or a genre. `parseTracklist` parses each line with `mode: "tracklist"`, which -trusts the first spaced dash. You can ask `parse()` for it too. These are real lines from a podcast -archive: +trusts the first spaced dash. You can ask `parse()` for it too (`mode="tracklist"` in Python, +`ModeOption::Tracklist` in Rust). These are real lines from a podcast archive: | Line | `parse(line)` | In a tracklist | |---|---|---| @@ -384,18 +427,19 @@ archive: | `10 Optiv & BTK-Inception (Gydra remix)` | no separator | position 10, Optiv, BTK / `Inception`, remix by Gydra | The last two rows need the neighbours. A bare `8 ` only counts as a position when the nearest line -before or after it that has a time or a spaced dash starts with a bare 7 or 9. Dotted numbers like `01.` never count as -neighbours, so `2 Unlimited - No Limit` between `01.` and `03.` stays an artist. The tight +before or after it that has a time or a spaced dash starts with a bare 7 or 9. Dotted numbers like +`01.` never count as neighbours, so `2 Unlimited - No Limit` between `01.` and `03.` stays an artist. The tight `BTK-Inception` dash only splits on a timed line without a marker word, and only when at least half of the list uses spaced dashes. ## How it's tested -**Docs:** [How it's tested](https://4matic.github.io/trackparse/project/testing/) +**Docs:** [How it's tested](https://4matic.github.io/trackparse/project/testing/) · [Ports](https://4matic.github.io/trackparse/project/ports/) -The fixtures in [`spec/fixtures`](spec/fixtures) are the source of truth. The spec says what should -happen, the fixtures pin it down, and every port has to pass all of them. The JS and Python -packages and the Rust crate all do: **13,130 of 13,130**, with empty skip lists, in CI on every push. +The fixtures in [`spec/fixtures`](spec/fixtures) are the source of truth +([format and matching rules](spec/fixtures/README.md)). The spec says what should happen, the +fixtures pin it down, and every port has to pass all of them. The JS and Python packages and the +Rust crate all do: **13,130 of 13,130**, with empty skip lists, in CI on every push. Passing a fixture only checks the fields the case asserts, so [`scripts/compare-ports.mjs`](scripts/compare-ports.mjs) also runs every fixture input through all @@ -427,7 +471,7 @@ field, so nothing can drift unnoticed. ### Generated: 11,927 cases -A deterministic generator in [`spec/generator`](spec/generator) builds inputs from small "atoms": an +A deterministic generator in [`spec/generator`](spec/generator) ([README](spec/generator/README.md)) builds inputs from small "atoms": an artist, a joiner, a feat placement, a version group, a junk suffix. Each atom carries its own expected contribution. The expected output is assembled from those atoms and never comes from running a parser, so the generator can't just agree with the code it is testing. @@ -449,22 +493,26 @@ line; the expected tracks are the plain lines' tracks. ### Properties -[fast-check](https://github.com/dubzzz/fast-check) throws thousands of random strings at the parser to -check the invariants from the spec ([Hypothesis](https://hypothesis.works) does the same for the -Python port): -- it never throws, on any input; -- a 10,000-character input stays linear; +Each port also checks the invariants from the spec on thousands of random strings. The JS suite +uses [fast-check](https://github.com/dubzzz/fast-check), the Python suite +[Hypothesis](https://hypothesis.works), and the Rust crate a small seeded generator of its own, so +it needs no extra dev dependency. The invariants: + +- it never throws or panics, on any input; +- 10,000-code-point inputs built from repeated blocks finish inside a time limit (one second in the + JS and Python suites), which catches anything that blows up on long input; - `normalize` is idempotent; - whitespace, dash and zero-width noise don't change the result; - every output validates against the schema; -- no word of the input goes missing; +- no word of the input goes missing (the Rust suite); - `parse(format(parse(s)))` round-trips. For tracklists, on random multi-line text and random edit lists: + - `raw + eol` over all entries gives the input back, and `lead + time + gap + rest` gives `raw`; - `applyEdits(t, [])` returns `t`, and an edit never touches a line it doesn't name; - `shift(+s)` then `shift(-s)` restores the text when nothing was clamped or upgraded; -- 10,000 lines parse in linear time (the JS suite allows 3 s; it takes about 0.6 s); +- 10,000 lines parse inside each suite's ceiling (3 s in JS); - a one-line list gives the same track as `parse()` in tracklist mode on its text without Markdown emphasis or a leading `w/`; - Markdown emphasis around a time or a track line gives the same kind, time and track as the plain @@ -472,10 +520,10 @@ For tracklists, on random multi-line text and random edit lists: ### Real tracklists -The tracklist rules were written against a real corpus: all 117 tracklists of the Neuropunk -podcast, 5,031 lines, exported from the label's platform. The corpus is not -redistributable, so it stays out of git (`spec/corpus/` is ignored), but every surprising line in -it became a handwritten fixture. [`scripts/corpus-check.mjs`](scripts/corpus-check.mjs) runs the +The tracklist rules were written against a real corpus: all 117 tracklists of one podcast series, +5,031 lines, exported from the platform that hosts it. The corpus is not redistributable, so it +stays out of git (`spec/corpus/` is ignored), but every surprising line in it became a handwritten +fixture. [`scripts/corpus-check.mjs`](scripts/corpus-check.mjs) runs the built package over it and asserts: - every list round-trips byte for byte, and every line's parts join back into the line; @@ -486,21 +534,52 @@ built package over it and asserts: - only 2 lines stay `line-unparsed`, and both really have no separator (`Gydra & Ihr Caliban`, `Grinda & Nic ZigZag`). -The whole corpus parses in about 0.3 s. +The whole corpus parses in under a second. + +### Run it yourself ```sh pnpm install -pnpm test # fixtures, properties, generator tests -pnpm conformance # pass rate per fixture file and per spec rule -pnpm --filter trackparse build && node scripts/corpus-check.mjs spec/corpus/.jsonl +pnpm test # JS: fixtures, properties, API tests, generator tests +pnpm conformance # pass rate per fixture file and per spec rule + +(cd python && uv run pytest) # the same fixtures and invariants in Python +(cd rust && cargo test) # and in Rust -cd python && uv run pytest # the same fixtures and invariants in Python -cd rust && cargo test # and in Rust +pnpm --filter trackparse build +node scripts/compare-ports.mjs # all three ports on every fixture; must print "differences: 0" +node scripts/corpus-check.mjs spec/corpus/.jsonl # only if you have the corpus ``` +Every other command is in [AGENTS.md](AGENTS.md#commands). + ## API -**Docs:** [parse and ParsedTrack](https://4matic.github.io/trackparse/reference/parse/) · [Other functions](https://4matic.github.io/trackparse/reference/functions/) +**Docs:** [parse and ParsedTrack](https://4matic.github.io/trackparse/reference/parse/) · [Options](https://4matic.github.io/trackparse/reference/options/) · [Other functions](https://4matic.github.io/trackparse/reference/functions/) · [Tracklist API](https://4matic.github.io/trackparse/reference/tracklist/) · [Warnings](https://4matic.github.io/trackparse/reference/warnings/) + +The three packages have the same functions: + +| JavaScript | Python | Rust | +|---|---|---| +| `parse(input, options?)` | `parse(input, **options)` | `parse(input)`, `parse_with(input, &options)` | +| `parseArtists(input, options?)` | `parse_artists(input, **options)` | `parse_artists(input)`, `parse_artists_with(input, &options)` | +| `format(track, options?)` | `format_track(track, **options)` | `format_track(&track)`, `format_track_with(&track, &options)` | +| `normalize(input)` | `normalize(input)` | `normalize(input)` | +| `allArtists(track)` | `all_artists(track)` | `all_artists(&track)` | +| `createParser(options)` | `create_parser(**options)` | `Parser::new(&options)` | +| `SPEC_VERSION` | `SPEC_VERSION` | `SPEC_VERSION` | +| `parseTracklist`, `applyEdits` from `trackparse/tracklist` | `parse_tracklist`, `apply_edits` from `trackparse.tracklist` | `parse_tracklist(_with)`, `apply_edits(_with)` from `trackparse::tracklist` | + +The tables below use the JavaScript names, which are also the keys of the JSON output. In Python +and Rust, options and fields are snake_case (`knownArtists` is `known_artists`, `fullTitle` is +`full_title`). Python results are frozen dataclasses with tuples and `None`. Rust results are +structs with `Vec` and `Option`, the fixed sets of names are enums (`VersionType::Remix`, +`JunkKind::Video`), and `Version.type` is the field `version_type`. Each package README lists its +own signatures and types: [JavaScript](js/README.md#api), [Python](python/README.md#api), +[Rust](rust/README.md#api). The Rust items are also on [docs.rs](https://docs.rs/trackparse). + +No function throws or panics on any string, and bad options fall back to the defaults. The one +exception is Python, which raises `TypeError` when the input is not a `str`. ### `parse(input, options?)` → `ParsedTrack` @@ -511,7 +590,7 @@ cd rust && cargo test # and in Rust | `position` | `{ raw, number } \| null` | Track number (`"01"` → 1) | | `timestamp` | `{ raw, seconds } \| null` | Leading cue time (`"1:02:03"` → 3723) | | `artists` | `Artist[]` | Primary, featured and producer credits. Remixers live in `versions` | -| `title` | `string` | Clean title. Brackets it doesn't recognise stay in | +| `title` | `string` | Clean title. Brackets it doesn't recognize stay in | | `fullTitle` | `string` | `title` with versions re-attached | | `versions` | `Version[]` | Remixes and versions, left to right | | `year` | `number \| null` | From `(2015)` or `- 2015` | @@ -545,7 +624,10 @@ cd rust && cargo test # and in Rust The vocabulary is in [`spec/data`](spec/data). **Warnings:** `noSeparator`, `ambiguousSeparator`, `unspacedDashSplit`, `asymmetricDashSplit`, -`bySplit`, `quotedTitleSplit`, `ambiguousMixCredit`, `unbalancedBrackets`. +`bySplit`, `quotedTitleSplit`, `ambiguousMixCredit`, `unbalancedBrackets`. What each one means is +on the [warnings page](https://4matic.github.io/trackparse/reference/warnings/). + +The JSON shape is fixed by [`spec/schema/parsed-track.schema.json`](spec/schema/parsed-track.schema.json). @@ -561,6 +643,10 @@ The vocabulary is in [`spec/data`](spec/data). | `splitAnd` | `"auto"` | `and` splits only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole | | `keywords` | – | Extra vocabulary: `versionHeads`, `descriptors`, `genres`, `junk`, `featMarkers` | +JavaScript takes an options object, Python takes keyword arguments +(`parse(s, mode="youtube", uploader="Daft Punk")`), and Rust takes a builder +(`parse_with(s, &ParseOptions::new().mode(ModeOption::Youtube).uploader("Daft Punk"))`). + ### Other functions **Docs:** [Other functions](https://4matic.github.io/trackparse/reference/functions/) · [Formatting](https://4matic.github.io/trackparse/guides/formatting/) @@ -585,6 +671,28 @@ const parser = createParser({ parser.parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)").versions[0].type; // 'rework' ``` +```python +from trackparse import create_parser + +parser = create_parser( + known_artists=["Chase & Status", "Camo & Krooked"], + keywords={"version_heads": {"rerub": "rework"}}, +) + +parser.parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)").versions[0].type # 'rework' +``` + +```rust +use trackparse::{KeywordOptions, ParseOptions, Parser, VersionType}; + +let keywords = KeywordOptions::new().version_head("rerub", VersionType::Rework); +let parser = Parser::new( + &ParseOptions::new().known_artists(["Chase & Status", "Camo & Krooked"]).keywords(keywords), +); + +parser.parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)").versions[0].version_type; // Rework +``` + ### Modes **Docs:** [Modes](https://4matic.github.io/trackparse/guides/modes/) @@ -599,10 +707,11 @@ parser.parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)").versi ### Tracklist API -**Docs:** [Tracklist API](https://4matic.github.io/trackparse/reference/tracklist/) · [Warnings](https://4matic.github.io/trackparse/reference/warnings/) +**Docs:** [Tracklist API](https://4matic.github.io/trackparse/reference/tracklist/) · [Warnings](https://4matic.github.io/trackparse/reference/warnings/) · [Editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/) -Import from `trackparse/tracklist` (Python: `trackparse.tracklist`, Rust: `trackparse::tracklist`). It's a separate entry, so code -that only parses single tracks never loads it. +Import from `trackparse/tracklist` (Python: `trackparse.tracklist`, Rust: `trackparse::tracklist`). +In JavaScript it's a separate entry, so code that only parses single tracks never loads it. The +JSON shape is fixed by [`spec/schema/tracklist.schema.json`](spec/schema/tracklist.schema.json). #### `parseTracklist(text, options?)` → `Tracklist` @@ -670,7 +779,7 @@ bytes and its line ending. Edit warnings are `{ code, edit, line }`, where `edit | `time-clamped` | A time would go below zero and was set to zero | | `edit-invalid` | Missing line, no time to set, a non-finite number, a time too large to write, a line break in `text`/`rest`, an unknown `op`. That edit changed nothing | -#### Options +#### Tracklist options Both functions take the same options. `applyEdits` accepts them for symmetry; edits don't depend on them. @@ -685,12 +794,22 @@ them. Python uses keyword arguments (`audio_seconds=`, `marker_words=`) and plain dicts for edits, with the same keys as JS: `{"op": "shift", "seconds": 45, "from": 5}`. +Rust has `parse_tracklist_with` and `apply_edits_with`, which take +`&TracklistOptions::new().audio_seconds(3600.0).marker_words(["drop"])`. Edits are built with +constructors on `Edit`: `set_time(line, seconds)`, `shift(seconds)`, `shift_from(seconds, from)`, +`shift_lines(seconds, lines)`, `sort_by_time()`, `set_rest(line, rest)`, `insert(after, text)` and +`delete(line)`. + +More on the options: [Tracklist options](https://4matic.github.io/trackparse/reference/options/#tracklist-options). + ## How it works **Docs:** [How it works](https://4matic.github.io/trackparse/project/how-it-works/) -A fixed pipeline of hand-written scanners. There are no regexes with lookaround and no -backtracking, so it runs in linear time and ports to Python and Rust with the same output. +The parser is a fixed pipeline of hand-written scanners over code points. It uses no regexes with +lookaround or backreferences and nothing backtracks, so long input can't make it hang: each port's +tests parse 10,000-code-point inputs under a time limit. Writing it this way is also what lets the +Python and Rust ports give the same output as JavaScript. ```mermaid flowchart LR @@ -707,7 +826,8 @@ flowchart LR Brackets are swapped for placeholders before anything is split, so a `&` inside `(Chase & Status Remix)` can't break the artist list. Groups are classified on their own: junk, feat, producer, flag, year, version, or unknown. Unknown ones go back into the title untouched. The full rules, R0–R12, -are in [spec/SPEC.md](spec/SPEC.md). +are in [spec/SPEC.md](spec/SPEC.md), which the site also shows as a +[page](https://4matic.github.io/trackparse/reference/spec/). Tracklists (R13) sit on top of that. The text is split into lines with their terminators, a small scanner reads the time at the start of each line, and the rest goes through the same pipeline in @@ -719,13 +839,24 @@ spaced dashes. The checks run last, over the finished entries. **Docs:** [Ports](https://4matic.github.io/trackparse/project/ports/) -| Language | Package | Status | -|---|---|---| -| JavaScript / TypeScript | [`trackparse`](https://www.npmjs.com/package/trackparse) on npm | reference implementation, 13,130 / 13,130 fixtures, tracklists as `trackparse/tracklist` | -| Python | [`trackparse`](https://pypi.org/project/trackparse/) on PyPI | 13,130 / 13,130 fixtures, output identical to JS, tracklists as `trackparse.tracklist` | -| Rust | [`trackparse`](https://crates.io/crates/trackparse) on crates.io | passes 13,130 / 13,130, output identical to JS, tracklists as `trackparse::tracklist` | +| Language | Package | Needs | README | Changelog | +|---|---|---|---|---| +| JavaScript / TypeScript | [`trackparse`](https://www.npmjs.com/package/trackparse) on npm | Node 18+ or any ES2020 runtime, no dependencies | [js/README.md](js/README.md) | [js/CHANGELOG.md](js/CHANGELOG.md) | +| Python | [`trackparse`](https://pypi.org/project/trackparse/) on PyPI | Python 3.9+, no dependencies | [python/README.md](python/README.md) | [python/CHANGELOG.md](python/CHANGELOG.md) | +| Rust | [`trackparse`](https://crates.io/crates/trackparse) on crates.io ([docs.rs](https://docs.rs/trackparse)) | Rust 1.74+, `unicode-normalization`, optional `serde` feature | [rust/README.md](rust/README.md) | [rust/CHANGELOG.md](rust/CHANGELOG.md) | + +The JavaScript package is the reference implementation. All three pass 13,130 of 13,130 fixtures, +and the Python and Rust output is byte-identical to JavaScript on every fixture input. -Want another language? The porting checklist is in [AGENTS.md](AGENTS.md). +The spec and the three packages share one version number and are released together, so the same +version means the same spec and the same fixtures in every language. The one known difference +outside the fixtures is a +[Unicode version note](https://4matic.github.io/trackparse/project/ports/#what-the-rust-port-taught) for the Rust crate. Changes to the rules and the fixtures are in +[spec/CHANGELOG.md](spec/CHANGELOG.md). + +Want another language? The porting checklist is in +[AGENTS.md](AGENTS.md#porting-guide-rust-others), along with the problems the Python and Rust ports +ran into. ## Compared to other libraries @@ -734,15 +865,15 @@ Want another language? The porting checklist is in [AGENTS.md](AGENTS.md). | | trackparse | [get-artist-title](https://github.com/goto-bus-stop/get-artist-title) | [metadata-filter](https://github.com/web-scrobbler/metadata-filter) | [track_parser](https://rubygems.org/gems/track_parser) | |---|---|---|---|---| | Output | structured object | `[artist, title]` | cleaned strings | artists, feat, remixer | -| Artists as a list with roles | ✅ | – | – | `&` / `and` only | -| Remixers and version types | ✅ 27 types | – | removed | raw remix name | +| Artists as a list with roles | yes | – | – | `&` / `and` only | +| Remixers and version types | 27 types | – | removed | raw remix name | | Noise | returned with a kind | removed | removed | – | -| Cross-language spec | ✅ | – | – | – | +| Cross-language spec | yes | – | – | – | | Last release | 2026 | 2021 | active | 2015 | -These libraries are fine at what they set out to do. If all you need is a clean string to scrobble, -metadata-filter is great. get-artist-title's YouTube test cases helped shape several rules here. -trackparse is for when you need to know who did what. +These libraries do what they set out to do. If all you need is a clean string to scrobble, +metadata-filter is the better fit. get-artist-title's YouTube test cases helped shape several rules +here. trackparse is for when you need to know who did what. ## Limitations @@ -755,27 +886,33 @@ Not there yet: - Times at the end of a line (`Noisia - Stigma [12:34]`) and time ranges (`00:00 - 05:30`). A trailing time stays in the title. In a range only the start is the line's time; the end ends up in `track.timestamp` and nothing checks it. -- Label and catalogue numbers (`[HOSP123]`) as fields. Catalogue numbers stay in the title; only +- Label and catalog numbers (`[HOSP123]`) as fields. Catalog numbers stay in the title; only known label phrases (`[NCS Release]`) land in `junk` as `label`. - Key and BPM (`8A`, `174 BPM`). - An artist database. `Earth, Wind & Fire` splits unless it's in `knownArtists`, and a tracklist doesn't yet learn names from its other lines. - Warnings for gaps or overlaps between consecutive tracklist times. -The browser playground is live at -[4matic.github.io/trackparse/playground](https://4matic.github.io/trackparse/playground/). +These limits are the same in all three packages, since they come from the spec. To see what the +parser does with a string today, paste it into the +[playground](https://4matic.github.io/trackparse/playground/). ## Contributing **Docs:** [Contributing](https://4matic.github.io/trackparse/project/contributing/) -The documentation site lives in [`site/`](site) (Astro + Starlight, `pnpm docs` to run it -locally) and deploys to GitHub Pages on every push to `main`. +The most useful bug report is an input string plus the output you expected, filed as an +[issue](https://github.com/4matic/trackparse/issues). It usually becomes a fixture as is. + +Behaviour changes start in the spec: a rule in [SPEC.md](spec/SPEC.md), a fixture that pins it +([fixture format](spec/fixtures/README.md)), then the code in all three ports (`js/`, `python/`, +`rust/`). A change is done when every port passes every fixture and +`node scripts/compare-ports.mjs` prints `differences: 0`. [AGENTS.md](AGENTS.md) has the repo map, +the workflow and every command. -Behaviour changes start in the spec: a rule in [SPEC.md](spec/SPEC.md), a fixture that pins it, -then the code. [AGENTS.md](AGENTS.md) has the repo map, the workflow and every command. The most -useful bug report is an input string plus the output you expected. It usually becomes a fixture -as is. +The documentation site lives in [`site/`](site) (Astro + Starlight, `pnpm docs` to run it locally) +and deploys to GitHub Pages on every push to `main`. Its examples have JavaScript, Python and Rust +tabs, and a change to behaviour updates them in the same pull request. ## License diff --git a/js/README.md b/js/README.md index 69ca8ea..d5d2a96 100644 --- a/js/README.md +++ b/js/README.md @@ -1,22 +1,34 @@ # trackparse -Parse music track names into structured metadata: artists, featured artists, remixers, version -(remix, extended, live, remaster), producers and a clean title. +[![npm](https://img.shields.io/npm/v/trackparse?logo=npm&logoColor=white)](https://www.npmjs.com/package/trackparse) +[![types](https://img.shields.io/npm/types/trackparse?logo=typescript&logoColor=white)](https://www.npmjs.com/package/trackparse) +[![tests](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/js.yml?branch=main&label=tests&logo=github)](https://github.com/4matic/trackparse/actions/workflows/js.yml) +[![license](https://img.shields.io/badge/license-MIT-blue)](https://github.com/4matic/trackparse/blob/main/LICENSE) -[![npm](https://img.shields.io/npm/v/trackparse.svg)](https://www.npmjs.com/package/trackparse) -[![js](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/js.yml?branch=main&label=js)](https://github.com/4matic/trackparse/actions/workflows/js.yml) -[![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/4matic/trackparse/blob/main/LICENSE) +**[Documentation](https://4matic.github.io/trackparse/)** · **[Getting started](https://4matic.github.io/trackparse/start/getting-started/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** -**[Documentation](https://4matic.github.io/trackparse/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** +**Turn messy track names into structured data: who made it, who's featured, who remixed it, and +what's just noise.** -This is the JavaScript/TypeScript reference implementation of the -[trackparse spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md). It passes all -13,130 shared fixtures. Zero dependencies, ESM and CommonJS, TypeScript types included, never -throws. +```text +01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video] +``` + +Most title parsers split that into `"Wilkinson ft. Becky Hill & Tom Cane"` and +`"Afterglow (Sub Focus VIP Remix)"` and stop. Others "clean" it and throw the feat and the remix +away. trackparse keeps all of it. Everything it recognizes goes into a field, and anything it +doesn't recognize stays in the title, word for word. + +This is the JavaScript and TypeScript package of +[trackparse](https://github.com/4matic/trackparse), and the reference implementation. Its behaviour +is defined by a [shared spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md) and +pinned by 13,130 fixtures. It passes all of them, and the +[Python and Rust packages](#other-languages) return the same output for every one. -The principle is **extract, don't delete**: everything recognised lands in a field (artists with -roles, versions with a type and their own credits, junk with a kind, flags, position), and -everything else stays in the title verbatim. +- Node 18 or later, browsers and other runtimes (no Node-specific APIs) +- No dependencies +- ESM and CommonJS, TypeScript types included +- Never throws ## Install @@ -25,15 +37,13 @@ npm install trackparse # or: pnpm add trackparse / yarn add trackparse / bun add trackparse ``` -Node 18 or later. No Node-specific APIs are used, so it also runs in browsers and other runtimes. - ## Quick start **Docs:** [Getting started](https://4matic.github.io/trackparse/start/getting-started/) ```js -import { parse } from "trackparse"; -// const { parse } = require("trackparse"); +import { format, parse } from "trackparse"; +// const { format, parse } = require("trackparse"); const track = parse( "01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video]", @@ -48,24 +58,184 @@ track.versions[0].artists[0].name; // 'Sub Focus' track.versions[0].modifiers; // [ 'vip' ] track.junk; // [ { raw: 'Official Video', kind: 'video' } ] track.position; // { raw: '01', number: 1 } -track.mode; // 'youtube' (auto-detected from the junk group) +track.mode; // 'youtube' (detected from the junk group) + +format(track, { joiners: "canonical" }); +// 'Wilkinson feat. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix)' +``` + +The result is a plain object, so `JSON.stringify(track)` gives the spec's JSON form. Every key is +always present: + +```js +console.log(JSON.stringify(track, null, 2)); ``` +
+Output + +```json +{ + "input": "01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video]", + "mode": "youtube", + "position": { "raw": "01", "number": 1 }, + "timestamp": null, + "artists": [ + { "name": "Wilkinson", "role": "primary", "joiner": null, "source": "artist" }, + { "name": "Becky Hill", "role": "featured", "joiner": "ft.", "source": "artist" }, + { "name": "Tom Cane", "role": "featured", "joiner": "&", "source": "artist" } + ], + "title": "Afterglow", + "fullTitle": "Afterglow (Sub Focus VIP Remix)", + "versions": [ + { + "type": "remix", + "raw": "Sub Focus VIP Remix", + "artists": [{ "name": "Sub Focus", "role": "remixer", "joiner": null, "source": "version" }], + "modifiers": ["vip"], + "descriptor": null, + "year": null, + "unknownArtist": false, + "delimiter": "(" + } + ], + "year": null, + "flags": { "explicit": false, "clean": false, "unknownArtist": false, "unknownTitle": false }, + "junk": [{ "raw": "Official Video", "kind": "video" }], + "warnings": [] +} +``` + +(Reformatted for width; the keys and values are exactly what `JSON.stringify` prints.) + +
+ ## API **Docs:** [parse and ParsedTrack](https://4matic.github.io/trackparse/reference/parse/) · [Other functions](https://4matic.github.io/trackparse/reference/functions/) -### `parse(input, options?) → ParsedTrack` +```ts +parse(input: string, options?: ParseOptions): ParsedTrack +parseArtists(input: string, options?: ParseOptions): Artist[] +format(track: ParsedTrack, options?: FormatOptions): string +normalize(input: string): string +allArtists(track: ParsedTrack): Artist[] +createParser(options?: ParseOptions): Parser // parser.parse(...), parser.parseArtists(...) +SPEC_VERSION: string + +// from "trackparse/tracklist" +parseTracklist(text: string, options?: TracklistOptions): Tracklist +applyEdits(text: string, edits: Edit[], options?: TracklistOptions): EditResult +``` -Parses one track string. Every key of the result is always present. +### `parse(input, options?)` -### `parseArtists(input, options?) → Artist[]` +**Docs:** [parse and ParsedTrack](https://4matic.github.io/trackparse/reference/parse/) · [Options](https://4matic.github.io/trackparse/reference/options/) -**Docs:** [parseArtists](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options) +Parses one track string. -Splits an artist string (no title) into credits. +| Option | Default | | +|---|---|---| +| `mode` | `"auto"` | `"clean"`, `"youtube"`, `"filename"`, `"tracklist"`, or `"auto"` to detect from the string. See [Modes](#modes) | +| `uploader` | – | YouTube channel name, used as the artist when there's no separator (`- Topic` and `VEVO` are dropped) | +| `knownArtists` | `[]` | Names that are never split. There is no built-in list | +| `splitAnd` | `"auto"` | `"auto"` splits on `and` only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole. Also `"always"`, `"never"` | +| `keywords` | – | Extra vocabulary, added to the built-in lists (see below) | ```js +parse("Chase & Status - Baddadan").artists.map((a) => a.name); +// [ 'Chase', 'Status' ] +parse("Chase & Status - Baddadan", { knownArtists: ["Chase & Status"] }).artists.map((a) => a.name); +// [ 'Chase & Status' ] + +parse("Simon and Garfunkel - Mrs. Robinson", { splitAnd: "always" }).artists.map((a) => a.name); +// [ 'Simon', 'Garfunkel' ] +``` + +`keywords` is an object with any of these keys: + +| Key | Type | | +|---|---|---| +| `versionHeads` | `Record` | Word that sets a version type (`{ rerub: "rework" }`) | +| `descriptors` | `string[]` | Words kept as a version's `descriptor` | +| `genres` | `string[]` | Genre words | +| `junk` | `Record` | Phrase to junk kind (`{ "some label rip": "label" }`) | +| `featMarkers` | `string[]` | Extra feat markers | + +```js +parse("Artist - Song [Some Label Rip]").title; +// 'Song [Some Label Rip]' +parse("Artist - Song [Some Label Rip]", { keywords: { junk: { "some label rip": "label" } } }).junk; +// [ { raw: 'Some Label Rip', kind: 'label' } ] +``` + +### `ParsedTrack` + +**Docs:** [ParsedTrack fields](https://4matic.github.io/trackparse/reference/parse/#parsedtrack) + +```ts +interface ParsedTrack { + input: string; // the original string, untouched + mode: "clean" | "youtube" | "filename" | "tracklist"; // resolved mode + position: { raw: string; number: number } | null; // track number: "01." gives 1 + timestamp: { raw: string; seconds: number } | null; // leading cue time: "[12:34]" gives 754 + artists: Artist[]; // primary, featured and producer credits (not remixers) + title: string; // clean title; brackets it doesn't recognize stay in + fullTitle: string; // title with the versions re-attached + versions: Version[]; // remixes and other versions, left to right + year: number | null; // from "(2015)" or "- 2015" + flags: { explicit: boolean; clean: boolean; unknownArtist: boolean; unknownTitle: boolean }; + junk: { raw: string; kind: JunkKind }[]; // what was taken out, each with a kind + warnings: Warning[]; // heuristics that fired +} + +interface Artist { + name: string; + role: "primary" | "featured" | "remixer" | "producer"; + joiner: string | null; // "&", ",", "x", "ft.", "prod. by" as written; null for the first name + source: "artist" | "title" | "version"; // left of the dash, right of it, or inside a version +} + +interface Version { + type: VersionType; // remix, vip, bootleg, extended, radio, live, remaster... + raw: string; // "Sub Focus VIP Remix" + artists: Artist[]; // remixers + modifiers: string[]; // type words that didn't become the type: ["vip"] + descriptor: string | null; // leftover words: "Taylor's", "at Wembley" + year: number | null; + unknownArtist: boolean; // "ID Remix" + delimiter: "(" | "[" | "{" | "-"; // the bracket it was in, or "-" for a dash suffix +} +``` + +```js +parse("Pendulum - Watercolour (Extended VIP Mix)").versions[0]; +// { type: 'vip', raw: 'Extended VIP Mix', artists: [], modifiers: [ 'extended' ], +// descriptor: null, year: null, unknownArtist: false, delimiter: '(' } + +parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)").versions[0]; +// { type: 'live', raw: 'Live at Wembley 1986', artists: [], modifiers: [], +// descriptor: 'at Wembley', year: 1986, unknownArtist: false, delimiter: '(' } +``` + +- `VersionType`: `remix`, `bootleg`, `vip`, `edit`, `flip`, `refix`, `rework`, `mashup`, `blend`, + `dub`, `mix`, `extended`, `radio`, `club`, `original`, `instrumental`, `acapella`, `live`, + `acoustic`, `remaster`, `demo`, `reprise`, `cover`, `version`, `spedUp`, `slowed`, `nightcore`. +- `JunkKind`: `video`, `audio`, `lyrics`, `quality`, `promo`, `platform`, `label`, `genre`, `other`. +- `Warning`: see [Warnings](#warnings). + +The same shape is published as a JSON Schema, +[`parsed-track.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/parsed-track.schema.json). + +### `parseArtists(input, options?)` + +**Docs:** [parseArtists](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options) · [Artists and credits](https://4matic.github.io/trackparse/guides/artists/) + +Splits a bare artist string (no title). Takes the same options as `parse`. + +```js +import { parseArtists } from "trackparse"; + parseArtists("Sub Focus, Wilkinson & Dimension feat. Kojo"); // [ // { name: 'Sub Focus', role: 'primary', joiner: null, source: 'artist' }, @@ -75,60 +245,72 @@ parseArtists("Sub Focus, Wilkinson & Dimension feat. Kojo"); // ] ``` -### `format(track, options?) → string` +### `format(track, options?)` **Docs:** [format](https://4matic.github.io/trackparse/reference/functions/#formattrack-options) · [Formatting](https://4matic.github.io/trackparse/guides/formatting/) -Renders a `ParsedTrack` back to `Artists - Title (versions) (prod. ...)`. +Renders a `ParsedTrack` back to a string: `Artists - Title (versions) (prod. ...)`. + +| Option | Default | | +|---|---|---| +| `feat` | `"source"` | Where featured artists go: `"source"` (where they were), `"artist"`, `"title"` (`(feat. X)` after the title) or `"omit"` | +| `featMarker` | – | Marker for featured artists, such as `"featuring"` | +| `joiners` | `"original"` | `"original"` keeps the joiners as written. `"canonical"` writes `and` as `&`, `vs` as `vs.` and every feat marker as `feat.` | +| `versions` | `"all"` | `"all"` or `"none"` | +| `producers` | `true` | Include `(prod. ...)` credits | +| `position` | `false` | Include the track number (`01. `) | ```js +import { format, parse } from "trackparse"; + const t = parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)"); format(t); // 'Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)' format(t, { feat: "title", joiners: "canonical" }); // 'Wilkinson - Afterglow (feat. Becky Hill) (Sub Focus Remix)' format(t, { feat: "omit", versions: "none" }); // 'Wilkinson - Afterglow' +format(t, { featMarker: "featuring" }); // 'Wilkinson featuring Becky Hill - Afterglow (Sub Focus Remix)' ``` -| Option | Default | Effect | -|---|---|---| -| `feat` | `"source"` | `"source"` (where they were found), `"artist"`, `"title"` (`(feat. X)` after the title) or `"omit"`. | -| `featMarker` | – | Override the feat marker (`"featuring"`). | -| `joiners` | `"original"` | `"canonical"`: `and` → `&`, `vs` → `vs.`, feat markers → `feat.`. | -| `versions` | `"all"` | `"none"` drops versions. | -| `producers` | `true` | Append `(prod. by X)`. | -| `position` | `false` | Prefix the track number (`01. `). | - -### `normalize(input) → string` +### `normalize(input)` **Docs:** [normalize](https://4matic.github.io/trackparse/reference/functions/#normalizeinput) -The Unicode cleanup applied before parsing: NFC, zero-width spaces, BOM and soft hyphens removed, fullwidth -brackets, smart quotes and dash variants mapped to ASCII, whitespace collapsed. Idempotent. +The Unicode cleanup every function runs first: NFC, zero-width spaces, BOM and soft hyphens +removed, fullwidth brackets, smart quotes and dash variants mapped to ASCII, whitespace collapsed. +Running it twice changes nothing. ```js -normalize(" Artist​ — Title (Remix) “Quoted” "); +import { normalize } from "trackparse"; + +normalize(" Artist\u200b — Title (Remix) “Quoted” "); // 'Artist - Title (Remix) "Quoted"' ``` -### `allArtists(track) → Artist[]` +### `allArtists(track)` **Docs:** [allArtists](https://4matic.github.io/trackparse/reference/functions/#allartiststrack) -Track credits plus every version's remixers, deduplicated. +Credits plus every remixer, deduplicated. ```js -allArtists(parse("Camo & Krooked - Kallisto (Noisia Remix)", { knownArtists: ["Camo & Krooked"] })) +import { allArtists, parse } from "trackparse"; + +allArtists(parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)")) .map((a) => `${a.name} (${a.role})`); -// [ 'Camo & Krooked (primary)', 'Noisia (remixer)' ] +// [ 'Wilkinson (primary)', 'Becky Hill (featured)', 'Sub Focus (remixer)' ] ``` -### `createParser(options) → { parse, parseArtists }` +### `createParser(options?)` **Docs:** [createParser](https://4matic.github.io/trackparse/reference/functions/#createparseroptions) -Compiles options, including extra vocabulary, once. Per-call options are merged over the base. +Compiles the options once, for many calls. Per-call options are merged over the parser's: a value +passed per call replaces the base one (`knownArtists` included), `undefined` leaves it alone, and +`keywords` objects are merged. ```js +import { createParser } from "trackparse"; + const parser = createParser({ knownArtists: ["Chase & Status", "Camo & Krooked"], keywords: { versionHeads: { rerub: "rework" }, junk: { "full album": "other" } }, @@ -143,92 +325,75 @@ r.junk; // [ { raw: 'Full Album', kind: 'other' } ] ### `SPEC_VERSION` -The spec version this build implements, e.g. `"0.3.0"`. Always equal to the package version. +The spec version this build implements, `"0.5.0"` in this release. The npm package, the PyPI +package, the Rust crate and the spec are released together and always share one version number. -## Options +## Modes -**Docs:** [Options](https://4matic.github.io/trackparse/reference/options/) +**Docs:** [Modes](https://4matic.github.io/trackparse/guides/modes/) -| Option | Default | Effect | +| Mode | For | Adds | |---|---|---| -| `mode` | `"auto"` | `"clean"` (tags, store metadata), `"youtube"` (video titles), `"filename"`, `"tracklist"` (one line of a tracklist), or `"auto"` to detect. | -| `uploader` | – | YouTube channel, used as the artist when no separator is found. ` - Topic` and `VEVO` are stripped. | -| `knownArtists` | `[]` | Names never split (`Chase & Status`). There is no built-in list. | -| `splitAnd` | `"auto"` | `and` splits only after a comma in the same list (`A, B and C`), so `Simon and Garfunkel` stays one. `"always"` / `"never"`. | -| `keywords` | – | Extra vocabulary: `versionHeads`, `descriptors`, `genres`, `junk`, `featMarkers`. | +| `clean` | Store metadata, tags | Only a spaced dash separates artist and title | +| `youtube` | Video titles, scrobbles | Pipe segments, `"Title" by Artist`, `Artist: "Title"`, unspaced dashes, trailing junk, uploader fallback | +| `filename` | Files | Strips the extension, `_` becomes a space, `01-Track` numbering | +| `auto` | Anything | `filename` for known extensions, `youtube` when it sees junk, pipes or platform suffixes, `clean` otherwise | +| `tracklist` | One line of a tracklist | The first spaced dash always separates; `_-_` too. Never picked by `auto` | ```js -parse("Chase & Status - Blind Faith (Loadstar Remix)").artists.map((a) => a.name); -// [ 'Chase', 'Status' ] -parse("Chase & Status - Blind Faith (Loadstar Remix)", { knownArtists: ["Chase & Status"] }) - .artists.map((a) => a.name); -// [ 'Chase & Status' ] +let t = parse('"Numb" by Linkin Park', { mode: "youtube" }); +[t.artists.map((a) => a.name), t.title, t.warnings]; +// [ [ 'Linkin Park' ], 'Numb', [ 'bySplit' ] ] + +t = parse("07_Burial_-_Archangel.mp3"); +[t.mode, t.artists.map((a) => a.name), t.title, t.position]; +// [ 'filename', [ 'Burial' ], 'Archangel', { raw: '07', number: 7 } ] -parse("Jay-Z-Numb").title; // 'Jay-Z-Numb' (clean: no split) +parse("Shelter", { mode: "youtube", uploader: "Porter Robinson" }).artists; +// [ { name: 'Porter Robinson', role: 'primary', joiner: null, source: 'artist' } ] + +parse("Jay-Z-Numb").title; // 'Jay-Z-Numb' (clean: no split) parse("Jay-Z-Numb", { mode: "youtube" }).artists.map((a) => a.name); // [ 'Jay-Z' ] ``` -## Output types +## Warnings -All types are exported (`import type { ParsedTrack } from "trackparse"`). +**Docs:** [Warnings](https://4matic.github.io/trackparse/reference/warnings/) -```ts -interface ParsedTrack { - input: string; // original, untouched - mode: "clean" | "youtube" | "filename" | "tracklist"; // resolved mode - position: { raw: string; number: number } | null; - timestamp: { raw: string; seconds: number } | null; - artists: Artist[]; // primary, featured, producer (not remixers) - title: string; // clean title - fullTitle: string; // title + versions with their brackets - versions: Version[]; - year: number | null; - flags: { explicit: boolean; clean: boolean; unknownArtist: boolean; unknownTitle: boolean }; - junk: { raw: string; kind: JunkKind }[]; - warnings: Warning[]; -} +The parser never fails, but it says when it had to guess. `track.warnings` is an array of strings, +empty when every decision was unambiguous. -interface Artist { - name: string; - role: "primary" | "featured" | "remixer" | "producer"; - joiner: string | null; // "&", ",", "x", "ft.", "prod. by"... as written - source: "artist" | "title" | "version"; -} +| Warning | Means | +|---|---| +| `noSeparator` | No artist/title separator was found. The whole string is the title | +| `ambiguousSeparator` | A two-part pipe title with no dash was read as artist and title | +| `unspacedDashSplit` | Split at a dash without spaces around it | +| `asymmetricDashSplit` | Split at a dash with a space on one side only | +| `bySplit` | Read `"Title" by Artist` | +| `quotedTitleSplit` | Took a quoted span as the title and the text before it as the artist | +| `ambiguousMixCredit` | ` Mix` was read as a remix, but the name is long enough to be a style | +| `unbalancedBrackets` | A bracket was opened and never closed | -interface Version { - type: VersionType; // remix, vip, bootleg, extended, radio, live, remaster... - raw: string; // "Sub Focus VIP Remix" - artists: Artist[]; // remixers - modifiers: string[]; // ["vip"] - descriptor: string | null; // "Taylor's", "at Wembley", genres - year: number | null; - unknownArtist: boolean; // "ID Remix" - delimiter: "(" | "[" | "{" | "-"; -} -``` +```js +const t = parse("Around the World"); +[t.artists, t.title, t.warnings]; +// [ [], 'Around the World', [ 'noSeparator' ] ] -- `VersionType`: `remix`, `bootleg`, `vip`, `edit`, `flip`, `refix`, `rework`, `mashup`, `blend`, - `dub`, `mix`, `extended`, `radio`, `club`, `original`, `instrumental`, `acapella`, `live`, - `acoustic`, `remaster`, `demo`, `reprise`, `cover`, `version`, `spedUp`, `slowed`, `nightcore`. -- `JunkKind`: `video`, `audio`, `lyrics`, `quality`, `promo`, `platform`, `label`, `genre`, `other`. -- `Warning`: `noSeparator`, `ambiguousSeparator`, `unspacedDashSplit`, `asymmetricDashSplit`, - `bySplit`, `quotedTitleSplit`, `ambiguousMixCredit`, `unbalancedBrackets`. +parse("Noisia - Stigma (VIP").warnings; +// [ 'unbalancedBrackets' ] +``` -The full field reference, a gallery of examples and the comparison with other libraries are in the -[documentation](https://4matic.github.io/trackparse/): [`parse` and ParsedTrack](https://4matic.github.io/trackparse/reference/parse/), -[options](https://4matic.github.io/trackparse/reference/options/), [warnings](https://4matic.github.io/trackparse/reference/warnings/), -[what it understands](https://4matic.github.io/trackparse/guides/what-it-understands/). Exact behaviour is defined by the -[spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md) and its -[fixtures](https://github.com/4matic/trackparse/tree/main/spec/fixtures). +Tracklists have their own warnings, with line numbers. They are listed under +[Tracklists](#tracklists). ## Tracklists -**Docs:** [Tracklists](https://4matic.github.io/trackparse/guides/tracklists/) · [Editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/) +**Docs:** [Tracklists](https://4matic.github.io/trackparse/guides/tracklists/) · [Editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/) · [Tracklist API](https://4matic.github.io/trackparse/reference/tracklist/) · [Warnings](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings) -`trackparse/tracklist` parses a whole tracklist: one entry per line with its kind, start time and -a full `ParsedTrack`, plus checks with line numbers. Joining `raw + eol` over the entries gives the -input back byte for byte, whatever the line endings. It's a separate entry point (about 8.3 KiB -gzipped), so you only pay for it if you import it. +`trackparse/tracklist` parses a whole tracklist, one entry per line, and checks it. Each entry +keeps its line exactly as written plus its own line ending, so +`list.entries.map((e) => e.raw + e.eol).join("")` is always the input, CRLF or not. It is a +separate entry point (about 8.4 KiB gzipped), so you only load it if you import it. ```js import { applyEdits, parseTracklist } from "trackparse/tracklist"; @@ -250,9 +415,14 @@ const list = parseTracklist(text); list.entries.map((e) => e.kind); // [ 'header', 'track', 'track', 'track', 'track', 'marker', 'track', 'track', 'track' ] -list.entries[2].time; // { raw: '52:47', seconds: 3167 } -list.entries[2].track.versions[0].type; // 'remix' -list.entries[3].track.flags.unknownTitle; // true + +const e = list.entries[2]; +e.time; // { raw: '52:47', seconds: 3167 } +e.parts; +// { lead: '', time: '52:47', gap: ' ', rest: 'Mefjus & Kasra - Bandwagon (Phace Remix)' } +[e.track.artists.map((a) => a.name), e.track.title, e.track.versions[0].type]; +// [ [ 'Mefjus', 'Kasra' ], 'Bandwagon', 'remix' ] +list.entries[3].track.flags.unknownTitle; // true (the ID) list.warnings; // [ @@ -260,12 +430,15 @@ list.warnings; // { code: 'time-out-of-order', line: 8, severity: 'warning', // suggestion: { line: 8, raw: '01:11:02', seconds: 4262 } } // ] + list.stats; // { lines: 9, tracks: 7, markers: 1, timed: 8, firstTime: 2900, lastTime: 4536 } ``` -`applyEdits` rewrites only the lines you name. Times keep their line's style, and the rest of the -text, CRLF included, stays as it was: +The suggestion exists because exactly one time, one digit away from `00:11:02`, fits between its +neighbours. With several candidates or none, `suggestion` is `null`. + +`applyEdits` takes an array of edit objects and only rewrites the lines they name: ```js const fix = list.warnings[1].suggestion; @@ -274,20 +447,38 @@ const result = applyEdits(text, [ { op: "shift", seconds: 45, from: 5 }, ]); -result.changed; // [ 5, 6, 7, 8, 9 ] -result.warnings; // [ { code: 'style-upgraded', edit: 1, line: 5 } ] -result.text.split("\r\n")[4]; // '01:00:16 Alix Perez - Fade Away' (was 59:31) +result.changed; // [ 5, 6, 7, 8, 9 ] +result.warnings; // [ { code: 'style-upgraded', edit: 1, line: 5 } ] +result.text.split("\r\n")[4]; // '01:00:16 Alix Perez - Fade Away' (was 59:31) + +applyEdits(text, [{ op: "shift", seconds: -3000, lines: [2, 3] }]).warnings; +// [ { code: 'time-clamped', edit: 0, line: 2 } ] ``` -Edits: `set-time {line, seconds}`, `shift {seconds, lines? | from?}` -(all timed lines when neither is given), `sort-by-time {}`, `set-rest {line, rest}`, -`insert {after, text}` (`after: 0` inserts at the top), `delete {line}`. -A bad edit changes nothing and warns `edit-invalid`; a time pushed below zero stops at zero and -warns `time-clamped`. +A rewritten time keeps its line's style: `52:47` stays `MM:SS`, and a time that crosses the hour +gets hours like the rest of the list, with a `style-upgraded` warning. A time pushed below zero +stops at zero and warns `time-clamped`. A bad edit changes nothing and warns `edit-invalid`. + +Both functions take the options `mode` (default `"tracklist"`), `knownArtists`, `splitAnd` and +`keywords`, as `parse` does, plus `audioSeconds` (the length of the audio, which turns on the +`time-after-audio-end` check) and `markerWords` (extra words that make a line a marker): + +```js +parseTracklist("00:00 Noisia - Stigma\n1:02:03 Mefjus - Suicide Bassline", { audioSeconds: 3600 }) + .warnings; +// [ { code: 'time-after-audio-end', line: 2, severity: 'warning', suggestion: null } ] +``` -Warning codes: `time-missing`, `time-out-of-order` (with a one- or two-digit `suggestion` when -exactly one fix fits), `time-duplicate`, `no-start-at-zero`, `time-after-audio-end` (pass -`audioSeconds`), `invalid-time`, `position-gap`, `position-duplicate`, `line-unparsed`. +| Result | Fields | +|---|---| +| `Tracklist` | `specVersion`, `entries`, `warnings`, `stats` | +| `TracklistEntry` | `line` (1-based), `kind` (`track`, `marker`, `header`, `link`, `note`, `blank`), `eol`, `raw`, `parts`, `time`, `track` (`ParsedTrack` or `null`), `layered` (the track text after any time starts with `w/`) | +| `EntryParts` | `lead`, `time`, `gap`, `rest`, joined they give `raw` | +| `TracklistWarning` | `code`, `line`, `severity` (`info` or `warning`), `suggestion` | +| `TracklistTime` | `raw`, `seconds` (`entry.time`, or `null` on untimed lines) | +| `TimeSuggestion` | `line`, `raw`, `seconds` (`warning.suggestion`, or `null`) | +| `TracklistStats` | `lines`, `tracks`, `markers`, `timed`, `firstTime`, `lastTime` | +| `EditResult` | `text`, `changed`, `warnings` (`EditWarning`: `code`, `edit`, `line`) | Lists pasted with list bullets or Markdown emphasis (`* 14:21 Artist - Title`, `**[**14:21**] Artist - Title**`) read like plain lines; the decoration stays in `raw` and `parts`. @@ -296,29 +487,133 @@ previous one ([Markdown](https://4matic.github.io/trackparse/guides/tracklists/#markdown), [layered tracks](https://4matic.github.io/trackparse/guides/tracklists/#layered-tracks)). -Options: `mode` (default `"tracklist"`), `knownArtists`, `splitAnd`, `keywords`, `audioSeconds`, -`markerWords`. Every type is exported (`import type { Tracklist, Edit } from -"trackparse/tracklist"`). +Warning codes: `time-missing`, `time-out-of-order`, `time-duplicate`, `no-start-at-zero`, +`time-after-audio-end` (needs `audioSeconds`), `invalid-time`, `position-gap`, +`position-duplicate`, `line-unparsed`. Edits: `set-time {line, seconds}`, +`shift {seconds, lines? | from?}` (all timed lines when neither is given), `sort-by-time {}`, +`set-rest {line, rest}`, `insert {after, text}` (`after: 0` inserts at the top), `delete {line}`. +The [Tracklist API reference](https://4matic.github.io/trackparse/reference/tracklist/) explains +each one, and the rules are in +[SPEC R13](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md#r13-tracklists). +`JSON.stringify(list)` matches +[`tracklist.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/tracklist.schema.json). -Each line is parsed with `mode: "tracklist"`, where the first spaced dash always separates artist -and title. `parse()` takes it too: +Every line is parsed with `mode: "tracklist"`, where the first spaced dash always separates artist +and title. `parse()` accepts it too: ```js -parse("Electrosoul System - Liquid Metal").title; // 'Electrosoul System' -parse("Electrosoul System - Liquid Metal", { mode: "tracklist" }).title; // 'Liquid Metal' +parse("Electrosoul System - Liquid Metal").junk; +// [ { raw: 'Liquid Metal', kind: 'genre' } ] +parse("Electrosoul System - Liquid Metal", { mode: "tracklist" }).title; +// 'Liquid Metal' ``` -Field tables and the full list of rules: the [tracklists guide](https://4matic.github.io/trackparse/guides/tracklists/), the -[Tracklist API](https://4matic.github.io/trackparse/reference/tracklist/) and [SPEC R13](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md#r13-tracklists). +## Errors + +No function throws. `parse` returns a complete `ParsedTrack` for any string, `""` included, and a +value that isn't a string is read as `""`. An option of the wrong type or with an unknown value is +ignored and the default is used. `applyEdits` reports a bad edit as an `edit-invalid` warning and +leaves the text alone. + +Recognition is done by hand-written scanners, so there is no regex backtracking. A +10,000-code-point input finishes in under 100 ms. + +## TypeScript + +**Docs:** [Types](https://4matic.github.io/trackparse/reference/parse/#types) · [Tracklist types](https://4matic.github.io/trackparse/reference/tracklist/#types) + +The types ship with the package for both ESM and CommonJS. Nothing else needs installing. + +```ts +import type { Artist, ParsedTrack, ParseOptions, VersionType } from "trackparse"; +import type { Edit, Tracklist, TracklistWarning } from "trackparse/tracklist"; +``` + +- `trackparse` exports `ParsedTrack`, `Artist`, `ArtistRole`, `ArtistSource`, `Version`, + `VersionType`, `VersionDelimiter`, `Junk`, `JunkKind`, `Flags`, `Position`, `Timestamp`, + `Warning`, `Mode`, `ModeOption`, `ParseOptions`, `KeywordOptions`, `FormatOptions` and `Parser`. +- `trackparse/tracklist` exports `Tracklist`, `TracklistEntry`, `EntryKind`, `EntryParts`, `Eol`, + `TracklistTime`, `TracklistWarning`, `TracklistWarningCode`, `TimeSuggestion`, `TracklistStats`, + `TracklistOptions`, `Edit`, `EditResult`, `EditWarning` and `EditWarningCode`. + +Version types, junk kinds, warnings and edit operations are string literal unions, so the compiler +catches a misspelt name. + +## How it is tested + +**Docs:** [How it's tested](https://4matic.github.io/trackparse/project/testing/) + +- 13,130 shared fixtures: 1,203 written by hand and 11,927 generated from the rules. Every output + is also validated against the JSON Schema. +- Property tests with [fast-check](https://github.com/dubzzz/fast-check) for the spec's invariants: + no throw on any input, `normalize` is idempotent, whitespace and dash noise doesn't change the + result, and `parse(format(parse(s)))` round-trips. +- The published build is run against every fixture on Node 18 and 20, as ESM and as CommonJS. +- [`compare-ports.mjs`](https://github.com/4matic/trackparse/blob/main/scripts/compare-ports.mjs) + runs every fixture input through this package, the Python package and the Rust crate and diffs + the complete JSON output. The difference count is zero. + +## Versioning + +**Changelog:** [js/CHANGELOG.md](https://github.com/4matic/trackparse/blob/main/js/CHANGELOG.md) + +The package version is the spec version (`SPEC_VERSION`). While it is 0.x, a release that changes +the output for some input bumps the minor version, and a patch release only fixes bugs. If you +store parsed results, pin the minor version (`"trackparse": "~0.5.0"`) and read the changelog +before moving up. + +## Other languages + +**Docs:** [Ports](https://4matic.github.io/trackparse/project/ports/) + +The same parser exists for Python and Rust. All three implement one spec, pass the same fixtures, +are released together under one version number, and return identical JSON for every fixture input. +You can parse in one language and read the result in another. + +| Language | Package | Install | +|---|---|---| +| JavaScript / TypeScript | [trackparse on npm](https://www.npmjs.com/package/trackparse) | `npm install trackparse` | +| Python | [trackparse on PyPI](https://pypi.org/project/trackparse/) | `pip install trackparse` | +| Rust | [trackparse on crates.io](https://crates.io/crates/trackparse) | `cargo add trackparse` | ## Limitations **Docs:** [Limitations and roadmap](https://4matic.github.io/trackparse/project/roadmap/) -One track string per `parse()` call; tracklists go through `trackparse/tracklist`, which reads -start times only (no durations, trailing times or ranges). No label/catalog, key or BPM fields, and -no built-in artist database: pass `knownArtists` for names that contain a joiner. +- `parse()` takes one track string. Whole tracklists go through `trackparse/tracklist`, which reads + start times only: no durations, trailing times or time ranges. +- Catalog numbers, key and BPM are not fields. They stay in the title. +- There is no artist database. Pass `knownArtists` for names that contain a joiner + (`Earth, Wind & Fire`). + +## Development + +From the root of the [repository](https://github.com/4matic/trackparse), with Node 22 or later and +[pnpm](https://pnpm.io/): + +```sh +pnpm install +pnpm --filter trackparse test # every shared fixture, properties, API +pnpm --filter trackparse typecheck +pnpm lint # Biome +pnpm --filter trackparse conformance # pass rate per fixture file and per rule +pnpm --filter trackparse build # js/dist, ESM and CommonJS +``` + +The Python and Rust ports mirror this package's modules one to one. Behaviour changes start in the +spec, not here: see [AGENTS.md](https://github.com/4matic/trackparse/blob/main/AGENTS.md). + +## Links + +- [Documentation](https://4matic.github.io/trackparse/), with every example in JavaScript, Python + and Rust, and a [playground](https://4matic.github.io/trackparse/playground/) that runs the + parser in your browser +- [Spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md) +- [Changelog](https://github.com/4matic/trackparse/blob/main/js/CHANGELOG.md) +- [Project README](https://github.com/4matic/trackparse#readme) +- [GitHub repository](https://github.com/4matic/trackparse) +- [PyPI package](https://pypi.org/project/trackparse/) · [Rust crate](https://crates.io/crates/trackparse) ## License -MIT © Maksim Maksimov +[MIT](https://github.com/4matic/trackparse/blob/main/LICENSE) diff --git a/python/README.md b/python/README.md index c0fbb7e..94edc2b 100644 --- a/python/README.md +++ b/python/README.md @@ -1,8 +1,8 @@ # trackparse -[![PyPI](https://img.shields.io/pypi/v/trackparse?color=3775a9&logo=pypi&logoColor=white)](https://pypi.org/project/trackparse/) +[![PyPI](https://img.shields.io/pypi/v/trackparse?logo=pypi&logoColor=white)](https://pypi.org/project/trackparse/) [![Python versions](https://img.shields.io/pypi/pyversions/trackparse?logo=python&logoColor=white)](https://pypi.org/project/trackparse/) -[![python](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/python.yml?branch=main&label=tests&logo=github)](https://github.com/4matic/trackparse/actions/workflows/python.yml) +[![tests](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/python.yml?branch=main&label=tests&logo=github)](https://github.com/4matic/trackparse/actions/workflows/python.yml) [![license](https://img.shields.io/badge/license-MIT-blue)](https://github.com/4matic/trackparse/blob/main/LICENSE) **[Documentation](https://4matic.github.io/trackparse/)** · **[Getting started](https://4matic.github.io/trackparse/start/getting-started/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** @@ -16,18 +16,18 @@ what's just noise.** Most title parsers split that into `"Wilkinson ft. Becky Hill & Tom Cane"` and `"Afterglow (Sub Focus VIP Remix)"` and stop. Others "clean" it and throw the feat and the remix -away. trackparse keeps all of it. Everything it recognises goes into a field, and anything it -doesn't recognise stays in the title, word for word. +away. trackparse keeps all of it. Everything it recognizes goes into a field, and anything it +doesn't recognize stays in the title, word for word. This is the Python port of [trackparse](https://github.com/4matic/trackparse). Its behaviour is defined by a [shared spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md) and pinned by 13,130 fixtures. It passes all of them, and for every fixture input its output is byte-identical -to the JavaScript package. +to the [JavaScript and Rust packages](#other-languages). - Python 3.9 to 3.14 - No dependencies - Typed (`py.typed`), immutable results -- Never raises on string input +- Never raises on `str` input ## Install @@ -123,6 +123,11 @@ normalize(s) -> str all_artists(track) -> list[Artist] create_parser(**options) -> Parser # Parser.parse(...), Parser.parse_artists(...) SPEC_VERSION, __version__ + +# from trackparse.tracklist +parse_tracklist(text, *, mode="tracklist", known_artists=(), keywords=None, split_and="auto", + audio_seconds=None, marker_words=()) -> Tracklist +apply_edits(text, edits, *, ) -> EditResult ``` ### `parse(input, **options)` @@ -131,7 +136,7 @@ SPEC_VERSION, __version__ | Option | Default | | |---|---|---| -| `mode` | `"auto"` | `"clean"`, `"youtube"`, `"filename"`, `"tracklist"`, or `"auto"` to detect from the string | +| `mode` | `"auto"` | `"clean"`, `"youtube"`, `"filename"`, `"tracklist"`, or `"auto"` to detect from the string. See [Modes](#modes) | | `uploader` | `None` | YouTube channel name, used as the artist when there's no separator (`- Topic` and `VEVO` are dropped) | | `known_artists` | `()` | Names that are never split. There is no built-in list | | `split_and` | `"auto"` | `"auto"` splits on `and` only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole. Also `"always"`, `"never"` | @@ -164,9 +169,6 @@ parse("Artist - Song [Some Label Rip]", keywords={"junk": {"some label rip": "la # (Junk(raw='Some Label Rip', kind='label'),) ``` -Parsing is total: any `str` gives a `ParsedTrack`, including `""`. Bad option values fall back to -the defaults. Passing something that isn't a `str` raises `TypeError`. - ### `ParsedTrack` **Docs:** [ParsedTrack fields](https://4matic.github.io/trackparse/reference/parse/#parsedtrack) @@ -178,7 +180,7 @@ the defaults. Passing something that isn't a `str` raises `TypeError`. | `position` | `Position \| None` | Track number: `Position(raw='01', number=1)` | | `timestamp` | `Timestamp \| None` | Leading cue time: `[12:34]` gives `Timestamp(raw='12:34', seconds=754)` | | `artists` | `tuple[Artist, ...]` | Primary, featured and producer credits. Remixers live in `versions` | -| `title` | `str` | Clean title. Brackets it doesn't recognise stay in | +| `title` | `str` | Clean title. Brackets it doesn't recognize stay in | | `full_title` | `str` | `title` with the versions re-attached | | `versions` | `tuple[Version, ...]` | Remixes and other versions, left to right | | `year` | `int \| None` | From `(2015)` or `- 2015` | @@ -206,14 +208,17 @@ parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)").versions[0] # descriptor='at Wembley', year=1986, unknown_artist=False, delimiter='(') ``` -Version types, junk kinds and warnings are listed in the -[API reference](https://4matic.github.io/trackparse/reference/parse/) and typed as `Literal` aliases -(`VersionType`, `JunkKind`, `Warning`, `ArtistRole`, `ArtistSource`, `Mode`, `ModeOption`, -`VersionDelimiter`). +- `VersionType`: `remix`, `bootleg`, `vip`, `edit`, `flip`, `refix`, `rework`, `mashup`, `blend`, + `dub`, `mix`, `extended`, `radio`, `club`, `original`, `instrumental`, `acapella`, `live`, + `acoustic`, `remaster`, `demo`, `reprise`, `cover`, `version`, `spedUp`, `slowed`, `nightcore`. +- `JunkKind`: `video`, `audio`, `lyrics`, `quality`, `promo`, `platform`, `label`, `genre`, `other`. +- `Warning`: see [Warnings](#warnings). + +These are plain strings, typed as `Literal` aliases (see [Typing](#typing)). ### `to_dict()` and `from_dict()` -**Docs:** [JSON and Python objects](https://4matic.github.io/trackparse/reference/parse/#json-and-python-objects) +**Docs:** [Serializing to JSON](https://4matic.github.io/trackparse/reference/parse/#serializing-to-json) Every result class has `to_dict()`, which returns plain dicts and lists matching [`parsed-track.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/parsed-track.schema.json) @@ -222,14 +227,16 @@ ensure_ascii=False)` the bytes are the same as `JSON.stringify(parse(s))` in JS. (`ParsedTrack`, `Artist`, ...) also have a `from_dict()` classmethod that goes the other way: ```python +from trackparse import ParsedTrack + ParsedTrack.from_dict(track.to_dict()) == track # True ``` ### `parse_artists(input, **options)` -**Docs:** [parseArtists](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options) +**Docs:** [parseArtists](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options) · [Artists and credits](https://4matic.github.io/trackparse/guides/artists/) -Splits a bare artist string. Takes the same options as `parse`. +Splits a bare artist string (no title). Takes the same options as `parse`. ```python from trackparse import parse_artists @@ -246,12 +253,12 @@ Renders a track back to a string. | Option | Default | | |---|---|---| -| `feat` | `"source"` | Where featured artists go: `"source"` (where they were), `"artist"`, `"title"` or `"omit"` | -| `feat_marker` | `None` | Marker for featured artists, such as `"feat."` | -| `joiners` | `"original"` | `"original"` keeps the joiners as written, `"canonical"` uses the standard ones | +| `feat` | `"source"` | Where featured artists go: `"source"` (where they were), `"artist"`, `"title"` (`(feat. X)` after the title) or `"omit"` | +| `feat_marker` | `None` | Marker for featured artists, such as `"featuring"` | +| `joiners` | `"original"` | `"original"` keeps the joiners as written. `"canonical"` writes `and` as `&`, `vs` as `vs.` and every feat marker as `feat.` | | `versions` | `"all"` | `"all"` or `"none"` | | `producers` | `True` | Include `(prod. ...)` credits | -| `position` | `False` | Include the track number | +| `position` | `False` | Include the track number (`01. `) | ```python from trackparse import format_track @@ -273,13 +280,14 @@ format_track(track, position=True) **Docs:** [normalize](https://4matic.github.io/trackparse/reference/functions/#normalizeinput) -The Unicode cleanup every function runs first: NFC, invisible characters, and dash, bracket and -quote variants. +The Unicode cleanup every function runs first: NFC, zero-width spaces, BOM and soft hyphens +removed, fullwidth brackets, smart quotes and dash variants mapped to ASCII, whitespace collapsed. +Running it twice changes nothing. ```python from trackparse import normalize -normalize("Noisia​ – Stigma (VIP)") +normalize("Noisia\u200b – Stigma (VIP)") # 'Noisia - Stigma (VIP)' ``` @@ -317,8 +325,9 @@ parser.parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)").versi ### `SPEC_VERSION` -The spec version this build implements. The PyPI package, the npm package and the spec are -released together and always share one version number. +The spec version this build implements, `"0.5.0"` in this release. It equals `__version__`: the +PyPI package, the npm package, the Rust crate and the spec are released together and always share +one version number. ## Modes @@ -345,9 +354,39 @@ parse("Shelter", mode="youtube", uploader="Porter Robinson").artists # (Artist(name='Porter Robinson', role='primary', joiner=None, source='artist'),) ``` +## Warnings + +**Docs:** [Warnings](https://4matic.github.io/trackparse/reference/warnings/) + +The parser never fails, but it says when it had to guess. `track.warnings` is a tuple of strings, +empty when every decision was unambiguous. + +| Warning | Means | +|---|---| +| `noSeparator` | No artist/title separator was found. The whole string is the title | +| `ambiguousSeparator` | A two-part pipe title with no dash was read as artist and title | +| `unspacedDashSplit` | Split at a dash without spaces around it | +| `asymmetricDashSplit` | Split at a dash with a space on one side only | +| `bySplit` | Read `"Title" by Artist` | +| `quotedTitleSplit` | Took a quoted span as the title and the text before it as the artist | +| `ambiguousMixCredit` | ` Mix` was read as a remix, but the name is long enough to be a style | +| `unbalancedBrackets` | A bracket was opened and never closed | + +```python +t = parse("Around the World") +t.artists, t.title, t.warnings +# ((), 'Around the World', ('noSeparator',)) + +parse("Noisia - Stigma (VIP").warnings +# ('unbalancedBrackets',) +``` + +Tracklists have their own warnings, with line numbers. They are listed under +[Tracklists](#tracklists). + ## Tracklists -**Docs:** [Tracklists](https://4matic.github.io/trackparse/guides/tracklists/) · [Editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/) +**Docs:** [Tracklists](https://4matic.github.io/trackparse/guides/tracklists/) · [Editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/) · [Tracklist API](https://4matic.github.io/trackparse/reference/tracklist/) · [Warnings](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings) `trackparse.tracklist` parses a whole tracklist, one entry per line, and checks it. Each entry keeps its line exactly as written plus its own line ending, so `"".join(e.raw + e.eol for e in @@ -416,13 +455,19 @@ apply_edits(text, [{"op": "shift", "seconds": -3000, "lines": [2, 3]}]).warnings ``` A rewritten time keeps its line's style: `52:47` stays `MM:SS`, and a time that crosses the hour -gets hours like the rest of the list, with a `style-upgraded` warning. A bad edit changes nothing -and warns `edit-invalid`. Neither function raises on `str` input. +gets hours like the rest of the list, with a `style-upgraded` warning. A time pushed below zero +stops at zero and warns `time-clamped`. A bad edit changes nothing and warns `edit-invalid`. + +Both functions take the keyword options `mode` (default `"tracklist"`), `known_artists`, +`split_and` and `keywords`, as `parse` does, plus `audio_seconds` (the length of the audio, which +turns on the `time-after-audio-end` check) and `marker_words` (extra words that make a line a +marker): ```python -parse_tracklist(text, *, mode="tracklist", known_artists=(), keywords=None, split_and="auto", - audio_seconds=None, marker_words=()) -> Tracklist -apply_edits(text, edits, *, ) -> EditResult +parse_tracklist( + "00:00 Noisia - Stigma\n1:02:03 Mefjus - Suicide Bassline", audio_seconds=3600 +).warnings +# (TracklistWarning(code='time-after-audio-end', line=2, severity='warning', suggestion=None),) ``` | Result | Fields | @@ -448,7 +493,9 @@ Warning codes: `time-missing`, `time-out-of-order`, `time-duplicate`, `no-start- `position-duplicate`, `line-unparsed`. Edits: `set-time {line, seconds}`, `shift {seconds, lines? | from?}` (all timed lines when neither is given), `sort-by-time {}`, `set-rest {line, rest}`, `insert {after, text}` (`after: 0` inserts at the top), `delete {line}`. The -[Tracklist API reference](https://4matic.github.io/trackparse/reference/tracklist/) explains each one. +[Tracklist API reference](https://4matic.github.io/trackparse/reference/tracklist/) explains each one, +and the rules are in +[SPEC R13](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md#r13-tracklists). `to_dict()` gives the camelCase JSON from [`tracklist.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/tracklist.schema.json), byte-identical to the JS package's output. @@ -463,17 +510,86 @@ parse("Electrosoul System - Liquid Metal", mode="tracklist").title # 'Liquid Metal' ``` +## Errors + +Parsing is total: any `str` gives a complete `ParsedTrack`, `""` included, and `parse_tracklist` +and `apply_edits` return for any text. An option of the wrong type or with an unknown value is +ignored and the default is used. `apply_edits` reports a bad edit as an `edit-invalid` warning and +leaves the text alone. + +The one exception is the input itself: passing something that isn't a `str` raises `TypeError`. + +```python +parse(None) +# TypeError: parse() expects str input, got NoneType +``` + +Recognition is done by hand-written scanners, so there is no regex backtracking. A +10,000-code-point input parses in well under a second, and the test suite enforces a 1 s ceiling. + ## Typing -**Docs:** [Types](https://4matic.github.io/trackparse/reference/parse/#types) +**Docs:** [Types](https://4matic.github.io/trackparse/reference/parse/#types) · [Tracklist types](https://4matic.github.io/trackparse/reference/tracklist/#types) + +The package ships `py.typed` and passes `mypy --strict`. + +- `ParsedTrack`, `Artist`, `Version`, `Junk`, `Flags`, `Position` and `Timestamp` are frozen + dataclasses with snake_case attributes, and so are the tracklist results in + `trackparse.tracklist`. Sequences are tuples, so results are immutable and hashable: they can go + in sets or be used as dict keys. +- Version types, junk kinds, warnings, roles and modes are plain strings, typed as `Literal` + aliases: `VersionType`, `JunkKind`, `Warning`, `ArtistRole`, `ArtistSource`, `Mode`, + `ModeOption`, `VersionDelimiter`. `trackparse.tracklist` adds `EntryKind`, `Eol`, `Severity`, + `TracklistWarningCode` and `EditWarningCode`. +- Option dicts have `TypedDict` types (`ParseOptions`, `KeywordOptions`, `FormatOptions`). + Tracklist edits are plain dicts. + +## How it is tested + +**Docs:** [How it's tested](https://4matic.github.io/trackparse/project/testing/) + +- 13,130 shared fixtures: 1,203 written by hand and 11,927 generated from the rules. Every output + is also validated against the JSON Schema. +- Property tests with [Hypothesis](https://hypothesis.works) for the spec's invariants: no + exception on any string, `normalize` is idempotent, whitespace and dash noise doesn't change + the result, and `parse(format_track(parse(s)))` round-trips. +- CI runs the suite on Python 3.9 to 3.14, and runs the fixtures again against the built wheel. +- [`compare-ports.mjs`](https://github.com/4matic/trackparse/blob/main/scripts/compare-ports.mjs) + runs every fixture input through the JavaScript package, this package and the Rust crate and + diffs the complete JSON output. The difference count is zero. + +## Versioning -The package ships `py.typed` and passes `mypy --strict`. `ParsedTrack`, `Artist`, `Version`, -`Junk`, `Flags`, `Position` and `Timestamp` are frozen dataclasses with snake_case attributes, and -so are the tracklist results in `trackparse.tracklist`. -Sequences are tuples, so results are immutable and hashable and can go in sets or be used as dict -keys. Option dicts have `TypedDict` types (`ParseOptions`, `KeywordOptions`, `FormatOptions`); -tracklist edits are plain dicts. `trackparse.tracklist` also exports the `Literal` aliases -`EntryKind`, `Eol`, `Severity`, `TracklistWarningCode` and `EditWarningCode`. +**Changelog:** [python/CHANGELOG.md](https://github.com/4matic/trackparse/blob/main/python/CHANGELOG.md) + +The package version is the spec version (`SPEC_VERSION`). While it is 0.x, a release that changes +the output for some input bumps the minor version, and a patch release only fixes bugs. If you +store parsed results, pin the minor version (`trackparse~=0.5.0`) and read the changelog before +moving up. + +## Other languages + +**Docs:** [Ports](https://4matic.github.io/trackparse/project/ports/) + +The same parser exists for JavaScript and Rust. All three implement one spec, pass the same +fixtures, are released together under one version number, and return identical JSON for every +fixture input. You can parse in one language and read the result in another. + +| Language | Package | Install | +|---|---|---| +| JavaScript / TypeScript | [trackparse on npm](https://www.npmjs.com/package/trackparse) | `npm install trackparse` | +| Python | [trackparse on PyPI](https://pypi.org/project/trackparse/) | `pip install trackparse` | +| Rust | [trackparse on crates.io](https://crates.io/crates/trackparse) | `cargo add trackparse` | + +## Limitations + +**Docs:** [Limitations and roadmap](https://4matic.github.io/trackparse/project/roadmap/) + +- `parse()` takes one track string. Whole tracklists go through `trackparse.tracklist`, which reads + start times only: no durations, trailing times or time ranges. +- Catalog numbers, key and BPM are not fields. They stay in the title. +- There is no artist database. Pass `known_artists` for names that contain a joiner + (`Earth, Wind & Fire`). ## Development @@ -495,13 +611,14 @@ same spec rule IDs. Behaviour changes start in the spec, not here: see ## Links -- [Documentation](https://4matic.github.io/trackparse/), with every example in Python and JavaScript, and a - [playground](https://4matic.github.io/trackparse/playground/) that runs the parser in your browser +- [Documentation](https://4matic.github.io/trackparse/), with every example in JavaScript, Python + and Rust, and a [playground](https://4matic.github.io/trackparse/playground/) that runs the + parser in your browser - [Spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md) +- [Changelog](https://github.com/4matic/trackparse/blob/main/python/CHANGELOG.md) - [Project README](https://github.com/4matic/trackparse#readme) - [GitHub repository](https://github.com/4matic/trackparse) -- [Changelog](https://github.com/4matic/trackparse/blob/main/python/CHANGELOG.md) -- [npm package](https://www.npmjs.com/package/trackparse) +- [npm package](https://www.npmjs.com/package/trackparse) · [Rust crate](https://crates.io/crates/trackparse) ## License diff --git a/rust/README.md b/rust/README.md index fc15a4a..3b0f7bc 100644 --- a/rust/README.md +++ b/rust/README.md @@ -2,7 +2,8 @@ [![crates.io](https://img.shields.io/crates/v/trackparse?logo=rust&logoColor=white)](https://crates.io/crates/trackparse) [![docs.rs](https://img.shields.io/docsrs/trackparse?logo=docsdotrs&logoColor=white)](https://docs.rs/trackparse) -[![rust](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/rust.yml?branch=main&label=tests&logo=github)](https://github.com/4matic/trackparse/actions/workflows/rust.yml) +[![MSRV](https://img.shields.io/crates/msrv/trackparse?logo=rust&logoColor=white)](https://crates.io/crates/trackparse) +[![tests](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/rust.yml?branch=main&label=tests&logo=github)](https://github.com/4matic/trackparse/actions/workflows/rust.yml) [![license](https://img.shields.io/badge/license-MIT-blue)](https://github.com/4matic/trackparse/blob/main/LICENSE) **[Documentation](https://4matic.github.io/trackparse/)** · **[Getting started](https://4matic.github.io/trackparse/start/getting-started/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** · **[API on docs.rs](https://docs.rs/trackparse)** @@ -16,15 +17,15 @@ what's just noise.** Most title parsers split that into `"Wilkinson ft. Becky Hill & Tom Cane"` and `"Afterglow (Sub Focus VIP Remix)"` and stop. Others "clean" it and throw the feat and the remix -away. trackparse keeps all of it. Everything it recognises goes into a field, and anything it -doesn't recognise stays in the title, word for word. +away. trackparse keeps all of it. Everything it recognizes goes into a field, and anything it +doesn't recognize stays in the title, word for word. This is the Rust port of [trackparse](https://github.com/4matic/trackparse). Its behaviour is defined by a [shared spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md) and pinned by 13,130 fixtures. It passes all of them, and for every fixture input its output is byte-identical -to the JavaScript and Python packages. +to the [JavaScript and Python packages](#other-languages). -- Rust 1.74 or later +- Rust 1.74 or later (the minimum supported version; CI runs the test suite on 1.74 and on stable) - One dependency (`unicode-normalization`); `serde` is optional - No `unsafe`, no regular expressions - Never panics and never returns an error: any `&str` gives a result @@ -143,7 +144,7 @@ Every function has a plain form with the default options and a `_with` form that | Option | Default | | |---|---|---| -| `mode` | `ModeOption::Auto` | `Clean`, `Youtube`, `Filename`, `Tracklist`, or `Auto` to detect from the string | +| `mode` | `ModeOption::Auto` | `Clean`, `Youtube`, `Filename`, `Tracklist`, or `Auto` to detect from the string. See [Modes](#modes) | | `uploader` | `None` | YouTube channel name, used as the artist when there's no separator (`- Topic` and `VEVO` are dropped) | | `known_artists` | empty | Names that are never split. There is no built-in list | | `split_and` | `SplitAnd::Auto` | `Auto` splits on `and` only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole. Also `Always`, `Never` | @@ -192,8 +193,6 @@ assert_eq!(track.junk[0].raw, "Some Label Rip"); assert_eq!(track.junk[0].kind, JunkKind::Label); ``` -Parsing is total: any `&str` gives a `ParsedTrack`, including `""`. - ### `ParsedTrack` **Docs:** [ParsedTrack fields](https://4matic.github.io/trackparse/reference/parse/#parsedtrack) @@ -205,7 +204,7 @@ Parsing is total: any `&str` gives a `ParsedTrack`, including `""`. | `position` | `Option` | Track number: `Position { raw: "01", number: 1 }` | | `timestamp` | `Option` | Leading cue time: `[12:34]` gives `Timestamp { raw: "12:34", seconds: 754 }` | | `artists` | `Vec` | Primary, featured and producer credits. Remixers live in `versions` | -| `title` | `String` | Clean title. Brackets it doesn't recognise stay in | +| `title` | `String` | Clean title. Brackets it doesn't recognize stay in | | `full_title` | `String` | `title` with the versions re-attached | | `versions` | `Vec` | Remixes and other versions, left to right | | `year` | `Option` | From `(2015)` or `- 2015` | @@ -243,7 +242,8 @@ assert_eq!(version.year, Some(1986)); Version types, junk kinds, warnings, roles and modes are enums (`VersionType`, `JunkKind`, `Warning`, `ArtistRole`, `ArtistSource`, `Mode`, `ModeOption`, `VersionDelimiter`), listed in the -[API reference](https://4matic.github.io/trackparse/reference/parse/). Each has `as_str()` (the name +[API reference](https://4matic.github.io/trackparse/reference/parse/) and on +[docs.rs](https://docs.rs/trackparse). Each has `as_str()` (the name used in the spec and in JSON), `from_name()`, `ALL`, `Display` and `FromStr`: ```rust @@ -260,7 +260,7 @@ warning, so a `match` on them needs a `_` arm. ### JSON and serde -**Docs:** [JSON and Python objects](https://4matic.github.io/trackparse/reference/parse/#json-and-python-objects) +**Docs:** [Serializing to JSON](https://4matic.github.io/trackparse/reference/parse/#serializing-to-json) Every result type has `to_json()`, which writes compact JSON matching [`parsed-track.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/parsed-track.schema.json) @@ -309,9 +309,9 @@ Reading options is strict: a missing key is the default, an unknown name such as ### `parse_artists` -**Docs:** [parseArtists](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options) +**Docs:** [parseArtists](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options) · [Artists and credits](https://4matic.github.io/trackparse/guides/artists/) -Splits a bare artist string. `parse_artists_with` takes the same options as `parse_with`. +Splits a bare artist string (no title). `parse_artists_with` takes the same options as `parse_with`. ```rust use trackparse::parse_artists; @@ -331,12 +331,12 @@ Renders a track back to a string. | Option | Default | | |---|---|---| -| `feat` | `FeatPlacement::Source` | Where featured artists go: `Source` (where they were), `Artist`, `Title` or `Omit` | -| `feat_marker` | `None` | Marker for featured artists, such as `"feat."` | -| `joiners` | `JoinerStyle::Original` | `Original` keeps the joiners as written, `Canonical` uses the standard ones | +| `feat` | `FeatPlacement::Source` | Where featured artists go: `Source` (where they were), `Artist`, `Title` (`(feat. X)` after the title) or `Omit` | +| `feat_marker` | `None` | Marker for featured artists, such as `"featuring"` | +| `joiners` | `JoinerStyle::Original` | `Original` keeps the joiners as written. `Canonical` writes `and` as `&`, `vs` as `vs.` and every feat marker as `feat.` | | `versions` | `VersionsOption::All` | `All` or `None` | | `producers` | `true` | Include `(prod. ...)` credits | -| `position` | `false` | Include the track number | +| `position` | `false` | Include the track number (`01. `) | ```rust use trackparse::{ @@ -366,8 +366,9 @@ assert_eq!( **Docs:** [normalize](https://4matic.github.io/trackparse/reference/functions/#normalizeinput) -The Unicode cleanup every function runs first: NFC, invisible characters, and dash, bracket and -quote variants. +The Unicode cleanup every function runs first: NFC, zero-width spaces, BOM and soft hyphens +removed, fullwidth brackets, smart quotes and dash variants mapped to ASCII, whitespace collapsed. +Running it twice changes nothing. ```rust use trackparse::normalize; @@ -411,8 +412,9 @@ assert_eq!(track.versions[0].version_type, VersionType::Rework); ### `SPEC_VERSION` -The spec version this build implements. The crate, the npm package, the PyPI package and the spec -are released together and always share one version number. +The spec version this build implements, `"0.5.0"` in this release. It equals the crate version: +the crate, the npm package, the PyPI package and the spec are released together and always share +one version number. ## Modes @@ -445,9 +447,42 @@ let track = parse_with("Shelter", &youtube.uploader("Porter Robinson")); assert_eq!(track.artists[0].name, "Porter Robinson"); ``` +## Warnings + +**Docs:** [Warnings](https://4matic.github.io/trackparse/reference/warnings/) + +The parser never fails, but it says when it had to guess. `track.warnings` is a `Vec`, +empty when every decision was unambiguous. `as_str()` gives the name used in the spec and in JSON. + +| Warning | JSON name | Means | +|---|---|---| +| `NoSeparator` | `noSeparator` | No artist/title separator was found. The whole string is the title | +| `AmbiguousSeparator` | `ambiguousSeparator` | A two-part pipe title with no dash was read as artist and title | +| `UnspacedDashSplit` | `unspacedDashSplit` | Split at a dash without spaces around it | +| `AsymmetricDashSplit` | `asymmetricDashSplit` | Split at a dash with a space on one side only | +| `BySplit` | `bySplit` | Read `"Title" by Artist` | +| `QuotedTitleSplit` | `quotedTitleSplit` | Took a quoted span as the title and the text before it as the artist | +| `AmbiguousMixCredit` | `ambiguousMixCredit` | ` Mix` was read as a remix, but the name is long enough to be a style | +| `UnbalancedBrackets` | `unbalancedBrackets` | A bracket was opened and never closed | + +```rust +use trackparse::{parse, Warning}; + +let track = parse("Around the World"); +assert!(track.artists.is_empty()); +assert_eq!(track.title, "Around the World"); +assert_eq!(track.warnings, [Warning::NoSeparator]); +assert_eq!(track.warnings[0].as_str(), "noSeparator"); + +assert_eq!(parse("Noisia - Stigma (VIP").warnings, [Warning::UnbalancedBrackets]); +``` + +Tracklists have their own warnings, with line numbers. They are listed under +[Tracklists](#tracklists). + ## Tracklists -**Docs:** [Tracklists](https://4matic.github.io/trackparse/guides/tracklists/) · [Editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/) · [Tracklist API](https://4matic.github.io/trackparse/reference/tracklist/) · [Warnings](https://4matic.github.io/trackparse/reference/warnings/) +**Docs:** [Tracklists](https://4matic.github.io/trackparse/guides/tracklists/) · [Editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/) · [Tracklist API](https://4matic.github.io/trackparse/reference/tracklist/) · [Warnings](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings) `trackparse::tracklist` parses a whole tracklist, one entry per line, and checks it. Each entry keeps its line exactly as written plus its own line ending, so joining every `raw` and `eol` is @@ -528,8 +563,8 @@ assert_eq!(result.warnings[0].code, EditWarningCode::TimeClamped); ``` A rewritten time keeps its line's style: `48:20` stays `MM:SS`, and a time that crosses the hour -gets hours, with a `style-upgraded` warning. A bad edit changes nothing and warns `edit-invalid`. -Neither function panics. +gets hours, with a `style-upgraded` warning. A time pushed below zero stops at zero and warns +`time-clamped`. A bad edit changes nothing and warns `edit-invalid`. `TracklistOptions` has `mode` (default `ModeOption::Tracklist`), `known_artists`, `split_and`, `keywords`, `audio_seconds` (enables `time-after-audio-end`) and `marker_words`: @@ -568,7 +603,8 @@ Warning codes (`WarningCode`): `time-missing`, `time-out-of-order`, `time-duplic `Edit::shift_lines(seconds, lines)`, `Edit::sort_by_time()`, `Edit::set_rest(line, rest)`, `Edit::insert(after, text)` (`after: 0` inserts at the top), `Edit::delete(line)`. The [Tracklist API reference](https://4matic.github.io/trackparse/reference/tracklist/) explains each -one. +one, and the rules are in +[SPEC R13](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md#r13-tracklists). Every line is parsed with `ModeOption::Tracklist`, where the first spaced dash always separates artist and title. `parse_with` accepts it too: @@ -584,9 +620,21 @@ let options = ParseOptions::new().mode(ModeOption::Tracklist); assert_eq!(parse_with("Electrosoul System - Liquid Metal", &options).title, "Liquid Metal"); ``` +## Errors + +No function returns a `Result` and none panics. `parse` gives a complete `ParsedTrack` for any +`&str`, `""` included, and `parse_tracklist` and `apply_edits` return for any text. Options are +typed, so a wrong value does not compile. `apply_edits` reports an edit it cannot apply (a line +that does not exist, non-finite seconds) as an `EditWarningCode::EditInvalid` warning and leaves +the text alone. + +The only fallible calls are conversions from text: `FromStr` on the enums returns `UnknownName` +for a name the spec does not have, and with the `serde` feature, deserializing options or edits +from JSON can fail as any `serde` type can. + ## How it is tested -**Docs:** [Testing](https://4matic.github.io/trackparse/project/testing/) · [Ports](https://4matic.github.io/trackparse/project/ports/) +**Docs:** [How it's tested](https://4matic.github.io/trackparse/project/testing/) · [Ports](https://4matic.github.io/trackparse/project/ports/) - `cargo test` runs all 13,130 shared fixtures (1,203 written by hand, the rest generated from the rules), the spec's invariants for single tracks and for tracklists on generated input (no @@ -618,14 +666,43 @@ not affected, and every shared fixture gives the same bytes. ## Performance -There are no regular expressions and no backtracking: each rule makes a bounded number of passes -over the string. A 10,000-code-point input parses in a few milliseconds in a release build, and -the test suite checks that hostile repetitions (thousands of duplicate credits, bracket groups or -junk phrases) take time roughly in proportion to their length, not to its square. +There are no regular expressions, so there is no regex backtracking. A 10,000-code-point input +parses in under 20 ms in a release build. The test suite runs hostile repetitions of that +length (thousands of duplicate credits, bracket groups or junk phrases) under a time ceiling. + +## Versioning + +**Changelog:** [rust/CHANGELOG.md](https://github.com/4matic/trackparse/blob/main/rust/CHANGELOG.md) + +The crate version is the spec version (`SPEC_VERSION`). While it is 0.x, a release that changes +the output for some input bumps the minor version, and a patch release only fixes bugs. Cargo's +default requirement (`trackparse = "0.5"`) already stays within one minor version, so `cargo update` +will not change your output. Read the changelog before moving to the next minor. + +## Other languages + +**Docs:** [Ports](https://4matic.github.io/trackparse/project/ports/) + +The same parser exists for JavaScript and Python. All three implement one spec, pass the same +fixtures, are released together under one version number, and return identical JSON for every +fixture input. You can parse in one language and read the result in another. The one known +difference is described under [Unicode version](#unicode-version). + +| Language | Package | Install | +|---|---|---| +| JavaScript / TypeScript | [trackparse on npm](https://www.npmjs.com/package/trackparse) | `npm install trackparse` | +| Python | [trackparse on PyPI](https://pypi.org/project/trackparse/) | `pip install trackparse` | +| Rust | [trackparse on crates.io](https://crates.io/crates/trackparse) | `cargo add trackparse` | + +## Limitations -## Minimum Rust version +**Docs:** [Limitations and roadmap](https://4matic.github.io/trackparse/project/roadmap/) -Rust 1.74. CI runs the test suite on 1.74 and on stable. +- `parse` takes one track string. Whole tracklists go through `trackparse::tracklist`, which reads + start times only: no durations, trailing times or time ranges. +- Catalog numbers, key and BPM are not fields. They stay in the title. +- There is no artist database. Pass `known_artists` for names that contain a joiner + (`Earth, Wind & Fire`). ## Development @@ -647,10 +724,12 @@ same spec rule IDs. Behaviour changes start in the spec, not here: see ## Links -- [Documentation](https://4matic.github.io/trackparse/), and a - [playground](https://4matic.github.io/trackparse/playground/) that runs the parser in your browser +- [Documentation](https://4matic.github.io/trackparse/), with every example in JavaScript, Python + and Rust, and a [playground](https://4matic.github.io/trackparse/playground/) that runs the + parser in your browser - [API documentation on docs.rs](https://docs.rs/trackparse) - [Spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md) +- [Changelog](https://github.com/4matic/trackparse/blob/main/rust/CHANGELOG.md) - [Project README](https://github.com/4matic/trackparse#readme) - [GitHub repository](https://github.com/4matic/trackparse) - [npm package](https://www.npmjs.com/package/trackparse) · [PyPI package](https://pypi.org/project/trackparse/) diff --git a/site/src/components/Compare.astro b/site/src/components/Compare.astro index 2cd8287..eed60a0 100644 --- a/site/src/components/Compare.astro +++ b/site/src/components/Compare.astro @@ -106,7 +106,8 @@ const rows: [string, string, string][] = [ @media (max-width: 34rem) { thead th:first-child, tbody th { - width: 4.8rem; + width: 5.4rem; + overflow-wrap: normal; } th, td { diff --git a/site/src/components/Features.astro b/site/src/components/Features.astro index 36e2ff8..4c661ce 100644 --- a/site/src/components/Features.astro +++ b/site/src/components/Features.astro @@ -32,6 +32,7 @@ const { items } = Astro.props as { items: Item[] }; display: grid; grid-template-columns: 2.2rem minmax(0, 1fr); column-gap: 0.4rem; + align-content: start; padding: 1.25rem 0 1.35rem; border-top: 1px solid var(--tp-border); margin: 0; diff --git a/site/src/components/HeroDemo.astro b/site/src/components/HeroDemo.astro index e05a87a..365805f 100644 --- a/site/src/components/HeroDemo.astro +++ b/site/src/components/HeroDemo.astro @@ -11,12 +11,13 @@ const examples = [ "Кино - Группа крови (Remastered 2019)", "ID - ID (ID Remix)", ]; -const playground = `${import.meta.env.BASE_URL}playground/`; +const base = import.meta.env.BASE_URL.replace(/\/$/, ""); +const playground = `${base}/playground/`; --- -
+
- parse(input)runs the real package in your browser + parse(input)the npm package, running in your browser
@@ -47,6 +48,7 @@ const playground = `${import.meta.env.BASE_URL}playground/`;
@@ -120,9 +122,23 @@ const playground = `${import.meta.env.BASE_URL}playground/`; padding: 0.4rem 1.1rem 1.1rem; } .hd-foot { - justify-content: flex-end; + flex-wrap: wrap; border-top: 1px solid var(--tp-border); } + .hd-note { + color: var(--sl-color-gray-3); + } + .hd-note a { + color: var(--sl-color-gray-2); + text-decoration: underline; + text-decoration-color: var(--tp-border-strong); + text-underline-offset: 0.2em; + white-space: nowrap; + } + .hd-note a:hover { + color: var(--sl-color-white); + text-decoration-color: var(--sl-color-accent); + } .hd-open { display: inline-flex; align-items: center; @@ -130,6 +146,8 @@ const playground = `${import.meta.env.BASE_URL}playground/`; font-weight: 500; color: var(--sl-color-white); text-decoration: none; + margin-left: auto; + white-space: nowrap; } .hd-open:hover { color: var(--sl-color-accent-high); @@ -163,7 +181,7 @@ const playground = `${import.meta.env.BASE_URL}playground/`; line.innerHTML = segmentsHtml(segs) || 'type a track name'; const kinds = [...new Set(segs.map((x) => x.kind).filter(Boolean))] as Kind[]; legend.innerHTML = kinds.map((k) => chip(KIND_LABEL[k], k)).join(""); - fields.innerHTML = fieldsHtml(track); + fields.innerHTML = fieldsHtml(track, root.dataset.base); open.href = `${base}#track=${encodeURIComponent(s)}`; time.textContent = `${ms < 1 ? "<1" : ms.toFixed(1)} ms`; for (const b of buttons) b.setAttribute("aria-pressed", String(b.dataset.example === s)); diff --git a/site/src/components/Install.astro b/site/src/components/Install.astro index 58dd715..20540ba 100644 --- a/site/src/components/Install.astro +++ b/site/src/components/Install.astro @@ -1,26 +1,45 @@ --- // One install line under the hero, switchable between npm, pip and cargo, with a copy button. +// The switch shares its choice with the docs' language tabs and the playground (lib/lang.ts). +import Check from "@lucide/astro/icons/check"; import Copy from "@lucide/astro/icons/copy"; +import { PACKAGE } from "../lib/lang"; -const cmds = { npm: "npm install trackparse", pip: "pip install trackparse", cargo: "cargo add trackparse" }; +const pms = [ + { lang: "js", label: "npm" }, + { lang: "py", label: "pip" }, + { lang: "rs", label: "cargo" }, +] as const; --- -
-
- - - +
+
+
+ { + pms.map((p, i) => ( + + )) + } +
+ {PACKAGE.js.install} +
- {cmds.npm} - +

+ Published on npm, PyPI and{" "} + crates.io. The Rust API docs are on docs.rs. +

diff --git a/site/src/components/Playground.astro b/site/src/components/Playground.astro index efae167..4ad857a 100644 --- a/site/src/components/Playground.astro +++ b/site/src/components/Playground.astro @@ -6,6 +6,10 @@ import Redo2 from "@lucide/astro/icons/redo-2"; import Undo2 from "@lucide/astro/icons/undo-2"; import "../styles/playground.css"; +// Docs links next to the controls they explain. +const base = import.meta.env.BASE_URL.replace(/\/$/, ""); +const doc = (path: string) => `${base}/${path}`; + const trackExamples = [ "01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video]", "Dimension - Offshore (Mefjus Remix / Noisia Remix)", @@ -71,7 +75,7 @@ const listExamples: { label: string; title: string; text: string }[] = [ ]; --- -
+
@@ -142,7 +153,10 @@ const listExamples: { label: string; title: string; text: string }[] = [

       
- format(track, options) +
+ format(track, options) + Formatting guide +
@@ -178,13 +192,23 @@ const listExamples: { label: string; title: string; text: string }[] = [

-        
+        
+ +

+