Compare commits

..
Author SHA1 Message Date
Anthony Stirling ccfdfcbc24 Merge branch 'main' into processor-docs-automation 2026-07-14 10:14:22 +01:00
2b118556f3 Merge hotfix/v2.14.2 into main (#7023)
Merges the `hotfix/v2.14.2` branch into `main`.
on the hotfix branch:

### What this actually changes on `main`
- **Version bump 2.14.1 → 2.14.2** `build.gradle`, `tauri.conf.json`,
both AUR `PKGBUILD`s, and the two `serverExperienceSimulations.ts`
test-config files.
- **Fix Postgres user settings for some users** removes `@Lob` from
`User.java that broke settings for some Postgres users.
- **Release workflow: stop msiexec hang in Windows signature verify**

---------

Co-authored-by: Ludy <Ludy87@users.noreply.github.com>
Co-authored-by: James Brunton <jbrunton96@gmail.com>
Co-authored-by: ConnorYoh <40631091+ConnorYoh@users.noreply.github.com>
Co-authored-by: LFdev <146497073+LFd3v@users.noreply.github.com>
Co-authored-by: EthanHealy01 <80844253+EthanHealy01@users.noreply.github.com>
2026-07-13 23:45:19 +01:00
Anthony Stirling fbaff56d1c Merge hotfix/v2.14.2 into main (v2.14.2 bump, Postgres user settings fix, msiexec release fix) 2026-07-13 20:23:14 +01:00
Anthony StirlingandGitHub a1b15e0570 Portal: dark disabled buttons and role column width (#7004)
# Description of Changes

Fixes disabled buttons rendering as plain grey in dark mode, and widens
the Users role column so "Organisation Owner" no longer clips.

Part of a portal (processor) UI-consistency pass, split into small
focused PRs.

## Before / after

<!-- paste before / after screenshots here -->

---

## Checklist

### General

- [x] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [x] I have performed a self-review of my own code
- [x] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [x] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have run `task check` to verify linters, typechecks, and tests
pass
- [x] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md#7-testing)
for more details.
2026-07-13 15:00:01 +00:00
James BruntonandGitHub 76549288a9 Redesign S3 connections to use connection resolver (#6965)
# Description of Changes
Redesign S3 connections based on feedback from #6948. Also redesigns the
UI for Sources to make them more like the Pipelines page which improves
UX quite a bit. There's still plenty more UI/UX work for Sources and S3
but moving in the right direction.
2026-07-13 14:44:41 +00:00
Anthony StirlingandGitHub b5d0c4a5ed Portal Home: SVG quick-action icons (#6998)
# Description of Changes

Replaces the ASCII quick-action glyphs on the Home hero with crisp
stroke SVG icons.

Part of a portal (processor) UI-consistency pass, split into small
focused PRs.

## Before / after
<img width="2880" height="2726" alt="after-home-dark"
src="https://github.com/user-attachments/assets/ab4c3611-25a6-4b2c-a993-99ce2f7b7558"
/>
<img width="2880" height="2726" alt="after-home-light"
src="https://github.com/user-attachments/assets/b0b342b9-4436-4791-b0a6-92837c3ec355"
/>
<img width="2880" height="2726" alt="before-home-dark"
src="https://github.com/user-attachments/assets/93d73393-5a81-4f34-a483-90671a6ae79e"
/>
<img width="2880" height="2726" alt="before-home-light"
src="https://github.com/user-attachments/assets/119389cc-78ef-4a43-9f9a-d551b03c9733"
/>


---

## Checklist

### General

- [x] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [x] I have performed a self-review of my own code
- [x] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [x] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have run `task check` to verify linters, typechecks, and tests
pass
- [x] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md#7-testing)
for more details.
2026-07-13 13:26:07 +00:00
Anthony StirlingandGitHub 8bfcf6eb7e Portal: theme-aware code blocks and hero-navy token (#7003)
# Description of Changes

Makes the code-snippet boxes theme-aware (a light palette in light mode)
and moves the hero navy into a design token without changing the colour
itself.

Part of a portal (processor) UI-consistency pass, split into small
focused PRs.

## Before / after

<img width="2136" height="272" alt="after-codeblock-light"
src="https://github.com/user-attachments/assets/ebdd4a7d-2d1a-429a-971b-0b04e93854fe"
/>
<img width="1800" height="740" alt="before-codeblock-light"
src="https://github.com/user-attachments/assets/6819231a-10d5-4730-9b7d-3c36dc1c8170"
/>

---

## Checklist

### General

- [x] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [x] I have performed a self-review of my own code
- [x] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [x] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have run `task check` to verify linters, typechecks, and tests
pass
- [x] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md#7-testing)
for more details.
2026-07-13 13:26:00 +00:00
James BruntonandGitHub b019f9b570 Fix missing and broken translations in Processor (#7016)
# Description of Changes
<img width="385" height="92" alt="image"
src="https://github.com/user-attachments/assets/7f4b1921-72e8-4c18-a4de-4b9736a5a2f1"
/>

Started from trying to fix this, but became a larger piece of work to
find missing/broken translations in the Processor and fix as many as I
could.
2026-07-13 12:55:36 +00:00
Frooodle 91f89cbbb8 Merge branch 'main' into processor-docs-automation 2026-07-13 11:17:09 +01:00
Anthony StirlingandGitHub 3631dfdf93 Merge branch 'main' into processor-docs-automation 2026-07-12 10:18:13 +01:00
Anthony Stirling 1b992fe1a3 Portal docs: de-duplicate heading anchors so the TOC highlights one section 2026-07-12 10:14:28 +01:00
Anthony Stirling 5d5b8ed39d Portal docs: add On this page TOC, edge-to-edge nav, centred content 2026-07-12 00:00:14 +01:00
Anthony Stirling c31f47216d Portal docs: load images eagerly so they render in the scroll pane 2026-07-11 22:40:10 +01:00
Anthony Stirling fc04542552 Portal: auto-synced Documentation tab with full-text search 2026-07-11 22:12:19 +01:00
Anthony Stirling 38ccea074c Version bump 2026-07-08 10:50:37 +01:00
Anthony Stirling a7307ff393 Fix Postgres user settings for some users 2026-07-08 10:50:36 +01:00
Anthony Stirling 72729e99c1 fix(release): stop msiexec hang in Windows signature verify; don't force latest or regen release notes 2026-07-07 23:35:12 +01:00
Anthony Stirling 5fba2720f0 Fix cert sign not showing under certain instances (#6908) 2026-07-07 22:45:56 +01:00
01a1ef8c44 Fix missing app icon on Linux/Wayland (#6875)
Co-authored-by: EthanHealy01 <80844253+EthanHealy01@users.noreply.github.com>
Co-authored-by: Ludy <Ludy87@users.noreply.github.com>
2026-07-07 22:15:01 +01:00
LudyandAnthony Stirling 8535c7e9ac feat(ui): add dedicated third-party license sections to settings (#6820) 2026-07-07 22:15:01 +01:00
ConnorYohandAnthony Stirling cca3f42623 Set App version to v2.14.1 (#6891)
Upped version in build.gradle then ran build so version falls through
2026-07-07 12:15:01 +01:00
James BruntonandAnthony Stirling 1b7ffcdbac Fix tooltip positioning on Add Page Numbers (#6885)
# Description of Changes
## Before

<img width="483" height="227" alt="image"
src="https://github.com/user-attachments/assets/4bf86eec-a9cc-4f63-84f0-4eb2bd535bab"
/>

## After

<img width="732" height="235" alt="image"
src="https://github.com/user-attachments/assets/101d2ea4-36e8-4e8f-990a-d72b33fa0ac2"
/>
2026-07-07 12:09:51 +01:00
LudyandAnthony Stirling 67a0ca6110 fix(frontend): respect analytics config before initializing PostHog (#6812)
# Description of Changes

Please provide a summary of the changes, including:

- What was changed
- Moved PostHog startup out of `index.tsx` and into a config-aware
initializer inside `AppProviders`.
- Added a dedicated `usePosthogTracking` hook that only initializes
PostHog when `enableAnalytics` is explicitly `true` and `enablePosthog`
is not disabled.
- Kept cookie-consent handling in the same flow so consent is applied
only after PostHog is actually initialized.
- Removed the unconditional `PostHogProvider` and `posthog.init(...)`
bootstrap from the app entrypoint.
- Added targeted frontend tests covering analytics-disabled and
analytics-enabled startup behavior.

- Why the change was made
- The previous frontend bootstrap initialized PostHog before app config
was loaded, so disabling analytics in the UI or via environment settings
did not prevent PostHog network activity.
- This change makes analytics behavior follow the server-provided config
instead of always connecting on page load.

Closes #6358

---

## Checklist

### General

- [x] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [x] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [x] I have performed a self-review of my own code
- [x] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [x] I have run `task check` to verify linters, typechecks, and tests
pass
- [x] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md#7-testing)
for more details.
2026-07-07 12:09:51 +01:00
Anthony Stirling 8e4b2e2fc6 Disable update check and notification in SaaS mode (#6863)
# Description of Changes

In SaaS mode the self-hosted "Update Available" notification could still
appear and the update-check code (external call to
`supabase.stirling.com/functions/v1/updates`) still ran, even though the
cloud owns app versioning. The web `UpdateStartupPopup` was already
SaaS-gated via a null override, but two other paths were not:

- **Desktop app in SaaS connection mode** - `useDesktopUpdatePopup()`
ran its startup check and rendered the `UpdateModal` regardless of
connection mode, so a self-hosted update popup appeared while connected
to SaaS.
- **Settings → General** - the core `GeneralSection` fired
`checkForUpdate()` on mount unconditionally, even when the update
section was hidden (as SaaS does), so the external call still ran.

**What changed**

- `useDesktopUpdatePopup.ts` - the startup timer now bails out
immediately when `connectionModeService.getCurrentMode() === "saas"`. No
mode lookup, no external fetch, no modal.
- `core/GeneralSection.tsx` - the mount `checkForUpdate()` now returns
early when `hideUpdateSection` is set, so hiding the section (web SaaS,
managed-disabled desktop) also stops the external call.
- `desktop/GeneralSection.tsx` - passes `hideUpdateSection` when
`useSaaSMode()` is true, which (via the above) suppresses the settings
check in desktop-SaaS too.

**Why** - in SaaS the update check should never be called and no update
notification should be shown; the cloud handles versioning.

---

## Checklist

### General

- [x] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [x] I have performed a self-review of my own code
- [x] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [x] I have run `task check` to verify linters, typechecks, and tests
pass
- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md#7-testing)
for more details.
2026-07-07 12:09:51 +01:00
Anthony Stirling 3c93457021 Fix rearrange-pages DUPLICATE producing shared page nodes (pypdf cyclic-references CI break) (#6851) 2026-07-07 12:09:51 +01:00
258 changed files with 6975 additions and 37178 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
# Maintainer: Stirling PDF Inc <contact@stirlingpdf.com>
pkgname=stirling-pdf-desktop
pkgver=2.14.1
pkgver=2.14.2
pkgrel=1
pkgdesc="Locally hosted, web-based PDF manipulation tool (Tauri desktop app, official Stirling PDF Inc build)"
arch=('x86_64')
+1 -1
View File
@@ -1,6 +1,6 @@
# Maintainer: Stirling PDF Inc <contact@stirlingpdf.com>
pkgname=stirling-pdf-server-bin
pkgver=2.14.1
pkgver=2.14.2
pkgrel=1
pkgdesc="Locally hosted, web-based PDF manipulation tool (server JAR, prebuilt)"
arch=('any')
+23 -6
View File
@@ -510,6 +510,7 @@ jobs:
# cargo output unsigned, so checking it produces false negatives.
- name: Verify Windows Code Signature
if: ${{ matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
timeout-minutes: 15
shell: pwsh
run: |
$allSigned = $true
@@ -531,11 +532,26 @@ jobs:
# Extract MSI and verify the inner exe (the file that actually gets installed).
# This is the critical check - AV flags the installed exe at runtime.
# Use lessmsi, not `msiexec /a`: msiexec serializes on the global
# _MSIExecute mutex and hangs forever on hosted runners when another
# installer is busy. lessmsi reads MSI tables directly - no mutex, no service.
$msi = $msiFiles[0].FullName
$extractDir = Join-Path $env:RUNNER_TEMP "msi-verify"
if (Test-Path $extractDir) { Remove-Item $extractDir -Recurse -Force }
$proc = Start-Process msiexec.exe -ArgumentList '/a', $msi, '/qn', "TARGETDIR=$extractDir" -Wait -PassThru -NoNewWindow
if ($proc.ExitCode -eq 0) {
New-Item -ItemType Directory -Force -Path $extractDir | Out-Null
choco install lessmsi -y --no-progress --limit-output | Out-Null
# Bound the extraction and kill on hang (defence in depth over timeout-minutes).
$proc = Start-Process lessmsi -ArgumentList 'x', "`"$msi`"", "`"$extractDir\`"" -PassThru -NoNewWindow
if (-not $proc.WaitForExit(120000)) {
try { $proc.Kill() } catch {}
Write-Host "[ERROR] MSI extraction timed out after 120s"
$allSigned = $false
} elseif ($proc.ExitCode -ne 0) {
Write-Host "[ERROR] Failed to extract MSI for verification (exit code: $($proc.ExitCode))"
$allSigned = $false
} else {
$innerExe = Get-ChildItem -Path $extractDir -Filter "stirling-pdf.exe" -Recurse -File | Select-Object -First 1
if ($innerExe) {
$sig = Get-AuthenticodeSignature -FilePath $innerExe.FullName
@@ -548,9 +564,6 @@ jobs:
Write-Host "[ERROR] Could not find stirling-pdf.exe inside MSI"
$allSigned = $false
}
} else {
Write-Host "[ERROR] Failed to extract MSI for verification (exit code: $($proc.ExitCode))"
$allSigned = $false
}
if (-not $allSigned) {
@@ -800,7 +813,11 @@ jobs:
uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3.0.0
with:
tag_name: v${{ needs.determine-matrix.outputs.version }}
generate_release_notes: true
# Don't regenerate/append notes on re-runs, and don't force this into the
# "Latest" slot - leave the release body and latest marker as they are.
generate_release_notes: false
append_body: false
make_latest: false
fail_on_unmatched_files: true
# Installers + updater payloads + manifest. .sig contents are embedded
# in latest.json so the .sig files themselves are not uploaded.
+92
View File
@@ -0,0 +1,92 @@
name: Sync Portal Docs
# Regenerates the portal Developer Docs manifest from the Stirling docs repo and
# opens a PR when it changes. Runs weekly, on manual dispatch, or when the docs
# repo fires a `docs-updated` repository_dispatch.
on:
schedule:
- cron: "0 6 * * 1"
workflow_dispatch:
inputs:
ref:
description: "Docs repo ref (branch or tag) to sync from"
required: false
default: "main"
repository_dispatch:
types: [docs-updated]
concurrency:
group: ${{ github.workflow }}
cancel-in-progress: true
permissions:
contents: read
jobs:
sync:
name: Sync docs manifest
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write
pull-requests: write
steps:
- name: Harden Runner
uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 # v2.19.3
with:
egress-policy: audit
- name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
fetch-depth: 0
persist-credentials: false
- name: Setup GitHub App Bot
id: setup-bot
uses: ./.github/actions/setup-bot
with:
app-id: ${{ secrets.GH_APP_ID }}
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
- name: Set up Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version: "22"
cache: "npm"
cache-dependency-path: frontend/package-lock.json
- name: Install frontend dependencies
working-directory: frontend
env:
NPM_CONFIG_IGNORE_SCRIPTS: "true"
run: npm ci --ignore-scripts --audit=false --fund=false
- name: Regenerate docs manifest
working-directory: frontend
env:
DOCS_REF: ${{ github.event.inputs.ref || github.event.client_payload.ref || 'main' }}
GITHUB_TOKEN: ${{ steps.setup-bot.outputs.token }}
run: npm run docs:sync
- name: Create Pull Request
id: cpr
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
with:
token: ${{ steps.setup-bot.outputs.token }}
commit-message: "Sync portal docs from docs repo"
committer: ${{ steps.setup-bot.outputs.committer }}
author: ${{ steps.setup-bot.outputs.committer }}
signoff: true
branch: sync-portal-docs
base: main
title: "Sync portal docs from docs repo"
body: |
Auto-generated by ${{ steps.setup-bot.outputs.app-slug }}[bot].
Regenerates `frontend/editor/src/portal/generated/docsManifest.json`
from the Stirling docs repo via `npm run docs:sync`.
labels: documentation,github-actions,frontend
add-paths: frontend/editor/src/portal/generated/docsManifest.json
delete-branch: true
sign-commits: true
@@ -1,515 +0,0 @@
package stirling.software.SPDF.controller.api;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.Operation;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.annotations.api.GeneralApi;
import stirling.software.common.service.CustomPDFDocumentFactory;
/**
* Charcode-encode helper for the v2 PDF text editor.
*
* <p>The frontend editor uses PDFium-WASM, which exposes {@code FPDFText_SetCharcodes} for writing
* new text using raw font charcodes (skipping PDFium's broken reverse Unicode→CID lookup for
* embedded subset fonts). What PDFium does NOT expose is the byte-encoding side of an existing font
* - given a PDFont and a Unicode string, what are the bytes the font's encoding produces? PDFBox
* does have that ({@link PDFont#encode}).
*
* <p>This endpoint accepts the source PDF + a "locator" describing where to find the font in
* question (page index + a sample char known to render in the target font, optionally narrowed by
* the font's /BaseFont name) + the Unicode text the frontend wants to encode. It returns the
* charcode sequence the frontend can pass to {@code FPDFText_SetCharcodes}.
*
* <p>If the locator can't find a matching text fragment, or if the font can't encode some chars,
* the response reports which chars are missing so the frontend can fall back to Helvetica per char.
*/
@Slf4j
@GeneralApi
@RequiredArgsConstructor
public class PdfTextEditorV2CharcodeController {
/** Reject JSON bodies whose base64 implies a decoded PDF larger than this. */
private static final int MAX_PDF_BYTES = 100 * 1024 * 1024;
/**
* Upper bound on {@code request.text} code units. Editor requests are word-sized; an unbounded
* text drove a per-code-point encode/exception loop (CPU burn) on crafted requests.
*/
private static final int MAX_TEXT_CHARS = 4096;
/** Nested form-XObject resource dictionaries visited per lookup (cycle/DoS guard). */
private static final int MAX_RESOURCE_DICTS = 32;
/** Bound on the reverse-map cache so a busy multi-document server can't grow it forever. */
private static final int REVERSE_MAP_CACHE_MAX = 32;
/** Access-ordered LRU bounded at {@link #REVERSE_MAP_CACHE_MAX} entries. */
private static final class BoundedReverseMapCache
extends java.util.LinkedHashMap<String, java.util.Map<String, Long>> {
private static final long serialVersionUID = 1L;
BoundedReverseMapCache() {
super(16, 0.75f, true);
}
@Override
protected boolean removeEldestEntry(
java.util.Map.Entry<String, java.util.Map<String, Long>> eldest) {
return size() > REVERSE_MAP_CACHE_MAX;
}
}
/**
* Reverse Unicode→charcode maps, cached by {@code pdfContentHash + "|" + fontName} so repeated
* edits on the SAME document reuse the 0..0xFFFF {@code toUnicode} probe instead of re-running
* it (up to 65 536 lookups per font) on every keystroke's request. Access-ordered LRU bounded
* by {@link #REVERSE_MAP_CACHE_MAX}.
*
* <p>The previous {@code WeakHashMap<PDFont, ...>} never hit across requests: every request
* loads a fresh {@link PDDocument} hence a fresh {@link PDFont} instance, so the key was never
* equal from one request to the next - it was effectively dead code. Keying on the PDF bytes'
* hash gives a stable cross-request key.
*/
private static final java.util.Map<String, java.util.Map<String, Long>> REVERSE_MAP_CACHE =
java.util.Collections.synchronizedMap(new BoundedReverseMapCache());
private final CustomPDFDocumentFactory pdfDocumentFactory;
// NOTE: PDFBox's PDSimpleFont emits one "No Unicode mapping for .notdef" WARN per probed
// charcode when buildReverseUnicodeMap iterates 0..0xFFFF, which once flooded info.log to
// ~1.4 GB overnight. That logger is silenced DECLARATIVELY in logback.xml (a config entry ops
// can see and revert) rather than by mutating the global logger from a static block here -
// mutating it at class-load time hid the same warnings from every other tool in the JVM with
// no trace in configuration.
@Data
public static class EncodeCharcodesRequest {
/** Base64-encoded original PDF. The frontend already has the bytes loaded. */
private String pdfBase64;
/** 0-based page index containing the font sample. */
private int pageIndex;
/**
* A char known to exist on the page in the target font. Combined with {@code fontName}
* (when supplied) it locates the source PDFont via its ToUnicode CMap.
*/
private String locatorChar;
/**
* Optional /BaseFont name of the target font (as PDFium's FPDFFont_GetBaseFontName reports
* it). When a page has TWO fonts that both render {@code locatorChar}, this disambiguates
* which one to encode against - otherwise the first font found wins and a cross-font edit
* gets the wrong font's charcode. Null = keep the legacy first-match behaviour.
*/
private String fontName;
/** Unicode text the frontend wants to encode. */
private String text;
}
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class EncodeCharcodesResponse {
/**
* Per-char charcode array (one entry per code point in {@code request.text}). When the
* font's encoding produces multi-byte sequences, each char gets the full unsigned int value
* of its bytes packed big-endian (so a 2-byte CID like 0x004D becomes 77).
*/
private List<Long> charcodes;
/** Chars from the request that the font couldn't encode. */
private List<String> missing;
/** Diagnostic note - included so the frontend HUD can show what happened. */
private String note;
/** Set when the request failed entirely (bad pdf bytes, no matching font, etc.). */
private String error;
}
@Operation(
summary = "Encode Unicode → font charcodes for the v2 PDF text editor",
description =
"""
Frontend-only helper: takes the source PDF, a locator pointing at an existing
char rendered in the target font, and a Unicode string. Returns the byte
sequence the target font produces for that Unicode, packed as one unsigned
int per char. The frontend then calls FPDFText_SetCharcodes with the
returned ints to inject new text that reuses the embedded font's actual
glyphs. Chars the font can't encode are listed in `missing` so the caller
can fall back per-char.
""")
@PostMapping(
value = "/pdf-text-editor-v2/encode-charcodes",
consumes = "application/json",
produces = "application/json")
public ResponseEntity<EncodeCharcodesResponse> encodeCharcodes(
@RequestBody EncodeCharcodesRequest request) {
EncodeCharcodesResponse resp = new EncodeCharcodesResponse();
if (request == null
|| request.getPdfBase64() == null
|| request.getText() == null
|| request.getLocatorChar() == null) {
resp.setError("missing required fields");
return ResponseEntity.badRequest().body(resp);
}
// length/4*3 bounds the decoded size without decoding, so we reject early before
// allocating.
String b64 = request.getPdfBase64();
if ((long) b64.length() / 4 * 3 > MAX_PDF_BYTES) {
resp.setError("pdf too large");
return ResponseEntity.status(413).body(resp);
}
if (request.getText().length() > MAX_TEXT_CHARS || request.getLocatorChar().length() > 4) {
resp.setError("text too long");
return ResponseEntity.badRequest().body(resp);
}
byte[] pdfBytes;
try {
pdfBytes = Base64.getDecoder().decode(b64);
} catch (IllegalArgumentException e) {
resp.setError("pdfBase64 is not valid base64");
return ResponseEntity.badRequest().body(resp);
}
try (PDDocument doc = pdfDocumentFactory.load(pdfBytes, true)) {
if (request.getPageIndex() < 0 || request.getPageIndex() >= doc.getNumberOfPages()) {
resp.setError("pageIndex out of range");
return ResponseEntity.badRequest().body(resp);
}
PDPage page = doc.getPage(request.getPageIndex());
// Skip walking the page's content stream (it crashes on Type3 fonts with
// UnsupportedOperationException("Not implemented: Type3") before we can do anything
// useful). Instead enumerate the page's font resources and pick the first one whose
// ToUnicode CMap maps SOME charcode to the locator char.
// For Chrome/Skia-printed PDFs that emit one Type3 font per glyph, this lands on
// the exact font that renders the locator char.
PDFont font =
findFontByToUnicode(page, request.getLocatorChar(), request.getFontName(), doc);
if (font == null) {
resp.setError(
"no font on page "
+ request.getPageIndex()
+ " renders locatorChar="
+ request.getLocatorChar()
+ (request.getFontName() != null
? " (fontName=" + request.getFontName() + ")"
: ""));
return ResponseEntity.ok(resp);
}
// Build a reverse Unicode→charcode map by walking the font's ToUnicode CMap.
// This is the ONLY path that works for Type3 fonts (PDFBox's font.encode() throws
// "Not implemented: Type3" on them), and it also acts as a more reliable fallback
// for subset fonts whose encode() rejects chars not in the original document.
//
// For Sample.pdf specifically, every embedded font is Type3 (Chrome/Skia output),
// but they all carry a ToUnicode CMap mapping CIDs back to Unicode. We iterate
// charcodes 0..0xFFFF, call font.toUnicode(cc) for each, and record the inverse
// mapping for the chars the user wants to write.
java.util.Map<String, Long> reverseMap =
buildReverseUnicodeMap(
pdfBytes, font, request.getPageIndex(), request.getLocatorChar());
List<Long> charcodes = new ArrayList<>();
List<String> missing = new ArrayList<>();
String text = request.getText();
int i = 0;
while (i < text.length()) {
int cp = text.codePointAt(i);
String oneChar = new String(Character.toChars(cp));
i += Character.charCount(cp);
// Whitespace is NEVER charcode-reused. Subset Type1/LaTeX fonts
// usually have no real space glyph, yet font.encode(0x20) still
// returns code 0x20 without throwing - and SetCharcodes(0x20)
// then paints whatever glyph sits at that subset code (e.g. „
// quotedblbase in LMRoman). Report whitespace as missing so the
// frontend emits it as a positional gap instead.
if (Character.isWhitespace(cp)) {
missing.add(oneChar);
continue;
}
// 1st try: font.encode() - works for Type0/TrueType/Type1
Long packed = null;
try {
byte[] encoded = font.encode(oneChar);
long p = 0L;
for (byte b : encoded) p = (p << 8) | (b & 0xff);
packed = p;
} catch (IOException
| IllegalArgumentException
| UnsupportedOperationException encodeEx) {
// 2nd try: ToUnicode reverse lookup - works for Type3 + anything with a CMap
packed = reverseMap.get(oneChar);
}
if (packed != null) charcodes.add(packed);
else missing.add(oneChar);
}
resp.setCharcodes(charcodes);
if (!missing.isEmpty()) resp.setMissing(missing);
resp.setNote(
"font="
+ font.getName()
+ " encoded "
+ charcodes.size()
+ " of "
+ (charcodes.size() + missing.size())
+ " chars");
return ResponseEntity.ok(resp);
} catch (IOException e) {
log.warn("encodeCharcodes: failed to load PDF", e);
resp.setError("failed to load PDF");
return ResponseEntity.badRequest().body(resp);
} catch (RuntimeException e) {
log.warn("encodeCharcodes: unexpected error", e);
resp.setError("unexpected error");
return ResponseEntity.status(500).body(resp);
}
}
/**
* Walk every font resource on the page (and on any nested Form XObjects we can reach) and
* return the FIRST font whose ToUnicode CMap includes the requested char. This avoids running
* PDFStreamEngine.processPage, which throws UnsupportedOperationException on Type3 font glyph
* rendering. The PDFont lookup itself is purely metadata-driven and works on all subtypes.
*/
/** How strictly {@code scanResources} compares a candidate font's name to the requested one. */
private enum NameMatch {
/** Full /BaseFont equality, subset tag included. */
EXACT,
/** Equality after stripping the "ABCDEF+" subset tag from both names. */
STRIPPED,
/** No name constraint: first font that renders the char wins. */
ANY
}
private static PDFont findFontByToUnicode(
PDPage page, String wantChar, String fontName, PDDocument doc) {
try {
PDResources resources = page.getResources();
// When a target font name is supplied, prefer an EXACT /BaseFont match (tag included)
// BEFORE a tag-stripped one. Two distinct subsets of the same base font ("ABCDEF+Arial"
// and "GHIJKL+Arial", common after a merge) share different charcode spaces but compare
// equal once the tag is stripped, so an exact match must win first or we could encode
// against the wrong subset. Only when no exact match exists do we fall back to the
// tag-stripped comparison (a re-saved subset whose tag changed).
if (fontName != null && !fontName.isEmpty()) {
PDFont exact = scanResourceTree(resources, wantChar, fontName, NameMatch.EXACT);
if (exact != null) return exact;
PDFont stripped =
scanResourceTree(resources, wantChar, fontName, NameMatch.STRIPPED);
if (stripped != null) return stripped;
// The frontend NAMED the font it is editing. Falling back to "any font that
// renders the char" would hand back a DIFFERENT font's charcodes, which the
// frontend then writes into the named font's text object - wrong glyph, and the
// backend strategy skips all frontend validation. Report the char missing
// instead so the caller takes its own fallback path.
return null;
}
return scanResourceTree(resources, wantChar, null, NameMatch.ANY);
} catch (RuntimeException ignore) {
// Be defensive: any single bad font shouldn't sink the whole request.
}
return null;
}
/**
* Breadth-first {@link #scanResources} over the page's resources AND every nested form
* XObject's resources (bounded by {@link #MAX_RESOURCE_DICTS}, cycle-safe). The v2 reader
* surfaces form-XObject text as editable, so its fonts must be findable too - previously only
* page-level resources were scanned and XObject text degraded to a wrong page font or
* Helvetica.
*/
private static PDFont scanResourceTree(
PDResources resources, String wantChar, String wantName, NameMatch mode) {
java.util.ArrayDeque<PDResources> queue = new java.util.ArrayDeque<>();
java.util.Set<org.apache.pdfbox.cos.COSDictionary> seen =
java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>());
if (resources != null) queue.add(resources);
PDFont nameOnly = null;
int visited = 0;
while (!queue.isEmpty() && visited < MAX_RESOURCE_DICTS) {
PDResources res = queue.poll();
if (!seen.add(res.getCOSObject())) continue;
visited++;
ScanResult r = scanResources(res, wantChar, wantName, mode);
if (r.probed() != null) return r.probed();
if (nameOnly == null) nameOnly = r.nameOnly();
try {
for (org.apache.pdfbox.cos.COSName xn : res.getXObjectNames()) {
try {
org.apache.pdfbox.pdmodel.graphics.PDXObject xo = res.getXObject(xn);
if (xo
instanceof
org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject form) {
PDResources fr = form.getResources();
if (fr != null) queue.add(fr);
}
} catch (IOException | RuntimeException ignore) {
}
}
} catch (RuntimeException ignore) {
}
}
// A name-matching font whose ToUnicode probe missed (or that has no ToUnicode at all):
// font.encode() may still succeed, so return it rather than degrading a correctly-named
// font. Never used in ANY mode (no name constraint -> an unprobed font is arbitrary).
return nameOnly;
}
/** One probed match (ToUnicode hit) plus, for named modes, a name-only candidate. */
private record ScanResult(PDFont probed, PDFont nameOnly) {}
/**
* Return a font on the page that renders {@code wantChar}, subject to {@code mode}: {@code
* EXACT} requires the /BaseFont to equal {@code wantName} verbatim, {@code STRIPPED} compares
* with subset tags removed, {@code ANY} ignores the name entirely (first font with the char
* wins).
*/
private static ScanResult scanResources(
PDResources resources, String wantChar, String wantName, NameMatch mode) {
if (resources == null) return new ScanResult(null, null);
String wantStripped = stripSubsetTag(wantName);
// Bound a crafted page declaring many fonts none of which match (CPU-DoS guard).
int scanned = 0;
final int MAX_FONTS = 64;
PDFont nameOnly = null;
for (org.apache.pdfbox.cos.COSName name : resources.getFontNames()) {
if (++scanned > MAX_FONTS) break;
PDFont font;
try {
font = resources.getFont(name);
} catch (IOException | RuntimeException e) {
continue;
}
if (font == null) continue;
if (mode == NameMatch.EXACT) {
if (wantName == null || !wantName.equals(font.getName())) continue;
} else if (mode == NameMatch.STRIPPED) {
if (wantStripped == null || !wantStripped.equals(stripSubsetTag(font.getName()))) {
continue;
}
}
// Cheap inverse-CMap probe: iterate codes until we hit one whose toUnicode is wantChar.
// For Type3 with at most ~16 glyphs, this is microseconds. For full Type0 subsets
// it's a few-thousand-iteration scan.
int upper = font.isStandard14() ? 256 : 0x10000;
boolean probeHit = false;
for (int cc = 0; cc < upper; cc++) {
String u;
try {
u = font.toUnicode(cc);
} catch (Exception ignore) {
continue;
}
if (u != null && u.equals(wantChar)) {
probeHit = true;
break;
}
}
if (probeHit) return new ScanResult(font, nameOnly);
// Name matched but the probe missed (e.g. no ToUnicode CMap at all - common for
// Type0/Identity-H). Remember it: font.encode() may still handle the chars.
if (mode != NameMatch.ANY && nameOnly == null) nameOnly = font;
}
return new ScanResult(null, nameOnly);
}
/** Drop the 6-letter "ABCDEF+" subset prefix PDF puts on subset /BaseFont names. */
private static String stripSubsetTag(String fontName) {
if (fontName == null) return null;
if (fontName.length() > 7
&& fontName.charAt(6) == '+'
&& fontName.chars().limit(6).allMatch(c -> c >= 'A' && c <= 'Z')) {
return fontName.substring(7);
}
return fontName;
}
/**
* Build a Unicode→charcode map for a font by iterating every charcode in 0..0xFFFF and asking
* the font's ToUnicode CMap what Unicode it maps to. Charcodes that aren't in the CMap throw
* inside toUnicode (PDFBox returns null or throws depending on font subtype), and those are
* skipped silently.
*
* <p>This is the encoding inverse PDFBox doesn't expose directly. For Type3 fonts (where
* font.encode() throws "Not implemented"), this is the ONLY way to write text in the same font
* - we look up the user's char in the reverse map and pass that charcode to
* FPDFText_SetCharcodes on the frontend.
*
* <p>The 0..0xFFFF range is sufficient for Type0/CIDFontType2 fonts (CIDs are 16-bit). For
* single-byte fonts the loop short-circuits after 256. We don't go higher because no PDF font
* has a CID outside that range in practice; the per-font result is memoised in {@link
* #REVERSE_MAP_CACHE} so the 65 536-entry probe runs once per document+font, not per request.
*/
private static java.util.Map<String, Long> buildReverseUnicodeMap(
byte[] pdfBytes, PDFont font, int pageIndex, String locatorChar) {
// Cache by (PDF content hash | font name) so repeated edits on the SAME document reuse the
// 0..0xFFFF probe instead of rebuilding it on every keystroke's request. Two fonts sharing
// a name within one PDF (rare) would collide, but that is no worse than the previous
// no-cross-request-cache behaviour, and the hash isolates different documents.
//
// NAME-LESS fonts (Skia/Chrome Type3 output has no /BaseFont, so getName() is null) must
// NOT share one "hash|null" entry - every name-less font in the doc would be served the
// FIRST one's map (wrong glyphs, trusted by the frontend). Key those by the lookup inputs
// (page + locator char) instead: for identical bytes the font located from those inputs is
// deterministic, so the cached map always belongs to the font that will consume it.
String fname = font.getName();
String key =
fname != null
? sha256Hex(pdfBytes) + "|n|" + fname
: sha256Hex(pdfBytes) + "|p" + pageIndex + "|c|" + locatorChar;
return REVERSE_MAP_CACHE.computeIfAbsent(key, k -> computeReverseUnicodeMap(font));
}
/** Lowercase hex SHA-256 of the PDF bytes; used as the reverse-map cache key. */
private static String sha256Hex(byte[] bytes) {
try {
byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(bytes);
StringBuilder sb = new StringBuilder(digest.length * 2);
for (byte b : digest) {
sb.append(Character.forDigit((b >> 4) & 0xf, 16));
sb.append(Character.forDigit(b & 0xf, 16));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
// SHA-256 is always present in a JRE; fall back to a length+hash key just in case so
// the cache still functions (correctness holds - collisions only cost a rebuild).
return bytes.length + ":" + java.util.Arrays.hashCode(bytes);
}
}
private static java.util.Map<String, Long> computeReverseUnicodeMap(PDFont font) {
java.util.Map<String, Long> out = new java.util.HashMap<>();
int upper = font.isStandard14() ? 256 : 0x10000;
for (int cc = 0; cc < upper; cc++) {
String u;
try {
u = font.toUnicode(cc);
} catch (Exception ignore) {
continue;
}
if (u == null || u.isEmpty()) continue;
// First charcode wins for a given Unicode (the canonical mapping).
out.putIfAbsent(u, (long) cc);
}
return out;
}
}
+5 -43
View File
@@ -15,62 +15,24 @@
<encoder>
<pattern>%d %p %c{1} [%thread] %m%n</pattern>
</encoder>
<!-- SizeAndTimeBased: rotate daily OR every 100 MB, keep 1 day of history,
hard cap the appender's total disk footprint at 200 MB so a runaway
logger can't ever fill the disk (see GENERAL appender note). -->
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/auth-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<maxFileSize>100MB</maxFileSize>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/auth-%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>1</maxHistory>
<totalSizeCap>200MB</totalSizeCap>
</rollingPolicy>
</appender>
<!-- Rolling File Appender for General Logs
Why SizeAndTimeBased + totalSizeCap: a previous build of the v2 PDF
text editor's reverse-CMap probe loop triggered PDSimpleFont to emit
one "No Unicode mapping for .notdef" WARN per probed charcode per
font per request. With TimeBasedRollingPolicy alone there was no
size ceiling; info.log grew to 1.4 GB in a single day before the JVM
choked. The class-level silencer fixes the specific offender, but
this size cap is the defence-in-depth: any future logger that
floods unexpectedly will roll + auto-delete instead of starving
disk + Jetty threads. -->
<!-- Rolling File Appender for General Logs -->
<appender name="GENERAL" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_PATH}/info.log</file>
<encoder>
<pattern>%d %p %c{1} [%thread] %m%n</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<maxFileSize>100MB</maxFileSize>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/info-%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>1</maxHistory>
<totalSizeCap>500MB</totalSizeCap>
</rollingPolicy>
</appender>
<!-- Suppress PDFBox PDSimpleFont's per-charcode .notdef WARN.
Required by the v2 PDF text editor's `buildReverseUnicodeMap`
which DELIBERATELY iterates every charcode in 0..0xFFFF to
discover the encoding-to-Unicode map of an embedded subset
font. For any subset font ~99% of those probes hit .notdef,
and the default WARN level for those misses turned info.log
into a 1.4 GB monster overnight.
This declarative logback entry is the SOLE mechanism: it is
visible to ops and revertable via configuration. An earlier
build also mutated this logger's level from a static block in
PdfTextEditorV2CharcodeController, which silenced the same
warnings JVM-wide with no trace in any config file - that
static block has been removed in favour of this entry. -->
<logger name="org.apache.pdfbox.pdmodel.font.PDSimpleFont"
level="ERROR" additivity="false">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="GENERAL"/>
</logger>
<!-- Root Logger -->
<root level="INFO">
<appender-ref ref="CONSOLE"/>
@@ -1,509 +0,0 @@
package stirling.software.SPDF.controller.api;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.imageio.ImageIO;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDFontDescriptor;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.PDType3Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.junit.jupiter.api.Test;
/**
* Probe: what can PDFBox actually do for font ENCODING on real-world PDFs. This is a diagnostic
* test (not a regression) - run with --tests PdfBoxFontEncodingProbeTest -i to see stdout.
*
* <p>Answers these questions:
*
* <ol>
* <li>Type0/CIDFontType2 subset: can we add a new glyph not in the original subset? (no, encode
* throws IllegalArgumentException).
* <li>Type1: same question.
* <li>TrueType: same question.
* <li>Can we load a fresh TTF via PDType0Font.load(doc, file) and write text with it? (yes,
* primary path).
* <li>Round-trip via getFontStream / re-embed - can it rehabilitate Type3? (no - Type3 has no
* FontFile* program at all).
* <li>What fonts ship with PDFBox / fontbox? (only LiberationSans-Regular.ttf + AFM for the 14
* standard fonts; CFF/Type1 binaries are NOT bundled - Standard14Fonts.getMappedFontName
* redirects unmappable ones to LiberationSans).
* </ol>
*/
public class PdfBoxFontEncodingProbeTest {
private static final Path PROJECT_ROOT =
Paths.get(System.getProperty("user.dir")).getParent().getParent();
private static final Path SAMPLE =
PROJECT_ROOT.resolve("frontend/editor/public/samples/Sample.pdf");
private static final Path[] EXTRA_FIXTURES = {
PROJECT_ROOT.resolve("frontend/editor/src/core/tests/test-fixtures/stirling-marketing.pdf"),
PROJECT_ROOT.resolve("frontend/editor/src/core/tests/test-fixtures/multi-page-sample.pdf"),
PROJECT_ROOT.resolve("frontend/editor/src/core/tests/test-fixtures/big-sample.pdf"),
PROJECT_ROOT.resolve("frontend/editor/src/core/tests/test-fixtures/paragraph-sample.pdf"),
PROJECT_ROOT.resolve("frontend/editor/src/core/tests/test-fixtures/user-sample.pdf"),
};
/**
* Rasterize the Q4b output (Sample.pdf with injected Liberation text) to confirm the new text
* actually renders on top of the existing Type3 content.
*/
@Test
public void probeRenderInjectedSample() throws IOException {
Path liberation =
PROJECT_ROOT.resolve(
"app/core/src/main/resources/static/fonts/LiberationSans-Regular.ttf");
byte[] pdfBytes = Files.readAllBytes(SAMPLE);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (PDDocument doc = Loader.loadPDF(pdfBytes)) {
PDPage page = doc.getPage(0);
PDType0Font ttf;
try (InputStream in = Files.newInputStream(liberation)) {
ttf = PDType0Font.load(doc, in, true);
}
try (PDPageContentStream cs =
new PDPageContentStream(
doc, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
cs.beginText();
cs.setFont(ttf, 24);
cs.newLineAtOffset(50, 120);
cs.showText("INJECTED via PDType0Font.load - $@#&Z");
cs.endText();
}
doc.save(out);
}
// Rasterize page 0 to a PNG so we can eyeball it.
try (PDDocument check = Loader.loadPDF(out.toByteArray())) {
PDFRenderer renderer = new PDFRenderer(check);
java.awt.image.BufferedImage img = renderer.renderImageWithDPI(0, 100);
Path png = PROJECT_ROOT.resolve("test-screenshots/pdfbox-probe-q4b-rendered.png");
Files.createDirectories(png.getParent());
ImageIO.write(img, "PNG", png.toFile());
System.out.println(
"Rendered injected sample to "
+ png
+ " - "
+ img.getWidth()
+ "x"
+ img.getHeight());
}
}
/**
* Build a PDF in memory that uses a Type0/CIDFontType2 subset font (the kind Word / InDesign /
* LibreOffice produce), then probe whether encode() can add a glyph that wasn't in the original
* subset.
*/
@Test
public void probeType0CIDFontType2Subset() throws IOException {
System.out.println(
"\n##################################################################\n"
+ "Q1 probe: Type0/CIDFontType2 SUBSET can/cannot add new glyphs\n"
+ "##################################################################\n");
Path liberation =
PROJECT_ROOT.resolve(
"app/core/src/main/resources/static/fonts/LiberationSans-Regular.ttf");
// Build a PDF that contains only "abc" subsetted from LiberationSans.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (PDDocument doc = new PDDocument()) {
PDPage page = new PDPage();
doc.addPage(page);
PDType0Font subset;
try (InputStream in = Files.newInputStream(liberation)) {
subset = PDType0Font.load(doc, in, true /* embedSubset */);
}
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
cs.beginText();
cs.setFont(subset, 12);
cs.newLineAtOffset(100, 700);
cs.showText("abc");
cs.endText();
}
doc.save(baos);
}
// Reload the produced PDF and try to add a NEW glyph through the embedded subset font.
byte[] subsetPdf = baos.toByteArray();
try (PDDocument doc = Loader.loadPDF(subsetPdf)) {
PDResources res = doc.getPage(0).getResources();
for (COSName fn : res.getFontNames()) {
PDFont f = res.getFont(fn);
System.out.println(
" Subset font in saved PDF: "
+ f.getName()
+ " ("
+ f.getClass().getSimpleName()
+ ", subType="
+ f.getSubType()
+ ")");
for (String ch : new String[] {"a", "b", "c", "Z", "z", "0", "$", "@", "X", " "}) {
try {
byte[] enc = f.encode(ch);
StringBuilder hex = new StringBuilder();
for (byte b : enc) hex.append(String.format("%02X ", b & 0xff));
System.out.println(
" encode('" + ch + "') -> [" + hex.toString().trim() + "] OK");
} catch (UnsupportedOperationException uoe) {
System.out.println(" encode('" + ch + "') UNSUPPORTED");
} catch (IllegalArgumentException iae) {
System.out.println(
" encode('" + ch + "') MISSING - " + iae.getMessage());
} catch (IOException ioe) {
System.out.println(" encode('" + ch + "') IO ERR - " + ioe.getMessage());
}
}
}
}
}
@Test
public void probeExtraFixtures() throws IOException {
System.out.println(
"\n##################################################################\n"
+ "Extra fixture font-class probe\n"
+ "##################################################################\n");
for (Path fixture : EXTRA_FIXTURES) {
if (!Files.exists(fixture)) {
System.out.println("(missing) " + fixture);
continue;
}
System.out.println("\n=== " + fixture.getFileName() + " ===");
byte[] bytes = Files.readAllBytes(fixture);
try (PDDocument doc = Loader.loadPDF(bytes)) {
Set<COSName> seen = new HashSet<>();
for (int p = 0; p < doc.getNumberOfPages(); p++) {
PDPage page = doc.getPage(p);
PDResources res = page.getResources();
if (res == null) continue;
for (COSName name : res.getFontNames()) {
if (!seen.add(name)) continue;
try {
PDFont f = res.getFont(name);
if (f == null) continue;
String fontFile = "none";
PDFontDescriptor d = f.getFontDescriptor();
if (d != null) {
if (d.getFontFile() != null) fontFile = "FontFile";
else if (d.getFontFile2() != null) fontFile = "FontFile2";
else if (d.getFontFile3() != null) fontFile = "FontFile3";
}
String z = "?";
try {
f.encode("Z");
z = "OK";
} catch (UnsupportedOperationException ex) {
z = "UNSUPPORTED";
} catch (IllegalArgumentException ex) {
z = "MISSING";
} catch (IOException ex) {
z = "IO_ERR";
}
System.out.println(
" page "
+ p
+ " "
+ name.getName()
+ " -> "
+ f.getName()
+ " "
+ f.getClass().getSimpleName()
+ " ("
+ f.getSubType()
+ ", "
+ fontFile
+ ", embed="
+ f.isEmbedded()
+ ") encode('Z')="
+ z);
} catch (IOException e) {
System.out.println(
" page "
+ p
+ " "
+ name.getName()
+ " load failed: "
+ e.getMessage());
}
}
}
}
}
}
@Test
public void probeAllQuestions() throws IOException {
System.out.println(
"\n##################################################################\n"
+ "PDFBox font-encoding probe (Sample.pdf + bundled fallback fonts)\n"
+ "##################################################################\n");
// Discover every font in Sample.pdf so we have a real-world test set.
byte[] pdfBytes = Files.readAllBytes(SAMPLE);
try (PDDocument doc = Loader.loadPDF(pdfBytes)) {
List<PDFont> allFonts = new ArrayList<>();
Set<COSName> seen = new HashSet<>();
for (int p = 0; p < doc.getNumberOfPages(); p++) {
PDPage page = doc.getPage(p);
PDResources res = page.getResources();
if (res == null) continue;
for (COSName name : res.getFontNames()) {
if (!seen.add(name)) continue;
try {
PDFont f = res.getFont(name);
if (f != null) allFonts.add(f);
} catch (Exception e) {
System.out.println(
" (skipped " + name.getName() + " - " + e.getMessage() + ")");
}
}
}
System.out.println(
"Discovered " + allFonts.size() + " unique fonts across Sample.pdf:");
for (PDFont f : allFonts) {
System.out.println(
" - "
+ f.getName()
+ " ("
+ f.getClass().getSimpleName()
+ ", subType="
+ f.getSubType()
+ ", embedded="
+ f.isEmbedded()
+ ")");
}
// ------------------ Q1/Q2/Q3 ------------------
// Try encoding a char that is NEVER in Sample.pdf via each font.
// 'Z' is unlikely to be in the subset for most marketing pages.
// Try several candidates to surface what each font can/can't add.
String[] candidates = {"Z", "$", "@", "#", "Q", "&", "A", "0", "M"};
for (PDFont f : allFonts) {
System.out.println("\n=== Encode-probe for font: " + f.getName() + " ===");
for (String ch : candidates) {
try {
byte[] enc = f.encode(ch);
StringBuilder hex = new StringBuilder();
for (byte b : enc) hex.append(String.format("%02X ", b & 0xff));
System.out.println(
" encode('" + ch + "') -> [" + hex.toString().trim() + "] OK");
} catch (UnsupportedOperationException uoe) {
System.out.println(
" encode('" + ch + "') UNSUPPORTED: " + uoe.getMessage());
} catch (IllegalArgumentException iae) {
System.out.println(" encode('" + ch + "') MISSING: " + iae.getMessage());
} catch (IOException ioe) {
System.out.println(" encode('" + ch + "') IO ERR: " + ioe.getMessage());
}
}
}
// ------------------ Q5 ------------------
// For each font, see what's in the FontFile* stream - this is what we'd
// have to round-trip through to "rehabilitate" a Type3 font.
System.out.println("\n=== FontFile stream availability (Q5) ===");
for (PDFont f : allFonts) {
String kind = "none";
int size = 0;
PDFontDescriptor d = f.getFontDescriptor();
if (d != null) {
if (d.getFontFile() != null) {
kind = "FontFile (Type1)";
size = streamBytes(d.getFontFile().getCOSObject().createInputStream());
} else if (d.getFontFile2() != null) {
kind = "FontFile2 (TTF)";
size = streamBytes(d.getFontFile2().getCOSObject().createInputStream());
} else if (d.getFontFile3() != null) {
kind = "FontFile3 (CFF/OpenType)";
size = streamBytes(d.getFontFile3().getCOSObject().createInputStream());
}
}
System.out.println(
" "
+ f.getName()
+ " ("
+ f.getClass().getSimpleName()
+ "): "
+ kind
+ " ("
+ size
+ " bytes)");
if (f instanceof PDType3Font) {
System.out.println(
" -> Type3 has CharProc streams, NOT a FontFile binary."
+ " getFontStream() returns null. Round-trip rehab is impossible:");
System.out.println(
" each glyph is a mini content stream, not a glyph outline in a"
+ " standard font format. We'd need to rasterize each CharProc to"
+ " glyph outlines + build a fresh TTF/CFF from scratch.");
}
}
}
// ------------------ Q4: PDType0Font.load(doc, file) round-trip ------------------
System.out.println("\n=== Q4: load fresh TTF and write text to a fresh PDF ===");
Path liberation =
PROJECT_ROOT.resolve(
"app/core/src/main/resources/static/fonts/LiberationSans-Regular.ttf");
if (!Files.exists(liberation)) {
System.out.println(" Liberation TTF not found at " + liberation);
} else {
try (PDDocument out = new PDDocument()) {
PDPage page = new PDPage();
out.addPage(page);
PDType0Font ttf;
try (InputStream in = Files.newInputStream(liberation)) {
ttf = PDType0Font.load(out, in, true /* embedSubset */);
}
System.out.println(
" Loaded TTF -> "
+ ttf.getName()
+ " ("
+ ttf.getClass().getSimpleName()
+ ")");
String testText = "Hello world! 0123 Z $ @";
byte[] encoded = ttf.encode(testText);
System.out.println(
" Encoded "
+ testText.length()
+ " chars -> "
+ encoded.length
+ " bytes (Identity-H = 2 bytes/glyph)");
try (PDPageContentStream cs = new PDPageContentStream(out, page)) {
cs.beginText();
cs.setFont(ttf, 12);
cs.newLineAtOffset(100, 700);
cs.showText(testText);
cs.endText();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
out.save(baos);
Path tmp = Files.createTempFile("pdfbox-probe-q4-", ".pdf");
Files.write(tmp, baos.toByteArray());
System.out.println(
" Wrote fresh-TTF PDF to "
+ tmp
+ " ("
+ baos.size()
+ " bytes) - opens cleanly.");
// Re-load to confirm the new font is embedded properly.
try (PDDocument check = Loader.loadPDF(baos.toByteArray())) {
PDResources res = check.getPage(0).getResources();
for (COSName fn : res.getFontNames()) {
PDFont f = res.getFont(fn);
System.out.println(
" embedded font: "
+ f.getName()
+ " ("
+ f.getClass().getSimpleName()
+ ", embedded="
+ f.isEmbedded()
+ ")");
}
}
}
}
// ------------------ Q4b: load TTF into an EXISTING PDF (Sample.pdf) and append text ------
System.out.println(
"\n=== Q4b: load TTF into EXISTING Sample.pdf and write text on page 0 ===");
try (PDDocument doc = Loader.loadPDF(pdfBytes)) {
PDPage page = doc.getPage(0);
PDType0Font ttf;
try (InputStream in = Files.newInputStream(liberation)) {
ttf = PDType0Font.load(doc, in, true);
}
// append-mode content stream so we don't disturb existing graphics
try (PDPageContentStream cs =
new PDPageContentStream(
doc,
page,
PDPageContentStream.AppendMode.APPEND,
true /* compress */,
true /* resetContext */)) {
cs.beginText();
cs.setFont(ttf, 12);
cs.newLineAtOffset(50, 50);
cs.showText("Injected via PDType0Font.load - $@#&");
cs.endText();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
Path tmp = Files.createTempFile("pdfbox-probe-q4b-", ".pdf");
Files.write(tmp, baos.toByteArray());
System.out.println(
" Wrote injected-text PDF to " + tmp + " (" + baos.size() + " bytes).");
// Verify by re-reading: how many fonts now on page 0?
try (PDDocument check = Loader.loadPDF(baos.toByteArray())) {
PDResources res = check.getPage(0).getResources();
int count = 0;
for (COSName fn : res.getFontNames()) {
PDFont f = res.getFont(fn);
count++;
System.out.println(
" page-0 font: "
+ fn.getName()
+ " -> "
+ f.getName()
+ " ("
+ f.getClass().getSimpleName()
+ ")");
}
System.out.println(" Total fonts on page 0: " + count);
}
}
// ------------------ Q6: what fonts ship in PDFBox / fontbox ------------------
System.out.println("\n=== Q6: bundled fonts (Standard14 redirect probe) ===");
for (Standard14Fonts.FontName fn : Standard14Fonts.FontName.values()) {
PDType1Font f = new PDType1Font(fn);
String mapped = "" + Standard14Fonts.getMappedFontName(fn.getName());
System.out.println(
" Standard14 "
+ fn.getName()
+ " -> mapped='"
+ mapped
+ "' name="
+ f.getName());
}
System.out.println(
" (PDFBox bundles ONLY LiberationSans-Regular.ttf as a binary; the AFMs cover"
+ " metrics for the 14 standard fonts but rendering Helvetica/Times/Courier"
+ " glyphs falls back to LiberationSans glyphs at runtime when no system font"
+ " is found.)");
}
private static int streamBytes(InputStream is) {
try (InputStream it = is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
int n;
while ((n = it.read(buf)) >= 0) baos.write(buf, 0, n);
return baos.size();
} catch (IOException e) {
return -1;
}
}
}
@@ -1,316 +0,0 @@
package stirling.software.SPDF.controller.api;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Base64;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.junit.jupiter.api.Test;
import org.springframework.http.ResponseEntity;
import stirling.software.SPDF.controller.api.PdfTextEditorV2CharcodeController.EncodeCharcodesRequest;
import stirling.software.SPDF.controller.api.PdfTextEditorV2CharcodeController.EncodeCharcodesResponse;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.service.PdfMetadataService;
/**
* Regression coverage for the v2 text editor "spaces render as „" bug.
*
* <p>mushroom-life.pdf is a LaTeX document whose embedded LMRoman subset font has NO real space
* glyph, yet {@code font.encode(" ")} still returns charcode 0x20 without throwing. Reusing that
* code via {@code FPDFText_SetCharcodes} paints whatever glyph sits at subset code 0x20 - the
* quotedblbase „. The controller must therefore report whitespace as {@code missing} so the
* frontend emits it as a positional gap instead of a reused glyph.
*/
class PdfTextEditorV2CharcodeControllerTest {
private static PdfTextEditorV2CharcodeController controller() {
return new PdfTextEditorV2CharcodeController(
new CustomPDFDocumentFactory(mock(PdfMetadataService.class)));
}
private static String mushroomBase64() throws Exception {
try (InputStream in =
PdfTextEditorV2CharcodeControllerTest.class.getResourceAsStream(
"/pdftexteditor/mushroom-life.pdf")) {
assertThat(in).as("mushroom-life.pdf test resource").isNotNull();
return Base64.getEncoder().encodeToString(in.readAllBytes());
}
}
private static EncodeCharcodesRequest request(String text) throws Exception {
EncodeCharcodesRequest req = new EncodeCharcodesRequest();
req.setPdfBase64(mushroomBase64());
req.setPageIndex(0);
// findFontByToUnicode locates the font via the ToUnicode CMap - "M" exists on page 0.
req.setLocatorChar("M");
req.setText(text);
return req;
}
@Test
void spaceIsReportedMissingNeverEncoded() throws Exception {
PdfTextEditorV2CharcodeController controller = controller();
ResponseEntity<EncodeCharcodesResponse> resp = controller.encodeCharcodes(request(" "));
EncodeCharcodesResponse body = resp.getBody();
assertThat(body).isNotNull();
assertThat(body.getError()).isNull();
// The space must be reported missing, NOT handed back as a charcode
// (0x20) the frontend would reuse into the „ glyph.
assertThat(body.getMissing()).containsExactly(" ");
assertThat(body.getCharcodes()).isNullOrEmpty();
}
@Test
void realCharsEncodeWhileWhitespaceStaysAGap() throws Exception {
PdfTextEditorV2CharcodeController controller = controller();
// "M M" - both M's must encode to real charcodes; only the space is a gap.
ResponseEntity<EncodeCharcodesResponse> resp = controller.encodeCharcodes(request("M M"));
EncodeCharcodesResponse body = resp.getBody();
assertThat(body).isNotNull();
assertThat(body.getError()).isNull();
assertThat(body.getCharcodes()).as("both M glyphs encode").hasSize(2);
assertThat(body.getMissing()).containsExactly(" ");
}
@Test
void tabAndNewlineAreAlsoTreatedAsGaps() throws Exception {
PdfTextEditorV2CharcodeController controller = controller();
ResponseEntity<EncodeCharcodesResponse> resp = controller.encodeCharcodes(request("\t\n"));
EncodeCharcodesResponse body = resp.getBody();
assertThat(body).isNotNull();
assertThat(body.getMissing()).containsExactly("\t", "\n");
assertThat(body.getCharcodes()).isNullOrEmpty();
}
/**
* A page with two fonts that BOTH render 'A'. {@code fontName} must select which one to encode
* against - the cross-font fix. Without it the first font in resources order won wins and a
* cross-font edit got the wrong font's charcode.
*/
private static String twoFontBase64() throws Exception {
try (PDDocument doc = new PDDocument()) {
PDPage page = new PDPage();
doc.addPage(page);
PDType1Font helvetica = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
PDType1Font times = new PDType1Font(Standard14Fonts.FontName.TIMES_ROMAN);
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
cs.beginText();
cs.setFont(helvetica, 12);
cs.newLineAtOffset(72, 720);
cs.showText("A");
cs.endText();
cs.beginText();
cs.setFont(times, 12);
cs.newLineAtOffset(72, 700);
cs.showText("A");
cs.endText();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
doc.save(bos);
return Base64.getEncoder().encodeToString(bos.toByteArray());
}
}
private static EncodeCharcodesRequest twoFontRequest(String fontName) throws Exception {
EncodeCharcodesRequest req = new EncodeCharcodesRequest();
req.setPdfBase64(twoFontBase64());
req.setPageIndex(0);
req.setLocatorChar("A");
req.setFontName(fontName);
req.setText("A");
return req;
}
@Test
void fontNameDisambiguatesBetweenTwoFontsRenderingTheSameChar() throws Exception {
PdfTextEditorV2CharcodeController controller = controller();
// Targeting Times-Roman must encode against Times-Roman, not whichever
// font happens to appear first in the page's font resources.
EncodeCharcodesResponse times =
controller.encodeCharcodes(twoFontRequest("Times-Roman")).getBody();
assertThat(times).isNotNull();
assertThat(times.getError()).isNull();
assertThat(times.getNote()).contains("Times-Roman");
assertThat(times.getCharcodes()).hasSize(1);
// Targeting Helvetica must encode against Helvetica.
EncodeCharcodesResponse helv =
controller.encodeCharcodes(twoFontRequest("Helvetica")).getBody();
assertThat(helv).isNotNull();
assertThat(helv.getError()).isNull();
assertThat(helv.getNote()).contains("Helvetica");
assertThat(helv.getCharcodes()).hasSize(1);
}
@Test
void unknownFontNameReportsNoFontInsteadOfWrongFont() throws Exception {
PdfTextEditorV2CharcodeController controller = controller();
// A name that matches no font on the page must NOT silently encode
// against a different font: the frontend writes the returned charcodes
// into the NAMED font's text object, so a first-match fallback would
// bake wrong glyphs. It must report failure so the caller falls back.
EncodeCharcodesResponse body =
controller.encodeCharcodes(twoFontRequest("DoesNotExist")).getBody();
assertThat(body).isNotNull();
assertThat(body.getError()).contains("no font");
assertThat(body.getCharcodes()).isNull();
}
@Test
void missingRequiredFieldsReturns400() {
EncodeCharcodesRequest req = new EncodeCharcodesRequest();
req.setPdfBase64("AAAA");
req.setLocatorChar("M");
// text is null
ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);
assertThat(resp.getStatusCode().value()).isEqualTo(400);
assertThat(resp.getBody()).isNotNull();
assertThat(resp.getBody().getError()).isEqualTo("missing required fields");
}
@Test
void invalidBase64Returns400() {
EncodeCharcodesRequest req = new EncodeCharcodesRequest();
req.setPdfBase64("!!!notbase64!!!");
req.setLocatorChar("M");
req.setText("M");
ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);
assertThat(resp.getStatusCode().value()).isEqualTo(400);
assertThat(resp.getBody()).isNotNull();
assertThat(resp.getBody().getError()).isEqualTo("pdfBase64 is not valid base64");
}
@Test
void pageIndexOutOfRangeReturns400() throws Exception {
EncodeCharcodesRequest req = request("M");
req.setPageIndex(999);
ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);
assertThat(resp.getStatusCode().value()).isEqualTo(400);
assertThat(resp.getBody()).isNotNull();
assertThat(resp.getBody().getError()).isEqualTo("pageIndex out of range");
}
@Test
void nonPdfBytesReturnsGenericError() {
EncodeCharcodesRequest req = new EncodeCharcodesRequest();
req.setPdfBase64(Base64.getEncoder().encodeToString("not a pdf".getBytes()));
req.setLocatorChar("M");
req.setText("M");
// Must not throw, and must not leak the raw PDFBox parser message.
ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);
assertThat(resp.getStatusCode().is4xxClientError()).isTrue();
assertThat(resp.getBody()).isNotNull();
assertThat(resp.getBody().getError()).isEqualTo("failed to load PDF");
}
@Test
void absentLocatorCharReturns200WithError() throws Exception {
// U+FFFF never appears in the document, so no font matches.
ResponseEntity<EncodeCharcodesResponse> resp =
controller().encodeCharcodes(requestWithLocator("￿"));
assertThat(resp.getStatusCode().value()).isEqualTo(200);
EncodeCharcodesResponse body = resp.getBody();
assertThat(body).isNotNull();
assertThat(body.getError()).isNotNull();
assertThat(body.getCharcodes()).isNull();
}
@Test
void oversizePdfRejected() {
EncodeCharcodesRequest req = new EncodeCharcodesRequest();
// A base64 string long enough that length/4*3 exceeds the 100MB cap, without
// ever allocating the decoded bytes (the guard runs before decode).
char[] huge = new char[140 * 1024 * 1024];
java.util.Arrays.fill(huge, 'A');
req.setPdfBase64(new String(huge));
req.setLocatorChar("M");
req.setText("M");
ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);
assertThat(resp.getStatusCode().value()).isEqualTo(413);
assertThat(resp.getBody()).isNotNull();
assertThat(resp.getBody().getError()).isEqualTo("pdf too large");
}
private static EncodeCharcodesRequest requestWithLocator(String locator) throws Exception {
EncodeCharcodesRequest req = request("M");
req.setLocatorChar(locator);
return req;
}
/**
* Build a page whose resources declare {@code filler} fonts that do NOT render 'A' (Symbol /
* ZapfDingbats have non-Latin encodings) plus, optionally, a trailing Helvetica that does. The
* Standard14 probe upper bound is 256 so each scan is cheap.
*/
private static String manyFontsBase64(int filler, boolean trailingTarget) throws Exception {
try (PDDocument doc = new PDDocument()) {
PDPage page = new PDPage();
doc.addPage(page);
org.apache.pdfbox.pdmodel.PDResources resources =
new org.apache.pdfbox.pdmodel.PDResources();
for (int n = 0; n < filler; n++) {
Standard14Fonts.FontName fn =
(n % 2 == 0)
? Standard14Fonts.FontName.SYMBOL
: Standard14Fonts.FontName.ZAPF_DINGBATS;
resources.put(
org.apache.pdfbox.cos.COSName.getPDFName("Ff" + n), new PDType1Font(fn));
}
if (trailingTarget) {
resources.put(
org.apache.pdfbox.cos.COSName.getPDFName("Target"),
new PDType1Font(Standard14Fonts.FontName.HELVETICA));
}
page.setResources(resources);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
doc.save(bos);
return Base64.getEncoder().encodeToString(bos.toByteArray());
}
}
private static EncodeCharcodesRequest manyFontsRequest(String base64) {
EncodeCharcodesRequest req = new EncodeCharcodesRequest();
req.setPdfBase64(base64);
req.setPageIndex(0);
req.setLocatorChar("A");
req.setText("A");
return req;
}
@Test
void targetFontFoundAmongManyFonts() throws Exception {
// 60 non-matching fonts then the Helvetica target, all within the 64-font cap.
ResponseEntity<EncodeCharcodesResponse> resp =
controller().encodeCharcodes(manyFontsRequest(manyFontsBase64(60, true)));
assertThat(resp.getStatusCode().value()).isEqualTo(200);
EncodeCharcodesResponse body = resp.getBody();
assertThat(body).isNotNull();
assertThat(body.getError()).isNull();
assertThat(body.getCharcodes()).hasSize(1);
}
@Test
void targetBeyondFontCapReturnsGracefulNoFont() throws Exception {
// 64 non-matching fonts then the target at position 65 - the scan cap stops
// before reaching it, so we get a graceful no-font error rather than a full scan.
ResponseEntity<EncodeCharcodesResponse> resp =
controller().encodeCharcodes(manyFontsRequest(manyFontsBase64(64, true)));
assertThat(resp.getStatusCode().value()).isEqualTo(200);
EncodeCharcodesResponse body = resp.getBody();
assertThat(body).isNotNull();
assertThat(body.getError()).isNotNull();
assertThat(body.getCharcodes()).isNull();
}
}
@@ -1,337 +0,0 @@
package stirling.software.SPDF.controller.api;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.contentstream.PDFStreamEngine;
import org.apache.pdfbox.contentstream.operator.state.Concatenate;
import org.apache.pdfbox.contentstream.operator.state.Restore;
import org.apache.pdfbox.contentstream.operator.state.Save;
import org.apache.pdfbox.contentstream.operator.state.SetGraphicsStateParameters;
import org.apache.pdfbox.contentstream.operator.state.SetMatrix;
import org.apache.pdfbox.contentstream.operator.text.BeginText;
import org.apache.pdfbox.contentstream.operator.text.EndText;
import org.apache.pdfbox.contentstream.operator.text.SetFontAndSize;
import org.apache.pdfbox.contentstream.operator.text.SetTextHorizontalScaling;
import org.apache.pdfbox.contentstream.operator.text.SetTextLeading;
import org.apache.pdfbox.contentstream.operator.text.SetTextRenderingMode;
import org.apache.pdfbox.contentstream.operator.text.SetTextRise;
import org.apache.pdfbox.contentstream.operator.text.SetWordSpacing;
import org.apache.pdfbox.contentstream.operator.text.ShowText;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDFontDescriptor;
import org.apache.pdfbox.pdmodel.font.PDType3CharProc;
import org.apache.pdfbox.pdmodel.font.PDType3Font;
import org.junit.jupiter.api.Test;
/**
* Diagnostic test: enumerate every font referenced by Sample.pdf and dump its subtype, encoding,
* ToUnicode, and embedded font program info. For Type3 fonts also dump CharProcs glyph names and
* the content stream of one glyph (the 'M' if present).
*
* <p>Not a real regression test - run with --tests SamplePdfFontDumpTest -i to see the stdout
* output.
*/
public class SamplePdfFontDumpTest {
private static final Path SAMPLE =
Paths.get(System.getProperty("user.dir"))
.getParent()
.getParent()
.resolve("frontend/editor/public/samples/Sample.pdf");
@Test
public void dumpFonts() throws IOException {
byte[] pdfBytes = Files.readAllBytes(SAMPLE);
try (PDDocument doc = Loader.loadPDF(pdfBytes)) {
int numPages = doc.getNumberOfPages();
System.out.println("Sample.pdf has " + numPages + " pages.");
Set<COSDictionary> seenFontDicts = new HashSet<>();
for (int p = 0; p < numPages; p++) {
PDPage page = doc.getPage(p);
System.out.println("\n=== Page " + p + " ===");
PDResources resources = page.getResources();
if (resources == null) {
System.out.println(" (no resources)");
continue;
}
for (COSName fontName : resources.getFontNames()) {
PDFont font;
try {
font = resources.getFont(fontName);
} catch (IOException e) {
System.out.println(
" Font "
+ fontName.getName()
+ ": failed to load - "
+ e.getMessage());
continue;
}
if (font == null) continue;
COSDictionary dict = font.getCOSObject();
if (!seenFontDicts.add(dict)) {
System.out.println(
" Font " + fontName.getName() + " -> already seen above");
continue;
}
dumpFont(fontName.getName(), font);
}
}
// Scan: for every text-show operation, record per-font (charcode, unicode) pairs.
System.out.println("\n=== All (font, charcode, unicode) seen on page ===");
for (int p = 0; p < numPages; p++) {
PDPage page = doc.getPage(p);
AllCharsScanner scanner = new AllCharsScanner();
scanner.processPage(page);
System.out.println("\nPage " + p + ":");
for (var entry : scanner.perFont.entrySet()) {
PDFont font = entry.getKey();
var seen = entry.getValue();
System.out.println(" Font " + font.getName() + " " + font.getSubType() + ":");
var sortedSeen = new java.util.TreeMap<Integer, String>(seen);
for (var s : sortedSeen.entrySet()) {
System.out.println(
" charcode 0x"
+ Integer.toHexString(s.getKey())
+ " ("
+ s.getKey()
+ ") -> '"
+ s.getValue()
+ "'");
}
}
}
// Confirm font.encode() works for Type3 fonts.
System.out.println("\n=== Can we encode existing chars in F27/F28? ===");
PDPage page0 = doc.getPage(0);
PDResources r0 = page0.getResources();
for (String fname : new String[] {"F27", "F28"}) {
PDFont f = r0.getFont(COSName.getPDFName(fname));
if (f == null) {
System.out.println(" " + fname + ": NOT FOUND on page 0");
continue;
}
System.out.println(" " + fname + ": " + f.getClass().getSimpleName());
for (String ch : new String[] {"M", "0", "1", "+", "Z", "a"}) {
try {
byte[] enc = f.encode(ch);
StringBuilder sb = new StringBuilder();
for (byte b : enc) sb.append(String.format("%02X ", b & 0xff));
System.out.println(
" encode('" + ch + "') -> [" + sb.toString().trim() + "]");
} catch (Exception e) {
System.out.println(
" encode('"
+ ch
+ "') FAILED: "
+ e.getClass().getSimpleName()
+ " "
+ e.getMessage());
}
}
}
// Dump page 0 content stream so we can see how "10M+" is composed.
System.out.println("\n=== Page 0 RAW content stream (first 4kb) ===");
try (InputStream is = doc.getPage(0).getContents()) {
byte[] bytes = is.readAllBytes();
System.out.println("Total content stream size: " + bytes.length + " bytes");
String asStr = new String(bytes, StandardCharsets.ISO_8859_1);
int idx = asStr.indexOf("F27");
if (idx >= 0) {
int start = Math.max(0, idx - 100);
int end = Math.min(asStr.length(), idx + 2500);
System.out.println("--- F27 context ---");
System.out.println(asStr.substring(start, end));
System.out.println("---");
}
int idx2 = asStr.indexOf("F28");
if (idx2 >= 0) {
int start = Math.max(0, idx2 - 200);
int end = Math.min(asStr.length(), idx2 + 600);
System.out.println("--- F28 context ---");
System.out.println(asStr.substring(start, end));
System.out.println("---");
}
}
// Dump a CharProc for each font's first non-zero glyph, with focus on any 'M' or "0".
System.out.println("\n=== Sample CharProc dumps for Type3 fonts ===");
Set<COSDictionary> printed = new HashSet<>();
for (int p = 0; p < numPages; p++) {
PDPage page = doc.getPage(p);
PDResources resources = page.getResources();
if (resources == null) continue;
for (COSName fn : resources.getFontNames()) {
PDFont font = resources.getFont(fn);
if (!(font instanceof PDType3Font)) continue;
if (!printed.add(font.getCOSObject())) continue;
PDType3Font t3 = (PDType3Font) font;
// Iterate charcodes 0..255 looking for any that map to 'M' or '0' or '+'.
for (int cc = 0; cc < 256; cc++) {
String u = null;
try {
u = t3.toUnicode(cc);
} catch (Exception e) {
/* */
}
if (u == null) continue;
if (u.equals("M") || u.equals("0") || u.equals("+") || u.equals("1")) {
System.out.println(
"Page "
+ p
+ " font '"
+ fn.getName()
+ "' charcode "
+ cc
+ " maps to '"
+ u
+ "':");
dumpType3Glyph(t3, cc);
}
}
}
}
}
}
private void dumpFont(String resourceName, PDFont font) {
COSDictionary dict = font.getCOSObject();
String subtype = dict.getNameAsString(COSName.SUBTYPE);
String baseFont = dict.getNameAsString(COSName.BASE_FONT);
boolean hasEncoding = dict.containsKey(COSName.ENCODING);
boolean hasToUnicode = dict.containsKey(COSName.TO_UNICODE);
PDFontDescriptor descriptor = font.getFontDescriptor();
boolean hasEmbedded = false;
String embeddedKind = "none";
if (descriptor != null) {
COSDictionary dDict = descriptor.getCOSObject();
if (dDict.containsKey(COSName.FONT_FILE)) {
hasEmbedded = true;
embeddedKind = "FontFile (Type1)";
} else if (dDict.containsKey(COSName.FONT_FILE2)) {
hasEmbedded = true;
embeddedKind = "FontFile2 (TrueType)";
} else if (dDict.containsKey(COSName.FONT_FILE3)) {
hasEmbedded = true;
COSBase ff3 = dDict.getDictionaryObject(COSName.FONT_FILE3);
if (ff3 instanceof COSStream) {
String ff3Subtype = ((COSStream) ff3).getNameAsString(COSName.SUBTYPE);
embeddedKind = "FontFile3 (" + ff3Subtype + ")";
} else {
embeddedKind = "FontFile3";
}
}
}
System.out.println(
" Font resource '"
+ resourceName
+ "': base='"
+ baseFont
+ "' subtype="
+ subtype
+ " hasEncoding="
+ hasEncoding
+ " hasToUnicode="
+ hasToUnicode
+ " embedded="
+ hasEmbedded
+ " ("
+ embeddedKind
+ ")");
if (font instanceof PDType3Font) {
PDType3Font t3 = (PDType3Font) font;
COSDictionary charProcs = t3.getCharProcs();
int count = charProcs == null ? 0 : charProcs.size();
System.out.println(" Type3 CharProcs count = " + count);
if (charProcs != null) {
TreeSet<String> names = new TreeSet<>();
for (COSName k : charProcs.keySet()) names.add(k.getName());
System.out.println(" glyph names: " + names);
}
}
}
private void dumpType3Glyph(PDType3Font font, int charcode) throws IOException {
String name = font.getEncoding() != null ? font.getEncoding().getName(charcode) : null;
System.out.println(" Type3 charcode " + charcode + " -> glyph name '" + name + "'");
PDType3CharProc proc = font.getCharProc(charcode);
if (proc == null) {
System.out.println(" (no CharProc for that charcode)");
return;
}
COSStream stream = proc.getCOSObject();
byte[] raw;
try (InputStream is = stream.createInputStream()) {
raw = is.readAllBytes();
}
System.out.println(" CharProc content stream (" + raw.length + " bytes):");
System.out.println("---");
System.out.println(new String(raw, StandardCharsets.ISO_8859_1));
System.out.println("---");
}
/** Records every (font, charcode -> unicode) tuple seen on a page. */
static final class AllCharsScanner extends PDFStreamEngine {
final java.util.LinkedHashMap<PDFont, java.util.Map<Integer, String>> perFont =
new java.util.LinkedHashMap<>();
AllCharsScanner() {
addOperator(new BeginText(this));
addOperator(new EndText(this));
addOperator(new SetFontAndSize(this));
addOperator(new SetTextHorizontalScaling(this));
addOperator(new SetTextLeading(this));
addOperator(new SetTextRenderingMode(this));
addOperator(new SetTextRise(this));
addOperator(new SetWordSpacing(this));
addOperator(new SetMatrix(this));
addOperator(new Save(this));
addOperator(new Restore(this));
addOperator(new Concatenate(this));
addOperator(new SetGraphicsStateParameters(this));
addOperator(new ShowText(this));
}
@Override
protected void showText(byte[] string) throws IOException {
PDFont font = getGraphicsState().getTextState().getFont();
if (font == null) return;
var seen = perFont.computeIfAbsent(font, k -> new java.util.LinkedHashMap<>());
ByteArrayInputStream in = new ByteArrayInputStream(string);
while (in.available() > 0) {
int code;
try {
code = font.readCode(in);
} catch (IOException e) {
break;
}
String u;
try {
u = font.toUnicode(code);
} catch (RuntimeException e) {
u = null;
}
seen.putIfAbsent(code, u);
}
}
}
}
@@ -43,6 +43,10 @@ public class IntegrationConfigService {
private final OwnershipService ownership;
private final SecretMasker secretMasker;
private final ResourceGrantRepository grantRepository;
// Bean-discovered extension points: features that understand a type contribute its config
// schema and report what still references a config, without this module depending on them.
private final List<IntegrationConfigValidator> validators;
private final List<IntegrationConfigUsageCheck> usageChecks;
// ---- commands ----
@@ -66,13 +70,21 @@ public class IntegrationConfigService {
? DefaultAccessPolicy.EXPLICIT_ONLY
: request.defaultAccess());
// TEAM scope may omit the team id: default to the caller's own team so clients (the
// portal) need not know it. assignOwnership still enforces admin-or-leader of that team.
Long ownerTeamId = request.ownerTeamId();
if (ownerTeamId == null && scope == OwnerScope.TEAM && currentUser.getTeam() != null) {
ownerTeamId = currentUser.getTeam().getId();
}
ownership.assignOwnership(
cfg,
scope,
request.ownerTeamId(),
ownerTeamId,
currentUser,
() -> lockedServerExists(cfg.getIntegrationType()));
cfg.setConfig(writeJson(secretMasker.sanitize(request.config())));
Map<String, Object> config = secretMasker.sanitize(request.config());
validateConfig(cfg.getIntegrationType(), config);
cfg.setConfig(writeJson(config));
return repository.save(cfg);
}
@@ -101,8 +113,10 @@ public class IntegrationConfigService {
cfg.setDefaultAccess(request.defaultAccess());
}
if (request.config() != null) {
cfg.setConfig(
writeJson(secretMasker.merge(readJson(cfg.getConfig()), request.config())));
Map<String, Object> merged =
secretMasker.merge(readJson(cfg.getConfig()), request.config());
validateConfig(cfg.getIntegrationType(), merged);
cfg.setConfig(writeJson(merged));
}
return repository.save(cfg);
}
@@ -113,6 +127,15 @@ public class IntegrationConfigService {
if (!ownership.canManage(TYPE, cfg, currentUser)) {
throw forbidden("You cannot manage this integration");
}
// Refuse to pull a connection out from under whatever still references it.
List<String> usages =
usageChecks.stream()
.flatMap(check -> check.usagesOf(cfg.getId()).stream())
.toList();
if (!usages.isEmpty()) {
throw new ResponseStatusException(
HttpStatus.CONFLICT, "Integration is in use by: " + String.join(", ", usages));
}
// Drop grants sharing this config so they do not dangle as dead rows.
grantRepository.deleteByResourceTypeAndResourceId(TYPE, String.valueOf(cfg.getId()));
repository.delete(cfg);
@@ -188,6 +211,19 @@ public class IntegrationConfigService {
// ---- integration-specific glue ----
/** Runs every registered validator for the type; unknown types save free-form. */
private void validateConfig(IntegrationType type, Map<String, Object> config) {
for (IntegrationConfigValidator validator : validators) {
if (validator.type() == type) {
try {
validator.validate(config == null ? Map.of() : config);
} catch (IllegalArgumentException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
}
}
}
}
/** A non-admin can't create a personal config of a type an admin has locked at server scope. */
private boolean lockedServerExists(IntegrationType type) {
return repository.findByScope(OwnerScope.SERVER).stream()
@@ -0,0 +1,15 @@
package stirling.software.proprietary.integration.service;
import java.util.List;
/**
* Reports what still references an integration config, so deletion can be refused instead of
* pulling a connection out from under a live consumer. Implementations are beans discovered by
* {@link IntegrationConfigService} (e.g. the policy subsystem reporting sources and pipelines that
* reference a connection).
*/
public interface IntegrationConfigUsageCheck {
/** Human-readable labels of everything still using the config; empty when unreferenced. */
List<String> usagesOf(long configId);
}
@@ -0,0 +1,23 @@
package stirling.software.proprietary.integration.service;
import java.util.Map;
import stirling.software.proprietary.integration.model.IntegrationType;
/**
* Validates one integration type's config map at save time. Implementations are beans discovered by
* {@link IntegrationConfigService}, so the feature that understands a type (e.g. the policy S3
* backend) owns its schema without the integration module depending on it. Types with no registered
* validator save free-form.
*/
public interface IntegrationConfigValidator {
/** The type this validator understands. */
IntegrationType type();
/**
* Validates the config as it will be stored (secrets already sanitized/merged, so values are
* real, never the redaction mask). Throws {@link IllegalArgumentException} on bad config.
*/
void validate(Map<String, Object> config);
}
@@ -120,6 +120,7 @@ public class PolicyController {
throws IOException {
stampPolicyAudit(definition);
requireRunnable(definition);
validateAdHocOutput(definition);
PolicyInputs inputs = toInputs(files);
PolicyRunHandle handle =
policyRunner.runAdHoc(definition, inputs, PolicyProgressListener.NOOP);
@@ -140,6 +141,7 @@ public class PolicyController {
throws IOException {
stampPolicyAudit(definition);
requireRunnable(definition);
validateAdHocOutput(definition);
PolicyInputs inputs = toInputs(files);
SseEmitter emitter =
@@ -530,6 +532,24 @@ public class PolicyController {
}
}
/**
* Authorization-check an ad-hoc run's output while the caller's principal is present (this
* request thread). The worker thread that later delivers carries no security context, so an S3
* output's connection-access check would be skipped there; without this gate a caller could
* reference another tenant's connection by id and write to it (confused deputy). Stored
* policies are covered by save-time {@link PolicyValidator#validate} instead.
*/
private void validateAdHocOutput(PipelineDefinition definition) {
if (definition.output() == null) {
return;
}
try {
policyValidator.validateOutput(definition.output());
} catch (IllegalArgumentException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
}
}
/**
* Ad-hoc runs (AI / one-off pipelines) are still editor activity, so their supplied documents
* feed the same virtual editor source as stored editor policies, counted against the caller's
@@ -52,7 +52,19 @@ public class PolicyValidator {
InputSpec spec = source.toInputSpec();
inputSourceFor(spec).validate(spec);
}
outputSinkFor(policy.output()).validate(policy.output());
validateOutput(policy.output());
}
/**
* Validate an output spec against its sink. Must be called on a request thread (caller's
* principal present) so an S3 output's connection is authorization-checked against the caller -
* ad-hoc runs are never persisted and so never hit {@link #validate(Policy)}, and the worker
* thread that later delivers has no principal, so this is their only access gate.
*
* @throws IllegalArgumentException if the type is unknown or the config is invalid/inaccessible
*/
public void validateOutput(OutputSpec output) {
outputSinkFor(output).validate(output);
}
private PolicyTrigger triggerFor(TriggerConfig config) {
@@ -18,6 +18,7 @@ import stirling.software.proprietary.policy.model.InputSpec;
import stirling.software.proprietary.policy.model.PolicyInputs;
import stirling.software.proprietary.policy.s3.S3Config;
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
import stirling.software.proprietary.policy.s3.S3ConnectionResolver;
import stirling.software.proprietary.policy.s3.S3Identities;
import software.amazon.awssdk.core.exception.SdkException;
@@ -36,15 +37,14 @@ import software.amazon.awssdk.services.s3.model.S3Object;
* Reads input files from an Amazon S3 (or S3-compatible) bucket; each listed object is its own unit
* of work, claimed through the {@link ResolveContext} ledger and tracked in place. Identity and
* version gate come from {@link S3Identities}, so the steady-state sweep never downloads content.
* Options (see {@link S3Config}): "bucket" (required), "region" (default us-east-1), "prefix" (only
* keys starting with it are read), "endpoint" (S3-compatible stores such as MinIO; path-style
* addressing is used automatically), "accessKeyId" and "secretAccessKey" (required; requests are
* never signed with the server's own AWS identity), and "mode" which is "consume" (default: a
* processed object is deleted once every policy that claimed it has settled successfully and it is
* still the version that ran; failures stay in place and are not retried until they change) or
* "snapshot" (stateless, every run sees the full set). Keys ending in "/" (folder placeholders) and
* keys with a dot-prefixed path segment are never picked up, mirroring the folder source's
* hidden-file rule.
* Options: "connectionId" references the stored S3 connection (an {@code IntegrationConfig} owning
* bucket, region, endpoint, and credentials - resolved by {@link S3ConnectionResolver}); "prefix"
* (only keys starting with it are read) and "mode" are per-source, where mode is "consume"
* (default: a processed object is deleted once every policy that claimed it has settled
* successfully and it is still the version that ran; failures stay in place and are not retried
* until they change) or "snapshot" (stateless, every run sees the full set). Keys ending in "/"
* (folder placeholders) and keys with a dot-prefixed path segment are never picked up, mirroring
* the folder source's hidden-file rule.
*/
@Slf4j
@Service
@@ -55,6 +55,7 @@ public class S3InputSource implements InputSource {
private static final String TYPE = "s3";
private final S3ConnectionPool connectionPool;
private final S3ConnectionResolver connectionResolver;
@Override
public String type() {
@@ -67,12 +68,12 @@ public class S3InputSource implements InputSource {
}
/**
* Fails fast at save time: bad config shape, a private endpoint without the operator opt-in, or
* a bucket the supplied credentials cannot list.
* Fails fast at save time: an unknown/disabled/unusable connection, bad config shape, a private
* endpoint without the operator opt-in, or a bucket the connection cannot list.
*/
@Override
public void validate(InputSpec spec) {
S3Config config = S3Config.from(spec.options());
S3Config config = connectionResolver.resolve(spec.options());
try {
connectionPool.clientFor(config).listObjectsV2(listRequest(config).maxKeys(1).build());
} catch (SdkException e) {
@@ -89,7 +90,7 @@ public class S3InputSource implements InputSource {
@Override
public List<ResolvedInput> resolve(InputSpec spec, ResolveContext ctx) throws IOException {
S3Config config = S3Config.from(spec.options());
S3Config config = connectionResolver.resolve(spec.options());
S3Client client = connectionPool.clientFor(config);
// A listing failure propagates so the sweep reads it as "could not list" (which vetoes
// presence cleanup), never as "verifiably no objects".
@@ -27,6 +27,7 @@ import stirling.software.proprietary.policy.ledger.ProcessedLedger;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.s3.S3Config;
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
import stirling.software.proprietary.policy.s3.S3ConnectionResolver;
import stirling.software.proprietary.policy.s3.S3Identities;
import software.amazon.awssdk.core.exception.SdkException;
@@ -59,6 +60,7 @@ public class S3OutputSink implements PolicyOutputSink {
private static final String TYPE = "s3";
private final S3ConnectionPool connectionPool;
private final S3ConnectionResolver connectionResolver;
private final ProcessedLedger processedLedger;
@Override
@@ -72,19 +74,19 @@ public class S3OutputSink implements PolicyOutputSink {
}
/**
* Config shape and endpoint guard only - no network probe, since write-only credentials
* (s3:PutObject without s3:ListBucket) are a legitimate setup for an output bucket and a
* listing probe would wrongly reject them.
* Connection resolution (including the saving user's right to use it) and endpoint guard only -
* no network probe, since write-only credentials (s3:PutObject without s3:ListBucket) are a
* legitimate setup for an output bucket and a listing probe would wrongly reject them.
*/
@Override
public void validate(OutputSpec spec) {
connectionPool.clientFor(S3Config.from(spec.options()));
connectionPool.clientFor(connectionResolver.resolve(spec.options()));
}
@Override
public List<ResultFile> deliver(
OutputDelivery delivery, List<Resource> outputs, OutputSpec spec) throws IOException {
S3Config config = S3Config.from(spec.options());
S3Config config = connectionResolver.resolve(spec.options());
S3Client client = connectionPool.clientFor(config);
List<ResultFile> results = new ArrayList<>();
@@ -0,0 +1,212 @@
package stirling.software.proprietary.policy.s3;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.proprietary.access.model.DefaultAccessPolicy;
import stirling.software.proprietary.access.model.OwnerScope;
import stirling.software.proprietary.integration.model.IntegrationConfig;
import stirling.software.proprietary.integration.model.IntegrationType;
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.source.Source;
import stirling.software.proprietary.policy.source.SourceStore;
import stirling.software.proprietary.policy.store.PolicyStore;
import stirling.software.proprietary.security.repository.TeamRepository;
import tools.jackson.databind.ObjectMapper;
/**
* One-time, idempotent extraction of legacy embedded S3 credentials into stored connections:
* sources and policy outputs written before connections shipped carry bucket/credentials in their
* own options; this rewrites each to reference a (deduplicated) S3 {@link IntegrationConfig} and
* keeps only per-use options (prefix, mode). MUST be programmatic - the option JSON is encrypted at
* the application layer, so no SQL migration can read it.
*
* <p>Idempotent by construction: rewritten rows no longer embed credentials, so re-runs find
* nothing to do. Connections are deduplicated against both this run's extractions and existing S3
* connections; a concurrent multi-node boot can at worst create a redundant connection row, never
* corrupt a source. Ownership follows the owning row: team-scoped when the source/policy has a
* team, server-scoped otherwise (single-operator self-hosted).
*/
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnBooleanProperty(name = "policies.enabled")
public class EmbeddedS3CredentialMigration {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final List<String> CONNECTION_OPTIONS =
List.of("bucket", "region", "endpoint", "accessKeyId", "secretAccessKey");
// Field separator for the dedup key: a unit-separator control char that cannot appear in a
// bucket/region/endpoint/credential, so distinct field sets can never collide.
private static final char DELIMITER = '\u001f';
private final SourceStore sourceStore;
private final PolicyStore policyStore;
private final IntegrationConfigRepository connections;
private final TeamRepository teamRepository;
@EventListener(ApplicationReadyEvent.class)
@Transactional
public void migrate() {
Map<String, IntegrationConfig> byCredentialKey = indexExistingConnections();
int migrated = 0;
for (Source source : sourceStore.all()) {
if (!"s3".equals(source.type()) || !embedsCredentials(source.options())) {
continue;
}
IntegrationConfig connection =
connectionFor(source.options(), source.teamId(), byCredentialKey);
sourceStore.save(withOptions(source, referencing(connection, source.options(), true)));
migrated++;
}
for (Policy policy : policyStore.all()) {
OutputSpec output = policy.output();
if (!"s3".equals(output.type()) || !embedsCredentials(output.options())) {
continue;
}
IntegrationConfig connection =
connectionFor(output.options(), policy.teamId(), byCredentialKey);
policyStore.save(
withOutput(
policy,
new OutputSpec(
output.type(),
referencing(connection, output.options(), false))));
migrated++;
}
if (migrated > 0) {
log.info("Extracted embedded S3 credentials from {} row(s) into connections", migrated);
}
}
private static boolean embedsCredentials(Map<String, Object> options) {
return options.get("accessKeyId") != null;
}
/** Reuses an existing connection with identical coordinates+credentials, else creates one. */
private IntegrationConfig connectionFor(
Map<String, Object> options, Long teamId, Map<String, IntegrationConfig> byKey) {
String key = credentialKey(options);
IntegrationConfig existing = byKey.get(key);
if (existing != null) {
return existing;
}
IntegrationConfig connection = new IntegrationConfig();
connection.setIntegrationType(IntegrationType.S3);
connection.setName(connectionName(options, byKey));
connection.setEnabled(true);
connection.setLocked(false);
connection.setDefaultAccess(DefaultAccessPolicy.EXPLICIT_ONLY);
Team team = teamId == null ? null : teamRepository.findById(teamId).orElse(null);
if (team != null) {
connection.setScope(OwnerScope.TEAM);
connection.setOwnerTeam(team);
} else {
// No team (teamless self-hosted, or a source whose team was since deleted): server
// scope, i.e. admin-owned. An orphaned-team source's non-admin editor would then need
// an admin to re-share the connection - acceptable for the narrow orphaned case.
connection.setScope(OwnerScope.SERVER);
}
Map<String, Object> config = new LinkedHashMap<>();
for (String option : CONNECTION_OPTIONS) {
Object value = options.get(option);
if (value != null && !value.toString().isBlank()) {
config.put(option, value);
}
}
connection.setConfig(OBJECT_MAPPER.writeValueAsString(config));
IntegrationConfig saved = connections.save(connection);
byKey.put(key, saved);
return saved;
}
/** The rewritten options: the connection reference plus per-use settings only. */
private static Map<String, Object> referencing(
IntegrationConfig connection, Map<String, Object> legacy, boolean keepMode) {
Map<String, Object> options = new LinkedHashMap<>();
options.put(S3ConnectionResolver.CONNECTION_ID_OPTION, connection.getId());
Object prefix = legacy.get("prefix");
if (prefix != null && !prefix.toString().isBlank()) {
options.put("prefix", prefix);
}
Object mode = legacy.get("mode");
if (keepMode && mode != null && !mode.toString().isBlank()) {
options.put("mode", mode);
}
return options;
}
private Map<String, IntegrationConfig> indexExistingConnections() {
Map<String, IntegrationConfig> byKey = new LinkedHashMap<>();
for (IntegrationConfig connection : connections.findAll()) {
if (connection.getIntegrationType() != IntegrationType.S3) {
continue;
}
try {
Map<String, Object> config =
OBJECT_MAPPER.readValue(connection.getConfig(), Map.class);
byKey.putIfAbsent(credentialKey(config), connection);
} catch (Exception e) {
log.debug(
"Skipping unreadable S3 connection {} while indexing: {}",
connection.getId(),
e.getMessage());
}
}
return byKey;
}
private static String credentialKey(Map<String, Object> options) {
StringBuilder key = new StringBuilder();
for (String option : CONNECTION_OPTIONS) {
Object value = options.get(option);
key.append(value == null ? "" : value.toString().trim()).append(DELIMITER);
}
return key.toString();
}
private static String connectionName(
Map<String, Object> options, Map<String, IntegrationConfig> byKey) {
String base = "S3: " + options.getOrDefault("bucket", "bucket");
long sameName = byKey.values().stream().filter(c -> c.getName().startsWith(base)).count();
return sameName == 0 ? base : base + " (" + (sameName + 1) + ")";
}
private static Source withOptions(Source source, Map<String, Object> options) {
return new Source(
source.id(),
source.name(),
source.type(),
options,
source.enabled(),
source.owner(),
source.teamId());
}
private static Policy withOutput(Policy policy, OutputSpec output) {
return new Policy(
policy.id(),
policy.name(),
policy.owner(),
policy.enabled(),
policy.trigger(),
policy.sourceIds(),
policy.steps(),
output,
policy.teamId());
}
}
@@ -0,0 +1,56 @@
package stirling.software.proprietary.policy.s3;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
import stirling.software.proprietary.integration.service.IntegrationConfigUsageCheck;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.source.Source;
import stirling.software.proprietary.policy.source.SourceStore;
import stirling.software.proprietary.policy.store.PolicyStore;
/**
* Reports the policy sources and pipeline outputs referencing an S3 connection, so the connection
* cannot be deleted out from under them (mirrors {@code SourceController}'s referenced-source
* delete guard). Scans in memory - fine at admin-dashboard scale, always consistent with the live
* stores.
*/
@Component
@RequiredArgsConstructor
@ConditionalOnBooleanProperty(name = "policies.enabled")
public class PolicyS3ConnectionUsageCheck implements IntegrationConfigUsageCheck {
private final SourceStore sourceStore;
private final PolicyStore policyStore;
@Override
public List<String> usagesOf(long configId) {
List<String> usages = new ArrayList<>();
for (Source source : sourceStore.all()) {
if (references(source.options(), configId)) {
usages.add("source '" + source.name() + "'");
}
}
for (Policy policy : policyStore.all()) {
if (references(policy.output().options(), configId)) {
usages.add("pipeline '" + policy.name() + "'");
}
}
return usages;
}
private static boolean references(Map<String, Object> options, long configId) {
try {
Long reference = S3ConnectionResolver.connectionId(options);
return reference != null && reference == configId;
} catch (IllegalArgumentException unparseable) {
return false;
}
}
}
@@ -5,10 +5,12 @@ import java.net.URISyntaxException;
import java.util.Map;
/**
* Connection settings shared by the S3 input source and output sink, parsed from a spec's options
* map. Credentials are required: there is deliberately no fallback to the server's own AWS
* credential chain, so user-supplied config can never borrow the host's identity. {@code snapshot}
* is input-only and ignored by the sink.
* The fully resolved connection settings the S3 input source and output sink run with - normally
* produced by {@link S3ConnectionResolver} merging a stored connection (bucket, region, endpoint,
* credentials) with per-use options (prefix, mode), or parsed directly from legacy options that
* still embed credentials. Credentials are required: there is deliberately no fallback to the
* server's own AWS credential chain, so user-supplied config can never borrow the host's identity.
* {@code snapshot} is input-only and ignored by the sink.
*/
public record S3Config(
String bucket,
@@ -0,0 +1,151 @@
package stirling.software.proprietary.policy.s3;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.proprietary.access.model.ResourceType;
import stirling.software.proprietary.access.service.OwnershipService;
import stirling.software.proprietary.integration.model.IntegrationConfig;
import stirling.software.proprietary.integration.model.IntegrationType;
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.service.UserService;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.ObjectMapper;
/**
* Turns a source's or output's options into a full {@link S3Config} by dereferencing its {@code
* connectionId} to a stored S3 {@link IntegrationConfig} (the connection owns bucket, region,
* endpoint, and credentials; the options own per-use settings such as prefix and mode). Options
* with no {@code connectionId} fall back to legacy embedded credentials, so rows written before
* connections shipped keep working until {@link EmbeddedS3CredentialMigration} rewrites them.
*
* <p>When an authenticated caller is present (save-time validation), they must be allowed to use
* the connection. Background sweeps and deliveries run with no caller and skip that check: the
* referencing source or policy was access-checked when it was saved.
*/
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
@ConditionalOnBooleanProperty(name = "policies.enabled")
public class S3ConnectionResolver {
static final String CONNECTION_ID_OPTION = "connectionId";
private static final String PREFIX_OPTION = "prefix";
private static final String MODE_OPTION = "mode";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final IntegrationConfigRepository connections;
private final OwnershipService ownership;
private final UserService userService;
public S3Config resolve(Map<String, Object> options) {
Long connectionId = connectionId(options);
if (connectionId == null) {
// Legacy embedded credentials, pending migration.
return S3Config.from(options);
}
IntegrationConfig connection =
connections
.findById(connectionId)
.filter(cfg -> cfg.getIntegrationType() == IntegrationType.S3)
.filter(this::usableByCurrentUser)
// Existence and access collapse into one error: a caller must not be able
// to tell "no such connection" from "someone else's connection" and
// enumerate ids. The id/name are never echoed.
.orElseThrow(
() ->
new IllegalArgumentException(
"unknown or inaccessible s3 connection"));
if (!connection.isEnabled()) {
throw new IllegalArgumentException("s3 connection is disabled");
}
Map<String, Object> merged = new LinkedHashMap<>(connectionConfig(connection));
copyPerUseOption(options, merged, PREFIX_OPTION);
copyPerUseOption(options, merged, MODE_OPTION);
return S3Config.from(merged);
}
/** The {@code connectionId} option as a long, or null when the options are legacy-embedded. */
static Long connectionId(Map<String, Object> options) {
Object reference = options.get(CONNECTION_ID_OPTION);
if (reference == null || (reference instanceof String s && s.isBlank())) {
return null;
}
if (reference instanceof Number number) {
return number.longValue();
}
try {
return Long.valueOf(reference.toString().trim());
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"s3 'connectionId' is not a valid connection reference: " + reference);
}
}
/**
* Whether the current caller may use this connection. With no principal - a background sweep or
* delivery on a worker thread that carries no {@code SecurityContext} - access is treated as
* already established: stored policies are validated with the caller present at save time, and
* ad-hoc runs are validated on the request thread before dispatch (see {@code
* PolicyValidator#validateOutput}). A missing principal must therefore never be the ONLY thing
* standing between a caller and a connection, or the check becomes a confused deputy.
*/
private boolean usableByCurrentUser(IntegrationConfig connection) {
User user = currentUser();
return user == null || ownership.canUse(ResourceType.INTEGRATION_CONFIG, connection, user);
}
// Mirrors ResourceAccessSecurity's principal resolution; null when unauthenticated.
private User currentUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null || !auth.isAuthenticated()) {
return null;
}
Object principal = auth.getPrincipal();
if (principal instanceof User user) {
return user;
}
if (principal instanceof UserDetails userDetails) {
return userService.findByUsername(userDetails.getUsername()).orElse(null);
}
if (principal instanceof String username && !"anonymousUser".equals(username)) {
return userService.findByUsername(username).orElse(null);
}
return null;
}
private static Map<String, Object> connectionConfig(IntegrationConfig connection) {
String json = connection.getConfig();
if (json == null || json.isBlank()) {
return Map.of();
}
try {
return OBJECT_MAPPER.readValue(
json, new TypeReference<LinkedHashMap<String, Object>>() {});
} catch (Exception e) {
throw new IllegalArgumentException(
"s3 connection '" + connection.getName() + "' has unreadable config", e);
}
}
private static void copyPerUseOption(
Map<String, Object> options, Map<String, Object> merged, String key) {
Object value = options.get(key);
if (value != null && !value.toString().isBlank()) {
merged.put(key, value);
}
}
}
@@ -0,0 +1,51 @@
package stirling.software.proprietary.policy.s3;
import java.net.URI;
import java.util.Map;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.cluster.s3.S3Clients;
import stirling.software.proprietary.integration.model.IntegrationType;
import stirling.software.proprietary.integration.service.IntegrationConfigValidator;
/**
* The S3 connection schema, enforced when an S3 {@link IntegrationType} config is saved: bucket and
* credentials required, endpoint an http(s) URL that must not reach private addresses without the
* operator opt-in - the same rules {@link S3ConnectionPool} enforces before signing, moved to save
* time so a bad connection fails in the form rather than in a sweep.
*/
@Component
@RequiredArgsConstructor
@ConditionalOnBooleanProperty(name = "policies.enabled")
public class S3IntegrationValidator implements IntegrationConfigValidator {
private final ApplicationProperties applicationProperties;
@Override
public IntegrationType type() {
return IntegrationType.S3;
}
@Override
public void validate(Map<String, Object> config) {
S3Config parsed = S3Config.from(config);
if (parsed.endpoint() == null) {
return;
}
try {
S3Clients.validateEndpointHost(
URI.create(parsed.endpoint()),
applicationProperties.getPolicies().isAllowPrivateS3Endpoints(),
"S3 connection endpoint",
"set policies.allowPrivateS3Endpoints=true to opt in (e.g. for a local"
+ " MinIO).");
} catch (IllegalStateException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
}
@@ -103,7 +103,6 @@ public class User implements UserDetails, Serializable {
@ElementCollection
@MapKeyColumn(name = "setting_key")
@Lob
@Column(name = "setting_value", columnDefinition = "text")
@CollectionTable(name = "user_settings", joinColumns = @JoinColumn(name = "user_id"))
@JsonIgnore
@@ -13,9 +13,9 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
@@ -52,7 +52,58 @@ class IntegrationConfigServiceTest {
@Mock
private stirling.software.proprietary.access.repository.ResourceGrantRepository grantRepository;
@InjectMocks private IntegrationConfigService service;
@Mock private IntegrationConfigValidator validator;
@Mock private IntegrationConfigUsageCheck usageCheck;
private IntegrationConfigService service;
@BeforeEach
void setUp() {
service =
new IntegrationConfigService(
repository,
ownership,
secretMasker,
grantRepository,
List.of(validator),
List.of(usageCheck));
}
@Test
void createRejectsAConfigItsTypeValidatorRefuses() {
when(secretMasker.sanitize(any())).thenReturn(Map.of());
when(validator.type()).thenReturn(IntegrationType.API);
org.mockito.Mockito.doThrow(new IllegalArgumentException("api config needs a 'url'"))
.when(validator)
.validate(any());
assertThatThrownBy(
() ->
service.create(
request(IntegrationType.API, OwnerScope.USER, null),
user(7)))
.isInstanceOf(ResponseStatusException.class)
.satisfies(
e ->
assertThat(((ResponseStatusException) e).getStatusCode())
.isEqualTo(HttpStatus.BAD_REQUEST));
}
@Test
void deleteRefusedWhileAnythingStillReferencesTheConfig() {
IntegrationConfig cfg = config(9L);
when(repository.findById(9L)).thenReturn(Optional.of(cfg));
when(ownership.canManage(any(), eq(cfg), any())).thenReturn(true);
when(usageCheck.usagesOf(9L)).thenReturn(List.of("source 'Claims intake'"));
assertThatThrownBy(() -> service.delete(9L, user(7)))
.isInstanceOf(ResponseStatusException.class)
.satisfies(
e ->
assertThat(((ResponseStatusException) e).getStatusCode())
.isEqualTo(HttpStatus.CONFLICT));
verify(repository, org.mockito.Mockito.never()).delete(any(IntegrationConfig.class));
}
@Test
void createDelegatesOwnershipAndSanitizesConfig() {
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -194,6 +195,29 @@ class PolicyControllerTest {
assertThat(((ResponseStatusException) e).getStatusCode())
.isEqualTo(HttpStatus.BAD_REQUEST));
}
@Test
@DisplayName("rejects an ad-hoc output the caller cannot use, on the request thread")
void rejectsUnauthorizedAdHocOutput() {
// The confused-deputy guard: an S3 output referencing a connection the caller may not
// use is validated here (principal present) and refused before any worker dispatch.
PipelineDefinition definition =
new PipelineDefinition(
"pipe",
List.of(new PipelineStep("/api/v1/misc/compress-pdf", null)),
new OutputSpec("s3", Map.of("connectionId", 999)));
doThrow(new IllegalArgumentException("unknown or inaccessible s3 connection"))
.when(policyValidator)
.validateOutput(any());
assertThatThrownBy(() -> controller.run(definition, new PolicyRunFiles()))
.isInstanceOf(ResponseStatusException.class)
.satisfies(
e ->
assertThat(((ResponseStatusException) e).getStatusCode())
.isEqualTo(HttpStatus.BAD_REQUEST));
verify(policyRunner, never()).runAdHoc(any(), any(), any());
}
}
@Nested
@@ -82,6 +82,28 @@ class PolicyValidatorTest {
assertTrue(ex.getMessage().contains("schedule"));
}
@Test
void validateOutputDelegatesToTheSink() {
when(outputSink.supports(any())).thenReturn(true);
OutputSpec output = new OutputSpec("s3", Map.of("connectionId", 1));
validator.validateOutput(output);
verify(outputSink).validate(output);
}
@Test
void validateOutputSurfacesAnInaccessibleConnection() {
when(outputSink.supports(any())).thenReturn(true);
doThrow(new IllegalArgumentException("unknown or inaccessible s3 connection"))
.when(outputSink)
.validate(any());
assertThrows(
IllegalArgumentException.class,
() -> validator.validateOutput(new OutputSpec("s3", Map.of("connectionId", 1))));
}
@Test
void rejectsAnUnknownTriggerType() {
when(trigger.type()).thenReturn("schedule");
@@ -23,6 +23,7 @@ import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
import stirling.software.proprietary.policy.model.InputSpec;
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
import stirling.software.proprietary.policy.s3.S3TestConnections;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
@@ -82,7 +83,9 @@ class S3InputSourceMinioTest {
// The MinIO endpoint resolves to loopback, so the operator opt-in must be on.
ApplicationProperties properties = new ApplicationProperties();
properties.getPolicies().setAllowPrivateS3Endpoints(true);
source = new S3InputSource(new S3ConnectionPool(properties));
source =
new S3InputSource(
new S3ConnectionPool(properties), S3TestConnections.legacyResolver());
ledger = new InProcessProcessedLedger();
ctx = new RecordingContext();
}
@@ -161,7 +164,9 @@ class S3InputSourceMinioTest {
@Test
void aPrivateEndpointIsRejectedWithoutTheOperatorOptIn() {
S3InputSource guarded =
new S3InputSource(new S3ConnectionPool(new ApplicationProperties()));
new S3InputSource(
new S3ConnectionPool(new ApplicationProperties()),
S3TestConnections.legacyResolver());
assertThatThrownBy(() -> guarded.validate(spec(Map.of())))
.isInstanceOf(IllegalArgumentException.class)
@@ -29,6 +29,7 @@ import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
import stirling.software.proprietary.policy.model.InputSpec;
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
import stirling.software.proprietary.policy.s3.S3TestConnections;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.exception.SdkClientException;
@@ -64,7 +65,8 @@ class S3InputSourceTest {
void setUp() {
source =
new S3InputSource(
new S3ConnectionPool(new ApplicationProperties(), config -> s3Client));
new S3ConnectionPool(new ApplicationProperties(), config -> s3Client),
S3TestConnections.legacyResolver());
ledger = new InProcessProcessedLedger();
ctx = new RecordingContext();
}
@@ -28,6 +28,7 @@ import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
import stirling.software.proprietary.policy.model.InputSpec;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
import stirling.software.proprietary.policy.s3.S3TestConnections;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
@@ -90,8 +91,8 @@ class S3OutputSinkMinioTest {
properties.getPolicies().setAllowPrivateS3Endpoints(true);
S3ConnectionPool pool = new S3ConnectionPool(properties);
ledger = new InProcessProcessedLedger();
sink = new S3OutputSink(pool, ledger);
source = new S3InputSource(pool);
sink = new S3OutputSink(pool, S3TestConnections.legacyResolver(), ledger);
source = new S3InputSource(pool, S3TestConnections.legacyResolver());
}
@Test
@@ -32,6 +32,7 @@ import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
import stirling.software.proprietary.policy.ledger.ProcessedFileStatus;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
import stirling.software.proprietary.policy.s3.S3TestConnections;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.exception.SdkClientException;
@@ -66,6 +67,7 @@ class S3OutputSinkTest {
sink =
new S3OutputSink(
new S3ConnectionPool(new ApplicationProperties(), config -> s3Client),
S3TestConnections.legacyResolver(),
ledger);
}
@@ -0,0 +1,212 @@
package stirling.software.proprietary.policy.s3;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import stirling.software.proprietary.access.model.OwnerScope;
import stirling.software.proprietary.integration.model.IntegrationConfig;
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.source.InProcessSourceStore;
import stirling.software.proprietary.policy.source.Source;
import stirling.software.proprietary.policy.store.InProcessPolicyStore;
import stirling.software.proprietary.security.repository.TeamRepository;
/**
* Tests for {@link EmbeddedS3CredentialMigration}: legacy embedded credentials become deduplicated
* team-scoped connections, rewritten rows keep only per-use options, and re-runs are no-ops.
*/
@ExtendWith(MockitoExtension.class)
class EmbeddedS3CredentialMigrationTest {
@Mock private IntegrationConfigRepository connections;
@Mock private TeamRepository teamRepository;
private final InProcessSourceStore sourceStore = new InProcessSourceStore();
private final InProcessPolicyStore policyStore = new InProcessPolicyStore();
private EmbeddedS3CredentialMigration migration;
@BeforeEach
void setUp() {
migration =
new EmbeddedS3CredentialMigration(
sourceStore, policyStore, connections, teamRepository);
AtomicLong ids = new AtomicLong(100);
// Lenient: the nothing-to-migrate cases never create a connection.
lenient().when(connections.findAll()).thenReturn(List.of());
lenient()
.when(connections.save(any()))
.thenAnswer(
invocation -> {
IntegrationConfig saved = invocation.getArgument(0);
if (saved.getId() == null) {
saved.setId(ids.incrementAndGet());
}
return saved;
});
}
@Test
void extractsSharedCredentialsIntoOneTeamScopedConnection() {
Team team = new Team();
team.setId(7L);
when(teamRepository.findById(7L)).thenReturn(Optional.of(team));
Source source =
sourceStore.save(
new Source(
null,
"Claims intake",
"s3",
Map.of(
"bucket", "inbox",
"prefix", "incoming/",
"mode", "snapshot",
"accessKeyId", "AKIAEXAMPLE",
"secretAccessKey", "shh"),
true,
"alice",
7L));
Policy policy =
policyStore.save(
new Policy(
null,
"Rotate",
"alice",
true,
null,
List.of(source.id()),
List.of(new PipelineStep("/api/v1/misc/compress-pdf", Map.of())),
new OutputSpec(
"s3",
Map.of(
"bucket", "inbox",
"prefix", "processed/",
"accessKeyId", "AKIAEXAMPLE",
"secretAccessKey", "shh")),
7L));
migration.migrate();
// Same bucket + credentials on both rows: exactly one connection extracted.
verify(connections, times(1)).save(any());
Map<String, Object> sourceOptions = sourceStore.get(source.id()).orElseThrow().options();
assertEquals(101L, sourceOptions.get("connectionId"));
assertEquals("incoming/", sourceOptions.get("prefix"));
assertEquals("snapshot", sourceOptions.get("mode"));
assertNull(sourceOptions.get("accessKeyId"));
assertNull(sourceOptions.get("secretAccessKey"));
assertNull(sourceOptions.get("bucket"));
Map<String, Object> outputOptions =
policyStore.get(policy.id()).orElseThrow().output().options();
assertEquals(101L, outputOptions.get("connectionId"));
assertEquals("processed/", outputOptions.get("prefix"));
assertNull(outputOptions.get("secretAccessKey"));
}
@Test
void connectionOwnershipFollowsTheSourceTeam() {
Team team = new Team();
team.setId(7L);
when(teamRepository.findById(7L)).thenReturn(Optional.of(team));
sourceStore.save(s3Source("teamed", 7L));
migration.migrate();
verify(connections)
.save(
org.mockito.ArgumentMatchers.argThat(
connection ->
connection.getScope() == OwnerScope.TEAM
&& connection.getOwnerTeam() == team));
}
@Test
void teamlessRowsBecomeServerScopedConnections() {
sourceStore.save(s3Source("solo", null));
migration.migrate();
verify(connections)
.save(
org.mockito.ArgumentMatchers.argThat(
connection -> connection.getScope() == OwnerScope.SERVER));
}
@Test
void aSecondRunFindsNothingToDo() {
sourceStore.save(s3Source("once", null));
migration.migrate();
migration.migrate();
// One connection from the first run; the rewritten source no longer embeds credentials.
verify(connections, times(1)).save(any());
}
@Test
void nonS3AndAlreadyMigratedRowsAreUntouched() {
Source folder =
sourceStore.save(
new Source(
null,
"Folder",
"folder",
Map.of("directory", "/in"),
true,
"alice",
null));
Source migrated =
sourceStore.save(
new Source(
null,
"Done already",
"s3",
Map.of("connectionId", 55L, "prefix", "in/"),
true,
"alice",
null));
migration.migrate();
verify(connections, times(0)).save(any());
assertEquals(
Map.of("directory", "/in"), sourceStore.get(folder.id()).orElseThrow().options());
assertEquals(
Map.of("connectionId", 55L, "prefix", "in/"),
sourceStore.get(migrated.id()).orElseThrow().options());
}
private static Source s3Source(String name, Long teamId) {
return new Source(
null,
name,
"s3",
Map.of(
"bucket", "inbox",
"accessKeyId", "AKIAEXAMPLE",
"secretAccessKey", "shh"),
true,
"alice",
teamId);
}
}
@@ -0,0 +1,52 @@
package stirling.software.proprietary.policy.s3;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.source.InProcessSourceStore;
import stirling.software.proprietary.policy.source.Source;
import stirling.software.proprietary.policy.store.InProcessPolicyStore;
/** Tests for {@link PolicyS3ConnectionUsageCheck}'s reference scan across sources and outputs. */
class PolicyS3ConnectionUsageCheckTest {
private final InProcessSourceStore sourceStore = new InProcessSourceStore();
private final InProcessPolicyStore policyStore = new InProcessPolicyStore();
private final PolicyS3ConnectionUsageCheck check =
new PolicyS3ConnectionUsageCheck(sourceStore, policyStore);
@Test
void reportsSourcesAndOutputsReferencingTheConnection() {
sourceStore.save(
new Source(
null,
"Claims intake",
"s3",
Map.of("connectionId", 5L, "prefix", "in/"),
true,
"alice",
null));
policyStore.save(
new Policy(
null,
"Rotate",
"alice",
true,
null,
List.of(),
List.of(new PipelineStep("/api/v1/misc/compress-pdf", Map.of())),
new OutputSpec("s3", Map.of("connectionId", "5")),
null));
assertThat(check.usagesOf(5))
.containsExactlyInAnyOrder("source 'Claims intake'", "pipeline 'Rotate'");
assertThat(check.usagesOf(6)).isEmpty();
}
}
@@ -0,0 +1,149 @@
package stirling.software.proprietary.policy.s3;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import stirling.software.proprietary.access.service.OwnershipService;
import stirling.software.proprietary.integration.model.IntegrationConfig;
import stirling.software.proprietary.integration.model.IntegrationType;
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.service.UserService;
/**
* Tests for {@link S3ConnectionResolver}: connection dereferencing with per-use overrides, the
* legacy embedded fallback, and the save-time access check that background sweeps skip.
*/
@ExtendWith(MockitoExtension.class)
class S3ConnectionResolverTest {
@Mock private IntegrationConfigRepository connections;
@Mock private OwnershipService ownership;
@Mock private UserService userService;
@AfterEach
void clearSecurityContext() {
SecurityContextHolder.clearContext();
}
@Test
void resolvesAConnectionAndMergesPerUseOptions() {
when(connections.findById(9L)).thenReturn(Optional.of(s3Connection(9L, true)));
S3Config config =
resolver()
.resolve(
Map.of(
"connectionId", 9L,
"prefix", "incoming/",
"mode", "snapshot"));
assertEquals("inbox", config.bucket());
assertEquals("AKIAEXAMPLE", config.accessKeyId());
assertEquals("incoming/", config.prefix());
assertTrue(config.snapshot());
}
@Test
void acceptsAStringConnectionReference() {
when(connections.findById(9L)).thenReturn(Optional.of(s3Connection(9L, true)));
assertEquals("inbox", resolver().resolve(Map.of("connectionId", "9")).bucket());
}
@Test
void fallsBackToLegacyEmbeddedCredentials() {
S3Config config =
resolver()
.resolve(
Map.of(
"bucket", "legacy",
"accessKeyId", "AKIAEXAMPLE",
"secretAccessKey", "shh"));
assertEquals("legacy", config.bucket());
}
@Test
void rejectsUnknownDisabledOrWrongTypeConnections() {
when(connections.findById(1L)).thenReturn(Optional.empty());
assertThrows(
IllegalArgumentException.class,
() -> resolver().resolve(Map.of("connectionId", 1L)));
when(connections.findById(2L)).thenReturn(Optional.of(s3Connection(2L, false)));
assertThrows(
IllegalArgumentException.class,
() -> resolver().resolve(Map.of("connectionId", 2L)));
IntegrationConfig mcp = s3Connection(3L, true);
mcp.setIntegrationType(IntegrationType.MCP);
when(connections.findById(3L)).thenReturn(Optional.of(mcp));
assertThrows(
IllegalArgumentException.class,
() -> resolver().resolve(Map.of("connectionId", 3L)));
}
@Test
void anAuthenticatedSaverMustBeAllowedToUseTheConnection() {
when(connections.findById(9L)).thenReturn(Optional.of(s3Connection(9L, true)));
User saver = new User();
saver.setUsername("alice");
SecurityContextHolder.getContext()
.setAuthentication(
new UsernamePasswordAuthenticationToken(saver, null, java.util.List.of()));
when(ownership.canUse(any(), any(IntegrationConfig.class), eq(saver))).thenReturn(false);
// Denied reads the same as unknown and never echoes the connection name, so ids can't be
// enumerated by probing.
assertThrows(
IllegalArgumentException.class,
() -> resolver().resolve(Map.of("connectionId", 9L)));
try {
resolver().resolve(Map.of("connectionId", 9L));
} catch (IllegalArgumentException e) {
org.junit.jupiter.api.Assertions.assertFalse(
e.getMessage().contains("Claims bucket"),
"access-denied error must not leak the connection name");
}
}
@Test
void backgroundSweepsWithNoUserSkipTheAccessCheck() {
when(connections.findById(9L)).thenReturn(Optional.of(s3Connection(9L, true)));
// No authentication in the context: resolution succeeds without consulting ownership.
assertEquals("inbox", resolver().resolve(Map.of("connectionId", 9L)).bucket());
}
private S3ConnectionResolver resolver() {
return new S3ConnectionResolver(connections, ownership, userService);
}
private static IntegrationConfig s3Connection(long id, boolean enabled) {
IntegrationConfig connection = new IntegrationConfig();
connection.setId(id);
connection.setIntegrationType(IntegrationType.S3);
connection.setName("Claims bucket");
connection.setEnabled(enabled);
connection.setConfig(
"{\"bucket\":\"inbox\",\"accessKeyId\":\"AKIAEXAMPLE\","
+ "\"secretAccessKey\":\"shh\"}");
return connection;
}
}
@@ -0,0 +1,71 @@
package stirling.software.proprietary.policy.s3;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Map;
import org.junit.jupiter.api.Test;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.integration.model.IntegrationType;
/**
* Tests for {@link S3IntegrationValidator}: the S3 connection schema fails at save time - missing
* credentials, bad endpoints, and private endpoints without the operator opt-in.
*/
class S3IntegrationValidatorTest {
@Test
void acceptsACompleteConnection() {
assertThatCode(
() ->
validator(false)
.validate(
Map.of(
"bucket", "inbox",
"accessKeyId", "AKIAEXAMPLE",
"secretAccessKey", "shh")))
.doesNotThrowAnyException();
}
@Test
void rejectsMissingCredentialsOrBucket() {
assertThatThrownBy(() -> validator(false).validate(Map.of("bucket", "inbox")))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(
() ->
validator(false)
.validate(
Map.of(
"accessKeyId", "AKIAEXAMPLE",
"secretAccessKey", "shh")))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void rejectsAPrivateEndpointWithoutTheOperatorOptIn() {
Map<String, Object> config =
Map.of(
"bucket", "inbox",
"accessKeyId", "AKIAEXAMPLE",
"secretAccessKey", "shh",
"endpoint", "http://localhost:9000");
assertThatThrownBy(() -> validator(false).validate(config))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("allowPrivateS3Endpoints");
assertThatCode(() -> validator(true).validate(config)).doesNotThrowAnyException();
}
@Test
void itOnlyClaimsTheS3Type() {
org.junit.jupiter.api.Assertions.assertEquals(IntegrationType.S3, validator(false).type());
}
private static S3IntegrationValidator validator(boolean allowPrivateEndpoints) {
ApplicationProperties properties = new ApplicationProperties();
properties.getPolicies().setAllowPrivateS3Endpoints(allowPrivateEndpoints);
return new S3IntegrationValidator(properties);
}
}
@@ -0,0 +1,24 @@
package stirling.software.proprietary.policy.s3;
import static org.mockito.Mockito.mock;
import stirling.software.proprietary.access.service.OwnershipService;
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
import stirling.software.proprietary.security.service.UserService;
/** Test fixtures for S3 connection plumbing shared across the policy S3 tests. */
public final class S3TestConnections {
private S3TestConnections() {}
/**
* A resolver for tests whose options embed credentials directly (the legacy pass-through path),
* so its collaborators are never touched.
*/
public static S3ConnectionResolver legacyResolver() {
return new S3ConnectionResolver(
mock(IntegrationConfigRepository.class),
mock(OwnershipService.class),
mock(UserService.class));
}
}
+1 -1
View File
@@ -91,7 +91,7 @@ springBoot {
allprojects {
group = 'stirling.software'
version = '2.14.1'
version = '2.14.2'
configurations.configureEach {
exclude group: "org.springframework.boot", module: "spring-boot-starter-tomcat"
-13
View File
@@ -468,14 +468,6 @@ class EmlToPdfParams(ApiModel):
)
class EncodeCharcodesParams(ApiModel):
font_name: str | None = None
locator_char: str | None = None
page_index: int | None = None
pdf_base64: str | None = None
text: str | None = None
class ExtractAttachmentsParams(ApiModel):
pass
@@ -1425,7 +1417,6 @@ class Model(
| EditTextParams
| MergePdfsParams
| MultiPageLayoutParams
| EncodeCharcodesParams
| PdfToSinglePageParams
| RearrangePagesParams
| RemoveImagePdfParams
@@ -1499,7 +1490,6 @@ class Model(
| EditTextParams
| MergePdfsParams
| MultiPageLayoutParams
| EncodeCharcodesParams
| PdfToSinglePageParams
| RearrangePagesParams
| RemoveImagePdfParams
@@ -1574,7 +1564,6 @@ type ParamToolModel = (
| EditTextParams
| MergePdfsParams
| MultiPageLayoutParams
| EncodeCharcodesParams
| PdfToSinglePageParams
| RearrangePagesParams
| RemoveImagePdfParams
@@ -1650,7 +1639,6 @@ class ToolEndpoint(StrEnum):
EDIT_TEXT = "/api/v1/general/edit-text"
MERGE_PDFS = "/api/v1/general/merge-pdfs"
MULTI_PAGE_LAYOUT = "/api/v1/general/multi-page-layout"
ENCODE_CHARCODES = "/api/v1/general/pdf-text-editor-v2/encode-charcodes"
PDF_TO_SINGLE_PAGE = "/api/v1/general/pdf-to-single-page"
REARRANGE_PAGES = "/api/v1/general/rearrange-pages"
REMOVE_IMAGE_PDF = "/api/v1/general/remove-image-pdf"
@@ -1724,7 +1712,6 @@ OPERATIONS: dict[ToolEndpoint, ParamToolModelType] = {
ToolEndpoint.EDIT_TEXT: EditTextParams,
ToolEndpoint.MERGE_PDFS: MergePdfsParams,
ToolEndpoint.MULTI_PAGE_LAYOUT: MultiPageLayoutParams,
ToolEndpoint.ENCODE_CHARCODES: EncodeCharcodesParams,
ToolEndpoint.PDF_TO_SINGLE_PAGE: PdfToSinglePageParams,
ToolEndpoint.REARRANGE_PAGES: RearrangePagesParams,
ToolEndpoint.REMOVE_IMAGE_PDF: RemoveImagePdfParams,
+2
View File
@@ -12,6 +12,8 @@ editor/public/mockServiceWorker.js
# Auto-generated OG/social-preview metadata (scripts/generate-og-metadata.mjs); regenerated verbatim.
editor/public/og-metadata.json
editor/src/core/data/ogImageMap.json
# Auto-generated portal docs manifest (scripts/sync-portal-docs.mts); regenerated verbatim.
editor/src/portal/generated/docsManifest.json
editor/public/pdfjs*/
editor/public/js/thirdParty/
editor/public/css/cookieconsent.css
+4 -8
View File
@@ -22,10 +22,6 @@ const chromiumViewport = {
viewport: { width: 1920, height: 1080 },
};
// Dedicated dev-server port via V2_PORT so local runs don't collide with a
// vite already on 5173 from other parallel work. Defaults to 5173.
const DEV_PORT = process.env.V2_PORT ?? "5173";
export default defineConfig({
testDir: "./src/core/tests",
testMatch: "**/*.spec.ts",
@@ -50,7 +46,7 @@ export default defineConfig({
expect: { timeout: 10_000 },
use: {
baseURL: process.env.PLAYWRIGHT_BASE_URL ?? `http://localhost:${DEV_PORT}`,
baseURL: process.env.PLAYWRIGHT_BASE_URL ?? "http://localhost:5173",
trace: "on-first-retry",
screenshot: "only-on-failure",
video: "on-first-retry",
@@ -116,9 +112,9 @@ export default defineConfig({
// blew the 30s navigationTimeout under --workers=3 - see
// all-tool-pages-load.spec.ts). Locally, keep `vite` dev for HMR.
command: process.env.CI
? `npx vite preview --port ${DEV_PORT} --strictPort`
: `npx vite --port ${DEV_PORT} --strictPort`,
url: `http://localhost:${DEV_PORT}`,
? "npx vite preview --port 5173 --strictPort"
: "npx vite",
url: "http://localhost:5173",
reuseExistingServer: !process.env.CI,
timeout: 120_000,
},
@@ -1,94 +0,0 @@
Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Noto Sans'.
Copyright 2014-2021 Google Inc (http://www.google.com/), with Reserved Font Name 'Noto Sans'.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
@@ -5724,282 +5724,6 @@ notIdealFor2 = "Magazines, brochures, or heavily designed documents"
notIdealFor3 = "Instruction manuals with complex layouts"
title = "Welcome to PDF Text Editor (Early Access)"
[pdfTextEditorV2]
confirmReplaceDirty = "You have unsaved changes. Replace the open document and discard them?"
save = "Save PDF"
saveTooltip = "Download edited PDF (Ctrl+S)"
title = "PDF Text Editor"
workbenchLabel = "Editor"
[pdfTextEditorV2.drop]
hint = "Releases on the editor stage replace any open document."
title = "Drop a PDF to open"
[pdfTextEditorV2.error]
decodeImage = "Could not decode the selected image."
insertImage = "Could not insert the selected image."
[pdfTextEditorV2.find]
close = "Close find bar"
count = "{{current}} of {{total}}"
findPlaceholder = "Find"
noMatches = "No matches"
replace = "Replace"
replaceAll = "Replace all"
replaced = " · {{count}} replaced"
replacePlaceholder = "Replace with"
title = "Find & replace"
typeToSearch = "Type to search"
[pdfTextEditorV2.fonts]
allPresent = "All letters & numbers present"
missing = "Missing: {{glyphs}}"
missingTooltip = "This font has no glyph for: {{glyphs}}. Typing one uses a standard fallback font."
title = "Fonts"
[pdfTextEditorV2.fonts.compat]
info = "Existing text edits perfectly. A new character an embedded font doesn't include falls back to a standard font."
ok = "Every font includes the full alphabet and digits - type freely."
warnOne = "{{count}} font missing some letters or numbers - typing those uses a standard fallback font."
warnOther = "{{count}} fonts missing some letters or numbers - typing those uses a standard fallback font."
[pdfTextEditorV2.fonts.help]
ariaLabel = "What do the font statuses mean?"
embeddedDesc = "full font shipped in the PDF - most new characters match; a glyph the font lacks falls back."
heading = "How fonts affect editing"
standardDesc = "base-14 PDF font - the full standard character set is always available."
subsetDesc = "only the document's existing characters are embedded - new ones usually fall back."
[pdfTextEditorV2.fonts.status.embedded]
hint = "Full font embedded in the PDF. Existing text edits perfectly. New characters render in this font when it includes them - any it lacks (e.g. an accent or symbol the font never carried) fall back to a standard font."
label = "Embedded"
[pdfTextEditorV2.fonts.status.standard]
hint = "Standard PDF font (Helvetica / Times / Courier family). The full standard character set is always available, so existing text AND new characters render in this font."
label = "Standard"
[pdfTextEditorV2.fonts.status.subset]
hint = "Only the characters the document already uses are embedded. Existing text edits fine, but a new character the document never used will usually fall back to a standard font."
label = "Subset"
[pdfTextEditorV2.help]
ariaLabel = "Keyboard shortcuts"
title = "Keyboard shortcuts"
tooltip = "Keyboard shortcuts (?)"
[pdfTextEditorV2.help.arrangement]
alignDesc = "Align edges L / centre / R / T / mid / B"
alignKey = "Toolbar align"
distributeDesc = "Equal horizontal / vertical spacing (3+)"
distributeKey = "Toolbar distribute"
frontBackDesc = "Bring to front / send to back"
frontBackKey = "Toolbar front/back"
heading = "Object arrangement"
lockDesc = "Lock / unlock selection (session-only)"
lockKey = "Lock button"
orderDesc = "Bring forward / send backward (one step)"
orderKey = "Toolbar ↑ ↓"
[pdfTextEditorV2.help.clipboard]
copyDesc = "Copy selected text"
copyKey = "Ctrl+C"
cutDesc = "Cut selected (copy + delete)"
cutKey = "Ctrl+X"
heading = "Clipboard"
pasteDesc = "Paste clipboard text as new run"
pasteKey = "Ctrl+V"
pastePlainDesc = "Paste as plain text"
pastePlainKey = "Ctrl+Shift+V"
[pdfTextEditorV2.help.document]
escDesc = "Clear selection / close find / close help"
escKey = "Esc"
heading = "Document"
helpDesc = "This help"
helpKey = "? / F1"
saveDesc = "Download edited PDF"
saveKey = "Ctrl+S"
[pdfTextEditorV2.help.editing]
clickDesc = "Edit text"
clickKey = "Click"
deleteDesc = "Remove selected"
deleteKey = "Delete"
duplicateDesc = "Duplicate selected"
duplicateKey = "Ctrl+D"
groupDesc = "Group selected runs (Group button)"
groupKey = "Ctrl+M"
heading = "Editing"
marqueeDesc = "Marquee multi-select"
marqueeKey = "Ctrl+Shift+drag"
moveDesc = "Move text run"
moveKey = "Ctrl+Click + drag"
selectAllDesc = "Select all"
selectAllKey = "Ctrl+A"
shiftClickDesc = "Add / remove a run from selection"
shiftClickKey = "Shift+Click"
undoRedoDesc = "Undo / Redo"
undoRedoKey = "Ctrl+Z / Ctrl+Y"
ungroupDesc = "Ungroup paragraph: select it, click Ungroup"
ungroupKey = "-"
[pdfTextEditorV2.help.find]
enterFindDesc = "Next match"
enterFindKey = "Enter (in find)"
enterReplaceDesc = "Replace one (Shift = Replace All)"
enterReplaceKey = "Enter (in replace)"
heading = "Find & Replace"
nextDesc = "Next match (Shift = previous)"
nextKey = "F3 / Ctrl+G"
openDesc = "Open find bar (and replace)"
openKey = "Ctrl+F"
[pdfTextEditorV2.help.formatting]
boldItalicDesc = "Bold / italic"
boldItalicKey = "Toolbar B / I"
caseDesc = "Change case (upper/lower/title/sentence)"
caseKey = "Toolbar case (Aa)"
colourDesc = "Change fill colour"
colourKey = "Toolbar colour"
fontFamilyDesc = "Swap to base-14 font"
fontFamilyKey = "Toolbar font family"
fontSizeDesc = "Change font size"
fontSizeKey = "Toolbar font size"
heading = "Text formatting"
[pdfTextEditorV2.help.image]
flipDesc = "Flip horizontally or vertically"
flipKey = "Toolbar flip"
heading = "Image"
moveDesc = "Move image"
moveKey = "Drag"
resizeDesc = "Resize image"
resizeKey = "Corner drag"
rotateDesc = "Rotate 90° clockwise or counter-clockwise"
rotateKey = "Toolbar rotate"
[pdfTextEditorV2.help.navigation]
firstLastDesc = "First / last page"
firstLastKey = "Ctrl+Home / Ctrl+End"
heading = "Navigation"
pageDesc = "Next / previous page"
pageKey = "PageDown / PageUp"
toolbarZoomDesc = "Manual zoom + Fit to width"
toolbarZoomKey = "Toolbar zoom"
zoomDesc = "Zoom in / out"
zoomKey = "Ctrl+Wheel"
[pdfTextEditorV2.password]
cancel = "Cancel"
incorrect = "Incorrect password - try again."
label = "Password"
open = "Open"
protected = "This PDF is password-protected."
protectedNamed = "\"{{fileName}}\" is password-protected."
title = "Password required"
[pdfTextEditorV2.run]
lockedTitle = "Locked - use the Unlock button to edit"
[pdfTextEditorV2.saveRisk]
cancel = "Cancel"
downloadAnyway = "Download anyway"
intro = "Downloading the edited copy rewrites the whole file. That means:"
note = "Your edits are kept. The changes listed above are unavoidable when downloading the edited copy."
title = "Saving will change this PDF"
[pdfTextEditorV2.sidebar]
addImage = "Add image"
addText = "Add text"
clickPageToAddText = "Click page to add text"
editorSettings = "Editor settings"
group = "Group"
groupingAuto = "Auto"
groupingAutoHint = "Equal-spaced lines group into editable paragraphs."
groupingLine = "Line"
groupingLineHint = "Each source line is edited on its own. Switching clears undo history."
groupTooltip = "Merge selected runs into one paragraph (Ctrl+M)"
groupTooltipDisabled = "Select 2+ runs to merge"
imageSelectedOne = "{{count}} image selected"
imageSelectedOther = "{{count}} images selected"
insert = "Insert"
moveTipPrefix = "Hold "
moveTipSuffix = " and drag a text box to move it."
noFile = "No file loaded"
noFileHint = "Pick a PDF from the Files panel on the left, or drop one in. The editor will open it automatically."
opening = "Opening document..."
paragraph = "Paragraph"
runSelectedOne = "{{count}} text run selected"
runSelectedOther = "{{count}} text runs selected"
textBoxWidth = "Text box width"
textGrouping = "Text grouping"
ungroup = "Ungroup"
ungroupTooltip = "Split this paragraph into one run per line"
ungroupTooltipDisabled = "Select a multi-line paragraph to ungroup"
widthGrow = "Grow"
widthGrowHint = "Boxes widen to the right as you type (no wrapping)."
widthWrap = "Wrap"
widthWrapHint = "Boxes keep their width; extra text wraps onto new lines."
[pdfTextEditorV2.stage]
loadingDocument = "Loading document"
loadingProgress = "Loading progress"
noDocument = "No document loaded."
pickPrompt = "Pick a PDF from the Files panel on the left to begin editing."
renderingPreview = "Rendering preview"
[pdfTextEditorV2.toolbar]
alignBottom = "Align bottom"
alignCentre = "Align centre"
alignLabel = "Align · needs 2+ objects"
alignLeft = "Align left"
alignMiddle = "Align middle"
alignRight = "Align right"
alignTop = "Align top"
arrange = "Arrange"
bold = "Bold"
bringForward = "Bring forward"
bringToFront = "Bring to front"
caseLower = "lowercase"
caseSentence = "Sentence case"
caseTitle = "Title Case"
caseUpper = "UPPERCASE"
changeCase = "Change case"
changeCaseTooltip = "Change case (text runs only)"
delete = "Delete selected"
deleteTooltip = "Delete (Del)"
distributeHorizontally = "Distribute horizontally"
distributeLabel = "Distribute · needs 3+ objects"
distributeVertically = "Distribute vertically"
flipHorizontal = "Flip horizontal"
flipVertical = "Flip vertical"
fontColour = "Font colour"
fontFamily = "Font family"
fontSize = "Font size"
image = "Image"
italic = "Italic"
lock = "Lock selection"
lockTooltip = "Lock selection - prevents accidental edits"
order = "Order"
redo = "Redo"
redoTooltip = "Redo (Ctrl+Y)"
rotateLeft = "Rotate 90° left"
rotateRight = "Rotate 90° right"
selectImageFirst = "Select an image first"
sendBackward = "Send backward"
sendToBack = "Send to back"
undo = "Undo"
undoTooltip = "Undo (Ctrl+Z)"
unlock = "Unlock selection"
unlockTooltip = "Unlock selection - makes it editable again"
[pdfTextEditorV2.zoom]
fit = "Fit"
fitToWidth = "Fit to width"
in = "Zoom in"
out = "Zoom out"
reset = "Reset zoom"
[PDFToCSV]
header = "PDF to CSV"
title = "PDF to CSV"
@@ -6879,6 +6603,10 @@ title = "No components available"
description = "GA components are available on Pay-as-you-go; a few Beta components are enterprise-only. Locked cards show an upgrade nudge."
title = "Some components need a paid plan"
[portal.docs]
browse = "Browse docs"
viewSource = "View source on GitHub"
[portal.docs.authentication]
codeCaption = "every request"
eyebrow = "GETTING STARTED"
@@ -6964,11 +6692,19 @@ title = "Official SDKs"
beta = "Beta"
deprecated = "Deprecated"
[portal.docs.search]
empty = "No matching docs"
placeholder = "Search docs"
results = "{{count}} results"
[portal.docs.skills]
eyebrow = "SKILLS"
lead = "Bundled, named capabilities your agent invokes as a single tool. Each skill is a deterministic op chain with evals attached."
title = "Agent skills"
[portal.docs.toc]
title = "On this page"
[portal.docs.webhooks]
codeCaption = "document.processed"
eyebrow = "API REFERENCE"
@@ -7522,7 +7258,7 @@ storage = "Storage"
[portal.nav]
agent-builder = "Agent Builder"
components = "Components"
docs = "Developer Docs"
docs = "Documentation"
documents = "Documents"
editor = "Editor"
home = "Home"
@@ -5781,288 +5781,6 @@ notIdealFor2 = "Magazines, brochures, or heavily designed documents"
notIdealFor3 = "Instruction manuals with complex layouts"
title = "Welcome to PDF Text Editor (Early Access)"
[pdfTextEditorV2]
confirmReplaceDirty = "You have unsaved changes. Replace the open document and discard them?"
save = "Save PDF"
saveTooltip = "Download edited PDF (Ctrl+S)"
title = "PDF Text Editor"
workbenchLabel = "Editor"
[pdfTextEditorV2.drop]
hint = "Releases on the editor stage replace any open document."
title = "Drop a PDF to open"
[pdfTextEditorV2.error]
decodeImage = "Could not decode the selected image."
insertImage = "Could not insert the selected image."
[pdfTextEditorV2.find]
close = "Close find bar"
count = "{{current}} of {{total}}"
findPlaceholder = "Find"
next = "Next match"
noMatches = "No matches"
previous = "Previous match"
replace = "Replace"
replaceAll = "Replace all"
replaced = " · {{count}} replaced"
replacePlaceholder = "Replace with"
title = "Find & replace"
typeToSearch = "Type to search"
[pdfTextEditorV2.fonts]
allPresent = "All letters & numbers present"
missing = "Missing: {{glyphs}}"
missingTooltip = "This font has no glyph for: {{glyphs}}. Typing one uses a standard fallback font."
title = "Fonts"
[pdfTextEditorV2.fonts.compat]
info = "Existing text edits perfectly. A new character an embedded font doesn't include falls back to a standard font."
ok = "Every font includes the full alphabet and digits - type freely."
warnOne = "{{count}} font missing some letters or numbers - typing those uses a standard fallback font."
warnOther = "{{count}} fonts missing some letters or numbers - typing those uses a standard fallback font."
[pdfTextEditorV2.fonts.help]
ariaLabel = "What do the font statuses mean?"
embeddedDesc = "full font shipped in the PDF - most new characters match; a glyph the font lacks falls back."
existingBody = "always edits in its original font."
existingLabel = "Existing text"
heading = "How fonts affect editing"
newBody = "you type keep the original font only when that font includes them - otherwise they fall back to a standard font (Helvetica)."
newLabel = "New characters"
standardDesc = "base-14 PDF font - the full standard character set is always available."
subsetDesc = "only the document's existing characters are embedded - new ones usually fall back."
[pdfTextEditorV2.fonts.status.embedded]
hint = "Full font embedded in the PDF. Existing text edits perfectly. New characters render in this font when it includes them - any it lacks (e.g. an accent or symbol the font never carried) fall back to a standard font."
label = "Embedded"
[pdfTextEditorV2.fonts.status.standard]
hint = "Standard PDF font (Helvetica / Times / Courier family). The full standard character set is always available, so existing text AND new characters render in this font."
label = "Standard"
[pdfTextEditorV2.fonts.status.subset]
hint = "Only the characters the document already uses are embedded. Existing text edits fine, but a new character the document never used will usually fall back to a standard font."
label = "Subset"
[pdfTextEditorV2.help]
ariaLabel = "Keyboard shortcuts"
title = "Keyboard shortcuts"
tooltip = "Keyboard shortcuts (?)"
[pdfTextEditorV2.help.arrangement]
alignDesc = "Align edges L / centre / R / T / mid / B"
alignKey = "Toolbar align"
distributeDesc = "Equal horizontal / vertical spacing (3+)"
distributeKey = "Toolbar distribute"
frontBackDesc = "Bring to front / send to back"
frontBackKey = "Toolbar front/back"
heading = "Object arrangement"
lockDesc = "Lock / unlock selection (session-only)"
lockKey = "Lock button"
orderDesc = "Bring forward / send backward (one step)"
orderKey = "Toolbar ↑ ↓"
[pdfTextEditorV2.help.clipboard]
copyDesc = "Copy selected text"
copyKey = "Ctrl+C"
cutDesc = "Cut selected (copy + delete)"
cutKey = "Ctrl+X"
heading = "Clipboard"
pasteDesc = "Paste clipboard text as new run"
pasteKey = "Ctrl+V"
pastePlainDesc = "Paste as plain text"
pastePlainKey = "Ctrl+Shift+V"
[pdfTextEditorV2.help.document]
escDesc = "Clear selection / close find / close help"
escKey = "Esc"
heading = "Document"
helpDesc = "This help"
helpKey = "? / F1"
saveDesc = "Download edited PDF"
saveKey = "Ctrl+S"
[pdfTextEditorV2.help.editing]
clickDesc = "Edit text"
clickKey = "Click"
deleteDesc = "Remove selected"
deleteKey = "Delete"
duplicateDesc = "Duplicate selected"
duplicateKey = "Ctrl+D"
groupDesc = "Group selected runs (Group button)"
groupKey = "Ctrl+M"
heading = "Editing"
marqueeDesc = "Marquee multi-select"
marqueeKey = "Ctrl+Shift+drag"
moveDesc = "Move text run"
moveKey = "Ctrl+Click + drag"
selectAllDesc = "Select all"
selectAllKey = "Ctrl+A"
shiftClickDesc = "Add / remove a run from selection"
shiftClickKey = "Shift+Click"
undoRedoDesc = "Undo / Redo"
undoRedoKey = "Ctrl+Z / Ctrl+Y"
ungroupDesc = "Ungroup paragraph: select it, click Ungroup"
ungroupKey = "-"
[pdfTextEditorV2.help.find]
enterFindDesc = "Next match"
enterFindKey = "Enter (in find)"
enterReplaceDesc = "Replace one (Shift = Replace All)"
enterReplaceKey = "Enter (in replace)"
heading = "Find & Replace"
nextDesc = "Next match (Shift = previous)"
nextKey = "F3 / Ctrl+G"
openDesc = "Open find bar (and replace)"
openKey = "Ctrl+F"
[pdfTextEditorV2.help.formatting]
boldItalicDesc = "Bold / italic"
boldItalicKey = "Toolbar B / I"
caseDesc = "Change case (upper/lower/title/sentence)"
caseKey = "Toolbar case (Aa)"
colourDesc = "Change fill colour"
colourKey = "Toolbar colour"
fontFamilyDesc = "Swap to base-14 font"
fontFamilyKey = "Toolbar font family"
fontSizeDesc = "Change font size"
fontSizeKey = "Toolbar font size"
heading = "Text formatting"
[pdfTextEditorV2.help.image]
flipDesc = "Flip horizontally or vertically"
flipKey = "Toolbar flip"
heading = "Image"
moveDesc = "Move image"
moveKey = "Drag"
resizeDesc = "Resize image"
resizeKey = "Corner drag"
rotateDesc = "Rotate 90° clockwise or counter-clockwise"
rotateKey = "Toolbar rotate"
[pdfTextEditorV2.help.navigation]
firstLastDesc = "First / last page"
firstLastKey = "Ctrl+Home / Ctrl+End"
heading = "Navigation"
pageDesc = "Next / previous page"
pageKey = "PageDown / PageUp"
toolbarZoomDesc = "Manual zoom + Fit to width"
toolbarZoomKey = "Toolbar zoom"
zoomDesc = "Zoom in / out"
zoomKey = "Ctrl+Wheel"
[pdfTextEditorV2.password]
cancel = "Cancel"
incorrect = "Incorrect password - try again."
label = "Password"
open = "Open"
protected = "This PDF is password-protected."
protectedNamed = "\"{{fileName}}\" is password-protected."
title = "Password required"
[pdfTextEditorV2.run]
lockedTitle = "Locked - use the Unlock button to edit"
[pdfTextEditorV2.saveRisk]
cancel = "Cancel"
downloadAnyway = "Download anyway"
intro = "Downloading the edited copy rewrites the whole file. That means:"
note = "Your edits are kept. The changes listed above are unavoidable when downloading the edited copy."
title = "Saving will change this PDF"
[pdfTextEditorV2.sidebar]
addImage = "Add image"
addText = "Add text"
clickPageToAddText = "Click page to add text"
editorSettings = "Editor settings"
group = "Group"
groupingAuto = "Auto"
groupingAutoHint = "Equal-spaced lines group into editable paragraphs."
groupingLine = "Line"
groupingLineHint = "Each source line is edited on its own. Switching clears undo history."
groupTooltip = "Merge selected runs into one paragraph (Ctrl+M)"
groupTooltipDisabled = "Select 2+ runs to merge"
imageSelectedOne = "{{count}} image selected"
imageSelectedOther = "{{count}} images selected"
insert = "Insert"
moveTipPrefix = "Hold "
moveTipSuffix = " and drag a text box to move it."
noFile = "No file loaded"
noFileHint = "Pick a PDF from the Files panel on the left, or drop one in. The editor will open it automatically."
opening = "Opening document..."
paragraph = "Paragraph"
runSelectedOne = "{{count}} text run selected"
runSelectedOther = "{{count}} text runs selected"
textBoxWidth = "Text box width"
textGrouping = "Text grouping"
ungroup = "Ungroup"
ungroupTooltip = "Split this paragraph into one run per line"
ungroupTooltipDisabled = "Select a multi-line paragraph to ungroup"
widthGrow = "Grow"
widthGrowHint = "Boxes widen to the right as you type (no wrapping)."
widthWrap = "Wrap"
widthWrapHint = "Boxes keep their width; extra text wraps onto new lines."
[pdfTextEditorV2.stage]
loadingDocument = "Loading document"
loadingProgress = "Loading progress"
noDocument = "No document loaded."
pickPrompt = "Pick a PDF from the Files panel on the left to begin editing."
renderingPreview = "Rendering preview"
[pdfTextEditorV2.toolbar]
alignBottom = "Align bottom"
alignCentre = "Align centre"
alignLabel = "Align · needs 2+ objects"
alignLeft = "Align left"
alignMiddle = "Align middle"
alignRight = "Align right"
alignTop = "Align top"
arrange = "Arrange"
bold = "Bold"
bringForward = "Bring forward"
bringToFront = "Bring to front"
caseLower = "lowercase"
caseSentence = "Sentence case"
caseTitle = "Title Case"
caseUpper = "UPPERCASE"
changeCase = "Change case"
changeCaseTooltip = "Change case (text runs only)"
delete = "Delete selected"
deleteTooltip = "Delete (Del)"
distributeHorizontally = "Distribute horizontally"
distributeLabel = "Distribute · needs 3+ objects"
distributeVertically = "Distribute vertically"
flipHorizontal = "Flip horizontal"
flipVertical = "Flip vertical"
fontColour = "Font colour"
fontFamily = "Font family"
fontSize = "Font size"
image = "Image"
italic = "Italic"
lock = "Lock selection"
lockTooltip = "Lock selection - prevents accidental edits"
order = "Order"
redo = "Redo"
redoTooltip = "Redo (Ctrl+Y)"
rotateLeft = "Rotate 90° left"
rotateRight = "Rotate 90° right"
selectImageFirst = "Select an image first"
sendBackward = "Send backward"
sendToBack = "Send to back"
undo = "Undo"
undoTooltip = "Undo (Ctrl+Z)"
unlock = "Unlock selection"
unlockTooltip = "Unlock selection - makes it editable again"
[pdfTextEditorV2.zoom]
fit = "Fit"
fitToWidth = "Fit to width"
in = "Zoom in"
out = "Zoom out"
reset = "Reset zoom"
[PDFToCSV]
header = "PDF to CSV"
title = "PDF to CSV"
@@ -6522,6 +6240,10 @@ muted = "muted"
nameLabel = "Name"
namePlaceholder = "e.g. Compliance escalation"
[portal.agentBuilder.status]
draft = "Draft"
published = "Published"
[portal.agentBuilder.tabs]
evals = "Evals"
scenarios = "Scenarios"
@@ -6745,7 +6467,7 @@ install = "Install"
usage = "Usage"
[portal.catalogue.detail.locked]
description = "{{name}} is included from the {{tier}} plan. Upgrade to embed it."
description = "{{name}} is included from the {{plan}}. Upgrade to embed it."
title = "Not available on your plan"
[portal.catalogue.detail.preview]
@@ -6812,6 +6534,39 @@ title = "No components available"
description = "GA components are available on Pay-as-you-go; a few Beta components are enterprise-only. Locked cards show an upgrade nudge."
title = "Some components need a paid plan"
[portal.connections]
createTitle = "New S3 connection"
delete = "Delete"
edit = "Edit"
editTitle = "Edit S3 connection"
subtitle = "Reusable S3 credentials that sources and pipeline outputs connect to."
[portal.connections.actions]
new = "New connection"
[portal.connections.empty]
description = "Add an S3 connection to reuse the same bucket and credentials across sources and pipeline outputs."
title = "No connections yet"
[portal.connections.picker]
cancel = "Cancel"
createNew = "New connection..."
placeholder = "Select a connection"
save = "Save connection"
[portal.connections.s3.fields]
name = "Connection name"
namePlaceholder = "e.g. Claims bucket"
[portal.connections.table]
bucket = "Bucket"
name = "Name"
region = "Region"
[portal.docs]
browse = "Browse docs"
viewSource = "View source on GitHub"
[portal.docs.authentication]
codeCaption = "every request"
eyebrow = "GETTING STARTED"
@@ -6897,11 +6652,19 @@ title = "Official SDKs"
beta = "Beta"
deprecated = "Deprecated"
[portal.docs.search]
empty = "No matching docs"
placeholder = "Search docs"
results = "{{count}} results"
[portal.docs.skills]
eyebrow = "SKILLS"
lead = "Bundled, named capabilities your agent invokes as a single tool. Each skill is a deterministic op chain with evals attached."
title = "Agent skills"
[portal.docs.toc]
title = "On this page"
[portal.docs.webhooks]
codeCaption = "document.processed"
eyebrow = "API REFERENCE"
@@ -7566,7 +7329,7 @@ storage = "Storage"
[portal.nav]
agent-builder = "Agent Builder"
components = "Components"
docs = "Developer Docs"
docs = "Documentation"
documents = "Documents"
editor = "Editor"
home = "Home"
@@ -7623,10 +7386,6 @@ operations_one = "Operation ({{count}})"
operations_other = "Operations ({{count}})"
output = "Output"
removeStep = "Remove operation"
s3Configure = "Configure"
s3Done = "Done"
s3ModalTitle = "Amazon S3 output"
s3NotConfigured = "Not configured"
s3PrefixHelp = "Outputs are uploaded under this key prefix."
save = "Save changes"
scheduleEvery = "Run every"
@@ -7697,6 +7456,7 @@ manual = "Manual"
schedule = "Scheduled"
[portal.policies]
defaultName = "{{category}} Policy"
subtitle = "Standing automations that enforce a tool pipeline on every document. Each policy fires on upload or export, runs its tool chain, and saves the enforced version alongside the original."
title = "Policies"
@@ -8268,34 +8028,29 @@ primaryNav = "Primary navigation"
switchApp = "Switch app"
[portal.sources]
subtitle = "Reusable input connections that feed documents into Stirling. Configure a connection once, then reference it from any number of policies. Click a row for its config and which policies use it."
subtitle = "Reusable input connections that feed documents into Stirling. Configure a source once, then reference it from any number of pipelines."
title = "Sources"
[portal.sources.actions]
agentBuilder = "Agent Builder"
connectSource = "Connect source"
[portal.sources.builder]
back = "Back to sources"
cancel = "Cancel"
create = "Create source"
createTitle = "Connect a source"
delete = "Delete"
editTitle = "Edit source"
enabled = "Enabled"
save = "Save changes"
[portal.sources.delete]
body = "Delete \"{{name}}\"? This can't be undone. Policies that reference it would need to be updated."
cancel = "Cancel"
confirm = "Delete"
title = "Delete source?"
[portal.sources.detail]
closeAriaLabel = "Close detail"
delete = "Delete source"
docs24h = "Last 24h"
docs30d = "Last 30 days"
docsTotal = "Total seen"
docsTrend = "Documents over the last 30 days"
documents = "Documents"
edit = "Edit"
notReferenced = "Not referenced by any policy, so it's safe to delete."
pause = "Pause"
resume = "Resume"
subtitle = "{{type}} · {{status}}"
usedBy = "Used by"
[portal.sources.empty]
description = "Connect a folder (and, soon, cloud storage) so your policies have somewhere to pull documents from."
title = "No sources connected yet"
@@ -8311,10 +8066,15 @@ disabled = "Disabled"
unused = "Unused"
[portal.sources.table]
documents = "Documents"
source = "Source"
status = "Status"
usedBy = "Policies"
[portal.sources.tabs]
connections = "Connections"
sources = "Sources"
[portal.sources.types.editor]
description = "Documents your team has processed in the editor, across policy and AI runs."
label = "Editor"
@@ -8362,6 +8122,10 @@ label = "Access key ID"
label = "Bucket"
placeholder = "my-company-inbox"
[portal.sources.types.s3.fields.connection]
helperText = "The stored connection holding the bucket and credentials. Reused by every source and pipeline output that references it."
label = "Connection"
[portal.sources.types.s3.fields.endpoint]
helperText = "Leave blank for Amazon S3. Set to use an S3-compatible service such as MinIO."
label = "Custom endpoint"
@@ -8391,21 +8155,14 @@ label = "Secret access key"
label = "Source"
[portal.sources.wizard]
back = "Back"
cancel = "Cancel"
continue = "Continue"
editTitle = "Edit source"
name = "Name"
namePlaceholder = "e.g. Claims intake"
save = "Save changes"
subtitle = "Step {{current}} of {{total}} · {{label}}"
title = "Connect a source"
type = "Type"
[portal.sources.wizard.steps]
chooseType = "Choose type"
configure = "Configure"
review = "Review & connect"
[portal.tier]
enterprise = "Enterprise plan"
free = "Editor plan"
pro = "Processor plan"
[portal.usage]
managePayment = "Manage Payment"
@@ -10421,6 +10178,19 @@ resetPw = "Reset password"
suspend = "Suspend"
unlock = "Unlock account"
[users.activity]
daysAgo = "{{count}}d ago"
hoursAgo = "{{count}}h ago"
justNow = "Just now"
minutesAgo = "{{count}}m ago"
monthsAgo_one = "{{count}} month ago"
monthsAgo_other = "{{count}} months ago"
never = "Never"
weeksAgo_one = "{{count}} week ago"
weeksAgo_other = "{{count}} weeks ago"
yearsAgo_one = "{{count}} year ago"
yearsAgo_other = "{{count}} years ago"
[users.cap]
addProcessor = "+ Processor"
approver = "Approves policy"
@@ -10491,7 +10261,9 @@ by = "Invited by {{who}}"
cancel = "Cancel"
count = "{{count}} pending"
desc = "Invited people who haven't joined yet. They hold a seat until they accept."
expires = "Expires"
expiresInDays_one = "Expires in {{count}} day"
expiresInDays_other = "Expires in {{count}} days"
expiresToday = "Expires today"
title = "Pending invitations"
[users.loadError]
@@ -0,0 +1,159 @@
/**
* Sync the portal Developer Docs from the Stirling docs repo.
*
* Fetches the docs repo tarball, extracts `docs/**` in-process (no external tar
* binary, no per-file GitHub rate limits), shapes it with the pure transforms in
* src/portal/docs/manifest/transform.ts, and writes the committed manifest that
* the portal docs view renders. Re-run with `npm run docs:sync`.
*
* Env: DOCS_REPO, DOCS_REF, DOCS_ROOT override the defaults below.
*/
import { gunzipSync } from "node:zlib";
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
// tsx/node16 can't resolve the @portal alias here, so import by relative .ts path.
// eslint-disable-next-line no-restricted-imports
import {
buildManifest,
type CategoryMap,
type RawDoc,
} from "../src/portal/docs/manifest/transform.ts";
const REPO = process.env.DOCS_REPO ?? "Stirling-Tools/Stirling-Tools.github.io";
const REF = process.env.DOCS_REF ?? "main";
const ROOT = process.env.DOCS_ROOT ?? "docs";
const SITE = "https://docs.stirlingpdf.com";
const HERE = dirname(fileURLToPath(import.meta.url));
const OUT = resolve(HERE, "../src/portal/generated/docsManifest.json");
/* ── Minimal tar reader (ustar + pax/GNU long names) ─────────────────────── */
interface TarEntry {
name: string;
type: string;
data: Buffer;
}
function readTar(buf: Buffer): TarEntry[] {
const entries: TarEntry[] = [];
let offset = 0;
let longName: string | null = null;
let paxPath: string | null = null;
const str = (start: number, len: number) => {
const slice = buf.subarray(start, start + len);
const end = slice.indexOf(0);
return slice.toString("utf8", 0, end === -1 ? len : end);
};
while (offset + 512 <= buf.length) {
const header = buf.subarray(offset, offset + 512);
// Two consecutive zero blocks mark the end of the archive.
if (header.every((b) => b === 0)) break;
const name = str(offset, 100);
const prefix = str(offset + 345, 155);
const sizeStr = str(offset + 124, 12).trim();
const size = parseInt(sizeStr, 8) || 0;
const type = String.fromCharCode(header[156]);
const dataStart = offset + 512;
const data = buf.subarray(dataStart, dataStart + size);
let fullName = prefix ? `${prefix}/${name}` : name;
if (longName) {
fullName = longName;
longName = null;
}
if (paxPath) {
fullName = paxPath;
paxPath = null;
}
if (type === "L") {
// GNU long name: the payload is the real name of the next entry.
longName = data.toString("utf8").replace(/\0+$/, "");
} else if (type === "x") {
// pax extended header: pull a `path=` record for the next entry.
const record = /(?:^|\n)\d+ path=([^\n]+)\n/.exec(data.toString("utf8"));
if (record) paxPath = record[1];
} else if (type === "0" || type === "\0" || type === "") {
entries.push({ name: fullName, type, data: Buffer.from(data) });
}
offset = dataStart + Math.ceil(size / 512) * 512;
}
return entries;
}
/* ── Fetch + shape ───────────────────────────────────────────────────────── */
async function main(): Promise<void> {
const url = `https://api.github.com/repos/${REPO}/tarball/${REF}`;
console.log(`Fetching ${REPO}@${REF} …`);
const res = await fetch(url, {
headers: {
Accept: "application/vnd.github+json",
"User-Agent": "stirling-portal-docs-sync",
...(process.env.GITHUB_TOKEN
? { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` }
: {}),
},
});
if (!res.ok) {
throw new Error(
`GitHub tarball fetch failed: ${res.status} ${res.statusText}`,
);
}
const gz = Buffer.from(await res.arrayBuffer());
const entries = readTar(gunzipSync(gz));
// Strip the "<repo>-<sha>/" wrapper dir and keep only files under docs root.
const prefix = `${ROOT}/`;
const rawDocs: RawDoc[] = [];
const categories: CategoryMap = {};
for (const entry of entries) {
const rel = entry.name.replace(/^[^/]+\//, "");
if (!rel.startsWith(prefix)) continue;
const inner = rel.slice(prefix.length);
if (!inner) continue;
if (inner.endsWith("/_category_.json")) {
const dir = inner.slice(0, -"/_category_.json".length);
try {
categories[dir] = JSON.parse(entry.data.toString("utf8"));
} catch {
console.warn(` skipping unparseable _category_.json in ${dir}`);
}
} else if (/\.mdx?$/i.test(inner)) {
rawDocs.push({ relPath: inner, content: entry.data.toString("utf8") });
}
}
if (rawDocs.length === 0) {
throw new Error(`No markdown found under ${ROOT}/ — wrong repo/ref/root?`);
}
const manifest = buildManifest(rawDocs, categories, {
repo: REPO,
ref: REF,
root: ROOT,
siteBaseUrl: SITE,
});
mkdirSync(dirname(OUT), { recursive: true });
writeFileSync(OUT, JSON.stringify(manifest, null, 2) + "\n", "utf8");
const items = manifest.nav.reduce((n, s) => n + s.items.length, 0);
console.log(
`Wrote ${manifest.nav.length} sections, ${items} docs → ${OUT.replace(/.*[/\\]frontend[/\\]/, "frontend/")}`,
);
for (const s of manifest.nav) {
console.log(` ${s.icon} ${s.label} (${s.items.length})`);
}
}
main().catch((err) => {
console.error(err instanceof Error ? err.message : err);
process.exitCode = 1;
});
+3 -1
View File
@@ -4,7 +4,9 @@
"module": "node16",
"moduleResolution": "node16",
"types": ["node"],
"noEmit": true
"noEmit": true,
// sync-portal-docs.mts imports the shared transform by its .ts path (run via tsx).
"allowImportingTsExtensions": true
},
"include": ["./**/*.ts", "./**/*.mts"]
}
+1 -1
View File
@@ -2,7 +2,7 @@
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "Stirling PDF",
"mainBinaryName": "Stirling-PDF",
"version": "2.14.1",
"version": "2.14.2",
"identifier": "stirling.pdf.dev",
"build": {
"frontendDist": "../dist",
@@ -399,22 +399,14 @@ export default function WorkbenchBar({
);
// View options
// Tools that own a custom workbench (e.g. the v2 PDF text editor) ship
// their own canvas; the generic Viewer tab is redundant noise while
// those tools are active. Hide it for those tools.
const ownsCustomWorkbenchAsDefault = selectedTool === "pdfTextEditor";
const viewOptions: ViewOption[] = [
...(ownsCustomWorkbenchAsDefault
? []
: [
{
value: "viewer" as WorkbenchType,
label: t("workbenchBar.viewer", "Viewer"),
icon: <InsertDriveFileOutlinedIcon fontSize="small" />,
},
]),
{
value: "fileEditor" as WorkbenchType,
value: "viewer",
label: t("workbenchBar.viewer", "Viewer"),
icon: <InsertDriveFileOutlinedIcon fontSize="small" />,
},
{
value: "fileEditor",
label: t("workbenchBar.activeFiles", "Active Files"),
icon: <FolderOutlinedIcon fontSize="small" />,
},
@@ -93,9 +93,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
/>
),
name: t("home.pdfTextEditor.title", "PDF Text Editor"),
component: lazy(
() => import("@app/tools/pdfTextEditor/v2/PdfTextEditorV2"),
),
component: lazy(() => import("@app/tools/pdfTextEditor/PdfTextEditor")),
description: t(
"home.pdfTextEditor.desc",
"Review and edit text and images in PDFs with grouped text editing and PDF regeneration",
@@ -289,43 +289,6 @@ function copyToWasmHeap(
(m.pdfium as typeof m.pdfium & ExtendedPdfiumRuntime).HEAPU8.set(bytes, ptr);
}
/** Human-readable message for an FPDF_GetLastError() code. */
function pdfiumOpenErrorMessage(err: number): string {
switch (err) {
case 1:
return "Could not open the PDF (unknown error).";
case 2:
return "This file is not a valid PDF or is corrupted.";
case 3:
return "The PDF file is corrupted and could not be read.";
case 4:
return "This PDF is password-protected.";
case 5:
return "This PDF uses an unsupported security scheme.";
case 6:
return "A page in this PDF could not be loaded.";
default:
return `Could not open the PDF (error ${err}).`;
}
}
/** FPDF_GetLastError() code for a missing/incorrect document password. */
export const FPDF_ERR_PASSWORD = 4;
/**
* Open failure carrying the raw FPDF_GetLastError() code so callers can tell a
* password prompt (code 4) apart from a corrupt file. Still an `Error`, so
* existing `instanceof Error` handlers keep working.
*/
export class PdfiumOpenError extends Error {
readonly code: number;
constructor(code: number) {
super(pdfiumOpenErrorMessage(code));
this.name = "PdfiumOpenError";
this.code = code;
}
}
/**
* Load a PDF into PDFium memory and return the document pointer.
* Caller MUST call `closeRawDocument(docPtr)` when finished.
@@ -343,7 +306,8 @@ export async function openRawDocument(
const docPtr = m.FPDF_LoadMemDocument(ptr, len, password ?? "");
if (!docPtr) {
m.pdfium.wasmExports.free(ptr);
throw new PdfiumOpenError(m.FPDF_GetLastError());
const err = m.FPDF_GetLastError();
throw new Error(`PDFium: failed to open document (error ${err})`);
}
// Keep the buffer alive — freed in closeRawDocument()
_docDataPtrs.set(docPtr, ptr);
@@ -38,7 +38,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {
const BASE_NO_LOGIN_CONFIG: AppConfig = {
enableAnalytics: true,
appVersion: "2.14.1",
appVersion: "2.14.2",
serverCertificateEnabled: false,
enableAlphaFunctionality: false,
serverPort: 8080,
@@ -1,250 +0,0 @@
import { test, expect } from "@app/tests/helpers/test-base";
import { loginAndSetup } from "@app/tests/helpers/login";
import * as path from "path";
import * as fs from "fs";
/**
* In dev environments where the Stirling backend ships with login
* disabled (anonymous-mode), `loginAndSetup` will throw because /login
* doesn't render. Detect that and silently skip the call. Live CI
* still hits the real login flow (login enabled in the CI backend
* profile), so this conditional only takes effect when running the
* suite against a no-auth dev backend.
*/
async function loginIfNeeded(
page: import("@playwright/test").Page,
): Promise<void> {
try {
await loginAndSetup(page);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
if (/email|login/i.test(msg)) {
// anonymous-mode backend - nothing to log in to.
return;
}
throw e;
}
}
/**
* Live e2e coverage for the v2 PDF text editor's `backend` charcode
* strategy.
*
* Unlike the `stubbed` suite, these tests hit the REAL Spring backend
* (`/api/v1/general/pdf-text-editor-v2/encode-charcodes`) via PDFBox.
* Sample.pdf is the standout repro: every glyph is a per-char Type3
* font where naive Helvetica fallback renders "M" as the wrong glyph
* shape. The backend's ToUnicode-reverse-CMap lookup resolves each
* char to its native font + charcode, the frontend's per-char emit
* branch creates one text object per char with the correct font
* handle + SetCharcodes(charcode), and the result visually matches
* the source text.
*
* The two things this suite guards against:
* 1. Regression of the per-char emit branch (must fire on the
* FIRST keystroke after focus, NOT the second - the prewarm in
* TextRunOverlay.onFocus exists precisely to eliminate the
* old 2-attempt UX).
* 2. Wrong charcode being emitted (e.g. M → 0 / .notdef instead of
* the real glyph index that PDFBox's ToUnicode reverse map
* returns).
*/
function fixture(filename: string): string {
const candidates = [
path.resolve(
process.cwd(),
"src",
"core",
"tests",
"test-fixtures",
filename,
),
path.resolve(
process.cwd(),
"frontend",
"src",
"core",
"tests",
"test-fixtures",
filename,
),
];
for (const p of candidates) {
if (fs.existsSync(p)) return p;
}
throw new Error(
`Test fixture not found: ${filename} (tried: ${candidates.join(", ")})`,
);
}
// `user-sample.pdf` is the same file as `frontend/editor/public/samples/Sample.pdf`,
// copied into the test fixtures dir so this suite is self-contained.
const USER_SAMPLE_PDF = fixture("user-sample.pdf");
async function gotoEditorWithBackendStrategy(
page: import("@playwright/test").Page,
): Promise<void> {
// `charcodeDebug=1` enables the HUD overlay (CharcodeDebugHud) that
// emits one row per attempt, which is what this test scrapes.
await page.goto("/pdf-text-editor?charcodeStrategy=backend&charcodeDebug=1", {
waitUntil: "domcontentloaded",
});
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 30_000 });
}
async function loadUserSamplePdf(
page: import("@playwright/test").Page,
): Promise<void> {
await page
.locator('[data-testid="v2-file-input"]')
.setInputFiles(USER_SAMPLE_PDF);
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 60_000 });
}
test.describe("v2 charcode backend strategy (live PDFBox)", () => {
test.describe.configure({ timeout: 120_000 });
test.beforeEach(async ({ page }) => {
await loginIfNeeded(page);
});
test("Sample.pdf 10M+: typing M into the per-glyph Type3 font emits charcodes-ok on the FIRST keystroke", async ({
page,
}) => {
await gotoEditorWithBackendStrategy(page);
await loadUserSamplePdf(page);
// Find the 10M+ run.
const runEl = page
.locator('[data-testid^="v2-run-p"]')
.filter({ hasText: /^10M\+$/ })
.first();
await expect(runEl).toBeVisible({ timeout: 15_000 });
const runTestId = (await runEl.getAttribute("data-testid")) ?? "";
expect(runTestId).toMatch(/^v2-run-p\d+-/);
// Listen for the prewarm-complete console.debug log BEFORE we
// focus the run, so we don't race the message.
// Match either of:
// "backend prewarm pageIdx=0 probes=N" - the completion log
// "backend prewarm pageIdx=0 probes=0 (already-prewarmed)" -
// cached from a prior test, treat as complete
// The prewarm-START log ("prewarm-start pageIdx=") confirms that
// the focus actually triggered the lazy-import path even on the
// early-return branches.
const prewarmComplete = page.waitForEvent("console", {
predicate: (msg) =>
/\[v2\.charcode\] backend prewarm pageIdx=/.test(msg.text()),
timeout: 90_000,
});
// Surface ALL console messages to the test stdout so we can see
// what's happening if the prewarm log doesn't fire. Wrapping
// page.on now means messages from before THIS line are missed,
// but the prewarm fires after focus (below) so we catch it.
page.on("console", (msg) => {
if (/v2\.charcode|prewarm/.test(msg.text())) {
process.stdout.write(`[page-console-${msg.type()}] ${msg.text()}\n`);
}
});
// Use Playwright's physical click - that dispatches real
// mousedown/up/click + focus events that React's synthetic
// event system catches reliably. Calling el.focus() from
// page.evaluate works for native DOM focus but can race React's
// focus delegation in unmount/mount transitions.
await runEl.click();
// Wait for prewarm to log "[v2.charcode] backend prewarm pageIdx=
// probes=N". After this fires the per-char cache for the page is
// populated and the next keystroke hits charcodes-ok on the FIRST
// try.
await prewarmComplete;
// First keystroke: should hit the per-char emit branch on the
// FIRST try (no Helvetica fallback). Use execCommand("insertText")
// because Playwright's keyboard.type on contenteditable can
// occasionally route through synthetic key events that the
// editor's onInput debounce drops.
await page.evaluate((tid) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="${tid}"]`,
);
if (!el) throw new Error(`run ${tid} not in DOM`);
el.focus();
const sel = window.getSelection();
if (!sel) throw new Error("no Selection api");
const range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, "M");
}, runTestId);
// The debug HUD was removed from production builds, so verify the emit
// through the window-exposed telemetry buffer instead (charcodeRegistry
// mirrors recent CharcodeEvents onto window.__v2_charcode_events for
// exactly this purpose). Poll for a charcodes-ok event covering the
// typed "M": robust to whether prewarm beat the keystroke (1-attempt)
// or the resolver's auto-prefetch retried slightly after.
type CharcodeEmitEvent = {
text: string;
outcome: string;
resolved: number[];
};
const readCharcodeEvents = () =>
page.evaluate(
() =>
(
window as unknown as {
__v2_charcode_events?: CharcodeEmitEvent[];
}
).__v2_charcode_events ?? [],
);
await expect
.poll(
async () => {
const events = await readCharcodeEvents();
return events.some(
(e) =>
e.text.includes("M") &&
e.outcome === "charcodes-ok" &&
e.resolved.length > 0,
);
},
{ timeout: 10_000, intervals: [250, 500, 1000] },
)
.toBe(true);
// Cross-check: the editor's model must reflect "10M+M" - the
// typed M became a real text run via the per-char emit branch.
const runText = await page.evaluate((tid) => {
const w = window as unknown as {
__v2_editor_store: {
state: { pages: { runs: { id: string; text: string }[] }[] };
};
};
for (const p of w.__v2_editor_store.state.pages) {
for (const r of p.runs) {
if (`v2-run-${r.id}` === tid) return r.text;
}
}
return "";
}, runTestId);
expect(runText).toBe("10M+M");
// No-regression guard: the MOST RECENT emit covering "M" must be a
// source-font charcodes-ok emit, NOT a Helvetica fallback. This is
// the "first-keystroke-must-work" assertion.
const events = await readCharcodeEvents();
const mEvents = events.filter((e) => e.text.includes("M"));
const lastM = mEvents[mEvents.length - 1];
expect(
lastM?.outcome,
`latest M emit must be charcodes-ok. Events:\n${JSON.stringify(events, null, 2)}`,
).toBe("charcodes-ok");
});
});
@@ -1,870 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page } from "@playwright/test";
import path from "path";
import type {
V2Matrix,
V2TestWindow,
} from "@app/tests/stubbed/v2EditorTestTypes";
/**
* Combined-feature regression suite: the new editor features (image
* rotate/flip, z-order, align/distribute, lock, change-case, cut/paste,
* find+replace) AND their interaction with the 12 bug fixes. Page-level
* operations (page rotate/print/reset) are intentionally absent.
*/
const SAMPLE = path.join(
import.meta.dirname,
"../../../../public/samples/Sample.pdf",
);
const PNG = path.join(import.meta.dirname, "../test-fixtures/sample.png");
// z-order / align / distribute live in the toolbar's "Arrange" menu, and
// image rotate/flip in the "Image" menu. Open the menu, then click the item.
async function clickArrange(page: Page, testid: string): Promise<void> {
await page.getByTestId("v2-arrange-menu").click();
await page.getByTestId(testid).click();
}
async function clickImage(page: Page, testid: string): Promise<void> {
await page.getByTestId("v2-imgop-menu").click();
await page.getByTestId(testid).click();
}
async function open(page: Page, firstPage = 0): Promise<void> {
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 15_000 });
await page.locator('[data-testid="v2-file-input"]').setInputFiles(SAMPLE);
await expect(page.getByTestId(`v2-page-${firstPage}`)).toBeVisible({
timeout: 30_000,
});
await page.waitForTimeout(900);
}
async function runId(
page: Page,
pageIdx: number,
src: string,
): Promise<string> {
const id = await page.evaluate(
({ pageIdx, src }: { pageIdx: number; src: string }) => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
const r = s.doc
.page(pageIdx)
.runs.find((x) => new RegExp(src).test(x.text));
return r ? r.id : null;
},
{ pageIdx, src },
);
if (!id) throw new Error(`run /${src}/ not found`);
return id;
}
async function selectRun(page: Page, id: string): Promise<void> {
await page.evaluate(
(rid: string) =>
(window as unknown as V2TestWindow).__v2_editor_store.selection.selectOne(
rid,
),
id,
);
await page.waitForTimeout(120);
}
async function selectMany(page: Page, ids: string[]): Promise<void> {
await page.evaluate(
(rids: string[]) =>
(
window as unknown as V2TestWindow
).__v2_editor_store.selection.selectMany(rids),
ids,
);
await page.waitForTimeout(120);
}
async function runText(
page: Page,
pageIdx: number,
id: string,
): Promise<string> {
return page.evaluate(
({ pageIdx, id }: { pageIdx: number; id: string }) => {
const r = (window as unknown as V2TestWindow).__v2_editor_store.doc
.page(pageIdx)
.runs.find((x) => x.id === id);
return r ? (r.text as string) : "(gone)";
},
{ pageIdx, id },
);
}
async function insertImage(
page: Page,
): Promise<{ id: string; matrix: V2Matrix } | null> {
await page.locator('[data-testid="v2-image-input"]').setInputFiles(PNG);
await page.waitForTimeout(1200);
return page.evaluate(() => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
for (const p of s.doc.loadedPages()) {
if (p.images.length > 0) {
const img = p.images[p.images.length - 1];
return { id: img.id, matrix: { ...img.matrix } };
}
}
return null;
});
}
async function imageMatrix(
page: Page,
imageId: string,
): Promise<V2Matrix | null> {
return page.evaluate((iid: string) => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
for (const p of s.doc.loadedPages()) {
const img = p.images.find((x) => x.id === iid);
if (img) return { ...img.matrix };
}
return null;
}, imageId);
}
async function totalRuns(page: Page): Promise<number> {
return page.evaluate(() =>
(window as unknown as V2TestWindow).__v2_editor_store.doc
.loadedPages()
.reduce((n: number, p) => n + p.runs.length, 0),
);
}
async function countRunsContaining(page: Page, sub: string): Promise<number> {
return page.evaluate((sub: string) => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
const needle = sub.toLowerCase();
let n = 0;
for (const p of s.doc.loadedPages())
for (const r of p.runs) if (r.text.toLowerCase().includes(needle)) n += 1;
return n;
}, sub);
}
async function firstRunIds(
page: Page,
pageIdx: number,
n: number,
): Promise<string[]> {
return page.evaluate(
({ pageIdx, n }: { pageIdx: number; n: number }) =>
(window as unknown as V2TestWindow).__v2_editor_store.doc
.page(pageIdx)
.runs.slice(0, n)
.map((r) => r.id),
{ pageIdx, n },
);
}
async function undoSize(page: Page): Promise<number> {
return page.evaluate(
() =>
(window as unknown as V2TestWindow).__v2_editor_store.history.size().undo,
);
}
test.describe("v2 editor - combined feature set", () => {
// Editor edits fire encode-charcodes; with no backend an UNMOCKED call 401s
// and redirects to login, unmounting the editor (the __v2_editor_store goes
// undefined mid-test). Abort it so the resolver sees a clean cold-cache miss.
test.beforeEach(async ({ page }) => {
await page.route("**/encode-charcodes", (route) => route.abort());
});
test("image insert (real png) adds an image, then rotate-cw changes its matrix and undo reverts", async ({
page,
}) => {
await open(page, 0);
const ins = await insertImage(page);
expect(ins, "image insert must add an image").not.toBeNull();
await page.evaluate(
(iid: string) =>
(
window as unknown as V2TestWindow
).__v2_editor_store.selection.selectImage(iid),
ins!.id,
);
await page.waitForTimeout(120);
await clickImage(page, "v2-imgop-rotate-cw");
await page.waitForTimeout(300);
const rotated = await imageMatrix(page, ins!.id);
// A 90deg rotation swaps the axes: original diagonal (a,d) becomes off-diagonal (b,c).
expect(
Math.abs(rotated!.a) + Math.abs(rotated!.d),
"rotate must move scale off the main diagonal",
).toBeLessThan(Math.abs(rotated!.b) + Math.abs(rotated!.c) + 0.01);
await page.getByTestId("v2-undo").click();
await page.waitForTimeout(300);
const reverted = await imageMatrix(page, ins!.id);
expect(reverted!.a).toBeCloseTo(ins!.matrix.a, 1);
expect(reverted!.d).toBeCloseTo(ins!.matrix.d, 1);
});
test("image flip-h mirrors the matrix and undo reverts", async ({ page }) => {
await open(page, 0);
const ins = await insertImage(page);
expect(ins).not.toBeNull();
await page.evaluate(
(iid: string) =>
(
window as unknown as V2TestWindow
).__v2_editor_store.selection.selectImage(iid),
ins!.id,
);
await page.waitForTimeout(120);
await clickImage(page, "v2-imgop-flip-h");
await page.waitForTimeout(300);
const flipped = await imageMatrix(page, ins!.id);
expect(Math.sign(flipped!.a), "flip-h negates horizontal scale").toBe(
-Math.sign(ins!.matrix.a || 1),
);
await page.getByTestId("v2-undo").click();
await page.waitForTimeout(300);
const reverted = await imageMatrix(page, ins!.id);
expect(reverted!.a).toBeCloseTo(ins!.matrix.a, 1);
});
test("change case UPPER then LOWER transforms the selected run's text", async ({
page,
}) => {
await open(page, 1);
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
const orig = await runText(page, 1, id);
await selectRun(page, id);
await page.getByTestId("v2-change-case").click();
await page.getByTestId("v2-change-case-upper").click();
await page.waitForTimeout(400);
const upper = await runText(page, 1, id);
expect(upper).toBe(orig.toUpperCase());
await selectRun(page, id);
await page.getByTestId("v2-change-case").click();
await page.getByTestId("v2-change-case-lower").click();
await page.waitForTimeout(400);
const lower = await runText(page, 1, id);
expect(lower).toBe(orig.toLowerCase());
});
test("lock makes a run inert (no select on click); unlock restores it", async ({
page,
}) => {
await open(page, 1);
const id = await runId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
await selectRun(page, id);
await page.getByTestId("v2-toggle-lock").click();
await page.waitForTimeout(200);
const locked = await page.evaluate(
(rid: string) =>
(window as unknown as V2TestWindow).__v2_editor_store.doc
.page(1)
.runs.find((x) => x.id === rid)!.locked,
id,
);
expect(locked, "run should be locked").toBe(true);
// The overlay snapshot must refresh so the lock takes visible effect:
// a locked run drops contentEditable and exposes data-locked.
await expect(page.getByTestId(`v2-run-${id}`)).toHaveAttribute(
"data-locked",
"true",
);
await expect(page.getByTestId(`v2-run-${id}`)).toHaveAttribute(
"contenteditable",
"false",
);
// Clear selection, then clicking the locked run must NOT select it.
await page.evaluate(() =>
(window as unknown as V2TestWindow).__v2_editor_store.selection.clear(),
);
await page
.getByTestId(`v2-run-${id}`)
.click()
.catch(() => {});
await page.waitForTimeout(150);
const selAfterClick = await page.evaluate(
() =>
(window as unknown as V2TestWindow).__v2_editor_store.selection.value
.runIds.length,
);
expect(selAfterClick, "locked run must not be selectable by click").toBe(0);
});
test("align-left makes selected runs share the same left x", async ({
page,
}) => {
await open(page, 1);
const a = await runId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
const b = await runId(page, 1, "Comprehensive\\s+toolkit");
await selectMany(page, [a, b]);
await clickArrange(page, "v2-align-left");
await page.waitForTimeout(300);
const xs = await page.evaluate(
({ a, b }: { a: string; b: string }) => {
const pg = (
window as unknown as V2TestWindow
).__v2_editor_store.doc.page(1);
const ra = pg.runs.find((x) => x.id === a)!;
const rb = pg.runs.find((x) => x.id === b)!;
return [ra.bounds.x, rb.bounds.x];
},
{ a, b },
);
expect(
Math.abs(xs[0] - xs[1]),
"aligned runs share a left edge",
).toBeLessThan(1.5);
});
test("cut (Ctrl+X) removes the run and paste (Ctrl+V) brings it back", async ({
page,
}) => {
// Cut/paste round-trips through the real system clipboard; the headless
// context blocks clipboard.read by default, so grant it explicitly.
await page
.context()
.grantPermissions(["clipboard-read", "clipboard-write"]);
await open(page, 1);
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
const before = await totalRuns(page);
await selectRun(page, id);
// Cut is suppressed while focus is inside a contentEditable run (so the
// browser's native cut wins there). The real editor-level cut path fires
// from a marquee/store selection with focus outside any run - mirror that.
await page.evaluate(() =>
(document.activeElement as HTMLElement | null)?.blur(),
);
await page.keyboard.press("Control+x");
await page.waitForTimeout(400);
const afterCut = await totalRuns(page);
expect(afterCut, "cut removes the run").toBeLessThan(before);
await page.keyboard.press("Control+v");
await page.waitForTimeout(600);
const afterPaste = await totalRuns(page);
expect(afterPaste, "paste re-adds a run").toBeGreaterThan(afterCut);
});
test("z-order: bring-to-front on an inserted image applies and undoes cleanly", async ({
page,
}) => {
await open(page, 0);
const ins = await insertImage(page);
expect(ins).not.toBeNull();
await page.evaluate(
(iid: string) =>
(
window as unknown as V2TestWindow
).__v2_editor_store.selection.selectImage(iid),
ins!.id,
);
await page.waitForTimeout(120);
const undoBefore = await page.evaluate(
() =>
(window as unknown as V2TestWindow).__v2_editor_store.history.size()
.undo,
);
await clickArrange(page, "v2-z-to-front");
await page.waitForTimeout(300);
const undoAfter = await page.evaluate(
() =>
(window as unknown as V2TestWindow).__v2_editor_store.history.size()
.undo,
);
expect(undoAfter, "z-order is its own undo step").toBe(undoBefore + 1);
// No crash + still one image present.
const imgs = await page.evaluate(() =>
(window as unknown as V2TestWindow).__v2_editor_store.doc
.loadedPages()
.reduce((n: number, p) => n + p.images.length, 0),
);
expect(imgs).toBeGreaterThan(0);
});
test("editing a run still preserves unedited paragraph lines (fix holds in combined build)", async ({
page,
}) => {
await open(page, 1);
const id = await runId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
const before = await page.evaluate(
(rid: string) => [
...(window as unknown as V2TestWindow).__v2_editor_store.doc
.page(1)
.runs.find((x) => x.id === rid)!.paragraphLeafPtrs,
],
id,
);
await page.evaluate((rid: string) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="v2-run-${rid}"]`,
)!;
el.focus();
const sel = window.getSelection()!;
const range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, " APPENDED");
}, id);
await page.waitForTimeout(150);
await page.evaluate(
(rid: string) =>
document
.querySelector<HTMLElement>(`[data-testid="v2-run-${rid}"]`)
?.blur(),
id,
);
await page.waitForTimeout(1200);
const after = await page.evaluate((rid: string) => {
const r = (window as unknown as V2TestWindow).__v2_editor_store.doc
.page(1)
.runs.find((x) => x.id === rid);
return r ? [...r.paragraphLeafPtrs] : [];
}, id);
const kept = before.filter((p: number) => after.includes(p)).length;
expect(
kept,
"most original glyph objects survive an append",
).toBeGreaterThan(before.length * 0.6);
const text = await runText(page, 1, id);
expect(text).toContain("APPENDED");
expect(text).not.toContain("ÿ");
});
test("image rotate-ccw changes the matrix and undo reverts", async ({
page,
}) => {
await open(page, 0);
const ins = await insertImage(page);
expect(ins).not.toBeNull();
await page.evaluate(
(iid: string) =>
(
window as unknown as V2TestWindow
).__v2_editor_store.selection.selectImage(iid),
ins!.id,
);
await page.waitForTimeout(120);
await clickImage(page, "v2-imgop-rotate-ccw");
await page.waitForTimeout(300);
const rotated = await imageMatrix(page, ins!.id);
expect(
Math.abs(rotated!.a) + Math.abs(rotated!.d),
"rotate moves scale off the main diagonal",
).toBeLessThan(Math.abs(rotated!.b) + Math.abs(rotated!.c) + 0.01);
await page.getByTestId("v2-undo").click();
await page.waitForTimeout(300);
const reverted = await imageMatrix(page, ins!.id);
expect(reverted!.a).toBeCloseTo(ins!.matrix.a, 1);
expect(reverted!.d).toBeCloseTo(ins!.matrix.d, 1);
});
test("image flip-v mirrors the vertical scale and undo reverts", async ({
page,
}) => {
await open(page, 0);
const ins = await insertImage(page);
expect(ins).not.toBeNull();
await page.evaluate(
(iid: string) =>
(
window as unknown as V2TestWindow
).__v2_editor_store.selection.selectImage(iid),
ins!.id,
);
await page.waitForTimeout(120);
await clickImage(page, "v2-imgop-flip-v");
await page.waitForTimeout(300);
const flipped = await imageMatrix(page, ins!.id);
expect(Math.sign(flipped!.d), "flip-v negates vertical scale").toBe(
-Math.sign(ins!.matrix.d || 1),
);
await page.getByTestId("v2-undo").click();
await page.waitForTimeout(300);
const reverted = await imageMatrix(page, ins!.id);
expect(reverted!.d).toBeCloseTo(ins!.matrix.d, 1);
});
test("rotating an image four times clockwise returns to the original matrix", async ({
page,
}) => {
await open(page, 0);
const ins = await insertImage(page);
expect(ins).not.toBeNull();
await page.evaluate(
(iid: string) =>
(
window as unknown as V2TestWindow
).__v2_editor_store.selection.selectImage(iid),
ins!.id,
);
await page.waitForTimeout(120);
for (let i = 0; i < 4; i++) {
await clickImage(page, "v2-imgop-rotate-cw");
await page.waitForTimeout(180);
}
const m = await imageMatrix(page, ins!.id);
expect(m!.a).toBeCloseTo(ins!.matrix.a, 1);
expect(m!.d).toBeCloseTo(ins!.matrix.d, 1);
expect(Math.abs(m!.b), "no residual shear after full turn").toBeLessThan(
0.01,
);
expect(Math.abs(m!.c), "no residual shear after full turn").toBeLessThan(
0.01,
);
});
test("locking an image makes it inert; unlocking restores selectability", async ({
page,
}) => {
await open(page, 0);
const ins = await insertImage(page);
expect(ins).not.toBeNull();
await page.evaluate(
(iid: string) =>
(
window as unknown as V2TestWindow
).__v2_editor_store.selection.selectImage(iid),
ins!.id,
);
await page.waitForTimeout(120);
await page.getByTestId("v2-toggle-lock").click();
await page.waitForTimeout(200);
const locked = await page.evaluate((iid: string) => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
for (const p of s.doc.loadedPages()) {
const im = p.images.find((x) => x.id === iid);
if (im) return im.locked;
}
return null;
}, ins!.id);
expect(locked, "image should be locked").toBe(true);
// Snapshot must refresh so the handle reflects the lock.
await expect(page.getByTestId(`v2-image-${ins!.id}`)).toHaveAttribute(
"data-locked",
"true",
);
// Clicking the locked image must not select it.
await page.evaluate(() =>
(window as unknown as V2TestWindow).__v2_editor_store.selection.clear(),
);
await page
.getByTestId(`v2-image-${ins!.id}`)
.click()
.catch(() => {});
await page.waitForTimeout(150);
const selImgs = await page.evaluate(
() =>
(window as unknown as V2TestWindow).__v2_editor_store.selection.value
.imageIds,
);
expect(
selImgs.includes(ins!.id),
"locked image not selectable by click",
).toBe(false);
// Unlock via store-selection (bypasses the inert UI) then toggle.
await page.evaluate(
(iid: string) =>
(
window as unknown as V2TestWindow
).__v2_editor_store.selection.selectImage(iid),
ins!.id,
);
await page.getByTestId("v2-toggle-lock").click();
await page.waitForTimeout(200);
await expect(page.getByTestId(`v2-image-${ins!.id}`)).not.toHaveAttribute(
"data-locked",
"true",
);
});
test("z-order: send-to-back is its own undo step and keeps the image", async ({
page,
}) => {
await open(page, 0);
const ins = await insertImage(page);
expect(ins).not.toBeNull();
await page.evaluate(
(iid: string) =>
(
window as unknown as V2TestWindow
).__v2_editor_store.selection.selectImage(iid),
ins!.id,
);
await page.waitForTimeout(120);
const undoBefore = await undoSize(page);
await clickArrange(page, "v2-z-to-back");
await page.waitForTimeout(300);
expect(await undoSize(page), "send-to-back is one undo step").toBe(
undoBefore + 1,
);
const imgs = await page.evaluate(() =>
(window as unknown as V2TestWindow).__v2_editor_store.doc
.loadedPages()
.reduce((n: number, p) => n + p.images.length, 0),
);
expect(imgs).toBeGreaterThan(0);
});
test("z-order: forward then backward each add an undoable step", async ({
page,
}) => {
await open(page, 0);
const ins = await insertImage(page);
expect(ins).not.toBeNull();
await page.evaluate(
(iid: string) =>
(
window as unknown as V2TestWindow
).__v2_editor_store.selection.selectImage(iid),
ins!.id,
);
await page.waitForTimeout(120);
const base = await undoSize(page);
await clickArrange(page, "v2-z-forward");
await page.waitForTimeout(250);
await clickArrange(page, "v2-z-backward");
await page.waitForTimeout(250);
expect(await undoSize(page), "two z-order steps recorded").toBe(base + 2);
await page.getByTestId("v2-undo").click();
await page.waitForTimeout(200);
expect(await undoSize(page)).toBe(base + 1);
});
test("align-right makes selected runs share the same right edge", async ({
page,
}) => {
await open(page, 1);
const a = await runId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
const b = await runId(page, 1, "Comprehensive\\s+toolkit");
await selectMany(page, [a, b]);
await clickArrange(page, "v2-align-right");
await page.waitForTimeout(300);
const rights = await page.evaluate(
({ a, b }: { a: string; b: string }) => {
const pg = (
window as unknown as V2TestWindow
).__v2_editor_store.doc.page(1);
const ra = pg.runs.find((x) => x.id === a)!;
const rb = pg.runs.find((x) => x.id === b)!;
return [ra.bounds.x + ra.bounds.width, rb.bounds.x + rb.bounds.width];
},
{ a, b },
);
expect(
Math.abs(rights[0] - rights[1]),
"aligned runs share a right edge",
).toBeLessThan(1.5);
});
test("align-top makes selected runs share the same top edge", async ({
page,
}) => {
await open(page, 1);
const a = await runId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
const b = await runId(page, 1, "Comprehensive\\s+toolkit");
await selectMany(page, [a, b]);
await clickArrange(page, "v2-align-top");
await page.waitForTimeout(300);
const tops = await page.evaluate(
({ a, b }: { a: string; b: string }) => {
const pg = (
window as unknown as V2TestWindow
).__v2_editor_store.doc.page(1);
const ra = pg.runs.find((x) => x.id === a)!;
const rb = pg.runs.find((x) => x.id === b)!;
return [ra.bounds.y + ra.bounds.height, rb.bounds.y + rb.bounds.height];
},
{ a, b },
);
expect(
Math.abs(tops[0] - tops[1]),
"aligned runs share a top edge",
).toBeLessThan(1.5);
});
test("distribute-v equalizes the vertical gaps across three runs", async ({
page,
}) => {
// Page text runs are stacked vertically (one per line/paragraph), so
// vertical distribution is the natural axis - they don't overlap on y,
// so the middle run stays between its neighbours and gaps equalize.
await open(page, 1);
const ids = await firstRunIds(page, 1, 3);
expect(ids.length, "need three runs to distribute").toBe(3);
await selectMany(page, ids);
await clickArrange(page, "v2-distribute-v");
await page.waitForTimeout(300);
const gaps = await page.evaluate((ids: string[]) => {
const pg = (window as unknown as V2TestWindow).__v2_editor_store.doc.page(
1,
);
const items = ids
.map((id) => pg.runs.find((r) => r.id === id)!)
.map((r) => ({ y: r.bounds.y, h: r.bounds.height }))
.sort((p, q) => p.y - q.y);
const g: number[] = [];
for (let i = 1; i < items.length; i++) {
g.push(items[i].y - (items[i - 1].y + items[i - 1].h));
}
return g;
}, ids);
expect(
Math.abs(gaps[0] - gaps[1]),
"consecutive gaps become equal",
).toBeLessThan(1.0);
});
test("change case Title Case transforms the selected run", async ({
page,
}) => {
await open(page, 1);
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
const orig = await runText(page, 1, id);
const expected = orig.replace(
/\b\w[\w']*/g,
(w) => w[0].toUpperCase() + w.slice(1).toLowerCase(),
);
await selectRun(page, id);
await page.getByTestId("v2-change-case").click();
await page.getByTestId("v2-change-case-title").click();
await page.waitForTimeout(400);
expect(await runText(page, 1, id)).toBe(expected);
});
test("change case Sentence case capitalizes after a lowercase pass", async ({
page,
}) => {
await open(page, 1);
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
const orig = await runText(page, 1, id);
await selectRun(page, id);
await page.getByTestId("v2-change-case").click();
await page.getByTestId("v2-change-case-lower").click();
await page.waitForTimeout(400);
await selectRun(page, id);
await page.getByTestId("v2-change-case").click();
await page.getByTestId("v2-change-case-sentence").click();
await page.waitForTimeout(400);
const expected = orig
.toLowerCase()
.replace(/(^\s*\w|[.!?]\s+\w)/g, (m) => m.toUpperCase());
expect(await runText(page, 1, id)).toBe(expected);
});
test("change case is undoable - undo restores the original text", async ({
page,
}) => {
await open(page, 1);
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
const orig = await runText(page, 1, id);
await selectRun(page, id);
await page.getByTestId("v2-change-case").click();
await page.getByTestId("v2-change-case-upper").click();
await page.waitForTimeout(400);
expect(await runText(page, 1, id)).toBe(orig.toUpperCase());
await page.getByTestId("v2-undo").click();
await page.waitForTimeout(400);
expect(await runText(page, 1, id)).toBe(orig);
});
test("duplicate (Ctrl+D) clones the selected run", async ({ page }) => {
await open(page, 1);
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
const before = await totalRuns(page);
await selectRun(page, id);
await page.evaluate(() =>
(document.activeElement as HTMLElement | null)?.blur(),
);
await page.keyboard.press("Control+d");
await page.waitForTimeout(300);
expect(await totalRuns(page), "duplicate adds one run").toBe(before + 1);
});
test("Delete key removes the selected run", async ({ page }) => {
await open(page, 1);
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
const before = await totalRuns(page);
await selectRun(page, id);
await page.evaluate(() =>
(document.activeElement as HTMLElement | null)?.blur(),
);
await page.keyboard.press("Delete");
await page.waitForTimeout(300);
expect(await totalRuns(page), "delete removes one run").toBe(before - 1);
expect(await runText(page, 1, id)).toBe("(gone)");
});
test("undo restores a locked run to unlocked + editable", async ({
page,
}) => {
await open(page, 1);
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
await selectRun(page, id);
await page.getByTestId("v2-toggle-lock").click();
await expect(page.getByTestId(`v2-run-${id}`)).toHaveAttribute(
"data-locked",
"true",
);
await page.getByTestId("v2-undo").click();
await page.waitForTimeout(250);
const locked = await page.evaluate(
(rid: string) =>
(window as unknown as V2TestWindow).__v2_editor_store.doc
.page(1)
.runs.find((x) => x.id === rid)!.locked,
id,
);
expect(locked, "undo unlocks the run").toBe(false);
await expect(page.getByTestId(`v2-run-${id}`)).toHaveAttribute(
"contenteditable",
"true",
);
});
test("find (Ctrl+F) reports a match count for an existing term", async ({
page,
}) => {
await open(page, 1);
await page.keyboard.press("Control+f");
await expect(page.getByTestId("v2-find-bar")).toBeVisible();
await page.getByTestId("v2-find-input").fill("PDF");
await page.waitForTimeout(400);
const count = await page.getByTestId("v2-find-count").innerText();
expect(count, "find reports N of M for a present term").toMatch(
/\d+ of \d+/,
);
});
test("replace swaps the matched run's text for the new term", async ({
page,
}) => {
await open(page, 1);
const before = await countRunsContaining(page, "toolkit");
expect(before, "fixture must contain the search term").toBeGreaterThan(0);
await page.keyboard.press("Control+f");
await expect(page.getByTestId("v2-find-bar")).toBeVisible();
await page.getByTestId("v2-find-input").fill("toolkit");
await page.waitForTimeout(400);
await page.getByTestId("v2-replace-input").fill("widget");
await page.getByTestId("v2-replace-one").click();
await page.waitForTimeout(600);
expect(
await countRunsContaining(page, "toolkit"),
"one match-run replaced",
).toBe(before - 1);
expect(
await countRunsContaining(page, "widget"),
"replacement text present",
).toBeGreaterThan(0);
});
test("replace all rewrites every matching run", async ({ page }) => {
await open(page, 1);
const before = await countRunsContaining(page, "pdf");
expect(before, "fixture must contain the search term").toBeGreaterThan(0);
await page.keyboard.press("Control+f");
await expect(page.getByTestId("v2-find-bar")).toBeVisible();
await page.getByTestId("v2-find-input").fill("PDF");
await page.waitForTimeout(400);
await page.getByTestId("v2-replace-input").fill("DOC");
await page.getByTestId("v2-replace-all").click();
await page.waitForTimeout(900);
expect(
await countRunsContaining(page, "pdf"),
"no matches remain after replace-all",
).toBe(0);
});
});
@@ -1,336 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import {
DisplayTransform,
type DisplayTransformData,
} from "@app/tools/pdfTextEditor/v2/model/DisplayTransform";
import path from "path";
/**
* Regression for the CropBox/rotation positioning bug (root-caused on
* spirit-sx-user-guide.pdf, which is NEVER committed). These use SYNTHETIC
* fixtures generated by generate-cropbox-fixtures.py:
*
* - cropbox-control.pdf : CropBox == MediaBox, /Rotate 0 (must be identity)
* - cropbox-offset.pdf : CropBox origin (50,30), 300x350 visible page
* - cropbox-rotate90.pdf : same crop + /Rotate 90 (displayed 350x300)
*
* The page object stores a DisplayTransform read from the real PDF's CropBox +
* rotation; the model stays in raw PDF (MediaBox) space; the overlay maps raw
* coords to the rendered (cropped/rotated) bitmap. Each fixture draws "Hi" at
* user-space baseline (60,350).
*/
interface Probe {
width: number;
height: number;
runCount: number;
matrixE: number;
matrixF: number;
boundsX: number;
display: DisplayTransformData;
}
async function load(
page: import("@playwright/test").Page,
name: string,
): Promise<Probe> {
await page.goto("/pdf-text-editor?charcodeStrategy=content-stream", {
waitUntil: "domcontentloaded",
});
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 30_000 });
await page
.locator('[data-testid="v2-file-input"]')
.setInputFiles(
path.join(import.meta.dirname, `../test-fixtures/${name}.pdf`),
);
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(800);
return page.evaluate(() => {
const s = (
window as unknown as {
__v2_editor_store: {
doc: {
page: (i: number) => {
width: number;
height: number;
runs: Array<{
bounds: { x: number };
matrix: { e: number; f: number };
}>;
display: Probe["display"];
};
};
};
}
).__v2_editor_store;
const pg = s.doc.page(0);
const r = pg.runs[0];
return {
width: pg.width,
height: pg.height,
runCount: pg.runs.length,
matrixE: r?.matrix.e,
matrixF: r?.matrix.f,
boundsX: r?.bounds.x,
display: pg.display,
};
}) as Promise<Probe>;
}
test("control fixture (CropBox==MediaBox) yields an identity transform", async ({
page,
}) => {
const p = await load(page, "cropbox-control");
expect(p.width).toBe(400);
expect(p.height).toBe(400);
expect(p.display.cropLeft).toBe(0);
expect(p.display.cropBottom).toBe(0);
expect(p.display.rotate).toBe(0);
const t = DisplayTransform.fromData(p.display);
expect(t.isIdentity).toBe(true);
// Model is raw; with identity the display position equals the raw position.
expect(t.apply(p.boundsX, p.matrixF)).toEqual({ x: p.boundsX, y: p.matrixF });
});
test("CropBox-offset fixture: page sized to CropBox, model raw, overlay offset", async ({
page,
}) => {
const p = await load(page, "cropbox-offset");
// page dims are the CropBox (visible) size, not the square MediaBox.
expect(p.width).toBe(300);
expect(p.height).toBe(350);
// The transform read the real PDF's CropBox origin.
expect(p.display.cropLeft).toBe(50);
expect(p.display.cropBottom).toBe(30);
expect(p.display.rotate).toBe(0);
// The MODEL stays in raw PDF (MediaBox) space - Td(60,350) baseline intact.
expect(p.matrixE).toBeCloseTo(60, 1);
expect(p.matrixF).toBeCloseTo(350, 1);
// The display anchor subtracts the CropBox origin: raw (~61.8,350) -> (~11.8,320).
const t = DisplayTransform.fromData(p.display);
const disp = t.apply(p.boundsX, p.matrixF);
expect(disp.x).toBeCloseTo(p.boundsX - 50, 3);
expect(disp.y).toBeCloseTo(320, 3);
// ...and the anchor now lands INSIDE the visible page (the bug put it past
// the right edge / above the top because the +50/-30 offset wasn't removed).
expect(disp.x).toBeGreaterThanOrEqual(0);
expect(disp.x).toBeLessThanOrEqual(p.width);
expect(disp.y).toBeGreaterThanOrEqual(0);
expect(disp.y).toBeLessThanOrEqual(p.height);
// Teeth: the un-transformed (pre-fix) x carried the +50 crop offset.
expect(p.boundsX).toBeGreaterThan(disp.x + 40);
});
test("CropBox + Rotate 90 fixture: dims swap, rotation in the transform, model raw", async ({
page,
}) => {
const p = await load(page, "cropbox-rotate90");
// /Rotate 90 swaps the displayed page dimensions.
expect(p.width).toBe(350);
expect(p.height).toBe(300);
expect(p.display.rotate).toBe(1);
expect(p.display.cropLeft).toBe(50);
expect(p.display.cropBottom).toBe(30);
// 90 CW affine is a proper rotation (det +1): a=0,b=-1,c=1,d=0.
expect([p.display.a, p.display.b, p.display.c, p.display.d]).toEqual([
0, -1, 1, 0,
]);
expect(
p.display.a * p.display.d - p.display.b * p.display.c,
"rotation must be det +1, not a reflection",
).toBeCloseTo(1, 9);
// Model still raw.
expect(p.matrixF).toBeCloseTo(350, 1);
// The display anchor lands inside the rotated visible page.
const t = DisplayTransform.fromData(p.display);
const disp = t.apply(p.boundsX, p.matrixF);
expect(disp.x).toBeGreaterThanOrEqual(0);
expect(disp.x).toBeLessThanOrEqual(p.width);
expect(disp.y).toBeGreaterThanOrEqual(0);
expect(disp.y).toBeLessThanOrEqual(p.height);
});
test("editing text on a Rotate-90 page applies cleanly and keeps placement in-bounds", async ({
page,
}) => {
// Editing happens in raw PDF space (commands are rotation-agnostic); the
// overlay maps the anchor through the rotation transform. Verify a real
// type-edit round-trips on a rotated page with no crash and in-bounds anchor.
const errs: string[] = [];
page.on("pageerror", (e) => errs.push(e.message));
await page.goto("/pdf-text-editor?charcodeStrategy=content-stream", {
waitUntil: "domcontentloaded",
});
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 30_000 });
await page
.locator('[data-testid="v2-file-input"]')
.setInputFiles(
path.join(import.meta.dirname, "../test-fixtures/cropbox-rotate90.pdf"),
);
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(800);
const id = await page.evaluate(() => {
const s = (
window as unknown as {
__v2_editor_store: {
doc: { page: (i: number) => { runs: Array<{ id: string }> } };
};
}
).__v2_editor_store;
return s.doc.page(0).runs[0]?.id ?? "";
});
expect(id).toMatch(/^p0-/);
await page.locator(`[data-testid="v2-run-${id}"]`).click();
await page.waitForTimeout(150);
await page.evaluate((rid) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="v2-run-${rid}"]`,
)!;
el.focus();
const sel = window.getSelection()!;
const range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, "Z");
}, id);
await page.waitForTimeout(150);
await page.evaluate(
(rid) =>
document
.querySelector<HTMLElement>(`[data-testid="v2-run-${rid}"]`)
?.blur(),
id,
);
await page.waitForTimeout(800);
const after = await page.evaluate(() => {
const s = (
window as unknown as {
__v2_editor_store: {
doc: {
page: (i: number) => {
width: number;
height: number;
runs: Array<{
id: string;
text: string;
bounds: { x: number };
matrix: { f: number };
}>;
display: {
a: number;
b: number;
c: number;
d: number;
e: number;
f: number;
};
};
};
};
}
).__v2_editor_store;
const pg = s.doc.page(0);
const r = pg.runs[0];
const d = pg.display;
return {
text: r.text,
width: pg.width,
height: pg.height,
dispX: d.a * r.bounds.x + d.c * r.matrix.f + d.e,
dispY: d.b * r.bounds.x + d.d * r.matrix.f + d.f,
};
});
expect(errs, `no page errors:\n${errs.join("\n")}`).toEqual([]);
expect(after.text).toContain("Z"); // edit applied
// Anchor still inside the rotated visible page (no off-page drift).
expect(after.dispX).toBeGreaterThanOrEqual(0);
expect(after.dispX).toBeLessThanOrEqual(after.width);
expect(after.dispY).toBeGreaterThanOrEqual(0);
expect(after.dispY).toBeLessThanOrEqual(after.height);
});
test("CropBox-offset: the rendered glyph pixels overlap the run overlay box", async ({
page,
}) => {
// End-to-end: the PDFium-rendered bitmap (CropBox-cropped) and the HTML
// overlay (positioned via the transform) must agree on where "Hi" sits.
await page.goto("/pdf-text-editor?charcodeStrategy=content-stream", {
waitUntil: "domcontentloaded",
});
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 30_000 });
await page
.locator('[data-testid="v2-file-input"]')
.setInputFiles(
path.join(import.meta.dirname, "../test-fixtures/cropbox-offset.pdf"),
);
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(1200);
const result = await page.evaluate(() => {
const pageEl = document.querySelector<HTMLElement>(
'[data-testid="v2-page-0"]',
)!;
const canvas = pageEl.querySelector("canvas")!;
const pageRect = pageEl.getBoundingClientRect();
const ctx = canvas.getContext("2d")!;
const img = ctx.getImageData(0, 0, canvas.width, canvas.height);
// Find the dark-pixel bounding box (the "Hi" glyphs) in canvas px.
let minX = Infinity,
minY = Infinity,
maxX = -Infinity,
maxY = -Infinity;
const { data, width, height } = img;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const o = (y * width + x) * 4;
const lum = (data[o] + data[o + 1] + data[o + 2]) / 3;
if (lum < 128 && data[o + 3] > 32) {
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
}
}
}
// Canvas is rendered at devicePixelRatio*scale; normalise to CSS px by the
// canvas's own client size.
const sx = canvas.clientWidth / canvas.width;
const sy = canvas.clientHeight / canvas.height;
const glyph = {
left: minX * sx,
top: minY * sy,
right: maxX * sx,
bottom: maxY * sy,
};
const overlay = document
.querySelector<HTMLElement>('[data-testid^="v2-run-"]')!
.getBoundingClientRect();
const ov = {
left: overlay.left - pageRect.left,
top: overlay.top - pageRect.top,
right: overlay.right - pageRect.left,
bottom: overlay.bottom - pageRect.top,
};
return { glyph, ov, found: maxX >= minX };
});
expect(result.found).toBe(true);
// The overlay box and the rendered-glyph box must overlap (loose: the
// overlay box is taller than the glyph ink, but they must not be disjoint -
// a pre-fix overlay would sit ~50px to the right and ~30px too high).
const overlaps =
result.ov.left <= result.glyph.right + 8 &&
result.ov.right >= result.glyph.left - 8 &&
result.ov.top <= result.glyph.bottom + 12 &&
result.ov.bottom >= result.glyph.top - 12;
expect(
overlaps,
`overlay ${JSON.stringify(result.ov)} must overlap glyph ${JSON.stringify(result.glyph)}`,
).toBe(true);
});
@@ -1,80 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page, Route } from "@playwright/test";
import path from "path";
import type { V2TestWindow } from "@app/tests/stubbed/v2EditorTestTypes";
/**
* Cross-font charcode disambiguation (H1H2/U).
*
* The backend encode-charcodes endpoint now accepts a `fontName` so a page with
* two fonts rendering the same char encodes against the RIGHT one. This test
* mocks the endpoint and asserts the frontend reads the run's /BaseFont name
* (FPDFFont_GetBaseFontName) and sends it - the wiring that makes the backend
* disambiguation reachable. The backend half is covered by the Java unit test
* (fontNameDisambiguatesBetweenTwoFontsRenderingTheSameChar).
*/
const SUBSET = path.join(
import.meta.dirname,
"../test-fixtures/subset-font-sample.pdf",
);
test("editor sends the run's font name to encode-charcodes", async ({
page,
}: {
page: Page;
}) => {
test.setTimeout(90_000);
const bodies: Array<Record<string, unknown>> = [];
await page.route("**/encode-charcodes", async (route: Route) => {
try {
bodies.push(route.request().postDataJSON() as Record<string, unknown>);
} catch {
/* ignore non-JSON */
}
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ charcodes: [65], missing: [], note: "stub" }),
});
});
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 20_000 });
await page.locator('[data-testid="v2-file-input"]').setInputFiles(SUBSET);
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(800);
// Edit a run - the cache-miss prefetch (and focus prewarm) POST to the
// endpoint, now carrying the resolved font's name.
const id = await page.evaluate(() => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
return s.doc.page(0).runs[0]?.id ?? null;
});
expect(id, "page 0 has a run").toBeTruthy();
await page.evaluate((rid: string) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="v2-run-${rid}"]`,
)!;
el.focus();
const sel = window.getSelection()!;
const range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, "s");
}, id as string);
await page.waitForTimeout(1500);
expect(bodies.length, "endpoint was called").toBeGreaterThan(0);
const named = bodies.filter(
(b) => typeof b.fontName === "string" && (b.fontName as string).length > 0,
);
expect(
named.length,
`at least one request carries a non-empty fontName; bodies=${JSON.stringify(
bodies.map((b) => b.fontName),
)}`,
).toBeGreaterThan(0);
});
@@ -1,59 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page, Route } from "@playwright/test";
import path from "path";
/**
* End-to-end coverage for the fonts panel's client-side glyph-coverage probe.
*
* The document loader primes each embedded font's cmap into a cache during its
* SERIALIZED text-read phase (reading font data at render time corrupts PDFium
* - that path is deliberately avoided). The panel then reports, per font, which
* of a-z A-Z 0-9 the font actually has glyphs for, with zero render-time WASM.
*
* subset-font-sample.pdf embeds a TrueType subset whose cmap omits most
* alphanumerics, so the panel must surface concrete "Missing: ..." chars and a
* yellow summary - all without backend help (encode-charcodes is aborted).
*/
const SUBSET = path.join(
import.meta.dirname,
"../test-fixtures/subset-font-sample.pdf",
);
async function open(page: Page, file: string): Promise<void> {
await page.route("**/encode-charcodes", (route: Route) => route.abort());
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 20_000 });
await page.locator('[data-testid="v2-file-input"]').setInputFiles(file);
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(1500);
}
test("fonts panel reports concrete a-zA-Z0-9 coverage gaps client-side", async ({
page,
}) => {
test.setTimeout(90_000);
const errs: string[] = [];
page.on("pageerror", (e) => errs.push(e.message));
await open(page, SUBSET);
// The editor must still render (the canvas page) - reading font data at load
// must not corrupt PDFium.
await expect(page.getByTestId("v2-page-0")).toBeVisible();
const panel = page.getByTestId("v2-fonts-panel");
await expect(panel).toBeVisible();
// A subset TrueType font with a parseable cmap => concrete missing chars.
const missing = panel.getByTestId("v2-font-missing").first();
await expect(missing).toBeVisible();
await expect(missing).toContainText(/Missing:/);
// ...and the summary escalates to the yellow "warn" tone accordingly.
await expect(panel.getByTestId("v2-font-compat")).toHaveAttribute(
"data-compat",
"warn",
);
expect(errs, `no page errors:\n${errs.join("\n")}`).toEqual([]);
});
@@ -1,54 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page, Route } from "@playwright/test";
import path from "path";
/**
* Inserting a JPEG embeds the original JPEG stream (DCTDecode) instead of
* re-encoding decoded RGBA pixels (FlateDecode), so the output stays small
* (finding R). Verified by scanning the saved PDF for the DCTDecode filter.
*/
const SAMPLE_PDF = path.join(
import.meta.dirname,
"../test-fixtures/sample.pdf",
);
const SAMPLE_JPG = path.join(
import.meta.dirname,
"../test-fixtures/sample.jpg",
);
test("inserting a JPEG embeds it as DCTDecode, not re-encoded RGBA", async ({
page,
}: {
page: Page;
}) => {
test.setTimeout(90_000);
await page.route("**/encode-charcodes", (route: Route) => route.abort());
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 20_000 });
await page.locator('[data-testid="v2-file-input"]').setInputFiles(SAMPLE_PDF);
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(500);
// Insert the JPEG via the editor's image input.
await page
.locator('[data-testid="v2-image-input"]')
.setInputFiles(SAMPLE_JPG);
await page.waitForTimeout(1500);
// Save and scan the bytes for the JPEG (DCTDecode) filter.
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("v2-save").click();
const dl = await downloadPromise;
const stream = await dl.createReadStream();
const chunks: Buffer[] = [];
for await (const c of stream) chunks.push(c as Buffer);
const saved = Buffer.concat(chunks);
const asText = saved.toString("latin1");
expect(saved.subarray(0, 4).toString("ascii")).toBe("%PDF");
expect(
asText.includes("DCTDecode"),
"saved PDF embeds the JPEG as DCTDecode (passthrough)",
).toBe(true);
});
@@ -1,560 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page } from "@playwright/test";
import path from "path";
import type { V2TestWindow } from "@app/tests/stubbed/v2EditorTestTypes";
/**
* REGRESSION suite for the 12 issues found by the QA sweep of the v2 PDF text
* editor - all since fixed. Each test asserts the desired behaviour and must
* pass. They were previously `test.fail()` placeholders documenting the bugs;
* the markers were removed as each fix landed.
*
* Scenarios are weighted to the shipped marketing Sample.pdf (Type3,
* per-glyph fonts) because that is what users actually load.
*/
const SAMPLE = path.join(
import.meta.dirname,
"../../../../public/samples/Sample.pdf",
);
const SUBSET = path.join(
import.meta.dirname,
"../test-fixtures/subset-font-sample.pdf",
);
async function open(page: Page, file: string, firstPage = 0): Promise<void> {
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 15_000 });
await page.locator('[data-testid="v2-file-input"]').setInputFiles(file);
await expect(page.getByTestId(`v2-page-${firstPage}`)).toBeVisible({
timeout: 30_000,
});
await page.waitForTimeout(900);
}
async function findId(
page: Page,
pageIdx: number,
src: string,
): Promise<string> {
const id = await page.evaluate(
({ pageIdx, src }: { pageIdx: number; src: string }) => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
const r = s.doc
.page(pageIdx)
.runs.find((x) => new RegExp(src).test(x.text));
return r ? r.id : null;
},
{ pageIdx, src },
);
if (!id) throw new Error(`run /${src}/ not found on page ${pageIdx}`);
return id;
}
async function leafPtrs(
page: Page,
pageIdx: number,
id: string,
): Promise<number[]> {
return page.evaluate(
({ pageIdx, id }: { pageIdx: number; id: string }) => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
const r = s.doc.page(pageIdx).runs.find((x) => x.id === id);
return r ? [...r.paragraphLeafPtrs] : [];
},
{ pageIdx, id },
);
}
async function caretEndInsert(
page: Page,
id: string,
text: string,
): Promise<void> {
await page.evaluate(
({ id, text }: { id: string; text: string }) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="v2-run-${id}"]`,
)!;
el.focus();
const sel = window.getSelection()!;
const range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, text);
},
{ id, text },
);
await page.waitForTimeout(150);
}
async function replaceAll(page: Page, id: string, full: string): Promise<void> {
await page.evaluate(
({ id, full }: { id: string; full: string }) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="v2-run-${id}"]`,
)!;
el.focus();
const sel = window.getSelection()!;
const range = document.createRange();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, full);
},
{ id, full },
);
await page.waitForTimeout(200);
}
async function blur(page: Page, id: string): Promise<void> {
await page.evaluate((rid: string) => {
document
.querySelector<HTMLElement>(`[data-testid="v2-run-${rid}"]`)
?.blur();
}, id);
await page.waitForTimeout(1200);
}
/** Per-glyph geometry + extracted text for a run, straight from PDFium. */
async function glyphs(
page: Page,
pageIdx: number,
id: string,
): Promise<{
boundsRight: number;
pageWidth: number;
fontId: string;
text: string;
maxGap: number;
hasYdieresis: boolean;
}> {
return page.evaluate(
({ pageIdx, id }: { pageIdx: number; id: string }) => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
const m = s.doc.module;
const pg = s.doc.page(pageIdx);
pg.flushGenerate(m);
const r = pg.runs.find((x) => x.id === id)!;
const ptrs: number[] = r.paragraphLeafPtrs.length
? r.paragraphLeafPtrs
: r.mergedFromPtrs.length
? r.mergedFromPtrs
: [r.pdfiumObjPtr];
const tp = m.FPDFText_LoadPage(pg.pagePtr);
const seg: Array<{ x: number; right: number; base: number }> = [];
let hasY = false;
try {
for (const ptr of ptrs) {
if (!ptr) continue;
const l = m.pdfium.wasmExports.malloc(4);
const b = m.pdfium.wasmExports.malloc(4);
const rr = m.pdfium.wasmExports.malloc(4);
const t = m.pdfium.wasmExports.malloc(4);
const mat = m.pdfium.wasmExports.malloc(24);
try {
if (!m.FPDFPageObj_GetBounds(ptr, l, b, rr, t)) continue;
let base = m.pdfium.getValue(b, "float");
if (m.FPDFPageObj_GetMatrix(ptr, mat))
base = m.pdfium.getValue(mat + 20, "float");
seg.push({
x: m.pdfium.getValue(l, "float"),
right: m.pdfium.getValue(rr, "float"),
base: Math.round(base),
});
const len = m.FPDFTextObj_GetText(ptr, tp, 0, 0);
if (len > 2) {
const buf = m.pdfium.wasmExports.malloc(len);
try {
m.FPDFTextObj_GetText(ptr, tp, buf, len);
let str = "";
for (let o = 0; o < len - 2; o += 2)
str += String.fromCharCode(m.pdfium.getValue(buf + o, "i16"));
if (str.includes("ÿ")) hasY = true;
} finally {
m.pdfium.wasmExports.free(buf);
}
}
} finally {
m.pdfium.wasmExports.free(l);
m.pdfium.wasmExports.free(b);
m.pdfium.wasmExports.free(rr);
m.pdfium.wasmExports.free(t);
m.pdfium.wasmExports.free(mat);
}
}
} finally {
m.FPDFText_ClosePage(tp);
}
// Largest gap between consecutive glyphs on the TOP line.
const top = seg.length ? Math.max(...seg.map((g) => g.base)) : 0;
const line = seg
.filter((g) => Math.abs(g.base - top) <= 2)
.sort((a, b) => a.x - b.x);
let maxGap = 0;
for (let i = 1; i < line.length; i++) {
maxGap = Math.max(maxGap, line[i].x - line[i - 1].right);
}
return {
boundsRight: r.bounds.x + r.bounds.width,
pageWidth: pg.width,
fontId: r.fontId as string,
text: (r.text as string) ?? "",
maxGap,
hasYdieresis: hasY,
};
},
{ pageIdx, id },
);
}
test.describe("v2 editor - fixed-issue regressions", () => {
// ISSUE: a single-line run grows past the right page edge when you type a
// long string - the overflow is clipped/lost in the saved PDF instead of
// wrapping or being clamped to the page.
test("typing a long string into a single-line run stays on the page", async ({
page,
}) => {
await open(page, SAMPLE, 0);
const id = await findId(page, 0, "Adobe.*Acrobat.*Alternative");
await caretEndInsert(
page,
id,
" plus a very long appended tail that keeps going and going and going",
);
await blur(page, id);
const g = await glyphs(page, 0, id);
expect(
g.boundsRight,
"run must not extend past the page width",
).toBeLessThanOrEqual(g.pageWidth + 2);
});
// ISSUE: typing non-Latin text (CJK / emoji) into a paragraph re-emits the
// WHOLE paragraph (surrogate guard bails), so every original line loses its
// source font objects.
test("typing non-Latin text keeps the paragraph's other lines' objects", async ({
page,
}) => {
await open(page, SAMPLE, 1);
const id = await findId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
const before = await leafPtrs(page, 1, id);
await caretEndInsert(page, id, " 日本語 🎉");
await blur(page, id);
const after = await leafPtrs(page, 1, id);
const kept = before.filter((p) => after.includes(p)).length;
expect(
kept,
"unedited lines must keep their objects when non-Latin text is added",
).toBe(before.length);
});
// ISSUE: non-Latin glyphs render as U+00FF (ydieresis "ÿ") tofu because the
// base-14 fallback font has no glyph for them.
test("typing non-Latin text does not render as ydieresis tofu", async ({
page,
}) => {
await open(page, SAMPLE, 1);
const id = await findId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
await caretEndInsert(page, id, " 日本語");
await blur(page, id);
const g = await glyphs(page, 1, id);
expect(g.hasYdieresis, "CJK must not be replaced by 'ÿ' tofu glyphs").toBe(
false,
);
});
// ISSUE: typing an emoji (astral / surrogate-pair char) then saving must
// round-trip the FULL surrogate pair - a code-unit-level edit could split it
// and leave a lone surrogate, and the base-14 fallback must not render it as
// U+00FF ("ÿ") tofu. Exercises the surrogate path through a save+reopen.
test("typing an emoji round-trips without a lone surrogate or U+00FF tofu", async ({
page,
}) => {
test.setTimeout(120_000);
await open(page, SAMPLE, 1);
const id = await findId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
await caretEndInsert(page, id, " 🎉");
await blur(page, id);
// Save, then reopen the produced bytes.
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("v2-save").click();
const dl = await downloadPromise;
const stream = await dl.createReadStream();
const chunks: Buffer[] = [];
for await (const c of stream) chunks.push(c as Buffer);
const saved = Buffer.concat(chunks);
await page.locator('[data-testid="v2-file-input"]').setInputFiles({
name: "emoji-round-trip.pdf",
mimeType: "application/pdf",
buffer: saved,
});
await expect(
page.locator('[data-testid^="v2-run-p1-"]').first(),
).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(500);
const reopened = await page.evaluate(() => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
return s.doc
.page(1)
.runs.map((r) => r.text)
.join("");
});
// No lone high surrogate (one not immediately followed by a low surrogate).
expect(
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(reopened),
"saved model must not contain a lone surrogate",
).toBe(false);
expect(
reopened.includes("ÿ"),
"emoji must not be replaced by 'ÿ' tofu",
).toBe(false);
});
// NOTE: two more issues are VISUALLY confirmed (see __qa screenshots) but
// omitted here because a stable automated assertion is hard:
// - replacing a long Type3 run with a short string leaves the surviving
// glyphs spread out ("He llo Wo r ld") - kept glyphs are not re-flowed.
// - deleting a word from a Type3 line leaves an internal gap
// ("The Free Adobe Acrob at" after removing "Alternative").
// ISSUE: deleting the LEADING word of a paragraph line injects a stray
// U+00FF ("ÿ") into the model text.
test("deleting the leading word does not inject a U+00FF artifact", async ({
page,
}) => {
await open(page, SAMPLE, 1);
const id = await findId(page, 1, "Comprehensive\\s+toolkit");
const cur = await page.evaluate(
(rid: string) =>
(window as unknown as V2TestWindow).__v2_editor_store.doc
.page(1)
.runs.find((x) => x.id === rid)!.text as string,
id,
);
await replaceAll(page, id, cur.replace(/^Comprehensive/, ""));
await blur(page, id);
const g = await glyphs(page, 1, id);
expect(g.text.includes("ÿ"), "model text must not contain 'ÿ'").toBe(false);
});
// ISSUE: deleting a single character from the MIDDLE of a Type3 word leaves
// a spurious space at the deletion point ("Comprehensive" -> "Compre ensive"
// after removing the 'h') - the surviving glyphs are not re-flowed together.
test("deleting a mid-word character does not inject a spurious space", async ({
page,
}) => {
await open(page, SAMPLE, 1);
const id = await findId(page, 1, "Comprehensive\\s+toolkit");
const cur = await page.evaluate(
(rid: string) =>
(window as unknown as V2TestWindow).__v2_editor_store.doc
.page(1)
.runs.find((x) => x.id === rid)!.text as string,
id,
);
// drop the 'h' from "Comprehensive" -> the word should read "Compreensive"
await replaceAll(page, id, cur.replace("Comprehensive", "Compreensive"));
await blur(page, id);
const g = await glyphs(page, 1, id);
expect(
g.text.includes("Compre ensive"),
"mid-word delete must not split the word with a space",
).toBe(false);
});
// ISSUE: inserting an image through the toolbar picker (the v2-image-input
// file input) does not add an image to the page - the count stays the same.
// createImageBitmap works headless (verified), so this is a real no-op, not
// an environment limitation.
test("inserting an image via the picker adds an image to the page", async ({
page,
}) => {
await open(page, SAMPLE, 0);
const countImages = () =>
page.evaluate(() => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
return s.doc
.loadedPages()
.reduce((n: number, p) => n + p.images.length, 0);
});
const before = await countImages();
// a 1x1 red PNG, decoded in-browser by handleInsertImage
const png = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
"base64",
);
await page.locator('[data-testid="v2-image-input"]').setInputFiles({
name: "dot.png",
mimeType: "image/png",
buffer: png,
});
await page.waitForTimeout(1800);
const after = await countImages();
expect(after, "image insert must add an image to the page").toBeGreaterThan(
before,
);
});
// ISSUE: injecting several consecutive spaces into a multi-line paragraph
// collapses them - the paragraph-edit/overlay path re-derives spacing from
// glyph geometry, so "Stirling PDF" (5 spaces) lands in the model with
// fewer spaces and the saved PDF loses the intended gap. (A short single-line
// replace preserves them, so this is specific to the multi-line path.)
test("injecting consecutive spaces into a paragraph preserves them", async ({
page,
}) => {
await open(page, SAMPLE, 1);
const id = await findId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
const cur = await page.evaluate(
(rid: string) =>
(window as unknown as V2TestWindow).__v2_editor_store.doc
.page(1)
.runs.find((x) => x.id === rid)!.text as string,
id,
);
await replaceAll(
page,
id,
cur.replace(/Stirling\s+PDF/, "Stirling PDF"),
);
await blur(page, id);
const g = await glyphs(page, 1, id);
expect(
/Stirling {5}PDF/.test(g.text),
"five consecutive injected spaces must survive into the model",
).toBe(true);
});
// ISSUE: redo after undo-all does NOT reproduce the text the original edit
// produced. A simple append to a Type3 paragraph keeps the source glyphs on
// first apply, but redo re-emits the whole paragraph through the overlay path
// (collapsing the Type3 double-space extraction), so redone != edited.
test("redo after undo-all reproduces the originally edited text", async ({
page,
}) => {
await open(page, SAMPLE, 1);
const id = await findId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
const get = (): Promise<string> =>
page.evaluate((r: string) => {
const x = (window as unknown as V2TestWindow).__v2_editor_store.doc
.page(1)
.runs.find((y) => y.id === r);
return x ? (x.text as string) : "(gone)";
}, id);
await caretEndInsert(page, id, " UNIQ");
await blur(page, id);
const edited = await get();
await page.evaluate(() =>
(window as unknown as V2TestWindow).__v2_editor_store.resetAll(),
);
await page.waitForTimeout(400);
// Redo until the button is disabled. The edit + its auto-reflow coalesce
// into ONE undo/redo step, so this is typically a single click - clicking
// a disabled button would hang, so stop once redo is exhausted.
for (let i = 0; i < 6; i++) {
const redoBtn = page.getByTestId("v2-redo");
if (await redoBtn.isDisabled()) break;
await redoBtn.click();
await page.waitForTimeout(120);
}
const redone = await get();
expect(
redone,
"redo must reproduce the exact text the original edit produced",
).toBe(edited);
});
// ISSUE / LIMITATION: editing embedded / subset / form-xobject text used to
// re-font the run to base-14 Helvetica even when the edit only adds chars the
// subset already embeds. Appending chars present in the source ("test", all
// of which appear in "Subset font sample") must keep the subset font - the
// reuse is safe because those glyphs are proven present, and emitTextLine
// falls back to base-14 only if a reused glyph fails to render.
test("editing a subset-font run keeps a non-base-14 font", async ({
page,
}) => {
await open(page, SUBSET, 0);
const id = await findId(page, 0, "Subset font sample");
await caretEndInsert(page, id, "test");
await blur(page, id);
const g = await glyphs(page, 0, id);
expect(
g.fontId.startsWith("base14:"),
"subset edit flips to Helvetica",
).toBe(false);
});
// ISSUE / UX: a single Enter-then-type produces several `input` events, so
// several undo steps are needed to revert one logical edit. One undo should
// suffice.
test("one undo reverts a single Enter+type action", async ({ page }) => {
await open(page, SAMPLE, 1);
const id = await findId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
const before = await page.evaluate(
(rid: string) =>
(window as unknown as V2TestWindow).__v2_editor_store.doc
.page(1)
.runs.find((x) => x.id === rid)!.text as string,
id,
);
await caretEndInsert(page, id, "\n");
await caretEndInsert(page, id, "Z");
await page.getByTestId("v2-undo").click();
// Poll for the revert rather than a fixed wait - the undo's store update can
// lag the click under load, which made a single fixed timeout flaky.
await expect
.poll(
() =>
page.evaluate(
(rid: string) =>
((window as unknown as V2TestWindow).__v2_editor_store.doc
.page(1)
.runs.find((x) => x.id === rid)?.text ?? null) as string | null,
id,
),
{ timeout: 6000, message: "one undo should fully revert Enter+type" },
)
.toBe(before);
});
// ISSUE: opening an ENCRYPTED PDF fails silently - the editor shows "No
// document loaded" with no error message and no password prompt. It now
// prompts for the password (client-side decrypt) instead of dead-ending.
test("opening an encrypted PDF surfaces an error or password prompt", async ({
page,
}) => {
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 15_000 });
await page
.locator('[data-testid="v2-file-input"]')
.setInputFiles(
path.join(import.meta.dirname, "../test-fixtures/encrypted.pdf"),
);
await page.waitForTimeout(2500);
const loaded = await page.getByTestId("v2-page-0").count();
const error = await page.getByTestId("v2-error").count();
const prompt = await page.getByTestId("v2-password-modal").count();
expect(
loaded > 0 || error > 0 || prompt > 0,
"an encrypted PDF must either open or tell the user why it can't",
).toBe(true);
});
// ISSUE: opening a CORRUPTED PDF fails silently - same "No document loaded"
// with no error feedback.
test("opening a corrupted PDF surfaces an error", async ({ page }) => {
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 15_000 });
await page
.locator('[data-testid="v2-file-input"]')
.setInputFiles(
path.join(import.meta.dirname, "../test-fixtures/corrupted.pdf"),
);
await page.waitForTimeout(2500);
const loaded = await page.getByTestId("v2-page-0").count();
const error = await page.getByTestId("v2-error").count();
expect(
loaded > 0 || error > 0,
"a corrupted PDF must surface an error instead of failing silently",
).toBe(true);
});
});
@@ -1,201 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page } from "@playwright/test";
import path from "path";
import type { V2TestWindow } from "@app/tests/stubbed/v2EditorTestTypes";
/**
* UI-layout coverage for the menu-grouped editor chrome:
* - the toolbar holds the per-selection controls, with z-order / align /
* distribute collapsed under an "Arrange" menu and rotate/flip under an
* "Image" menu (icon-only lock + delete);
* - the sidebar holds the general editor tools (Insert, Paragraph, Editor
* settings) - NOT in the toolbar;
* - the slim app top bar holds only chrome (zoom / save / help).
*/
const SAMPLE = path.join(
import.meta.dirname,
"../../../../public/samples/Sample.pdf",
);
async function open(page: Page, firstPage = 0): Promise<void> {
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 15_000 });
await page.locator('[data-testid="v2-file-input"]').setInputFiles(SAMPLE);
await expect(page.getByTestId(`v2-page-${firstPage}`)).toBeVisible({
timeout: 30_000,
});
await page.waitForTimeout(900);
}
async function runId(
page: Page,
pageIdx: number,
src: string,
): Promise<string> {
const id = await page.evaluate(
({ pageIdx, src }: { pageIdx: number; src: string }) => {
const r = (window as unknown as V2TestWindow).__v2_editor_store.doc
.page(pageIdx)
.runs.find((x) => new RegExp(src).test(x.text));
return r ? r.id : null;
},
{ pageIdx, src },
);
if (!id) throw new Error(`run /${src}/ not found`);
return id;
}
async function selectOne(page: Page, id: string): Promise<void> {
await page.evaluate(
(rid: string) =>
(window as unknown as V2TestWindow).__v2_editor_store.selection.selectOne(
rid,
),
id,
);
await page.waitForTimeout(150);
}
test.describe("v2 editor - menu-grouped layout", () => {
test("Arrange menu groups z-order, align and distribute with correct gating", async ({
page,
}) => {
await open(page, 0);
// A single single-line run: z-order is always available, align needs
// 2+ objects and distribute needs 3+, so both are gated off here.
const id = await runId(page, 0, "Downloads");
await selectOne(page, id);
const arrange = page.getByTestId("v2-arrange-menu");
await expect(arrange).toBeVisible();
await expect(arrange).toBeEnabled();
// The Arrange control belongs to the toolbar, not the sidebar.
await expect(
page.getByTestId("v2-toolbar").getByTestId("v2-arrange-menu"),
).toHaveCount(1);
await arrange.click();
// Sub-section labels make the grouping explicit.
await expect(page.getByText("Align · needs 2+ objects")).toBeVisible();
await expect(page.getByText("Distribute · needs 3+ objects")).toBeVisible();
// Z-order works on a single object; align/distribute are disabled.
await expect(page.getByTestId("v2-z-to-front")).toBeEnabled();
await expect(page.getByTestId("v2-align-left")).toBeDisabled();
await expect(page.getByTestId("v2-distribute-h")).toBeDisabled();
await page.keyboard.press("Escape");
});
test("Image menu opens with rotate/flip gated off while a text run is selected", async ({
page,
}) => {
await open(page, 0);
const id = await runId(page, 0, "Downloads");
await selectOne(page, id);
// Enabled because something is selected, but the transforms are disabled
// and an in-dropdown label explains why (reachable, unlike a tooltip on a
// disabled button).
await expect(page.getByTestId("v2-imgop-menu")).toBeEnabled();
await page.getByTestId("v2-imgop-menu").click();
await expect(page.getByText("Select an image first")).toBeVisible();
await expect(page.getByTestId("v2-imgop-rotate-cw")).toBeDisabled();
await page.getByTestId("v2-zoom-percent").click();
});
test("Arrange and Image menus are disabled with nothing selected", async ({
page,
}) => {
await open(page, 0);
// On load no object is selected, so both selection-scoped menus are off.
await expect(page.getByTestId("v2-arrange-menu")).toBeDisabled();
await expect(page.getByTestId("v2-imgop-menu")).toBeDisabled();
});
test("lock and delete are icon buttons in the toolbar", async ({ page }) => {
await open(page, 0);
const id = await runId(page, 0, "Downloads");
await selectOne(page, id);
const toolbar = page.getByTestId("v2-toolbar");
// Icon-only: identified by aria-label, located inside the toolbar.
await expect(toolbar.getByTestId("v2-toggle-lock")).toBeVisible();
await expect(toolbar.getByTestId("v2-delete")).toBeVisible();
await expect(page.getByTestId("v2-toggle-lock")).toHaveAttribute(
"aria-label",
/lock selection/i,
);
});
test("general tools live in the sidebar, not the toolbar", async ({
page,
}) => {
await open(page, 0);
const sidebar = page.getByTestId("v2-sidebar-status");
// Insert + Paragraph + Editor-settings controls are in the sidebar.
for (const id of [
"v2-add-text",
"v2-add-image",
"v2-group",
"v2-ungroup",
"v2-grouping-mode-control",
"v2-width-mode-control",
]) {
await expect(sidebar.getByTestId(id)).toBeVisible();
}
// ...and they are NOT duplicated in the toolbar.
const toolbar = page.getByTestId("v2-toolbar");
for (const id of ["v2-add-text", "v2-add-image", "v2-group"]) {
await expect(toolbar.getByTestId(id)).toHaveCount(0);
}
});
test("app top bar holds only chrome (no insert/group controls)", async ({
page,
}) => {
await open(page, 0);
// Zoom / save / help remain; insert + paragraph actions moved out.
await expect(page.getByTestId("v2-save")).toBeVisible();
await expect(page.getByTestId("v2-zoom-percent")).toBeVisible();
await expect(page.getByTestId("v2-help")).toBeVisible();
});
test("Add text toggles its label and inserts from the sidebar", async ({
page,
}) => {
await open(page, 0);
const runs = page.locator('[data-testid^="v2-run-p0-"]');
const before = await runs.count();
const addText = page.getByTestId("v2-add-text");
await addText.click();
await expect(addText).toContainText(/click page to add text/i);
await page.getByTestId("v2-page-0").click({ position: { x: 200, y: 400 } });
await expect(runs).toHaveCount(before + 1, { timeout: 5_000 });
await expect(addText).toHaveText("Add text");
});
test("sidebar lists the page fonts with a status badge", async ({ page }) => {
await open(page, 0);
const panel = page.getByTestId("v2-fonts-panel");
await expect(panel).toBeVisible();
await expect(panel.getByText("Fonts", { exact: true })).toBeVisible();
// At least one font row with a status badge (standard / embedded / subset).
const badges = panel.locator('[data-testid^="v2-font-"]');
expect(await badges.count()).toBeGreaterThan(0);
});
test("fonts panel shows a compatibility summary and an info explainer", async ({
page,
}) => {
await open(page, 0);
const panel = page.getByTestId("v2-fonts-panel");
// The summary banner is present and carries an honest tone (ok / info /
// warn) - never claiming a blanket "no issues" for embedded fonts.
const compat = panel.getByTestId("v2-font-compat");
await expect(compat).toBeVisible();
const tone = await compat.getAttribute("data-compat");
expect(["ok", "info", "warn"]).toContain(tone);
// The (i) explainer is present and reveals the existing-vs-new guidance.
const info = panel.getByTestId("v2-fonts-info");
await expect(info).toBeVisible();
await info.hover();
await expect(page.getByText(/New characters/i).first()).toBeVisible();
});
});
@@ -1,118 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Route } from "@playwright/test";
import path from "path";
import type { V2TestWindow } from "@app/tests/stubbed/v2EditorTestTypes";
/**
* Regression for the mushroom-life.pdf "paragraph scramble" report.
*
* Body lines in this PDF are each ONE PDFium text object in a NON-SUBSET
* LMRoman font. A mid-line edit forces the whole line to be re-emitted
* (planParagraphEdit nulls the slot plan to avoid SetText-ing whitespace).
* With a cold/offline backend the emit path used to fall back to the
* client-side content-stream resolver, which GUESSES each glyph's charcode
* by its sequential order on the page - correct for many subset fonts but
* WRONG for this re-encoded font. The wrong-but-valid glyphs (e.g.
* "occupying" -> "Λffff´`ˇΘΞΩ", "a" -> "fi") passed the advance self-check
* and scrambled every unchanged word on the edited line.
*
* The fix gates the content-stream guess to SUBSET fonts + SINGLE code
* points. A non-subset font now re-emits via FPDFText_SetText (whose reverse
* Unicode->charcode lookup is correct for non-subset fonts), so the line's
* unchanged words keep their real glyphs - readable, font preserved.
*/
const MUSHROOM = path.join(
import.meta.dirname,
"../test-fixtures/mushroom-life.pdf",
);
test("mid-line paragraph edit does not scramble unchanged words (cold backend, non-subset font)", async ({
page,
}) => {
test.setTimeout(120_000);
// Offline backend: every encode-charcodes call fails, so the emit path hits
// the cold-cache fallback - the exact condition that used to scramble.
await page.route("**/encode-charcodes", (route: Route) => route.abort());
const errs: string[] = [];
page.on("pageerror", (e) => errs.push(e.message));
await page.goto("/pdf-text-editor?charcodeStrategy=backend", {
waitUntil: "domcontentloaded",
});
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 30_000 });
await page.locator('[data-testid="v2-file-input"]').setInputFiles(MUSHROOM);
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(1200);
const probe = () =>
page.evaluate(() => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
const pg = s.doc.page(0);
const r =
pg.runs.find((x) => (x.paragraphLineSlots?.length ?? 0) > 1) ??
pg.runs[0];
return {
id: r?.id as string,
fontSubset: r?.fontSubset as boolean,
lineCount: r?.paragraphLineSlots?.length ?? 0,
firstLine: (r?.text ?? "").split("\n")[0] as string,
};
});
const before = await probe();
// Sanity: a multi-line paragraph in a non-subset font (the scramble setup).
expect(before.lineCount).toBeGreaterThan(1);
expect(before.fontSubset).toBe(false);
expect(before.firstLine).toContain("fascinating");
const id = before.id;
// Mid-line replace spanning several words (so it spans spaces) -> forces the
// whole one-object line to be re-emitted, the path that used to scramble.
await page.locator(`[data-testid="v2-run-${id}"]`).click();
await page.waitForTimeout(400);
await page.evaluate((rid) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="v2-run-${rid}"]`,
);
if (!el) throw new Error("overlay missing");
el.focus();
const tn = el.firstChild ?? el;
const len = (tn.textContent ?? "").length;
const sel = window.getSelection()!;
const range = document.createRange();
range.setStart(tn, Math.min(5, len));
range.setEnd(tn, Math.min(20, len)); // "ooms represent " - has spaces
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, "X");
}, id);
await page.waitForTimeout(250);
await page.evaluate(
(rid) =>
document
.querySelector<HTMLElement>(`[data-testid="v2-run-${rid}"]`)
?.blur(),
id,
);
await page.waitForTimeout(1200);
// The model text reflects the RENDERED glyphs after the blur reflow re-reads
// the page - so a scramble would surface here as garbage glyphs in place of
// the unchanged words. After the fix the words past the edit are intact.
const after = await probe();
const firstLine = after.firstLine;
expect(errs, `no page errors:\n${errs.join("\n")}`).toEqual([]);
// Words AFTER the edited span are unchanged and must render correctly - the
// exact words the content-stream guess used to scramble.
for (const word of ["fascinating", "organisms", "occupying", "unique"]) {
expect(
firstLine,
`unchanged word "${word}" must survive the re-emit (no scramble). Got: ${JSON.stringify(firstLine)}`,
).toContain(word);
}
// And the edit itself applied (the replaced span collapsed to "X").
expect(firstLine).toContain("MushrX");
});
@@ -1,161 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Route } from "@playwright/test";
import path from "path";
/**
* Regression for the mushroom-life.pdf reports (backend charcode strategy):
*
* 1. Editing inserted „ (U+201E) where spaces should be. The LMRoman subset
* font has no space glyph but encode(" ") returns charcode 0x20, which
* SetCharcodes paints as the quotedblbase glyph at that subset code.
* 2. Continuous edits collapsed the paragraph onto one baseline on blur.
*
* This test stubs the encode-charcodes endpoint with a DELIBERATELY BUGGY
* backend that hands back a charcode for EVERY char including whitespace
* (0x20 for a space - exactly the old behaviour). The fixed frontend must
* never reuse whitespace anyway: the resolver, prewarm and word-splitter all
* refuse it, so no emit event ever resolves more charcodes than it has
* non-whitespace chars, and the paragraph keeps all its lines.
*/
const MUSHROOM = path.join(
import.meta.dirname,
"../test-fixtures/mushroom-life.pdf",
);
interface CharcodeEvent {
text: string;
outcome: string;
resolved: number[];
}
test("mushroom first-line edits never reuse whitespace (no „) and keep the paragraph lines", async ({
page,
}) => {
// BUGGY backend: returns a charcode for every code point, even whitespace
// (space -> 0x20). The frontend must still refuse to reuse it.
await page.route("**/encode-charcodes", (route: Route) => {
let text = "";
try {
text = (route.request().postDataJSON() as { text?: string }).text ?? "";
} catch {
/* ignore */
}
const charcodes = Array.from(text).map((ch) => ch.codePointAt(0) ?? 0);
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ charcodes, missing: [] }),
});
});
const errs: string[] = [];
page.on("pageerror", (e) => errs.push(e.message));
await page.goto("/pdf-text-editor?charcodeStrategy=backend", {
waitUntil: "domcontentloaded",
});
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 30_000 });
await page.locator('[data-testid="v2-file-input"]').setInputFiles(MUSHROOM);
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(1000);
const probe = () =>
page.evaluate(() => {
const s = (
window as unknown as {
__v2_editor_store: {
doc: {
page: (i: number) => {
runs: Array<{
id: string;
text: string;
paragraphLineSlots?: unknown[];
}>;
};
};
};
}
).__v2_editor_store;
const pg = s.doc.page(0);
const r =
pg.runs.find((x) => (x.paragraphLineSlots?.length ?? 0) > 1) ??
pg.runs[0];
return {
id: r?.id,
lineCount: r?.paragraphLineSlots?.length ?? 0,
text: (r?.text ?? "").slice(0, 200),
hasLowQuote: (r?.text ?? "").includes("„"),
};
});
const before = await probe();
expect(before.lineCount).toBeGreaterThan(1);
const id = before.id;
// Focus engages the backend prewarm; wait for it to complete so the cache
// is populated before the first keystroke.
const prewarm = page.waitForEvent("console", {
predicate: (m) =>
/\[v2\.charcode\] backend prewarm pageIdx=/.test(m.text()),
timeout: 30_000,
});
await page.locator(`[data-testid="v2-run-${id}"]`).click();
await prewarm.catch(() => undefined);
// MID-LINE replace: select a span that spans several words (so it includes
// spaces) and replace it. This forces the whole-line sub-run (one PDFium
// object covering many words) to be re-emitted - the exact path that used
// to SetText whitespace onto the no-space-glyph subset font and paint „.
await page.evaluate((rid) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="v2-run-${rid}"]`,
);
if (!el) return;
el.focus();
const tn = el.firstChild ?? el;
const len = (tn.textContent ?? "").length;
const sel = window.getSelection()!;
const range = document.createRange();
range.setStart(tn, Math.min(5, len));
range.setEnd(tn, Math.min(20, len)); // "ooms represent " - has spaces
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, "X");
}, id);
await page.waitForTimeout(200);
await page.evaluate(
(rid) =>
document
.querySelector<HTMLElement>(`[data-testid="v2-run-${rid}"]`)
?.blur(),
id,
);
await page.waitForTimeout(1000);
const after = await probe();
expect(errs, `no page errors:\n${errs.join("\n")}`).toEqual([]);
// No „ in the model text - spaces survived as real gaps, not the
// quotedblbase glyph at subset code 0x20.
expect(after.hasLowQuote).toBe(false);
// Paragraph kept its lines - no collapse onto a single baseline.
expect(after.lineCount).toBeGreaterThan(1);
// Decisive: no emit event ever resolved MORE charcodes than it had
// non-whitespace chars - i.e. whitespace was never charcode-reused (which
// is what painted „), even though the stubbed backend offered a code for it.
const events: CharcodeEvent[] = await page.evaluate(
() =>
(window as unknown as { __v2_charcode_events?: CharcodeEvent[] })
.__v2_charcode_events ?? [],
);
const whitespaceReused = events.filter((e) => {
const nonWs = Array.from(e.text).filter((c) => !/\s/.test(c)).length;
return (e.resolved?.length ?? 0) > nonWs;
});
expect(
whitespaceReused,
`whitespace must never be charcode-reused. Offending:\n${JSON.stringify(whitespaceReused, null, 2)}`,
).toHaveLength(0);
});
@@ -1,697 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page } from "@playwright/test";
import path from "path";
import type { V2TestWindow } from "@app/tests/stubbed/v2EditorTestTypes";
const SAMPLE = path.join(
import.meta.dirname,
"../../../../public/samples/Sample.pdf",
);
/**
* Comprehensive paragraph-editing battery for the v2 editor.
*
* These exercise the hard cases the user hit: typing into wrapped
* paragraphs, manual Enter line breaks surviving a wrap, live wrapping
* while typing (no off-page overflow), and text-content integrity. Many
* tests read the run's ACTUAL glyph layout (position + baseline + text)
* straight from PDFium so the assertions describe what renders, not the
* in-memory model only.
*/
async function gotoWrap(page: Page): Promise<void> {
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 15_000 });
await page.locator('[data-testid="v2-file-input"]').setInputFiles(SAMPLE);
await expect(page.getByTestId("v2-page-1")).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(700);
await page
.getByTestId("v2-width-mode-control")
.getByText("Wrap", { exact: true })
.click();
await page.waitForTimeout(150);
}
/** Load page 2 but leave the default "grow" width mode (no wrap toggle). */
async function gotoGrow(page: Page): Promise<void> {
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 15_000 });
await page.locator('[data-testid="v2-file-input"]').setInputFiles(SAMPLE);
await expect(page.getByTestId("v2-page-1")).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(700);
}
async function findPara(page: Page, re: RegExp): Promise<string | null> {
return page.evaluate((src: string) => {
const store = (window as unknown as V2TestWindow).__v2_editor_store;
const rx = new RegExp(src);
const r = store.doc.page(1).runs.find((x) => rx.test(x.text));
return r ? r.id : null;
}, re.source);
}
async function focusCaretEnd(page: Page, id: string): Promise<void> {
await page.evaluate((rid: string) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="v2-run-${rid}"]`,
);
if (!el) throw new Error("run not in DOM");
el.focus();
const sel = window.getSelection()!;
const range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
}, id);
}
/** Type a string one character at a time (the way a real user does). */
async function typeChars(page: Page, id: string, str: string): Promise<void> {
await focusCaretEnd(page, id);
for (const ch of str) {
await page.evaluate((c: string) => {
document.execCommand("insertText", false, c);
}, ch);
await page.waitForTimeout(20);
}
}
async function blurRun(page: Page, id: string): Promise<void> {
await page.evaluate((rid: string) => {
document
.querySelector<HTMLElement>(`[data-testid="v2-run-${rid}"]`)
?.blur();
}, id);
await page.waitForTimeout(300);
}
interface Glyph {
text: string;
x: number;
right: number;
baseline: number;
}
interface ParaInfo {
text: string;
fontId: string;
fontSize: number;
pageWidth: number;
glyphs: Glyph[];
}
/** Read every leaf glyph's real text + bounds + baseline from PDFium. */
async function readGlyphs(page: Page, id: string): Promise<ParaInfo | null> {
return page.evaluate((rid: string) => {
const store = (window as unknown as V2TestWindow).__v2_editor_store;
const m = store.doc.module;
const pg = store.doc.page(1);
const r = pg.runs.find((x) => x.id === rid);
if (!r) return null;
const ptrs: number[] =
r.paragraphLeafPtrs && r.paragraphLeafPtrs.length
? r.paragraphLeafPtrs
: r.mergedFromPtrs;
const tp = m.FPDFText_LoadPage(pg.pagePtr);
const glyphs: Glyph[] = [];
try {
for (const ptr of ptrs) {
if (!ptr) continue;
const l = m.pdfium.wasmExports.malloc(4);
const b = m.pdfium.wasmExports.malloc(4);
const rr = m.pdfium.wasmExports.malloc(4);
const t = m.pdfium.wasmExports.malloc(4);
const mb = m.pdfium.wasmExports.malloc(24);
try {
if (!m.FPDFPageObj_GetBounds(ptr, l, b, rr, t)) continue;
const x = m.pdfium.getValue(l, "float");
const right = m.pdfium.getValue(rr, "float");
let baseline = m.pdfium.getValue(b, "float");
if (m.FPDFPageObj_GetMatrix(ptr, mb)) {
baseline = m.pdfium.getValue(mb + 20, "float");
}
const len = m.FPDFTextObj_GetText(ptr, tp, 0, 0);
let text = "";
if (len > 2) {
const buf = m.pdfium.wasmExports.malloc(len);
m.FPDFTextObj_GetText(ptr, tp, buf, len);
for (let i = 0; i < len - 2; i += 2) {
const code = m.pdfium.getValue(buf + i, "i16") & 0xffff;
if (code) text += String.fromCharCode(code);
}
m.pdfium.wasmExports.free(buf);
}
glyphs.push({ text, x, right, baseline });
} finally {
m.pdfium.wasmExports.free(l);
m.pdfium.wasmExports.free(b);
m.pdfium.wasmExports.free(rr);
m.pdfium.wasmExports.free(t);
m.pdfium.wasmExports.free(mb);
}
}
} finally {
m.FPDFText_ClosePage(tp);
}
return {
text: r.text,
fontId: r.fontId,
fontSize: r.fontSize,
pageWidth: pg.width,
glyphs,
};
}, id);
}
/** Number of distinct baselines (visual lines) the glyphs occupy. */
function lineCount(info: ParaInfo): number {
const ys = info.glyphs.map((g) => Math.round(g.baseline));
const uniq = new Set<number>();
for (const y of ys) {
let found = false;
for (const u of uniq) if (Math.abs(u - y) <= 2) found = true;
if (!found) uniq.add(y);
}
return uniq.size;
}
const INTRO = "Stirling\\s+PDF\\s+is\\s+a\\s+robust";
const CARD = "Comprehensive\\s+toolkit";
test.describe("PDF text editor v2 - paragraph editing battery", () => {
test("wrap: a long appended tail wraps within the page after click-off", async ({
page,
}) => {
await gotoWrap(page);
const id = await findPara(page, new RegExp(INTRO));
if (!id) {
test.skip(true, "intro paragraph missing");
return;
}
await typeChars(
page,
id,
" ZZZZ YYYY XXXX WWWW VVVV UUUU TTTT SSSS RRRR QQQQ PPPP OOOO",
);
await blurRun(page, id);
const info = await readGlyphs(page, id);
if (!info) throw new Error("vanished");
const maxRight = Math.max(...info.glyphs.map((g) => g.right));
expect(
maxRight,
`text ran off the page (maxRight=${maxRight}, pageWidth=${info.pageWidth})`,
).toBeLessThanOrEqual(info.pageWidth);
expect(lineCount(info)).toBeGreaterThan(1);
});
test("wrap: typed text stays within the page while typing AND after click-off", async ({
page,
}) => {
await gotoWrap(page);
const id = await findPara(page, new RegExp(INTRO));
if (!id) {
test.skip(true, "intro paragraph missing");
return;
}
await typeChars(
page,
id,
" ZZZZ YYYY XXXX WWWW VVVV UUUU TTTT SSSS RRRR QQQQ PPPP OOOO",
);
// NO blur - the box the user SEES while editing must stay within the page.
// The editing box is capped to the page width and wraps via CSS, so it can
// never grow off the right edge (the heavy reflow that bakes the wrapped
// layout into glyphs runs once on click-off, not on every keystroke).
await page.waitForTimeout(120);
const box = await page.evaluate((rid: string) => {
const el = document.querySelector<HTMLElement>(
`[data-testid="v2-run-${rid}"]`,
);
const pageEl = document.querySelector<HTMLElement>(
'[data-testid="v2-page-1"]',
);
if (!el || !pageEl) return null;
const er = el.getBoundingClientRect();
const pr = pageEl.getBoundingClientRect();
return { elRight: er.right, pageRight: pr.right };
}, id);
expect(box, "elements missing").not.toBeNull();
expect(
box!.elRight,
`editing box overflowed the page while typing (boxRight=${box!.elRight}, pageRight=${box!.pageRight})`,
).toBeLessThanOrEqual(box!.pageRight + 4);
// After click-off the baked glyphs stay on the page too.
await blurRun(page, id);
const info = await readGlyphs(page, id);
if (!info) throw new Error("vanished");
const maxRight = Math.max(...info.glyphs.map((g) => g.right));
expect(
maxRight,
`text overflowed the page after click-off (maxRight=${maxRight}, pageWidth=${info.pageWidth})`,
).toBeLessThanOrEqual(info.pageWidth + 2);
});
test("wrap: a manual Enter break is kept after click-off (no extra typing)", async ({
page,
}) => {
await gotoWrap(page);
const id = await findPara(page, new RegExp(INTRO));
if (!id) {
test.skip(true, "intro paragraph missing");
return;
}
// Append a clear marker, Enter, second marker.
await typeChars(page, id, " AAAALPHA");
await page.evaluate(() => {
document.execCommand("insertText", false, "\n");
});
await page.waitForTimeout(40);
await typeChars(page, id, "BBBBETA");
await blurRun(page, id);
const info = await readGlyphs(page, id);
if (!info) throw new Error("vanished");
// The two markers must sit on DIFFERENT baselines (a real break).
const a = info.glyphs.find((g) => g.text.includes("A"));
const baseOfAlpha = lastBaselineOfWord(info, "ALPHA");
const baseOfBeta = firstBaselineOfWord(info, "BBBB");
expect(a, "no glyphs").toBeTruthy();
expect(
baseOfAlpha !== null && baseOfBeta !== null,
`markers missing: ${JSON.stringify(info.text)}`,
).toBe(true);
expect(
baseOfBeta!,
`manual break lost: ALPHA baseline=${baseOfAlpha}, BETA baseline=${baseOfBeta}`,
).toBeLessThan(baseOfAlpha! - 1);
});
test("wrap: a manual Enter break survives a subsequent word-wrap", async ({
page,
}) => {
await gotoWrap(page);
const id = await findPara(page, new RegExp(INTRO));
if (!id) {
test.skip(true, "intro paragraph missing");
return;
}
// Manual break, then type a LONG tail that forces wrapping. The break
// between the original text and "GAMMA..." must remain a break.
await page.evaluate(() => {
document.execCommand("insertText", false, "");
});
await focusCaretEnd(page, id);
await page.evaluate(() => {
document.execCommand("insertText", false, "\n");
});
await page.waitForTimeout(40);
await typeChars(
page,
id,
"GAMMA DELTA EPSILON ZETA ETA THETA IOTA KAPPA LAMBDA MUMU NUNU",
);
await blurRun(page, id);
const info = await readGlyphs(page, id);
if (!info) throw new Error("vanished");
// "more." ends the original last line; "GAMMA" begins the manual line.
const baseMore = lastBaselineOfWord(info, "more");
const baseGamma = firstBaselineOfWord(info, "GAMMA");
expect(
baseMore !== null && baseGamma !== null,
`markers missing: ${JSON.stringify(info.text.slice(-80))}`,
).toBe(true);
expect(
baseGamma!,
`manual break merged by wrap: more=${baseMore}, GAMMA=${baseGamma}`,
).toBeLessThan(baseMore! - 1);
});
test("wrap: Enter at end then typing puts the new text on a lower line", async ({
page,
}) => {
await gotoWrap(page);
const id = await findPara(page, new RegExp(CARD));
if (!id) {
test.skip(true, "card paragraph missing");
return;
}
await focusCaretEnd(page, id);
await page.evaluate(() => document.execCommand("insertText", false, "\n"));
await page.waitForTimeout(40);
await typeChars(page, id, "NEWLINEWORD");
await blurRun(page, id);
const info = await readGlyphs(page, id);
if (!info) throw new Error("vanished");
const baseProc = lastBaselineOfWord(info, "processing");
const baseNew = firstBaselineOfWord(info, "NEWLINEWORD");
expect(baseNew !== null, `NEW word missing: ${info.text}`).toBe(true);
if (baseProc !== null) {
expect(baseNew!).toBeLessThan(baseProc! - 1);
}
});
test("integrity: every original word survives editing exactly once", async ({
page,
}) => {
await gotoWrap(page);
const id = await findPara(page, new RegExp(CARD));
if (!id) {
test.skip(true, "card paragraph missing");
return;
}
await typeChars(page, id, " APPENDIX");
await blurRun(page, id);
const info = await readGlyphs(page, id);
if (!info) throw new Error("vanished");
const flat = info.text.replace(/\s+/g, " ");
for (const w of ["Comprehensive", "toolkit", "processing", "APPENDIX"]) {
const n = flat.split(w).length - 1;
expect(
n,
`"${w}" appears ${n}x (expected 1): ${JSON.stringify(flat)}`,
).toBe(1);
}
});
test("integrity: typing into the MIDDLE of a paragraph keeps it intact", async ({
page,
}) => {
await gotoWrap(page);
const id = await findPara(page, new RegExp(CARD));
if (!id) {
test.skip(true, "card paragraph missing");
return;
}
// Caret after "Comprehensive", type a marker.
await page.evaluate((rid: string) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="v2-run-${rid}"]`,
)!;
el.focus();
const tw = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
let node: Text | null = null;
let rem = "Comprehensive".length;
while (tw.nextNode()) {
const n = tw.currentNode as Text;
const len = n.textContent?.length ?? 0;
if (rem <= len) {
node = n;
break;
}
rem -= len;
}
if (!node) return;
const sel = window.getSelection()!;
const range = document.createRange();
range.setStart(node, rem);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, "MIDWORD");
}, id);
await page.waitForTimeout(80);
await blurRun(page, id);
const info = await readGlyphs(page, id);
if (!info) throw new Error("vanished");
expect(info.text.replace(/\s+/g, " ")).toContain("MIDWORD");
expect(info.text.replace(/\s+/g, " ")).toMatch(/Comprehensive.*toolkit/);
});
test("undo: wrapping then Ctrl+Z restores the original text and layout", async ({
page,
}) => {
await gotoWrap(page);
const id = await findPara(page, new RegExp(INTRO));
if (!id) {
test.skip(true, "intro paragraph missing");
return;
}
const before = await readGlyphs(page, id);
if (!before) throw new Error("vanished");
const beforeLines = lineCount(before);
await typeChars(
page,
id,
" OMEGA SIGMA PSICHI TAUTAU RHORHO PHIPHI UPSILON",
);
await blurRun(page, id);
// Undo every command from this edit.
for (let i = 0; i < 60; i++) {
await page.keyboard.press("Control+z");
await page.waitForTimeout(15);
}
await page.waitForTimeout(200);
const after = await readGlyphs(page, id);
if (!after) throw new Error("vanished after undo");
expect(after.text.replace(/\s+/g, " ")).not.toContain("OMEGA");
expect(after.text.replace(/\s+/g, " ")).toMatch(/Stirling.*robust/);
expect(Math.abs(lineCount(after) - beforeLines)).toBeLessThanOrEqual(1);
});
test("grow mode: typing a long tail grows right (one line, no wrap)", async ({
page,
}) => {
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 15_000 });
await page.locator('[data-testid="v2-file-input"]').setInputFiles(SAMPLE);
await expect(page.getByTestId("v2-page-1")).toBeVisible({
timeout: 30_000,
});
await page.waitForTimeout(700);
// Default mode is "grow".
const id = await findPara(page, new RegExp(CARD));
if (!id) {
test.skip(true, "card paragraph missing");
return;
}
await typeChars(page, id, " GROWGROWGROW");
await blurRun(page, id);
const info = await readGlyphs(page, id);
if (!info) throw new Error("vanished");
expect(info.text.replace(/\s+/g, " ")).toContain("GROWGROWGROW");
});
test("wrap: a single very long unbreakable word does not corrupt the paragraph", async ({
page,
}) => {
await gotoWrap(page);
const id = await findPara(page, new RegExp(CARD));
if (!id) {
test.skip(true, "card paragraph missing");
return;
}
await typeChars(
page,
id,
" SUPERCALIFRAGILISTICEXPIALIDOCIOUSANTIDISESTAB",
);
await blurRun(page, id);
const info = await readGlyphs(page, id);
if (!info) throw new Error("vanished");
expect(info.text.replace(/\s+/g, " ")).toContain(
"SUPERCALIFRAGILISTICEXPIALIDOCIOUSANTIDISESTAB",
);
// Original words still intact.
expect(info.text.replace(/\s+/g, " ")).toMatch(/Comprehensive.*toolkit/);
});
test("wrap: a MID-paragraph manual break is not removed when a later line wraps", async ({
page,
}) => {
await gotoWrap(page);
const id = await findPara(page, new RegExp(CARD));
if (!id) {
test.skip(true, "card paragraph missing");
return;
}
// Insert a manual break right after "Comprehensive" (where the line is
// NOT full - width alone would keep "Comprehensive toolkit" together).
await page.evaluate((rid: string) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="v2-run-${rid}"]`,
)!;
el.focus();
const tw = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
let node: Text | null = null;
let rem = "Comprehensive".length;
while (tw.nextNode()) {
const n = tw.currentNode as Text;
const len = n.textContent?.length ?? 0;
if (rem <= len) {
node = n;
break;
}
rem -= len;
}
if (!node) return;
const sel = window.getSelection()!;
const range = document.createRange();
range.setStart(node, rem);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, "\n");
}, id);
await page.waitForTimeout(80);
// Type a long tail at the END to force a width-wrap (triggers reflow).
await typeChars(page, id, " ZZZZ YYYY XXXX WWWW VVVV UUUU TTTT SSSS RRRR");
await blurRun(page, id);
const info = await readGlyphs(page, id);
if (!info) throw new Error("vanished");
const baseComp = lastBaselineOfWord(info, "Comprehensive");
const baseTool = firstBaselineOfWord(info, "toolkit");
expect(
baseComp !== null && baseTool !== null,
`words missing: ${JSON.stringify(info.text.slice(0, 60))}`,
).toBe(true);
expect(
baseTool!,
`mid-paragraph manual break removed by wrap: "Comprehensive" baseline=${baseComp}, "toolkit" baseline=${baseTool} (same line = break lost)`,
).toBeLessThan(baseComp! - 1);
});
test("wrap: deleting a manual break merges the two lines back together", async ({
page,
}) => {
await gotoWrap(page);
const id = await findPara(page, new RegExp(CARD));
if (!id) {
test.skip(true, "card paragraph missing");
return;
}
// Add a manual break at the end + a word, then delete back over the break.
await focusCaretEnd(page, id);
await page.evaluate(() => document.execCommand("insertText", false, "\n"));
await page.waitForTimeout(40);
await typeChars(page, id, "TAILWORD");
await page.waitForTimeout(60);
// Backspace the whole TAILWORD + the newline.
for (let i = 0; i < "TAILWORD\n".length; i++) {
await page.evaluate(() => document.execCommand("delete"));
await page.waitForTimeout(25);
}
await blurRun(page, id);
const info = await readGlyphs(page, id);
if (!info) throw new Error("vanished");
expect(info.text.replace(/\s+/g, " ")).not.toContain("TAILWORD");
expect(info.text.replace(/\s+/g, " ")).toMatch(/Comprehensive.*processing/);
});
test("grow mode: editing a paragraph (Enter + type) never blows the box off the page", async ({
page,
}) => {
// The reported bug: clicking a paragraph in the DEFAULT (grow) mode,
// pressing Enter and typing made the editing box expand past the page's
// right edge, clipping text the user never touched. A paragraph must
// wrap within the page even in grow mode.
await gotoGrow(page);
const id = await findPara(page, new RegExp(INTRO));
if (!id) {
test.skip(true, "intro paragraph missing");
return;
}
await focusCaretEnd(page, id);
await page.evaluate(() => document.execCommand("insertText", false, "\n"));
await page.waitForTimeout(40);
await typeChars(page, id, "dfg");
await page.waitForTimeout(120);
// While focused: the editing box must not extend past the page's right
// edge (allowing a small tolerance).
const box = await page.evaluate((rid: string) => {
const el = document.querySelector<HTMLElement>(
`[data-testid="v2-run-${rid}"]`,
);
const pageEl = document.querySelector<HTMLElement>(
'[data-testid="v2-page-1"]',
);
if (!el || !pageEl) return null;
const er = el.getBoundingClientRect();
const pr = pageEl.getBoundingClientRect();
return { elRight: er.right, pageRight: pr.right };
}, id);
expect(box, "elements missing").not.toBeNull();
expect(
box!.elRight,
`editing box ran off the page (boxRight=${box!.elRight}, pageRight=${box!.pageRight})`,
).toBeLessThanOrEqual(box!.pageRight + 4);
// And the committed glyphs stay on the page too.
await blurRun(page, id);
const info = await readGlyphs(page, id);
if (!info) throw new Error("vanished");
const maxRight = Math.max(...info.glyphs.map((g) => g.right));
expect(
maxRight,
`committed text ran off the page (maxRight=${maxRight}, pageWidth=${info.pageWidth})`,
).toBeLessThanOrEqual(info.pageWidth);
// "dfg" landed and the original words survived.
expect(info.text.replace(/\s+/g, " ")).toContain("dfg");
expect(info.text.replace(/\s+/g, " ")).toMatch(/Stirling.*robust/);
});
test("wrap: two manual breaks both survive", async ({ page }) => {
await gotoWrap(page);
const id = await findPara(page, new RegExp(INTRO));
if (!id) {
test.skip(true, "intro paragraph missing");
return;
}
await typeChars(page, id, " ONEONE");
await page.evaluate(() => document.execCommand("insertText", false, "\n"));
await page.waitForTimeout(30);
await typeChars(page, id, "TWOTWO");
await page.evaluate(() => document.execCommand("insertText", false, "\n"));
await page.waitForTimeout(30);
await typeChars(page, id, "THREE");
await blurRun(page, id);
const info = await readGlyphs(page, id);
if (!info) throw new Error("vanished");
const b1 = firstBaselineOfWord(info, "ONEONE");
const b2 = firstBaselineOfWord(info, "TWOTWO");
const b3 = firstBaselineOfWord(info, "THREE");
expect(b1 !== null && b2 !== null && b3 !== null, info.text).toBe(true);
// Each marker on its own progressively-lower line.
expect(b2!).toBeLessThan(b1! - 1);
expect(b3!).toBeLessThan(b2! - 1);
});
});
function lastBaselineOfWord(info: ParaInfo, word: string): number | null {
// Find the run of glyphs spelling `word` (contiguous, same baseline) and
// return that baseline. Glyphs may be per-char or per-word.
const baselines = matchWordBaselines(info, word);
return baselines.length ? baselines[baselines.length - 1] : null;
}
function firstBaselineOfWord(info: ParaInfo, word: string): number | null {
const baselines = matchWordBaselines(info, word);
return baselines.length ? baselines[0] : null;
}
function matchWordBaselines(info: ParaInfo, word: string): number[] {
// Concatenate glyph texts in reading order (baseline desc, x asc) and find
// `word`; return the baseline(s) of the glyphs covering it.
const sorted = [...info.glyphs].sort((a, b) => {
if (Math.abs(a.baseline - b.baseline) > 2) return b.baseline - a.baseline;
return a.x - b.x;
});
let concat = "";
const owner: number[] = []; // glyph index per concatenated char
sorted.forEach((g, gi) => {
for (let i = 0; i < g.text.length; i++) {
concat += g.text[i];
owner.push(gi);
}
});
const idx = concat.indexOf(word);
if (idx < 0) return [];
const result: number[] = [];
const seen = new Set<number>();
for (let i = idx; i < idx + word.length; i++) {
const gi = owner[i];
if (gi != null && !seen.has(gi)) {
seen.add(gi);
result.push(sorted[gi].baseline);
}
}
return result;
}
@@ -1,129 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page, Route } from "@playwright/test";
import path from "path";
/**
* Coverage for two save/open safety features:
* - Encrypted PDFs prompt for a password and decrypt client-side (PDFium),
* re-prompting on a wrong password rather than dead-ending.
* - Saving a document that carries digital signatures (or XFA) warns first,
* because PDFium's full rewrite would invalidate them.
*
* Assertions target the modals' inner controls (buttons / inputs / text),
* not the Mantine Modal ROOT wrapper - that root persists in the DOM and is a
* zero-size positioning element, so toBeVisible()/count() on it is unreliable.
*
* Backend-free: encode-charcodes is aborted so nothing depends on a server.
*/
const ENCRYPTED = path.join(
import.meta.dirname,
"../test-fixtures/encrypted.pdf",
);
const SIGNED = path.join(
import.meta.dirname,
"../test-fixtures/signed-sample.pdf",
);
const SAMPLE = path.join(import.meta.dirname, "../test-fixtures/sample.pdf");
const ENCRYPTED_PASSWORD = "testpass123";
async function gotoEditor(page: Page): Promise<void> {
await page.route("**/encode-charcodes", (route: Route) => route.abort());
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 20_000 });
}
async function upload(page: Page, file: string): Promise<void> {
await page.locator('[data-testid="v2-file-input"]').setInputFiles(file);
}
test.describe("v2 editor - encrypted PDF password prompt", () => {
test("wrong password re-prompts, correct password opens the document", async ({
page,
}) => {
test.setTimeout(90_000);
await gotoEditor(page);
await upload(page, ENCRYPTED);
const submit = page.getByTestId("v2-password-submit");
await expect(submit).toBeVisible({ timeout: 20_000 });
const input = page
.getByTestId("v2-password-modal")
.locator("input")
.first();
// Wrong password -> prompt stays, shows the retry error.
await input.fill("definitely-wrong");
await submit.click();
await expect(page.getByText("Incorrect password - try again.")).toBeVisible(
{ timeout: 20_000 },
);
await expect(submit).toBeVisible();
// Correct password -> prompt closes and the page renders.
await input.fill(ENCRYPTED_PASSWORD);
await submit.click();
await expect(submit).toBeHidden({ timeout: 20_000 });
await expect(page.getByTestId("v2-page-0")).toBeVisible({
timeout: 30_000,
});
});
test("cancel dismisses the prompt without loading a document", async ({
page,
}) => {
test.setTimeout(60_000);
await gotoEditor(page);
await upload(page, ENCRYPTED);
const cancel = page.getByTestId("v2-password-cancel");
await expect(cancel).toBeVisible({ timeout: 20_000 });
await cancel.click();
await expect(cancel).toBeHidden();
expect(await page.getByTestId("v2-page-0").count()).toBe(0);
});
});
test.describe("v2 editor - pre-save data-loss warning", () => {
test("signed PDF warns before saving, then downloads on confirm", async ({
page,
}) => {
test.setTimeout(90_000);
await gotoEditor(page);
await upload(page, SIGNED);
await expect(page.getByTestId("v2-page-0")).toBeVisible({
timeout: 30_000,
});
// First save attempt surfaces the warning instead of downloading.
await page.getByTestId("v2-save").click();
const confirm = page.getByTestId("v2-save-risk-confirm");
await expect(confirm).toBeVisible({ timeout: 10_000 });
await expect(page.getByTestId("v2-save-risk-modal")).toContainText(
/signature/i,
);
// Confirming downloads the rewritten copy and closes the modal.
const downloadPromise = page.waitForEvent("download");
await confirm.click();
const download = await downloadPromise;
expect(download.suggestedFilename()).toMatch(/\.pdf$/i);
await expect(confirm).toBeHidden();
});
test("a normal PDF saves without any warning", async ({ page }) => {
test.setTimeout(60_000);
await gotoEditor(page);
await upload(page, SAMPLE);
await expect(page.getByTestId("v2-page-0")).toBeVisible({
timeout: 30_000,
});
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("v2-save").click();
const download = await downloadPromise;
expect(download.suggestedFilename()).toMatch(/\.pdf$/i);
// The warning's confirm button must never have mounted for a plain PDF.
expect(await page.getByTestId("v2-save-risk-confirm").count()).toBe(0);
});
});
@@ -1,447 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page } from "@playwright/test";
import path from "path";
import type { V2TestWindow } from "@app/tests/stubbed/v2EditorTestTypes";
/**
* Regression coverage for three user-reported issues:
* 1. Align/distribute buttons stayed disabled because shift-click did not
* reliably add a 2nd run to the selection (TextRunOverlay focused the
* run before selecting and never preventDefault'd). FIXED - these tests
* drive the REAL shift-click DOM gesture (not store.selectMany).
* 2. Inserting a character must keep the run text correct and must never
* emit the U+00FF "ydieresis" tofu, across different page sections.
* 3. Bullet glyphs on the "Plus Many More" page are detached from their
* list items into an orphan bullet-only run - documented as a known
* grouping bug via test.fail until the grouper is reworked.
*/
const SAMPLE = path.join(
import.meta.dirname,
"../../../../public/samples/Sample.pdf",
);
// Align / distribute / z-order now live inside the toolbar's "Arrange" menu.
// Open the menu, then act on or inspect the item.
async function clickArrange(page: Page, testid: string): Promise<void> {
await page.getByTestId("v2-arrange-menu").click();
await page.getByTestId(testid).click();
}
async function arrangeItemDisabled(
page: Page,
testid: string,
): Promise<boolean> {
await page.getByTestId("v2-arrange-menu").click();
const item = page.getByTestId(testid);
await item.waitFor({ state: "visible" });
const disabled = await item.isDisabled();
// Close via a neutral click in the top bar, NOT Escape: the editor's global
// Escape handler also clears the selection, which would break the next check.
await page.getByTestId("v2-zoom-percent").click();
await item.waitFor({ state: "hidden" });
return disabled;
}
async function open(page: Page, firstPage = 0): Promise<void> {
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 15_000 });
await page.locator('[data-testid="v2-file-input"]').setInputFiles(SAMPLE);
await expect(page.getByTestId(`v2-page-${firstPage}`)).toBeVisible({
timeout: 30_000,
});
await page.waitForTimeout(900);
}
async function runId(
page: Page,
pageIdx: number,
src: string,
): Promise<string> {
const id = await page.evaluate(
({ pageIdx, src }: { pageIdx: number; src: string }) => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
const r = s.doc
.page(pageIdx)
.runs.find((x) => new RegExp(src).test(x.text));
return r ? r.id : null;
},
{ pageIdx, src },
);
if (!id) throw new Error(`run /${src}/ not found`);
return id;
}
async function runText(
page: Page,
pageIdx: number,
id: string,
): Promise<string> {
return page.evaluate(
({ pageIdx, id }: { pageIdx: number; id: string }) => {
const r = (window as unknown as V2TestWindow).__v2_editor_store.doc
.page(pageIdx)
.runs.find((x) => x.id === id);
return r ? (r.text as string) : "(gone)";
},
{ pageIdx, id },
);
}
async function selRunCount(page: Page): Promise<number> {
return page.evaluate(
() =>
(window as unknown as V2TestWindow).__v2_editor_store.selection.value
.runIds.length,
);
}
/** Append text into a run via the contentEditable overlay, then blur. */
async function appendViaOverlay(
page: Page,
id: string,
text: string,
): Promise<void> {
await page.evaluate(
({ rid, text }: { rid: string; text: string }) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="v2-run-${rid}"]`,
);
if (!el) throw new Error("run el missing");
el.focus();
const sel = window.getSelection()!;
const range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, text);
},
{ rid: id, text },
);
await page.waitForTimeout(150);
await page.evaluate(
(rid: string) =>
document
.querySelector<HTMLElement>(`[data-testid="v2-run-${rid}"]`)
?.blur(),
id,
);
await page.waitForTimeout(900);
}
test.describe("v2 editor - reported issue: align multi-select (real UI)", () => {
test("shift-click adds a 2nd run, which enables and applies align-left", async ({
page,
}) => {
// Use page-0 SINGLE-LINE runs at different x: a single one keeps align
// disabled (single paragraphs enable it - covered in the paragraph
// suite), and the two sit at different left edges so align-left is a
// real move, not a no-op.
await open(page, 0);
const a = await runId(page, 0, "10M\\+");
const b = await runId(page, 0, "Downloads");
await page.getByTestId(`v2-run-${a}`).click();
await page.waitForTimeout(150);
expect(await selRunCount(page)).toBe(1);
expect(await arrangeItemDisabled(page, "v2-align-left")).toBe(true);
// Shift-click B must ADD it (the bug was it failed to add).
await page.getByTestId(`v2-run-${b}`).click({ modifiers: ["Shift"] });
await page.waitForTimeout(200);
expect(await selRunCount(page), "shift-click adds a 2nd run").toBe(2);
expect(await arrangeItemDisabled(page, "v2-align-left")).toBe(false);
// And it actually aligns the two left edges.
await clickArrange(page, "v2-align-left");
await page.waitForTimeout(250);
const xs = await page.evaluate(
({ a, b }: { a: string; b: string }) => {
const pg = (
window as unknown as V2TestWindow
).__v2_editor_store.doc.page(0);
return [
pg.runs.find((r) => r.id === a)!.bounds.x,
pg.runs.find((r) => r.id === b)!.bounds.x,
];
},
{ a, b },
);
expect(Math.abs(xs[0] - xs[1])).toBeLessThan(1.5);
});
test("shift-clicking the same run twice toggles it back off (align re-disables)", async ({
page,
}) => {
await open(page, 0);
const a = await runId(page, 0, "10M\\+");
const b = await runId(page, 0, "Downloads");
await page.getByTestId(`v2-run-${a}`).click();
await page.getByTestId(`v2-run-${b}`).click({ modifiers: ["Shift"] });
await page.waitForTimeout(200);
expect(await selRunCount(page)).toBe(2);
expect(await arrangeItemDisabled(page, "v2-align-left")).toBe(false);
// Shift-click B again removes it -> back to 1 single-line run -> disabled.
await page.getByTestId(`v2-run-${b}`).click({ modifiers: ["Shift"] });
await page.waitForTimeout(200);
expect(await selRunCount(page)).toBe(1);
expect(await arrangeItemDisabled(page, "v2-align-left")).toBe(true);
});
test("distribute needs three runs: enabled only after a 3rd shift-click", async ({
page,
}) => {
await open(page, 1);
const a = await runId(page, 1, "What\\s+is\\s+Stirling");
const b = await runId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
const c = await runId(page, 1, "Comprehensive\\s+toolkit");
await page.getByTestId(`v2-run-${a}`).click();
await page.getByTestId(`v2-run-${b}`).click({ modifiers: ["Shift"] });
await page.waitForTimeout(150);
expect(await arrangeItemDisabled(page, "v2-distribute-v")).toBe(true);
await page.getByTestId(`v2-run-${c}`).click({ modifiers: ["Shift"] });
await page.waitForTimeout(200);
expect(await selRunCount(page)).toBe(3);
expect(await arrangeItemDisabled(page, "v2-distribute-v")).toBe(false);
});
});
test.describe("v2 editor - reported issue: align a single paragraph's lines", () => {
async function selectOne(page: Page, id: string): Promise<void> {
await page.evaluate(
(rid: string) =>
(
window as unknown as V2TestWindow
).__v2_editor_store.selection.selectOne(rid),
id,
);
await page.waitForTimeout(120);
}
async function lineRights(page: Page, id: string): Promise<number[]> {
return page.evaluate((rid: string) => {
const run = (window as unknown as V2TestWindow).__v2_editor_store.doc
.page(1)
.runs.find((r) => r.id === rid);
return (run?.paragraphLineSlots ?? []).map((s) =>
Math.max(...s.mergedFromBounds.map((b) => b.right)),
);
}, id);
}
async function lineLefts(page: Page, id: string): Promise<number[]> {
return page.evaluate((rid: string) => {
const run = (window as unknown as V2TestWindow).__v2_editor_store.doc
.page(1)
.runs.find((r) => r.id === rid);
return (run?.paragraphLineSlots ?? []).map((s) =>
Math.min(...s.mergedFromBounds.map((b) => b.x)),
);
}, id);
}
test("align buttons enable for a single multi-line paragraph", async ({
page,
}) => {
await open(page, 1);
const para = await runId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
await selectOne(page, para);
// Horizontal aligns enable on a single paragraph...
expect(await arrangeItemDisabled(page, "v2-align-left")).toBe(false);
expect(await arrangeItemDisabled(page, "v2-align-right")).toBe(false);
expect(await arrangeItemDisabled(page, "v2-align-center-h")).toBe(false);
// ...but vertical aligns still need 2+ objects.
expect(await arrangeItemDisabled(page, "v2-align-top")).toBe(true);
});
test("align buttons stay disabled for a single single-line run", async ({
page,
}) => {
await open(page, 1);
const heading = await runId(page, 1, "What\\s+is\\s+Stirling");
await selectOne(page, heading);
expect(await arrangeItemDisabled(page, "v2-align-left")).toBe(true);
expect(await arrangeItemDisabled(page, "v2-align-right")).toBe(true);
});
test("align-right flushes a paragraph's lines to a shared right edge; undo reverts", async ({
page,
}) => {
await open(page, 1);
const para = await runId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
await selectOne(page, para);
const before = await lineRights(page, para);
expect(before.length, "paragraph has multiple lines").toBeGreaterThan(1);
await clickArrange(page, "v2-align-right");
await page.waitForTimeout(300);
const after = await lineRights(page, para);
expect(
Math.max(...after) - Math.min(...after),
"all lines share a right edge",
).toBeLessThan(1.5);
// Undo restores the original per-line right edges.
await page.getByTestId("v2-undo").click();
await page.waitForTimeout(300);
const reverted = await lineRights(page, para);
for (let i = 0; i < before.length; i++) {
expect(reverted[i]).toBeCloseTo(before[i], 0);
}
});
test("align-left flushes a paragraph's lines to a shared left edge", async ({
page,
}) => {
await open(page, 1);
const para = await runId(page, 1, "Comprehensive\\s+toolkit");
await selectOne(page, para);
const before = await lineLefts(page, para);
expect(before.length).toBeGreaterThan(1);
await clickArrange(page, "v2-align-left");
await page.waitForTimeout(300);
const after = await lineLefts(page, para);
expect(
Math.max(...after) - Math.min(...after),
"all lines share a left edge",
).toBeLessThan(1.5);
});
});
test.describe("v2 editor - reported issue: character insertion + font integrity", () => {
// Editor edits fire encode-charcodes; with no backend in the stubbed project
// an UNMOCKED call 401s and redirects to login (unmounting the editor mid-
// edit). Abort it so the resolver sees a clean cold-cache miss - the exact
// path these tests exercise (font reuse via SetText / the single-char
// content-stream fallback).
test.beforeEach(async ({ page }) => {
await page.route("**/encode-charcodes", (route) => route.abort());
});
test("inserting a duplicate letter into an embedded-font run keeps text correct and emits no ydieresis tofu", async ({
page,
}) => {
await open(page, 1);
const id = await runId(page, 1, "Multi-Language\\s+Support");
await appendViaOverlay(page, id, "S");
const text = await runText(page, 1, id);
expect(text, "appended char is present").toMatch(/SupportS\s*$/);
expect(text, "no U+00FF tofu").not.toContain("ÿ");
});
test("inserting into a large heading section keeps text correct and tofu-free", async ({
page,
}) => {
await open(page, 0);
const id = await runId(page, 0, "Adobe\\s+Acrobat\\s+Alternative");
const before = await runText(page, 0, id);
await appendViaOverlay(page, id, "X");
const after = await runText(page, 0, id);
expect(after.length, "text grew by the inserted char").toBeGreaterThan(
before.length,
);
expect(after).toContain("X");
expect(after).not.toContain("ÿ");
});
test("inserting a character that already exists elsewhere in the run is tofu-free", async ({
page,
}) => {
await open(page, 1);
const id = await runId(page, 1, "Open\\s+Source");
// 'p' is not in "Open Source"; 'e'/'o'/'r'/'S' are. Insert an 'e'.
await appendViaOverlay(page, id, "e");
const text = await runText(page, 1, id);
expect(text).toMatch(/e\s*$/);
expect(text).not.toContain("ÿ");
});
test("inserting a duplicate char into a non-subset font reuses the embedded glyph via SetText, not the content-stream guess", async ({
page,
}) => {
// "Multi-Language Support" uses a NON-SUBSET embedded font. For those,
// FPDFText_SetText's reverse Unicode->charcode lookup works, so the
// inserted 'S' reuses the embedded glyph directly. The content-stream
// GUESS (sequential CID by page order) is gated OFF for non-subset fonts:
// it picks valid-but-wrong glyphs on re-encoded fonts (the paragraph
// scramble), and its advance self-check can't catch a same-width wrong
// glyph. So no content-stream charcode write must happen here - the result
// is the correct glyph via SetText, never a guessed one.
await open(page, 1);
const id = await runId(page, 1, "Multi-Language\\s+Support");
await page.evaluate(
() => ((window as unknown as V2TestWindow).__v2_charcode_events = []),
);
await appendViaOverlay(page, id, "S");
const outcomes = await page.evaluate(
() =>
((window as unknown as V2TestWindow).__v2_charcode_events ?? []).map(
(e) => `${e.strategy}:${e.outcome}`,
) as string[],
);
expect(
outcomes,
`non-subset font must not use the content-stream guess; got ${JSON.stringify(outcomes)}`,
).not.toContain("content-stream:charcodes-ok");
const text = await runText(page, 1, id);
expect(text, "appended char is present").toMatch(/SupportS\s*$/);
expect(text, "no U+00FF tofu").not.toContain("ÿ");
});
test("character insertion telemetry records an emit attempt (font-reuse vs fallback)", async ({
page,
}) => {
// The window telemetry buffer records the outcome of every emit. We
// assert an emit happened and (in the no-backend stubbed env) it is one
// of the known outcomes - documenting that the path runs without error.
await open(page, 1);
const id = await runId(page, 1, "Multi-Language\\s+Support");
await page.evaluate(
() =>
((window as unknown as V2TestWindow).__v2_charcode_events =
[]) as unknown as void,
);
await appendViaOverlay(page, id, "S");
const outcomes = await page.evaluate(
() =>
((window as unknown as V2TestWindow).__v2_charcode_events ?? []).map(
(e) => e.outcome,
) as string[],
);
// At least one emit event fired for the edit.
expect(outcomes.length).toBeGreaterThan(0);
const known = [
"charcodes-ok",
"charcodes-call-failed",
"partial-coverage-fallback",
"no-strategy",
"no-font",
];
for (const o of outcomes) expect(known).toContain(o);
});
});
test.describe("v2 editor - reported issue: bullet-to-item mapping", () => {
async function loadPage2(page: Page): Promise<void> {
await open(page, 0);
await page.evaluate(() => {
document.querySelector('[data-testid="v2-page-1"]')?.scrollIntoView();
document.querySelector('[data-testid="v2-page-2"]')?.scrollIntoView();
});
await expect(page.getByTestId("v2-page-2")).toBeVisible({
timeout: 30_000,
});
await page.waitForTimeout(2000);
}
// FIXED by the LineGrouper rework (font-scaled sort band + bullet-indent
// gap): bullets now attach to their list items instead of forming an
// orphan stacked bullet-only run.
test("bullets attach to their list items (not an orphan bullet-only run)", async ({
page,
}) => {
await loadPage2(page);
const hasOrphanBulletRun = await page.evaluate(() => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
const runs = s.doc.page(2).runs as Array<{ text: string }>;
// An "orphan" run is one whose text is ONLY bullets + whitespace
// and holds 2+ bullets (the stacked bullet column).
return runs.some(
(r) =>
/^[\s•]+$/.test(r.text) && (r.text.match(/•/g) ?? []).length >= 2,
);
});
expect(
hasOrphanBulletRun,
"bullets should attach to items, not form a stacked bullet-only run",
).toBe(false);
});
});
@@ -1,132 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page, Route } from "@playwright/test";
import path from "path";
import type { V2TestWindow } from "@app/tests/stubbed/v2EditorTestTypes";
/**
* Editing OBJECT-rotated text (a text run whose matrix is rotated within an
* upright page) must keep the rotation, not force the re-emitted glyphs upright
* (finding N). The fixture's "Rotated" run is at 30 degrees (matrix b ~ 0.5).
*
* Backend-free: encode-charcodes aborted so the edit takes the client emit path.
*/
const ROTATED = path.join(
import.meta.dirname,
"../test-fixtures/rotated-text-sample.pdf",
);
const ROTATE90 = path.join(
import.meta.dirname,
"../test-fixtures/cropbox-rotate90.pdf",
);
async function rotatedRunMatrix(page: Page): Promise<{ a: number; b: number }> {
return page.evaluate(() => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
const r = s.doc.page(0).runs.find((x) => /Rotated/.test(x.text));
return r ? { a: r.matrix.a, b: r.matrix.b } : { a: 1, b: 0 };
});
}
test("editing rotated text keeps its rotation through save+reopen", async ({
page,
}: {
page: Page;
}) => {
test.setTimeout(120_000);
const errs: string[] = [];
page.on("pageerror", (e) => errs.push(e.message));
await page.route("**/encode-charcodes", (route: Route) => route.abort());
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 20_000 });
await page.locator('[data-testid="v2-file-input"]').setInputFiles(ROTATED);
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(500);
// Sanity: the run loaded rotated (b is the sin component ~0.5).
const before = await rotatedRunMatrix(page);
expect(Math.abs(before.b)).toBeGreaterThan(0.3);
// Edit the run, then commit (blur).
const id = await page.evaluate(() => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
const r = s.doc.page(0).runs.find((x) => /Rotated/.test(x.text));
return r ? r.id : null;
});
expect(id, "rotated run found").toBeTruthy();
await page.evaluate((rid: string) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="v2-run-${rid}"]`,
)!;
el.focus();
const sel = window.getSelection()!;
const range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, "X");
}, id as string);
await page.waitForTimeout(200);
await page.evaluate((rid: string) => {
document
.querySelector<HTMLElement>(`[data-testid="v2-run-${rid}"]`)
?.blur();
}, id as string);
await page.waitForTimeout(1000);
// Save + reopen, then confirm the run is STILL rotated (not forced upright).
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("v2-save").click();
const dl = await downloadPromise;
const stream = await dl.createReadStream();
const chunks: Buffer[] = [];
for await (const c of stream) chunks.push(c as Buffer);
await page.locator('[data-testid="v2-file-input"]').setInputFiles({
name: "round-trip.pdf",
mimeType: "application/pdf",
buffer: Buffer.concat(chunks),
});
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(500);
const after = await rotatedRunMatrix(page);
expect(
Math.abs(after.b),
`rotation preserved after edit+save+reopen (matrix.b=${after.b})`,
).toBeGreaterThan(0.3);
expect(errs, `no page errors:\n${errs.join("\n")}`).toEqual([]);
});
test("inserting text on a /Rotate 90 page lands upright (counter-rotated)", async ({
page,
}: {
page: Page;
}) => {
test.setTimeout(90_000);
await page.route("**/encode-charcodes", (route: Route) => route.abort());
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 20_000 });
await page.locator('[data-testid="v2-file-input"]').setInputFiles(ROTATE90);
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(500);
// Enter add-text mode and click the page to drop a new text run.
await page.getByTestId("v2-add-text").click();
await page.getByTestId("v2-page-0").click({ position: { x: 120, y: 90 } });
await page.waitForTimeout(500);
// The inserted run must be counter-rotated so it reads upright on the
// 90deg-displayed page (matrix.b non-zero), not axis-aligned.
const m = await page.evaluate(() => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
const r = s.doc.page(0).runs.find((x) => /New text/.test(x.text));
return r ? { a: r.matrix.a, b: r.matrix.b } : null;
});
expect(m, "inserted run found").toBeTruthy();
expect(
Math.abs(m!.b),
`inserted text counter-rotated for the page (matrix=${JSON.stringify(m)})`,
).toBeGreaterThan(0.5);
});
@@ -1,293 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page, Route } from "@playwright/test";
import path from "path";
import type { V2TestWindow } from "@app/tests/stubbed/v2EditorTestTypes";
/**
* Client-side Unicode fallback font (Noto Sans, embedded on demand).
*
* Base-14 PDF fonts only cover Latin-1. The editor embeds Noto Sans (Latin,
* Greek, Cyrillic) via FPDFText_LoadFont so those scripts survive a
* save+reopen round-trip. Scripts the bundled font does NOT cover (CJK, Arabic,
* Hebrew, emoji) are dropped on save - but cleanly: no U+00FF tofu and no lone
* surrogate, and surrounding Latin text is preserved.
*
* Backend-free: encode-charcodes is aborted, so the edit takes the base-14
* re-emit path where the fallback kicks in.
*/
const SAMPLE = path.join(
import.meta.dirname,
"../../../../public/samples/Sample.pdf",
);
// Scripts the bundled Noto Sans covers - these survive a round-trip.
const COVERED = [{ name: "Cyrillic", text: "Привет" }];
// Scripts the bundled font lacks - dropped cleanly (no tofu) on save.
const UNCOVERED = [
{ name: "CJK", text: "日本語" },
{ name: "astral", text: "😀" },
];
// A Latin anchor from Sample.pdf's first run, used to prove the surrounding
// text is intact after an uncovered script is dropped.
const LATIN_ANCHOR = "Acrobat";
const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])/;
async function gotoEditor(page: Page): Promise<Promise<unknown>> {
await page.route("**/encode-charcodes", (route: Route) => route.abort());
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
// Capture the fallback-font fetch (fired on mount) so we can await it before
// editing - the embed is sync and needs the bytes cached.
const fontLoaded = page
.waitForResponse((r) => /NotoSans-Regular\.ttf/.test(r.url()), {
timeout: 20_000,
})
.catch(() => null);
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 20_000 });
return fontLoaded;
}
// Load SAMPLE, append `text` to the first run, blur, save, and reopen the
// produced bytes. Returns the reopened page-0 model text plus any page errors.
async function appendSaveReopen(
page: Page,
text: string,
): Promise<{ reopened: string; errs: string[]; runId: string }> {
const errs: string[] = [];
page.on("pageerror", (e) => errs.push(e.message));
const fontLoaded = await gotoEditor(page);
await page.locator('[data-testid="v2-file-input"]').setInputFiles(SAMPLE);
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
await fontLoaded; // bytes cached before we edit
await page.waitForTimeout(400);
// Append the sample text to the first run and commit (blur).
const id = await page.evaluate(() => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
return s.doc.page(0).runs[0]?.id ?? null;
});
expect(id, "page 0 has at least one run").toBeTruthy();
await page.evaluate(
({ rid, txt }: { rid: string; txt: string }) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="v2-run-${rid}"]`,
)!;
el.focus();
const sel = window.getSelection()!;
const range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, " " + txt);
},
{ rid: id as string, txt: text },
);
await page.waitForTimeout(200);
await page.evaluate((rid: string) => {
document
.querySelector<HTMLElement>(`[data-testid="v2-run-${rid}"]`)
?.blur();
}, id as string);
await page.waitForTimeout(1000);
// Save, then reopen the produced bytes.
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("v2-save").click();
const dl = await downloadPromise;
const stream = await dl.createReadStream();
const chunks: Buffer[] = [];
for await (const c of stream) chunks.push(c as Buffer);
const saved = Buffer.concat(chunks);
await page.locator('[data-testid="v2-file-input"]').setInputFiles({
name: "round-trip.pdf",
mimeType: "application/pdf",
buffer: saved,
});
await expect(page.locator('[data-testid^="v2-run-p0-"]').first()).toBeVisible(
{ timeout: 30_000 },
);
await page.waitForTimeout(500);
const reopened = await page.evaluate(() => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
return s.doc
.page(0)
.runs.map((r) => r.text)
.join("");
});
return { reopened, errs, runId: id as string };
}
for (const { name, text } of COVERED) {
test(`non-Latin (${name}) survives a save+reopen via the embedded fallback font`, async ({
page,
}) => {
test.setTimeout(120_000);
const { reopened, errs } = await appendSaveReopen(page, text);
// The reopened document must still carry the text (embedded, not dropped).
expect(reopened).toContain(text);
expect(errs, `no page errors:\n${errs.join("\n")}`).toEqual([]);
});
}
for (const { name, text } of UNCOVERED) {
test(`non-Latin (${name}) is dropped cleanly (no tofu) when the fallback lacks it`, async ({
page,
}) => {
test.setTimeout(120_000);
const { reopened, errs } = await appendSaveReopen(page, text);
// The bundled font lacks this script, so it is dropped on save - but
// without injecting U+00FF tofu or a lone surrogate, and the original
// Latin text must remain intact.
expect(reopened).not.toContain(text);
expect(reopened).not.toContain("ÿ");
expect(LONE_SURROGATE.test(reopened)).toBe(false);
expect(reopened).toContain(LATIN_ANCHOR);
expect(errs, `no page errors:\n${errs.join("\n")}`).toEqual([]);
});
}
/**
* RTL / bidi insertion.
*
* RTL scripts (Arabic, Hebrew) need the Noto fallback since base-14 lacks them.
* The editor positions runs by left-x/advance, so RTL/bidi is a classic source
* of caret/bounds/save-order bugs. These assert model correctness, an in-bounds
* run, save+reopen survival, and logical character order for a bidi mix.
*/
const RTL_SAMPLES = [
{ name: "Arabic", text: "مرحبا" },
{ name: "Hebrew", text: "שלום" },
];
for (const { name, text } of RTL_SAMPLES) {
test(`RTL (${name}) insert: model, in-bounds run, save+reopen`, async ({
page,
}) => {
test.setTimeout(120_000);
// Read the edited run's bounds before save so we can check it stays on page.
const errs: string[] = [];
page.on("pageerror", (e) => errs.push(e.message));
const fontLoaded = await gotoEditor(page);
await page.locator('[data-testid="v2-file-input"]').setInputFiles(SAMPLE);
await expect(page.getByTestId("v2-page-0")).toBeVisible({
timeout: 30_000,
});
await fontLoaded;
await page.waitForTimeout(400);
const id = await page.evaluate(() => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
return s.doc.page(0).runs[0]?.id ?? null;
});
expect(id, "page 0 has at least one run").toBeTruthy();
await page.evaluate(
({ rid, txt }: { rid: string; txt: string }) => {
const el = document.querySelector<HTMLDivElement>(
`[data-testid="v2-run-${rid}"]`,
)!;
el.focus();
const sel = window.getSelection()!;
const range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("insertText", false, " " + txt);
},
{ rid: id as string, txt: text },
);
await page.waitForTimeout(200);
await page.evaluate((rid: string) => {
document
.querySelector<HTMLElement>(`[data-testid="v2-run-${rid}"]`)
?.blur();
}, id as string);
await page.waitForTimeout(1000);
// (a) model text carries the inserted RTL string.
const model = await page.evaluate((rid: string) => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
return s.doc.page(0).runs.find((r) => r.id === rid)?.text ?? "";
}, id as string);
expect(model).toContain(text);
// (b) the edited run stays within page bounds after the edit.
const fits = await page.evaluate((rid: string) => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
const pg = s.doc.page(0);
const r = pg.runs.find((x) => x.id === rid)!;
return { boundsRight: r.bounds.x + r.bounds.width, pageWidth: pg.width };
}, id as string);
expect(
fits.boundsRight,
"RTL run must not extend past the page width",
).toBeLessThanOrEqual(fits.pageWidth + 2);
// (c) save+reopen preserves the text.
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("v2-save").click();
const dl = await downloadPromise;
const stream = await dl.createReadStream();
const chunks: Buffer[] = [];
for await (const c of stream) chunks.push(c as Buffer);
const saved = Buffer.concat(chunks);
await page.locator('[data-testid="v2-file-input"]').setInputFiles({
name: "rtl-round-trip.pdf",
mimeType: "application/pdf",
buffer: saved,
});
await expect(
page.locator('[data-testid^="v2-run-p0-"]').first(),
).toBeVisible({ timeout: 30_000 });
await page.waitForTimeout(500);
const reopened = await page.evaluate(() => {
const s = (window as unknown as V2TestWindow).__v2_editor_store;
return s.doc
.page(0)
.runs.map((r) => r.text)
.join("");
});
// Noto Sans lacks Arabic/Hebrew, so the script is dropped on save - but
// cleanly (no U+00FF tofu) with the Latin content preserved.
expect(reopened).not.toContain(text);
expect(reopened).not.toContain("ÿ");
expect(reopened).toContain(LATIN_ANCHOR);
expect(errs, `no page errors:\n${errs.join("\n")}`).toEqual([]);
});
}
test("bidi mix preserves logical character order in the model", async ({
page,
}) => {
test.setTimeout(120_000);
// Logical order is the order the characters are typed, not the visual order.
const BIDI = "abc مرحبا 123";
const { reopened, errs } = await appendSaveReopen(page, BIDI);
// The Arabic span is dropped (no Noto coverage), but the covered Latin/digit
// parts survive in logical order without tofu or reordering.
expect(reopened).not.toContain("مرحبا");
expect(reopened).not.toContain("ÿ");
expect(reopened).toContain("abc");
expect(reopened).toContain("123");
expect(reopened.indexOf("abc")).toBeLessThan(reopened.indexOf("123"));
expect(errs, `no page errors:\n${errs.join("\n")}`).toEqual([]);
});
File diff suppressed because it is too large Load Diff
@@ -1,142 +0,0 @@
/**
* Structural test-only types for the v2 PDF text editor Playwright specs.
*
* These describe ONLY the members the stubbed specs touch on the window-exposed
* `__v2_editor_store` (and friends). They are deliberately not the real
* `EditorStore`/`PdfDocument` classes - those have private members the specs
* cannot reach - so this is a minimal structural view used for annotations
* inside `page.evaluate` closures.
*/
/** Affine matrix on runs/images. */
export interface V2Matrix {
a: number;
b: number;
c: number;
d: number;
e?: number;
f?: number;
}
/** Axis-aligned bounds; `right` appears on per-line merged bounds. */
export interface V2Bounds {
x: number;
y: number;
width: number;
height: number;
right: number;
}
export interface V2LineSlot {
mergedFromBounds: V2Bounds[];
}
export interface V2Run {
id: string;
text: string;
locked: boolean;
fontId: string;
fontSize: number;
fontSubset: boolean;
matrix: V2Matrix;
bounds: V2Bounds;
pdfiumObjPtr: number;
paragraphLeafPtrs: number[];
mergedFromPtrs: number[];
paragraphLineSlots?: V2LineSlot[];
}
export interface V2Image {
id: string;
locked: boolean;
matrix: V2Matrix;
}
export interface V2Page {
pageIndex: number;
pagePtr: number;
width: number;
runs: V2Run[];
images: V2Image[];
flushGenerate(module: V2PdfiumModule): void;
}
export interface V2Doc {
module: V2PdfiumModule;
page(idx: number): V2Page;
loadedPages(): V2Page[];
}
export interface V2SelectionValue {
runIds: string[];
imageIds: string[];
}
export interface V2Selection {
selectOne(id: string): void;
selectMany(ids: string[]): void;
selectImage(id: string): void;
clear(): void;
value: V2SelectionValue;
}
export interface V2HistorySize {
undo: number;
redo: number;
}
export interface V2History {
size(): V2HistorySize;
}
export interface V2EditorStore {
doc: V2Doc;
selection: V2Selection;
history: V2History;
resetAll(): void;
}
/** Minimal PDFium WASM surface the specs poke directly. */
export interface V2PdfiumExports {
malloc(size: number): number;
free(ptr: number): void;
}
export interface V2PdfiumRuntime {
wasmExports: V2PdfiumExports;
getValue(ptr: number, type: string): number;
}
export interface V2PdfiumModule {
pdfium: V2PdfiumRuntime;
FPDFText_LoadPage(pagePtr: number): number;
FPDFText_ClosePage(textPagePtr: number): void;
FPDFPageObj_GetBounds(
ptr: number,
left: number,
bottom: number,
right: number,
top: number,
): number;
FPDFPageObj_GetMatrix(ptr: number, matrixPtr: number): number;
FPDFTextObj_GetText(
ptr: number,
textPagePtr: number,
buf: number,
len: number,
): number;
}
/** Telemetry buffer entry mirrored onto the window during edits. */
export interface V2CharcodeEvent {
outcome: string;
strategy?: string;
text?: string;
resolved?: number[];
}
/** The window globals the specs read inside `page.evaluate` closures. */
export interface V2TestWindow {
__v2_editor_store: V2EditorStore;
__v2_charcode_events?: V2CharcodeEvent[];
}
@@ -1,33 +0,0 @@
%PDF-1.4
%âãÏÓ
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [ 0 0 400 400 ] /CropBox [ 0 0 400 400 ] /Rotate 0 /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>
endobj
4 0 obj
<< /Length 33 >>
stream
BT /F1 24 Tf 60 350 Td (Hi) Tj ET
endstream
endobj
5 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
xref
0 6
0000000000 65535 f
0000000015 00000 n
0000000064 00000 n
0000000121 00000 n
0000000284 00000 n
0000000367 00000 n
trailer
<< /Size 6 /Root 1 0 R >>
startxref
437
%%EOF
@@ -1,33 +0,0 @@
%PDF-1.4
%âãÏÓ
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [ 0 0 400 400 ] /CropBox [ 50 30 350 380 ] /Rotate 0 /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>
endobj
4 0 obj
<< /Length 33 >>
stream
BT /F1 24 Tf 60 350 Td (Hi) Tj ET
endstream
endobj
5 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
xref
0 6
0000000000 65535 f
0000000015 00000 n
0000000064 00000 n
0000000121 00000 n
0000000286 00000 n
0000000369 00000 n
trailer
<< /Size 6 /Root 1 0 R >>
startxref
439
%%EOF
@@ -1,33 +0,0 @@
%PDF-1.4
%âãÏÓ
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [ 0 0 400 400 ] /CropBox [ 50 30 350 380 ] /Rotate 90 /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>
endobj
4 0 obj
<< /Length 33 >>
stream
BT /F1 24 Tf 60 350 Td (Hi) Tj ET
endstream
endobj
5 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
xref
0 6
0000000000 65535 f
0000000015 00000 n
0000000064 00000 n
0000000121 00000 n
0000000287 00000 n
0000000370 00000 n
trailer
<< /Size 6 /Root 1 0 R >>
startxref
440
%%EOF
@@ -1,52 +0,0 @@
import process from "node:process";
// One-off script: generate `big-sample.pdf`, an 80-page synthetic PDF
// with a few hundred text objects per page. Exercises the loading
// overlay (visible for several seconds on cold load) and the lazy
// page reader. Not heavy on disk (~ a few hundred KB) but heavy enough
// on parse + extract time to surface a UI freeze if one returns.
//
// Run with: node generate-big-sample.mjs
import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { PDFDocument, StandardFonts, rgb } from "@cantoo/pdf-lib";
const __dirname = dirname(fileURLToPath(import.meta.url));
async function main() {
const doc = await PDFDocument.create();
const font = await doc.embedFont(StandardFonts.Helvetica);
const PAGES = 80;
const LINES_PER_PAGE = 80;
for (let p = 0; p < PAGES; p++) {
const page = doc.addPage([612, 792]);
page.drawText(`Page ${p + 1} of ${PAGES}`, {
x: 50,
y: 740,
size: 22,
font,
color: rgb(0, 0, 0),
});
for (let l = 0; l < LINES_PER_PAGE; l++) {
page.drawText(
`Line ${l + 1} on page ${p + 1}: sample body content for paragraph clustering.`,
{
x: 50,
y: 700 - l * 18,
size: 11,
font,
color: rgb(0, 0, 0),
},
);
}
}
const out = await doc.save();
const target = join(__dirname, "big-sample.pdf");
writeFileSync(target, out);
console.log(`wrote ${target} (${out.length} bytes, ${PAGES} pages)`);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
@@ -1,70 +0,0 @@
#!/usr/bin/env python3
"""Generate minimal synthetic PDFs for the v2 editor CropBox/rotation tests.
These are hand-authored fixtures (NOT spirit-sx, which must never be committed).
Each has one page with a single Helvetica text object "Hi" at a known user-space
baseline, a MediaBox, and a CropBox whose origin is deliberately offset from the
MediaBox so the editor's display transform is exercised. Run from this dir:
python generate-cropbox-fixtures.py
"""
def build_pdf(media, crop, rotate, text, tx, ty, font_size=24):
"""Return bytes of a 1-page PDF. media/crop are [x0,y0,x1,y1]; text drawn
at Td(tx,ty) in user space with Helvetica."""
objs = []
objs.append(b"<< /Type /Catalog /Pages 2 0 R >>")
objs.append(b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>")
page = (
b"<< /Type /Page /Parent 2 0 R "
+ b"/MediaBox [ %d %d %d %d ] " % tuple(media)
+ b"/CropBox [ %d %d %d %d ] " % tuple(crop)
+ b"/Rotate %d " % rotate
+ b"/Resources << /Font << /F1 5 0 R >> >> "
+ b"/Contents 4 0 R >>"
)
objs.append(page)
stream = (
b"BT /F1 %d Tf %d %d Td (%s) Tj ET"
% (font_size, tx, ty, text.encode("ascii"))
)
objs.append(b"<< /Length %d >>\nstream\n" % len(stream) + stream + b"\nendstream")
objs.append(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")
out = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")
offsets = [0]
for i, body in enumerate(objs, start=1):
offsets.append(len(out))
out += b"%d 0 obj\n" % i + body + b"\nendobj\n"
xref_pos = len(out)
out += b"xref\n0 %d\n" % (len(objs) + 1)
out += b"0000000000 65535 f \n"
for off in offsets[1:]:
out += b"%010d 00000 n \n" % off
out += (
b"trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n"
% (len(objs) + 1, xref_pos)
)
return bytes(out)
def main():
# (A) Control: CropBox == MediaBox, Rotate 0. Must behave like today.
open("cropbox-control.pdf", "wb").write(
build_pdf([0, 0, 400, 400], [0, 0, 400, 400], 0, "Hi", 60, 350)
)
# (B) CropBox origin offset (50,30); visible page is 300x350 portrait.
# Text baseline user-space (60,350) -> display (10,320).
open("cropbox-offset.pdf", "wb").write(
build_pdf([0, 0, 400, 400], [50, 30, 350, 380], 0, "Hi", 60, 350)
)
# (C) CropBox offset + Rotate 90. Displayed page swaps to 350x300.
open("cropbox-rotate90.pdf", "wb").write(
build_pdf([0, 0, 400, 400], [50, 30, 350, 380], 90, "Hi", 60, 350)
)
print("wrote cropbox-control.pdf, cropbox-offset.pdf, cropbox-rotate90.pdf")
if __name__ == "__main__":
main()
@@ -1,68 +0,0 @@
import process from "node:process";
// One-off script: generate `form-xobject-sample.pdf`, a synthetic
// magazine-style PDF whose page content lives inside a Form XObject.
// This mirrors the structural pattern InDesign / professional layout
// tools emit (e.g. PC Magazin issues) so the editor's recursive text
// extractor can be regression-tested without shipping a copyrighted
// binary fixture.
//
// Run with: node generate-form-xobject-sample.mjs
//
// The output is checked into test-fixtures/ and consumed by
// pdf-text-editor-v2.spec.ts under the "form xobject recursion" group.
import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { PDFDocument, StandardFonts, rgb } from "@cantoo/pdf-lib";
const __dirname = dirname(fileURLToPath(import.meta.url));
async function main() {
const srcDoc = await PDFDocument.create();
const helv = await srcDoc.embedFont(StandardFonts.Helvetica);
const srcPage = srcDoc.addPage([400, 200]);
srcPage.drawText("Magazine cover title", {
x: 30,
y: 150,
size: 24,
font: helv,
color: rgb(0, 0, 0),
});
srcPage.drawText("Subheading line below", {
x: 30,
y: 110,
size: 14,
font: helv,
color: rgb(0.2, 0.2, 0.2),
});
srcPage.drawText("Inner body paragraph one.", {
x: 30,
y: 80,
size: 11,
font: helv,
color: rgb(0, 0, 0),
});
srcPage.drawText("Inner body paragraph two.", {
x: 30,
y: 60,
size: 11,
font: helv,
color: rgb(0, 0, 0),
});
const srcBytes = await srcDoc.save();
const dstDoc = await PDFDocument.create();
const [embedded] = await dstDoc.embedPdf(srcBytes);
const dstPage = dstDoc.addPage([400, 200]);
dstPage.drawPage(embedded, { x: 0, y: 0, width: 400, height: 200 });
const out = await dstDoc.save();
const target = join(__dirname, "form-xobject-sample.pdf");
writeFileSync(target, out);
console.log(`wrote ${target} (${out.length} bytes)`);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
@@ -1,55 +0,0 @@
import process from "node:process";
// One-off script: generate `paragraph-sample.pdf`, a synthetic PDF
// whose page contains a multi-line body paragraph with consistent
// font/size/colour/left-margin. ParagraphGrouper should fold all four
// lines into one editable block.
//
// Run with: node generate-paragraph-sample.mjs
import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { PDFDocument, StandardFonts, rgb } from "@cantoo/pdf-lib";
const __dirname = dirname(fileURLToPath(import.meta.url));
async function main() {
const doc = await PDFDocument.create();
const font = await doc.embedFont(StandardFonts.Helvetica);
const page = doc.addPage([400, 300]);
const left = 30;
const lineHeight = 16;
let y = 260;
page.drawText("Heading in a bigger size", {
x: left,
y,
size: 18,
font,
color: rgb(0, 0, 0),
});
y -= 36;
const bodyLines = [
"First line of the body paragraph that we want grouped together.",
"Second line continues the paragraph and shares the same font and",
"left margin so the grouper recognises it as part of the block.",
"Fourth line wraps the paragraph at the bottom of the column.",
];
for (const text of bodyLines) {
page.drawText(text, {
x: left,
y,
size: 11,
font,
color: rgb(0, 0, 0),
});
y -= lineHeight;
}
const out = await doc.save();
const target = join(__dirname, "paragraph-sample.pdf");
writeFileSync(target, out);
console.log(`wrote ${target} (${out.length} bytes)`);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
@@ -1,54 +0,0 @@
#!/usr/bin/env python3
"""Generate rotated-text-sample.pdf: one page with a single text object whose
text matrix is rotated 30 degrees (an OBJECT rotation, not a page /Rotate).
Used to verify the editor preserves a run's rotation when it re-emits the text
on edit (instead of forcing it upright).
"""
import math
def build() -> bytes:
cos = math.cos(math.radians(30))
sin = math.sin(math.radians(30))
stream = (
f"BT /F1 24 Tf {cos:.5f} {sin:.5f} {-sin:.5f} {cos:.5f} 200 400 Tm "
f"(Rotated) Tj ET"
).encode("ascii")
objs: list[bytes] = []
objs.append(b"<< /Type /Catalog /Pages 2 0 R >>")
objs.append(b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>")
objs.append(
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
b"/Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>"
)
objs.append(
b"<< /Length " + str(len(stream)).encode() + b" >>\nstream\n" + stream + b"\nendstream"
)
objs.append(
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"
)
out = bytearray(b"%PDF-1.7\n%\xe2\xe3\xcf\xd3\n")
offsets: list[int] = []
for i, body in enumerate(objs, start=1):
offsets.append(len(out))
out += str(i).encode() + b" 0 obj\n" + body + b"\nendobj\n"
xref_pos = len(out)
n = len(objs) + 1
out += b"xref\n0 " + str(n).encode() + b"\n0000000000 65535 f \n"
for off in offsets:
out += ("%010d 00000 n \n" % off).encode()
out += (
b"trailer\n<< /Size " + str(n).encode() + b" /Root 1 0 R >>\n"
b"startxref\n" + str(xref_pos).encode() + b"\n%%EOF"
)
return bytes(out)
if __name__ == "__main__":
data = build()
with open("rotated-text-sample.pdf", "wb") as f:
f.write(data)
print(f"wrote rotated-text-sample.pdf ({len(data)} bytes)")
@@ -1,67 +0,0 @@
#!/usr/bin/env python3
"""Generate signed-sample.pdf: a 1-page PDF carrying a digital-signature field.
PDFium's FPDF_GetSignatureCount counts AcroForm fields of /FT /Sig that have a
/V signature dictionary, so the editor's pre-save warning can flag it. The
signature bytes are a placeholder - the point is detection, not validity.
"""
import struct # noqa: F401 (kept for parity with sibling generators)
def build() -> bytes:
objs: list[bytes] = []
# 1: Catalog with an AcroForm referencing the signature field.
objs.append(
b"<< /Type /Catalog /Pages 2 0 R "
b"/AcroForm << /Fields [5 0 R] /SigFlags 3 >> >>"
)
# 2: Pages
objs.append(b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>")
# 3: Page (the widget annotation is the signature field itself)
objs.append(
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
b"/Resources << >> /Contents 4 0 R /Annots [5 0 R] >>"
)
# 4: empty content stream
stream = b"BT /F1 12 Tf 72 720 Td (Signed sample) Tj ET"
objs.append(
b"<< /Length " + str(len(stream)).encode() + b" >>\nstream\n" + stream + b"\nendstream"
)
# 5: signature field + widget annotation
objs.append(
b"<< /FT /Sig /Type /Annot /Subtype /Widget /T (Signature1) "
b"/Rect [72 700 272 740] /P 3 0 R /V 6 0 R /F 132 >>"
)
# 6: signature dictionary
objs.append(
b"<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached "
b"/Name (Test Signer) /M (D:20260101000000Z) "
b"/ByteRange [0 0 0 0] /Contents <0000> >>"
)
header = b"%PDF-1.6\n%\xe2\xe3\xcf\xd3\n"
out = bytearray(header)
offsets: list[int] = []
for i, body in enumerate(objs, start=1):
offsets.append(len(out))
out += str(i).encode() + b" 0 obj\n" + body + b"\nendobj\n"
xref_pos = len(out)
n = len(objs) + 1
out += b"xref\n0 " + str(n).encode() + b"\n"
out += b"0000000000 65535 f \n"
for off in offsets:
out += ("%010d 00000 n \n" % off).encode()
out += (
b"trailer\n<< /Size " + str(n).encode() + b" /Root 1 0 R >>\n"
b"startxref\n" + str(xref_pos).encode() + b"\n%%EOF"
)
return bytes(out)
if __name__ == "__main__":
data = build()
with open("signed-sample.pdf", "wb") as f:
f.write(data)
print(f"wrote signed-sample.pdf ({len(data)} bytes)")
@@ -1,77 +0,0 @@
#!/usr/bin/env python3
"""One-off generator for `subset-font-sample.pdf`.
This fixture exercises the v2 editor's subset-font fallback branch
(`canReuseFont = ... && !run.fontSubset`). The editor flags a run as a
subset font only when PDFium's FPDFFont_GetFamilyName returns a name
matching /^[A-Z]{6}\\+/ - and PDFium reads that name from the embedded
font program's `name` table, NOT the PDF BaseFont entry. Plain pdf-lib /
fontTools subsetting only tags the BaseFont, so we must also rewrite the
embedded font's name table to carry the 6-letter "ABCDEF+" subset tag.
Run with: pip install pymupdf fonttools && python generate-subset-font-sample.py
Source font: @embedpdf/fonts-latin NotoSans-Regular.ttf (already a repo dep).
"""
import os
from fontTools.ttLib import TTFont
from fontTools.subset import Subsetter, Options
import fitz # PyMuPDF
HERE = os.path.dirname(os.path.abspath(__file__))
SRC_FONT = os.path.join(
HERE,
"../../../../../node_modules/@embedpdf/fonts-latin/fonts/NotoSans-Regular.ttf",
)
OUT = os.path.join(HERE, "subset-font-sample.pdf")
TAG = "ABCDEF+"
LINES = [
"Subset font sample line one",
"Body text with embedded subset glyphs",
"Editing this run must fall back cleanly",
]
def make_named_subset(tmp_path: str) -> None:
font = TTFont(SRC_FONT)
opt = Options()
opt.name_IDs = ["*"]
ss = Subsetter(options=opt)
ss.populate(text="".join(LINES))
ss.subset(font)
# Stamp the subset tag into the font program's own name table so PDFium
# surfaces it via FPDFFont_GetFamilyName (Windows 3,1 + Mac 1,0 records).
name = font["name"]
for pid, eid, lid in [(3, 1, 0x409), (1, 0, 0)]:
name.setName(TAG + "NotoSubset", 1, pid, eid, lid) # family
name.setName("Regular", 2, pid, eid, lid) # subfamily
name.setName(TAG + "NotoSubset", 4, pid, eid, lid) # full
name.setName(TAG + "NotoSubset", 6, pid, eid, lid) # postscript
font.save(tmp_path)
font.close()
def main() -> None:
tmp = os.path.join(HERE, "_noto-subset-named.ttf")
make_named_subset(tmp)
try:
doc = fitz.open()
page = doc.new_page(width=420, height=220)
# set_simple=True -> simple (non-CID) TrueType, so PDFium reports the
# name-table family verbatim (CID fonts get the tag stripped).
page.insert_font(fontname="NS", fontfile=tmp, set_simple=True)
y = 70
for line in LINES:
page.insert_text((36, y), line, fontname="NS", fontsize=14)
y += 30
# Do NOT call doc.subset_fonts(): the font is already subset + renamed.
doc.save(OUT, garbage=4, deflate=True)
doc.close()
print(f"wrote {OUT} ({os.path.getsize(OUT)} bytes)")
finally:
if os.path.exists(tmp):
os.remove(tmp)
if __name__ == "__main__":
main()
@@ -1,33 +0,0 @@
%PDF-1.7
%âãÏÓ
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>
endobj
4 0 obj
<< /Length 72 >>
stream
BT /F1 24 Tf 0.86603 0.50000 -0.50000 0.86603 200 400 Tm (Rotated) Tj ET
endstream
endobj
5 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>
endobj
xref
0 6
0000000000 65535 f
0000000015 00000 n
0000000064 00000 n
0000000121 00000 n
0000000247 00000 n
0000000369 00000 n
trailer
<< /Size 6 /Root 1 0 R >>
startxref
466
%%EOF
@@ -1,37 +0,0 @@
%PDF-1.6
%âãÏÓ
1 0 obj
<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R] /SigFlags 3 >> >>
endobj
2 0 obj
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Contents 4 0 R /Annots [5 0 R] >>
endobj
4 0 obj
<< /Length 44 >>
stream
BT /F1 12 Tf 72 720 Td (Signed sample) Tj ET
endstream
endobj
5 0 obj
<< /FT /Sig /Type /Annot /Subtype /Widget /T (Signature1) /Rect [72 700 272 740] /P 3 0 R /V 6 0 R /F 132 >>
endobj
6 0 obj
<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached /Name (Test Signer) /M (D:20260101000000Z) /ByteRange [0 0 0 0] /Contents <0000> >>
endobj
xref
0 7
0000000000 65535 f
0000000015 00000 n
0000000108 00000 n
0000000165 00000 n
0000000285 00000 n
0000000379 00000 n
0000000503 00000 n
trailer
<< /Size 7 /Root 1 0 R >>
startxref
671
%%EOF
+28 -3
View File
@@ -270,8 +270,29 @@
--grad-banner: linear-gradient(135deg, #0f172a 0%, #111827 50%, #1a1535 100%);
}
/* Always-dark code palette. Not theme-switched. */
:root {
/* Code palette — theme-aware: a light GitHub-style box in light mode, the dark
terminal palette in dark mode. (CodeBlock renders plain text, so only the
base colours are load-bearing; the syntax slots are kept for future Shiki. */
:root,
[data-theme="light"] {
--code-bg: #f6f8fa;
--code-bg-alt: #eef1f4;
--code-bg-header: #eaeef2;
--code-text: #1f2328;
--code-dim: #656d76;
--code-muted: #8c959f;
--code-keyword: #cf222e;
--code-string: #0a3069;
--code-number: #0550ae;
--code-fn: #8250df;
--code-type: #953800;
--code-property: #0550ae;
--code-comment: #6e7781;
--code-border: #d0d7de;
/* Window-chrome traffic-light dots in the code-block header. */
--code-dot: #d0d7de;
}
[data-theme="dark"] {
--code-bg: #0f172a;
--code-bg-alt: #1e293b;
--code-bg-header: #1a2332;
@@ -286,12 +307,16 @@
--code-property: #93c5fd;
--code-comment: #475569;
--code-border: #1e293b;
/* Window-chrome traffic-light dots in the code-block header. */
--code-dot: #475569;
}
/* Radii / typography / motion / spacing / z-index — theme-stable */
:root {
/* Home hero strip navy. Theme-stable by design — the hero keeps this deep
navy in both light and dark (it's a branded surface, like the assistant
header), so it's defined once here rather than in the light/dark blocks. */
--color-hero-navy: #16213e;
--radius-xs: 0.1875rem;
--radius-sm: 0.25rem;
--radius-md: 0.375rem;
@@ -1,556 +0,0 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Alert, Stack } from "@mantine/core";
import { useTranslation } from "react-i18next";
import DescriptionIcon from "@mui/icons-material/DescriptionOutlined";
import { downloadBlob } from "@app/utils/downloadUtils";
import type { BaseToolProps } from "@app/types/tool";
import { useEditorStore } from "@app/tools/pdfTextEditor/v2/hooks/useEditorStore";
import { useDocumentLoader } from "@app/tools/pdfTextEditor/v2/hooks/useDocumentLoader";
import { useAutoLoadFile } from "@app/tools/pdfTextEditor/v2/hooks/useAutoLoadFile";
import { useWorkbenchPin } from "@app/tools/pdfTextEditor/v2/hooks/useWorkbenchPin";
import { useUnsavedChangesGuard } from "@app/tools/pdfTextEditor/v2/hooks/useUnsavedChangesGuard";
import { useEditorTestGlobal } from "@app/tools/pdfTextEditor/v2/hooks/useEditorTestGlobal";
import { useSelectionActions } from "@app/tools/pdfTextEditor/v2/hooks/useSelectionActions";
import { useEditorKeyboardShortcuts } from "@app/tools/pdfTextEditor/v2/hooks/useEditorKeyboardShortcuts";
import { FindBar } from "@app/tools/pdfTextEditor/v2/components/FindBar";
import { HelpOverlay } from "@app/tools/pdfTextEditor/v2/components/HelpOverlay";
import { SaveRiskModal } from "@app/tools/pdfTextEditor/v2/components/SaveRiskModal";
import { PasswordPromptModal } from "@app/tools/pdfTextEditor/v2/components/PasswordPromptModal";
import { EditorTopBar } from "@app/tools/pdfTextEditor/v2/components/EditorTopBar";
import { EditorSidebar } from "@app/tools/pdfTextEditor/v2/components/EditorSidebar";
import { EditorFileInputs } from "@app/tools/pdfTextEditor/v2/components/EditorFileInputs";
import { PageStage } from "@app/tools/pdfTextEditor/v2/components/PageStage";
import { InsertImageCommand } from "@app/tools/pdfTextEditor/v2/commands/InsertImageCommand";
import { InsertTextCommand } from "@app/tools/pdfTextEditor/v2/commands/InsertTextCommand";
import { DisplayTransform } from "@app/tools/pdfTextEditor/v2/model/DisplayTransform";
import { jpegExifOrientation } from "@app/tools/pdfTextEditor/v2/util/jpegOrientation";
import { MergeRunsCommand } from "@app/tools/pdfTextEditor/v2/commands/MergeRunsCommand";
import { UngroupParagraphCommand } from "@app/tools/pdfTextEditor/v2/commands/UngroupParagraphCommand";
import { exportToBlob } from "@app/tools/pdfTextEditor/v2/util/exportPdf";
import {
detectSaveRisks,
hasSaveRisks,
type SaveRisks,
} from "@app/tools/pdfTextEditor/v2/util/documentRisks";
import { preloadFallbackFontBytes } from "@app/tools/pdfTextEditor/v2/util/fallbackFont";
import { visiblePageNumber } from "@app/tools/pdfTextEditor/v2/util/dom";
import type { SelectionState } from "@app/tools/pdfTextEditor/v2/types";
const WORKBENCH_ID = "custom:pdfTextEditorV2" as const;
const WORKBENCH_VIEW_ID = "pdfTextEditorV2Workbench";
const INSERTED_IMAGE_RATIO = 0.4;
export default function PdfTextEditorV2(_props: BaseToolProps) {
const { t } = useTranslation();
const { store, state } = useEditorStore();
const load = useDocumentLoader(store);
const [selection, setSelection] = useState<SelectionState>(
store.selection.value,
);
const [findOpen, setFindOpen] = useState(false);
const [helpOpen, setHelpOpen] = useState(false);
const [openedFileName, setOpenedFileName] = useState<string | null>(null);
useEditorTestGlobal(store);
useUnsavedChangesGuard(state.dirty);
useWorkbenchPin({
workbenchId: WORKBENCH_ID,
workbenchViewId: WORKBENCH_VIEW_ID,
label: t("pdfTextEditorV2.workbenchLabel", "Editor"),
icon: <DescriptionIcon fontSize="small" />,
component: PageStage,
});
useAutoLoadFile(load, setOpenedFileName);
useEffect(() => store.selection.subscribe(setSelection), [store]);
// Warm the Unicode fallback font so a non-Latin edit can embed it instead of
// dropping the glyphs. Fire-and-forget; the emit path degrades gracefully if
// the bytes haven't arrived yet.
useEffect(() => {
void preloadFallbackFontBytes();
}, []);
const sel = useSelectionActions(store);
// Guards against re-entrant saves while a (synchronous) serialize runs.
const savingRef = useRef(false);
// Pending save-risk warning (signatures/XFA) shown before the actual save.
const [saveRisks, setSaveRisks] = useState<SaveRisks | null>(null);
// docPtr the user already acknowledged risks for, so we don't re-nag.
// Keyed by document OBJECT identity + the acked risk SET: the raw docPtr
// is allocator-reused across documents (a later doc could inherit the
// ack), and a risk that APPEARS after the first ack (e.g. chars dropped
// by a later edit) must re-warn.
const ackedRiskRef = useRef<{ doc: object; sig: string } | null>(null);
const doSave = useCallback(async () => {
if (!store.document || savingRef.current) return;
savingRef.current = true;
store.setError(null);
try {
// Yield once so React can paint the disabled/saving state before the
// synchronous PDFium serialize blocks the main thread.
await new Promise((resolve) => setTimeout(resolve, 0));
const { blob, filename } = exportToBlob(store.document, openedFileName);
downloadBlob(blob, filename);
store.markSaved();
} catch (err) {
// Surface the failure instead of silently dropping it - the user
// must not believe a broken save succeeded.
store.setError(err instanceof Error ? err.message : String(err));
} finally {
savingRef.current = false;
}
}, [store, openedFileName]);
const handleSave = useCallback(async () => {
const doc = store.document;
if (!doc || savingRef.current) return;
// Re-evaluate on EVERY save: the ack only covers the exact risk set
// the user saw. A new risk appearing later must warn again.
const risks = detectSaveRisks(doc);
if (hasSaveRisks(risks)) {
const sig = JSON.stringify(risks);
const acked = ackedRiskRef.current;
if (!acked || acked.doc !== doc || acked.sig !== sig) {
setSaveRisks(risks);
return;
}
}
await doSave();
}, [store, doSave]);
const handleConfirmSaveRisk = useCallback(() => {
const doc = store.document;
if (doc) {
ackedRiskRef.current = {
doc,
sig: JSON.stringify(detectSaveRisks(doc)),
};
}
setSaveRisks(null);
void doSave();
}, [store, doSave]);
const handleInsertImage = useCallback(
async (file: File) => {
const doc = store.document;
if (!doc) return;
// Decode via an <img> element rather than createImageBitmap: the latter
// lacks codec support in some environments (and headless Chromium),
// throwing "source image could not be decoded". The <img> path decodes
// anywhere the browser can render the format. Surface failures instead
// of swallowing them so the user isn't left wondering why nothing happened.
let decoded: { data: ImageData; width: number; height: number };
try {
decoded = await decodeImageFile(file);
} catch (err) {
store.setError(
err instanceof Error
? err.message
: t(
"pdfTextEditorV2.error.decodeImage",
"Could not decode the selected image.",
),
);
return;
}
// Keep the original JPEG bytes so the insert embeds them as-is
// (DCTDecode) instead of re-encoding decoded RGBA - far smaller output.
let jpegBytes: Uint8Array | undefined;
if (file.type === "image/jpeg") {
try {
jpegBytes = new Uint8Array(await file.arrayBuffer());
// The <img> decode above APPLIES EXIF orientation; the raw bytes
// don't. Passing rotated bytes through embedded phone photos
// sideways with swapped aspect - use the upright bitmap instead.
if (jpegExifOrientation(jpegBytes) !== 1) jpegBytes = undefined;
} catch {
jpegBytes = undefined; // fall back to the bitmap path
}
}
// The document may have been reloaded while the image decoded; bail
// rather than insert against geometry from the wrong document.
if (store.document !== doc) return;
// Insert onto the page currently in view, read from fresh store state
// (not a stale render closure), so scrolling to page 10 and inserting
// doesn't silently drop the image onto page 1 off-screen.
const pages = store.getState().pages;
const visibleIndex = visiblePageNumber();
const page = pages.find((p) => p.pageIndex === visibleIndex) ?? pages[0];
if (!page) return;
const w = page.width * INSERTED_IMAGE_RATIO;
const h = w * (decoded.height / decoded.width);
// Centre in the VISIBLE (display) page, then invert the CropBox/rotation
// transform to raw PDF space (commands store raw coords). Identity on
// normal pages => unchanged.
const ll = DisplayTransform.fromData(page.display).invert(
(page.width - w) / 2,
(page.height - h) / 2,
);
const cmd = new InsertImageCommand({
pageIndex: page.pageIndex,
rgba: decoded.data.data,
pixelWidth: decoded.width,
pixelHeight: decoded.height,
x: ll.x,
y: ll.y,
width: w,
height: h,
jpegBytes,
});
store.dispatch(cmd);
if (cmd.insertedImageId) {
store.selection.selectImage(cmd.insertedImageId);
} else {
store.setError(
t(
"pdfTextEditorV2.error.insertImage",
"Could not insert the selected image.",
),
);
}
},
[store, t],
);
const handleCopySelected = useCallback(() => {
const ids = store.selection.value.runIds;
if (ids.length === 0) return;
const texts = store
.getState()
.pages.flatMap((p) => p.runs)
.filter((r) => ids.includes(r.id))
.map((r) => r.text);
if (texts.length === 0) return;
// Guard against non-secure contexts where navigator.clipboard is undefined.
if (navigator.clipboard?.writeText) {
void navigator.clipboard.writeText(texts.join("\n")).catch(() => {});
}
}, [store]);
/**
* Ctrl+X: copy the selected runs' text to the clipboard AND remove
* them. Browser's native cut on a contentEditable would just remove
* the text inside the focused run; we want the editor-level
* behaviour: clipboard gets the run text(s), the selected runs are
* deleted as text/image objects. The clipboard write is fire-and-
* forget (no await) so the delete fires immediately even if the
* clipboard API is slow.
*/
const handleCutSelected = useCallback(() => {
handleCopySelected();
sel.deleteSelection();
}, [handleCopySelected, sel]);
/**
* Ctrl+V: read clipboard and create a fresh InsertTextCommand on
* the currently-visible page, positioned in roughly the centre. The
* whole clipboard string (newlines preserved) is inserted as a single
* multi-line text run.
*
* Skipped silently when:
* - no document loaded
* - clipboard API unavailable / permission denied
* - clipboard is empty
* - focus is in a contentEditable run (the browser's default paste
* into the active text run is what the user intends in that case)
*/
const handlePaste = useCallback(
async (stripFormatting: boolean) => {
const doc = store.document;
if (!doc) return;
// Don't hijack the browser paste when the caret is in a text run.
const active = document.activeElement as HTMLElement | null;
if (active && active.isContentEditable) return;
let text: string;
try {
text = await navigator.clipboard.readText();
} catch {
return;
}
if (!text) return;
// `stripFormatting` is honoured by normalising line endings and
// collapsing leading/trailing whitespace - the underlying paste
// already drops everything but plain text since the clipboard
// API returns a string. The flag is kept so the same handler
// can be re-pointed at a richer source later.
const normalised = stripFormatting
? text.replace(/\r\n?/g, "\n").trim()
: text.replace(/\r\n?/g, "\n");
if (!normalised) return;
// Find the visible page (Ctrl+End behaves the same way).
const stage = document.querySelector<HTMLElement>(
'[data-testid="v2-stage"]',
);
const stageRect = stage?.getBoundingClientRect();
const stageCentreY = stageRect ? stageRect.top + stageRect.height / 2 : 0;
let pageIndex = 0;
let bestDist = Infinity;
for (const p of doc.loadedPages()) {
const el = document.querySelector<HTMLElement>(
`[data-testid="v2-page-${p.index}"]`,
);
if (!el) continue;
const r = el.getBoundingClientRect();
const centre = r.top + r.height / 2;
const dist = Math.abs(centre - stageCentreY);
if (dist < bestDist) {
bestDist = dist;
pageIndex = p.index;
}
}
const page = doc.page(pageIndex);
// Position roughly at the page centre (display space), biased toward the
// upper third so multi-line paste has room to flow downward, then invert
// the CropBox/rotation transform to raw PDF space. Identity => unchanged.
const anchor = page.display.invert(
page.width / 2 - 80,
page.height * 0.55,
);
const cmd = new InsertTextCommand({
pageIndex,
x: anchor.x,
y: anchor.y,
text: normalised,
});
store.dispatch(cmd);
if (cmd.insertedRunId) store.selection.selectOne(cmd.insertedRunId);
},
[store],
);
const handleFindNext = useCallback((reverse: boolean) => {
setFindOpen(true);
const button = document.querySelector<HTMLButtonElement>(
reverse ? '[data-testid="v2-find-prev"]' : '[data-testid="v2-find-next"]',
);
button?.click();
}, []);
const handleEscape = useCallback(() => {
store.selection.clear();
store.setMode("select");
setHelpOpen(false);
setFindOpen(false);
}, [store]);
const handleUngroupSelection = useCallback(() => {
const doc = store.document;
if (!doc) return;
const ids = store.selection.value.runIds;
// Snapshot the target runs first - dispatching mutates page.runs, and
// the ungroup replaces the paragraph run with per-line runs.
const targets: Array<{ pageIndex: number; runId: string }> = [];
for (const pageIdx of doc.loadedPages().map((p) => p.index)) {
for (const r of doc.page(pageIdx).runs) {
if (!ids.includes(r.id)) continue;
if (r.paragraphMemberPtrs.length < 2) continue;
targets.push({ pageIndex: pageIdx, runId: r.id });
}
}
const resultIds: string[] = [];
for (const t of targets) {
const cmd = new UngroupParagraphCommand(t);
store.dispatch(cmd);
resultIds.push(...cmd.resultRunIds);
}
// Reconcile selection against the new run model so the toolbar keeps
// acting on real runs instead of the now-removed paragraph ids.
if (resultIds.length > 0) store.selection.selectMany(resultIds);
else store.selection.clear();
}, [store]);
const handleMergeSelection = useCallback(() => {
const doc = store.document;
if (!doc) return;
const selectedIds = new Set(store.selection.value.runIds);
if (selectedIds.size < 2) return;
const byPage = new Map<number, string[]>();
for (const page of doc.loadedPages()) {
for (const r of page.runs) {
if (!selectedIds.has(r.id)) continue;
const list = byPage.get(r.pageIndex) ?? [];
list.push(r.id);
byPage.set(r.pageIndex, list);
}
}
// Collect every page's new representative, then select them all once -
// selecting inside the loop left only the last page's merge selected.
const reps: string[] = [];
for (const [pageIndex, runIds] of byPage) {
if (runIds.length < 2) continue;
const cmd = new MergeRunsCommand({ pageIndex, runIds });
store.dispatch(cmd);
if (cmd.representativeRunId) reps.push(cmd.representativeRunId);
}
if (reps.length > 0) store.selection.selectMany(reps);
}, [store]);
useEditorKeyboardShortcuts({
store,
onUndo: useCallback(() => store.undo(), [store]),
onRedo: useCallback(() => store.redo(), [store]),
onSave: handleSave,
onDelete: sel.deleteSelection,
onDuplicate: sel.duplicateFirstSelected,
onSelectAll: useCallback(() => {
const ids = store
.getState()
.pages.flatMap((p) => p.runs.map((r) => r.id));
if (ids.length > 0) store.selection.selectMany(ids);
}, [store]),
onCopySelected: handleCopySelected,
onCutSelected: handleCutSelected,
onPaste: useCallback(
(stripFormatting: boolean) => void handlePaste(stripFormatting),
[handlePaste],
),
onToggleHelp: useCallback(() => setHelpOpen((v) => !v), []),
onOpenFind: useCallback(() => setFindOpen(true), []),
onFindNext: handleFindNext,
onEscape: handleEscape,
onMergeSelection: handleMergeSelection,
});
const canGroup = selection.runIds.length >= 2;
const canUngroup = (() => {
if (selection.runIds.length !== 1) return false;
const run = state.pages
.flatMap((p) => p.runs)
.find((r) => r.id === selection.runIds[0]);
return !!run && (run.paragraphLineCount ?? 0) > 1;
})();
const handleToggleAddText = useCallback(
() =>
store.setMode(store.getState().mode === "addText" ? "select" : "addText"),
[store],
);
const handlePickImageClick = useCallback(() => {
(
document.querySelector(
'[data-testid="v2-image-input"]',
) as HTMLInputElement | null
)?.click();
}, []);
const onPickPdf = useCallback(
(file: File) => {
setOpenedFileName(file.name);
void load(file);
},
[load],
);
const handleSubmitPassword = useCallback(
(password: string) => {
const file = store.pendingPasswordFile;
if (file) void load(file, password);
},
[store, load],
);
const handleCancelPassword = useCallback(
() => store.clearPasswordPrompt(),
[store],
);
return (
<Stack
gap={0}
h="100%"
style={{ overflow: "hidden" }}
data-testid="v2-root"
>
<EditorTopBar
store={store}
hasDocument={state.hasDocument}
dirty={state.dirty}
renderScale={state.renderScale}
pages={state.pages}
openedFileName={openedFileName}
onSave={handleSave}
onShowHelp={() => setHelpOpen(true)}
/>
{state.error && (
<Alert color="red" m="sm" data-testid="v2-error">
{state.error}
</Alert>
)}
<EditorFileInputs onPickPdf={onPickPdf} onPickImage={handleInsertImage} />
{findOpen && state.hasDocument && (
<FindBar
store={store}
pages={state.pages}
onClose={() => setFindOpen(false)}
/>
)}
<HelpOverlay opened={helpOpen} onClose={() => setHelpOpen(false)} />
<SaveRiskModal
risks={saveRisks}
onConfirm={handleConfirmSaveRisk}
onCancel={() => setSaveRisks(null)}
/>
<PasswordPromptModal
prompt={state.passwordPrompt}
loading={state.loading}
onSubmit={handleSubmitPassword}
onCancel={handleCancelPassword}
/>
<EditorSidebar
state={state}
selection={selection}
mode={state.mode}
canGroup={canGroup}
canUngroup={canUngroup}
onToggleAddText={handleToggleAddText}
onPickImage={handlePickImageClick}
onGroup={handleMergeSelection}
onUngroup={handleUngroupSelection}
onSetGroupingMode={(mode) => store.setGroupingMode(mode)}
onSetWidthMode={(m) => store.setWidthMode(m)}
/>
</Stack>
);
}
/**
* Decode an image File to RGBA via an <img> element + canvas. Used instead of
* createImageBitmap, which lacks codec support in some environments. Rejects
* (so the caller can surface an error) when the image can't be decoded.
*/
function decodeImageFile(
file: File,
): Promise<{ data: ImageData; width: number; height: number }> {
return new Promise((resolve, reject) => {
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => {
try {
const width = img.naturalWidth || img.width;
const height = img.naturalHeight || img.height;
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
if (!ctx) {
reject(new Error("Canvas 2D context unavailable"));
return;
}
ctx.drawImage(img, 0, 0);
resolve({ data: ctx.getImageData(0, 0, width, height), width, height });
} catch (e) {
reject(e instanceof Error ? e : new Error(String(e)));
} finally {
URL.revokeObjectURL(url);
}
};
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error("Could not decode the selected image."));
};
img.src = url;
});
}
@@ -1,321 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
/**
* Regression coverage for `BackendResolver`'s HTTP transport.
*
* Why this test exists: we previously rolled a custom `fetch()` inside
* BackendResolver that bypassed every concern the shared `apiClient`
* already handles (JWT auth header, XSRF, credentials, token refresh).
* That regressed silently the moment the Spring backend enabled the
* security profile - every probe returned 401, the prewarm cache
* stayed empty, and the per-char emit branch in editTextHelpers had
* nothing to look up. The user reported "the M-glyph fix is broken"
* and the broken code path had ZERO test coverage.
*
* These assertions pin the resolver to the shared apiClient so future
* refactors can't sneak around it: any encode-charcodes POST must go
* through `apiClient.post`, which means automatic auth + the
* `suppressErrorToast` flag we set explicitly to keep prewarm probes
* from popping toasts. We drive the REAL transport via
* `prewarmBackendCacheForPage`, which is the only public entry that
* reaches `postCharcodes`, with a faked PDFium module + editor store.
*/
// Mock apiClient BEFORE BackendResolver imports it.
vi.mock("@app/services/apiClient", () => ({
default: { post: vi.fn() },
}));
// Stub the document serializer so the prewarm path can produce PDF bytes
// without a real PDFium file-writer. The bytes themselves are irrelevant
// to the transport assertions - we just need a non-empty buffer.
vi.mock("@app/tools/pdfTextEditor/v2/pdfium/PdfiumSave", () => ({
PdfiumSave: { serialize: vi.fn(() => new Uint8Array([0, 1, 2, 3])) },
}));
import apiClient from "@app/services/apiClient";
import {
BackendResolver,
prewarmBackendCacheForPage,
resetBackendResolverCaches,
_clearBackendCacheForTests,
_clearPrewarmGuardForTests,
} from "@app/tools/pdfTextEditor/v2/charcode/BackendResolver";
import type { ResolverContext } from "@app/tools/pdfTextEditor/v2/charcode/CharcodeStrategy";
const post = apiClient.post as unknown as ReturnType<typeof vi.fn>;
// Minimal stub for ResolverContext - the resolver path under test
// never dereferences pagePtr/docPtr/module for cache lookup; the
// auto-prefetch fall-through DOES, but it's gated by absence of a
// loaded editor document on window so it bails early in this env.
const fakeCtx: ResolverContext = {
module: {} as unknown as ResolverContext["module"],
pagePtr: 0,
docPtr: 0,
};
/**
* Build a fake PDFium module that renders a single char on a page so the
* prewarm text-walk finds exactly one (font, char) probe to fire. `char`
* is the Unicode codepoint of the only glyph on the page; `fontPtr` is the
* font handle the prewarm caches the charcode under.
*/
function makeFakeModule(char: string, fontPtr: number) {
const cp = char.codePointAt(0) ?? 0;
const TEXT_PAGE = 555;
const TEXT_OBJ = 777;
return {
FPDFText_LoadPage: vi.fn(() => TEXT_PAGE),
FPDFText_ClosePage: vi.fn(),
FPDFText_CountChars: vi.fn(() => 1),
FPDFText_GetUnicode: vi.fn(() => cp),
FPDFText_GetTextObject: vi.fn(() => TEXT_OBJ),
FPDFTextObj_GetFont: vi.fn(() => fontPtr),
} as unknown as ResolverContext["module"];
}
/**
* Fake PDFium module rendering an arbitrary sequence of glyphs, each with its
* own font handle. `glyphs` is a list of [char, fontPtr] in page reading order.
* Used to exercise the prewarm batching + cross-font cache-key paths.
*/
function makeFakeModulePage(glyphs: Array<[string, number]>) {
const TEXT_PAGE = 555;
const OBJ_BASE = 1000;
return {
FPDFText_LoadPage: vi.fn(() => TEXT_PAGE),
FPDFText_ClosePage: vi.fn(),
FPDFText_CountChars: vi.fn(() => glyphs.length),
FPDFText_GetUnicode: vi.fn(
(_tp: number, i: number) => glyphs[i][0].codePointAt(0) ?? 0,
),
FPDFText_GetTextObject: vi.fn((_tp: number, i: number) => OBJ_BASE + i),
FPDFTextObj_GetFont: vi.fn((obj: number) => glyphs[obj - OBJ_BASE][1]),
} as unknown as ResolverContext["module"];
}
/** Poll until `predicate` is true (async prefetch settles) or time out. */
async function waitUntil(predicate: () => boolean): Promise<void> {
for (let i = 0; i < 100; i++) {
if (predicate()) return;
await new Promise((r) => setTimeout(r, 1));
}
}
/**
* Install a fake editor document on window so `prewarmBackendCacheForPage`
* resolves a page + module instead of bailing on "no-editor-ctx".
*/
function installEditorDocument(
module: ResolverContext["module"],
pagePtr: number,
docPtr: number,
) {
const doc = {
module,
docPtr,
loadedPages: () => [{ index: 0, pagePtr, docPtr }],
};
(window as unknown as { __v2_editor_store?: unknown }).__v2_editor_store = {
document: doc,
};
}
beforeEach(() => {
post.mockReset();
resetBackendResolverCaches();
_clearBackendCacheForTests();
_clearPrewarmGuardForTests();
delete (window as unknown as { __v2_editor_store?: unknown })
.__v2_editor_store;
});
afterEach(() => {
post.mockReset();
vi.restoreAllMocks();
delete (window as unknown as { __v2_editor_store?: unknown })
.__v2_editor_store;
});
describe("BackendResolver", () => {
describe("HTTP transport via shared apiClient (regression #111)", () => {
it("routes the encode POST through apiClient.post with the suppressErrorToast header", async () => {
// One glyph 'M' on the page, rendered by font handle 7. Prewarm walks
// the page, finds one probe, serializes the doc (mocked) and POSTs.
const module = makeFakeModule("M", 7);
installEditorDocument(module, 9001, 4242);
post.mockResolvedValueOnce({ data: { charcodes: [182] } });
await prewarmBackendCacheForPage(0);
expect(post).toHaveBeenCalledTimes(1);
expect(post).toHaveBeenCalledWith(
"/api/v1/general/pdf-text-editor-v2/encode-charcodes",
expect.objectContaining({
pdfBase64: expect.any(String),
pageIndex: 0,
locatorChar: "M",
text: "M",
}),
{ headers: { suppressErrorToast: "true" } },
);
});
it("never calls raw fetch() (must go through apiClient)", async () => {
const fetchSpy = vi.spyOn(globalThis, "fetch");
const module = makeFakeModule("A", 3);
installEditorDocument(module, 9002, 4242);
post.mockResolvedValueOnce({ data: { charcodes: [65] } });
await prewarmBackendCacheForPage(0);
expect(post).toHaveBeenCalledTimes(1);
expect(fetchSpy).not.toHaveBeenCalled();
});
it("swallows an HTTP/network error from apiClient.post (postCharcodes -> null, no throw)", async () => {
const module = makeFakeModule("Z", 5);
installEditorDocument(module, 9003, 4242);
// A rejected probe (e.g. a 401) must not propagate: prewarm is
// best-effort and postCharcodes' catch returns null.
post.mockRejectedValueOnce(new Error("401"));
await expect(prewarmBackendCacheForPage(0)).resolves.toBeUndefined();
expect(post).toHaveBeenCalledTimes(1);
});
});
describe("prewarm batching + cross-font cache key", () => {
const ENDPOINT = "/api/v1/general/pdf-text-editor-v2/encode-charcodes";
it("batches all of a font's page chars into ONE request (H3)", async () => {
// Two glyphs 'A','B' both rendered by font 7. Prewarm must fire ONE
// request carrying "AB", not one per char.
const module = makeFakeModulePage([
["A", 7],
["B", 7],
]);
installEditorDocument(module, 9100, 4242);
post.mockResolvedValueOnce({ data: { charcodes: [65, 66] } });
await prewarmBackendCacheForPage(0);
expect(post).toHaveBeenCalledTimes(1);
expect(post).toHaveBeenCalledWith(
ENDPOINT,
expect.objectContaining({ text: "AB" }),
{ headers: { suppressErrorToast: "true" } },
);
// Both chars cached under font 7 in request order.
const r = new BackendResolver();
const res = r.resolve(7, "AB", { module, pagePtr: 9100, docPtr: 4242 });
expect(res?.charcodes).toEqual([65, 66]);
});
it("fires one request per distinct font, not per char", async () => {
const module = makeFakeModulePage([
["A", 7],
["B", 8],
]);
installEditorDocument(module, 9101, 4242);
post.mockResolvedValue({ data: { charcodes: [1] } });
await prewarmBackendCacheForPage(0);
expect(post).toHaveBeenCalledTimes(2);
});
it("respects the backend's `missing` list when mapping batched charcodes", async () => {
const module = makeFakeModulePage([
["A", 7],
["B", 7],
["C", 7],
]);
installEditorDocument(module, 9102, 4242);
// Backend could encode A and C but not B: charcodes align to the
// NON-missing chars in order.
post.mockResolvedValueOnce({
data: { charcodes: [65, 67], missing: ["B"] },
});
await prewarmBackendCacheForPage(0);
const r = new BackendResolver();
const ctx = { module, pagePtr: 9102, docPtr: 4242 };
expect(r.resolve(7, "A", ctx)?.charcodes).toEqual([65]);
expect(r.resolve(7, "C", ctx)?.charcodes).toEqual([67]);
// 'B' was reported missing -> cached null -> reported missing, not 67.
const b = r.resolve(7, "B", ctx);
expect(b?.charcodes).toEqual([]);
expect(b?.missing).toEqual(["B"]);
});
it("does not re-POST every keystroke when the queried font differs from the rendering font (H2)", async () => {
// 'A' is rendered by font 7 on the page, but the run is editing under a
// borrowed font handle 99. The first resolve misses and prefetches; the
// sentinel it seeds under font 99 must stop every subsequent keystroke
// from re-serializing + re-POSTing the whole PDF.
const module = makeFakeModulePage([["A", 7]]);
installEditorDocument(module, 9200, 4242);
post.mockResolvedValue({ data: { charcodes: [65] } });
const r = new BackendResolver();
const ctx: ResolverContext = { module, pagePtr: 9200, docPtr: 4242 };
r.resolve(99, "A", ctx); // miss under font 99 -> kicks prefetch
await waitUntil(() => post.mock.calls.length >= 1);
const callsAfterFirst = post.mock.calls.length;
// More keystrokes for the same (font 99, 'A'): the null sentinel must
// short-circuit resolve() so no further prefetch fires.
r.resolve(99, "A", ctx);
r.resolve(99, "A", ctx);
await new Promise((res) => setTimeout(res, 5));
expect(post.mock.calls.length).toBe(callsAfterFirst);
// The real charcode landed under the rendering font 7.
expect(r.resolve(7, "A", ctx)?.charcodes).toEqual([65]);
});
});
describe("cache semantics", () => {
it("resolve() with an empty text returns null", () => {
const r = new BackendResolver();
expect(r.resolve(1, "", fakeCtx)).toBeNull();
});
it("resolve() with a 0 font returns null", () => {
const r = new BackendResolver();
expect(r.resolve(0, "M", fakeCtx)).toBeNull();
});
});
describe("whitespace is never charcode-reused (mushroom „ bug)", () => {
it("resolve() reports a space as missing and never round-trips it", async () => {
const r = new BackendResolver();
const result = r.resolve(99, " ", fakeCtx);
// Space must be reported missing (-> emitted as a positional gap),
// NOT looked up / cached / sent to the backend (which would paint a
// garbage glyph like „ for charcode 0x20 in subset fonts).
expect(result?.missing).toEqual([" "]);
expect(result?.charcodes).toEqual([]);
await Promise.resolve();
await Promise.resolve();
expect(post).not.toHaveBeenCalled();
});
it("resolve() splits a mixed chunk: real chars miss the cache, whitespace stays a gap", async () => {
const r = new BackendResolver();
// "a b" - 'a' and 'b' are genuine cache misses (kick a prefetch), the
// space is reported missing WITHOUT being counted as a prefetch miss.
const result = r.resolve(99, "a b", fakeCtx);
expect(result?.missing).toEqual(["a", " ", "b"]);
expect(result?.charcodes).toEqual([]);
// The prefetch (for 'a') bails before HTTP in this no-window-doc env,
// but crucially the space alone must never be the reason it fires.
const spaceOnly = r.resolve(99, "\t\n ", fakeCtx);
expect(spaceOnly?.charcodes).toEqual([]);
expect(spaceOnly?.missing).toEqual(["\t", "\n", " "]);
});
});
});
@@ -1,109 +0,0 @@
import { describe, it, expect } from "vitest";
import { Page } from "@app/tools/pdfTextEditor/v2/model/Page";
import { TextRun } from "@app/tools/pdfTextEditor/v2/model/TextRun";
import { LineGrouper } from "@app/tools/pdfTextEditor/v2/pdfium/LineGrouper";
import { ParagraphGrouper } from "@app/tools/pdfTextEditor/v2/pdfium/ParagraphGrouper";
// Reproduces the "Plus Many More" two-column bulleted-list geometry from
// public/samples/Sample.pdf page 3 (probed from the live editor): bullets are
// separate text objects indented ~14pt left of their item text, and in the
// bottom section the bullet font (13.5) sits ~2.3pt above the item font (11.3).
// The grouper must pair each bullet with its OWN item (one run per item,
// bullet at the start) and must NOT merge across the column gutter.
let ptr = 1000;
function mkRun(opts: {
x: number;
width: number;
f: number;
fs: number;
text: string;
}): TextRun {
return new TextRun({
id: `r${ptr}`,
pageIndex: 0,
bounds: { x: opts.x, y: opts.f, width: opts.width, height: opts.fs },
matrix: { a: opts.fs, b: 0, c: 0, d: opts.fs, e: opts.x, f: opts.f },
text: opts.text,
fontId: "pdf:1:Test",
fontSize: opts.fs,
fill: { r: 0, g: 0, b: 0, a: 255 },
fontSubset: false,
pdfiumObjPtr: ptr++,
containerPtr: 0,
});
}
function group(runs: TextRun[]): TextRun[] {
const page = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });
page.setRuns(runs);
page.loaded = true;
LineGrouper.apply(page);
ParagraphGrouper.apply(page);
return page.runs;
}
describe("bullet-to-item grouping (Plus Many More)", () => {
it("pairs each bullet with its own item and keeps columns separate", () => {
const runs: TextRun[] = [
// Bottom "Plus Many More" section: bullet fs13.5, item fs11.3,
// bullet baseline ~2.3pt above the item, ~14-17pt indent.
// LEFT column
mkRun({ x: 66, width: 3, f: 178.9, fs: 13.5, text: "• " }),
mkRun({
x: 83,
width: 111,
f: 176.6,
fs: 11.3,
text: "OCR text recognition",
}),
mkRun({ x: 66, width: 3, f: 153.4, fs: 13.5, text: "• " }),
mkRun({ x: 83, width: 80, f: 151.1, fs: 11.3, text: "Compress PDFs" }),
// RIGHT column (gutter ~245pt to the right)
mkRun({ x: 311, width: 3, f: 178.9, fs: 13.5, text: "• " }),
mkRun({ x: 328, width: 101, f: 176.6, fs: 11.3, text: "Flatten forms" }),
mkRun({ x: 311, width: 3, f: 153.4, fs: 13.5, text: "• " }),
mkRun({
x: 328,
width: 95,
f: 151.1,
fs: 11.3,
text: "PDF/A conversion",
}),
];
const out = group(runs);
// No orphan bullet-only run (the reported bug = a stacked bullet column).
const orphan = out.find(
(r) => /^[\s•]+$/.test(r.text) && (r.text.match(/•/g) ?? []).length >= 2,
);
expect(orphan, `orphan bullet run: ${orphan?.text}`).toBeUndefined();
// Each item's run starts with the bullet and does not swallow a foreign item.
const ocr = out.find((r) => /OCR\s+text/.test(r.text));
expect(ocr, "OCR run exists").toBeTruthy();
expect(ocr!.text.trimStart().startsWith("•")).toBe(true);
expect(ocr!.text).not.toMatch(/Flatten/); // not merged across the gutter
const flatten = out.find((r) => /Flatten\s+forms/.test(r.text));
expect(flatten, "Flatten run exists").toBeTruthy();
expect(flatten!.text.trimStart().startsWith("•")).toBe(true);
expect(flatten!.text).not.toMatch(/OCR/);
});
it("pairs same-baseline bullets (upper lists) with their item", () => {
const runs: TextRun[] = [
mkRun({ x: 66, width: 3, f: 642.4, fs: 10.5, text: "• " }),
mkRun({
x: 80,
width: 91,
f: 642.4,
fs: 10.5,
text: "Merge & split PDFs",
}),
];
const out = group(runs);
const merge = out.find((r) => /Merge/.test(r.text));
expect(merge!.text.trimStart().startsWith("•")).toBe(true);
});
});
@@ -1,145 +0,0 @@
import { describe, it, expect } from "vitest";
import { ChangeZOrderCommand } from "@app/tools/pdfTextEditor/v2/commands/ChangeZOrderCommand";
import { Page } from "@app/tools/pdfTextEditor/v2/model/Page";
import { ImageObject } from "@app/tools/pdfTextEditor/v2/model/ImageObject";
import { TextRun } from "@app/tools/pdfTextEditor/v2/model/TextRun";
import type { EditorDocument } from "@app/tools/pdfTextEditor/v2/model/EditorDocument";
/**
* Fake PDFium module backing the page object list with a plain array of
* pointers (index 0 = painted first = bottom, last = top). Enough surface for
* ChangeZOrderCommand: count / get / remove / insert-at-index.
*/
function fakeDoc(objs: number[], page: Page): EditorDocument {
const module = {
FPDFPage_CountObjects: () => objs.length,
FPDFPage_GetObject: (_p: number, i: number) => objs[i] ?? 0,
FPDFPage_RemoveObject: (_p: number, ptr: number) => {
const i = objs.indexOf(ptr);
if (i >= 0) objs.splice(i, 1);
return true;
},
FPDFPage_InsertObjectAtIndex: (_p: number, ptr: number, idx: number) => {
objs.splice(idx, 0, ptr);
return true;
},
};
return { module, page: () => page } as unknown as EditorDocument;
}
function pageWithImage(ptr: number): Page {
const page = new Page({ index: 0, pagePtr: 1, width: 100, height: 100 });
page.setImages([
new ImageObject({
id: "img1",
pageIndex: 0,
pdfiumObjPtr: ptr,
bounds: { x: 0, y: 0, width: 10, height: 10 },
matrix: { a: 10, b: 0, c: 0, d: 10, e: 0, f: 0 },
}),
]);
return page;
}
describe("ChangeZOrderCommand", () => {
it("bring-to-front moves the object to the top AND triggers re-render + regen", () => {
const page = pageWithImage(42);
const objs = [42, 7, 9]; // image (42) at bottom, covered by 7 and 9
const doc = fakeDoc(objs, page);
const rev0 = page.revision;
new ChangeZOrderCommand({
pageIndex: 0,
imageId: "img1",
mode: "to-front",
}).apply(doc);
expect(objs).toEqual([7, 9, 42]); // now painted last = on top
// Without these the reorder is invisible (no bitmap re-render) and lost on
// save (content stream never regenerated) - the reported bug.
expect(page.revision).toBeGreaterThan(rev0);
expect(page.needsGenerateContent).toBe(true);
});
it("send-to-back moves the object to the bottom", () => {
const page = pageWithImage(42);
const objs = [7, 9, 42]; // image on top
const doc = fakeDoc(objs, page);
new ChangeZOrderCommand({
pageIndex: 0,
imageId: "img1",
mode: "to-back",
}).apply(doc);
expect(objs).toEqual([42, 7, 9]); // painted first = underneath
});
it("revert restores the original index and re-renders again", () => {
const page = pageWithImage(42);
const objs = [42, 7, 9];
const doc = fakeDoc(objs, page);
const cmd = new ChangeZOrderCommand({
pageIndex: 0,
imageId: "img1",
mode: "to-front",
});
cmd.apply(doc);
expect(objs).toEqual([7, 9, 42]);
const revAfterApply = page.revision;
cmd.revert(doc);
expect(objs).toEqual([42, 7, 9]); // back where it started
expect(page.revision).toBeGreaterThan(revAfterApply);
expect(page.needsGenerateContent).toBe(true);
});
it("already-on-top bring-to-front is a no-op (no spurious revision bump)", () => {
const page = pageWithImage(42);
const objs = [7, 9, 42]; // already last
const doc = fakeDoc(objs, page);
const rev0 = page.revision;
new ChangeZOrderCommand({
pageIndex: 0,
imageId: "img1",
mode: "to-front",
}).apply(doc);
expect(objs).toEqual([7, 9, 42]);
expect(page.revision).toBe(rev0);
});
it("send-to-back moves a NON-CONTIGUOUS member group whose bottom sits at index 0", () => {
// Run leaf objects M1=5, M2=9 at page indices [0, 2] with unrelated X=7
// between them: [M1, X, M2]. A blanket `bottomIdx===0` no-op guard wrongly
// skipped this; the whole group must land at the back -> [M1, M2, X].
const page = new Page({ index: 0, pagePtr: 1, width: 100, height: 100 });
const run = new TextRun({
id: "run1",
pageIndex: 0,
pdfiumObjPtr: 5,
bounds: { x: 0, y: 0, width: 10, height: 10 },
matrix: { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 },
text: "hi",
fontId: "base14:Helvetica",
fontSize: 12,
fill: { r: 0, g: 0, b: 0, a: 255 },
fontSubset: false,
});
run.paragraphLeafPtrs = [5, 9];
run.paragraphLeafContainers = [0, 0];
page.setRuns([run]);
const objs = [5, 7, 9];
const doc = fakeDoc(objs, page);
new ChangeZOrderCommand({
pageIndex: 0,
runId: "run1",
mode: "to-back",
}).apply(doc);
expect(objs).toEqual([5, 9, 7]); // both members now under X
expect(page.needsGenerateContent).toBe(true);
});
});
@@ -1,275 +0,0 @@
import { beforeEach, describe, expect, it } from "vitest";
/**
* Unit coverage for the embedded-font cmap strategy.
*
* `parseTrueTypeCmap` and `CmapResolver.resolve()` had ZERO direct test
* coverage: the only path that built a cmap read font bytes via PDFium
* (WASM), so nothing exercised the byte parser or the resolve lookup in
* isolation. These tests:
* - parse a hand-built minimal sfnt with a format-4 cmap and assert the
* Unicode->glyphId Map (the happy path the whole strategy rests on);
* - assert the parser returns null for non-sfnt and truncated blobs;
* - drive `resolve()` against a cmap primed through the real
* `primeFontGlyphMap` path (a faked PDFium module feeds the same
* synthetic font bytes), proving covered chars resolve and uncovered
* chars land in `missing`, and that a font with no cmap reports the
* "cmap unavailable" result.
*/
import {
CmapResolver,
parseTrueTypeCmap,
primeFontGlyphMap,
_clearCmapCacheForTests,
} from "@app/tools/pdfTextEditor/v2/charcode/CmapResolver";
import type { ResolverContext } from "@app/tools/pdfTextEditor/v2/charcode/CharcodeStrategy";
/**
* Build a minimal TrueType sfnt carrying a single format-4 cmap subtable
* that maps each [codepoint => glyphId] entry. Each entry becomes its own
* one-char segment (idRangeOffset=0, idDelta=gid-code) plus the mandatory
* terminal 0xFFFF segment. Entries are sorted by codepoint as format 4
* requires ascending endCode order.
*/
function buildSfntWithFormat4(entries: Array<[number, number]>): Uint8Array {
const sorted = [...entries].sort((a, b) => a[0] - b[0]);
const segCount = sorted.length + 1; // + terminal 0xFFFF segment
const segCountX2 = segCount * 2;
// format(2) length(2) language(2) segCountX2(2) searchRange(2)
// entrySelector(2) rangeShift(2) = 14 header bytes, then the 4 parallel
// arrays of segCountX2 bytes each, plus the 2-byte reservedPad after
// endCodes. No glyphIdArray needed (all idRangeOffset=0).
const subtableLen = 14 + 2 + segCountX2 * 4;
const HEADER = 12;
const TABLE_RECORD = 16;
const cmapStart = HEADER + TABLE_RECORD; // 28
const subtableStart = cmapStart + 4 + 8; // cmap hdr(4) + 1 encoding rec(8) = 40
const total = subtableStart + subtableLen;
const buf = new ArrayBuffer(total);
const dv = new DataView(buf);
// sfnt header: scaler 0x00010000 (TrueType), numTables=1.
dv.setUint32(0, 0x00010000);
dv.setUint16(4, 1);
// searchRange / entrySelector / rangeShift left 0 (unused by parser).
// Single table record: tag 'cmap', checksum 0, offset, length.
dv.setUint32(HEADER, 0x636d6170); // 'cmap'
dv.setUint32(HEADER + 4, 0);
dv.setUint32(HEADER + 8, cmapStart);
dv.setUint32(HEADER + 12, 4 + 8 + subtableLen);
// cmap header: version 0, numSubtables 1.
dv.setUint16(cmapStart, 0);
dv.setUint16(cmapStart + 2, 1);
// encoding record: platform 3 (Microsoft), encoding 1 (Unicode BMP),
// offset from cmap start to the subtable.
dv.setUint16(cmapStart + 4, 3);
dv.setUint16(cmapStart + 6, 1);
dv.setUint32(cmapStart + 8, subtableStart - cmapStart);
// format-4 subtable.
const o = subtableStart;
dv.setUint16(o, 4); // format
dv.setUint16(o + 2, subtableLen); // length
dv.setUint16(o + 4, 0); // language
dv.setUint16(o + 6, segCountX2);
dv.setUint16(o + 8, 0); // searchRange (unused by parser)
dv.setUint16(o + 10, 0); // entrySelector
dv.setUint16(o + 12, 0); // rangeShift
const endCodesOff = o + 14;
const startCodesOff = endCodesOff + segCountX2 + 2; // + reservedPad
const idDeltasOff = startCodesOff + segCountX2;
const idRangeOffsetsOff = idDeltasOff + segCountX2;
sorted.forEach(([code, gid], i) => {
dv.setUint16(endCodesOff + i * 2, code);
dv.setUint16(startCodesOff + i * 2, code);
dv.setInt16(idDeltasOff + i * 2, (gid - code) & 0xffff);
dv.setUint16(idRangeOffsetsOff + i * 2, 0);
});
// Terminal segment: 0xFFFF..0xFFFF, idDelta 1, idRangeOffset 0.
const t = sorted.length;
dv.setUint16(endCodesOff + t * 2, 0xffff);
dv.setUint16(startCodesOff + t * 2, 0xffff);
dv.setInt16(idDeltasOff + t * 2, 1);
dv.setUint16(idRangeOffsetsOff + t * 2, 0);
// reservedPad already zero.
return new Uint8Array(buf);
}
/**
* Fake PDFium module whose `FPDFFont_GetFontData` copies `fontBytes` into a
* scratch heap, mirroring the two-call (size probe, then read) contract
* `buildCmap` uses. Lets `primeFontGlyphMap` build a real cmap with no WASM.
*/
function makeFontDataModule(
fontBytes: Uint8Array | null,
): ResolverContext["module"] {
const heap = new Uint8Array(1 << 16);
let bump = 8;
const malloc = (n: number): number => {
const ptr = bump;
bump += n;
return ptr;
};
const getValue = (ptr: number, _type: string): number => {
return new DataView(heap.buffer).getInt32(ptr, true);
};
const setI32 = (ptr: number, v: number) =>
new DataView(heap.buffer).setInt32(ptr, v, true);
const FPDFFont_GetFontData = (
_font: number,
bufferPtr: number,
length: number,
outSizePtr: number,
): boolean => {
if (!fontBytes) return false;
if (bufferPtr === 0 || length === 0) {
// Size-probe call.
setI32(outSizePtr, fontBytes.length);
return true;
}
heap.set(fontBytes.subarray(0, length), bufferPtr);
setI32(outSizePtr, fontBytes.length);
return true;
};
return {
FPDFFont_GetFontData,
pdfium: {
wasmExports: { malloc, free: (_p: number) => {} },
getValue,
HEAPU8: heap,
},
} as unknown as ResolverContext["module"];
}
beforeEach(() => {
_clearCmapCacheForTests();
});
describe("parseTrueTypeCmap", () => {
it("parses a format-4 subtable into a Unicode->glyphId map", () => {
// 'A' (65) -> 3, 'M' (77) -> 7.
const bytes = buildSfntWithFormat4([
[65, 3],
[77, 7],
]);
const map = parseTrueTypeCmap(bytes);
expect(map).not.toBeNull();
expect(map?.get(65)).toBe(3);
expect(map?.get(77)).toBe(7);
// Unmapped codepoints are absent (not zero).
expect(map?.get(66)).toBeUndefined();
});
it("returns null for a non-sfnt blob", () => {
const bytes = new Uint8Array(64);
bytes.fill(0xab); // bogus scaler type, not 0x00010000 / OTTO / true / typ1
expect(parseTrueTypeCmap(bytes)).toBeNull();
});
it("returns null for a truncated buffer (<12 bytes)", () => {
expect(parseTrueTypeCmap(new Uint8Array([0, 1, 0, 0]))).toBeNull();
});
});
describe("CmapResolver.resolve()", () => {
const FONT = 1;
it("returns charcodes for covered chars and reports uncovered chars as missing", () => {
const module = makeFontDataModule(
buildSfntWithFormat4([
[65, 3],
[77, 7],
]),
);
primeFontGlyphMap(FONT, module);
const ctx: ResolverContext = { module, pagePtr: 0, docPtr: 0 };
const result = new CmapResolver().resolve(FONT, "AMZ", ctx);
expect(result).not.toBeNull();
// 'A'->3 and 'M'->7 are covered; 'Z' (90) is not in the cmap.
expect(result?.charcodes).toEqual([3, 7]);
expect(result?.coverage).toBe(2);
expect(result?.missing).toEqual(["Z"]);
});
it("returns null when font is 0", () => {
const module = makeFontDataModule(null);
const ctx: ResolverContext = { module, pagePtr: 0, docPtr: 0 };
expect(new CmapResolver().resolve(0, "A", ctx)).toBeNull();
});
it("reports 'cmap unavailable' when the font has no parseable cmap", () => {
// FPDFFont_GetFontData returns false -> buildCmap caches null.
const module = makeFontDataModule(null);
primeFontGlyphMap(FONT, module);
const ctx: ResolverContext = { module, pagePtr: 0, docPtr: 0 };
const result = new CmapResolver().resolve(FONT, "AB", ctx);
expect(result?.charcodes).toEqual([]);
expect(result?.coverage).toBe(0);
expect(result?.missing).toEqual(["A", "B"]);
expect(result?.note).toBe("cmap unavailable for this font");
});
});
describe("parseFormat4 entry cap (I11)", () => {
it("never builds more than the MAX_CMAP_ENTRIES (70k) cap from a single segment", () => {
// One segment spanning a huge range with idRangeOffset=0 would map every
// codepoint in [start,end]. The I11 cap must stop it well under the span.
const segCountX2 = 4; // 2 segments: the big range + terminal 0xFFFF
const subtableLen = 14 + 2 + segCountX2 * 4;
const cmapStart = 28;
const subtableStart = cmapStart + 4 + 8;
const total = subtableStart + subtableLen;
const buf = new ArrayBuffer(total);
const dv = new DataView(buf);
dv.setUint32(0, 0x00010000);
dv.setUint16(4, 1);
dv.setUint32(12, 0x636d6170);
dv.setUint32(12 + 8, cmapStart);
dv.setUint32(12 + 12, 4 + 8 + subtableLen);
dv.setUint16(cmapStart, 0);
dv.setUint16(cmapStart + 2, 1);
dv.setUint16(cmapStart + 4, 3);
dv.setUint16(cmapStart + 6, 1);
dv.setUint32(cmapStart + 8, subtableStart - cmapStart);
const o = subtableStart;
dv.setUint16(o, 4);
dv.setUint16(o + 2, subtableLen);
dv.setUint16(o + 6, segCountX2);
const endCodesOff = o + 14;
const startCodesOff = endCodesOff + segCountX2 + 2;
const idDeltasOff = startCodesOff + segCountX2;
const idRangeOffsetsOff = idDeltasOff + segCountX2;
// Segment 0: 0x0001 .. 0xFFFE, idDelta 1 (maps every code to code+1).
dv.setUint16(endCodesOff, 0xfffe);
dv.setUint16(startCodesOff, 0x0001);
dv.setInt16(idDeltasOff, 1);
dv.setUint16(idRangeOffsetsOff, 0);
// Terminal 0xFFFF segment.
dv.setUint16(endCodesOff + 2, 0xffff);
dv.setUint16(startCodesOff + 2, 0xffff);
dv.setInt16(idDeltasOff + 2, 1);
dv.setUint16(idRangeOffsetsOff + 2, 0);
const map = parseTrueTypeCmap(new Uint8Array(buf));
expect(map).not.toBeNull();
// The full span is ~65k which is under 70k, so it should map without the
// cap firing - the guarantee is it stays bounded, never unbounded.
expect((map as Map<number, number>).size).toBeLessThanOrEqual(70_000);
expect((map as Map<number, number>).size).toBeGreaterThan(0);
});
});
@@ -1,63 +0,0 @@
import { describe, expect, it } from "vitest";
import {
BLACK,
WHITE,
equalsRGBA,
parseCssColor,
toCssHex,
} from "@app/tools/pdfTextEditor/v2/model/Color";
describe("Color", () => {
it("parses #rrggbb", () => {
expect(parseCssColor("#ff8800")).toEqual({ r: 255, g: 136, b: 0, a: 255 });
});
it("parses #rrggbbaa", () => {
expect(parseCssColor("#11223380")).toEqual({
r: 17,
g: 34,
b: 51,
a: 128,
});
});
it("parses rgb(...)", () => {
expect(parseCssColor("rgb(10, 20, 30)")).toEqual({
r: 10,
g: 20,
b: 30,
a: 255,
});
});
it("parses rgba(...) with fractional alpha", () => {
expect(parseCssColor("rgba(10, 20, 30, 0.5)")).toEqual({
r: 10,
g: 20,
b: 30,
a: 128,
});
});
it("returns null for invalid input", () => {
expect(parseCssColor("not a colour")).toBeNull();
expect(parseCssColor("#abc")).toBeNull(); // short hex unsupported on purpose
});
it("round-trips through toCssHex", () => {
const rgba = parseCssColor("#abcdef")!;
expect(toCssHex(rgba)).toBe("#abcdef");
});
it("clamps and rounds when serialising", () => {
expect(toCssHex({ r: -10, g: 300, b: 0.5, a: 255 })).toBe("#00ff01");
});
it("equalsRGBA respects every component", () => {
expect(equalsRGBA(BLACK, BLACK)).toBe(true);
expect(equalsRGBA(BLACK, WHITE)).toBe(false);
expect(
equalsRGBA({ r: 1, g: 2, b: 3, a: 4 }, { r: 1, g: 2, b: 3, a: 5 }),
).toBe(false);
});
});
@@ -1,134 +0,0 @@
import { describe, it, expect } from "vitest";
import { DisplayTransform } from "@app/tools/pdfTextEditor/v2/model/DisplayTransform";
/**
* Unit coverage for the raw-PDF <-> display (CropBox/rotation) transform that
* fixes the spirit-sx positioning bug. Pure math, no PDFium. Pins the
* rotation/crop affine, the apply/invert round-trip, and - critically - the
* identity (CropBox==MediaBox, /Rotate==0) byte-exact pass-through so the
* common case cannot drift.
*/
const CROP = { cl: 36, cb: 72, cw: 540, ch: 720 };
const ROTATIONS = [0, 1, 2, 3];
function mk(rotate: number): DisplayTransform {
const { cl, cb, cw, ch } = CROP;
// displayWidth/Height swap for 90/270.
const dw = rotate % 2 === 0 ? cw : ch;
const dh = rotate % 2 === 0 ? ch : cw;
return DisplayTransform.fromCropAndRotate(cl, cb, cw, ch, rotate, dw, dh);
}
describe("DisplayTransform", () => {
it("identity for CropBox==MediaBox, Rotate 0 (byte-exact pass-through)", () => {
const t = DisplayTransform.fromCropAndRotate(0, 0, 600, 800, 0, 600, 800);
expect(t.isIdentity).toBe(true);
expect([t.a, t.b, t.c, t.d, t.e, t.f]).toEqual([1, 0, 0, 1, 0, 0]);
for (const [px, py] of [
[0, 0],
[123.4, 567.8],
[600, 800],
]) {
expect(t.apply(px, py)).toEqual({ x: px, y: py });
expect(t.invert(px, py)).toEqual({ x: px, y: py });
}
});
it("apply/invert round-trip to identity for all rotations + non-zero crop", () => {
for (const r of ROTATIONS) {
const t = mk(r);
for (const [px, py] of [
[36, 72],
[300, 500],
[576, 792],
[100.25, 240.75],
]) {
const d = t.apply(px, py);
const back = t.invert(d.x, d.y);
expect(back.x).toBeCloseTo(px, 6);
expect(back.y).toBeCloseTo(py, 6);
}
}
});
it("displayed-size invariant: the CropBox maps to a (Wd,Hd) AABB anchored at the origin, swapped for 90/270", () => {
const { cl, cb, cw, ch } = CROP;
const corners: Array<[number, number]> = [
[cl, cb],
[cl + cw, cb],
[cl, cb + ch],
[cl + cw, cb + ch],
];
for (const r of ROTATIONS) {
const t = mk(r);
const ds = corners.map(([px, py]) => t.apply(px, py));
const w =
Math.max(...ds.map((d) => d.x)) - Math.min(...ds.map((d) => d.x));
const h =
Math.max(...ds.map((d) => d.y)) - Math.min(...ds.map((d) => d.y));
const expW = r % 2 === 0 ? cw : ch;
const expH = r % 2 === 0 ? ch : cw;
expect(w).toBeCloseTo(expW, 6);
expect(h).toBeCloseTo(expH, 6);
// The displayed AABB must lie in [0,Wd] x [0,Hd] (origin at lower-left).
expect(Math.min(...ds.map((d) => d.x))).toBeCloseTo(0, 6);
expect(Math.min(...ds.map((d) => d.y))).toBeCloseTo(0, 6);
}
});
it("matches PDFium ground truth for all rotations (pins orientation; det +1)", () => {
// Ground truth from the real PDFium engine (FPDF_PageToDevice -> display-PDF
// y-up) for CropBox [50,20,350,370] and raw user-space point (60,350).
// This is what catches a 90/270 reflection (det -1) flip.
const c = { cl: 50, cb: 20, cw: 300, ch: 350 };
const cases: Array<[number, [number, number]]> = [
[0, [10, 330]],
[1, [330, 290]],
[2, [290, 20]],
[3, [20, 10]],
];
for (const [rot, [ex, ey]] of cases) {
const dw = rot % 2 === 0 ? c.cw : c.ch;
const dh = rot % 2 === 0 ? c.ch : c.cw;
const t = DisplayTransform.fromCropAndRotate(
c.cl,
c.cb,
c.cw,
c.ch,
rot,
dw,
dh,
);
// Proper rotation/reflection-free: determinant must be +1.
expect(t.a * t.d - t.b * t.c).toBeCloseTo(1, 9);
const d = t.apply(60, 350);
expect(d.x).toBeCloseTo(ex, 4);
expect(d.y).toBeCloseTo(ey, 4);
}
});
it("rotate 0 is a pure crop translate", () => {
const t = mk(0);
expect(t.apply(CROP.cl + 10, CROP.cb + 20)).toEqual({ x: 10, y: 20 });
});
it("applyVector/invertVector round-trip and ignore translation", () => {
for (const r of ROTATIONS) {
const t = mk(r);
const v = t.applyVector(5, -3);
const back = t.invertVector(v.x, v.y);
expect(back.x).toBeCloseTo(5, 6);
expect(back.y).toBeCloseTo(-3, 6);
// identity-rotate keeps the vector as-is.
if (r === 0) expect(v).toEqual({ x: 5, y: -3 });
}
});
it("fromData / toData are lossless", () => {
const t = mk(3);
const r = DisplayTransform.fromData(t.toData());
expect(r.toData()).toEqual(t.toData());
expect(r.apply(100, 200)).toEqual(t.apply(100, 200));
});
});
@@ -1,88 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { HistoryStack } from "@app/tools/pdfTextEditor/v2/store/HistoryStack";
import type { Command } from "@app/tools/pdfTextEditor/v2/commands/Command";
import type { EditorDocument } from "@app/tools/pdfTextEditor/v2/model/EditorDocument";
function makeCmd(type = "test") {
const apply = vi.fn();
const revert = vi.fn();
const cmd: Command = { type, apply, revert };
return { cmd, apply, revert };
}
const fakeDoc = {} as unknown as EditorDocument;
describe("HistoryStack", () => {
it("starts empty and reports neither undo nor redo", () => {
const h = new HistoryStack();
expect(h.canUndo).toBe(false);
expect(h.canRedo).toBe(false);
expect(h.size()).toEqual({ undo: 0, redo: 0 });
});
it("execute applies and pushes onto the undo stack", () => {
const h = new HistoryStack();
const { cmd, apply } = makeCmd();
h.execute(cmd, fakeDoc);
expect(apply).toHaveBeenCalledOnce();
expect(h.canUndo).toBe(true);
expect(h.canRedo).toBe(false);
});
it("undo reverts the most recent command and moves it to redo", () => {
const h = new HistoryStack();
const { cmd, revert } = makeCmd();
h.execute(cmd, fakeDoc);
const popped = h.undo(fakeDoc);
expect(popped).toBe(cmd);
expect(revert).toHaveBeenCalledOnce();
expect(h.canUndo).toBe(false);
expect(h.canRedo).toBe(true);
});
it("redo re-applies and shifts back to undo", () => {
const h = new HistoryStack();
const { cmd, apply } = makeCmd();
h.execute(cmd, fakeDoc);
h.undo(fakeDoc);
const popped = h.redo(fakeDoc);
expect(popped).toBe(cmd);
// apply was called once on execute and once on redo.
expect(apply).toHaveBeenCalledTimes(2);
expect(h.canUndo).toBe(true);
expect(h.canRedo).toBe(false);
});
it("a new execute after undo discards the redo stack", () => {
const h = new HistoryStack();
const a = makeCmd("a");
const b = makeCmd("b");
h.execute(a.cmd, fakeDoc);
h.undo(fakeDoc);
expect(h.canRedo).toBe(true);
h.execute(b.cmd, fakeDoc);
expect(h.canRedo).toBe(false);
});
it("undo on an empty stack is a no-op and returns null", () => {
const h = new HistoryStack();
expect(h.undo(fakeDoc)).toBeNull();
});
it("clear empties both stacks", () => {
const h = new HistoryStack();
h.execute(makeCmd("a").cmd, fakeDoc);
h.execute(makeCmd("b").cmd, fakeDoc);
h.clear();
expect(h.size()).toEqual({ undo: 0, redo: 0 });
});
it("enforces the configured limit by dropping the oldest entry", () => {
const h = new HistoryStack(3);
h.execute(makeCmd("a").cmd, fakeDoc);
h.execute(makeCmd("b").cmd, fakeDoc);
h.execute(makeCmd("c").cmd, fakeDoc);
h.execute(makeCmd("d").cmd, fakeDoc);
expect(h.size().undo).toBe(3);
});
});
@@ -1,217 +0,0 @@
import { describe, it, expect } from "vitest";
import {
planParagraphEdit,
planPartialEdit,
} from "@app/tools/pdfTextEditor/v2/commands/partialEdit";
import {
TextRun,
type ParagraphLineSlot,
} from "@app/tools/pdfTextEditor/v2/model/TextRun";
/**
* Regression coverage for the mushroom-life.pdf "line collapse" bug.
*
* A paragraph's `run.text` joins VISUAL lines with one-char separators:
* "\n" for hard (user) breaks, " " for soft word-wraps. `planParagraphEdit`
* used to derive its per-line view via `run.text.split("\n")`, which
* UNDER-COUNTS lines the moment a paragraph soft-wraps - then bailed on
* `prevLines.length !== paragraphLineSlots.length`, routing the edit to the
* whole-paragraph overlay re-emit which collapsed every visual line onto a
* single baseline.
*
* The fix derives per-line text from the slot CHAR RANGES instead, so a
* soft-wrapped paragraph edits in place (font-preserving) like any other.
*/
let nextPtr = 100;
function slot(
text: string,
startChar: number,
baselineY: number,
): ParagraphLineSlot {
const ptr = nextPtr++;
return {
startChar,
endChar: startChar + text.length,
baselineY,
matrixE: 0,
containerPtr: 0,
fontId: "pdf:1:LMRoman12",
fontSize: 12,
fontSubset: false,
mergedFromPtrs: [ptr],
mergedFromTexts: [text],
mergedFromBounds: [{ x: 0, right: text.length * 6 }],
mergedFromCharStarts: [0],
};
}
/**
* Build a paragraph run whose `text` is the visual lines joined by the
* given separators (one per gap, "\n" or " ").
*/
function makeParagraph(lines: string[], separators: string[]): TextRun {
let text = lines[0];
const slots: ParagraphLineSlot[] = [slot(lines[0], 0, 800)];
let cursor = lines[0].length;
for (let i = 1; i < lines.length; i++) {
text += separators[i - 1] + lines[i];
cursor += 1; // separator
slots.push(slot(lines[i], cursor, 800 - i * 14));
cursor += lines[i].length;
}
const run = new TextRun({
id: "p0-t0",
pageIndex: 0,
bounds: { x: 0, y: 0, width: 100, height: 100 },
matrix: { a: 1, b: 0, c: 0, d: 1, e: 0, f: 800 },
text,
fontId: "pdf:1:LMRoman12",
fontSize: 12,
fill: { r: 0, g: 0, b: 0, a: 255 },
fontSubset: false,
pdfiumObjPtr: 0,
});
run.paragraphLineSlots = slots;
run.paragraphLineHeight = 14;
return run;
}
/**
* Build a single-sub-run TextRun whose own `mergedFrom*` arrays carry `text`
* as one object - the shape `planPartialEdit` diffs against. Used to exercise
* the surrogate-pair bailout directly.
*/
function makeSingleSubRun(text: string): TextRun {
const run = new TextRun({
id: "p0-t0",
pageIndex: 0,
bounds: { x: 0, y: 0, width: text.length * 6, height: 14 },
matrix: { a: 1, b: 0, c: 0, d: 1, e: 0, f: 800 },
text,
fontId: "pdf:1:LMRoman12",
fontSize: 12,
fill: { r: 0, g: 0, b: 0, a: 255 },
fontSubset: false,
pdfiumObjPtr: 0,
});
run.mergedFromPtrs = [200];
run.mergedFromTexts = [text];
run.mergedFromBounds = [{ x: 0, right: text.length * 6 }];
run.mergedFromCharStarts = [0];
return run;
}
describe("planPartialEdit surrogate-pair guard (astral chars)", () => {
it("bails (returns null) when prevText already contains an emoji surrogate pair", () => {
// "🎉" is two UTF-16 code units; the LCS indexes by code unit, so an
// existing astral char could split across keep/drop and emit a lone
// surrogate. The guard at partialEdit.ts must null the plan instead.
const run = makeSingleSubRun("🎉ab");
expect(planPartialEdit(run, "🎉ab", "🎉abc")).toBeNull();
});
it("returns a non-null plan for the same edit when prevText has NO surrogate", () => {
// Identical append, but an ASCII anchor instead of the emoji - proves the
// guard is specific to surrogate pairs and not a blanket bailout.
const run = makeSingleSubRun("Xab");
expect(planPartialEdit(run, "Xab", "Xabc")).not.toBeNull();
});
});
describe("planParagraphEdit slot-range line mapping", () => {
it("does NOT bail on a soft-wrapped paragraph (the collapse bug)", () => {
// 4 visual lines, but only ONE hard break: "aaa bbb\nccc ddd".
// split("\n") => 2 segments, slots => 4. The old guard bailed here.
const run = makeParagraph(["aaa", "bbb", "ccc", "ddd"], [" ", "\n", " "]);
const prev = run.text;
expect(prev).toBe("aaa bbb\nccc ddd");
const next = "Zaaa bbb\nccc ddd"; // insert "Z" at the very start
const plan = planParagraphEdit(run, prev, next);
expect(plan).not.toBeNull();
// Per-visual-line next text, slot-aligned (NOT \n-split).
expect(plan?.nextLines).toEqual(["Zaaa", "bbb", "ccc", "ddd"]);
// Only the hit slot (line 0) is in the per-slot edit list.
expect(plan?.perSlot.map((p) => p.slotIdx)).toEqual([0]);
});
it("maps an edit confined to a later soft-wrapped line to the right slot", () => {
const run = makeParagraph(["aaa", "bbb", "ccc", "ddd"], [" ", "\n", " "]);
const prev = run.text; // "aaa bbb\nccc ddd"
// Insert "X" at the start of the last visual line ("ddd" -> "Xddd").
const next = "aaa bbb\nccc Xddd";
const plan = planParagraphEdit(run, prev, next);
expect(plan).not.toBeNull();
expect(plan?.nextLines).toEqual(["aaa", "bbb", "ccc", "Xddd"]);
expect(plan?.perSlot.map((p) => p.slotIdx)).toEqual([3]);
});
it("bails when the edit changes the hard-break count (structural)", () => {
const run = makeParagraph(["aaa", "bbb", "ccc", "ddd"], [" ", "\n", " "]);
const prev = run.text;
// Type Enter inside the first line -> a NEW hard break.
const next = "aa\na bbb\nccc ddd";
expect(planParagraphEdit(run, prev, next)).toBeNull();
});
it("bails when the edit spans a soft-wrap separator (two slots)", () => {
const run = makeParagraph(["aaa", "bbb", "ccc", "ddd"], [" ", "\n", " "]);
const prev = run.text; // "aaa bbb\nccc ddd"
// Delete the soft-wrap space between "ccc" and "ddd" (merges two slots).
const next = "aaa bbb\ncccddd";
expect(planParagraphEdit(run, prev, next)).toBeNull();
});
it("bails when slot ranges don't tile run.text (desynced model)", () => {
const run = makeParagraph(["aaa", "bbb"], ["\n"]);
// Corrupt run.text so the slot ranges no longer tile it.
run.text = "aaa bbb EXTRA";
expect(planParagraphEdit(run, run.text, "Zaaa bbb EXTRA")).toBeNull();
});
it("forces a fresh word-split re-emit when a mid-line edit would SetText whitespace (the „ bug)", () => {
// A whole line as ONE sub-run carrying spaces (LaTeX one-object-per-line).
// A mid-line edit makes planPartialEdit a "modify" op whose surviving text
// still has spaces - SetText-ing that onto a no-space-glyph subset font
// paints „. planParagraphEdit must null the slot plan so the apply step
// re-emits the line word-split (spaces become positional gaps) instead.
const run = makeParagraph(["aaa bbb ccc", "ddd eee"], ["\n"]);
const prev = run.text; // "aaa bbb ccc\nddd eee"
const next = "aaa Xbb ccc\nddd eee"; // replace one char mid-line-0
const plan = planParagraphEdit(run, prev, next);
expect(plan).not.toBeNull();
const entry = plan?.perSlot.find((p) => p.slotIdx === 0);
expect(entry).toBeDefined();
// null plan => the apply step fresh-emits this line (word-split), avoiding „.
expect(entry?.plan).toBeNull();
expect(entry?.nextLine).toBe("aaa Xbb ccc");
});
it("keeps the in-place modify fast path for a single-word sub-run (no whitespace)", () => {
// Per-word sub-runs (no spaces inside any one) keep the surgical modify
// path - only multi-word single objects need the word-split re-emit.
const run = makeParagraph(["hello", "world"], ["\n"]);
const prev = run.text; // "hello\nworld"
const next = "hello\nworXd";
const plan = planParagraphEdit(run, prev, next);
expect(plan).not.toBeNull();
const entry = plan?.perSlot.find((p) => p.slotIdx === 1);
// A non-null plan => surgical in-place edit kept (sub-run has no spaces).
expect(entry?.plan).not.toBeNull();
});
it("handles an all-hard-break paragraph (initial-load shape) too", () => {
// Every visual line a hard break: this is the shape ParagraphGrouper
// builds at load. split("\n") == slots here, so it always worked - pin
// it so the slot-range path stays equivalent for the common case.
const run = makeParagraph(["one", "two", "three"], ["\n", "\n"]);
const prev = run.text;
expect(prev).toBe("one\ntwo\nthree");
const next = "one\ntwoX\nthree";
const plan = planParagraphEdit(run, prev, next);
expect(plan).not.toBeNull();
expect(plan?.nextLines).toEqual(["one", "twoX", "three"]);
expect(plan?.perSlot.map((p) => p.slotIdx)).toEqual([1]);
});
});
@@ -1,126 +0,0 @@
import { describe, it, expect } from "vitest";
import {
composeAffine,
invertAffine,
imageMatrixBounds,
remapImageMatrix,
transformRectAABB,
} from "@app/tools/pdfTextEditor/v2/model/affine";
import { DisplayTransform } from "@app/tools/pdfTextEditor/v2/model/DisplayTransform";
import type { Affine, PageRect } from "@app/tools/pdfTextEditor/v2/types";
const IDENTITY: Affine = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
function expectAffineClose(got: Affine, want: Affine): void {
for (const k of ["a", "b", "c", "d", "e", "f"] as const) {
expect(got[k]).toBeCloseTo(want[k], 4);
}
}
describe("affine helpers", () => {
it("invertAffine inverts a rotation+translation, identity on singular", () => {
const t: Affine = { a: 0, b: -1, c: 1, d: 0, e: 5, f: 7 };
const round = composeAffine(t, invertAffine(t));
expectAffineClose(round, IDENTITY);
// Degenerate (zero linear part) -> identity rather than NaN.
expectAffineClose(
invertAffine({ a: 0, b: 0, c: 0, d: 0, e: 3, f: 4 }),
IDENTITY,
);
});
it("imageMatrixBounds is the AABB of the unit square under the matrix", () => {
// 90deg-rotated 200x100 image -> 100 wide x 200 tall AABB.
const m: Affine = { a: 0, b: 200, c: -100, d: 0, e: 562, f: 100 };
const b = imageMatrixBounds(m);
expect(b).toEqual({ x: 462, y: 100, width: 100, height: 200 });
});
});
describe("remapImageMatrix - unrotated page stays byte-identical", () => {
const display = IDENTITY; // CropBox==MediaBox, /Rotate 0
it("moving an axis-aligned image only translates it", () => {
const prev: Affine = { a: 100, b: 0, c: 0, d: 50, e: 10, f: 20 };
const prevBounds: PageRect = { x: 10, y: 20, width: 100, height: 50 };
const nextBounds: PageRect = { x: 60, y: 80, width: 100, height: 50 };
expectAffineClose(remapImageMatrix(prev, prevBounds, nextBounds, display), {
a: 100,
b: 0,
c: 0,
d: 50,
e: 60,
f: 80,
});
});
it("resizing an axis-aligned image rebuilds (w,0,0,h,x,y)", () => {
const prev: Affine = { a: 100, b: 0, c: 0, d: 50, e: 10, f: 20 };
const prevBounds: PageRect = { x: 10, y: 20, width: 100, height: 50 };
const nextBounds: PageRect = { x: 10, y: 20, width: 200, height: 100 };
expectAffineClose(remapImageMatrix(prev, prevBounds, nextBounds, display), {
a: 200,
b: 0,
c: 0,
d: 100,
e: 10,
f: 20,
});
});
});
describe("remapImageMatrix - /Rotate 90 landscape page preserves orientation", () => {
// Portrait MediaBox 612x792 displayed landscape via /Rotate 90.
const display = DisplayTransform.fromCropAndRotate(
0,
0,
612,
792,
1,
792,
612,
);
// An image that displays upright as 200 wide x 100 tall has this raw matrix
// (rotated 90deg in raw space) and a 100x200 raw AABB.
const prev: Affine = { a: 0, b: 200, c: -100, d: 0, e: 562, f: 100 };
const prevBounds: PageRect = { x: 462, y: 100, width: 100, height: 200 };
it("a no-op move returns the original matrix unchanged (no flip)", () => {
const next = remapImageMatrix(prev, prevBounds, prevBounds, display);
expectAffineClose(next, prev);
});
it("a move keeps the image's linear part (orientation + aspect) intact", () => {
// Drag the displayed image by (+30, +40) px in display space. That is a
// raw-space translation of A^-1 * (30,40) = (-40, 30).
const nextBounds: PageRect = { x: 422, y: 130, width: 100, height: 200 };
const next = remapImageMatrix(prev, prevBounds, nextBounds, display);
// Linear part is byte-stable -> the image is NOT re-oriented by a move.
expect(next.a).toBeCloseTo(prev.a, 4);
expect(next.b).toBeCloseTo(prev.b, 4);
expect(next.c).toBeCloseTo(prev.c, 4);
expect(next.d).toBeCloseTo(prev.d, 4);
expect(next.e).toBeCloseTo(522, 4);
expect(next.f).toBeCloseTo(130, 4);
// And the image still DISPLAYS as 200 wide x 100 tall (landscape upright),
// not the swapped 100x200 the old counter-rotate path produced.
const dispBox = transformRectAABB(display, imageMatrixBounds(next));
expect(dispBox.width).toBeCloseTo(200, 3);
expect(dispBox.height).toBeCloseTo(100, 3);
});
it("a uniform resize scales display footprint without swapping w/h", () => {
// Halve the displayed size: 200x100 -> 100x50, anchored at same display
// lower-left. The displayed AABB stays landscape (wider than tall).
const half = remapImageMatrix(
prev,
prevBounds,
{ x: 512, y: 100, width: 50, height: 100 },
display,
);
const dispBox = transformRectAABB(display, imageMatrixBounds(half));
expect(dispBox.width).toBeCloseTo(100, 3);
expect(dispBox.height).toBeCloseTo(50, 3);
});
});
@@ -1,53 +0,0 @@
import { describe, it, expect } from "vitest";
import {
cloneParagraphLineSlot,
type ParagraphLineSlot,
} from "@app/tools/pdfTextEditor/v2/model/TextRun";
function mkSlot(): ParagraphLineSlot {
return {
startChar: 0,
endChar: 5,
baselineY: 100,
matrixE: 10,
containerPtr: 0,
fontId: "pdf:1:Helvetica",
fontSize: 12,
fontSubset: false,
mergedFromPtrs: [11, 22],
mergedFromTexts: ["He", "llo"],
mergedFromBounds: [
{ x: 0, right: 5 },
{ x: 5, right: 10 },
],
mergedFromCharStarts: [0, 2],
};
}
describe("cloneParagraphLineSlot", () => {
it("produces an equal but independent copy", () => {
const src = mkSlot();
const copy = cloneParagraphLineSlot(src);
expect(copy).toEqual(src);
// Nested arrays/objects must be fresh references, not shared.
expect(copy.mergedFromPtrs).not.toBe(src.mergedFromPtrs);
expect(copy.mergedFromTexts).not.toBe(src.mergedFromTexts);
expect(copy.mergedFromBounds).not.toBe(src.mergedFromBounds);
expect(copy.mergedFromBounds[0]).not.toBe(src.mergedFromBounds[0]);
expect(copy.mergedFromCharStarts).not.toBe(src.mergedFromCharStarts);
});
it("mutating the copy never touches the source (snapshot-safety)", () => {
const src = mkSlot();
const snapshot = cloneParagraphLineSlot(src);
// Simulate a later in-place edit of the live slot.
src.mergedFromPtrs.push(33);
src.mergedFromTexts[0] = "XX";
src.mergedFromBounds[0].right = 999;
src.mergedFromCharStarts[1] = 7;
expect(snapshot.mergedFromPtrs).toEqual([11, 22]);
expect(snapshot.mergedFromTexts).toEqual(["He", "llo"]);
expect(snapshot.mergedFromBounds[0].right).toBe(5);
expect(snapshot.mergedFromCharStarts).toEqual([0, 2]);
});
});
@@ -1,122 +0,0 @@
import { describe, it, expect } from "vitest";
import {
detectSaveRisks,
hasSaveRisks,
describeSaveRisks,
} from "@app/tools/pdfTextEditor/v2/util/documentRisks";
import type { EditorDocument } from "@app/tools/pdfTextEditor/v2/model/EditorDocument";
function mkDoc(opts: {
signatures?: number;
formType?: number;
throwOnSig?: boolean;
secHandlerRev?: number;
throwOnEncrypt?: boolean;
}): EditorDocument {
return {
docPtr: 1,
loadedPages: () => [{ pagePtr: 10 }],
module: {
FPDF_GetSignatureCount: () => {
if (opts.throwOnSig) throw new Error("no API");
return opts.signatures ?? 0;
},
FPDF_GetFormType: () => opts.formType ?? 0,
FPDF_GetSecurityHandlerRevision: () => {
if (opts.throwOnEncrypt) throw new Error("no API");
return opts.secHandlerRev ?? -1;
},
},
} as unknown as EditorDocument;
}
describe("detectSaveRisks", () => {
it("reports no risk for a plain document", () => {
const r = detectSaveRisks(mkDoc({}));
expect(r).toEqual({
signatures: 0,
xfaForm: false,
encrypted: false,
droppedChars: [],
});
expect(hasSaveRisks(r)).toBe(false);
});
it("flags digital signatures", () => {
const r = detectSaveRisks(mkDoc({ signatures: 2 }));
expect(r.signatures).toBe(2);
expect(hasSaveRisks(r)).toBe(true);
expect(describeSaveRisks(r)).toEqual([
"2 digital signatures will be invalidated.",
]);
});
it("flags XFA forms (formType 2/3) but not plain AcroForm (1)", () => {
expect(detectSaveRisks(mkDoc({ formType: 1 })).xfaForm).toBe(false);
expect(detectSaveRisks(mkDoc({ formType: 2 })).xfaForm).toBe(true);
expect(detectSaveRisks(mkDoc({ formType: 3 })).xfaForm).toBe(true);
});
it("singular wording for one signature", () => {
expect(
describeSaveRisks({
signatures: 1,
xfaForm: false,
encrypted: false,
droppedChars: [],
}),
).toEqual(["1 digital signature will be invalidated."]);
});
it("flags characters dropped because no font could render them", () => {
const r = {
signatures: 0,
xfaForm: false,
encrypted: false,
droppedChars: ["中", "文"],
};
expect(hasSaveRisks(r)).toBe(true);
expect(describeSaveRisks(r)).toEqual([
"Some characters could not be embedded in any available font and were dropped: 中 文",
]);
});
it("truncates a long dropped-char list with a +N more suffix", () => {
const dropped = Array.from({ length: 15 }, (_, i) =>
String.fromCharCode(0x4e00 + i),
);
const line = describeSaveRisks({
signatures: 0,
xfaForm: false,
encrypted: false,
droppedChars: dropped,
})[0];
expect(line).toContain("(+3 more)");
});
it("clamps negative signature counts and survives a missing API", () => {
expect(detectSaveRisks(mkDoc({ signatures: -1 })).signatures).toBe(0);
expect(detectSaveRisks(mkDoc({ throwOnSig: true })).signatures).toBe(0);
});
it("combines both risks", () => {
const r = detectSaveRisks(mkDoc({ signatures: 1, formType: 2 }));
expect(describeSaveRisks(r)).toEqual([
"1 digital signature will be invalidated.",
"Interactive XFA form data may be lost.",
]);
});
it("flags an encrypted document and survives a missing API", () => {
expect(detectSaveRisks(mkDoc({ secHandlerRev: -1 })).encrypted).toBe(false);
const r = detectSaveRisks(mkDoc({ secHandlerRev: 3 }));
expect(r.encrypted).toBe(true);
expect(hasSaveRisks(r)).toBe(true);
expect(describeSaveRisks(r)).toContain(
"This PDF is encrypted; the saved copy will NOT be encrypted (password and access restrictions are removed).",
);
expect(detectSaveRisks(mkDoc({ throwOnEncrypt: true })).encrypted).toBe(
false,
);
});
});

Some files were not shown because too many files have changed in this diff Show More