diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 7c60bf9..986b65e 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -2,7 +2,7 @@ version: 2 updates: - package-ecosystem: "github-actions" directory: "/" - target-branch: "v2.3" + target-branch: "v2.4" schedule: interval: "weekly" pull-request-branch-name: @@ -12,7 +12,7 @@ updates: prefix: "🔧[Config] " - package-ecosystem: "npm" directory: "/" - target-branch: "v2.3" + target-branch: "v2.4" schedule: interval: "weekly" open-pull-requests-limit: 5 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8aeab54..b7b4136 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,7 +6,7 @@ on: branches: - main - v2 - - v2.3 + - v2.4 permissions: contents: read @@ -88,6 +88,12 @@ jobs: - name: Verify responsive navigation, metadata layouts and accessibility run: node tests/browser/responsive.mjs + - name: Verify scanner inputs, orientation, lifecycle and privacy + run: node tests/browser/scanner.mjs + + - name: Verify scanner PDF output, source quality and lifecycle + run: node tests/browser/scanner-pdf.mjs + - name: Inspect isolated release review artifact run: node scripts/inspect-release-artifact.mjs @@ -107,4 +113,6 @@ jobs: path: | .ts-build/production-smoke .ts-build/responsive + .ts-build/scanner-qa + .ts-build/scanner-pdf-qa retention-days: 7 diff --git a/.github/workflows/security-monitoring.yml b/.github/workflows/security-monitoring.yml index 5850615..9c8c232 100644 --- a/.github/workflows/security-monitoring.yml +++ b/.github/workflows/security-monitoring.yml @@ -2,9 +2,9 @@ name: Security monitoring on: pull_request: - branches: [v2.3, main] + branches: [v2.4, main] push: - branches: [v2.3, main] + branches: [v2.4, main] schedule: - cron: '29 3 * * 3' workflow_dispatch: diff --git a/AGENTS.md b/AGENTS.md index af82669..dba696e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,13 +2,13 @@ ## Protected branches -- `main` is production-only. `v2.3` is the active integration branch for the v2.3.0 development cycle. -- Never commit feature, fix, test, or chore work directly to `main` or `v2.3`. +- `main` is production-only. `v2.4` is the active integration branch for the v2.4.0 development cycle, bootstrapped from production `main` after v2.3.0. +- Never commit feature, fix, test, or chore work directly to `main` or `v2.4`. ## Development work -- Create short-lived `feat/*`, `fix/*`, `test/*`, or `chore/*` branches from `v2.3`. -- Sprint and routine development pull requests target `v2.3`, not `main`. +- Create short-lived `feat/*`, `fix/*`, `test/*`, or `chore/*` branches from `v2.4`. +- Sprint and routine development pull requests target `v2.4`, not `main`. - After a successful merge, delete only the merged short-lived branch when cleanup is authorized. ## Commit messages @@ -30,8 +30,8 @@ ## Production promotion -- Normal development reaches `main` only through a dedicated release or hardening pull request from `v2.3`. -- Creating the v2.3.0 tag or release requires separate explicit authorization after final verification. +- Normal development reaches `main` only through a dedicated release or hardening pull request from `v2.4`. +- Creating the v2.4.0 tag or release requires separate explicit authorization after final verification. ## Hotfixes diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e54d3a..7993ffc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 2.4.0 — Unreleased + +- Add source-resolution Scan to PDF with per-page appearance, EXIF-aware ordered pages, A4 fitting, cancellable generation, local PDF preview/download, export workload limits and cleanup. + +- Add Document Scanner Core with local JPEG/PNG/WebP input, page ordering, removal, clear, EXIF-aware bounded previews, and Original/Grayscale/Document modes. +- Bound the scanner queue to 20 pages and 200 MiB, release temporary resources, and invalidate cancelled or replaced preview work. +- Establish v2.4 integration policy and scanner regression/browser coverage. PDF export and scanner OCR are reserved for later sprints. + ## 2.3.0 — Release candidate, unpublished ### Security and reliability diff --git a/README.md b/README.md index 685215a..4c9077b 100644 --- a/README.md +++ b/README.md @@ -86,3 +86,7 @@ Release history is recorded in the [changelog](./CHANGELOG.md). The current v2.0 Source: [SecureToolsProject/Secure_Tools](https://github.com/SecureToolsProject/Secure_Tools) See [LICENSE](./LICENSE). Vendored third-party code retains its own license beside each dependency. + +## v2.4 development + +Document Scanner Core is available in the development build at `/scan/document/`: local multi-image input, accessible ordering, orientation-aware previews, and Original/Grayscale/Document appearance. Scan to PDF now exports source-resolution pages with per-page appearance, progress/cancel, local PDF preview and download. Optional scanner OCR remains planned. See [Sprint 24B implementation and QA](docs/sprint-24b-scan-to-pdf.md). See [Sprint 24A implementation and QA](docs/sprint-24a-scanner-core.md). diff --git a/docs/architecture.md b/docs/architecture.md index 7ec1dd6..4c1406b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -74,3 +74,13 @@ Secure Tools may evolve as both: - a discovery hub for separately deployed companion applications that need different runtime or resource models. This is a direction, not a current integration contract. There is no companion registry, external-application schema, plugin framework, service discovery mechanism, or v3 navigation implementation in the present architecture. + +## Document Scanner Core (v2.4 / 24A) + +`tools/shared/scan.ts` decodes through the existing signature-validated, EXIF-aware image helper, bounds previews to 1,000 pixels on the longest edge, composites transparency over white, and provides deterministic pixel preprocessing. `tools/scan/document/state.ts` holds ordered source Files and preview URLs, with 20-page/200-MiB aggregate limits, per-operation cancellation and stale-result guards. It releases replaced/removed/cleared URLs and decoded/canvas resources. Only one current queue operation may publish results. The UI is a static ES module with native picker, drop/paste inputs and keyboard ordering. + +Appearance is recorded per page; cancelling a batch retains completed previews. Apply to all pages retries the selected mode. Originals remain immutable and are retained as File references for future full-resolution export. 24B must decode originals again and must not compose a PDF from bounded thumbnails. Shared OCR/PDF services remain unchanged. No new external service, persistence, runtime dependency or CSP relaxation is introduced. + +## Scanner PDF export (v2.4 / 24B) + +`tools/scan/document/pdf.ts` composes ordered source Files with their per-page modes through the existing Images to PDF writer. `renderScanImage` shares preview preprocessing at full source resolution, using bounded pixel strips; PNG output preserves the document threshold. Exports are serialized and guarded against stale publication. `result.js` reuses LocalPdfRenderer for a bounded canvas preview and destroys its worker/document on invalidation. The UI owns output Blob/download lifetime; changes to source/order/appearance discard the result. See [24B implementation, budgets and verification](sprint-24b-scan-to-pdf.md). diff --git a/docs/development-workflow.md b/docs/development-workflow.md index f93a1f0..e0050a8 100644 --- a/docs/development-workflow.md +++ b/docs/development-workflow.md @@ -5,28 +5,30 @@ Secure Tools separates product versions from Sprint numbers. A Sprint is a bound ## Branch roles - `main` is the production branch. Routine development does not target it. -- `v2.3` is the active integration branch for the v2.3.0 cycle. -- Short-lived `feat/*`, `fix/*`, `test/*`, and `chore/*` branches start from `v2.3` and return through pull requests into `v2.3`. -- Direct feature or fix commits to `main` or `v2.3` are prohibited. +- `v2.4` is the active integration branch for the v2.4.0 cycle. +- Short-lived `feat/*`, `fix/*`, `test/*`, and `chore/*` branches start from `v2.4` and return through pull requests into `v2.4`. +- Direct feature or fix commits to `main` or `v2.4` are prohibited. ```text main (production) ↑ -release PR after v2.3 hardening +release PR after v2.4 hardening ↑ -v2.3 (active integration) +v2.4 (active integration) ↑ Sprint PRs ↑ feat/* fix/* test/* chore/* ``` +The v2.4 branch starts at production main commit `2eb8e865e32558bfd031cd65c85d5d0fea64f5c7`. The policy migration is reviewed as a separate prerequisite commit in the first v2.4 PR; no integration or production merge is implied. Existing v2.3 dependency proposals remain unmerged and require separate review. + ## Sprint delivery -1. Update local `v2.3` from `origin/v2.3`. +1. Update local `v2.4` from `origin/v2.4`. 2. Create a short-lived branch from that exact integration state. 3. Commit and validate only the Sprint’s intended changes. -4. Open a pull request into `v2.3` and wait for required CI. +4. Open a pull request into `v2.4` and wait for required CI. 5. Treat review and merge as a separate step. An agent does not merge its own pull request or enable auto-merge unless the user explicitly authorizes that specific action. 6. After a successful merge and verification, remove the merged short-lived branch when branch cleanup is authorized. @@ -40,7 +42,7 @@ CI validates non-merge commits introduced by the pull request’s actual base-to ## Production release -The v2.2.0 cycle is released. The v2.3.0 cycle is active development. After the v2.3.0 scope is integrated, complete release hardening and final verification on `v2.3`. Promote it through a dedicated `v2.3` → `main` pull request. Only after that pull request is explicitly reviewed and merged may a separately authorized task create the v2.3.0 tag and release. +The v2.3.0 cycle is released. The v2.4.0 cycle is active development. After the v2.4.0 scope is integrated, complete release hardening and final verification on `v2.4`. Promote it through a dedicated `v2.4` → `main` pull request. Only after that pull request is explicitly reviewed and merged may a separately authorized task create the v2.4.0 tag and release. ## Hotfixes @@ -48,4 +50,4 @@ Urgent production fixes use a dedicated `hotfix/*` branch and pull request into ## Enforced pull request policy -CI permits routine `feat/*`, `fix/*`, `test/*`, and `chore/*` pull requests into `v2.3`. Pull requests into `main` pass the branch-policy gate only when the head is exactly `v2.3` or a dedicated `hotfix/*` branch. The repository protects both long-lived branches with required pull requests, the existing `Validate static tools` check, resolved review conversations, blocked force pushes, and blocked deletion. Because the repository currently has one maintainer, an approving-review count is not required; explicit merge authorization remains mandatory. +CI permits routine `feat/*`, `fix/*`, `test/*`, and `chore/*` pull requests into `v2.4`. Pull requests into `main` pass the branch-policy gate only when the head is exactly `v2.4` or a dedicated `hotfix/*` branch. Existing main/v2.3 branch protections are unchanged. The new v2.4 branch does not inherit remote branch protections automatically; equivalent required-PR/check, resolved-conversation, force-push and deletion protections remain an administrator follow-up. This PR enforces the branch policy in CI but does not claim to configure remote protection settings. Because the repository currently has one maintainer, an approving-review count is not required; explicit merge authorization remains mandatory. diff --git a/docs/sprint-24a-scanner-core.md b/docs/sprint-24a-scanner-core.md new file mode 100644 index 0000000..8618a24 --- /dev/null +++ b/docs/sprint-24a-scanner-core.md @@ -0,0 +1,71 @@ +# Sprint 24A — Document Scanner Core + +## Implementation + +The v2.4 development scanner is `/scan/document/`. It accepts signature-validated JPEG, PNG and WebP from the native multi-file picker, drop and paste. Pages can be moved with semantic keyboard-accessible buttons, removed, or cleared. All six existing locales are supported. Original, Grayscale and Document modes operate locally; Document uses a deterministic threshold of 160, with no corner detection or perspective correction. + +Previews retain aspect ratio and EXIF normalization through `decodeImage`. Each preview is at most 1,000 pixels on its longest edge. Source File references remain unchanged; decoded bitmaps and canvas backing stores are released after processing. Preview URLs are revoked on replacement, removal, clear and page exit. The queue admits at most 20 pages / 200 MiB total, plus existing 50-MiB-file / 50-megapixel / 16,384-pixel decoder limits. Oversized or broken inputs produce recoverable messages, while valid files in the batch remain available. + +Adding another batch cancels publication from the previous batch. Clear and cancellation invalidate in-flight results. Cancelling appearance changes retains completed pages with their actual mode labels; Apply to all pages is the retry mechanism. Native decoding/encoding cannot be interrupted mid-call, but resources are released and stale results cannot enter the queue. Replacement previews wait for existing native work to finish, preventing overlapping full-resolution decodes under rapid input changes. + +## Branch policy + +Production `main` and tag v2.3.0 were inspected at `2eb8e865e32558bfd031cd65c85d5d0fea64f5c7`; no v2.4 branch existed. v2.4 was bootstrapped from that production commit. The prerequisite policy migration is an independent Config commit in the scanner feature branch, covering AGENTS, workflow documentation, CI/security triggers, Dependabot targets and policy tests. It remains reviewable in the v2.4 PR; neither integration nor production was merged. Existing v2.3 maintenance PRs were not changed. Remote protections do not inherit automatically onto a newly created branch; equivalent v2.4 protection settings remain an administrator follow-up. Dependabot’s new target configuration takes effect when present on the repository default branch; this task does not promote development changes into main. + +## Verification + +- `npm run typecheck`: passed. +- `npm run compile:ts`: passed. +- `node tests/scanner.test.mjs`: passed (state/order, all modes, invalid inputs, limits, stale completion, orientation contract, resource cleanup). +- `npm run build`: passed; 20 canonical pages, 17 existing redirects, pinned OCR/font asset checks unchanged. +- `npm test`: local functional/regression tests passed through release artifact checks; the HTTP hardening gate failed because host AdGuard rewrites CSP. The strict expected policy was preserved. Clean hosted CI is required for the full result. +- `node tests/browser/scanner.mjs`: completed 30 viewport/locale functional cases (320×568, 390×844, 844×390, 768×1024, 1280×900; en/ko/ja/es/de/fr), actual JPEG/PNG/WebP inputs, EXIF orientation=6 JPEG, grayscale pixels, Document mode, keyboard ordering/focus, removal/clear, drop/paste, two 12-megapixel photos, stale clear, URL cleanup. The local privacy gate failed on injected `local.adguard.org` traffic/CSP mutations; it was not waived. The same strict test is included in hosted CI. +- Browser screenshots were visually inspected at Korean 320px and English desktop widths. Physical mobile, Firefox and Edge were not exercised locally. + +No upload, telemetry, document persistence, new dependency or global CSP change was added. Host-injected traffic is recorded separately from app behavior; a clean privacy pass must come from hosted CI. Local diagnostic output and screenshots are in ignored `.ts-build/scanner-qa/`; the hosted failure artifact retains the same directory. + +## Follow-ups + +24B: compose the ordered original source images with shared PDF tooling, applying the chosen per-page appearance at export resolution; add output preview/download, export budgets, cancellation and cleanup. Do not export thumbnail pixels. 24C: adapt the existing shared OCR worker service. 24D: adapt existing OCR geometry/searchable-PDF capabilities. No PDF export, OCR controls, searchable-PDF rewrite, library replacement, production deployment, release tag or merge is included here. + +## Changed files + +- `.github/dependabot.yml` +- `.github/workflows/ci.yml` +- `.github/workflows/security-monitoring.yml` +- `AGENTS.md` +- `CHANGELOG.md` +- `README.md` +- `docs/architecture.md` +- `docs/development-workflow.md` +- `docs/sprint-24a-scanner-core.md` +- `docs/tool-status.md` +- `js/i18n.js` +- `js/locales/document-scanner.js` +- `scripts/site-routes.mjs` +- `scripts/typescript-modules.mjs` +- `scripts/validate-branch-policy.mjs` +- `sitemap.xml` +- `tests/action-pins.test.mjs` +- `tests/branch-policy.test.mjs` +- `tests/browser/scanner.mjs` +- `tests/category-availability.test.mjs` +- `tests/ci-foundation.test.mjs` +- `tests/i18n-quality.test.mjs` +- `tests/pdf-to-text.test.mjs` +- `tests/release-hardening-http.test.mjs` +- `tests/run-all.mjs` +- `tests/scanner.test.mjs` +- `tests/security-monitoring.test.mjs` +- `tests/seo-foundation.test.mjs` +- `tests/typescript-foundation.test.mjs` +- `tests/url-namespace.test.mjs` +- `tools/scan/document/app.js` +- `tools/scan/document/index.html` +- `tools/scan/document/state.ts` +- `tools/scan/document/tool.css` +- `tools/scan/index.html` +- `tools/shared/image.d.ts` +- `tools/shared/scan.ts` +- `tsconfig.build.json` +- `tsconfig.json` diff --git a/docs/sprint-24b-scan-to-pdf.md b/docs/sprint-24b-scan-to-pdf.md new file mode 100644 index 0000000..a21ee6b --- /dev/null +++ b/docs/sprint-24b-scan-to-pdf.md @@ -0,0 +1,59 @@ +# Sprint 24B — Scanner to PDF + +## Implementation and dependency + +The working tree was clean. PR #141 was inspected and remained open at `f33acada5e0406fdb3d20a9e938ce62556c6acec`. This feature branch (`feat/v2.4-scan-to-pdf`) starts from that exact head, preserving its commits without modifying or merging #141. The requested PR base is v2.4: until #141 merges, its prerequisite commits appear in the comparison. Review the 24B-specific range from the recorded parent head; merge #141 through a separately authorized review first. No production branch, release tag or deployment is changed by this task. + +`tools/scan/document/pdf.ts` adapts the existing Images to PDF `createPdfBlob` writer and vendored jsPDF. It snapshots ordered source Files and their actual per-page modes, decodes with the existing EXIF-aware helper, and calls the shared scan rasterizer at full source resolution. It never exports a preview URL or a 1,000px thumbnail. Lossless PNG embedding preserves the deterministic document threshold; grayscale and original modes are also represented in the exported pixels. The existing A4/automatic-orientation/10-mm-margin contain-fit convention is reused without new paper controls or dependencies. + +The shared composition function now supports optional AbortSignal, asynchronous image conversion and a PNG format override while retaining its original JPEG defaults for Images to PDF. The shared scan rasterizer exposes source-resolution rendering and processes non-original modes in 64-row strips, reusing the same deterministic pixel function as previews. The preview entry point retains its 1,000px bound and owns bitmap cleanup. + +The scanner UI adds Create PDF, progress/status, keyboard-accessible Cancel, retry through Create PDF, actual PDF.js canvas preview with previous/next navigation, and native PDF download. PDF.js is the existing local renderer; there is no iframe/object, CSP exception, document upload or new service. Input addition, page order/removal, appearance application, clear/reset and page exit invalidate generated output and destroy preview resources. The output Blob remains only while its matching page state is current; download URLs use the existing delayed revocation helper. + +## Limits and lifecycle + +- Existing admission: 20 pages, 200 MiB source total, 50 MiB per source; shared decode dimensions/pixel bounds remain intact. +- Export: at most 12,000,000 decoded pixels per image and 24,000,000 total; cumulative encoded page images and final PDF are limited to 64 MiB. Larger inputs remain previewable but export reports a recoverable limit error; no silent quality reduction is performed. +- One export writer runs at a time, including superseded jobs. A generation guard suppresses old progress/results even if a native writer ignores abort. Scanner preview work remains serialized separately; an input change can briefly overlap one native export operation and one preview decode, rather than accumulating export writers. +- Bitmaps close in composition `finally`; raster canvases shrink to 1×1 on success/error/cancel. Strip processing yields to input and checks cancellation. PDF preview buffers are bounded to 900px on the longest edge and reset after rendering. PDF.js loading/rendering tasks and workers are destroyed on invalidation/reset. Only the output Blob and the active renderer's document buffers remain for preview/download. +- Native decode, canvas encoding, synchronous jsPDF image embedding and final serialization cannot be interrupted mid-call. Cancellation is checked around those calls and between strips/pages, and prevents output publication. This is cancellation by invalidation during an uninterruptible native call, not a claim of hard process termination. + +## Validation + +- `npm run typecheck`, `npm run compile:ts`, `npm run build`: passed locally; 20 canonical routes / 17 redirects; pinned assets unchanged. +- `node tests/scanner-pdf.test.mjs`: passed. Real jsPDF output reloads with pdf-lib; state/order/mode snapshots, portrait/landscape geometry, pixel/page/byte budgets, source-resolution strip rasterization, mid-strip cancellation, bitmap/canvas cleanup, serialized rapid replacement, stale results, errors and retry are covered. +- `node tests/scanner.test.mjs`, `node tests/image-to-pdf.test.mjs`, `node tests/i18n-quality.test.mjs`, `node tests/typescript-foundation.test.mjs`, `node tests/verify-browser-export-artifacts.mjs`: passed. Existing JPEG composition remains compatible; all six locale key sets are checked. +- `npm test`: functional/regression tests passed through artifact checks locally; HTTP security hardening rejects AdGuard's injected CSP mutations. The strict policy was not relaxed. The remaining retained export artifact check was also run independently and passed. +- `node tests/browser/scanner-pdf.mjs`: real Chromium completed ten PDF-result viewport cases (en/ko × 320×568, 390×844, 844×390, 768×1024, 1280×900). Two native four-page PDF downloads were parsed and rendered. Embedded images retained 1,200×2,000 / 2,000×1,200 dimensions while queue previews were 600×1,000 / 1,000×600; EXIF orientation=6 exported 30×60. Rendered sample RGB values were `[92,92,92]` (Grayscale), `[220,40,20]` (Original), `[0,0,0]` (Document), with the exact reordered portrait/landscape sequence. Preview navigation, cancellation, rapid mutation, fault-injected writer error/retry, mode invalidation, over-budget rejection, one download per click, URL revocation and worker teardown are exercised. +- Browser screenshots were visually inspected. Local strict CSP/network checks detect host-injected `local.adguard.org` requests; document POST/mutation requests were absent. Clean hosted CI runs the same strict scanner-PDF gate alongside original scanner, existing PDF/Image/OCR, responsive/accessibility, security-header and artifact gates. The final hosted run links/status are recorded in the PR to avoid making local interference appear to pass. + +Physical mobile devices, Firefox and Edge were not tested locally. The Chromium results are browser automation and visual review, not a claim of physical-device QA. Output contains raster document pages; OCR/searchable text is not added. + +## 24C follow-ups + +Reuse the existing OCR service for optional scanner text recognition, including English/Korean/combined selection, progress, cancellation, worker reuse, retry and normalized geometry. Keep ordinary PDF creation independent of OCR. Searchable-PDF adapter work remains 24D; neither existing OCR initialization nor searchable-PDF writer should be duplicated. + +## Changed paths (24B only, relative to the #141 head) + +- `.github/workflows/ci.yml` +- `CHANGELOG.md` +- `README.md` +- `docs/architecture.md` +- `docs/sprint-24b-scan-to-pdf.md` +- `docs/tool-status.md` +- `js/locales/document-scanner.js` +- `scripts/stage-typescript-test-dependencies.mjs` +- `scripts/typescript-modules.mjs` +- `tests/browser/scanner-pdf.mjs` +- `tests/i18n-quality.test.mjs` +- `tests/run-all.mjs` +- `tests/scanner-pdf.test.mjs` +- `tests/typescript-foundation.test.mjs` +- `tools/pdf/images-to-pdf/pdf.d.ts` +- `tools/pdf/images-to-pdf/pdf.js` +- `tools/scan/document/app.js` +- `tools/scan/document/index.html` +- `tools/scan/document/pdf.ts` +- `tools/scan/document/result.js` +- `tools/scan/document/tool.css` +- `tools/shared/scan.ts` diff --git a/docs/tool-status.md b/docs/tool-status.md index f92f717..fe4701d 100644 --- a/docs/tool-status.md +++ b/docs/tool-status.md @@ -16,12 +16,13 @@ | Image | [Image Metadata Inspector & Cleaner](https://tools.securetools.app/image/metadata/) | Production | Supported JPEG, PNG, WebP metadata | | Image | [Image → Text OCR](https://tools.securetools.app/image/to-text/) | Production | One PNG, JPEG, or WebP → editable English/Korean text | | Privacy | [Privacy hub](https://tools.securetools.app/privacy/) | Production hub | Navigation to Image and PDF metadata tools | -| Scan/OCR | Category surface | Planned | No production processing tool | +| Scan/OCR | Category surface | Available | Image/PDF OCR links; Document Scanner Core in v2.4 development | +| Scan/OCR | Document Scanner | Development (24A/24B) | JPEG/PNG/WebP; arrange/preprocess pages; source-resolution PDF preview/download; no scanner OCR yet | | Media | Category surface | Planned | No production processing tool | “Production” means linked and covered by the current repository validation. “Planned” cards are non-interactive. Secure Tools may later link separately deployed companion applications, but no Companion status or integration exists on the live site today. -The Image category exposes the tested OCR runtime through a single-image Image → Text workflow with English, Korean, and combined recognition. The broader Scan/OCR category remains planned; PDF OCR and searchable PDF output are deferred. +The Image category exposes the tested OCR runtime through a single-image Image → Text workflow with English, Korean, and combined recognition. PDF OCR and searchable PDF output already exist in PDF to Text. Scanner Core is available in v2.4 development; scanner PDF export is implemented in 24B and optional OCR remains deferred to 24C. ## Shared Image boundaries @@ -79,7 +80,7 @@ Inspects Title, Author, Subject, Keywords, Creator, Producer, Creation Date, and ## Deferred directions -Broader PDF modification, compression, encryption, XMP/structural sanitization, PDF OCR, searchable PDF output, broader Scan/OCR workflows, Media, and offline/PWA work remain deferred. Separately deployed companion applications are an architectural possibility, not a current product status or integration. +Broader PDF modification, compression, encryption, XMP/structural sanitization, scanner PDF export/OCR integration, broader Scan/OCR workflows, Media, and offline/PWA work remain deferred. Separately deployed companion applications are an architectural possibility, not a current product status or integration. ## Related guarantees diff --git a/js/i18n.js b/js/i18n.js index 9542849..a772eb8 100644 --- a/js/i18n.js +++ b/js/i18n.js @@ -1,3 +1,4 @@ +import { documentScannerLocales } from "./locales/document-scanner.js"; import { en } from "./locales/en.js"; import { ko } from "./locales/ko.js"; import { ja } from "./locales/ja.js"; @@ -16,9 +17,10 @@ const STORAGE_KEY = "secure-tools-language"; const baseTranslations = { en, ko, ja, es, de, fr }; export const translations = Object.fromEntries(Object.entries(baseTranslations).map(([language, catalog]) => [language, { ...catalog, - metadata: { ...catalog.metadata, imageResize: imageResizeLocales[language].metadata, imageCompressor: imageCompressorLocales[language].metadata, imageMetadata: imageMetadataLocales[language].metadata, imageToText: imageToTextLocales[language].metadata, pdfToText: pdfToTextLocales[language].metadata, privacyCategory: privacyHubLocales[language].metadata }, + metadata: { ...catalog.metadata, documentScanner: documentScannerLocales[language].metadata, imageResize: imageResizeLocales[language].metadata, imageCompressor: imageCompressorLocales[language].metadata, imageMetadata: imageMetadataLocales[language].metadata, imageToText: imageToTextLocales[language].metadata, pdfToText: pdfToTextLocales[language].metadata, privacyCategory: privacyHubLocales[language].metadata }, tools: { ...catalog.tools, imageMetadata: imageMetadataLocales[language].toolName, imageToText: imageToTextLocales[language].toolName, pdfToText: pdfToTextLocales[language].toolName, categoryDescriptions: { ...catalog.tools.categoryDescriptions, privacy: privacyHubLocales[language].categoryDescription } }, categories: { ...catalog.categories, pdf: { ...catalog.categories.pdf, toText: pdfToTextLocales[language].categoryDescription }, image: { ...catalog.categories.image, metadata: imageMetadataLocales[language].categoryDescription, toText: imageToTextLocales[language].categoryDescription }, scan: { ...catalog.categories.scan, pdfToText: pdfToTextLocales[language].categoryDescription } }, + documentScanner: documentScannerLocales[language].copy, imageResize: imageResizeLocales[language].copy, imageCompressor: imageCompressorLocales[language].copy, imageMetadata: { ...imageMetadataLocales[language].copy, source: { ...imageMetadataLocales[language].copy.source, ...metadataUxLocales[language].image.source }, inspector: { ...imageMetadataLocales[language].copy.inspector, ...metadataUxLocales[language].image.inspector }, clean: { ...imageMetadataLocales[language].copy.clean, ...metadataUxLocales[language].image.clean }, policy: metadataUxLocales[language].image.policy }, diff --git a/js/locales/document-scanner.js b/js/locales/document-scanner.js new file mode 100644 index 0000000..ed323a4 --- /dev/null +++ b/js/locales/document-scanner.js @@ -0,0 +1,368 @@ +export const documentScannerLocales = { + "en": { + "metadata": { + "title": "Document Scanner — Secure Tools", + "description": "Arrange and clean document images on this device." + }, + "copy": { + "title": "Document Scanner", + "eyebrow": "Local scan tool", + "description": "Arrange and clean document images on this device.", + "add": "Add images", + "inputHelp": "Choose, drop or paste JPEG, PNG or WebP images. Up to 20 pages and 200 MiB total; 50 MiB per image.", + "appearance": "Scan appearance", + "mode": "Appearance for new pages", + "original": "Original", + "grayscale": "Grayscale", + "document": "Document", + "modeHelp": "Document mode uses a fixed black-and-white threshold. No automatic cropping or corner detection.", + "apply": "Apply to all pages", + "cancel": "Cancel processing", + "clear": "Clear all", + "scope": "Create PDFs locally. Optional text recognition is coming later.", + "pages": "Document pages", + "empty": "No pages added yet.", + "count": "{count} pages", + "preview": "Page {page} preview", + "up": "Move up", + "down": "Move down", + "remove": "Remove", + "processing": "Processing locally… {count} pages ready.", + "cancelled": "Processing cancelled. Completed previews remain available.", + "added": "Added {count} pages.", + "rejected": "Added {added} pages. Could not add: {names}", + "limit": "Image or queue limit exceeded. Try fewer or smaller images.", + "unsupported": "Unsupported or invalid image. Use JPEG, PNG or WebP.", + "decode": "Could not decode this image. Try another file.", + "failure": "Could not process previews. Try again or use smaller images.", + "cleared": "All pages cleared.", + "applied": "Appearance applied to all pages.", + "removed": "Page removed.", + "reordered": "Page order updated.", + "pdfCreate": "Create PDF", + "pdfCancel": "Cancel PDF", + "pdfProgressLabel": "PDF generation progress", + "pdfHelp": "A4, automatic orientation, 10 mm margins. Export limits: 12 megapixels per image, 24 megapixels total and 64 MiB output.", + "pdfResult": "Generated PDF", + "pdfPreview": "Generated PDF page preview", + "pdfPrevious": "Previous page", + "pdfNext": "Next page", + "pdfDownload": "Download PDF", + "pdfLoading": "Loading PDF preview…", + "pdfPage": "Page {page} of {total}", + "pdfProgress": "Creating PDF locally… {done} of {total} pages.", + "pdfReady": "PDF ready. Review the preview or download.", + "pdfLimit": "Export limit exceeded. Use fewer or smaller source images.", + "pdfError": "Could not create PDF. Try again or use smaller images.", + "pdfCancelled": "PDF creation cancelled. Your scan pages are unchanged.", + "pdfDownloaded": "PDF download started.", + "pdfPreviewError": "PDF preview unavailable. You can download the PDF or create it again.", + "pdfDownloadError": "Could not start the download. Try downloading again." + } + }, + "ko": { + "metadata": { + "title": "문서 스캐너 — Secure Tools", + "description": "이 기기에서 문서 이미지를 정렬하고 보정합니다." + }, + "copy": { + "title": "문서 스캐너", + "eyebrow": "로컬 스캔 도구", + "description": "이 기기에서 문서 이미지를 정렬하고 보정합니다.", + "add": "이미지 추가", + "inputHelp": "JPEG, PNG, WebP 이미지를 선택하거나 끌어 놓거나 붙여넣으세요. 최대 20장, 합계 200MiB, 이미지당 50MiB입니다.", + "appearance": "스캔 모양", + "mode": "새 페이지의 모양", + "original": "원본", + "grayscale": "회색조", + "document": "문서", + "modeHelp": "문서 모드는 고정 임계값으로 흑백 처리합니다. 자동 자르기나 모서리 감지는 지원하지 않습니다.", + "apply": "모든 페이지에 적용", + "cancel": "처리 취소", + "clear": "모두 지우기", + "scope": "기기에서 PDF를 만듭니다. 선택적 문자 인식은 추후 제공할 예정입니다.", + "pages": "문서 페이지", + "empty": "아직 추가된 페이지가 없습니다.", + "count": "{count}페이지", + "preview": "{page}페이지 미리보기", + "up": "위로 이동", + "down": "아래로 이동", + "remove": "제거", + "processing": "기기에서 처리 중… {count}페이지 준비됨.", + "cancelled": "처리를 취소했습니다. 완료된 미리보기는 유지됩니다.", + "added": "{count}페이지를 추가했습니다.", + "rejected": "{added}페이지 추가됨. 추가 실패: {names}", + "limit": "이미지 또는 대기열 제한을 초과했습니다. 이미지 수나 크기를 줄여 주세요.", + "unsupported": "지원하지 않거나 잘못된 이미지입니다. JPEG, PNG, WebP를 사용하세요.", + "decode": "이미지를 읽을 수 없습니다. 다른 파일을 사용해 주세요.", + "failure": "미리보기를 처리하지 못했습니다. 다시 시도하거나 작은 이미지를 사용해 주세요.", + "cleared": "모든 페이지를 지웠습니다.", + "applied": "모든 페이지에 모양을 적용했습니다.", + "removed": "페이지를 제거했습니다.", + "reordered": "페이지 순서를 변경했습니다.", + "pdfCreate": "PDF 만들기", + "pdfCancel": "PDF 취소", + "pdfProgressLabel": "PDF 생성 진행률", + "pdfHelp": "A4, 자동 방향, 여백 10mm. 출력 제한: 이미지당 1,200만 픽셀, 합계 2,400만 픽셀, 출력 64MiB.", + "pdfResult": "생성된 PDF", + "pdfPreview": "생성된 PDF 페이지 미리보기", + "pdfPrevious": "이전 페이지", + "pdfNext": "다음 페이지", + "pdfDownload": "PDF 다운로드", + "pdfLoading": "PDF 미리보기 불러오는 중…", + "pdfPage": "{total}페이지 중 {page}페이지", + "pdfProgress": "기기에서 PDF 생성 중… {total}페이지 중 {done}페이지.", + "pdfReady": "PDF가 준비되었습니다. 미리보기를 확인하거나 다운로드하세요.", + "pdfLimit": "출력 제한을 초과했습니다. 원본 이미지 수나 크기를 줄여 주세요.", + "pdfError": "PDF를 만들지 못했습니다. 다시 시도하거나 작은 이미지를 사용하세요.", + "pdfCancelled": "PDF 생성을 취소했습니다. 스캔 페이지는 유지됩니다.", + "pdfDownloaded": "PDF 다운로드를 시작했습니다.", + "pdfPreviewError": "PDF를 미리 볼 수 없습니다. 다운로드하거나 다시 생성할 수 있습니다.", + "pdfDownloadError": "다운로드를 시작하지 못했습니다. 다시 다운로드해 주세요." + } + }, + "ja": { + "metadata": { + "title": "ドキュメントスキャナー — Secure Tools", + "description": "このデバイスで文書画像を並べ替えて補正します。" + }, + "copy": { + "title": "ドキュメントスキャナー", + "eyebrow": "ローカルスキャンツール", + "description": "このデバイスで文書画像を並べ替えて補正します。", + "add": "画像を追加", + "inputHelp": "JPEG、PNG、WebPを選択、ドロップ、貼り付けできます。最大20ページ、合計200 MiB、1画像50 MiB。", + "appearance": "スキャンの表示", + "mode": "新しいページの表示", + "original": "オリジナル", + "grayscale": "グレースケール", + "document": "文書", + "modeHelp": "固定しきい値で白黒に変換します。自動切り抜きや角の検出は行いません。", + "apply": "全ページに適用", + "cancel": "処理をキャンセル", + "clear": "すべてクリア", + "scope": "ローカルでPDFを作成します。任意の文字認識は今後対応予定です。", + "pages": "文書のページ", + "empty": "ページはまだありません。", + "count": "{count}ページ", + "preview": "{page}ページのプレビュー", + "up": "上へ", + "down": "下へ", + "remove": "削除", + "processing": "ローカルで処理中… {count}ページ準備完了。", + "cancelled": "処理をキャンセルしました。完了したプレビューは保持されます。", + "added": "{count}ページを追加しました。", + "rejected": "{added}ページ追加。追加できませんでした: {names}", + "limit": "画像またはキューの上限を超えました。画像の数やサイズを減らしてください。", + "unsupported": "非対応または無効な画像です。JPEG、PNG、WebPをご使用ください。", + "decode": "画像を読み込めません。他のファイルをお試しください。", + "failure": "プレビューを処理できません。再試行するか小さい画像をお試しください。", + "cleared": "全ページをクリアしました。", + "applied": "全ページに表示を適用しました。", + "removed": "ページを削除しました。", + "reordered": "ページ順を更新しました。", + "pdfCreate": "PDFを作成", + "pdfCancel": "PDFをキャンセル", + "pdfProgressLabel": "PDF作成の進行状況", + "pdfHelp": "A4、自動方向、余白10 mm。上限: 1画像1,200万画素、合計2,400万画素、出力64 MiB。", + "pdfResult": "作成したPDF", + "pdfPreview": "作成したPDFページのプレビュー", + "pdfPrevious": "前のページ", + "pdfNext": "次のページ", + "pdfDownload": "PDFをダウンロード", + "pdfLoading": "PDFプレビューを読み込み中…", + "pdfPage": "{total}ページ中{page}ページ", + "pdfProgress": "ローカルでPDF作成中… {total}ページ中{done}ページ。", + "pdfReady": "PDFを作成しました。プレビューまたはダウンロードできます。", + "pdfLimit": "出力上限を超えました。元画像の数やサイズを減らしてください。", + "pdfError": "PDFを作成できません。再試行するか小さい画像を使用してください。", + "pdfCancelled": "PDF作成をキャンセルしました。スキャンページは保持されます。", + "pdfDownloaded": "PDFのダウンロードを開始しました。", + "pdfPreviewError": "PDFをプレビューできません。ダウンロードするか再作成してください。", + "pdfDownloadError": "ダウンロードを開始できません。再試行してください。" + } + }, + "es": { + "metadata": { + "title": "Escáner de documentos — Secure Tools", + "description": "Ordena y mejora imágenes de documentos en este dispositivo." + }, + "copy": { + "title": "Escáner de documentos", + "eyebrow": "Herramienta de escaneo local", + "description": "Ordena y mejora imágenes de documentos en este dispositivo.", + "add": "Añadir imágenes", + "inputHelp": "Selecciona, arrastra o pega JPEG, PNG o WebP. Hasta 20 páginas y 200 MiB en total; 50 MiB por imagen.", + "appearance": "Aspecto del escaneo", + "mode": "Aspecto de páginas nuevas", + "original": "Original", + "grayscale": "Escala de grises", + "document": "Documento", + "modeHelp": "El modo Documento usa un umbral fijo de blanco y negro. Sin recorte automático ni detección de esquinas.", + "apply": "Aplicar a todas las páginas", + "cancel": "Cancelar procesamiento", + "clear": "Borrar todo", + "scope": "Crea PDF localmente. El reconocimiento de texto opcional llegará más adelante.", + "pages": "Páginas del documento", + "empty": "Aún no hay páginas.", + "count": "{count} páginas", + "preview": "Vista previa de la página {page}", + "up": "Subir", + "down": "Bajar", + "remove": "Eliminar", + "processing": "Procesando localmente… {count} páginas listas.", + "cancelled": "Procesamiento cancelado. Se conservan las vistas previas terminadas.", + "added": "Se añadieron {count} páginas.", + "rejected": "Se añadieron {added} páginas. No se pudieron añadir: {names}", + "limit": "Se superó el límite de imagen o cola. Usa menos imágenes o imágenes más pequeñas.", + "unsupported": "Imagen no compatible o inválida. Usa JPEG, PNG o WebP.", + "decode": "No se pudo leer la imagen. Prueba otro archivo.", + "failure": "No se pudieron procesar las vistas previas. Reintenta o usa imágenes más pequeñas.", + "cleared": "Se borraron todas las páginas.", + "applied": "Aspecto aplicado a todas las páginas.", + "removed": "Página eliminada.", + "reordered": "Orden de páginas actualizado.", + "pdfCreate": "Crear PDF", + "pdfCancel": "Cancelar PDF", + "pdfProgressLabel": "Progreso de creación del PDF", + "pdfHelp": "A4, orientación automática, márgenes de 10 mm. Límites: 12 megapíxeles por imagen, 24 en total y 64 MiB de salida.", + "pdfResult": "PDF generado", + "pdfPreview": "Vista previa de la página PDF generada", + "pdfPrevious": "Página anterior", + "pdfNext": "Página siguiente", + "pdfDownload": "Descargar PDF", + "pdfLoading": "Cargando vista previa del PDF…", + "pdfPage": "Página {page} de {total}", + "pdfProgress": "Creando PDF localmente… {done} de {total} páginas.", + "pdfReady": "PDF listo. Revisa la vista previa o descárgalo.", + "pdfLimit": "Límite de exportación superado. Usa menos imágenes o imágenes más pequeñas.", + "pdfError": "No se pudo crear el PDF. Reintenta o usa imágenes más pequeñas.", + "pdfCancelled": "Creación del PDF cancelada. Se conservan las páginas escaneadas.", + "pdfDownloaded": "Descarga del PDF iniciada.", + "pdfPreviewError": "Vista previa no disponible. Puedes descargar el PDF o volver a crearlo.", + "pdfDownloadError": "No se pudo iniciar la descarga. Inténtalo de nuevo." + } + }, + "de": { + "metadata": { + "title": "Dokumentenscanner — Secure Tools", + "description": "Dokumentbilder auf diesem Gerät ordnen und verbessern." + }, + "copy": { + "title": "Dokumentenscanner", + "eyebrow": "Lokales Scanwerkzeug", + "description": "Dokumentbilder auf diesem Gerät ordnen und verbessern.", + "add": "Bilder hinzufügen", + "inputHelp": "JPEG, PNG oder WebP auswählen, ablegen oder einfügen. Bis zu 20 Seiten und insgesamt 200 MiB; 50 MiB pro Bild.", + "appearance": "Scanansicht", + "mode": "Ansicht für neue Seiten", + "original": "Original", + "grayscale": "Graustufen", + "document": "Dokument", + "modeHelp": "Der Dokumentmodus nutzt einen festen Schwarzweiß-Schwellenwert. Kein automatischer Zuschnitt oder Eckenerkennung.", + "apply": "Auf alle Seiten anwenden", + "cancel": "Verarbeitung abbrechen", + "clear": "Alles löschen", + "scope": "PDFs lokal erstellen. Optionale Texterkennung folgt später.", + "pages": "Dokumentseiten", + "empty": "Noch keine Seiten hinzugefügt.", + "count": "{count} Seiten", + "preview": "Vorschau von Seite {page}", + "up": "Nach oben", + "down": "Nach unten", + "remove": "Entfernen", + "processing": "Lokale Verarbeitung… {count} Seiten bereit.", + "cancelled": "Verarbeitung abgebrochen. Fertige Vorschauen bleiben erhalten.", + "added": "{count} Seiten hinzugefügt.", + "rejected": "{added} Seiten hinzugefügt. Nicht hinzugefügt: {names}", + "limit": "Bild- oder Warteschlangenlimit überschritten. Weniger oder kleinere Bilder verwenden.", + "unsupported": "Nicht unterstütztes oder ungültiges Bild. JPEG, PNG oder WebP verwenden.", + "decode": "Bild konnte nicht gelesen werden. Andere Datei versuchen.", + "failure": "Vorschauen konnten nicht verarbeitet werden. Erneut versuchen oder kleinere Bilder verwenden.", + "cleared": "Alle Seiten gelöscht.", + "applied": "Ansicht auf alle Seiten angewendet.", + "removed": "Seite entfernt.", + "reordered": "Seitenreihenfolge aktualisiert.", + "pdfCreate": "PDF erstellen", + "pdfCancel": "PDF abbrechen", + "pdfProgressLabel": "Fortschritt der PDF-Erstellung", + "pdfHelp": "A4, automatische Ausrichtung, 10 mm Rand. Grenzen: 12 Megapixel pro Bild, 24 insgesamt und 64 MiB Ausgabe.", + "pdfResult": "Erstelltes PDF", + "pdfPreview": "Vorschau der erstellten PDF-Seite", + "pdfPrevious": "Vorherige Seite", + "pdfNext": "Nächste Seite", + "pdfDownload": "PDF herunterladen", + "pdfLoading": "PDF-Vorschau wird geladen…", + "pdfPage": "Seite {page} von {total}", + "pdfProgress": "PDF wird lokal erstellt… {done} von {total} Seiten.", + "pdfReady": "PDF bereit. Vorschau prüfen oder herunterladen.", + "pdfLimit": "Exportgrenze überschritten. Weniger oder kleinere Quellbilder verwenden.", + "pdfError": "PDF konnte nicht erstellt werden. Erneut versuchen oder kleinere Bilder verwenden.", + "pdfCancelled": "PDF-Erstellung abgebrochen. Scanseiten bleiben erhalten.", + "pdfDownloaded": "PDF-Download gestartet.", + "pdfPreviewError": "PDF-Vorschau nicht verfügbar. PDF herunterladen oder erneut erstellen.", + "pdfDownloadError": "Download konnte nicht gestartet werden. Erneut versuchen." + } + }, + "fr": { + "metadata": { + "title": "Scanner de documents — Secure Tools", + "description": "Classez et améliorez vos images de documents sur cet appareil." + }, + "copy": { + "title": "Scanner de documents", + "eyebrow": "Outil de numérisation local", + "description": "Classez et améliorez vos images de documents sur cet appareil.", + "add": "Ajouter des images", + "inputHelp": "Sélectionnez, déposez ou collez des JPEG, PNG ou WebP. Jusqu’à 20 pages et 200 Mio au total ; 50 Mio par image.", + "appearance": "Aspect du scan", + "mode": "Aspect des nouvelles pages", + "original": "Original", + "grayscale": "Niveaux de gris", + "document": "Document", + "modeHelp": "Le mode Document utilise un seuil noir et blanc fixe. Sans recadrage automatique ni détection des coins.", + "apply": "Appliquer à toutes les pages", + "cancel": "Annuler le traitement", + "clear": "Tout effacer", + "scope": "Créez des PDF localement. La reconnaissance de texte facultative viendra ultérieurement.", + "pages": "Pages du document", + "empty": "Aucune page ajoutée.", + "count": "{count} pages", + "preview": "Aperçu de la page {page}", + "up": "Monter", + "down": "Descendre", + "remove": "Supprimer", + "processing": "Traitement local… {count} pages prêtes.", + "cancelled": "Traitement annulé. Les aperçus terminés sont conservés.", + "added": "{count} pages ajoutées.", + "rejected": "{added} pages ajoutées. Échec de l’ajout : {names}", + "limit": "Limite d’image ou de file dépassée. Utilisez moins d’images ou des images plus petites.", + "unsupported": "Image non prise en charge ou invalide. Utilisez JPEG, PNG ou WebP.", + "decode": "Impossible de lire cette image. Essayez un autre fichier.", + "failure": "Impossible de traiter les aperçus. Réessayez ou utilisez des images plus petites.", + "cleared": "Toutes les pages ont été effacées.", + "applied": "Aspect appliqué à toutes les pages.", + "removed": "Page supprimée.", + "reordered": "Ordre des pages mis à jour.", + "pdfCreate": "Créer le PDF", + "pdfCancel": "Annuler le PDF", + "pdfProgressLabel": "Progression de création du PDF", + "pdfHelp": "A4, orientation automatique, marges de 10 mm. Limites : 12 mégapixels par image, 24 au total et 64 Mio en sortie.", + "pdfResult": "PDF généré", + "pdfPreview": "Aperçu de la page PDF générée", + "pdfPrevious": "Page précédente", + "pdfNext": "Page suivante", + "pdfDownload": "Télécharger le PDF", + "pdfLoading": "Chargement de l’aperçu PDF…", + "pdfPage": "Page {page} sur {total}", + "pdfProgress": "Création locale du PDF… {done} pages sur {total}.", + "pdfReady": "PDF prêt. Consultez l’aperçu ou téléchargez-le.", + "pdfLimit": "Limite d’export dépassée. Utilisez moins d’images ou des images plus petites.", + "pdfError": "Impossible de créer le PDF. Réessayez ou utilisez des images plus petites.", + "pdfCancelled": "Création du PDF annulée. Les pages numérisées sont conservées.", + "pdfDownloaded": "Téléchargement du PDF lancé.", + "pdfPreviewError": "Aperçu indisponible. Vous pouvez télécharger le PDF ou le recréer.", + "pdfDownloadError": "Impossible de lancer le téléchargement. Réessayez." + } + } +}; diff --git a/scripts/site-routes.mjs b/scripts/site-routes.mjs index 025ffe9..8b70542 100644 --- a/scripts/site-routes.mjs +++ b/scripts/site-routes.mjs @@ -19,6 +19,7 @@ export const canonicalPages = [ { source: "tools/image/metadata/index.html", route: "/image/metadata/" }, { source: "tools/image/to-text/index.html", route: "/image/to-text/" }, { source: "tools/scan/index.html", route: "/scan/" }, + { source: "tools/scan/document/index.html", route: "/scan/document/", legacy: false }, { source: "tools/media/index.html", route: "/media/" }, ]; diff --git a/scripts/stage-typescript-test-dependencies.mjs b/scripts/stage-typescript-test-dependencies.mjs index 77c7c31..ddb7f8a 100644 --- a/scripts/stage-typescript-test-dependencies.mjs +++ b/scripts/stage-typescript-test-dependencies.mjs @@ -9,3 +9,7 @@ fs.mkdirSync(stagingDirectory, { recursive: true }); for (const file of ["image.js", "ocr.js", "pdf.js", "save.js"]) { fs.copyFileSync(path.join(root, "tools", "shared", file), path.join(stagingDirectory, file)); } + +fs.mkdirSync(path.join(root, ".ts-build/tools/pdf/images-to-pdf"), { recursive: true }); +fs.copyFileSync(path.join(root, "tools/pdf/images-to-pdf/pdf.js"), path.join(root, ".ts-build/tools/pdf/images-to-pdf/pdf.js")); +fs.copyFileSync(path.join(root, "tools/shared/file.js"), path.join(stagingDirectory, "file.js")); diff --git a/scripts/typescript-modules.mjs b/scripts/typescript-modules.mjs index 035249c..eee0028 100644 --- a/scripts/typescript-modules.mjs +++ b/scripts/typescript-modules.mjs @@ -1,4 +1,7 @@ export const compiledBrowserModules = Object.freeze([ + Object.freeze({ source: "tools/scan/document/pdf.ts", compiled: "tools/scan/document/pdf.js", public: "scan/document/pdf.js" }), + Object.freeze({ source: "tools/shared/scan.ts", compiled: "tools/shared/scan.js", public: "shared/scan.js" }), + Object.freeze({ source: "tools/scan/document/state.ts", compiled: "tools/scan/document/state.js", public: "scan/document/state.js" }), Object.freeze({ source: "tools/pdf/to-text/app.ts", compiled: "tools/pdf/to-text/app.js", diff --git a/scripts/validate-branch-policy.mjs b/scripts/validate-branch-policy.mjs index e3ff75f..385e4e5 100644 --- a/scripts/validate-branch-policy.mjs +++ b/scripts/validate-branch-policy.mjs @@ -1,7 +1,7 @@ import { fileURLToPath } from "node:url"; import { execFileSync } from "node:child_process"; -export const ACTIVE_INTEGRATION_BRANCH = "v2.3"; +export const ACTIVE_INTEGRATION_BRANCH = "v2.4"; const routineBranch = /^(?:feat|fix|test|chore)\/.+$/; const hotfixBranch = /^hotfix\/.+$/; diff --git a/sitemap.xml b/sitemap.xml index e0fc784..0d97915 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -18,5 +18,6 @@ https://tools.securetools.app/image/metadata/ https://tools.securetools.app/image/to-text/ https://tools.securetools.app/scan/ + https://tools.securetools.app/scan/document/ https://tools.securetools.app/media/ diff --git a/tests/action-pins.test.mjs b/tests/action-pins.test.mjs index 1f073bd..53881c0 100644 --- a/tests/action-pins.test.mjs +++ b/tests/action-pins.test.mjs @@ -22,10 +22,10 @@ const dependabot = fs.readFileSync(".github/dependabot.yml", "utf8"); assert.match(dependabot, /^version: 2$/m); assert.match(dependabot, /package-ecosystem: "github-actions"/); assert.match(dependabot, /directory: "\/"/); -assert.match(dependabot, /target-branch: "v2\.3"/); +assert.match(dependabot, /target-branch: "v2\.4"/); assert.match(dependabot, /interval: "weekly"/); assert.match(dependabot, /pull-request-branch-name:\s*\n\s+prefix: "chore\/dependabot"/); assert.match(dependabot, /commit-message:[\s\S]*?prefix: "🔧\[Config\] "/); -assert.equal(validateBranchPolicy("v2.3", "chore/dependabot/github_actions/actions/checkout-4.4.0").valid, true); +assert.equal(validateBranchPolicy("v2.4", "chore/dependabot/github_actions/actions/checkout-4.4.0").valid, true); assert.doesNotMatch(dependabot, /auto-merge|enable-pull-request-automerge/); console.log(`Action supply-chain gate passed: ${references.length} references classified; mutable/abbreviated/dynamic refs rejected; reviewed weekly update configuration checked.`); diff --git a/tests/branch-policy.test.mjs b/tests/branch-policy.test.mjs index e355573..8b3ea16 100644 --- a/tests/branch-policy.test.mjs +++ b/tests/branch-policy.test.mjs @@ -9,14 +9,14 @@ import { validateProductionVerificationLock, } from "../scripts/validate-branch-policy.mjs"; -assert.equal(ACTIVE_INTEGRATION_BRANCH, "v2.3"); +assert.equal(ACTIVE_INTEGRATION_BRANCH, "v2.4"); for (const [headRef, baseRef] of [ - ["feat/example", "v2.3"], - ["fix/example", "v2.3"], - ["test/example", "v2.3"], - ["chore/example", "v2.3"], - ["v2.3", "main"], + ["feat/example", "v2.4"], + ["fix/example", "v2.4"], + ["test/example", "v2.4"], + ["chore/example", "v2.4"], + ["v2.4", "main"], ["hotfix/example", "main"], ]) { assert.deepEqual(validateBranchPolicy(baseRef, headRef), { valid: true, reason: null }, `${headRef} → ${baseRef}`); @@ -33,14 +33,14 @@ for (const [headRef, baseRef] of [ ]) { const result = validateBranchPolicy(baseRef, headRef); assert.equal(result.valid, false, `${headRef} → ${baseRef}`); - assert.match(result.reason, /Only v2\.3 release promotion or an explicit hotfix/); - assert.throws(() => run([baseRef, headRef]), /Only v2\.3 release promotion or an explicit hotfix/); + assert.match(result.reason, /Only v2\.4 release promotion or an explicit hotfix/); + assert.throws(() => run([baseRef, headRef]), /Only v2\.4 release promotion or an explicit hotfix/); } for (const headRef of ["v2.1", "main", "hotfix/example", "feature/example"]) { - const result = validateBranchPolicy("v2.3", headRef); - assert.equal(result.valid, false, `${headRef} → v2.3`); - assert.match(result.reason, /Pull requests into v2\.3 must come from feat\/\*, fix\/\*, test\/\*, or chore\/\*/); + const result = validateBranchPolicy("v2.4", headRef); + assert.equal(result.valid, false, `${headRef} → v2.4`); + assert.match(result.reason, /Pull requests into v2\.4 must come from feat\/\*, fix\/\*, test\/\*, or chore\/\*/); } for (const base of ["v2.2", "v2.1", "unknown"]) { @@ -83,4 +83,4 @@ assert.throws(() => validateProductionVerificationLock(originalLock, changedLock const leakedRuntime = structuredClone(verificationLock); leakedRuntime.packages["node_modules/playwright"].dev = false; assert.throws(() => validateProductionVerificationLock(originalLock, leakedRuntime), /test-only Playwright/); -console.log("v2.3 integration, production promotion, hotfix, and rejection branch-policy checks passed."); +console.log("v2.4 integration, production promotion, hotfix, and rejection branch-policy checks passed."); diff --git a/tests/browser/scanner-pdf.mjs b/tests/browser/scanner-pdf.mjs new file mode 100644 index 0000000..1a30a9d --- /dev/null +++ b/tests/browser/scanner-pdf.mjs @@ -0,0 +1,63 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import { spawn } from "node:child_process"; +import { createRequire } from "node:module"; +import { chromium } from "playwright"; +import { assertSecurityHeaders } from "../../scripts/http-security-headers.mjs"; +import { translations } from "../../js/i18n.js"; +const { PDFDocument, PDFName } = createRequire(import.meta.url)("../../assets/vendor/pdf-lib/pdf-lib.min.js"); +const directory = ".ts-build/scanner-pdf-qa"; +await fs.mkdir(directory,{recursive:true}); +const port=45000+Math.floor(Math.random()*8000);const origin=`http://127.0.0.1:${port}`; +const server=spawn(process.execPath,["tests/serve-ocr-smoke.mjs",String(port)],{stdio:["ignore","pipe","inherit"]}); +const report={cases:[],artifacts:[],external:[],mutating:[],errors:[],headerErrors:[],status:"FAIL"}; +let browser; +try { + await new Promise((resolve,reject)=>{const timer=setTimeout(()=>reject(Error("Server timeout")),10000);server.stdout.once("data",()=>{clearTimeout(timer);resolve();});server.once("error",reject);}); + browser=await chromium.launch();const maker=await browser.newPage(); + const images=await maker.evaluate(async()=>{ + async function make(w,h,type="image/png") {const canvas=document.createElement("canvas");canvas.width=w;canvas.height=h;const c=canvas.getContext("2d");c.fillStyle="rgb(200,200,200)";c.fillRect(0,0,w,h);c.fillStyle="rgb(220,40,20)";c.fillRect(0,0,w/2,h);const blob=await new Promise(resolve=>canvas.toBlob(resolve,type));const data=[...new Uint8Array(await blob.arrayBuffer())];canvas.width=canvas.height=1;return data;} + return {landscape:await make(2000,1200),portrait:await make(1200,2000),rotated:await make(60,30,"image/jpeg"),oversized:await make(4000,3001)}; + });await maker.close(); + const jpeg=Buffer.from(images.rotated);const exif=Buffer.from([255,225,0,34,69,120,105,102,0,0,73,73,42,0,8,0,0,0,1,0,18,1,3,0,1,0,0,0,6,0,0,0,0,0,0,0]); + const rotated=Buffer.concat([jpeg.subarray(0,2),exif,jpeg.subarray(2)]); + for (const language of ["en","ko"]) { + const copy=translations[language].documentScanner; + const context=await browser.newContext({locale:language,acceptDownloads:true}); + await context.addInitScript(language=>{localStorage.setItem("secure-tools-language",language);window.pdfAudit={created:[],revoked:[],workers:0,terminated:0};window.Worker=class extends Worker{constructor(...args){super(...args);window.pdfAudit.workers++;}terminate(){window.pdfAudit.terminated++;return super.terminate();}};const create=URL.createObjectURL.bind(URL),revoke=URL.revokeObjectURL.bind(URL);URL.createObjectURL=blob=>{const url=create(blob);window.pdfAudit.created.push(url);return url;};URL.revokeObjectURL=url=>{window.pdfAudit.revoked.push(url);revoke(url);};document.addEventListener("securitypolicyviolation",event=>console.error(`CSP: ${event.effectiveDirective}`));},language); + context.on("request",request=>{if(!request.url().startsWith(origin+"/")&&!/^(blob:|data:|about:)/.test(request.url()))report.external.push(request.url());if(!["GET","HEAD"].includes(request.method()))report.mutating.push(request.url());}); + const page=await context.newPage();page.on("pageerror",error=>report.errors.push(error.message));page.on("console",msg=>{if(msg.type()==="error")report.errors.push(msg.text());});let downloads=0;page.on("download",()=>downloads++); + await page.goto(origin+"/scan/document/"); + try{assertSecurityHeaders((await fetch(origin+"/scan/document/")).headers);}catch(error){report.headerErrors.push(error.message);} + async function add(name,data,mode="original",mimeType="image/png") {await page.selectOption("#scan-mode",mode);await page.setInputFiles("#file-input",{name,mimeType,buffer:Buffer.from(data)});await page.waitForFunction(()=>document.querySelector("#cancel-scan").hidden);} + await add("original.png",images.landscape);await add("gray.png",images.portrait,"grayscale");await add("document.png",images.landscape,"document");await add("exif.jpg",rotated,"original","image/jpeg"); + assert.equal(await page.locator(".scan-page").count(),4); + await page.locator(".scan-page").first().locator('[data-action="down"]').focus();await page.keyboard.press("Enter"); + await page.locator("#create-pdf").focus();await page.keyboard.press("Enter"); + await page.waitForFunction(()=>!document.querySelector("#pdf-result").hidden&&document.querySelector("#pdf-preview").getAttribute("aria-busy")==="false"); + assert.ok(await page.locator("#create-pdf").evaluate(el=>el===document.activeElement));assert.equal(await page.locator("#cancel-pdf").isVisible(),false); + for(const [width,height] of [[320,568],[390,844],[844,390],[768,1024],[1280,900]]) {await page.setViewportSize({width,height});assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));assert.ok((await page.locator("#download-pdf").boundingBox()).height>=44);report.cases.push({language,width,height});if(width===320)await page.screenshot({path:`${directory}/${language}-mobile.png`,fullPage:true});} + await page.click("#pdf-next");await page.waitForFunction(()=>document.querySelector("#pdf-preview").getAttribute("aria-busy")==="false");assert.equal(await page.locator("#pdf-page").innerText(),copy.pdfPage.replace("{page}","2").replace("{total}","4")); + const downloadPromise=page.waitForEvent("download");await page.click("#download-pdf");const download=await downloadPromise;assert.equal(download.suggestedFilename(),"scanned-document.pdf");const path=`${directory}/${language}-scanned.pdf`;await download.saveAs(path);const bytes=await fs.readFile(path); + const pdf=await PDFDocument.load(bytes);assert.equal(pdf.getPageCount(),4); + assert.deepEqual(pdf.getPages().map(p=>p.getWidth()>p.getHeight()),[false,true,true,false],"Order and EXIF orientation match current scanner pages"); + const sizes=[];const objects=pdf.getPages()[0].node.Resources().lookup(PDFName.of("XObject"));for(const name of objects.keys()){const image=objects.lookup(name);if(image.dict.get(PDFName.of("Subtype"))?.toString()==="/Image")sizes.push([image.dict.get(PDFName.of("Width")).asNumber(),image.dict.get(PDFName.of("Height")).asNumber()]);} + assert.ok(sizes.some(([w,h])=>w===2000&&h===1200));assert.ok(sizes.some(([w,h])=>w===1200&&h===2000));assert.ok(sizes.some(([w,h])=>w===30&&h===60)); + const samples=await page.evaluate(async bytes=>{const lib=await import("/assets/vendor/pdfjs/pdf.min.mjs");const task=lib.getDocument({data:new Uint8Array(bytes),isEvalSupported:false,useWorkerFetch:false,useWasm:false});try{const pdf=await task.promise;const samples=[];for(let i=1;i<=3;i++){const page=await pdf.getPage(i);const viewport=page.getViewport({scale:1});const canvas=document.createElement("canvas");canvas.width=Math.ceil(viewport.width);canvas.height=Math.ceil(viewport.height);const c=canvas.getContext("2d");await page.render({canvasContext:c,viewport}).promise;samples.push([...c.getImageData(Math.floor(canvas.width*.25),Math.floor(canvas.height*.5),1,1).data].slice(0,3));canvas.width=canvas.height=1;page.cleanup();}return samples;}finally{await task.destroy();}},[...bytes]); + assert.ok(samples[0].every(v=>Math.abs(v-92)<=2),`Grayscale exported: ${samples[0]}`);assert.ok(samples[1].every((v,i)=>Math.abs(v-[220,40,20][i])<=2));assert.deepEqual(samples[2],[0,0,0],"Document threshold is represented in actual PDF pixels"); + report.artifacts.push({language,bytes:bytes.length,pages:4,embeddedSizes:sizes,samples}); + await page.locator(".scan-page").first().locator('[data-action="down"]').click();assert.equal(await page.locator("#pdf-result").isVisible(),false); + // Immediate cancellation and repeated creation must never expose stale output. + await page.evaluate(()=>{document.querySelector("#create-pdf").click();document.querySelector("#cancel-pdf").click();});assert.equal(await page.locator("#pdf-result").isVisible(),false);assert.ok(await page.locator("#create-pdf").evaluate(el=>el===document.activeElement)); + await page.evaluate(()=>{document.querySelector("#create-pdf").click();document.querySelector(".scan-page [data-action='down']").click();});await page.waitForTimeout(100);assert.equal(await page.locator("#pdf-result").isVisible(),false); + if(language==="en") { + await page.evaluate(()=>{window.originalJsPDF=window.jspdf.jsPDF;window.jspdf.jsPDF=function(){throw Error("controlled writer failure");};});await page.click("#create-pdf");await page.waitForFunction(text=>document.querySelector("#tool-status").textContent===text,copy.pdfError);await page.evaluate(()=>{window.jspdf.jsPDF=window.originalJsPDF;delete window.originalJsPDF;}); + await page.click("#create-pdf");await page.waitForFunction(()=>!document.querySelector("#pdf-result").hidden&&document.querySelector("#pdf-preview").getAttribute("aria-busy")==="false"); + await page.selectOption("#scan-mode","grayscale");await page.click("#apply-mode");assert.equal(await page.locator("#pdf-result").isVisible(),false);await page.waitForFunction(()=>document.querySelector("#cancel-scan").hidden); + await page.click("#clear-images");await add("over-budget.png",images.oversized);await page.click("#create-pdf");await page.waitForFunction(text=>document.querySelector("#tool-status").textContent===text,copy.pdfLimit);assert.equal(await page.locator("#pdf-result").isVisible(),false); + } + await page.click("#clear-images");await page.waitForTimeout(1600);assert.equal(downloads,1,"Only an explicit download emits an artifact");const audit=await page.evaluate(()=>window.pdfAudit);assert.deepEqual([...audit.created].sort(),[...audit.revoked].sort());assert.equal(audit.workers,audit.terminated,"PDF preview workers are terminated on reset");await context.close(); + } + assert.deepEqual(report.headerErrors,[]);assert.deepEqual(report.external,[]);assert.deepEqual(report.mutating,[]);assert.deepEqual(report.errors,[]);report.status="PASS"; + console.log("Scanner PDF browser gate passed: real source-resolution PDF bytes, order, EXIF, modes, preview/download, cancellation/retry/invalidation, budgets, cleanup, responsive keyboard and privacy."); +}finally{await fs.writeFile(`${directory}/report.json`,JSON.stringify(report,null,2));await browser?.close();server.kill();} diff --git a/tests/browser/scanner.mjs b/tests/browser/scanner.mjs new file mode 100644 index 0000000..13f3495 --- /dev/null +++ b/tests/browser/scanner.mjs @@ -0,0 +1,138 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import { spawn } from "node:child_process"; +import { chromium } from "playwright"; +import { assertSecurityHeaders } from "../../scripts/http-security-headers.mjs"; +import { translations } from "../../js/i18n.js"; + +const directory = ".ts-build/scanner-qa"; +await fs.mkdir(directory, { recursive: true }); +const port = 44000 + Math.floor(Math.random() * 9000); +const origin = `http://127.0.0.1:${port}`; +const server = spawn(process.execPath, ["tests/serve-ocr-smoke.mjs", String(port)], { stdio: ["ignore", "pipe", "inherit"] }); +const report = { cases: [], external: [], mutating: [], errors: [], headerErrors: [], status: "FAIL" }; +let browser; +try { + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("Server timed out")), 10000); + server.stdout.once("data", () => { clearTimeout(timer); resolve(); }); + server.once("error", reject); + }); + browser = await chromium.launch(); + const maker = await browser.newPage(); + const images = await maker.evaluate(async () => { + async function make(width, height, type) { + const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; + const c = canvas.getContext("2d"); c.fillStyle = "white"; c.fillRect(0,0,width,height); + c.fillStyle = "#e08050"; c.fillRect(0,0,width/2,height/2); + c.fillStyle = "black"; c.font = "20px sans-serif"; c.fillText("Document 문서", 4, height - 10); + const blob = await new Promise(resolve => canvas.toBlob(resolve, type)); + const data = [...new Uint8Array(await blob.arrayBuffer())]; canvas.width = canvas.height = 1; return data; + } + return { png: await make(180, 300, "image/png"), jpeg: await make(60, 30, "image/jpeg"), webp: await make(300, 180, "image/webp"), large: await make(4000,3000,"image/jpeg") }; + }); + await maker.close(); + // EXIF APP1/TIFF orientation=6: a real JPEG that browsers must rotate 90°. + const exif = Buffer.from([0xff,0xe1,0,34,69,120,105,102,0,0,73,73,42,0,8,0,0,0,1,0,18,1,3,0,1,0,0,0,6,0,0,0,0,0,0,0]); + const jpeg = Buffer.from(images.jpeg); + const rotated = Buffer.concat([jpeg.subarray(0,2), exif, jpeg.subarray(2)]); + const fixtures = [ + { name: "문서-portrait.png", mimeType: "image/png", buffer: Buffer.from(images.png) }, + { name: "landscape.webp", mimeType: "image/webp", buffer: Buffer.from(images.webp) }, + { name: "rotated-exif.jpg", mimeType: "image/jpeg", buffer: rotated }, + ]; + for (const language of ["en", "ko", "ja", "es", "de", "fr"]) { + const context = await browser.newContext({ locale: language }); + await context.addInitScript(language => { + localStorage.setItem("secure-tools-language", language); + window.scanUrls = { created: [], revoked: [] }; + const create = URL.createObjectURL.bind(URL); const revoke = URL.revokeObjectURL.bind(URL); + URL.createObjectURL = blob => { const url = create(blob); window.scanUrls.created.push(url); return url; }; + URL.revokeObjectURL = url => { window.scanUrls.revoked.push(url); revoke(url); }; + document.addEventListener("securitypolicyviolation", event => console.error(`CSP: ${event.effectiveDirective}`)); + }, language); + context.on("request", request => { + if (!request.url().startsWith(`${origin}/`) && !/^(blob:|data:|about:)/.test(request.url())) report.external.push(request.url()); + if (!["GET", "HEAD"].includes(request.method())) report.mutating.push({ url: request.url(), method: request.method() }); + }); + const page = await context.newPage(); + page.on("pageerror", error => report.errors.push(error.message)); + page.on("console", message => { if (message.type() === "error") report.errors.push(message.text()); }); + const response = await page.goto(`${origin}/scan/document/`); + assert.equal(response.status(), 200); + // Check raw server headers; desktop browser middleware may append a second + // Permissions-Policy value, exposed by Playwright with embedded newlines. + try { assertSecurityHeaders((await fetch(`${origin}/scan/document/`)).headers); } + catch (error) { report.headerErrors.push(error.message); } + await page.setInputFiles("#file-input", fixtures); + await page.waitForFunction(() => document.querySelectorAll(".scan-page").length === 3 && document.querySelector("#cancel-scan").hidden); + assert.equal(await page.locator("#cancel-scan").isVisible(), false); + assert.equal(await page.locator(".scan-page").nth(2).locator("p").innerText(), `30 × 60 · ${translations[language].documentScanner.original}`); + // Deterministic preprocessing is applied to real encoded thumbnails. + await page.selectOption("#scan-mode", "grayscale"); await page.click("#apply-mode"); + await page.waitForFunction(() => document.querySelector("#cancel-scan").hidden); + const grayscale = await page.locator(".scan-page img").first().evaluate(async image => { + await image.decode(); const c = document.createElement("canvas"); c.width = image.naturalWidth; c.height = image.naturalHeight; + const ctx = c.getContext("2d"); ctx.drawImage(image,0,0); const data = ctx.getImageData(0,0,c.width,c.height).data; + return Array.from({length:data.length/4}, (_,i) => data[i*4] === data[i*4+1] && data[i*4] === data[i*4+2]).every(Boolean); + }); + assert.equal(grayscale, true); + await page.selectOption("#scan-mode", "document"); await page.click("#apply-mode"); + await page.waitForFunction(() => document.querySelector("#cancel-scan").hidden); + assert.ok((await page.locator(".scan-page p").allTextContents()).every(text => text.endsWith(translations[language].documentScanner.document))); + const firstId = await page.locator(".scan-page").first().getAttribute("data-id"); + await page.locator(".scan-page").first().locator('[data-action="down"]').focus(); await page.keyboard.press("Enter"); + assert.equal(await page.locator(".scan-page").nth(1).getAttribute("data-id"), firstId); + assert.ok(await page.locator(".scan-page").nth(1).evaluate(card => card.contains(document.activeElement))); + for (const [width,height] of [[320,568],[390,844],[844,390],[768,1024],[1280,900]]) { + await page.setViewportSize({width,height}); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), `${language} ${width}: no horizontal overflow`); + for (const button of await page.locator(".scan-page-actions button").all()) assert.ok((await button.boundingBox()).height >= 44); + if (language === "ko" && width === 320) await page.screenshot({ path: `${directory}/mobile-ko.png`, fullPage: true }); + if (language === "en" && width === 1280) await page.screenshot({ path: `${directory}/desktop-en.png`, fullPage: true }); + report.cases.push({ language, width, height, pages: 3 }); + } + await page.locator(".scan-page").first().locator('[data-action="remove"]').click(); + assert.equal(await page.locator(".scan-page").count(), 2); + await page.click("#clear-images"); assert.equal(await page.locator(".scan-page").count(), 0); + assert.ok(await page.locator("#add-images").evaluate(el => el === document.activeElement)); + const urls = await page.evaluate(() => window.scanUrls); + assert.deepEqual([...urls.created].sort(), [...urls.revoked].sort(), "All successful previews are released after clear"); + if (language === "en") { + await page.setInputFiles("#file-input", [{ name:"broken.png", mimeType:"image/png", buffer:Buffer.from([137,80,78,71,13,10,26,10,0,0,0,0]) }, {name:"bad.gif",mimeType:"image/gif",buffer:Buffer.from("gif")}]); + await page.waitForFunction(() => document.querySelector("#cancel-scan").hidden && document.querySelector("#tool-status").textContent.includes("Could not add")); + assert.equal(await page.locator(".scan-page").count(), 0); + // Actual drag/drop and paste events exercise the UI's file paths. + for (const type of ["drop", "paste"]) { + await page.evaluate(({type, bytes}) => { + const transfer = new DataTransfer(); transfer.items.add(new File([new Uint8Array(bytes)], `${type}.png`, {type:"image/png"})); + if (type === "drop") document.querySelector("#drop-zone").dispatchEvent(new DragEvent("drop", {bubbles:true,cancelable:true,dataTransfer:transfer})); + else document.dispatchEvent(new ClipboardEvent("paste", {bubbles:true,cancelable:true,clipboardData:transfer})); + }, {type, bytes:images.png}); + await page.waitForFunction(count => document.querySelectorAll(".scan-page").length === count && document.querySelector("#cancel-scan").hidden, type === "drop" ? 1 : 2); + } + await page.setInputFiles("#file-input", [1,2].map(index => ({name:`large-${index}.jpg`,mimeType:"image/jpeg",buffer:Buffer.from(images.large)}))); + await page.waitForFunction(() => document.querySelectorAll(".scan-page").length === 4 && document.querySelector("#cancel-scan").hidden); + assert.ok(await page.locator(".scan-page img").evaluateAll(async images => { await Promise.all(images.map(image => image.decode())); return images.every(image => Math.max(image.naturalWidth,image.naturalHeight) <= 1000); })); + // Trigger large input and clear synchronously before decode may finish. + await page.evaluate(bytes => { + const transfer = new DataTransfer(); for(let i=0;i<5;i++) transfer.items.add(new File([new Uint8Array(bytes)], `stale-${i}.jpg`, {type:"image/jpeg"})); + document.querySelector("#drop-zone").dispatchEvent(new DragEvent("drop", {bubbles:true,cancelable:true,dataTransfer:transfer})); + document.querySelector("#clear-images").click(); + }, images.large); + await page.waitForTimeout(300); + assert.equal(await page.locator(".scan-page").count(), 0); + const finalUrls = await page.evaluate(() => window.scanUrls); + assert.deepEqual([...finalUrls.created].sort(), [...finalUrls.revoked].sort()); + } + await context.close(); + } + assert.deepEqual(report.headerErrors, []); + assert.deepEqual(report.mutating, [], "No document data is posted even to the same origin"); + assert.deepEqual(report.external, []); assert.deepEqual(report.errors, []); + report.status = "PASS"; + console.log("Scanner browser smoke passed: 30 viewport/locale cases; JPEG/PNG/WebP; EXIF; modes; keyboard order; input/drop/paste; large images; cleanup; CSP/network."); +} finally { + await fs.writeFile(`${directory}/report.json`, JSON.stringify(report,null,2)); + await browser?.close(); server.kill(); +} diff --git a/tests/category-availability.test.mjs b/tests/category-availability.test.mjs index 141281f..ccdbe38 100644 --- a/tests/category-availability.test.mjs +++ b/tests/category-availability.test.mjs @@ -68,8 +68,8 @@ assert.equal( "Image and Scan/OCR entries must resolve to the same route", ); assertRoutesExist("tools/scan/index.html", [scanOcrCard[1]]); -assert.equal((scanList.match(/
/g) || []).length, 1); -assert.equal((scanList.match(/tools\.comingSoon/g) || []).length, 1); +assert.equal((scanList.match(/
/g) || []).length, 0); +assert.equal((scanList.match(/tools\.comingSoon/g) || []).length, 0); assert.match(scanList, /data-i18n="categories\.scan\.documentTitle"/); const privacyHtml = read("privacy/index.html"); diff --git a/tests/ci-foundation.test.mjs b/tests/ci-foundation.test.mjs index 58b41c5..54fb1ff 100644 --- a/tests/ci-foundation.test.mjs +++ b/tests/ci-foundation.test.mjs @@ -4,7 +4,7 @@ import fs from "node:fs"; const workflow = fs.readFileSync(".github/workflows/ci.yml", "utf8"); assert.match(workflow, /^name: CI$/m); assert.match(workflow, /^\s{2}pull_request:$/m); -assert.match(workflow, /^\s{2}push:\s*$[\s\S]*?^\s{6}- main$[\s\S]*?^\s{6}- v2$[\s\S]*?^\s{6}- v2\.3$/m); +assert.match(workflow, /^\s{2}push:\s*$[\s\S]*?^\s{6}- main$[\s\S]*?^\s{6}- v2$[\s\S]*?^\s{6}- v2\.4$/m); assert.match(workflow, /uses: actions\/checkout@[0-9a-f]{40} # v4\.\d+\.\d+/); assert.match(workflow, /uses: actions\/setup-node@[0-9a-f]{40} # v4\.\d+\.\d+/); assert.match(workflow, /node-version: 24/); diff --git a/tests/i18n-quality.test.mjs b/tests/i18n-quality.test.mjs index 36e5e46..1e44e52 100644 --- a/tests/i18n-quality.test.mjs +++ b/tests/i18n-quality.test.mjs @@ -46,7 +46,7 @@ function placeholders(value) { function testCatalogParityAndQuality() { assert.deepEqual([...Object.keys(translations)], [...languageNames.keys()]); const english = flatten(translations.en); - assert.equal(english.size, 897); + assert.equal(english.size, 952); for (const [language, catalog] of Object.entries(translations)) { const flattened = flatten(catalog); @@ -78,7 +78,7 @@ function testResolutionDetectionAndPersistence() { function testSelectorsAndDocumentTranslation() { const pages = canonicalPages.map(({ source }) => path.join(root, source)); - assert.equal(pages.length, 19, "Every canonical page comes from the route manifest"); + assert.equal(pages.length, 20, "Every canonical page comes from the route manifest"); for (const file of pages) { const html = fs.readFileSync(file, "utf8"); const select = html.match(/]*data-language-select[^>]*>([\s\S]*?)<\/select>/)?.[1]; diff --git a/tests/pdf-to-text.test.mjs b/tests/pdf-to-text.test.mjs index b15cfc7..d594ebc 100644 --- a/tests/pdf-to-text.test.mjs +++ b/tests/pdf-to-text.test.mjs @@ -11,7 +11,7 @@ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const read = (file) => fs.readFileSync(path.join(root, file), "utf8"); const html = read("tools/pdf/to-text/index.html"); -assert.equal(canonicalPages.length, 19); +assert.equal(canonicalPages.length, 20); assert.equal(legacyRedirects.length, 17); assert.ok(canonicalPages.some(({ route }) => route === "/pdf/to-text/")); assert.ok(!legacyRedirects.some(({ from }) => from === "/tools/pdf/to-text/")); diff --git a/tests/release-hardening-http.test.mjs b/tests/release-hardening-http.test.mjs index 628e6ba..bd364c0 100644 --- a/tests/release-hardening-http.test.mjs +++ b/tests/release-hardening-http.test.mjs @@ -69,6 +69,6 @@ try { assert.doesNotMatch(file, /(?:\.d)?\.ts$|\.map$|[\\/]\.ts-build[\\/]|[\\/]tests[\\/]/); if (/\.(?:js|mjs|html|css|json)$/.test(file)) assert.doesNotMatch(fs.readFileSync(file, "utf8"), /C:\\Users\\|C:\/Users\//); } - assert.equal(canonicalPages.length, 19); assert.equal(legacyRedirects.length, 17); - console.log(`Release hardening HTTP: all 19 routes, ${checkedAssets.size} linked static assets, 17 single-hop/query-preserving redirects, SEO/sitemap/robots, and production artifact hygiene passed.`); + assert.equal(canonicalPages.length, 20); assert.equal(legacyRedirects.length, 17); + console.log(`Release hardening HTTP: all 20 routes, ${checkedAssets.size} linked static assets, 17 single-hop/query-preserving redirects, SEO/sitemap/robots, and production artifact hygiene passed.`); } finally { server.kill(); } diff --git a/tests/run-all.mjs b/tests/run-all.mjs index b95802f..1fb47f7 100644 --- a/tests/run-all.mjs +++ b/tests/run-all.mjs @@ -25,6 +25,8 @@ const sourceFiles = sourceDirectories for (const file of sourceFiles) runNode(["--check", file], `Syntax check for ${path.relative(root, file)}`); for (const test of [ + "tests/scanner.test.mjs", + "tests/scanner-pdf.test.mjs", "tests/image-to-pdf.test.mjs", "tests/image-converter.test.mjs", "tests/image-resize.test.mjs", diff --git a/tests/scanner-pdf.test.mjs b/tests/scanner-pdf.test.mjs new file mode 100644 index 0000000..1d9976a --- /dev/null +++ b/tests/scanner-pdf.test.mjs @@ -0,0 +1,64 @@ +import assert from "node:assert/strict"; +import { File } from "node:buffer"; +import { createRequire } from "node:module"; +import { createScanPdf, createScanPdfController, SCAN_EXPORT_PAGE_PIXELS, SCAN_EXPORT_TOTAL_PIXELS, SCAN_EXPORT_BYTES } from "../.ts-build/tools/scan/document/pdf.js"; +import { createPdfBlob } from "../tools/pdf/images-to-pdf/pdf.js"; +import { renderScanImage } from "../.ts-build/tools/shared/scan.js"; + +const require = createRequire(import.meta.url); +const { jsPDF } = require("../assets/vendor/jspdf/jspdf.umd.min.js"); +const { PDFDocument } = require("../assets/vendor/pdf-lib/pdf-lib.min.js"); +const png = new Blob([Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=", "base64")], {type:"image/png"}); +const file = name => new File([png], name, {type:"image/png"}); +const pages = [{file:file("landscape.png"),mode:"document"},{file:file("portrait.png"),mode:"grayscale"},{file:file("original.png"),mode:"original"}]; +const closed = []; const seen = []; const progress = []; +const decode = async f => ({source:f,width:f.name.startsWith("landscape")?2400:1200,height:f.name.startsWith("landscape")?1200:2400,close(){closed.push(f.name);}}); +const raster = async (image,mode) => {seen.push([image.source.name,mode,image.width,image.height]);return {blob:png,width:image.width,height:image.height};}; +const blob = await createScanPdf({pages,JsPDF:jsPDF,decode,raster,onProgress:(done,total)=>progress.push([done,total])}); +const pdf = await PDFDocument.load(await blob.arrayBuffer()); +assert.equal(pdf.getPageCount(),3); +assert.ok(pdf.getPages()[0].getWidth()>pdf.getPages()[0].getHeight()); +assert.ok(pdf.getPages()[1].getWidth()row.slice(0,2)),pages.map(page=>[page.file.name,page.mode])); +assert.deepEqual(closed,pages.map(page=>page.file.name)); +assert.deepEqual(progress,[[1,3],[2,3],[3,3]]); +assert.ok(seen.every(row=>row[2]>1000),"Export decodes source dimensions, never preview URLs"); +const base = {pages,JsPDF:jsPDF,decode,raster}; +await assert.rejects(createScanPdf({...base,pages:[]}),error=>error.code==="NO_FILES"); +await assert.rejects(createScanPdf({...base,JsPDF:null}),error=>error.code==="PDF_LIBRARY_UNAVAILABLE"); +let oversizedClosed=0; +await assert.rejects(createScanPdf({...base,decode:async()=>({source:{},width:SCAN_EXPORT_PAGE_PIXELS+1,height:1,close(){oversizedClosed++;}})}),error=>error.code==="SCAN_EXPORT_LIMIT"); +assert.equal(oversizedClosed,1); +let budgetClosed=0; +await assert.rejects(createScanPdf({...base,decode:async()=>({source:{},width:4000,height:3000,close(){budgetClosed++;}})}),error=>error.code==="SCAN_EXPORT_LIMIT"); +assert.equal(budgetClosed,3); assert.equal(SCAN_EXPORT_TOTAL_PIXELS,24_000_000); +await assert.rejects(createScanPdf({...base,pages:Array(21).fill(pages[0])}),error=>error.code==="SCAN_EXPORT_LIMIT"); +await assert.rejects(createScanPdf({...base,raster:async()=>({blob:new Blob([new Uint8Array(SCAN_EXPORT_BYTES+1)]),width:1,height:1})}),error=>error.code==="SCAN_EXPORT_LIMIT"); + +// Full-resolution strip preprocessing, including mid-strip cancellation/cleanup. +for (const mode of ["original","grayscale","document"]) { + const widths=[];const stripes=[];const canvas={width:0,height:0,getContext:()=>({fillRect(){},drawImage(){},getImageData(x,y,w,h){widths.push(w);stripes.push(h);return {data:new Uint8ClampedArray(w*h*4).fill(200)};},putImageData(){}}),toBlob(callback){callback(png);}}; + const result=await renderScanImage({source:{},width:2400,height:1600,close(){}},mode,{canvasFactory:()=>canvas}); + assert.equal(result.width,2400);assert.equal(result.height,1600);assert.equal(canvas.width,1); + assert.ok(stripes.every(height=>height<=64));assert.ok(widths.every(width=>width===2400)); +} +const abort=new AbortController(); let cancelClosed=0; +const stripAbort=new AbortController();let strips=0; +const stripCanvas={width:0,height:0,getContext:()=>({fillRect(){},drawImage(){},getImageData(){if(++strips===2)stripAbort.abort();return {data:new Uint8ClampedArray(16)};},putImageData(){}})}; +await assert.rejects(renderScanImage({source:{},width:2000,height:2000,close(){}},"document",{signal:stripAbort.signal,canvasFactory:()=>stripCanvas}),error=>error.name==="AbortError"); +assert.equal(stripCanvas.width,1,"Cancelled preprocessing releases the full-size canvas"); +await assert.rejects(createPdfBlob({files:[file("cancel.png")],JsPDF:jsPDF,options:{pageSize:"a4",orientation:"auto",margin:10},signal:abort.signal,decode:async()=>({source:{},width:10,height:20,close(){cancelClosed++;}}),convert:async()=>{abort.abort();return new Uint8Array(await png.arrayBuffer());}}),error=>error.name==="AbortError"); +assert.equal(cancelClosed,1); + +// A writer that ignores abort must still never publish a stale/cancelled result. +let release;let calls=0; +const controller=createScanPdfController(async()=>{calls++;return new Promise(resolve=>{release=resolve;});}); +const old=controller.create(pages);while(!release)await new Promise(resolve=>setTimeout(resolve,0)); +const next=controller.create(pages.slice(0,1));assert.equal(calls,1,"Writers are serialized"); +release(blob);assert.equal(await old,null); +while(calls<2)await new Promise(resolve=>setTimeout(resolve,0));release(blob);assert.equal(await next,blob);assert.equal(controller.result,blob); +controller.invalidate();assert.equal(controller.result,null); +let fail=true; +const retry=createScanPdfController(async()=>{if(fail)throw new Error("writer failed");return blob;}); +await assert.rejects(retry.create(pages));assert.equal(retry.busy,false);fail=false;assert.equal(await retry.create(pages),blob); +console.log("Scanner PDF composition, order/modes, full-resolution raster, page fit, budgets, cancellation, stale output and retry passed."); diff --git a/tests/scanner.test.mjs b/tests/scanner.test.mjs new file mode 100644 index 0000000..5aa8340 --- /dev/null +++ b/tests/scanner.test.mjs @@ -0,0 +1,90 @@ +import assert from "node:assert/strict"; +import { File } from "node:buffer"; +import { createScanQueue, MAX_SCAN_PAGES } from "../.ts-build/tools/scan/document/state.js"; +import { createScanPreview, preprocessScanPixels } from "../.ts-build/tools/shared/scan.js"; +import { decodeImage } from "../tools/shared/image.js"; + +const pixels = new Uint8ClampedArray([240, 200, 180, 255, 20, 50, 80, 255]); +const original = pixels.slice(); +assert.deepEqual(preprocessScanPixels(pixels, "original"), original); +assert.deepEqual(preprocessScanPixels(pixels, "grayscale"), new Uint8ClampedArray([210,210,210,255,44,44,44,255])); +assert.deepEqual(preprocessScanPixels(pixels, "document"), new Uint8ClampedArray([255,255,255,255,0,0,0,255])); +assert.deepEqual(pixels, original, "Preprocessing never mutates source pixels"); +assert.throws(() => preprocessScanPixels(pixels, "invalid"), /SCAN_MODE_INVALID/); + +const file = name => new File([Uint8Array.of(137,80,78,71,13,10,26,10,0,0,0,0)], name, { type: "image/png" }); +const preview = async () => ({ blob: new Blob(["preview"]), width: 200, height: 400 }); +const revoked = []; const created = []; const modes = []; +const config = { + preview: async (file, mode) => { modes.push(mode); return preview(); }, + createUrl: () => { const url = `blob:test-${created.length}`; created.push(url); return url; }, + revokeUrl: url => revoked.push(url), +}; +const queue = createScanQueue(config); +assert.equal((await queue.add([file("one.png"), file("two.png"), file("three.png")], "original")).added, 3); +const ids = queue.pages.map(page => page.id); +queue.move(ids[2], -1); +assert.deepEqual(queue.pages.map(page => page.file.name), ["one.png", "three.png", "two.png"]); +assert.equal(queue.move(ids[0], -1), false); +queue.remove(ids[2]); +assert.deepEqual(queue.pages.map(page => page.file.name), ["one.png", "two.png"]); +await queue.setMode("document"); +assert.ok(queue.pages.every(page => page.mode === "document")); +assert.deepEqual(modes, ["original", "original", "original", "document", "document"]); +queue.clear(); assert.equal(queue.pages.length, 0); +assert.deepEqual([...revoked].sort(), [...created].sort(), "Every replaced/removed/cleared URL is revoked once"); +const bad = await queue.add([new File(["text"], "bad.gif", { type: "image/gif" }), new File(["broken"], "broken.png", { type: "image/png" })], "original"); +assert.equal(bad.added, 0); assert.equal(bad.rejected.length, 2); +assert.equal((await queue.add(Array.from({length: MAX_SCAN_PAGES + 1}, (_, i) => file(`${i}.png`)), "original")).rejected[0].code, "SCAN_QUEUE_LIMIT"); +queue.clear(); +const broken = createScanQueue({ ...config, preview: async () => { throw new Error("IMAGE_DECODE_FAILED"); } }); +assert.equal((await broken.add([file("broken.png")], "original")).rejected[0].code, "IMAGE_DECODE_FAILED"); +assert.equal(broken.busy, false); + +// Delayed work cannot resurrect pages after clear/cancel/disposal or replacement. +for (const action of ["clear", "cancel", "dispose", "replace"]) { + let release; let calls = 0; + const delayed = createScanQueue({ ...config, preview: async () => ++calls === 1 ? new Promise(resolve => { release = resolve; }) : preview() }); + const pending = delayed.add([file("old.png")], "original"); + while (!release) await new Promise(resolve => setTimeout(resolve, 0)); + let replacement; + if (action === "replace") replacement = delayed.add([file("new.png")], "grayscale"); else delayed[action](); + assert.equal(calls, 1, "Replacement decode waits for native work already in flight"); + release(await preview()); + assert.equal((await pending).cancelled, true); + await replacement; + assert.deepEqual(delayed.pages.map(page => page.file.name), action === "replace" ? ["new.png"] : []); + delayed.dispose(); +} + +// Disposal of a page during a mode update cannot create a leaked preview URL. +let releaseMode; +const modeQueue = createScanQueue({ ...config, preview: async (file, mode) => mode === "original" ? preview() : new Promise(resolve => { releaseMode = resolve; }) }); +await modeQueue.add([file("mode.png")], "original"); +const change = modeQueue.setMode("grayscale"); +while (!releaseMode) await new Promise(resolve => setTimeout(resolve, 0)); +modeQueue.remove(modeQueue.pages[0].id); +const before = created.length; releaseMode(await preview()); await change; +assert.equal(created.length, before); + +// Canvas and decoded bitmap cleanup on success, failure and mid-decode abort. +for (const outcome of ["success", "encoder", "canvas", "abort"]) { + let closed = 0; const abort = new AbortController(); + const canvas = { width: 0, height: 0, getContext: () => outcome === "canvas" ? null : ({ fillRect() {}, drawImage() {} }), toBlob(callback) { callback(outcome === "encoder" ? null : new Blob(["png"])); } }; + const options = { signal: abort.signal, canvasFactory: () => canvas, decode: async () => { if (outcome === "abort") abort.abort(); return { width: 4000, height: 6000, source: {}, close() { closed++; } }; } }; + if (outcome === "success") { const result = await createScanPreview(file("x.png"), "original", options); assert.equal(result.width, 667); assert.equal(result.height, 1000); } + else await assert.rejects(createScanPreview(file("x.png"), "original", options)); + assert.equal(closed, 1); + if (outcome !== "abort") assert.equal(canvas.width, 1); +} + +// Shared decoder must explicitly request EXIF normalization and close bitmaps. +let bitmapOptions; let closed = false; +globalThis.window = { createImageBitmap: true }; +globalThis.createImageBitmap = async (source, options) => { bitmapOptions = options; return { width: 30, height: 60, close() { closed = true; } }; }; +const decoded = await decodeImage(file("oriented.png")); +assert.deepEqual(bitmapOptions, { imageOrientation: "from-image" }); +decoded.close(); assert.equal(closed, true); +delete globalThis.window; delete globalThis.createImageBitmap; +queue.dispose(); modeQueue.dispose(); broken.dispose(); +console.log("Scanner state, ordering, limits, pixels, invalid input, stale work, orientation contract and cleanup passed."); diff --git a/tests/security-monitoring.test.mjs b/tests/security-monitoring.test.mjs index 9d0a0ab..e5f1312 100644 --- a/tests/security-monitoring.test.mjs +++ b/tests/security-monitoring.test.mjs @@ -87,7 +87,7 @@ await assert.rejects(scanGithubVendor(github, projectRequest({ advisories: {} }) await assert.rejects(scanGithubVendor(github, projectRequest({ secondPage: true, advisories: [{ ghsa_id: "GHSA-test-test-test", state: "published", published_at: "2026-10-01T00:00:00Z", withdrawn_at: null }] })), /applicability needs review/); const workflow = fs.readFileSync(".github/workflows/security-monitoring.yml", "utf8"); -assert.match(workflow, /branches: \[v2\.3, main\]/); +assert.match(workflow, /branches: \[v2\.4, main\]/); assert.match(workflow, /languages: javascript-typescript\n\s+build-mode: none/); assert.match(workflow, /security-events: write/); assert.doesNotMatch(workflow, /contents: write|pull-requests: write|continue-on-error|\|\| true|pull_request_target/); @@ -96,7 +96,7 @@ assert.match(workflow, /npm audit --json --audit-level=low/); assert.match(workflow, /node scripts\/check-security-advisories\.mjs/); assert.match(fs.readFileSync(".github/codeql/config.yml", "utf8"), /assets\/vendor\/\*\*/); const dependabot = fs.readFileSync(".github/dependabot.yml", "utf8"); -assert.match(dependabot, /package-ecosystem: "npm"[\s\S]*?target-branch: "v2\.3"/); +assert.match(dependabot, /package-ecosystem: "npm"[\s\S]*?target-branch: "v2\.4"/); assert.match(dependabot, /package-ecosystem: "github-actions"/); assert.doesNotMatch(dependabot, /auto-merge/); auditActionPins(); diff --git a/tests/seo-foundation.test.mjs b/tests/seo-foundation.test.mjs index beb4c61..3970885 100644 --- a/tests/seo-foundation.test.mjs +++ b/tests/seo-foundation.test.mjs @@ -15,7 +15,7 @@ const indexableRoutes = new Map(canonicalPages.map(({ source, route }) => [sourc const excludedRoutes = ["404.html", "tools/image-to-pdf/index.html"]; const allHtmlRoutes = [...indexableRoutes.keys(), ...excludedRoutes]; -assert.equal(indexableRoutes.size, 19, "all canonical pages come from the route manifest"); +assert.equal(indexableRoutes.size, 20, "all canonical pages come from the route manifest"); const shareImagePath = "assets/images/og-image.png"; const shareImageUrl = `${origin}/${shareImagePath}`; const iconLinks = new Map([ diff --git a/tests/typescript-foundation.test.mjs b/tests/typescript-foundation.test.mjs index 7ea1ba3..16fd0cf 100644 --- a/tests/typescript-foundation.test.mjs +++ b/tests/typescript-foundation.test.mjs @@ -21,7 +21,7 @@ assert.equal(typeConfig.compilerOptions.noEmit, true); assert.equal(typeConfig.compilerOptions.sourceMap, false); assert.equal(buildConfig.compilerOptions.outDir, ".ts-build"); -assert.equal(compiledBrowserModules.length, 8, "the compiled TypeScript boundary remains intentionally bounded"); +assert.equal(compiledBrowserModules.length, 11, "the compiled TypeScript boundary remains intentionally bounded"); assert.ok(compiledBrowserModules.some((module) => module.source === "tools/shared/searchable-pdf.ts")); assert.equal(new Set(compiledBrowserModules.map((module) => module.public)).size, compiledBrowserModules.length); for (const module of compiledBrowserModules) { diff --git a/tests/url-namespace.test.mjs b/tests/url-namespace.test.mjs index 47cc2c9..a3dec92 100644 --- a/tests/url-namespace.test.mjs +++ b/tests/url-namespace.test.mjs @@ -8,7 +8,7 @@ import { canonicalPages, legacyRedirects, productionOrigin, redirectStatus } fro const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const routes = new Set(canonicalPages.map(({ route }) => route)); -assert.equal(canonicalPages.length, 19); +assert.equal(canonicalPages.length, 20); assert.equal(legacyRedirects.length, 17); assert.equal(redirectStatus, 308); assert.ok(routes.has("/image/to-text/")); diff --git a/tools/pdf/images-to-pdf/pdf.d.ts b/tools/pdf/images-to-pdf/pdf.d.ts new file mode 100644 index 0000000..fe0a586 --- /dev/null +++ b/tools/pdf/images-to-pdf/pdf.d.ts @@ -0,0 +1,9 @@ +import type { DecodedImage } from "../../shared/image.js"; +export interface ImagePdfOptions { pageSize: string; orientation: string; margin: number; quality: number; fillPage: boolean } +export function createPdfBlob(options: { + files: readonly File[]; options: ImagePdfOptions; JsPDF: unknown; + signal?: AbortSignal; imageFormat?: string; + onProgress?: (completed: number, total: number) => void; + decode?: (file: File) => Promise; + convert?: (image: DecodedImage, quality: number, index: number) => Promise; +}): Promise; diff --git a/tools/pdf/images-to-pdf/pdf.js b/tools/pdf/images-to-pdf/pdf.js index edb594a..792a5cc 100644 --- a/tools/pdf/images-to-pdf/pdf.js +++ b/tools/pdf/images-to-pdf/pdf.js @@ -63,7 +63,11 @@ export async function createPdfBlob({ onProgress = () => {}, decode = decodeImage, convert = imageToJpegData, + imageFormat = "JPEG", + signal, }) { + const checkCancelled = () => { if (signal?.aborted) throw new DOMException("Cancelled", "AbortError"); }; + checkCancelled(); if (!files.length) { const error = new Error("NO_FILES"); error.code = "NO_FILES"; @@ -79,7 +83,9 @@ export async function createPdfBlob({ for (let index = 0; index < files.length; index += 1) { let image; try { + checkCancelled(); image = await decode(files[index]); + checkCancelled(); const [pageWidth, pageHeight] = getPageDimensions( options.pageSize, options.orientation, @@ -98,7 +104,8 @@ export async function createPdfBlob({ pdf.addPage([pageWidth, pageHeight], pageOrientation); } - const jpegData = convert(image, Number(options.quality) || 0.92); + const imageData = await convert(image, Number(options.quality) || 0.92, index); + checkCancelled(); const placement = getImagePlacement( image, pageWidth, @@ -107,8 +114,8 @@ export async function createPdfBlob({ options.fillPage, ); pdf.addImage( - jpegData, - "JPEG", + imageData, + imageFormat, placement.x, placement.y, placement.width, @@ -119,6 +126,7 @@ export async function createPdfBlob({ onProgress(index + 1, files.length); await new Promise((resolve) => setTimeout(resolve, 0)); } catch (cause) { + if (signal?.aborted || cause.name === "AbortError") throw new DOMException("Cancelled", "AbortError"); const error = new Error(cause.code || "PDF_GENERATION_FAILED", { cause }); error.code = cause.code || "PDF_GENERATION_FAILED"; error.fileName = files[index]?.name || ""; @@ -128,5 +136,8 @@ export async function createPdfBlob({ } } - return pdf.output("blob"); + checkCancelled(); + const result = pdf.output("blob"); + checkCancelled(); + return result; } diff --git a/tools/scan/document/app.js b/tools/scan/document/app.js new file mode 100644 index 0000000..f8911a5 --- /dev/null +++ b/tools/scan/document/app.js @@ -0,0 +1,164 @@ +import { t } from "../../../js/i18n.js"; +import { createScanQueue } from "./state.js"; +import { createScanPdf, createScanPdfController } from "./pdf.js"; +import { createScanResultPreview } from "./result.js"; +import { downloadBlob } from "../../shared/save.js"; + +const input = document.querySelector("#file-input"); +const list = document.querySelector("#page-list"); +const mode = document.querySelector("#scan-mode"); +const status = document.querySelector("#tool-status"); +const add = document.querySelector("#add-images"); +const clear = document.querySelector("#clear-images"); +const apply = document.querySelector("#apply-mode"); +const cancel = document.querySelector("#cancel-scan"); +let notice = null; +let noticeValues = {}; +let actionVersion = 0; +const message = (key, values = {}) => Object.entries(values).reduce((text, [name, value]) => text.replaceAll(`{${name}}`, String(value)), t(`documentScanner.${key}`)); +let queueKey = ""; +let pdfVersion = 0; +const queue = createScanQueue({ changed: queueChanged }); +const pdf = createScanPdfController((pages, signal, onProgress) => createScanPdf({ pages, signal, onProgress, JsPDF: window.jspdf?.jsPDF }), render); +const resultPreview = createScanResultPreview(document.querySelector("#pdf-preview"), render, () => announce("pdfPreviewError")); +function invalidatePdf() { ++pdfVersion; pdf.invalidate(); resultPreview.clear(); } +function queueChanged() { + const key = queue.pages.map(page => `${page.id}/${page.mode}`).join(","); + if (key !== queueKey) { queueKey = key; invalidatePdf(); } + render(); +} + +function announce(key, values = {}) { notice = key; noticeValues = values; render(); } +function render() { + // Keep existing DOM nodes so progress and reorder do not steal keyboard focus. + const focused = document.activeElement; + for (const child of [...list.children]) if (!queue.pages.some(page => String(page.id) === child.dataset.id)) child.remove(); + queue.pages.forEach((page, index) => { + let card = list.querySelector(`[data-id="${page.id}"]`); + if (!card) { + card = document.createElement("li"); card.className = "scan-page"; card.dataset.id = String(page.id); + const image = document.createElement("img"); image.decoding = "async"; + const name = document.createElement("strong"); const details = document.createElement("p"); + const actions = document.createElement("div"); actions.className = "scan-page-actions"; + for (const action of ["up", "down", "remove"]) { + const button = document.createElement("button"); button.type = "button"; button.className = "button button--secondary"; button.dataset.action = action; actions.append(button); + } + card.append(image, name, details, actions); + } + const image = card.querySelector("img"); if (image.getAttribute("src") !== page.url) image.src = page.url; + image.alt = message("preview", { page: index + 1 }); + card.querySelector("strong").textContent = `${index + 1}. ${page.file.name}`; + card.querySelector("p").textContent = `${page.width} × ${page.height} · ${message(page.mode)}`; + for (const button of card.querySelectorAll("button")) { + const action = button.dataset.action; + button.textContent = message(action); button.setAttribute("aria-label", `${message(action)}: ${page.file.name}`); + button.disabled = (action === "up" && index === 0) || (action === "down" && index === queue.pages.length - 1); + } + // insertBefore avoids detaching nodes already in their correct position. + if (list.children[index] !== card) list.insertBefore(card, list.children[index] || null); + }); + if (focused?.isConnected && document.activeElement !== focused) focused.focus(); + document.querySelector("#queue-empty").hidden = queue.pages.length > 0; + document.querySelector("#page-count").textContent = message("count", { count: queue.pages.length }); + clear.disabled = !queue.pages.length && !queue.busy && !pdf.busy && !pdf.result; + apply.disabled = !queue.pages.length || queue.busy; + mode.disabled = queue.busy; + cancel.hidden = !queue.busy; + list.setAttribute("aria-busy", String(queue.busy)); + document.querySelector("#create-pdf").disabled = !queue.pages.length || queue.busy || pdf.busy; + document.querySelector("#cancel-pdf").hidden = !pdf.busy; + const progress = document.querySelector("#pdf-progress"); + progress.hidden = !pdf.busy; progress.max = pdf.total || 1; progress.value = pdf.progress; + document.querySelector("#pdf-result").hidden = !pdf.result; + document.querySelector("#pdf-preview").setAttribute("aria-busy", String(resultPreview.busy)); + document.querySelector("#pdf-page").textContent = resultPreview.busy ? message("pdfLoading") : message("pdfPage", { page: resultPreview.pageNumber, total: resultPreview.pageCount }); + document.querySelector("#pdf-previous").disabled = resultPreview.busy || resultPreview.pageNumber <= 1; + document.querySelector("#pdf-next").disabled = resultPreview.busy || resultPreview.pageNumber >= resultPreview.pageCount; + status.textContent = pdf.busy ? message("pdfProgress", { done: pdf.progress, total: pdf.total }) : queue.busy ? message("processing", { count: queue.pages.length }) : notice ? message(notice, noticeValues) : ""; +} + +async function addFiles(files) { + if (!files.length) return; + invalidatePdf(); + const version = ++actionVersion; + try { + const result = await queue.add(files, mode.value); + if (version !== actionVersion) return; + if (result.cancelled) announce("cancelled"); + else if (result.rejected.length) announce("rejected", { added: result.added, names: result.rejected.map(item => `${item.name}: ${message(errorKey(item.code))}`).join("; ") }); + else announce("added", { count: result.added }); + } catch { if (version === actionVersion) announce("failure"); } +} +function errorKey(code) { + if (["SCAN_QUEUE_LIMIT", "IMAGE_FILE_TOO_LARGE", "IMAGE_DIMENSION_EXCEEDED", "IMAGE_PIXELS_EXCEEDED"].includes(code)) return "limit"; + if (["UNSUPPORTED_IMAGE", "IMAGE_SIGNATURE_INVALID"].includes(code)) return "unsupported"; + return "decode"; +} +add.addEventListener("click", () => input.click()); +input.addEventListener("change", () => { void addFiles([...input.files]); input.value = ""; }); +const zone = document.querySelector("#drop-zone"); +for (const event of ["dragover", "drop"]) zone.addEventListener(event, e => e.preventDefault()); +zone.addEventListener("drop", event => { void addFiles([...event.dataTransfer.files]); }); +document.addEventListener("paste", event => { + if (event.target.closest?.("input, textarea, [contenteditable]")) return; + const files = [...(event.clipboardData?.files || [])]; + if (files.length) { event.preventDefault(); void addFiles(files); } +}); +clear.addEventListener("click", () => { ++actionVersion; invalidatePdf(); queue.clear(); announce("cleared"); add.focus(); }); +cancel.addEventListener("click", () => { ++actionVersion; queue.cancel(); announce("cancelled"); add.focus(); }); +apply.addEventListener("click", async () => { + invalidatePdf(); + const version = ++actionVersion; + try { const complete = await queue.setMode(mode.value); if (version === actionVersion) announce(complete ? "applied" : "cancelled"); } + catch { if (version === actionVersion) announce("failure"); } + finally { if (version === actionVersion && !queue.busy) apply.focus(); } +}); +list.addEventListener("click", event => { + const button = event.target.closest("button[data-action]"); if (!button) return; + const card = button.closest("[data-id]"); const id = Number(card.dataset.id); + if (button.dataset.action === "remove") { + const index = queue.pages.findIndex(page => page.id === id); queue.remove(id); + const next = queue.pages[Math.min(index, queue.pages.length - 1)]; + (next ? list.querySelector(`[data-id="${next.id}"] [data-action="remove"]`) : add)?.focus(); + announce("removed"); + } else { + queue.move(id, button.dataset.action === "up" ? -1 : 1); announce("reordered"); + const target = list.querySelector(`[data-id="${id}"] button:not(:disabled)`); target?.focus(); + } +}); +document.addEventListener("securetools:languagechange", render); +document.querySelector("#create-pdf").addEventListener("click", async () => { + if (queue.busy || pdf.busy || !queue.pages.length) return; + const version = ++pdfVersion; + resultPreview.clear(); + const creation = pdf.create(queue.pages); + document.querySelector("#cancel-pdf").focus(); + try { + const blob = await creation; + if (version !== pdfVersion || !blob) return; + announce("pdfReady"); + void resultPreview.open(blob); + } catch (error) { + if (version === pdfVersion) announce(error.code === "SCAN_EXPORT_LIMIT" ? "pdfLimit" : "pdfError"); + } finally { + if (version === pdfVersion) document.querySelector("#create-pdf").focus(); + } +}); +document.querySelector("#cancel-pdf").addEventListener("click", () => { ++actionVersion; invalidatePdf(); announce("pdfCancelled"); document.querySelector("#create-pdf").focus(); }); +document.querySelector("#download-pdf").addEventListener("click", () => { + if (!pdf.result) return; + try { downloadBlob(pdf.result, "scanned-document.pdf"); announce("pdfDownloaded"); } + catch { announce("pdfDownloadError"); } +}); +async function movePdfPreview(offset) { + const focused = document.activeElement; + await resultPreview.move(offset); + if (!pdf.result || (document.activeElement !== document.body && document.activeElement !== focused)) return; + const preferred = document.querySelector(offset < 0 ? "#pdf-previous" : "#pdf-next"); + const alternate = document.querySelector(offset < 0 ? "#pdf-next" : "#pdf-previous"); + (preferred.disabled ? alternate : preferred).focus(); +} +document.querySelector("#pdf-previous").addEventListener("click", () => { void movePdfPreview(-1); }); +document.querySelector("#pdf-next").addEventListener("click", () => { void movePdfPreview(1); }); +window.addEventListener("pagehide", event => { ++actionVersion; invalidatePdf(); if (event.persisted) queue.clear(); else queue.dispose(); }); +render(); diff --git a/tools/scan/document/index.html b/tools/scan/document/index.html new file mode 100644 index 0000000..d7260fc --- /dev/null +++ b/tools/scan/document/index.html @@ -0,0 +1,19 @@ + + + + +Document Scanner — Secure Tools + + + + +
+

Local scan tool

Document Scanner

Arrange and clean document images on this device.

+

Add images

Choose, drop or paste JPEG, PNG or WebP images. Up to 20 pages and 200 MiB total; 50 MiB per image.

Your files stay on your device.

+

Scan appearance

Document mode uses a fixed black-and-white threshold. No automatic cropping or corner detection.

A4, automatic orientation, 10 mm margins. Export limits: 12 megapixels per image and 24 megapixels total.

Create PDFs locally. Optional text recognition is coming later.

+

Document pages

No pages added yet.

    +
    + + diff --git a/tools/scan/document/pdf.ts b/tools/scan/document/pdf.ts new file mode 100644 index 0000000..1cabc7c --- /dev/null +++ b/tools/scan/document/pdf.ts @@ -0,0 +1,77 @@ +import { createPdfBlob } from "../../pdf/images-to-pdf/pdf.js"; +import { decodeImage } from "../../shared/image.js"; +import { renderScanImage } from "../../shared/scan.js"; +import type { DecodedImage } from "../../shared/image.js"; +import type { ScanMode } from "../../shared/scan.js"; + +export const SCAN_EXPORT_PAGE_PIXELS = 12_000_000; +export const SCAN_EXPORT_TOTAL_PIXELS = 24_000_000; +export const SCAN_EXPORT_BYTES = 64 * 1024 * 1024; +export interface ScanExportPage { file: File; mode: ScanMode } +interface ExportOptions { + pages: readonly ScanExportPage[]; JsPDF: unknown; signal?: AbortSignal; + onProgress?: (done: number, total: number) => void; + decode?: (file: File) => Promise; + raster?: typeof renderScanImage; +} +function limit(): never { throw Object.assign(new Error("SCAN_EXPORT_LIMIT"), { code: "SCAN_EXPORT_LIMIT" }); } + +export async function createScanPdf(options: ExportOptions): Promise { + if (options.pages.length > 20 || options.pages.reduce((n, page) => n + page.file.size, 0) > 200 * 1024 * 1024) limit(); + let totalPixels = 0; + let totalBytes = 0; + const blob = await createPdfBlob({ + files: options.pages.map(page => page.file), + options: { pageSize: "a4", orientation: "auto", margin: 10, fillPage: false, quality: 1 }, + JsPDF: options.JsPDF, signal: options.signal, imageFormat: "PNG", onProgress: options.onProgress, + decode: async file => { + const image = await (options.decode || decodeImage)(file); + const pixels = image.width * image.height; + if (pixels > SCAN_EXPORT_PAGE_PIXELS || totalPixels + pixels > SCAN_EXPORT_TOTAL_PIXELS) { image.close(); limit(); } + totalPixels += pixels; + return image; + }, + convert: async (image, _quality, index) => { + const result = await (options.raster || renderScanImage)(image, options.pages[index].mode, { signal: options.signal }); + totalBytes += result.blob.size; + if (totalBytes > SCAN_EXPORT_BYTES) limit(); + return new Uint8Array(await result.blob.arrayBuffer()); + }, + }); + if (blob.size > SCAN_EXPORT_BYTES) limit(); + return blob; +} + +// Serialize native PDF writers, and guard every publication with its generation. +// Results are held as a Blob only; renderer and download URL lifetimes belong to UI. +export function createScanPdfController(build: (pages: readonly ScanExportPage[], signal: AbortSignal, progress: (done: number, total: number) => void) => Promise, changed: () => void = () => {}) { + let revision = 0; + let job: AbortController | null = null; + let work: Promise = Promise.resolve(); + let result: Blob | null = null; + let progress = 0; + let total = 0; + function invalidate() { revision++; job?.abort(); job = null; result = null; changed(); } + return { + get result() { return result; }, get busy() { return job !== null; }, + get progress() { return progress; }, get total() { return total; }, invalidate, + async create(pages: readonly ScanExportPage[]) { + invalidate(); + const version = revision; + const current = new AbortController(); job = current; progress = 0; total = pages.length; changed(); + const snapshot = pages.map(page => ({ file: page.file, mode: page.mode })); + const task = work.then(async () => { + if (current.signal.aborted) return null; + const blob = await build(snapshot, current.signal, (done, count) => { + if (version === revision && !current.signal.aborted) { progress = done; total = count; changed(); } + }); + if (version !== revision || current.signal.aborted) return null; + result = blob; return blob; + }); + work = task.then(() => {}, () => {}); + try { return await task; } + catch (error) { if (version !== revision || current.signal.aborted) return null; throw error; } + finally { if (version === revision) { job = null; changed(); } } + }, + }; +} diff --git a/tools/scan/document/result.js b/tools/scan/document/result.js new file mode 100644 index 0000000..4d98bc4 --- /dev/null +++ b/tools/scan/document/result.js @@ -0,0 +1,58 @@ +import { LocalPdfRenderer } from "../../shared/pdf-renderer.js"; + +// Render the generated PDF through the existing local PDF.js service, never an +// iframe/object URL. Keep one bounded canvas and dispose the renderer on reset. +export function createScanResultPreview(canvas, changed, failed) { + let renderer = null; + let version = 0; + let pageNumber = 1; + let pageCount = 0; + let busy = false; + let disposed = Promise.resolve(); + const resetCanvas = () => { canvas.width = canvas.height = 1; }; + function clear() { + version++; const previous = renderer; renderer = null; + if (previous) disposed = disposed.then(() => previous.destroy()).catch(() => {}); + pageNumber = 1; pageCount = 0; busy = false; resetCanvas(); changed(); + } + async function draw(current, revision) { + let page; + try { + page = await current.getPage(pageNumber); + if (revision !== version) return; + const size = page.getViewport({ scale: 1 }); + const viewport = page.getViewport({ scale: Math.min(1.5, 900 / Math.max(size.width, size.height)) }); + // A detached canvas prevents an obsolete render from touching live output. + const buffer = document.createElement("canvas"); + try { + buffer.width = Math.ceil(viewport.width); buffer.height = Math.ceil(viewport.height); + await current.runRender(page, { canvasContext: buffer.getContext("2d"), viewport, background: "#ffffff" }); + if (revision !== version) return; + canvas.width = buffer.width; canvas.height = buffer.height; + canvas.getContext("2d").drawImage(buffer, 0, 0); + } finally { buffer.width = buffer.height = 1; } + } finally { page?.cleanup(); } + } + async function open(blob) { + clear(); const revision = version; busy = true; changed(); + try { + await disposed; + const bytes = await blob.arrayBuffer(); + if (revision !== version) return; + const current = renderer = new LocalPdfRenderer(bytes); + const count = await current.load(); + if (revision !== version) return; + pageCount = count; + await draw(current, revision); + } catch { if (revision === version) { clear(); failed(); } } + finally { if (revision === version) { busy = false; changed(); } } + } + async function move(offset) { + if (busy || !renderer || pageNumber + offset < 1 || pageNumber + offset > pageCount) return; + pageNumber += offset; busy = true; changed(); const revision = version; + try { await draw(renderer, revision); } + catch { if (revision === version) { clear(); failed(); } } + finally { if (revision === version) { busy = false; changed(); } } + } + return { clear, open, move, get busy() { return busy; }, get pageNumber() { return pageNumber; }, get pageCount() { return pageCount; } }; +} diff --git a/tools/scan/document/state.ts b/tools/scan/document/state.ts new file mode 100644 index 0000000..e64d411 --- /dev/null +++ b/tools/scan/document/state.ts @@ -0,0 +1,109 @@ +import { isSupportedImage, MAX_FILE_SIZE, validateImageSignature } from "../../shared/image.js"; +import { createScanPreview } from "../../shared/scan.js"; +import type { ScanMode, ScanPreview, ScanPreviewOptions } from "../../shared/scan.js"; + +export const MAX_SCAN_PAGES = 20; +export const MAX_SCAN_BYTES = 200 * 1024 * 1024; +export interface ScanPage { id: number; file: File; url: string; width: number; height: number; mode: ScanMode } +interface QueueOptions { + preview?: (file: Blob, mode: ScanMode, options: ScanPreviewOptions) => Promise; + createUrl?: (blob: Blob) => string; + revokeUrl?: (url: string) => void; + changed?: () => void; +} + +export function createScanQueue(options: QueueOptions = {}) { + const pages: ScanPage[] = []; + const preview = options.preview || createScanPreview; + const createUrl = options.createUrl || (blob => URL.createObjectURL(blob)); + const revokeUrl = options.revokeUrl || (url => URL.revokeObjectURL(url)); + let controller: AbortController | null = null; + let sequence = 0; + let disposed = false; + let previewWork: Promise = Promise.resolve(); + const changed = () => options.changed?.(); + + // Native decode cannot be interrupted. Serialize replacements behind it so + // rapid input changes cannot accumulate concurrent full-resolution bitmaps. + function renderPreview(file: File, mode: ScanMode, signal: AbortSignal) { + const result = previewWork.then(() => { + if (signal.aborted) throw new DOMException("Cancelled", "AbortError"); + return preview(file, mode, { signal }); + }); + previewWork = result.then(() => {}, () => {}); + return result; + } + + function cancel() { controller?.abort(); controller = null; changed(); } + function start() { + if (disposed) throw new Error("SCAN_DISPOSED"); + cancel(); + const job = new AbortController(); + controller = job; + changed(); + return job; + } + function current(job: AbortController) { return !disposed && controller === job && !job.signal.aborted; } + function finish(job: AbortController) { if (controller === job) { controller = null; changed(); } } + function remove(id: number) { + const index = pages.findIndex(page => page.id === id); + if (index < 0) return; + revokeUrl(pages[index].url); pages.splice(index, 1); changed(); + } + function clear() { cancel(); pages.forEach(page => revokeUrl(page.url)); pages.length = 0; changed(); } + + async function add(files: readonly File[], mode: ScanMode) { + const job = start(); + const rejected: { name: string; code: string }[] = []; + let added = 0; + try { + for (const file of files) { + if (!current(job)) break; + try { + if (!isSupportedImage(file)) throw new Error("UNSUPPORTED_IMAGE"); + if (file.size > MAX_FILE_SIZE) throw new Error("IMAGE_FILE_TOO_LARGE"); + if (pages.length >= MAX_SCAN_PAGES || pages.reduce((total, page) => total + page.file.size, 0) + file.size > MAX_SCAN_BYTES) throw new Error("SCAN_QUEUE_LIMIT"); + await validateImageSignature(file); + if (!current(job)) break; + const result = await renderPreview(file, mode, job.signal); + if (!current(job)) break; + pages.push({ id: ++sequence, file, url: createUrl(result.blob), width: result.width, height: result.height, mode }); + added++; changed(); + } catch (error) { + if (!current(job)) break; + rejected.push({ name: file.name, code: error instanceof Error ? error.message : "IMAGE_DECODE_FAILED" }); + } + } + return { added, rejected, cancelled: !current(job) }; + } finally { finish(job); } + } + + async function setMode(mode: ScanMode) { + const job = start(); + try { + for (const page of [...pages]) { + if (!current(job)) return false; + if (page.mode === mode) continue; + const result = await renderPreview(page.file, mode, job.signal); + if (!current(job)) return false; + if (!pages.includes(page)) continue; + const url = createUrl(result.blob); + revokeUrl(page.url); page.url = url; page.mode = mode; changed(); + } + return current(job); + } finally { finish(job); } + } + + return { + get pages(): readonly ScanPage[] { return pages; }, + get busy() { return controller !== null; }, + add, setMode, cancel, clear, remove, + move(id: number, offset: number) { + const index = pages.findIndex(page => page.id === id); + const next = index + offset; + if (index < 0 || next < 0 || next >= pages.length) return false; + [pages[index], pages[next]] = [pages[next], pages[index]]; changed(); return true; + }, + dispose() { disposed = true; clear(); }, + }; +} diff --git a/tools/scan/document/tool.css b/tools/scan/document/tool.css new file mode 100644 index 0000000..5f7136e --- /dev/null +++ b/tools/scan/document/tool.css @@ -0,0 +1,17 @@ +.scanner-layout { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr); gap: 1.25rem; margin-block: 1.5rem; } +.tool-main [hidden] { display: none !important; } +.scanner-controls, .scanner-pages { padding: clamp(1rem, 3vw, 1.5rem); min-width: 0; } +.scanner-controls select { display: block; width: 100%; margin-block: .5rem; } +.scan-page-list { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr)); gap: 1rem; padding: 0; list-style: none; } +.scan-page { min-width: 0; border: 1px solid var(--border); border-radius: .75rem; padding: 1rem; } +.scan-page img { display: block; width: 100%; height: 280px; object-fit: contain; background: #fff; } +.scan-page strong, .scan-page p { display: block; overflow-wrap: anywhere; margin-block: .75rem; } +.scan-page-actions { display: flex; flex-wrap: wrap; gap: .5rem; } +.scan-page-actions button { min-height: 44px; min-width: 44px; white-space: normal; overflow-wrap: anywhere; } +#tool-status { overflow-wrap: anywhere; } +@media (max-width: 700px) { .scanner-layout { grid-template-columns: minmax(0, 1fr); } } + +#pdf-preview { display: block; max-width: 100%; max-height: 65vh; width: auto; height: auto; margin: 1rem auto; border: 1px solid var(--border); background: #fff; } +#pdf-progress { width: 100%; margin-block: .75rem; } +#pdf-result { margin-block-start: 1.25rem; } +#pdf-progress + .field-help { margin-block: .75rem; } diff --git a/tools/scan/index.html b/tools/scan/index.html index d5c6b22..91378b0 100644 --- a/tools/scan/index.html +++ b/tools/scan/index.html @@ -23,4 +23,4 @@
    Menu
    -

    Tool category

    Scan & OCR tools

    Turn scans into useful documents while keeping source material on your device.

    Available tools process file contents locally in browser memory.

    +
    diff --git a/tools/shared/image.d.ts b/tools/shared/image.d.ts new file mode 100644 index 0000000..026cc97 --- /dev/null +++ b/tools/shared/image.d.ts @@ -0,0 +1,12 @@ +export interface DecodedImage { + source: CanvasImageSource; + width: number; + height: number; + close(): void; +} +export const ACCEPTED_IMAGE_TYPES: string; +export const MAX_FILE_SIZE: number; +export function decodeImage(file: Blob): Promise; +export function isSupportedImage(file: Blob): boolean; +export function validateImageSignature(file: Blob): Promise; +export function validateImageDimensions(width: number, height: number): boolean; diff --git a/tools/shared/scan.ts b/tools/shared/scan.ts new file mode 100644 index 0000000..c10373c --- /dev/null +++ b/tools/shared/scan.ts @@ -0,0 +1,75 @@ +import { decodeImage } from "./image.js"; +import type { DecodedImage } from "./image.js"; + +export const SCAN_MODES = ["original", "grayscale", "document"] as const; +export type ScanMode = typeof SCAN_MODES[number]; +export const SCAN_PREVIEW_EDGE = 1000; + +// Return a copy: callers may safely reuse the original pixels for other modes. +export function preprocessScanPixels(source: Uint8ClampedArray, mode: ScanMode): Uint8ClampedArray { + if (!SCAN_MODES.includes(mode)) throw new Error("SCAN_MODE_INVALID"); + const output = new Uint8ClampedArray(source); + if (mode === "original") return output; + for (let i = 0; i < output.length; i += 4) { + const gray = Math.round(source[i] * 0.299 + source[i + 1] * 0.587 + source[i + 2] * 0.114); + const value = mode === "document" ? (gray >= 160 ? 255 : 0) : gray; + output[i] = output[i + 1] = output[i + 2] = value; + } + return output; +} + +function checkCancellation(signal?: AbortSignal): void { + if (signal?.aborted) throw new DOMException("Cancelled", "AbortError"); +} + +export interface ScanPreview { blob: Blob; width: number; height: number } +export interface ScanPreviewOptions { + signal?: AbortSignal; + decode?: (file: Blob) => Promise; + canvasFactory?: () => HTMLCanvasElement; +} + +export interface ScanRasterOptions extends ScanPreviewOptions { maxEdge?: number } + +// Only the source File and a bounded preview are retained by the page queue. +// Future exports can decode the source again without exporting thumbnail pixels. +export async function createScanPreview(file: Blob, mode: ScanMode, options: ScanPreviewOptions = {}): Promise { + checkCancellation(options.signal); + const image = await (options.decode || decodeImage)(file); + try { return await renderScanImage(image, mode, { ...options, maxEdge: SCAN_PREVIEW_EDGE }); } + finally { image.close(); } +} + +// No maxEdge means full decoded source resolution. Export callers own image.close. +export async function renderScanImage(image: DecodedImage, mode: ScanMode, options: ScanRasterOptions = {}): Promise { + let canvas: HTMLCanvasElement | undefined; + try { + checkCancellation(options.signal); + canvas = (options.canvasFactory || (() => document.createElement("canvas")))(); + const ratio = Math.min(1, (options.maxEdge ?? Infinity) / Math.max(image.width, image.height)); + const width = canvas.width = Math.max(1, Math.round(image.width * ratio)); + const height = canvas.height = Math.max(1, Math.round(image.height * ratio)); + const context = canvas.getContext("2d", { alpha: false }); + if (!context) throw new Error("CANVAS_UNAVAILABLE"); + context.fillStyle = "#ffffff"; + context.fillRect(0, 0, width, height); + context.drawImage(image.source, 0, 0, width, height); + if (mode !== "original") { + // Bounded strips avoid two additional full-resolution pixel buffers. + for (let y = 0; y < height; y += 64) { + checkCancellation(options.signal); + const pixels = context.getImageData(0, y, width, Math.min(64, height - y)); + pixels.data.set(preprocessScanPixels(pixels.data, mode)); + context.putImageData(pixels, 0, y); + if (y % 1024 === 0) await new Promise(resolve => setTimeout(resolve, 0)); + } + } + const blob = await new Promise((resolve, reject) => canvas!.toBlob( + result => result ? resolve(result) : reject(new Error("IMAGE_EXPORT_FAILED")), "image/png", + )); + checkCancellation(options.signal); + return { blob, width, height }; + } finally { + if (canvas) canvas.width = canvas.height = 1; + } +} diff --git a/tsconfig.build.json b/tsconfig.build.json index 73e475a..a0e481d 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -14,6 +14,8 @@ "tools/pdf/to-text/output.ts", "tools/shared/pdf-ocr.ts", "tools/shared/searchable-pdf.ts", - "tools/shared/*.d.ts" + "tools/shared/*.d.ts", + "tools/shared/scan.ts", + "tools/scan/document/*.ts" ] } diff --git a/tsconfig.json b/tsconfig.json index fd68b31..052d259 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,7 +4,11 @@ "declaration": false, "forceConsistentCasingInFileNames": true, "isolatedModules": true, - "lib": ["ES2022", "DOM", "DOM.Iterable"], + "lib": [ + "ES2022", + "DOM", + "DOM.Iterable" + ], "module": "ESNext", "moduleResolution": "Bundler", "noEmit": true, @@ -21,6 +25,8 @@ "tools/shared/searchable-pdf.ts", "tools/shared/*.d.ts", "tools/pdf/split/*.d.ts", - "js/*.d.ts" + "js/*.d.ts", + "tools/shared/scan.ts", + "tools/scan/document/*.ts" ] }