diff --git a/.forgejo/workflows/check.yml b/.forgejo/workflows/check.yml new file mode 100644 index 0000000..6e13d91 --- /dev/null +++ b/.forgejo/workflows/check.yml @@ -0,0 +1,74 @@ +name: Check + +on: + push: + branches: ['main'] + pull_request: + branches: ['main'] + +env: + CARGO_TERM_COLOR: always + RUSTFLAGS: '-Dwarnings' + +jobs: + build: + runs-on: docker + + steps: + - uses: actions/checkout@v4 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: '22.x' + check-latest: true + + - name: Cache Rust dependencies + uses: actions/cache@v4 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-cargo- + + - name: Cache npm dependencies + uses: actions/cache@v4 + with: + path: | + reconcile-js/node_modules + examples/website/node_modules + ~/.npm + key: >- + ${{ runner.os }}-npm-${{ + hashFiles( + 'reconcile-js/package-lock.json', + 'examples/website/package-lock.json' + ) + }} + restore-keys: | + ${{ runner.os }}-npm- + + - name: Install Rust toolchain + run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \ + | sh -s -- -y --default-toolchain none --profile minimal + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + + - name: Install uv + run: | + curl --proto '=https' --tlsv1.2 -LsSf https://astral.sh/uv/install.sh | sh + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + + - name: Lint + run: scripts/lint.sh + + - name: Test + run: scripts/test.sh + + - name: Build website + run: scripts/build-website.sh diff --git a/.forgejo/workflows/publish.yml b/.forgejo/workflows/publish.yml new file mode 100644 index 0000000..bbaf253 --- /dev/null +++ b/.forgejo/workflows/publish.yml @@ -0,0 +1,265 @@ +name: Publish + +on: + push: + branches: ['main'] + tags: ['*'] + workflow_dispatch: + +env: + CARGO_TERM_COLOR: always + RUSTFLAGS: '-Dwarnings' + +concurrency: + group: 'pages' + cancel-in-progress: false + +jobs: + build: + runs-on: docker + + steps: + - uses: actions/checkout@v4 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: '22.x' + check-latest: true + + - name: Cache Rust dependencies + uses: actions/cache@v4 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-cargo- + + - name: Cache npm dependencies + uses: actions/cache@v4 + with: + path: | + reconcile-js/node_modules + examples/website/node_modules + ~/.npm + key: >- + ${{ runner.os }}-npm-${{ + hashFiles( + 'reconcile-js/package-lock.json', + 'examples/website/package-lock.json' + ) + }} + restore-keys: | + ${{ runner.os }}-npm- + + - name: Install Rust toolchain + run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \ + | sh -s -- -y --default-toolchain none --profile minimal + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + + - name: Install uv + run: | + curl --proto '=https' --tlsv1.2 -LsSf https://astral.sh/uv/install.sh | sh + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + + - name: Lint + run: scripts/lint.sh + + - name: Test + run: scripts/test.sh + + - name: Build website + run: scripts/build-website.sh + + - name: Deploy to pages mount + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + run: | + apt-get update && apt-get install -y rsync + rsync -a --delete examples/website/dist/ /pages/reconcile + + publish-crate: + needs: build + runs-on: docker + if: startsWith(github.ref, 'refs/tags/') + + steps: + - uses: actions/checkout@v4 + + - name: Cache Rust dependencies + uses: actions/cache@v4 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-cargo- + + - name: Install Rust toolchain + run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \ + | sh -s -- -y --default-toolchain none --profile minimal + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + + - name: Publish to crates.io + run: cargo publish --token ${{ secrets.CRATES_IO_TOKEN }} + + publish-npm: + needs: build + runs-on: docker + if: startsWith(github.ref, 'refs/tags/') + + steps: + - uses: actions/checkout@v4 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: '22.x' + check-latest: true + registry-url: 'https://registry.npmjs.org' + + - name: Cache Rust dependencies + uses: actions/cache@v4 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-cargo- + + - name: Cache npm dependencies + uses: actions/cache@v4 + with: + path: | + reconcile-js/node_modules + ~/.npm + key: >- + ${{ runner.os }}-npm-${{ + hashFiles('reconcile-js/package-lock.json') + }} + restore-keys: | + ${{ runner.os }}-npm- + + - name: Install Rust toolchain + run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \ + | sh -s -- -y --default-toolchain none --profile minimal + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + + - name: Build website + run: scripts/build-website.sh + + - name: Publish reconcile-js to NPM + run: | + cd reconcile-js + cp ../README.md . + npm publish + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + publish-pypi: + needs: build + runs-on: docker + if: startsWith(github.ref, 'refs/tags/') + + steps: + - uses: actions/checkout@v4 + + - name: Cache Rust dependencies + uses: actions/cache@v4 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: ${{ runner.os }}-cargo-pypi-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-cargo-pypi- + ${{ runner.os }}-cargo- + + # clang/lld/llvm provide clang-cl, lld-link and llvm-lib, which cargo-xwin + # uses to cross-compile the Windows wheel from this Linux runner. + - name: Install cross-compilation system dependencies + run: | + apt-get update + apt-get install -y clang lld llvm + + - name: Install Rust toolchain + run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \ + | sh -s -- -y --default-toolchain none --profile minimal + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + + # The Linux targets ship in rust-toolchain.toml; add the cross targets. + - name: Add cross-compilation Rust targets + run: | + rustup target add aarch64-unknown-linux-gnu x86_64-pc-windows-msvc + + # zig is the C toolchain maturin's `--zig` uses to produce manylinux2014 + # wheels with a pinned (old) glibc, independent of the runner's glibc. + - name: Install zig + run: | + ZIG_VERSION=0.13.0 + curl --proto '=https' --tlsv1.2 -fLsS \ + "https://ziglang.org/download/${ZIG_VERSION}/zig-linux-x86_64-${ZIG_VERSION}.tar.xz" \ + | tar -xJ + echo "$PWD/zig-linux-x86_64-${ZIG_VERSION}" >> "$GITHUB_PATH" + + - name: Install cargo-xwin + run: command -v cargo-xwin || cargo install --locked cargo-xwin + + - name: Install uv + run: | + curl --proto '=https' --tlsv1.2 -LsSf https://astral.sh/uv/install.sh | sh + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + + - name: Copy README + run: cp README.md reconcile-python/ + + - name: Build sdist + working-directory: reconcile-python + run: uv run maturin sdist --out dist + + - name: Build Linux x86_64 wheel + working-directory: reconcile-python + run: >- + uv run maturin build --release --out dist + --compatibility manylinux2014 + --target x86_64-unknown-linux-gnu --zig + + - name: Build Linux aarch64 wheel + working-directory: reconcile-python + run: >- + uv run maturin build --release --out dist + --compatibility manylinux2014 + --target aarch64-unknown-linux-gnu --zig + + - name: Build Windows x86_64 wheel + working-directory: reconcile-python + run: >- + uv run maturin build --release --out dist + --target x86_64-pc-windows-msvc + + # Forgejo cannot use PyPI trusted publishing (OIDC), so authenticate with + # an API token. --skip-existing makes re-runs of a tag idempotent. + - name: Publish to PyPI + working-directory: reconcile-python + env: + MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }} + run: uv run maturin upload --skip-existing dist/* diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index f5af792..0000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,26 +0,0 @@ -# To get started with Dependabot version updates, you'll need to specify which -# package ecosystems to update and where the package manifests are located. -# Please see the documentation for all configuration options: -# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file - -version: 2 -updates: - - package-ecosystem: 'cargo' - directories: ['**'] - schedule: - interval: 'daily' - - - package-ecosystem: 'github-actions' - directories: ['**'] - schedule: - interval: 'daily' - - - package-ecosystem: 'npm' - directories: ['/reconcile-js', '/examples/website'] - schedule: - interval: 'daily' - - - package-ecosystem: 'pip' - directories: ['/reconcile-python'] - schedule: - interval: 'daily' diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml deleted file mode 100644 index 4bddad5..0000000 --- a/.github/workflows/check.yml +++ /dev/null @@ -1,198 +0,0 @@ -name: Check & publish - -on: - push: - branches: ['main'] - tags: ['*'] - pull_request: - branches: ['main'] - -env: - CARGO_TERM_COLOR: always - RUSTFLAGS: '-Dwarnings' - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v6 - - - name: Setup Node.js environment - uses: actions/setup-node@v6.3.0 - with: - node-version: '22.x' - check-latest: true - - - name: Install uv - uses: astral-sh/setup-uv@v6 - - - name: Cache Rust dependencies - uses: actions/cache@v5 - with: - path: | - ~/.cargo/bin/ - ~/.cargo/registry/index/ - ~/.cargo/registry/cache/ - ~/.cargo/git/db/ - target/ - key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} - restore-keys: | - ${{ runner.os }}-cargo- - - - name: Lint - run: scripts/lint.sh - - - name: Test - run: scripts/test.sh - - publish-crate: - needs: build - runs-on: ubuntu-latest - if: startsWith(github.ref, 'refs/tags/') - - steps: - - uses: actions/checkout@v6 - - - name: Cache Rust dependencies - uses: actions/cache@v5 - with: - path: | - ~/.cargo/bin/ - ~/.cargo/registry/index/ - ~/.cargo/registry/cache/ - ~/.cargo/git/db/ - target/ - key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} - restore-keys: | - ${{ runner.os }}-cargo- - - - name: Publish to crates.io - run: cargo publish --token ${{ secrets.CRATES_IO_TOKEN }} - - publish-npm: - needs: build - runs-on: ubuntu-latest - if: startsWith(github.ref, 'refs/tags/') - permissions: - contents: read - id-token: write - - steps: - - uses: actions/checkout@v6 - - - name: Setup Node.js environment - uses: actions/setup-node@v6.3.0 - with: - node-version: '22.x' - check-latest: true - registry-url: 'https://registry.npmjs.org' - - - name: Cache Rust dependencies - uses: actions/cache@v5 - with: - path: | - ~/.cargo/bin/ - ~/.cargo/registry/index/ - ~/.cargo/registry/cache/ - ~/.cargo/git/db/ - target/ - key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} - restore-keys: | - ${{ runner.os }}-cargo- - - - name: Cache npm dependencies - uses: actions/cache@v5 - with: - path: | - reconcile-js/node_modules - ~/.npm - key: ${{ runner.os }}-npm-${{ hashFiles('reconcile-js/package-lock.json') }} - restore-keys: | - ${{ runner.os }}-npm- - - - name: Build website - run: scripts/build-website.sh - - - name: Publish reconcile-js to NPM - run: | - cd reconcile-js - cp ../README.md . - npm publish --provenance --access public - - build-python-wheels: - needs: build - if: startsWith(github.ref, 'refs/tags/') - strategy: - matrix: - include: - - os: ubuntu-latest - target: x86_64 - - os: ubuntu-latest - target: aarch64 - - os: macos-latest - target: x86_64 - - os: macos-latest - target: aarch64 - - os: windows-latest - target: x86_64 - runs-on: ${{ matrix.os }} - - steps: - - uses: actions/checkout@v6 - - - uses: actions/setup-python@v6 - with: - python-version: '3.x' - - - name: Copy README - run: cp README.md reconcile-python/ - - - uses: PyO3/maturin-action@v1 - with: - target: ${{ matrix.target }} - args: --release --out dist --find-interpreter - manylinux: auto - working-directory: reconcile-python - - - uses: actions/upload-artifact@v4 - with: - name: wheels-${{ matrix.os }}-${{ matrix.target }} - path: reconcile-python/dist/*.whl - - build-python-sdist: - needs: build - if: startsWith(github.ref, 'refs/tags/') - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v6 - - - name: Copy README - run: cp README.md reconcile-python/ - - - uses: PyO3/maturin-action@v1 - with: - command: sdist - args: --out dist - working-directory: reconcile-python - - - uses: actions/upload-artifact@v4 - with: - name: sdist - path: reconcile-python/dist/*.tar.gz - - publish-pypi: - needs: [build-python-wheels, build-python-sdist] - runs-on: ubuntu-latest - permissions: - id-token: write - - steps: - - uses: actions/download-artifact@v4 - with: - pattern: '{wheels-*,sdist}' - merge-multiple: true - path: dist - - - uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml deleted file mode 100644 index 7ac04ea..0000000 --- a/.github/workflows/gh-pages.yml +++ /dev/null @@ -1,72 +0,0 @@ -name: Deploy Website to GitHub Pages - -on: - push: - branches: - - main - workflow_dispatch: - -# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages -permissions: - contents: read - pages: write - id-token: write - -# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. -# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. -concurrency: - group: 'pages' - cancel-in-progress: false - -jobs: - build: - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - name: Checkout repository - uses: actions/checkout@v6 - - - name: Cache Rust dependencies - uses: actions/cache@v5 - with: - path: | - ~/.cargo/bin/ - ~/.cargo/registry/index/ - ~/.cargo/registry/cache/ - ~/.cargo/git/db/ - target/ - key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} - restore-keys: | - ${{ runner.os }}-cargo- - - - name: Cache npm dependencies - uses: actions/cache@v5 - with: - path: | - reconcile-js/node_modules - ~/.npm - key: ${{ runner.os }}-npm-${{ hashFiles('reconcile-js/package-lock.json') }} - restore-keys: | - ${{ runner.os }}-npm- - - - name: Build wasm - run: | - which wasm-pack || cargo install wasm-pack - scripts/build-website.sh - - - name: Upload artifact - uses: actions/upload-pages-artifact@v4 - with: - path: examples/website/dist - - deploy: - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - runs-on: ubuntu-latest - needs: build - steps: - - name: Deploy to GitHub Pages - id: deployment - uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore index 0957a69..c58feaf 100644 --- a/.gitignore +++ b/.gitignore @@ -10,5 +10,8 @@ node_modules # WebPack build output dist +# Generated wasm-bindgen bundler + wasm2js output for the React Native build +pkg-rn + # Python virtual environment .venv diff --git a/.vscode/settings.json b/.vscode/settings.json index db11dce..4571f3c 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -8,5 +8,8 @@ }, "rust-analyzer.cargo.features": [ "all" + ], + "python.analysis.extraPaths": [ + "./reconcile-python/python" ] } \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 168c1e6..0971f12 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -428,7 +428,7 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "reconcile-text" -version = "0.9.3" +version = "0.12.1" dependencies = [ "console_error_panic_hook", "diff-match-patch-rs", diff --git a/Cargo.toml b/Cargo.toml index c7321f3..21ff69b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "reconcile-text" description = "Intelligent 3-way text merging with automated conflict resolution" -version = "0.9.3" +version = "0.12.1" rust-version = "1.94" authors = ["Andras Schmelczer "] edition = "2024" diff --git a/README.md b/README.md index c25ef92..b644077 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,13 @@ console.log(result.text); // "Hi beautiful world" See the [example website source](examples/website/src/index.ts) for a more complex example, or the [advanced examples document](docs/advanced-ts.md). +#### React Native (Hermes) + +React Native's default engine, Hermes, does not expose a runtime `WebAssembly` +global, so the WebAssembly build cannot run there. For React Native, the package +ships a pure-JavaScript build produced by [Binaryen's `wasm2js`](https://github.com/WebAssembly/binaryen) +via its `react-native` entry point. + ### Python Install via uv or pip: diff --git a/docs/advanced-ts.md b/docs/advanced-ts.md index 7e53bf5..dd1633d 100644 --- a/docs/advanced-ts.md +++ b/docs/advanced-ts.md @@ -2,40 +2,65 @@ ## Edit Provenance -Track which changes came from where using `reconcileWithHistory`: +Track which changes came from where using `reconcileWithHistory`. The result's +`history` field is typed as `SpanWithHistory[]`, and each span's `history` is a +`History` string-literal union. -```javascript -const result = reconcileWithHistory( - 'Hello world', - 'Hello beautiful world', - 'Hi world' -); +```typescript +import { reconcileWithHistory, type History, type SpanWithHistory } from 'reconcile-text'; -console.log(result.text); // "Hi beautiful world" -console.log(result.history); /* -[ - { - "text": "Hello", - "history": "RemovedFromRight" - }, - { - "text": "Hi", - "history": "AddedFromRight" - }, - { - "text": " beautiful", - "history": "AddedFromLeft" - }, - { - "text": " ", - "history": "Unchanged" - }, - { - "text": "world", - "history": "Unchanged" +const result = reconcileWithHistory('Hello world', 'Hello beautiful world', 'Hi world'); + +console.log(result.text); // "Hi beautiful world" + +const history: SpanWithHistory[] = result.history; +console.log(history); +// [ +// { text: "Hello", history: "RemovedFromRight" }, +// { text: "Hi", history: "AddedFromRight" }, +// { text: " beautiful", history: "AddedFromLeft" }, +// { text: " ", history: "Unchanged" }, +// { text: "world", history: "Unchanged" }, +// ] + +const classByHistory = { + Unchanged: 'merge-unchanged', + AddedFromLeft: 'merge-added-left', + AddedFromRight: 'merge-added-right', + RemovedFromLeft: 'merge-removed-left', + RemovedFromRight: 'merge-removed-right', +} satisfies Record; +``` + +Using `satisfies Record` keeps the object literal's values +narrow while forcing every history case to be handled. If a future version adds +another `History` value, TypeScript will point at this mapping. + +For control flow, use the same union as an exhaustiveness check: + +```typescript +import type { History } from 'reconcile-text'; + +function historyLabel(history: History): string { + switch (history) { + case 'Unchanged': + return 'unchanged'; + case 'AddedFromLeft': + return 'added by left'; + case 'AddedFromRight': + return 'added by right'; + case 'RemovedFromLeft': + return 'removed from left'; + case 'RemovedFromRight': + return 'removed from right'; + default: + return assertNever(history); } -] -*/ +} + +function assertNever(value: never): never { + throw new Error(`Unhandled history value: ${value}`); +} ``` ## Tokenisation Strategies @@ -45,26 +70,162 @@ console.log(result.history); /* - **Word tokeniser** (`"Word"`) - Splits on word boundaries (recommended for prose) - **Character tokeniser** (`"Character"`) - Individual characters (fine-grained control) - **Line tokeniser** (`"Line"`) - Line-by-line (similar to `git merge` or more precisely [`git merge-file`](https://git-scm.com/docs/git-merge-file)) +- **Markdown tokeniser** (`"Markdown"`) - Splits on Markdown structural boundaries (headings, list items, paragraphs) + +```typescript +import { reconcile, type BuiltinTokenizer } from 'reconcile-text'; + +const tokenizers = [ + 'Word', + 'Character', + 'Line', + 'Markdown', +] as const satisfies readonly BuiltinTokenizer[]; + +const result = reconcile('abc', 'axc', 'abyc', 'Character'); +console.log(result.text); // "axyc" + +for (const tokenizer of tokenizers) { + const merged = reconcile( + '# Title\n\n- old item\n', + '# Title\n\n- old item\n- left item\n', + '# New title\n\n- old item\n', + tokenizer + ); + + console.log(tokenizer, merged.text); +} +``` ## Cursor Tracking -`reconcile-text` automatically tracks cursor positions through merges, which is useful for collaborative editors. Selections can be tracked by providing them as a pair of cursors. +`reconcile-text` automatically tracks cursor positions through merges, which is +useful for collaborative editors. Selections can be tracked by providing them as +a pair of cursors. -```javascript -const result = reconcile( - 'Hello world', - { - text: 'Hello beautiful world', - cursors: [{ id: 1, position: 6 }], // After "Hello " - }, - { - text: 'Hi world', - cursors: [{ id: 2, position: 0 }], // At the beginning - } -); +```typescript +import { reconcile, type TextWithOptionalCursors } from 'reconcile-text'; + +const left = { + text: 'Hello beautiful world', + cursors: [{ id: 1, position: 6 }], // After "Hello " +} satisfies TextWithOptionalCursors; + +const right = { + text: 'Hi world', + cursors: [{ id: 2, position: 0 }], // At the beginning +} satisfies TextWithOptionalCursors; + +const result = reconcile('Hello world', left, right); // Result: "Hi beautiful world" with repositioned cursors -console.log(result.text); // "Hi beautiful world" +console.log(result.text); // "Hi beautiful world" console.log(result.cursors); // [{ id: 2, position: 0 }, { id: 1, position: 3 }] ``` + > The `cursors` list is sorted by character position (not IDs). + +## Generic Helpers and Inference + +The exported merge functions are intentionally small: they merge strings, or +strings plus cursor metadata. In TypeScript applications, keep domain-specific +metadata in your own typed wrappers and let inference preserve the surrounding +shape. + +```typescript +import { reconcile, type BuiltinTokenizer } from 'reconcile-text'; + +type ReconciledText = Omit & { + text: string; +}; + +function reconcileDraft( + parent: TDraft, + left: TDraft, + right: TDraft, + tokenizer?: BuiltinTokenizer +): ReconciledText { + return { + ...right, + text: reconcile(parent.text, left.text, right.text, tokenizer).text, + }; +} + +interface MarkdownDraft { + id: string; + text: string; + updatedAt: Date; +} + +const parent: MarkdownDraft = { + id: 'intro', + text: '# Title\n\nOld text\n', + updatedAt: new Date('2026-01-01T00:00:00Z'), +}; + +const left: MarkdownDraft = { + ...parent, + text: '# Title\n\nOld text\n\n- left note\n', +}; + +const right: MarkdownDraft = { + ...parent, + text: '# New title\n\nOld text\n', +}; + +const merged = reconcileDraft(parent, left, right, 'Markdown'); +// merged is inferred as { id: string; updatedAt: Date; text: string } +``` + +Use `satisfies` for configuration objects and cursor payloads when you want +compile-time checking without widening everything to the library interface. + +```typescript +import type { BuiltinTokenizer, TextWithOptionalCursors } from 'reconcile-text'; + +const mergeOptions = { + tokenizer: 'Markdown', + renderDeletedSpans: true, +} satisfies { + tokenizer: BuiltinTokenizer; + renderDeletedSpans: boolean; +}; + +const documentWithSelection = { + text: 'Hello beautiful world', + cursors: [ + { id: 1, position: 6 }, + { id: 2, position: 15 }, + ], +} satisfies TextWithOptionalCursors; +``` + +## Compact Diffs + +Generate and apply compact diff representations. The TypeScript type is +`Array` for `diff()` and `Array` for +`undiff()`, because the underlying WebAssembly layer may represent integer +entries as `bigint`. + +```typescript +import { diff, undiff } from 'reconcile-text'; + +const original = 'Hello world'; +const changed = 'Hello beautiful world'; + +// Generate a compact diff +const changes = diff(original, changed); +console.log(changes); // [5, " beautiful world"] + +// Reconstruct the changed text from the diff +const reconstructed = undiff(original, changes); +console.assert(reconstructed === changed); +``` + +Diff entries are positive integers (retain N characters), negative integers +(delete N characters), and strings (insert text). + +## Complete Example + +For a complete browser example that renders `SpanWithHistory` values and cursor +selections, see the [example website source](../examples/website/src/index.ts). diff --git a/examples/website/package-lock.json b/examples/website/package-lock.json index faaa511..cfab4c3 100644 --- a/examples/website/package-lock.json +++ b/examples/website/package-lock.json @@ -28,11 +28,12 @@ }, "../../reconcile-js": { "name": "reconcile-text", - "version": "0.9.3", + "version": "0.12.1", "dev": true, "license": "MIT", "devDependencies": { "@types/jest": "^30.0.0", + "binaryen": "^123.0.0", "jest": "^30.3.0", "prettier": "^3.8.1", "reconcile-text": "file:../pkg", @@ -651,16 +652,6 @@ "node": ">=20.0.0" } }, - "node_modules/@trysound/sax": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/@trysound/sax/-/sax-0.2.0.tgz", - "integrity": "sha512-L7z9BgrNEcYyUYtF+HaEfiS5ebkh9jXqbszz7pC0hRBPaatV0XjSD3+eHrpqFemQfgwiFF0QPIarnIihIDn7OA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=10.13.0" - } - }, "node_modules/@types/body-parser": { "version": "1.19.6", "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", @@ -1145,6 +1136,7 @@ "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", "dev": true, "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -1180,11 +1172,12 @@ } }, "node_modules/ajv": { - "version": "8.17.1", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", - "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", @@ -1421,6 +1414,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -3396,9 +3390,9 @@ } }, "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "version": "4.17.23", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz", + "integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==", "dev": true, "license": "MIT" }, @@ -3986,6 +3980,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", @@ -4494,6 +4489,7 @@ "integrity": "sha512-+4N/u9dZ4PrgzGgPlKnaaRQx64RO0JBKs9sDhQ2pLgN6JQZ25uPQZKQYaBJU48Kd5BxgXoJ4e09Dq7nMcOUW3A==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "chokidar": "^4.0.0", "immutable": "^5.1.5", @@ -4550,6 +4546,16 @@ } } }, + "node_modules/sax": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.5.0.tgz", + "integrity": "sha512-21IYA3Q5cQf089Z6tgaUTr7lDAyzoTPx5HRtbhsME8Udispad8dC/+sziTNugOEx54ilvatQ9YCzl4KQLPcRHA==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=11.0.0" + } + }, "node_modules/schema-utils": { "version": "4.3.3", "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.3.3.tgz", @@ -5098,19 +5104,19 @@ } }, "node_modules/svgo": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/svgo/-/svgo-3.3.2.tgz", - "integrity": "sha512-OoohrmuUlBs8B8o6MB2Aevn+pRIH9zDALSR+6hhqVfa6fRwG/Qw9VUMSMW9VNg2CFc/MTIfabtdOVl9ODIJjpw==", + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/svgo/-/svgo-3.3.3.tgz", + "integrity": "sha512-+wn7I4p7YgJhHs38k2TNjy1vCfPIfLIJWR5MnCStsN8WuuTcBnRKcMHQLMM2ijxGZmDoZwNv8ipl5aTTen62ng==", "dev": true, "license": "MIT", "dependencies": { - "@trysound/sax": "0.2.0", "commander": "^7.2.0", "css-select": "^5.1.0", "css-tree": "^2.3.1", "css-what": "^6.1.0", "csso": "^5.0.5", - "picocolors": "^1.0.0" + "picocolors": "^1.0.0", + "sax": "^1.5.0" }, "bin": { "svgo": "bin/svgo" @@ -5303,6 +5309,7 @@ "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -5386,7 +5393,8 @@ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "dev": true, - "license": "0BSD" + "license": "0BSD", + "peer": true }, "node_modules/tsyringe": { "version": "4.10.0", @@ -5428,6 +5436,7 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -5568,6 +5577,7 @@ "integrity": "sha512-jTywjboN9aHxFlToqb0K0Zs9SbBoW4zRUlGzI2tYNxVYcEi/IPpn+Xi4ye5jTLvX2YeLuic/IvxNot+Q1jMoOw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@types/eslint-scope": "^3.7.7", "@types/estree": "^1.0.8", @@ -5617,6 +5627,7 @@ "integrity": "sha512-MfwFQ6SfwinsUVi0rNJm7rHZ31GyTcpVE5pgVA3hwFRb7COD4TzjUUwhGWKfO50+xdc2MQPuEBBJoqIMGt3JDw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@discoveryjs/json-ext": "^0.6.1", "@webpack-cli/configtest": "^3.0.1", diff --git a/examples/website/src/index.html b/examples/website/src/index.html index 1e7ac57..4519472 100644 --- a/examples/website/src/index.html +++ b/examples/website/src/index.html @@ -198,6 +198,8 @@