@mecorelabs/free-pdf-sdk 0.0.0-stage → 0.2.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.
Files changed (48) hide show
  1. package/LICENSE-APACHE +177 -0
  2. package/LICENSE-MIT +21 -0
  3. package/NOTICE +46 -0
  4. package/README.md +104 -2
  5. package/bin/free-pdf-sdk.mjs +39 -0
  6. package/dist/controller.d.ts +47 -0
  7. package/dist/controller.js +170 -0
  8. package/dist/controller.js.map +1 -0
  9. package/dist/element.d.ts +66 -0
  10. package/dist/element.js +199 -0
  11. package/dist/element.js.map +1 -0
  12. package/dist/free-pdf-sdk.d.ts +353 -0
  13. package/dist/free-pdf-sdk.js +565 -0
  14. package/dist/free-pdf-sdk.js.map +1 -0
  15. package/dist/react.d.ts +47 -0
  16. package/dist/react.js +63 -0
  17. package/dist/react.js.map +1 -0
  18. package/dist/svelte.d.ts +35 -0
  19. package/dist/svelte.js +49 -0
  20. package/dist/svelte.js.map +1 -0
  21. package/dist/vue.d.ts +136 -0
  22. package/dist/vue.js +90 -0
  23. package/dist/vue.js.map +1 -0
  24. package/package.json +94 -4
  25. package/third-party/README.md +34 -0
  26. package/third-party/adobe-cmaps/LICENSE.txt +28 -0
  27. package/third-party/crates.md +415 -0
  28. package/third-party/egui-default-fonts/Hack-Regular.txt +31 -0
  29. package/third-party/egui-default-fonts/OFL.txt +92 -0
  30. package/third-party/egui-default-fonts/UFL.txt +96 -0
  31. package/third-party/egui-default-fonts/emoji-icon-font-mit-license.txt +9 -0
  32. package/third-party/fonts/OFL-DancingScript.txt +93 -0
  33. package/third-party/fonts/OFL-Inter.txt +92 -0
  34. package/third-party/fonts/OFL-JetBrainsMono.txt +93 -0
  35. package/third-party/foxit/LICENSE_FOXIT +27 -0
  36. package/third-party/hayro/LICENSE-APACHE +177 -0
  37. package/third-party/hayro/LICENSE-MIT +7 -0
  38. package/third-party/icc/CGATS_LICENSE.txt +116 -0
  39. package/third-party/lopdf/LICENSE +21 -0
  40. package/third-party/lucide/LICENSE-lucide.txt +43 -0
  41. package/third-party/pdfcraft/ATTRIBUTION.md +335 -0
  42. package/third-party/pdfcraft/LICENSE-APACHE +177 -0
  43. package/third-party/pdfcraft/LICENSE-MIT +21 -0
  44. package/third-party/pdfcraft/NOTICE +60 -0
  45. package/version.json +4 -0
  46. package/viewer/fps-viewer-2048cf2709_bg.wasm +4 -0
  47. package/viewer/fps-viewer-a2ad2665f7.js +3528 -0
  48. package/viewer/index.html +23 -0
