@hussmartinez/pdf-sdk 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -3
- package/dist/assets/processing/processing.worker.js +1 -1
- package/dist/index.d.ts +33 -47
- package/dist/index.js +1 -1
- package/dist/lazy/{processing-worker-Dy5JQHXJ.js → processing-worker-B70FATD2.js} +2 -2
- package/dist/lazy/{processing-worker-Dy5JQHXJ.js.map → processing-worker-B70FATD2.js.map} +1 -1
- package/dist/react.d.ts +177 -172
- package/dist/react.js +479 -42
- package/dist/react.js.map +1 -1
- package/dist/shared/{en-CQX26xju.js → en-DiJkcy2X.js} +56 -46
- package/dist/shared/en-DiJkcy2X.js.map +1 -0
- package/dist/styles.css +18 -0
- package/package.json +11 -8
- package/dist/shared/en-CQX26xju.js.map +0 -1
package/README.md
CHANGED
|
@@ -28,10 +28,22 @@ const bytes = await editor.current?.export();
|
|
|
28
28
|
|
|
29
29
|
**A bounded height.** `PdfEditor` fills the height of its container, and its viewer and thumbnails scroll within it, so give it a bounded height: a fixed height, or a grid row such as `minmax(0, 1fr)`. The same goes for `PdfViewer` and `PdfThumbnails` used on their own.
|
|
30
30
|
|
|
31
|
-
**Text.** `messages` overrides any text the editor shows, by key, including ui's, such as `"spinner.label"`. The editor builds one set of text from them and your `locale`, for its own components and for ui's ([sdk-core ADR 0046](https://github.com/ie-huss-martinez/sdk-core/blob/main/docs/adr/0046-ui-text-through-the-sdk.md)). `pdfEditorMessages
|
|
31
|
+
**Text.** `messages` overrides any text the editor shows, by key, including ui's, such as `"spinner.label"`. The editor builds one set of text from them and your `locale`, for its own components and for ui's ([sdk-core ADR 0046](https://github.com/ie-huss-martinez/sdk-core/blob/main/docs/adr/0046-ui-text-through-the-sdk.md)). `pdfEditorMessages`, from `@hussmartinez/pdf-sdk/react`, is the English catalogue, and `MessageOverrides<PdfEditorMessageCatalogue>` types your overrides. `pdfMessages`, from the server-safe entry, holds only error and warning text, for hosts that show the session's errors themselves ([ADR 0010](docs/adr/0010-interface-text-outside-the-server-safe-entry.md)).
|
|
32
32
|
|
|
33
33
|
`file` opens a document, and a different one replaces it; `null` closes it. Users can also open one with the editor's button or by dropping it on the editor. `onChange` reports each `open`, `edit` and `close`, and the ref's `PdfEditorHandle` exports, undoes, redoes and closes.
|
|
34
34
|
|
|
35
|
+
**The file's name.** On `open`, `onChange` also gives the opened file's `fileName`, from the `File`, or from the `name` option of `handle.open(bytes, { name })`. The session's `sources` carry it as `name`. It's cleaned first: one path segment, with no control or bidirectional formatting characters and at most 128 code points ([ADR 0009](docs/adr/0009-saving-the-document.md)). It comes from the file, so show it only as text. It's never sent to `onEvent`.
|
|
36
|
+
|
|
37
|
+
### Saving
|
|
38
|
+
|
|
39
|
+
The download tool builds the document in the processing worker and downloads it. The file is named after the opened file, or `document.pdf` ([ADR 0009](docs/adr/0009-saving-the-document.md)). The download uses a `blob:` URL, so it makes no request and needs nothing more in your Content Security Policy.
|
|
40
|
+
|
|
41
|
+
- **`downloadName(info)`** names the file yourself. `info` has the opened file's `sourceName` and the `pageCount`. The result is cleaned as a file name and gets a `.pdf` extension.
|
|
42
|
+
- **`onExport(bytes, info)`** receives the bytes instead of the browser downloading them, for example to keep them in your app's storage. `info` has the `fileName` the download would have had, and the `pageCount`. If it throws or rejects, the editor says the PDF couldn't be saved. Your error is yours to log, and the editor doesn't read it.
|
|
43
|
+
- **While it builds,** the button is disabled but keeps focus, and the header says "Preparing the PDF…". After a second, a Cancel button appears beside it.
|
|
44
|
+
- **Cancelling:** cancelling, or opening or closing a document, stops the build quietly.
|
|
45
|
+
- **Failures:** a failed build shows its error's text in the header.
|
|
46
|
+
|
|
35
47
|
### Tools, the toolbar and shortcuts
|
|
36
48
|
|
|
37
49
|
The editor's tools are in `pdfTools`:
|
|
@@ -39,10 +51,15 @@ The editor's tools are in `pdfTools`:
|
|
|
39
51
|
| Tool | Shortcut | What it does |
|
|
40
52
|
|---|---|---|
|
|
41
53
|
| `pdf.open` | none: `Ctrl+O` is the browser's own | Opens a PDF, replacing the current one |
|
|
54
|
+
| `pdf.insert-pages` | none | Inserts every page of another PDF after the current page, which merges the two |
|
|
42
55
|
| `pdf.undo` | `Ctrl+Z`, or `⌘Z` on Apple platforms | Undoes the last edit |
|
|
43
56
|
| `pdf.redo` | `Ctrl+Shift+Z` or `Ctrl+Y`, or `⇧⌘Z` | Redoes the last undone edit |
|
|
44
57
|
| `pdf.rotate-left` | `[` | Turns the selected pages, or the current one, a quarter turn anticlockwise |
|
|
45
58
|
| `pdf.rotate-right` | `]` | Turns them a quarter turn clockwise |
|
|
59
|
+
| `pdf.move-earlier` | `Alt+↑` (`Option+↑` on macOS), in the thumbnails only | Moves the selected pages, or the current one, one position earlier |
|
|
60
|
+
| `pdf.move-later` | `Alt+↓` (`Option+↓`), in the thumbnails only | Moves them one position later |
|
|
61
|
+
| `pdf.delete-pages` | `Delete` or `Backspace`, in the thumbnails only | Deletes the selected pages, or the current one; a document keeps at least one page |
|
|
62
|
+
| `pdf.download` | none: `Ctrl+S` is the browser's own | Builds the document and downloads it, or hands it to `onExport` |
|
|
46
63
|
|
|
47
64
|
Choose which tools are present with `tools`, and arrange the toolbar with `toolbar`, as groups of tool ids; `toolbar={[]}` hides it and keeps the shortcuts. An unknown id throws when the editor renders, so a typo never leaves a tool silently missing. `icons` replaces any icon by name with your own component.
|
|
48
65
|
|
|
@@ -53,7 +70,13 @@ Choose which tools are present with `tools`, and arrange the toolbar with `toolb
|
|
|
53
70
|
/>
|
|
54
71
|
```
|
|
55
72
|
|
|
56
|
-
Shortcuts work only while focus is inside the editor, never on the rest of your page, and never while typing in a field. The toolbar is one tab stop, with arrow keys between its buttons; each button names its shortcut in `aria-keyshortcuts`. Undoing, redoing and
|
|
73
|
+
Shortcuts work only while focus is inside the editor, never on the rest of your page, and never while typing in a field. The toolbar is one tab stop, with arrow keys between its buttons; each button names its shortcut in `aria-keyshortcuts`. A button that can't run is disabled with `aria-disabled`, so it keeps focus. Undoing, redoing, rotating and deleting are announced to screen readers.
|
|
74
|
+
|
|
75
|
+
Inserting puts every page of the chosen PDF after the current page, selects the inserted pages and shows the first. The file policy's limits apply to the combined document: `maxPages` counts the pages after the insert, and `maxSessionSize` counts every document held. A failed insert leaves the document unchanged and shows why in the header. When undo steps had to be dropped to make room within `maxSessionSize`, the header says so.
|
|
76
|
+
|
|
77
|
+
Moving gathers pages that aren't next to each other into one block, in their order, and moves the block one position. The moved pages stay selected, and focus stays on them. The keys were chosen so they don't clash with browser or system shortcuts; ADR 0008 records the check.
|
|
78
|
+
|
|
79
|
+
Deleting and moving work on the thumbnails' selection, so their keys work only while focus is in the thumbnails ([ADR 0008](docs/adr/0008-page-organisation-in-the-editor.md)). The page that takes the first deleted page's place is selected, and focus moves to it if its thumbnail had focus. Undo and redo bring back the selection and the current page with the pages. `PdfThumbnails` used on its own takes `onDelete` and `onMove` props for those keys.
|
|
57
80
|
|
|
58
81
|
## Saving a project
|
|
59
82
|
|
|
@@ -98,15 +121,17 @@ The browser and end-to-end tests also need Docker. They run in the pinned browse
|
|
|
98
121
|
|
|
99
122
|
| Step | Script | Tool |
|
|
100
123
|
|---|---|---|
|
|
101
|
-
| Format and lint | `lint` | Biome |
|
|
124
|
+
| Format and lint | `lint` | Biome, then `tools/check-hidden-unicode.ts`, which fails on bidirectional formatting and zero-width characters in tracked files outside `test/fixtures`; write them as escapes |
|
|
102
125
|
| CSS rules | `lint:css` | stylelint, with the `hm-` namespace and token rules |
|
|
103
126
|
| Types | `typecheck` | TypeScript |
|
|
104
127
|
| Dependency rules | `lint:deps` | dependency-cruiser, through `hm-lint-deps` |
|
|
128
|
+
| Playwright pinned to the browser test image | `check:playwright-image` | `hm-check-playwright-image` (sdk-core ADR 0025) |
|
|
105
129
|
| Build | `build` | Vite, then api-extractor for the type declarations |
|
|
106
130
|
| Unit tests | `test` | Vitest |
|
|
107
131
|
| Browser tests | `test:browser` | Vitest in Chromium in the browser test image, and in Firefox and WebKit too in CI |
|
|
108
132
|
| Examples | `build:examples` | Production builds of the Next.js and Vite examples, against the built package |
|
|
109
133
|
| End-to-end tests | `test:e2e` | Playwright in the browser test image, against the examples: server rendering and hydration, axe, no foreign requests, and both asset modes under the Content Security Policies above |
|
|
134
|
+
| Visual regression | `test:visual` | `hm-test-visual`: screenshots of the editor's states in [`e2e/visual`](e2e/visual), on Chromium in the browser test image, in light and dark, compact and comfortable (sdk-core ADR 0048). `pnpm test:visual:update` rewrites the baselines |
|
|
110
135
|
| Size budgets | `check:size` | size-limit, brotli size of each entry point |
|
|
111
136
|
| API reports | `check:api` | api-extractor, one report per entry point in [`api`](api), and `hm-check-api-reports` across them |
|
|
112
137
|
| Package checks | `check:package` | publint and Are the Types Wrong? |
|
|
@@ -54,4 +54,4 @@ end\
|
|
|
54
54
|
endstream
|
|
55
55
|
endobj
|
|
56
56
|
`))}finish(e){let t=this.offsets.size+1,n=this.length,r=`xref\n0 ${t}\n0000000000 65535 f \n`,i=[...this.offsets.entries()].sort(([e],[t])=>e-t);for(let[,e]of i)r+=`${String(e).padStart(10,`0`)} 00000 n \n`;r+=`trailer\n<< /Size ${t} /Root ${e} 0 R >>\nstartxref\n${n}\n%%EOF\n`,this.push(ev(r));let a=new Uint8Array(this.length),o=0;for(let e of this.chunks)a.set(e,o),o+=e.length;return a}push(e){this.chunks.push(e),this.length+=e.length}}})),iv=/* @__PURE__ */ c({PdfError:()=>Y_,PdfPasswordError:()=>X_,PdfToolkit:()=>mv,createPdfToolkit:()=>av,imagesToPdf:()=>Q_});function av(e={}){return mv.create(e)}function ov(e){return typeof e==`object`&&e&&`data`in e?e:{data:e}}function sv(e){return e.replace(/[^\w.-]/g,`_`)||`attachment`}function cv(e){return Number.parseInt(e.replace(/^part-/,``),10)}function lv(e){return`--password=${e}`}function uv(e){return typeof e==`number`?String(e):typeof e==`string`?e:e.map(String).join(`,`)}function dv(e){let{userPassword:t,ownerPassword:n=t,keyLength:r=256,permissions:i={}}=e,a=[];r===40&&a.push(`--allow-weak-crypto`),a.push(`--encrypt`,`--user-password=${t}`,`--owner-password=${n}`,`--bits=${r}`),r===128&&a.push(`--use-aes=y`);let{print:o,modify:s,extract:c,accessibility:l}=i;return r===40?(o!==void 0&&a.push(`--print=${o===`none`?`n`:`y`}`),s!==void 0&&a.push(`--modify=${s===`none`?`n`:`y`}`),c!==void 0&&a.push(`--extract=${c?`y`:`n`}`)):(o!==void 0&&a.push(`--print=${o}`),s!==void 0&&a.push(`--modify=${s}`),c!==void 0&&a.push(`--extract=${c?`y`:`n`}`),l!==void 0&&a.push(`--accessibility=${l?`y`:`n`}`)),a.push(`--`),a}function fv(e){if(e.exitCode!==0&&e.exitCode!==3)throw pv(e)}function pv(e){let t=e.stderr.trim(),n=t.split(`
|
|
57
|
-
`).at(-1)??`qpdf failed with exit code ${e.exitCode}`;return/invalid password|password.*(required|incorrect)/i.test(t)?new X_(n,e.exitCode,t):new Y_(n,e.exitCode,t)}var mv,hv=o((()=>{J_(),Z_(),rv(),mv=class e{runner;constructor(e){this.runner=e}static async create(t={}){return new e(await G_.create(t))}unlock(e,t){return this.transform(e,[lv(t.password),`--decrypt`])}removePassword(e,t){return this.unlock(e,t)}lock(e,t){return this.transform(e,dv(t))}changePassword(e,t){let n={userPassword:t.newPassword,ownerPassword:t.newOwnerPassword??t.newPassword,...t.keyLength!==void 0&&{keyLength:t.keyLength},...t.permissions!==void 0&&{permissions:t.permissions}};return this.transform(e,[lv(t.currentPassword),...dv(n)])}async merge(e){if(e.length===0)throw TypeError(`merge() needs at least one source document`);let t=e.map(ov);return this.runner.run(t.map(e=>e.data),({dir:e,inputPaths:n,exec:r,fs:i})=>{let a=[`--empty`,`--pages`];t.forEach((e,t)=>{a.push(n[t]),e.password!==void 0&&a.push(`--password=${e.password}`),a.push(e.pages===void 0?`1-z`:uv(e.pages))});let o=`${e}/out.pdf`;return a.push(`--`,o),fv(r(a)),i.readFile(o)})}async split(e,t={}){let n=t.pagesPerFile??1;if(!Number.isInteger(n)||n<1)throw TypeError(`pagesPerFile must be a positive integer, got ${n}`);return this.runner.run([e],({dir:e,inputPaths:r,exec:i,fs:a})=>{let o=[];return t.password!==void 0&&o.push(lv(t.password)),o.push(`--split-pages=${n}`,r[0],`${e}/part-%d.pdf`),fv(i(o)),a.readdir(e).filter(e=>e.startsWith(`part-`)).sort((e,t)=>cv(e)-cv(t)).map(t=>a.readFile(`${e}/${t}`))})}extractPages(e,t){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--pages`,`.`,uv(t.pages),`--`),this.transform(e,n)}async rotate(e,t){let{angle:n,absolute:r=!1,pages:i,password:a}=t;if(r&&n<0)throw TypeError(`absolute rotation must use a non-negative angle (90, 180, or 270)`);let o=`${r?``:n<0?`-`:`+`}${Math.abs(n)}${i===void 0?``:`:${uv(i)}`}`,s=[];return a!==void 0&&s.push(lv(a)),s.push(`--rotate=${o}`),this.transform(e,s)}async pageCount(e,t={}){return this.runner.run([e],({inputPaths:e,exec:n})=>{let r=[];t.password!==void 0&&r.push(lv(t.password)),r.push(`--show-npages`,e[0]);let i=n(r);return fv(i),Number.parseInt(i.stdoutText.trim(),10)})}async isEncrypted(e){return this.runner.run([e],({inputPaths:e,exec:t})=>{let n=t([`--is-encrypted`,e[0]]);if(n.exitCode===0)return!0;if(n.exitCode===2)return!1;throw pv(n)})}async requiresPassword(e){return this.runner.run([e],({inputPaths:e,exec:t})=>{let n=t([`--requires-password`,e[0]]);if(n.exitCode===0)return!0;if(n.exitCode===2||n.exitCode===3)return!1;throw pv(n)})}compress(e,t={}){let{password:n,compressionLevel:r=9,objectStreams:i=!0,linearize:a=!1}=t;if(!Number.isInteger(r)||r<1||r>9)throw TypeError(`compressionLevel must be 1-9, got ${r}`);let o=[];return n!==void 0&&o.push(lv(n)),o.push(`--compress-streams=y`,`--recompress-flate`,`--compression-level=${r}`,`--object-streams=${i?`generate`:`preserve`}`),a&&o.push(`--linearize`),this.transform(e,o)}linearize(e,t={}){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--linearize`),this.transform(e,n)}repair(e,t={}){let n=[];return t.password!==void 0&&n.push(lv(t.password)),this.transform(e,n)}async watermark(e,t,n={}){let{mode:r=`overlay`,password:i,stampPassword:a,to:o,from:s,repeat:c}=n;return this.runner.run([e,t],({dir:e,inputPaths:t,exec:n,fs:l})=>{let u=[];i!==void 0&&u.push(lv(i)),u.push(`--${r}`,t[1]),a!==void 0&&u.push(`--password=${a}`),o!==void 0&&u.push(`--to=${uv(o)}`),s!==void 0&&u.push(`--from=${uv(s)}`),c!==void 0&&u.push(`--repeat=${uv(c)}`);let d=`${e}/out.pdf`;return u.push(`--`,t[0],d),fv(n(u)),l.readFile(d)})}deletePages(e,t){let n={pages:`1-z,${uv(t.pages).split(`,`).map(e=>`x${e}`).join(`,`)}`,...t.password!==void 0&&{password:t.password}};return this.extractPages(e,n)}reversePages(e,t={}){return this.extractPages(e,{pages:`z-1`,...t})}async collate(e,t={}){let n=t.groupSize??1;if(!Number.isInteger(n)||n<1)throw TypeError(`groupSize must be a positive integer, got ${n}`);if(e.length<2)throw TypeError(`collate() needs at least two source documents`);let r=e.map(ov);return this.runner.run(r.map(e=>e.data),({dir:e,inputPaths:t,exec:i,fs:a})=>{let o=[`--empty`,`--collate=${n}`,`--pages`];r.forEach((e,n)=>{o.push(t[n]),e.password!==void 0&&o.push(`--password=${e.password}`),o.push(e.pages===void 0?`1-z`:uv(e.pages))});let s=`${e}/out.pdf`;return o.push(`--`,s),fv(i(o)),a.readFile(s)})}flatten(e,t={}){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--generate-appearances`,`--flatten-annotations=${t.annotations??`all`}`),this.transform(e,n)}async addAttachment(e,t){let{data:n,name:r,mimeType:i,description:a,password:o}=t;return this.runner.run([e],async({dir:e,inputPaths:t,exec:s,fs:c})=>{let l=`${e}/${sv(r)}`;c.writeFile(l,await W_(n));let u=[];o!==void 0&&u.push(lv(o)),u.push(`--add-attachment`,l,`--key=${r}`,`--filename=${r}`),i!==void 0&&u.push(`--mimetype=${i}`),a!==void 0&&u.push(`--description=${a}`);let d=`${e}/out.pdf`;return u.push(`--`,t[0],d),fv(s(u)),c.readFile(d)})}removeAttachment(e,t){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--remove-attachment=${t.name}`),this.transform(e,n)}async getAttachment(e,t){return this.runner.run([e],({inputPaths:e,exec:n})=>{let r=[];t.password!==void 0&&r.push(lv(t.password)),r.push(`--show-attachment=${t.name}`,e[0]);let i=n(r);return fv(i),i.stdout})}async listAttachments(e,t={}){return(await this.getInfo(e,t)).attachments}async getInfo(e,t={}){return this.runner.run([e],({inputPaths:e,exec:n,fs:r})=>{let i=n([...t.password===void 0?[]:[lv(t.password)],`--json`,`--json-key=encrypt`,`--json-key=attachments`,`--json-key=pages`,e[0]]);fv(i);let a=JSON.parse(i.stdoutText),o=new TextDecoder(`latin1`).decode(r.readFile(e[0]).slice(0,1024)),s=/%PDF-(\d+\.\d+)/.exec(o)?.[1]??`unknown`,c=Object.entries(a.attachments??{}).map(([e,t])=>({name:e,...t.preferredname!==void 0&&{filename:t.preferredname},...t.description!==void 0&&{description:t.description}})),l=a.encrypt,u={pdfVersion:s,pageCount:a.pages?.length??0,encrypted:l?.encrypted??!1,attachments:c};if(l?.encrypted){let e=l.capabilities??{};u.encryption={bits:l.parameters?.bits??0,method:l.parameters?.method??`unknown`,userPasswordMatched:l.userpasswordmatched??!1,ownerPasswordMatched:l.ownerpasswordmatched??!1,permissions:{accessibility:e.accessibility??!1,extract:e.extract??!1,print:e.printhigh??e.printlow??!1,modify:e.modify??!1,annotate:e.modifyannotations??!1,fillForms:e.modifyforms??!1,assemble:e.modifyassembly??!1}}}return u})}async raw(e,t){return this.runner.run(e,({dir:e,inputPaths:n,exec:r,fs:i})=>{let a=`${e}/out.pdf`;return fv(r(t.map(e=>e.replace(/\$out/g,a).replace(/\$in(\d+)/g,(e,t)=>{let r=n[Number(t)];if(r===void 0)throw TypeError(`no input for placeholder $in${t}`);return r})))),i.readFile(a)})}async transform(e,t){return this.runner.run([e],({dir:e,inputPaths:n,exec:r,fs:i})=>{let a=`${e}/out.pdf`;return fv(r([...t,n[0],a])),i.readFile(a)})}}})),gv;function _v(e){return gv??=(async()=>{let[{createPdfToolkit:t},n]=await Promise.all([Promise.resolve().then(()=>(hv(),iv)),e()]);return t({wasmModule:await WebAssembly.compile(n)})})(),gv.catch(()=>{gv=void 0}),gv}function vv(e){de({async build(t,n){try{return{ok:!0,bytes:await F_(t,{toolkit:()=>_v(e),signal:n.signal,progress:e=>n.progress(e)})}}catch(e){if(e instanceof TypeError||e instanceof RangeError)return{ok:!1,error:e.name,message:e.message};throw e}}},{packageVersion:`0.
|
|
57
|
+
`).at(-1)??`qpdf failed with exit code ${e.exitCode}`;return/invalid password|password.*(required|incorrect)/i.test(t)?new X_(n,e.exitCode,t):new Y_(n,e.exitCode,t)}var mv,hv=o((()=>{J_(),Z_(),rv(),mv=class e{runner;constructor(e){this.runner=e}static async create(t={}){return new e(await G_.create(t))}unlock(e,t){return this.transform(e,[lv(t.password),`--decrypt`])}removePassword(e,t){return this.unlock(e,t)}lock(e,t){return this.transform(e,dv(t))}changePassword(e,t){let n={userPassword:t.newPassword,ownerPassword:t.newOwnerPassword??t.newPassword,...t.keyLength!==void 0&&{keyLength:t.keyLength},...t.permissions!==void 0&&{permissions:t.permissions}};return this.transform(e,[lv(t.currentPassword),...dv(n)])}async merge(e){if(e.length===0)throw TypeError(`merge() needs at least one source document`);let t=e.map(ov);return this.runner.run(t.map(e=>e.data),({dir:e,inputPaths:n,exec:r,fs:i})=>{let a=[`--empty`,`--pages`];t.forEach((e,t)=>{a.push(n[t]),e.password!==void 0&&a.push(`--password=${e.password}`),a.push(e.pages===void 0?`1-z`:uv(e.pages))});let o=`${e}/out.pdf`;return a.push(`--`,o),fv(r(a)),i.readFile(o)})}async split(e,t={}){let n=t.pagesPerFile??1;if(!Number.isInteger(n)||n<1)throw TypeError(`pagesPerFile must be a positive integer, got ${n}`);return this.runner.run([e],({dir:e,inputPaths:r,exec:i,fs:a})=>{let o=[];return t.password!==void 0&&o.push(lv(t.password)),o.push(`--split-pages=${n}`,r[0],`${e}/part-%d.pdf`),fv(i(o)),a.readdir(e).filter(e=>e.startsWith(`part-`)).sort((e,t)=>cv(e)-cv(t)).map(t=>a.readFile(`${e}/${t}`))})}extractPages(e,t){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--pages`,`.`,uv(t.pages),`--`),this.transform(e,n)}async rotate(e,t){let{angle:n,absolute:r=!1,pages:i,password:a}=t;if(r&&n<0)throw TypeError(`absolute rotation must use a non-negative angle (90, 180, or 270)`);let o=`${r?``:n<0?`-`:`+`}${Math.abs(n)}${i===void 0?``:`:${uv(i)}`}`,s=[];return a!==void 0&&s.push(lv(a)),s.push(`--rotate=${o}`),this.transform(e,s)}async pageCount(e,t={}){return this.runner.run([e],({inputPaths:e,exec:n})=>{let r=[];t.password!==void 0&&r.push(lv(t.password)),r.push(`--show-npages`,e[0]);let i=n(r);return fv(i),Number.parseInt(i.stdoutText.trim(),10)})}async isEncrypted(e){return this.runner.run([e],({inputPaths:e,exec:t})=>{let n=t([`--is-encrypted`,e[0]]);if(n.exitCode===0)return!0;if(n.exitCode===2)return!1;throw pv(n)})}async requiresPassword(e){return this.runner.run([e],({inputPaths:e,exec:t})=>{let n=t([`--requires-password`,e[0]]);if(n.exitCode===0)return!0;if(n.exitCode===2||n.exitCode===3)return!1;throw pv(n)})}compress(e,t={}){let{password:n,compressionLevel:r=9,objectStreams:i=!0,linearize:a=!1}=t;if(!Number.isInteger(r)||r<1||r>9)throw TypeError(`compressionLevel must be 1-9, got ${r}`);let o=[];return n!==void 0&&o.push(lv(n)),o.push(`--compress-streams=y`,`--recompress-flate`,`--compression-level=${r}`,`--object-streams=${i?`generate`:`preserve`}`),a&&o.push(`--linearize`),this.transform(e,o)}linearize(e,t={}){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--linearize`),this.transform(e,n)}repair(e,t={}){let n=[];return t.password!==void 0&&n.push(lv(t.password)),this.transform(e,n)}async watermark(e,t,n={}){let{mode:r=`overlay`,password:i,stampPassword:a,to:o,from:s,repeat:c}=n;return this.runner.run([e,t],({dir:e,inputPaths:t,exec:n,fs:l})=>{let u=[];i!==void 0&&u.push(lv(i)),u.push(`--${r}`,t[1]),a!==void 0&&u.push(`--password=${a}`),o!==void 0&&u.push(`--to=${uv(o)}`),s!==void 0&&u.push(`--from=${uv(s)}`),c!==void 0&&u.push(`--repeat=${uv(c)}`);let d=`${e}/out.pdf`;return u.push(`--`,t[0],d),fv(n(u)),l.readFile(d)})}deletePages(e,t){let n={pages:`1-z,${uv(t.pages).split(`,`).map(e=>`x${e}`).join(`,`)}`,...t.password!==void 0&&{password:t.password}};return this.extractPages(e,n)}reversePages(e,t={}){return this.extractPages(e,{pages:`z-1`,...t})}async collate(e,t={}){let n=t.groupSize??1;if(!Number.isInteger(n)||n<1)throw TypeError(`groupSize must be a positive integer, got ${n}`);if(e.length<2)throw TypeError(`collate() needs at least two source documents`);let r=e.map(ov);return this.runner.run(r.map(e=>e.data),({dir:e,inputPaths:t,exec:i,fs:a})=>{let o=[`--empty`,`--collate=${n}`,`--pages`];r.forEach((e,n)=>{o.push(t[n]),e.password!==void 0&&o.push(`--password=${e.password}`),o.push(e.pages===void 0?`1-z`:uv(e.pages))});let s=`${e}/out.pdf`;return o.push(`--`,s),fv(i(o)),a.readFile(s)})}flatten(e,t={}){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--generate-appearances`,`--flatten-annotations=${t.annotations??`all`}`),this.transform(e,n)}async addAttachment(e,t){let{data:n,name:r,mimeType:i,description:a,password:o}=t;return this.runner.run([e],async({dir:e,inputPaths:t,exec:s,fs:c})=>{let l=`${e}/${sv(r)}`;c.writeFile(l,await W_(n));let u=[];o!==void 0&&u.push(lv(o)),u.push(`--add-attachment`,l,`--key=${r}`,`--filename=${r}`),i!==void 0&&u.push(`--mimetype=${i}`),a!==void 0&&u.push(`--description=${a}`);let d=`${e}/out.pdf`;return u.push(`--`,t[0],d),fv(s(u)),c.readFile(d)})}removeAttachment(e,t){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--remove-attachment=${t.name}`),this.transform(e,n)}async getAttachment(e,t){return this.runner.run([e],({inputPaths:e,exec:n})=>{let r=[];t.password!==void 0&&r.push(lv(t.password)),r.push(`--show-attachment=${t.name}`,e[0]);let i=n(r);return fv(i),i.stdout})}async listAttachments(e,t={}){return(await this.getInfo(e,t)).attachments}async getInfo(e,t={}){return this.runner.run([e],({inputPaths:e,exec:n,fs:r})=>{let i=n([...t.password===void 0?[]:[lv(t.password)],`--json`,`--json-key=encrypt`,`--json-key=attachments`,`--json-key=pages`,e[0]]);fv(i);let a=JSON.parse(i.stdoutText),o=new TextDecoder(`latin1`).decode(r.readFile(e[0]).slice(0,1024)),s=/%PDF-(\d+\.\d+)/.exec(o)?.[1]??`unknown`,c=Object.entries(a.attachments??{}).map(([e,t])=>({name:e,...t.preferredname!==void 0&&{filename:t.preferredname},...t.description!==void 0&&{description:t.description}})),l=a.encrypt,u={pdfVersion:s,pageCount:a.pages?.length??0,encrypted:l?.encrypted??!1,attachments:c};if(l?.encrypted){let e=l.capabilities??{};u.encryption={bits:l.parameters?.bits??0,method:l.parameters?.method??`unknown`,userPasswordMatched:l.userpasswordmatched??!1,ownerPasswordMatched:l.ownerpasswordmatched??!1,permissions:{accessibility:e.accessibility??!1,extract:e.extract??!1,print:e.printhigh??e.printlow??!1,modify:e.modify??!1,annotate:e.modifyannotations??!1,fillForms:e.modifyforms??!1,assemble:e.modifyassembly??!1}}}return u})}async raw(e,t){return this.runner.run(e,({dir:e,inputPaths:n,exec:r,fs:i})=>{let a=`${e}/out.pdf`;return fv(r(t.map(e=>e.replace(/\$out/g,a).replace(/\$in(\d+)/g,(e,t)=>{let r=n[Number(t)];if(r===void 0)throw TypeError(`no input for placeholder $in${t}`);return r})))),i.readFile(a)})}async transform(e,t){return this.runner.run([e],({dir:e,inputPaths:n,exec:r,fs:i})=>{let a=`${e}/out.pdf`;return fv(r([...t,n[0],a])),i.readFile(a)})}}})),gv;function _v(e){return gv??=(async()=>{let[{createPdfToolkit:t},n]=await Promise.all([Promise.resolve().then(()=>(hv(),iv)),e()]);return t({wasmModule:await WebAssembly.compile(n)})})(),gv.catch(()=>{gv=void 0}),gv}function vv(e){de({async build(t,n){try{return{ok:!0,bytes:await F_(t,{toolkit:()=>_v(e),signal:n.signal,progress:e=>n.progress(e)})}}catch(e){if(e instanceof TypeError||e instanceof RangeError)return{ok:!1,error:e.name,message:e.message};throw e}}},{packageVersion:`0.4.1`})}async function yv(){let e=new URL(`qpdf.wasm`,self.location.href),t=await fetch(e);if(!t.ok)throw new T_(`WORKER_START_FAILED`,`qpdf.wasm couldn't be loaded from ${e}.`,{details:{asset:`qpdf.wasm`,status:t.status}});let n=new Uint8Array(await t.arrayBuffer()),r=[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,n))].map(e=>e.toString(16).padStart(2,`0`)).join(``);if(r!==`48a6044e2b5abb32295fa1682e26f20338181bb2423b2ab6e8456b7c4a8c9756`)throw new T_(`WORKER_START_FAILED`,`qpdf.wasm doesn't match this version of the SDK. Copy dist/assets again after upgrading.`,{details:{asset:`qpdf.wasm`,expected:d,actual:r}});return n}vv(yv);
|
package/dist/index.d.ts
CHANGED
|
@@ -696,7 +696,7 @@ export declare interface PdfImageCompression {
|
|
|
696
696
|
*
|
|
697
697
|
* @public
|
|
698
698
|
*/
|
|
699
|
-
export declare interface PdfInsertOptions extends
|
|
699
|
+
export declare interface PdfInsertOptions extends PdfOpenOptions {
|
|
700
700
|
/** The position of the first inserted page. Defaults to the end. */
|
|
701
701
|
readonly at?: number;
|
|
702
702
|
/** Zero-based indexes of the pages to insert. Defaults to every page. */
|
|
@@ -855,10 +855,14 @@ export declare interface PdfLink {
|
|
|
855
855
|
export declare type PdfMessageCatalogue = typeof pdfMessages;
|
|
856
856
|
|
|
857
857
|
/**
|
|
858
|
-
* The PDF SDK's English message catalogue
|
|
859
|
-
* every {@link PdfErrorCode} and every
|
|
860
|
-
* `createMessages` from `@hussmartinez/sdk-core`,
|
|
861
|
-
* overrides.
|
|
858
|
+
* The PDF SDK's English message catalogue for the server-safe entry:
|
|
859
|
+
* sdk-core's messages, and text for every {@link PdfErrorCode} and every
|
|
860
|
+
* limit's warning. Pass it to `createMessages` from `@hussmartinez/sdk-core`,
|
|
861
|
+
* with the host's locale and overrides.
|
|
862
|
+
*
|
|
863
|
+
* It holds no interface text: the editor's, the viewer's and the
|
|
864
|
+
* thumbnails' text is in `pdfEditorMessages`, from the React entry
|
|
865
|
+
* (docs/adr/0010).
|
|
862
866
|
*
|
|
863
867
|
* Error text is looked up by code, with the error's `details` as
|
|
864
868
|
* parameters, and never taken from `error.message` (ADR 0019).
|
|
@@ -890,46 +894,6 @@ export declare const pdfMessages: {
|
|
|
890
894
|
};
|
|
891
895
|
readonly "warnings.maxSessionSize": "The open documents use {actual, fileSize}. Clearing the undo history frees memory.";
|
|
892
896
|
readonly "warnings.maxImagePixels": "Some images are very large and may be slow to show.";
|
|
893
|
-
readonly "viewer.label": "Document";
|
|
894
|
-
readonly "viewer.empty": "No document is open.";
|
|
895
|
-
readonly "viewer.page": "Page {page} of {count}";
|
|
896
|
-
readonly "viewer.webLink": "Link to {destination}, opens in a new tab";
|
|
897
|
-
readonly "viewer.emailLink": "Email {destination}";
|
|
898
|
-
readonly "thumbnails.label": "Pages";
|
|
899
|
-
readonly "thumbnails.page": "Page {page} of {count}";
|
|
900
|
-
readonly "thumbnails.number": "{page}";
|
|
901
|
-
readonly "editor.label": "PDF editor";
|
|
902
|
-
readonly "editor.start.title": "Open a PDF to get started";
|
|
903
|
-
readonly "editor.start.retryTitle": "Try another PDF";
|
|
904
|
-
readonly "editor.start.choose": "Choose a PDF";
|
|
905
|
-
readonly "editor.start.retry": "Choose another PDF";
|
|
906
|
-
readonly "editor.start.hint": "Or drop one here. Your file stays on this device and is never uploaded.";
|
|
907
|
-
readonly "editor.opening": "Opening the PDF…";
|
|
908
|
-
readonly "editor.opened": {
|
|
909
|
-
readonly $plural: "count";
|
|
910
|
-
} & {
|
|
911
|
-
readonly one: "Opened a PDF with {count} page.";
|
|
912
|
-
readonly other: "Opened a PDF with {count} pages.";
|
|
913
|
-
};
|
|
914
|
-
readonly "editor.closed": "The PDF was closed.";
|
|
915
|
-
readonly "editor.undone": "Undone.";
|
|
916
|
-
readonly "editor.redone": "Redone.";
|
|
917
|
-
readonly "editor.rotated": {
|
|
918
|
-
readonly $plural: "count";
|
|
919
|
-
} & {
|
|
920
|
-
readonly one: "Rotated {count} page.";
|
|
921
|
-
readonly other: "Rotated {count} pages.";
|
|
922
|
-
};
|
|
923
|
-
readonly "toolbar.label": "PDF tools";
|
|
924
|
-
readonly "toolbar.groups.file": "File";
|
|
925
|
-
readonly "toolbar.groups.history": "History";
|
|
926
|
-
readonly "toolbar.groups.pages": "Pages";
|
|
927
|
-
readonly "toolbar.groups.other": "More tools";
|
|
928
|
-
readonly "tools.open": "Open a PDF";
|
|
929
|
-
readonly "tools.undo": "Undo";
|
|
930
|
-
readonly "tools.redo": "Redo";
|
|
931
|
-
readonly "tools.rotate-left": "Rotate left";
|
|
932
|
-
readonly "tools.rotate-right": "Rotate right";
|
|
933
897
|
readonly "errors.UNKNOWN": "Something went wrong. Please try again.";
|
|
934
898
|
readonly "errors.ABORTED": "The operation was cancelled.";
|
|
935
899
|
readonly "errors.TIMEOUT": "The operation took too long and was stopped.";
|
|
@@ -990,6 +954,19 @@ export declare interface PdfMovePagesCommand {
|
|
|
990
954
|
readonly to: number;
|
|
991
955
|
}
|
|
992
956
|
|
|
957
|
+
/**
|
|
958
|
+
* Options for {@link PdfSession.open}.
|
|
959
|
+
*
|
|
960
|
+
* @public
|
|
961
|
+
*/
|
|
962
|
+
export declare interface PdfOpenOptions extends PdfCallOptions {
|
|
963
|
+
/**
|
|
964
|
+
* The file's name, for bytes or a `Blob` that isn't a `File`. It wins over
|
|
965
|
+
* `File.name`, and is cleaned before it's kept (docs/adr/0009).
|
|
966
|
+
*/
|
|
967
|
+
readonly name?: string;
|
|
968
|
+
}
|
|
969
|
+
|
|
993
970
|
/**
|
|
994
971
|
* Facts about one page of a source document.
|
|
995
972
|
*
|
|
@@ -1246,7 +1223,7 @@ export declare interface PdfSession {
|
|
|
1246
1223
|
* Rejects with a `PdfError`, which the snapshot also holds; the current
|
|
1247
1224
|
* document, if any, stays open.
|
|
1248
1225
|
*/
|
|
1249
|
-
open(file: Blob | PdfBytes, options?:
|
|
1226
|
+
open(file: Blob | PdfBytes, options?: PdfOpenOptions): Promise<void>;
|
|
1250
1227
|
/**
|
|
1251
1228
|
* Inserts the pages of another document, as one undoable step. If the
|
|
1252
1229
|
* documents held would then exceed `maxSessionSize`, the session first
|
|
@@ -1379,7 +1356,9 @@ export declare interface PdfSessionSnapshot {
|
|
|
1379
1356
|
readonly historyTrimmed: boolean;
|
|
1380
1357
|
/**
|
|
1381
1358
|
* The keys of the selected pages, in plan order. Tools act on them, such as
|
|
1382
|
-
* rotating the selection. View state: not
|
|
1359
|
+
* rotating the selection. View state: not part of the plan and never in
|
|
1360
|
+
* events, but undo and redo bring back the selection and current page
|
|
1361
|
+
* that went with each step (docs/adr/0008).
|
|
1383
1362
|
*/
|
|
1384
1363
|
readonly selection: readonly string[];
|
|
1385
1364
|
/** The key of the page the user is looking at, if a document is open. */
|
|
@@ -1432,6 +1411,13 @@ export declare interface PdfSourceInfo {
|
|
|
1432
1411
|
readonly pageCount: number;
|
|
1433
1412
|
/** The size of its bytes. */
|
|
1434
1413
|
readonly byteLength: number;
|
|
1414
|
+
/**
|
|
1415
|
+
* The file's name, from `File.name` or the `name` option, cleaned as
|
|
1416
|
+
* docs/adr/0009 describes: one path segment, without control or
|
|
1417
|
+
* bidirectional formatting characters, at most 128 code points. Absent
|
|
1418
|
+
* when there was none. Show it only as text; it never reaches `onEvent`.
|
|
1419
|
+
*/
|
|
1420
|
+
readonly name?: string;
|
|
1435
1421
|
}
|
|
1436
1422
|
|
|
1437
1423
|
/**
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as
|
|
1
|
+
import { C as pdfLimits, S as pdfLimitDefinitions, T as isPdfError, _ as createPdfJsEngine, a as checkAnnotation, b as safeLinkUrl, c as invalid, d as PDF_MAX_ID_LENGTH, f as PDF_MAX_STROKE_POINTS, g as createPdfProcessor, h as longerThan, i as Invalid, l as isRecord, m as PDF_POSITION_GRID, n as createPdfSession, o as checkId, p as PDF_MAX_TEXT_LENGTH, s as fields, t as pdfMessages, u as PDF_MAX_FIELD_NAME_LENGTH, v as PDF_MAX_CANVAS_PIXELS, w as PdfError, x as addRotation, y as linkDestination } from "./shared/en-DiJkcy2X.js";
|
|
2
2
|
// src/core/format/plan-document.ts
|
|
3
3
|
var PDF_PLAN_FORMAT = "hm-pdf-plan";
|
|
4
4
|
var PDF_PLAN_VERSION = 1;
|