package/LICENSE-APACHE ADDED
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 the Free PDF SDK contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,46 @@
1
+ Free PDF SDK
2
+ Copyright (c) 2026 the Free PDF SDK contributors.
3
+ Licensed under the MIT License or the Apache License, Version 2.0, at your option
4
+ (LICENSE-MIT, LICENSE-APACHE).
5
+
6
+ Based on pdfcraft
7
+ -----------------
8
+ Free PDF SDK is based on pdfcraft by the ArtCraft Team and the PdfCraft contributors
9
+ (https://github.com/storytold/pdfcraft), used as a Cargo dependency pinned to commit
10
+
11
+ 88dad98dd478d255399b1405b33765f4da542704 (pdfcraft 0.11.0)
12
+
13
+ with Free PDF SDK modifications to pdfcraft's interface crate (pdfcraft-ui-egui): opt-in hooks
14
+ for white-label branding and for hiding features. The exact modified commit is in Cargo.lock
15
+ and in version.json as "pdfcraftRev".
16
+
17
+ pdfcraft is Copyright (c) 2026 ArtCraft Team and the PdfCraft contributors, licensed under
18
+ the MIT License or the Apache License, Version 2.0. Its licence files, NOTICE and
19
+ ATTRIBUTION.md are in third-party/pdfcraft/.
20
+
21
+ Trademarks
22
+ ----------
23
+ "ArtCraft", "PdfCraft" and the ArtCraft logos are trademarks of the ArtCraft Team. Free PDF SDK
24
+ does not use them as its name or logo, does not display them, and is not endorsed by the
25
+ ArtCraft Team. The ArtCraft logos are not compiled into the viewer (pdfcraft-ui-egui is built
26
+ without its `artcraft-marks` feature); the names remain only inside pdfcraft's unused message
27
+ strings and translations. The placeholder logos in brand/ are original to this project.
28
+
29
+ Third-party material
30
+ --------------------
31
+ The viewer embeds third-party material under its own licences: Lucide icons (ISC); the Inter,
32
+ JetBrains Mono and Dancing Script typefaces (SIL OFL 1.1); egui's default fonts (Ubuntu Font
33
+ Licence 1.0, MIT / Bitstream Vera, SIL OFL 1.1, MIT); the Foxit standard-14 substitute fonts and
34
+ Adobe CMap resources (BSD-3-Clause); a CC0 ICC profile; and the Rust crates listed in
35
+ third-party/crates.md. Licences and required notices are in third-party/ (see its README.md).
36
+
37
+ Foxit standard-14 substitute fonts:
38
+ Copyright 2014 PDFium Authors. All rights reserved. Original code copyright 2014 Foxit
39
+ Software Inc. Redistributed under the BSD-3-Clause licence (third-party/foxit/LICENSE_FOXIT).
40
+
41
+ CMap resources (character-mapping data bundled by hayro-cmap):
42
+ Copyright 1990-2023 Adobe. All rights reserved. Redistributed under the BSD-3-Clause licence
43
+ (third-party/adobe-cmaps/LICENSE.txt). Neither the name of Adobe nor the names of its
44
+ contributors are used to endorse or promote this product.
45
+
46
+ The brand/ placeholder wordmarks contain outlines of the Inter typeface (SIL OFL 1.1).
package/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ # Free PDF SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Show your users exactly what they need. Hide the rest.**
4
+
5
+ A free, open-source, white-label PDF viewer, annotator and editor for the web. Your users switch
6
+ PDF layers on and off with a click. You switch panels, tools and whole features on or off, and
7
+ every menu, toolbar and shortcut follows. It runs in the browser (WebAssembly), so documents never
8
+ leave your page.
9
+
10
+ [Website](https://freepdfsdk.mecorelabs.com/) · [Live demo](https://freepdfsdk.mecorelabs.com/demo/) ·
11
+ [Get started](https://freepdfsdk.mecorelabs.com/docs/getting-started/) ·
12
+ [Docs](https://freepdfsdk.mecorelabs.com/docs/) · [GitHub](https://github.com/GeorgeMilroy/free-pdf-sdk)
13
+
14
+ ![The viewer in annotate mode on a floor plan, with the Layers panel open and the Furniture layer hidden](https://freepdfsdk.mecorelabs.com/assets/img/viewer-layers.png)
15
+
16
+ - **8 modes**, from read-only to full authoring, and **31 feature switches**. What's off is gone
17
+ from every menu, toolbar, right-click menu and shortcut, not greyed out.
18
+ - **PDF layers**: show or hide structure, furniture, electrical, dimensions... in one click.
19
+ Printing follows what is shown; the file is untouched.
20
+ - **Comments & review**: notes, callouts, highlights, shapes, ink and stamps, with replies and
21
+ review status. Standard XFDF in and out.
22
+ - **Measurement**, **Forms, Fill & Sign**, **page organization**, **redaction**, **signature
23
+ validation**, export to Word, images and HTML, PDF/A, accessibility checker, search and print.
24
+ - **Private by design**: an iframe on your own origin, no server, no uploads, no tracking.
25
+ AES-256 encrypted files open in place; an owner password lifts their restrictions.
26
+ - **23 languages**, light, dark and system themes.
27
+ - **React, Vue, Svelte, Angular** (Web Component) and plain JavaScript. Fully typed.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ npm install @mecorelabs/free-pdf-sdk
33
+ npx @mecorelabs/free-pdf-sdk copy-viewer public/free-pdf-sdk
34
+ ```
35
+
36
+ The second command copies the viewer files into a folder your site serves. The viewer must be
37
+ served from the same origin as your page. Run it again after upgrading, or add it as a
38
+ `postinstall` script: `"postinstall": "free-pdf-sdk copy-viewer public/free-pdf-sdk"`.
39
+
40
+ ## Use
41
+
42
+ ```ts
43
+ import { FreePdf } from "@mecorelabs/free-pdf-sdk";
44
+
45
+ const viewer = await FreePdf.init(document.getElementById("viewer")!, {
46
+ baseUrl: "/free-pdf-sdk/",
47
+ mode: "annotate",
48
+ features: { stamps: false, measurement: false },
49
+ author: "Ada Lovelace",
50
+ document: { url: "/files/plan.pdf" },
51
+ });
52
+
53
+ viewer.on("annotationsChanged", ({ count }) => console.log(count, "comments"));
54
+ const xfdf = await viewer.exportXfdf(); // store it anywhere; importXfdf() brings it back
55
+ ```
56
+
57
+ Give the element a height. Modes: `view`, `review`, `annotate`, `fill`, `sign`, `organize`,
58
+ `edit`, `full`.
59
+
60
+ ### Frameworks
61
+
62
+ ```tsx
63
+ // React
64
+ import { FreePdfViewer } from "@mecorelabs/free-pdf-sdk/react";
65
+ <FreePdfViewer baseUrl="/free-pdf-sdk/" mode="annotate" document={{ url: "/files/plan.pdf" }} style={{ height: "80vh" }} />
66
+ ```
67
+
68
+ ```vue
69
+ <!-- Vue -->
70
+ <script setup lang="ts">
71
+ import { FreePdfViewer } from "@mecorelabs/free-pdf-sdk/vue";
72
+ </script>
73
+ <template>
74
+ <FreePdfViewer base-url="/free-pdf-sdk/" mode="annotate" :document="{ url: '/files/plan.pdf' }" style="height: 80vh" />
75
+ </template>
76
+ ```
77
+
78
+ ```html
79
+ <!-- Web Component: Angular and everything else -->
80
+ <script type="module">
81
+ import { defineFreePdfViewer } from "@mecorelabs/free-pdf-sdk/element";
82
+ defineFreePdfViewer();
83
+ </script>
84
+ <free-pdf-viewer base-url="/free-pdf-sdk/" src="/files/plan.pdf" mode="view" style="height: 80vh"></free-pdf-viewer>
85
+ ```
86
+
87
+ Svelte: `import { freePdf } from "@mecorelabs/free-pdf-sdk/svelte"` (an action).
88
+
89
+ ## Documentation
90
+
91
+ Guides for every framework, the full API reference and recipes:
92
+ **[freepdfsdk.mecorelabs.com/docs](https://freepdfsdk.mecorelabs.com/docs/)**. For AI coding assistants,
93
+ every page is also Markdown, indexed in [/llms.txt](https://freepdfsdk.mecorelabs.com/llms.txt), with a
94
+ [JSON Schema](https://freepdfsdk.mecorelabs.com/schema/viewer-options.schema.json) of the options.
95
+
96
+ ## Support the project
97
+
98
+ Free PDF SDK is open source and free. Donations pay for bringing in each new engine release,
99
+ testing new browsers, fixing bugs and keeping the docs current:
100
+ [Donate on Ko-fi](https://ko-fi.com/K4V228W28L).
101
+
102
+ ## Licence
103
+
104
+ MIT OR Apache-2.0. Built on [pdfcraft](https://github.com/storytold/pdfcraft) by the ArtCraft
105
+ Team; see `NOTICE` and `third-party/` in the package.
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ // Free PDF SDK command line: copies the viewer files (viewer/, version.json and the licences)
3
+ // from this package into a folder your web server serves, such as public/free-pdf-sdk.
4
+ //
5
+ // npx @mecorelabs/free-pdf-sdk copy-viewer public/free-pdf-sdk
6
+ //
7
+ // Run it after every install or upgrade (for example in a "postinstall" or "prebuild" script),
8
+ // so the viewer always matches the wrapper version.
9
+
10
+ import { cpSync, existsSync, mkdirSync, rmSync } from "node:fs";
11
+ import { dirname, join, resolve } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+
14
+ const pkg = resolve(dirname(fileURLToPath(import.meta.url)), "..");
15
+ const [command, target] = process.argv.slice(2);
16
+
17
+ function usage(code) {
18
+ console.log("Usage: free-pdf-sdk copy-viewer <folder>\n\nCopies the viewer files into <folder>; then use that folder's URL as baseUrl.");
19
+ process.exit(code);
20
+ }
21
+
22
+ if (command === "--help" || command === "-h") usage(0);
23
+ if (command !== "copy-viewer" || !target) usage(1);
24
+
25
+ const source = join(pkg, "viewer");
26
+ if (!existsSync(source)) {
27
+ console.error(`free-pdf-sdk: ${source} is missing; reinstall the package`);
28
+ process.exit(1);
29
+ }
30
+ const dest = resolve(process.cwd(), target);
31
+ mkdirSync(dest, { recursive: true });
32
+ // A new version has new hashed file names: start clean so old ones don't pile up.
33
+ rmSync(join(dest, "viewer"), { recursive: true, force: true });
34
+ cpSync(source, join(dest, "viewer"), { recursive: true });
35
+ for (const file of ["version.json", "NOTICE", "LICENSE-MIT", "LICENSE-APACHE"]) {
36
+ if (existsSync(join(pkg, file))) cpSync(join(pkg, file), join(dest, file));
37
+ }
38
+ if (existsSync(join(pkg, "third-party"))) cpSync(join(pkg, "third-party"), join(dest, "third-party"), { recursive: true });
39
+ console.log(`free-pdf-sdk: copied the viewer to ${dest}`);
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The shared engine of the framework adapters: mounts a viewer in a container, turns later
3
+ * option changes into the matching API calls (in order), and tears it down. The Web Component,
4
+ * React, Vue and Svelte integrations are thin layers over it.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ import { type EventMap, type EventName, type FreePdfViewer, type InitOptions } from "./free-pdf-sdk.js";
9
+ /** The DOM event name for each SDK event (`<free-pdf-viewer>` and the Svelte action). */
10
+ export declare const ELEMENT_EVENTS: Record<EventName, string>;
11
+ /** Every event name, for adapters that forward them all. */
12
+ export declare const EVENT_NAMES: readonly EventName[];
13
+ /** What a controller mounts: the {@link InitOptions} without `listeners`. */
14
+ export type ViewerOptions = Omit<InitOptions, "listeners">;
15
+ /** Receives every event of the viewer. */
16
+ export type EventSink = <K extends EventName>(name: K, data: EventMap[K]) => void;
17
+ /** A viewer whose options can change after it mounted. */
18
+ export declare class FreePdfController {
19
+ private readonly container;
20
+ private readonly sink;
21
+ private viewer;
22
+ private options;
23
+ private queue;
24
+ private generation;
25
+ private destroyed;
26
+ /** The iframe of a mount still starting, removed at once if it is abandoned. */
27
+ private starting;
28
+ /** Resolves with the viewer once it is ready and its first document has loaded or failed to (a failure is a `documentError` event). */
29
+ ready: Promise<FreePdfViewer>;
30
+ /**
31
+ * @param container - The element the viewer fills; give it a size.
32
+ * @param options - Initial options.
33
+ * @param sink - Called with every event.
34
+ */
35
+ constructor(container: HTMLElement, options: ViewerOptions, sink: EventSink);
36
+ /** The mounted viewer, once ready. */
37
+ get current(): FreePdfViewer | null;
38
+ private mount;
39
+ /**
40
+ * Applies new options: what changed becomes API calls (`setMode`, `setFeatures`, `setUi`,
41
+ * `setTheme`, `setAuthor`, `setLocale`, `setDisabledElements`, `load`); a new `baseUrl`
42
+ * mounts a new viewer. Failures are reported as `error` events.
43
+ */
44
+ update(next: ViewerOptions): void;
45
+ /** Removes the viewer. Safe to call twice. */
46
+ destroy(): Promise<void>;
47
+ }
@@ -0,0 +1,170 @@
1
+ /**
2
+ * The shared engine of the framework adapters: mounts a viewer in a container, turns later
3
+ * option changes into the matching API calls (in order), and tears it down. The Web Component,
4
+ * React, Vue and Svelte integrations are thin layers over it.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ import { FreePdfError, init, } from "./free-pdf-sdk.js";
9
+ /** The DOM event name for each SDK event (`<free-pdf-viewer>` and the Svelte action). */
10
+ export const ELEMENT_EVENTS = {
11
+ ready: "fps-ready",
12
+ documentLoaded: "fps-document-loaded",
13
+ documentError: "fps-document-error",
14
+ annotationsChanged: "fps-annotations-changed",
15
+ dirtyChanged: "fps-dirty-changed",
16
+ error: "fps-error",
17
+ saveRequested: "fps-save-requested",
18
+ };
19
+ /** Every event name, for adapters that forward them all. */
20
+ export const EVENT_NAMES = ["ready", "documentLoaded", "documentError", "annotationsChanged", "dirtyChanged", "error", "saveRequested"];
21
+ const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
22
+ function sameDocument(a, b) {
23
+ if (!a || !b)
24
+ return a === b;
25
+ if ("url" in a && "url" in b)
26
+ return a.url === b.url && a.name === b.name;
27
+ if ("data" in a && "data" in b)
28
+ return a.data === b.data && a.name === b.name;
29
+ return false;
30
+ }
31
+ /** A viewer whose options can change after it mounted. */
32
+ export class FreePdfController {
33
+ /**
34
+ * @param container - The element the viewer fills; give it a size.
35
+ * @param options - Initial options.
36
+ * @param sink - Called with every event.
37
+ */
38
+ constructor(container, options, sink) {
39
+ this.container = container;
40
+ this.sink = sink;
41
+ this.viewer = null;
42
+ this.queue = Promise.resolve();
43
+ this.generation = 0;
44
+ this.destroyed = false;
45
+ /** The iframe of a mount still starting, removed at once if it is abandoned. */
46
+ this.starting = null;
47
+ this.options = options;
48
+ this.ready = this.mount();
49
+ }
50
+ /** The mounted viewer, once ready. */
51
+ get current() {
52
+ return this.viewer;
53
+ }
54
+ mount() {
55
+ const generation = ++this.generation;
56
+ const listeners = {};
57
+ for (const name of EVENT_NAMES) {
58
+ listeners[name] = (data) => {
59
+ if (generation === this.generation && !this.destroyed)
60
+ this.sink(name, data);
61
+ };
62
+ }
63
+ // The viewer starts without the document: a document that fails to open must not take the
64
+ // viewer with it (init would remove it), so later options can still load another one.
65
+ const { document: doc, password, ...config } = this.options;
66
+ const started = init(this.container, { ...config, listeners });
67
+ // init appends its iframe synchronously; remember it so an abandoned start can remove it.
68
+ this.starting = this.container.lastElementChild;
69
+ return started.then(async (viewer) => {
70
+ this.starting = null;
71
+ if (generation !== this.generation || this.destroyed) {
72
+ await viewer.destroy();
73
+ throw new FreePdfError("DESTROYED", "the viewer was replaced before it was ready");
74
+ }
75
+ this.viewer = viewer;
76
+ if (doc) {
77
+ // The viewer reports a failure itself (documentError); ready still resolves.
78
+ await viewer.load(doc, password === undefined ? undefined : { password }).catch(() => undefined);
79
+ }
80
+ return viewer;
81
+ }, (e) => {
82
+ this.starting = null;
83
+ const err = e instanceof FreePdfError ? e : new FreePdfError("INTERNAL", String(e));
84
+ if (generation === this.generation && !this.destroyed && err.code !== "DESTROYED")
85
+ this.sink("error", { code: err.code, message: err.message });
86
+ throw err;
87
+ });
88
+ }
89
+ /**
90
+ * Applies new options: what changed becomes API calls (`setMode`, `setFeatures`, `setUi`,
91
+ * `setTheme`, `setAuthor`, `setLocale`, `setDisabledElements`, `load`); a new `baseUrl`
92
+ * mounts a new viewer. Failures are reported as `error` events.
93
+ */
94
+ update(next) {
95
+ const prev = this.options;
96
+ this.options = next;
97
+ if (this.destroyed)
98
+ return;
99
+ if (next.baseUrl !== prev.baseUrl) {
100
+ const old = this.viewer;
101
+ this.viewer = null;
102
+ this.queue = Promise.resolve();
103
+ this.starting?.remove();
104
+ this.starting = null;
105
+ void old?.destroy();
106
+ this.ready = this.mount();
107
+ this.ready.catch(() => undefined);
108
+ return;
109
+ }
110
+ const calls = [];
111
+ if (next.mode !== undefined && next.mode !== prev.mode)
112
+ calls.push((v) => v.setMode(next.mode ?? "view"));
113
+ if (!same(next.features, prev.features))
114
+ calls.push((v) => v.setFeatures(next.features ?? {}));
115
+ if (!same(next.ui, prev.ui) && next.ui)
116
+ calls.push((v) => v.setUi(next.ui ?? {}));
117
+ if (!same(next.disabledElements, prev.disabledElements))
118
+ calls.push((v) => v.setDisabledElements(next.disabledElements ?? []));
119
+ if (next.theme !== undefined && next.theme !== prev.theme)
120
+ calls.push((v) => v.setTheme(next.theme ?? "system"));
121
+ if (next.author !== undefined && next.author !== prev.author)
122
+ calls.push((v) => v.setAuthor(next.author ?? ""));
123
+ if (next.locale !== undefined && next.locale !== prev.locale)
124
+ calls.push((v) => v.setLocale(next.locale ?? "en"));
125
+ if (next.document && !sameDocument(next.document, prev.document)) {
126
+ const doc = next.document;
127
+ calls.push((v) => v.load(doc, next.password === undefined ? undefined : { password: next.password }));
128
+ }
129
+ if (calls.length === 0)
130
+ return;
131
+ const generation = this.generation;
132
+ this.queue = this.queue
133
+ .then(() => this.ready)
134
+ .then(async (v) => {
135
+ // Each call on its own: one refused call (a bad locale) must not drop the rest (the load).
136
+ for (const call of calls) {
137
+ if (generation !== this.generation || this.destroyed)
138
+ return;
139
+ try {
140
+ await call(v);
141
+ }
142
+ catch (e) {
143
+ if (generation !== this.generation || this.destroyed)
144
+ return;
145
+ const err = e instanceof FreePdfError ? e : new FreePdfError("INTERNAL", String(e));
146
+ if (err.code !== "DESTROYED")
147
+ this.sink("error", { code: err.code, message: err.message });
148
+ }
149
+ }
150
+ })
151
+ .catch(() => undefined);
152
+ }
153
+ /** Removes the viewer. Safe to call twice. */
154
+ async destroy() {
155
+ if (this.destroyed)
156
+ return;
157
+ this.destroyed = true;
158
+ this.generation++;
159
+ const v = this.viewer;
160
+ this.viewer = null;
161
+ // A start still under way: take its iframe away now (it is destroyed when init settles).
162
+ this.starting?.remove();
163
+ this.starting = null;
164
+ if (v)
165
+ await v.destroy();
166
+ else
167
+ await this.ready.then((late) => late.destroy()).catch(() => undefined);
168
+ }
169
+ }
170
+ //# sourceMappingURL=controller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"controller.js","sourceRoot":"","sources":["../src/controller.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAOL,YAAY,EACZ,IAAI,GACL,MAAM,mBAAmB,CAAC;AAE3B,yFAAyF;AACzF,MAAM,CAAC,MAAM,cAAc,GAA8B;IACvD,KAAK,EAAE,WAAW;IAClB,cAAc,EAAE,qBAAqB;IACrC,aAAa,EAAE,oBAAoB;IACnC,kBAAkB,EAAE,yBAAyB;IAC7C,YAAY,EAAE,mBAAmB;IACjC,KAAK,EAAE,WAAW;IAClB,aAAa,EAAE,oBAAoB;CACpC,CAAC;AAEF,4DAA4D;AAC5D,MAAM,CAAC,MAAM,WAAW,GAAyB,CAAC,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,oBAAoB,EAAE,cAAc,EAAE,OAAO,EAAE,eAAe,CAAC,CAAC;AAQ9J,MAAM,IAAI,GAAG,CAAC,CAAU,EAAE,CAAU,EAAW,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC;AAE1G,SAAS,YAAY,CAAC,CAA6B,EAAE,CAA6B;IAChF,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC;QAAE,OAAO,CAAC,KAAK,CAAC,CAAC;IAC7B,IAAI,KAAK,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC;QAAE,OAAO,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,IAAI,CAAC;IAC1E,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,IAAI,CAAC;QAAE,OAAO,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,IA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CAAC;aACD,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAC5B,CAAC;IAED,8CAA8C;IAC9C,KAAK,CAAC,OAAO;QACX,IAAI,IAAI,CAAC,SAAS;YAAE,OAAO;QAC3B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,UAAU,EAAE,CAAC;QAClB,MAAM,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;QACtB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,yFAAyF;QACzF,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,CAAC;QACxB,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,IAAI,CAAC;YAAE,MAAM,CAAC,CAAC,OAAO,EAAE,CAAC;;YACpB,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAC9E,CAAC;CACF","sourcesContent":["/**\n * The shared engine of the framework adapters: mounts a viewer in a container, turns later\n * option changes into the matching API calls (in order), and tears it down. The Web Component,\n * React, Vue and Svelte integrations are thin layers over it.\n *\n * @packageDocumentation\n */\n\nimport {\n type DocumentSource,\n type EventMap,\n type EventName,\n type FreePdfViewer,\n type InitOptions,\n type Listener,\n FreePdfError,\n init,\n} from \"./free-pdf-sdk.js\";\n\n/** The DOM event name for each SDK event (`<free-pdf-viewer>` and the Svelte action). */\nexport const ELEMENT_EVENTS: Record<EventName, string> = {\n ready: \"fps-ready\",\n documentLoaded: \"fps-document-loaded\",\n documentError: \"fps-document-error\",\n annotationsChanged: \"fps-annotations-changed\",\n dirtyChanged: \"fps-dirty-changed\",\n error: \"fps-error\",\n saveRequested: \"fps-save-requested\",\n};\n\n/** Every event name, for adapters that forward them all. */\nexport const EVENT_NAMES: readonly EventName[] = [\"ready\", \"documentLoaded\", \"documentError\", \"annotationsChanged\", \"dirtyChanged\", \"error\", \"saveRequested\"];\n\n/** What a controller mounts: the {@link InitOptions} without `listeners`. */\nexport type ViewerOptions = Omit<InitOptions, \"listeners\">;\n\n/** Receives every event of the viewer. */\nexport type EventSink = <K extends EventName>(name: K, data: EventMap[K]) => void;\n\nconst same = (a: unknown, b: unknown): boolean => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);\n\nfunction sameDocument(a: DocumentSource | undefined, b: DocumentSource | undefined): boolean {\n if (!a || !b) return a === b;\n if (\"url\" in a && \"url\" in b) return a.url === b.url && a.name === b.name;\n if (\"data\" in a && \"data\" in b) return a.data === b.data && a.name === b.name;\n return false;\n}\n\n/** A viewer whose options can change after it mounted. */\nexport class FreePdfController {\n private viewer: FreePdfViewer | null = null;\n private options: ViewerOptions;\n private queue: Promise<unknown> = Promise.resolve();\n private generation = 0;\n private destroyed = false;\n /** The iframe of a mount still starting, removed at once if it is abandoned. */\n private starting: Element | null = null;\n /** Resolves with the viewer once it is ready and its first document has loaded or failed to (a failure is a `documentError` event). */\n ready: Promise<FreePdfViewer>;\n\n /**\n * @param container - The element the viewer fills; give it a size.\n * @param options - Initial options.\n * @param sink - Called with every event.\n */\n constructor(\n private readonly container: HTMLElement,\n options: ViewerOptions,\n private readonly sink: EventSink,\n ) {\n this.options = options;\n this.ready = this.mount();\n }\n\n /** The mounted viewer, once ready. */\n get current(): FreePdfViewer | null {\n return this.viewer;\n }\n\n private mount(): Promise<FreePdfViewer> {\n const generation = ++this.generation;\n const listeners: { [K in EventName]?: Listener<K> } = {};\n for (const name of EVENT_NAMES) {\n (listeners as Record<EventName, Listener<EventName>>)[name] = (data) => {\n if (generation === this.generation && !this.destroyed) this.sink(name, data);\n };\n }\n // The viewer starts without the document: a document that fails to open must not take the\n // viewer with it (init would remove it), so later options can still load another one.\n const { document: doc, password, ...config } = this.options;\n const started = init(this.container, { ...config, listeners });\n // init appends its iframe synchronously; remember it so an abandoned start can remove it.\n this.starting = this.container.lastElementChild;\n return started.then(\n async (viewer) => {\n this.starting = null;\n if (generation !== this.generation || this.destroyed) {\n await viewer.destroy();\n throw new FreePdfError(\"DESTROYED\", \"the viewer was replaced before it was ready\");\n }\n this.viewer = viewer;\n if (doc) {\n // The viewer reports a failure itself (documentError); ready still resolves.\n await viewer.load(doc, password === undefined ? undefined : { password }).catch(() => undefined);\n }\n return viewer;\n },\n (e: unknown) => {\n this.starting = null;\n const err = e instanceof FreePdfError ? e : new FreePdfError(\"INTERNAL\", String(e));\n if (generation === this.generation && !this.destroyed && err.code !== \"DESTROYED\") this.sink(\"error\", { code: err.code, message: err.message });\n throw err;\n },\n );\n }\n\n /**\n * Applies new options: what changed becomes API calls (`setMode`, `setFeatures`, `setUi`,\n * `setTheme`, `setAuthor`, `setLocale`, `setDisabledElements`, `load`); a new `baseUrl`\n * mounts a new viewer. Failures are reported as `error` events.\n */\n update(next: ViewerOptions): void {\n const prev = this.options;\n this.options = next;\n if (this.destroyed) return;\n if (next.baseUrl !== prev.baseUrl) {\n const old = this.viewer;\n this.viewer = null;\n this.queue = Promise.resolve();\n this.starting?.remove();\n this.starting = null;\n void old?.destroy();\n this.ready = this.mount();\n this.ready.catch(() => undefined);\n return;\n }\n const calls: Array<(v: FreePdfViewer) => Promise<unknown>> = [];\n if (next.mode !== undefined && next.mode !== prev.mode) calls.push((v) => v.setMode(next.mode ?? \"view\"));\n if (!same(next.features, prev.features)) calls.push((v) => v.setFeatures(next.features ?? {}));\n if (!same(next.ui, prev.ui) && next.ui) calls.push((v) => v.setUi(next.ui ?? {}));\n if (!same(next.disabledElements, prev.disabledElements)) calls.push((v) => v.setDisabledElements(next.disabledElements ?? []));\n if (next.theme !== undefined && next.theme !== prev.theme) calls.push((v) => v.setTheme(next.theme ?? \"system\"));\n if (next.author !== undefined && next.author !== prev.author) calls.push((v) => v.setAuthor(next.author ?? \"\"));\n if (next.locale !== undefined && next.locale !== prev.locale) calls.push((v) => v.setLocale(next.locale ?? \"en\"));\n if (next.document && !sameDocument(next.document, prev.document)) {\n const doc = next.document;\n calls.push((v) => v.load(doc, next.password === undefined ? undefined : { password: next.password }));\n }\n if (calls.length === 0) return;\n const generation = this.generation;\n this.queue = this.queue\n .then(() => this.ready)\n .then(async (v) => {\n // Each call on its own: one refused call (a bad locale) must not drop the rest (the load).\n for (const call of calls) {\n if (generation !== this.generation || this.destroyed) return;\n try {\n await call(v);\n } catch (e) {\n if (generation !== this.generation || this.destroyed) return;\n const err = e instanceof FreePdfError ? e : new FreePdfError(\"INTERNAL\", String(e));\n if (err.code !== \"DESTROYED\") this.sink(\"error\", { code: err.code, message: err.message });\n }\n }\n })\n .catch(() => undefined);\n }\n\n /** Removes the viewer. Safe to call twice. */\n async destroy(): Promise<void> {\n if (this.destroyed) return;\n this.destroyed = true;\n this.generation++;\n const v = this.viewer;\n this.viewer = null;\n // A start still under way: take its iframe away now (it is destroyed when init settles).\n this.starting?.remove();\n this.starting = null;\n if (v) await v.destroy();\n else await this.ready.then((late) => late.destroy()).catch(() => undefined);\n }\n}\n"]}