@chialab/pdfjs-lib 1.0.0-alpha.35 → 1.0.0-alpha.37

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.
@@ -1,2085 +0,0 @@
1
- import {
2
- BaseException,
3
- FeatureTest,
4
- Util,
5
- shadow,
6
- stringToBytes,
7
- unreachable,
8
- updateUrlHash,
9
- warn
10
- } from "./chunk-T2JWSGAF.js";
11
- import {
12
- __privateAdd,
13
- __privateGet,
14
- __privateMethod,
15
- __privateSet,
16
- __privateWrapper,
17
- __publicField
18
- } from "./chunk-ZFIGV5OT.js";
19
-
20
- // src/lib/NodeUtils.ts
21
- import {
22
- DOMMatrix as NodeDOMMatrix,
23
- DOMPoint as NodeDOMPoint,
24
- ImageData as NodeImageData,
25
- Path2D as NodePath2D
26
- } from "skia-canvas";
27
-
28
- // src/pdf.js/src/display/xfa_text.js
29
- var XfaText = class _XfaText {
30
- /**
31
- * Walk an XFA tree and create an array of text nodes that is compatible
32
- * with a regular PDFs TextContent. Currently, only TextItem.str is supported,
33
- * all other fields and styles haven't been implemented.
34
- *
35
- * @param {Object} xfa - An XFA fake DOM object.
36
- *
37
- * @returns {TextContent}
38
- */
39
- static textContent(xfa) {
40
- const items = [];
41
- const output = {
42
- items,
43
- styles: /* @__PURE__ */ Object.create(null)
44
- };
45
- function walk(node) {
46
- if (!node) {
47
- return;
48
- }
49
- let str = null;
50
- const name = node.name;
51
- if (name === "#text") {
52
- str = node.value;
53
- } else if (!_XfaText.shouldBuildText(name)) {
54
- return;
55
- } else if (node?.attributes?.textContent) {
56
- str = node.attributes.textContent;
57
- } else if (node.value) {
58
- str = node.value;
59
- }
60
- if (str !== null) {
61
- items.push({
62
- str
63
- });
64
- }
65
- if (!node.children) {
66
- return;
67
- }
68
- for (const child of node.children) {
69
- walk(child);
70
- }
71
- }
72
- walk(xfa);
73
- return output;
74
- }
75
- /**
76
- * @param {string} name - DOM node name. (lower case)
77
- *
78
- * @returns {boolean} true if the DOM node should have a corresponding text
79
- * node.
80
- */
81
- static shouldBuildText(name) {
82
- return !(name === "textarea" || name === "input" || name === "option" || name === "select");
83
- }
84
- };
85
-
86
- // src/pdf.js/src/display/xfa_layer.js
87
- var XfaLayer = class {
88
- static setupStorage(html, id, element, storage, intent) {
89
- const storedData = storage.getValue(id, { value: null });
90
- switch (element.name) {
91
- case "textarea":
92
- if (storedData.value !== null) {
93
- html.textContent = storedData.value;
94
- }
95
- if (intent === "print") {
96
- break;
97
- }
98
- html.addEventListener("input", (event) => {
99
- storage.setValue(id, { value: event.target.value });
100
- });
101
- break;
102
- case "input":
103
- if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
104
- if (storedData.value === element.attributes.xfaOn) {
105
- html.setAttribute("checked", true);
106
- } else if (storedData.value === element.attributes.xfaOff) {
107
- html.removeAttribute("checked");
108
- }
109
- if (intent === "print") {
110
- break;
111
- }
112
- html.addEventListener("change", (event) => {
113
- storage.setValue(id, {
114
- value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
115
- });
116
- });
117
- } else {
118
- if (storedData.value !== null) {
119
- html.setAttribute("value", storedData.value);
120
- }
121
- if (intent === "print") {
122
- break;
123
- }
124
- html.addEventListener("input", (event) => {
125
- storage.setValue(id, { value: event.target.value });
126
- });
127
- }
128
- break;
129
- case "select":
130
- if (storedData.value !== null) {
131
- html.setAttribute("value", storedData.value);
132
- for (const option of element.children) {
133
- if (option.attributes.value === storedData.value) {
134
- option.attributes.selected = true;
135
- } else if (option.attributes.hasOwnProperty("selected")) {
136
- delete option.attributes.selected;
137
- }
138
- }
139
- }
140
- html.addEventListener("input", (event) => {
141
- const options = event.target.options;
142
- const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
143
- storage.setValue(id, { value });
144
- });
145
- break;
146
- }
147
- }
148
- static setAttributes({ html, element, storage = null, intent, linkService }) {
149
- const { attributes } = element;
150
- const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
151
- if (attributes.type === "radio") {
152
- attributes.name = `${attributes.name}-${intent}`;
153
- }
154
- for (const [key, value] of Object.entries(attributes)) {
155
- if (value === null || value === void 0) {
156
- continue;
157
- }
158
- switch (key) {
159
- case "class":
160
- if (value.length) {
161
- html.setAttribute(key, value.join(" "));
162
- }
163
- break;
164
- case "dataId":
165
- break;
166
- case "id":
167
- html.setAttribute("data-element-id", value);
168
- break;
169
- case "style":
170
- Object.assign(html.style, value);
171
- break;
172
- case "textContent":
173
- html.textContent = value;
174
- break;
175
- default:
176
- if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
177
- html.setAttribute(key, value);
178
- }
179
- }
180
- }
181
- if (isHTMLAnchorElement) {
182
- linkService.addLinkAttributes(
183
- html,
184
- attributes.href,
185
- attributes.newWindow
186
- );
187
- }
188
- if (storage && attributes.dataId) {
189
- this.setupStorage(html, attributes.dataId, element, storage);
190
- }
191
- }
192
- /**
193
- * Render the XFA layer.
194
- *
195
- * @param {XfaLayerParameters} parameters
196
- */
197
- static render(parameters) {
198
- const storage = parameters.annotationStorage;
199
- const linkService = parameters.linkService;
200
- const root = parameters.xfaHtml;
201
- const intent = parameters.intent || "display";
202
- const rootHtml = document.createElement(root.name);
203
- if (root.attributes) {
204
- this.setAttributes({
205
- html: rootHtml,
206
- element: root,
207
- intent,
208
- linkService
209
- });
210
- }
211
- const isNotForRichText = intent !== "richText";
212
- const rootDiv = parameters.div;
213
- rootDiv.append(rootHtml);
214
- if (parameters.viewport) {
215
- const transform = `matrix(${parameters.viewport.transform.join(",")})`;
216
- rootDiv.style.transform = transform;
217
- }
218
- if (isNotForRichText) {
219
- rootDiv.setAttribute("class", "xfaLayer xfaFont");
220
- }
221
- const textDivs = [];
222
- if (root.children.length === 0) {
223
- if (root.value) {
224
- const node = document.createTextNode(root.value);
225
- rootHtml.append(node);
226
- if (isNotForRichText && XfaText.shouldBuildText(root.name)) {
227
- textDivs.push(node);
228
- }
229
- }
230
- return { textDivs };
231
- }
232
- const stack = [[root, -1, rootHtml]];
233
- while (stack.length > 0) {
234
- const [parent, i, html] = stack.at(-1);
235
- if (i + 1 === parent.children.length) {
236
- stack.pop();
237
- continue;
238
- }
239
- const child = parent.children[++stack.at(-1)[1]];
240
- if (child === null) {
241
- continue;
242
- }
243
- const { name } = child;
244
- if (name === "#text") {
245
- const node = document.createTextNode(child.value);
246
- textDivs.push(node);
247
- html.append(node);
248
- continue;
249
- }
250
- const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name);
251
- html.append(childHtml);
252
- if (child.attributes) {
253
- this.setAttributes({
254
- html: childHtml,
255
- element: child,
256
- storage,
257
- intent,
258
- linkService
259
- });
260
- }
261
- if (child.children?.length > 0) {
262
- stack.push([child, -1, childHtml]);
263
- } else if (child.value) {
264
- const node = document.createTextNode(child.value);
265
- if (isNotForRichText && XfaText.shouldBuildText(name)) {
266
- textDivs.push(node);
267
- }
268
- childHtml.append(node);
269
- }
270
- }
271
- for (const el of rootDiv.querySelectorAll(
272
- ".xfaNonInteractive input, .xfaNonInteractive textarea"
273
- )) {
274
- el.setAttribute("readOnly", true);
275
- }
276
- return {
277
- textDivs
278
- };
279
- }
280
- /**
281
- * Update the XFA layer.
282
- *
283
- * @param {XfaLayerParameters} parameters
284
- */
285
- static update(parameters) {
286
- const transform = `matrix(${parameters.viewport.transform.join(",")})`;
287
- parameters.div.style.transform = transform;
288
- parameters.div.hidden = false;
289
- }
290
- };
291
-
292
- // src/pdf.js/src/display/display_utils.js
293
- var SVG_NS = "http://www.w3.org/2000/svg";
294
- var _PixelsPerInch = class _PixelsPerInch {
295
- };
296
- __publicField(_PixelsPerInch, "CSS", 96);
297
- __publicField(_PixelsPerInch, "PDF", 72);
298
- __publicField(_PixelsPerInch, "PDF_TO_CSS_UNITS", _PixelsPerInch.CSS / _PixelsPerInch.PDF);
299
- var PixelsPerInch = _PixelsPerInch;
300
- async function fetchData(url, type = "text") {
301
- if (isValidFetchUrl(url, document.baseURI)) {
302
- const response = await fetch(url);
303
- if (!response.ok) {
304
- throw new Error(response.statusText);
305
- }
306
- switch (type) {
307
- case "arraybuffer":
308
- return response.arrayBuffer();
309
- case "blob":
310
- return response.blob();
311
- case "json":
312
- return response.json();
313
- }
314
- return response.text();
315
- }
316
- return new Promise((resolve, reject) => {
317
- const request = new XMLHttpRequest();
318
- request.open(
319
- "GET",
320
- url,
321
- /* async = */
322
- true
323
- );
324
- request.responseType = type;
325
- request.onreadystatechange = () => {
326
- if (request.readyState !== XMLHttpRequest.DONE) {
327
- return;
328
- }
329
- if (request.status === 200 || request.status === 0) {
330
- switch (type) {
331
- case "arraybuffer":
332
- case "blob":
333
- case "json":
334
- resolve(request.response);
335
- return;
336
- }
337
- resolve(request.responseText);
338
- return;
339
- }
340
- reject(new Error(request.statusText));
341
- };
342
- request.send(null);
343
- });
344
- }
345
- var PageViewport = class _PageViewport {
346
- /**
347
- * @param {PageViewportParameters}
348
- */
349
- constructor({
350
- viewBox,
351
- userUnit,
352
- scale,
353
- rotation,
354
- offsetX = 0,
355
- offsetY = 0,
356
- dontFlip = false
357
- }) {
358
- this.viewBox = viewBox;
359
- this.userUnit = userUnit;
360
- this.scale = scale;
361
- this.rotation = rotation;
362
- this.offsetX = offsetX;
363
- this.offsetY = offsetY;
364
- scale *= userUnit;
365
- const centerX = (viewBox[2] + viewBox[0]) / 2;
366
- const centerY = (viewBox[3] + viewBox[1]) / 2;
367
- let rotateA, rotateB, rotateC, rotateD;
368
- rotation %= 360;
369
- if (rotation < 0) {
370
- rotation += 360;
371
- }
372
- switch (rotation) {
373
- case 180:
374
- rotateA = -1;
375
- rotateB = 0;
376
- rotateC = 0;
377
- rotateD = 1;
378
- break;
379
- case 90:
380
- rotateA = 0;
381
- rotateB = 1;
382
- rotateC = 1;
383
- rotateD = 0;
384
- break;
385
- case 270:
386
- rotateA = 0;
387
- rotateB = -1;
388
- rotateC = -1;
389
- rotateD = 0;
390
- break;
391
- case 0:
392
- rotateA = 1;
393
- rotateB = 0;
394
- rotateC = 0;
395
- rotateD = -1;
396
- break;
397
- default:
398
- throw new Error(
399
- "PageViewport: Invalid rotation, must be a multiple of 90 degrees."
400
- );
401
- }
402
- if (dontFlip) {
403
- rotateC = -rotateC;
404
- rotateD = -rotateD;
405
- }
406
- let offsetCanvasX, offsetCanvasY;
407
- let width, height;
408
- if (rotateA === 0) {
409
- offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
410
- offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
411
- width = (viewBox[3] - viewBox[1]) * scale;
412
- height = (viewBox[2] - viewBox[0]) * scale;
413
- } else {
414
- offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
415
- offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
416
- width = (viewBox[2] - viewBox[0]) * scale;
417
- height = (viewBox[3] - viewBox[1]) * scale;
418
- }
419
- this.transform = [
420
- rotateA * scale,
421
- rotateB * scale,
422
- rotateC * scale,
423
- rotateD * scale,
424
- offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
425
- offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
426
- ];
427
- this.width = width;
428
- this.height = height;
429
- }
430
- /**
431
- * The original, un-scaled, viewport dimensions.
432
- * @type {Object}
433
- */
434
- get rawDims() {
435
- const dims = this.viewBox;
436
- return shadow(this, "rawDims", {
437
- pageWidth: dims[2] - dims[0],
438
- pageHeight: dims[3] - dims[1],
439
- pageX: dims[0],
440
- pageY: dims[1]
441
- });
442
- }
443
- /**
444
- * Clones viewport, with optional additional properties.
445
- * @param {PageViewportCloneParameters} [params]
446
- * @returns {PageViewport} Cloned viewport.
447
- */
448
- clone({
449
- scale = this.scale,
450
- rotation = this.rotation,
451
- offsetX = this.offsetX,
452
- offsetY = this.offsetY,
453
- dontFlip = false
454
- } = {}) {
455
- return new _PageViewport({
456
- viewBox: this.viewBox.slice(),
457
- userUnit: this.userUnit,
458
- scale,
459
- rotation,
460
- offsetX,
461
- offsetY,
462
- dontFlip
463
- });
464
- }
465
- /**
466
- * Converts PDF point to the viewport coordinates. For examples, useful for
467
- * converting PDF location into canvas pixel coordinates.
468
- * @param {number} x - The x-coordinate.
469
- * @param {number} y - The y-coordinate.
470
- * @returns {Array} Array containing `x`- and `y`-coordinates of the
471
- * point in the viewport coordinate space.
472
- * @see {@link convertToPdfPoint}
473
- * @see {@link convertToViewportRectangle}
474
- */
475
- convertToViewportPoint(x, y) {
476
- const p = [x, y];
477
- Util.applyTransform(p, this.transform);
478
- return p;
479
- }
480
- /**
481
- * Converts PDF rectangle to the viewport coordinates.
482
- * @param {Array} rect - The xMin, yMin, xMax and yMax coordinates.
483
- * @returns {Array} Array containing corresponding coordinates of the
484
- * rectangle in the viewport coordinate space.
485
- * @see {@link convertToViewportPoint}
486
- */
487
- convertToViewportRectangle(rect) {
488
- const topLeft = [rect[0], rect[1]];
489
- Util.applyTransform(topLeft, this.transform);
490
- const bottomRight = [rect[2], rect[3]];
491
- Util.applyTransform(bottomRight, this.transform);
492
- return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
493
- }
494
- /**
495
- * Converts viewport coordinates to the PDF location. For examples, useful
496
- * for converting canvas pixel location into PDF one.
497
- * @param {number} x - The x-coordinate.
498
- * @param {number} y - The y-coordinate.
499
- * @returns {Array} Array containing `x`- and `y`-coordinates of the
500
- * point in the PDF coordinate space.
501
- * @see {@link convertToViewportPoint}
502
- */
503
- convertToPdfPoint(x, y) {
504
- const p = [x, y];
505
- Util.applyInverseTransform(p, this.transform);
506
- return p;
507
- }
508
- };
509
- var RenderingCancelledException = class extends BaseException {
510
- constructor(msg, extraDelay = 0) {
511
- super(msg, "RenderingCancelledException");
512
- this.extraDelay = extraDelay;
513
- }
514
- };
515
- function isDataScheme(url) {
516
- const ii = url.length;
517
- let i = 0;
518
- while (i < ii && url[i].trim() === "") {
519
- i++;
520
- }
521
- return url.substring(i, i + 5).toLowerCase() === "data:";
522
- }
523
- function isPdfFile(filename) {
524
- return typeof filename === "string" && /\.pdf$/i.test(filename);
525
- }
526
- function getFilenameFromUrl(url) {
527
- [url] = url.split(/[#?]/, 1);
528
- return url.substring(url.lastIndexOf("/") + 1);
529
- }
530
- function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
531
- if (typeof url !== "string") {
532
- return defaultFilename;
533
- }
534
- if (isDataScheme(url)) {
535
- warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
536
- return defaultFilename;
537
- }
538
- const getURL = (urlString) => {
539
- try {
540
- return new URL(urlString);
541
- } catch {
542
- try {
543
- return new URL(decodeURIComponent(urlString));
544
- } catch {
545
- try {
546
- return new URL(urlString, "https://foo.bar");
547
- } catch {
548
- try {
549
- return new URL(decodeURIComponent(urlString), "https://foo.bar");
550
- } catch {
551
- return null;
552
- }
553
- }
554
- }
555
- }
556
- };
557
- const newURL = getURL(url);
558
- if (!newURL) {
559
- return defaultFilename;
560
- }
561
- const decode = (name) => {
562
- try {
563
- let decoded = decodeURIComponent(name);
564
- if (decoded.includes("/")) {
565
- decoded = decoded.split("/").at(-1);
566
- if (decoded.test(/^\.pdf$/i)) {
567
- return decoded;
568
- }
569
- return name;
570
- }
571
- return decoded;
572
- } catch {
573
- return name;
574
- }
575
- };
576
- const pdfRegex = /\.pdf$/i;
577
- const filename = newURL.pathname.split("/").at(-1);
578
- if (pdfRegex.test(filename)) {
579
- return decode(filename);
580
- }
581
- if (newURL.searchParams.size > 0) {
582
- const values = Array.from(newURL.searchParams.values()).reverse();
583
- for (const value of values) {
584
- if (pdfRegex.test(value)) {
585
- return decode(value);
586
- }
587
- }
588
- const keys = Array.from(newURL.searchParams.keys()).reverse();
589
- for (const key of keys) {
590
- if (pdfRegex.test(key)) {
591
- return decode(key);
592
- }
593
- }
594
- }
595
- if (newURL.hash) {
596
- const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
597
- const hashFilename = reFilename.exec(newURL.hash);
598
- if (hashFilename) {
599
- return decode(hashFilename[0]);
600
- }
601
- }
602
- return defaultFilename;
603
- }
604
- var StatTimer = class {
605
- constructor() {
606
- __publicField(this, "started", /* @__PURE__ */ Object.create(null));
607
- __publicField(this, "times", []);
608
- }
609
- time(name) {
610
- if (name in this.started) {
611
- warn(`Timer is already running for ${name}`);
612
- }
613
- this.started[name] = Date.now();
614
- }
615
- timeEnd(name) {
616
- if (!(name in this.started)) {
617
- warn(`Timer has not been started for ${name}`);
618
- }
619
- this.times.push({
620
- name,
621
- start: this.started[name],
622
- end: Date.now()
623
- });
624
- delete this.started[name];
625
- }
626
- toString() {
627
- const outBuf = [];
628
- let longest = 0;
629
- for (const { name } of this.times) {
630
- longest = Math.max(name.length, longest);
631
- }
632
- for (const { name, start, end } of this.times) {
633
- outBuf.push(`${name.padEnd(longest)} ${end - start}ms
634
- `);
635
- }
636
- return outBuf.join("");
637
- }
638
- };
639
- function isValidFetchUrl(url, baseUrl) {
640
- if (false) {
641
- throw new Error("Not implemented: isValidFetchUrl");
642
- }
643
- const res = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url);
644
- return res?.protocol === "http:" || res?.protocol === "https:";
645
- }
646
- function noContextMenu(e) {
647
- e.preventDefault();
648
- }
649
- function stopEvent(e) {
650
- e.preventDefault();
651
- e.stopPropagation();
652
- }
653
- function deprecated(details) {
654
- console.log("Deprecated API usage: " + details);
655
- }
656
- var _regex;
657
- var PDFDateString = class {
658
- /**
659
- * Convert a PDF date string to a JavaScript `Date` object.
660
- *
661
- * The PDF date string format is described in section 7.9.4 of the official
662
- * PDF 32000-1:2008 specification. However, in the PDF 1.7 reference (sixth
663
- * edition) Adobe describes the same format including a trailing apostrophe.
664
- * This syntax in incorrect, but Adobe Acrobat creates PDF files that contain
665
- * them. We ignore all apostrophes as they are not necessary for date parsing.
666
- *
667
- * Moreover, Adobe Acrobat doesn't handle changing the date to universal time
668
- * and doesn't use the user's time zone (effectively ignoring the HH' and mm'
669
- * parts of the date string).
670
- *
671
- * @param {string} input
672
- * @returns {Date|null}
673
- */
674
- static toDateObject(input) {
675
- if (input instanceof Date) {
676
- return input;
677
- }
678
- if (!input || typeof input !== "string") {
679
- return null;
680
- }
681
- __privateGet(this, _regex) || __privateSet(this, _regex, new RegExp(
682
- "^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"
683
- // Trailing apostrophe (optional)
684
- ));
685
- const matches = __privateGet(this, _regex).exec(input);
686
- if (!matches) {
687
- return null;
688
- }
689
- const year = parseInt(matches[1], 10);
690
- let month = parseInt(matches[2], 10);
691
- month = month >= 1 && month <= 12 ? month - 1 : 0;
692
- let day = parseInt(matches[3], 10);
693
- day = day >= 1 && day <= 31 ? day : 1;
694
- let hour = parseInt(matches[4], 10);
695
- hour = hour >= 0 && hour <= 23 ? hour : 0;
696
- let minute = parseInt(matches[5], 10);
697
- minute = minute >= 0 && minute <= 59 ? minute : 0;
698
- let second = parseInt(matches[6], 10);
699
- second = second >= 0 && second <= 59 ? second : 0;
700
- const universalTimeRelation = matches[7] || "Z";
701
- let offsetHour = parseInt(matches[8], 10);
702
- offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
703
- let offsetMinute = parseInt(matches[9], 10) || 0;
704
- offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
705
- if (universalTimeRelation === "-") {
706
- hour += offsetHour;
707
- minute += offsetMinute;
708
- } else if (universalTimeRelation === "+") {
709
- hour -= offsetHour;
710
- minute -= offsetMinute;
711
- }
712
- return new Date(Date.UTC(year, month, day, hour, minute, second));
713
- }
714
- };
715
- _regex = new WeakMap();
716
- __privateAdd(PDFDateString, _regex);
717
- function getXfaPageViewport(xfaPage, { scale = 1, rotation = 0 }) {
718
- const { width, height } = xfaPage.attributes.style;
719
- const viewBox = [0, 0, parseInt(width), parseInt(height)];
720
- return new PageViewport({
721
- viewBox,
722
- userUnit: 1,
723
- scale,
724
- rotation
725
- });
726
- }
727
- function getRGB(color) {
728
- if (color.startsWith("#")) {
729
- const colorRGB = parseInt(color.slice(1), 16);
730
- return [
731
- (colorRGB & 16711680) >> 16,
732
- (colorRGB & 65280) >> 8,
733
- colorRGB & 255
734
- ];
735
- }
736
- if (color.startsWith("rgb(")) {
737
- return color.slice(
738
- /* "rgb(".length */
739
- 4,
740
- -1
741
- ).split(",").map((x) => parseInt(x));
742
- }
743
- if (color.startsWith("rgba(")) {
744
- return color.slice(
745
- /* "rgba(".length */
746
- 5,
747
- -1
748
- ).split(",").map((x) => parseInt(x)).slice(0, 3);
749
- }
750
- warn(`Not a valid color format: "${color}"`);
751
- return [0, 0, 0];
752
- }
753
- function getColorValues(colors) {
754
- const span = document.createElement("span");
755
- span.style.visibility = "hidden";
756
- span.style.colorScheme = "only light";
757
- document.body.append(span);
758
- for (const name of colors.keys()) {
759
- span.style.color = name;
760
- const computedColor = window.getComputedStyle(span).color;
761
- colors.set(name, getRGB(computedColor));
762
- }
763
- span.remove();
764
- }
765
- function getCurrentTransform(ctx) {
766
- const { a, b, c, d, e, f } = ctx.getTransform();
767
- return [a, b, c, d, e, f];
768
- }
769
- function getCurrentTransformInverse(ctx) {
770
- const { a, b, c, d, e, f } = ctx.getTransform().invertSelf();
771
- return [a, b, c, d, e, f];
772
- }
773
- function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
774
- if (viewport instanceof PageViewport) {
775
- const { pageWidth, pageHeight } = viewport.rawDims;
776
- const { style } = div;
777
- const useRound = FeatureTest.isCSSRoundSupported;
778
- const w = `var(--total-scale-factor) * ${pageWidth}px`, h = `var(--total-scale-factor) * ${pageHeight}px`;
779
- const widthStr = useRound ? `round(down, ${w}, var(--scale-round-x))` : `calc(${w})`, heightStr = useRound ? `round(down, ${h}, var(--scale-round-y))` : `calc(${h})`;
780
- if (!mustFlip || viewport.rotation % 180 === 0) {
781
- style.width = widthStr;
782
- style.height = heightStr;
783
- } else {
784
- style.width = heightStr;
785
- style.height = widthStr;
786
- }
787
- }
788
- if (mustRotate) {
789
- div.setAttribute("data-main-rotation", viewport.rotation);
790
- }
791
- }
792
- var OutputScale = class _OutputScale {
793
- constructor() {
794
- const { pixelRatio } = _OutputScale;
795
- this.sx = pixelRatio;
796
- this.sy = pixelRatio;
797
- }
798
- /**
799
- * @type {boolean} Returns `true` when scaling is required, `false` otherwise.
800
- */
801
- get scaled() {
802
- return this.sx !== 1 || this.sy !== 1;
803
- }
804
- /**
805
- * @type {boolean} Returns `true` when scaling is symmetric,
806
- * `false` otherwise.
807
- */
808
- get symmetric() {
809
- return this.sx === this.sy;
810
- }
811
- /**
812
- * @returns {boolean} Returns `true` if scaling was limited,
813
- * `false` otherwise.
814
- */
815
- limitCanvas(width, height, maxPixels, maxDim, capAreaFactor = -1) {
816
- let maxAreaScale = Infinity, maxWidthScale = Infinity, maxHeightScale = Infinity;
817
- maxPixels = _OutputScale.capPixels(maxPixels, capAreaFactor);
818
- if (maxPixels > 0) {
819
- maxAreaScale = Math.sqrt(maxPixels / (width * height));
820
- }
821
- if (maxDim !== -1) {
822
- maxWidthScale = maxDim / width;
823
- maxHeightScale = maxDim / height;
824
- }
825
- const maxScale = Math.min(maxAreaScale, maxWidthScale, maxHeightScale);
826
- if (this.sx > maxScale || this.sy > maxScale) {
827
- this.sx = maxScale;
828
- this.sy = maxScale;
829
- return true;
830
- }
831
- return false;
832
- }
833
- static get pixelRatio() {
834
- return globalThis.devicePixelRatio || 1;
835
- }
836
- static capPixels(maxPixels, capAreaFactor) {
837
- if (capAreaFactor >= 0) {
838
- const winPixels = Math.ceil(
839
- (false ? window.innerWidth * window.innerHeight : window.screen.availWidth * window.screen.availHeight) * this.pixelRatio ** 2 * (1 + capAreaFactor / 100)
840
- );
841
- return maxPixels > 0 ? Math.min(maxPixels, winPixels) : winPixels;
842
- }
843
- return maxPixels;
844
- }
845
- };
846
- var SupportedImageMimeTypes = [
847
- "image/apng",
848
- "image/avif",
849
- "image/bmp",
850
- "image/gif",
851
- "image/jpeg",
852
- "image/png",
853
- "image/svg+xml",
854
- "image/webp",
855
- "image/x-icon"
856
- ];
857
- var ColorScheme = class {
858
- static get isDarkMode() {
859
- return shadow(
860
- this,
861
- "isDarkMode",
862
- !!window?.matchMedia?.("(prefers-color-scheme: dark)").matches
863
- );
864
- }
865
- };
866
- var CSSConstants = class {
867
- static get commentForegroundColor() {
868
- const element = document.createElement("span");
869
- element.classList.add("comment", "sidebar");
870
- const { style } = element;
871
- style.width = style.height = "0";
872
- style.display = "none";
873
- style.color = "var(--comment-fg-color)";
874
- document.body.append(element);
875
- const { color } = window.getComputedStyle(element);
876
- element.remove();
877
- return shadow(this, "commentForegroundColor", getRGB(color));
878
- }
879
- };
880
- function applyOpacity(r, g, b, opacity) {
881
- opacity = Math.min(Math.max(opacity ?? 1, 0), 1);
882
- const white = 255 * (1 - opacity);
883
- r = Math.round(r * opacity + white);
884
- g = Math.round(g * opacity + white);
885
- b = Math.round(b * opacity + white);
886
- return [r, g, b];
887
- }
888
- function RGBToHSL(rgb, output) {
889
- const r = rgb[0] / 255;
890
- const g = rgb[1] / 255;
891
- const b = rgb[2] / 255;
892
- const max = Math.max(r, g, b);
893
- const min = Math.min(r, g, b);
894
- const l = (max + min) / 2;
895
- if (max === min) {
896
- output[0] = output[1] = 0;
897
- } else {
898
- const d = max - min;
899
- output[1] = l < 0.5 ? d / (max + min) : d / (2 - max - min);
900
- switch (max) {
901
- case r:
902
- output[0] = ((g - b) / d + (g < b ? 6 : 0)) * 60;
903
- break;
904
- case g:
905
- output[0] = ((b - r) / d + 2) * 60;
906
- break;
907
- case b:
908
- output[0] = ((r - g) / d + 4) * 60;
909
- break;
910
- }
911
- }
912
- output[2] = l;
913
- }
914
- function HSLToRGB(hsl, output) {
915
- const h = hsl[0];
916
- const s = hsl[1];
917
- const l = hsl[2];
918
- const c = (1 - Math.abs(2 * l - 1)) * s;
919
- const x = c * (1 - Math.abs(h / 60 % 2 - 1));
920
- const m = l - c / 2;
921
- switch (Math.floor(h / 60)) {
922
- case 0:
923
- output[0] = c + m;
924
- output[1] = x + m;
925
- output[2] = m;
926
- break;
927
- case 1:
928
- output[0] = x + m;
929
- output[1] = c + m;
930
- output[2] = m;
931
- break;
932
- case 2:
933
- output[0] = m;
934
- output[1] = c + m;
935
- output[2] = x + m;
936
- break;
937
- case 3:
938
- output[0] = m;
939
- output[1] = x + m;
940
- output[2] = c + m;
941
- break;
942
- case 4:
943
- output[0] = x + m;
944
- output[1] = m;
945
- output[2] = c + m;
946
- break;
947
- case 5:
948
- case 6:
949
- output[0] = c + m;
950
- output[1] = m;
951
- output[2] = x + m;
952
- break;
953
- }
954
- }
955
- function computeLuminance(x) {
956
- return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
957
- }
958
- function contrastRatio(hsl1, hsl2, output) {
959
- HSLToRGB(hsl1, output);
960
- output.map(computeLuminance);
961
- const lum1 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2];
962
- HSLToRGB(hsl2, output);
963
- output.map(computeLuminance);
964
- const lum2 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2];
965
- return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05);
966
- }
967
- var contrastCache = /* @__PURE__ */ new Map();
968
- function findContrastColor(baseColor, fixedColor) {
969
- const key = baseColor[0] + baseColor[1] * 256 + baseColor[2] * 65536 + fixedColor[0] * 16777216 + fixedColor[1] * 4294967296 + fixedColor[2] * 1099511627776;
970
- let cachedValue = contrastCache.get(key);
971
- if (cachedValue) {
972
- return cachedValue;
973
- }
974
- const array = new Float32Array(9);
975
- const output = array.subarray(0, 3);
976
- const baseHSL = array.subarray(3, 6);
977
- RGBToHSL(baseColor, baseHSL);
978
- const fixedHSL = array.subarray(6, 9);
979
- RGBToHSL(fixedColor, fixedHSL);
980
- const isFixedColorDark = fixedHSL[2] < 0.5;
981
- const minContrast = isFixedColorDark ? 12 : 4.5;
982
- baseHSL[2] = isFixedColorDark ? Math.sqrt(baseHSL[2]) : 1 - Math.sqrt(1 - baseHSL[2]);
983
- if (contrastRatio(baseHSL, fixedHSL, output) < minContrast) {
984
- let start, end;
985
- if (isFixedColorDark) {
986
- start = baseHSL[2];
987
- end = 1;
988
- } else {
989
- start = 0;
990
- end = baseHSL[2];
991
- }
992
- const PRECISION = 5e-3;
993
- while (end - start > PRECISION) {
994
- const mid = baseHSL[2] = (start + end) / 2;
995
- if (isFixedColorDark === contrastRatio(baseHSL, fixedHSL, output) < minContrast) {
996
- start = mid;
997
- } else {
998
- end = mid;
999
- }
1000
- }
1001
- baseHSL[2] = isFixedColorDark ? end : start;
1002
- }
1003
- HSLToRGB(baseHSL, output);
1004
- cachedValue = Util.makeHexColor(
1005
- Math.round(output[0] * 255),
1006
- Math.round(output[1] * 255),
1007
- Math.round(output[2] * 255)
1008
- );
1009
- contrastCache.set(key, cachedValue);
1010
- return cachedValue;
1011
- }
1012
- function renderRichText({ html, dir, className }, container) {
1013
- const fragment = document.createDocumentFragment();
1014
- if (typeof html === "string") {
1015
- const p = document.createElement("p");
1016
- p.dir = dir || "auto";
1017
- const lines = html.split(/(?:\r\n?|\n)/);
1018
- for (let i = 0, ii = lines.length; i < ii; ++i) {
1019
- const line = lines[i];
1020
- p.append(document.createTextNode(line));
1021
- if (i < ii - 1) {
1022
- p.append(document.createElement("br"));
1023
- }
1024
- }
1025
- fragment.append(p);
1026
- } else {
1027
- XfaLayer.render({
1028
- xfaHtml: html,
1029
- div: fragment,
1030
- intent: "richText"
1031
- });
1032
- }
1033
- fragment.firstChild.classList.add("richText", className);
1034
- container.append(fragment);
1035
- }
1036
-
1037
- // src/pdf.js/src/display/cmap_reader_factory.js
1038
- var BaseCMapReaderFactory = class {
1039
- constructor({ baseUrl = null, isCompressed = true }) {
1040
- if (false) {
1041
- unreachable("Cannot initialize BaseCMapReaderFactory.");
1042
- }
1043
- this.baseUrl = baseUrl;
1044
- this.isCompressed = isCompressed;
1045
- }
1046
- async fetch({ name }) {
1047
- if (!this.baseUrl) {
1048
- throw new Error(
1049
- "Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided."
1050
- );
1051
- }
1052
- if (!name) {
1053
- throw new Error("CMap name must be specified.");
1054
- }
1055
- const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
1056
- return this._fetch(url).then((cMapData) => ({ cMapData, isCompressed: this.isCompressed })).catch((reason) => {
1057
- throw new Error(
1058
- `Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`
1059
- );
1060
- });
1061
- }
1062
- /**
1063
- * @ignore
1064
- * @returns {Promise<Uint8Array>}
1065
- */
1066
- async _fetch(url) {
1067
- unreachable("Abstract method `_fetch` called.");
1068
- }
1069
- };
1070
- var DOMCMapReaderFactory = class extends BaseCMapReaderFactory {
1071
- /**
1072
- * @ignore
1073
- */
1074
- async _fetch(url) {
1075
- const data = await fetchData(
1076
- url,
1077
- /* type = */
1078
- this.isCompressed ? "arraybuffer" : "text"
1079
- );
1080
- return data instanceof ArrayBuffer ? new Uint8Array(data) : stringToBytes(data);
1081
- }
1082
- };
1083
-
1084
- // src/pdf.js/src/display/standard_fontdata_factory.js
1085
- var BaseStandardFontDataFactory = class {
1086
- constructor({ baseUrl = null }) {
1087
- if (false) {
1088
- unreachable("Cannot initialize BaseStandardFontDataFactory.");
1089
- }
1090
- this.baseUrl = baseUrl;
1091
- }
1092
- async fetch({ filename }) {
1093
- if (!this.baseUrl) {
1094
- throw new Error(
1095
- "Ensure that the `standardFontDataUrl` API parameter is provided."
1096
- );
1097
- }
1098
- if (!filename) {
1099
- throw new Error("Font filename must be specified.");
1100
- }
1101
- const url = `${this.baseUrl}${filename}`;
1102
- return this._fetch(url).catch((reason) => {
1103
- throw new Error(`Unable to load font data at: ${url}`);
1104
- });
1105
- }
1106
- /**
1107
- * @ignore
1108
- * @returns {Promise<Uint8Array>}
1109
- */
1110
- async _fetch(url) {
1111
- unreachable("Abstract method `_fetch` called.");
1112
- }
1113
- };
1114
- var DOMStandardFontDataFactory = class extends BaseStandardFontDataFactory {
1115
- /**
1116
- * @ignore
1117
- */
1118
- async _fetch(url) {
1119
- const data = await fetchData(
1120
- url,
1121
- /* type = */
1122
- "arraybuffer"
1123
- );
1124
- return new Uint8Array(data);
1125
- }
1126
- };
1127
-
1128
- // src/pdf.js/src/display/wasm_factory.js
1129
- var BaseWasmFactory = class {
1130
- constructor({ baseUrl = null }) {
1131
- if (false) {
1132
- unreachable("Cannot initialize BaseWasmFactory.");
1133
- }
1134
- this.baseUrl = baseUrl;
1135
- }
1136
- async fetch({ filename }) {
1137
- if (!this.baseUrl) {
1138
- throw new Error("Ensure that the `wasmUrl` API parameter is provided.");
1139
- }
1140
- if (!filename) {
1141
- throw new Error("Wasm filename must be specified.");
1142
- }
1143
- const url = `${this.baseUrl}${filename}`;
1144
- return this._fetch(url).catch((reason) => {
1145
- throw new Error(`Unable to load wasm data at: ${url}`);
1146
- });
1147
- }
1148
- /**
1149
- * @ignore
1150
- * @returns {Promise<Uint8Array>}
1151
- */
1152
- async _fetch(url) {
1153
- unreachable("Abstract method `_fetch` called.");
1154
- }
1155
- };
1156
- var DOMWasmFactory = class extends BaseWasmFactory {
1157
- /**
1158
- * @ignore
1159
- */
1160
- async _fetch(url) {
1161
- const data = await fetchData(
1162
- url,
1163
- /* type = */
1164
- "arraybuffer"
1165
- );
1166
- return new Uint8Array(data);
1167
- }
1168
- };
1169
-
1170
- // src/lib/NodeCanvasFactory.ts
1171
- import { Canvas } from "skia-canvas";
1172
-
1173
- // src/pdf.js/src/display/canvas_factory.js
1174
- var _enableHWA;
1175
- var BaseCanvasFactory = class {
1176
- constructor({ enableHWA = false }) {
1177
- __privateAdd(this, _enableHWA, false);
1178
- if (false) {
1179
- unreachable("Cannot initialize BaseCanvasFactory.");
1180
- }
1181
- __privateSet(this, _enableHWA, enableHWA);
1182
- }
1183
- create(width, height) {
1184
- if (width <= 0 || height <= 0) {
1185
- throw new Error("Invalid canvas size");
1186
- }
1187
- const canvas = this._createCanvas(width, height);
1188
- return {
1189
- canvas,
1190
- context: canvas.getContext("2d", {
1191
- willReadFrequently: !__privateGet(this, _enableHWA)
1192
- })
1193
- };
1194
- }
1195
- reset(canvasAndContext, width, height) {
1196
- if (!canvasAndContext.canvas) {
1197
- throw new Error("Canvas is not specified");
1198
- }
1199
- if (width <= 0 || height <= 0) {
1200
- throw new Error("Invalid canvas size");
1201
- }
1202
- canvasAndContext.canvas.width = width;
1203
- canvasAndContext.canvas.height = height;
1204
- }
1205
- destroy(canvasAndContext) {
1206
- if (!canvasAndContext.canvas) {
1207
- throw new Error("Canvas is not specified");
1208
- }
1209
- canvasAndContext.canvas.width = 0;
1210
- canvasAndContext.canvas.height = 0;
1211
- canvasAndContext.canvas = null;
1212
- canvasAndContext.context = null;
1213
- }
1214
- /**
1215
- * @ignore
1216
- */
1217
- _createCanvas(width, height) {
1218
- unreachable("Abstract method `_createCanvas` called.");
1219
- }
1220
- };
1221
- _enableHWA = new WeakMap();
1222
- var DOMCanvasFactory = class extends BaseCanvasFactory {
1223
- constructor({ ownerDocument = globalThis.document, enableHWA = false }) {
1224
- super({ enableHWA });
1225
- this._document = ownerDocument;
1226
- }
1227
- /**
1228
- * @ignore
1229
- */
1230
- _createCanvas(width, height) {
1231
- const canvas = this._document.createElement("canvas");
1232
- canvas.width = width;
1233
- canvas.height = height;
1234
- return canvas;
1235
- }
1236
- };
1237
-
1238
- // src/pdf.js/src/display/filter_factory.js
1239
- var BaseFilterFactory = class {
1240
- constructor() {
1241
- if (false) {
1242
- unreachable("Cannot initialize BaseFilterFactory.");
1243
- }
1244
- }
1245
- addFilter(maps) {
1246
- return "none";
1247
- }
1248
- addHCMFilter(fgColor, bgColor) {
1249
- return "none";
1250
- }
1251
- addAlphaFilter(map) {
1252
- return "none";
1253
- }
1254
- addLuminosityFilter(map) {
1255
- return "none";
1256
- }
1257
- addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
1258
- return "none";
1259
- }
1260
- destroy(keepHCM = false) {
1261
- }
1262
- };
1263
- var _baseUrl, __cache, __defs, _docId, _document, __hcmCache, _id, _DOMFilterFactory_instances, cache_get, hcmCache_get, defs_get, createTables_fn, createUrl_fn, addLuminosityConversion_fn, addGrayConversion_fn, createFilter_fn, appendFeFunc_fn, addTransferMapConversion_fn, addTransferMapAlphaConversion_fn, getRGB_fn;
1264
- var DOMFilterFactory = class extends BaseFilterFactory {
1265
- constructor({ docId, ownerDocument = globalThis.document }) {
1266
- super();
1267
- __privateAdd(this, _DOMFilterFactory_instances);
1268
- __privateAdd(this, _baseUrl);
1269
- __privateAdd(this, __cache);
1270
- __privateAdd(this, __defs);
1271
- __privateAdd(this, _docId);
1272
- __privateAdd(this, _document);
1273
- __privateAdd(this, __hcmCache);
1274
- __privateAdd(this, _id, 0);
1275
- __privateSet(this, _docId, docId);
1276
- __privateSet(this, _document, ownerDocument);
1277
- }
1278
- addFilter(maps) {
1279
- if (!maps) {
1280
- return "none";
1281
- }
1282
- let value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(maps);
1283
- if (value) {
1284
- return value;
1285
- }
1286
- const [tableR, tableG, tableB] = __privateMethod(this, _DOMFilterFactory_instances, createTables_fn).call(this, maps);
1287
- const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`;
1288
- value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(key);
1289
- if (value) {
1290
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(maps, value);
1291
- return value;
1292
- }
1293
- const id = `g_${__privateGet(this, _docId)}_transfer_map_${__privateWrapper(this, _id)._++}`;
1294
- const url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
1295
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(maps, url);
1296
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(key, url);
1297
- const filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
1298
- __privateMethod(this, _DOMFilterFactory_instances, addTransferMapConversion_fn).call(this, tableR, tableG, tableB, filter);
1299
- return url;
1300
- }
1301
- addHCMFilter(fgColor, bgColor) {
1302
- const key = `${fgColor}-${bgColor}`;
1303
- const filterName = "base";
1304
- let info = __privateGet(this, _DOMFilterFactory_instances, hcmCache_get).get(filterName);
1305
- if (info?.key === key) {
1306
- return info.url;
1307
- }
1308
- if (info) {
1309
- info.filter?.remove();
1310
- info.key = key;
1311
- info.url = "none";
1312
- info.filter = null;
1313
- } else {
1314
- info = {
1315
- key,
1316
- url: "none",
1317
- filter: null
1318
- };
1319
- __privateGet(this, _DOMFilterFactory_instances, hcmCache_get).set(filterName, info);
1320
- }
1321
- if (!fgColor || !bgColor) {
1322
- return info.url;
1323
- }
1324
- const fgRGB = __privateMethod(this, _DOMFilterFactory_instances, getRGB_fn).call(this, fgColor);
1325
- fgColor = Util.makeHexColor(...fgRGB);
1326
- const bgRGB = __privateMethod(this, _DOMFilterFactory_instances, getRGB_fn).call(this, bgColor);
1327
- bgColor = Util.makeHexColor(...bgRGB);
1328
- __privateGet(this, _DOMFilterFactory_instances, defs_get).style.color = "";
1329
- if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) {
1330
- return info.url;
1331
- }
1332
- const map = new Array(256);
1333
- for (let i = 0; i <= 255; i++) {
1334
- const x = i / 255;
1335
- map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
1336
- }
1337
- const table = map.join(",");
1338
- const id = `g_${__privateGet(this, _docId)}_hcm_filter`;
1339
- const filter = info.filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
1340
- __privateMethod(this, _DOMFilterFactory_instances, addTransferMapConversion_fn).call(this, table, table, table, filter);
1341
- __privateMethod(this, _DOMFilterFactory_instances, addGrayConversion_fn).call(this, filter);
1342
- const getSteps = (c, n) => {
1343
- const start = fgRGB[c] / 255;
1344
- const end = bgRGB[c] / 255;
1345
- const arr = new Array(n + 1);
1346
- for (let i = 0; i <= n; i++) {
1347
- arr[i] = start + i / n * (end - start);
1348
- }
1349
- return arr.join(",");
1350
- };
1351
- __privateMethod(this, _DOMFilterFactory_instances, addTransferMapConversion_fn).call(this, getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter);
1352
- info.url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
1353
- return info.url;
1354
- }
1355
- addAlphaFilter(map) {
1356
- let value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(map);
1357
- if (value) {
1358
- return value;
1359
- }
1360
- const [tableA] = __privateMethod(this, _DOMFilterFactory_instances, createTables_fn).call(this, [map]);
1361
- const key = `alpha_${tableA}`;
1362
- value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(key);
1363
- if (value) {
1364
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(map, value);
1365
- return value;
1366
- }
1367
- const id = `g_${__privateGet(this, _docId)}_alpha_map_${__privateWrapper(this, _id)._++}`;
1368
- const url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
1369
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(map, url);
1370
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(key, url);
1371
- const filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
1372
- __privateMethod(this, _DOMFilterFactory_instances, addTransferMapAlphaConversion_fn).call(this, tableA, filter);
1373
- return url;
1374
- }
1375
- addLuminosityFilter(map) {
1376
- let value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(map || "luminosity");
1377
- if (value) {
1378
- return value;
1379
- }
1380
- let tableA, key;
1381
- if (map) {
1382
- [tableA] = __privateMethod(this, _DOMFilterFactory_instances, createTables_fn).call(this, [map]);
1383
- key = `luminosity_${tableA}`;
1384
- } else {
1385
- key = "luminosity";
1386
- }
1387
- value = __privateGet(this, _DOMFilterFactory_instances, cache_get).get(key);
1388
- if (value) {
1389
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(map, value);
1390
- return value;
1391
- }
1392
- const id = `g_${__privateGet(this, _docId)}_luminosity_map_${__privateWrapper(this, _id)._++}`;
1393
- const url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
1394
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(map, url);
1395
- __privateGet(this, _DOMFilterFactory_instances, cache_get).set(key, url);
1396
- const filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
1397
- __privateMethod(this, _DOMFilterFactory_instances, addLuminosityConversion_fn).call(this, filter);
1398
- if (map) {
1399
- __privateMethod(this, _DOMFilterFactory_instances, addTransferMapAlphaConversion_fn).call(this, tableA, filter);
1400
- }
1401
- return url;
1402
- }
1403
- addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
1404
- const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;
1405
- let info = __privateGet(this, _DOMFilterFactory_instances, hcmCache_get).get(filterName);
1406
- if (info?.key === key) {
1407
- return info.url;
1408
- }
1409
- if (info) {
1410
- info.filter?.remove();
1411
- info.key = key;
1412
- info.url = "none";
1413
- info.filter = null;
1414
- } else {
1415
- info = {
1416
- key,
1417
- url: "none",
1418
- filter: null
1419
- };
1420
- __privateGet(this, _DOMFilterFactory_instances, hcmCache_get).set(filterName, info);
1421
- }
1422
- if (!fgColor || !bgColor) {
1423
- return info.url;
1424
- }
1425
- const [fgRGB, bgRGB] = [fgColor, bgColor].map(__privateMethod(this, _DOMFilterFactory_instances, getRGB_fn).bind(this));
1426
- let fgGray = Math.round(
1427
- 0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]
1428
- );
1429
- let bgGray = Math.round(
1430
- 0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]
1431
- );
1432
- let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(
1433
- __privateMethod(this, _DOMFilterFactory_instances, getRGB_fn).bind(this)
1434
- );
1435
- if (bgGray < fgGray) {
1436
- [fgGray, bgGray, newFgRGB, newBgRGB] = [
1437
- bgGray,
1438
- fgGray,
1439
- newBgRGB,
1440
- newFgRGB
1441
- ];
1442
- }
1443
- __privateGet(this, _DOMFilterFactory_instances, defs_get).style.color = "";
1444
- const getSteps = (fg, bg, n) => {
1445
- const arr = new Array(256);
1446
- const step = (bgGray - fgGray) / n;
1447
- const newStart = fg / 255;
1448
- const newStep = (bg - fg) / (255 * n);
1449
- let prev = 0;
1450
- for (let i = 0; i <= n; i++) {
1451
- const k = Math.round(fgGray + i * step);
1452
- const value = newStart + i * newStep;
1453
- for (let j = prev; j <= k; j++) {
1454
- arr[j] = value;
1455
- }
1456
- prev = k + 1;
1457
- }
1458
- for (let i = prev; i < 256; i++) {
1459
- arr[i] = arr[prev - 1];
1460
- }
1461
- return arr.join(",");
1462
- };
1463
- const id = `g_${__privateGet(this, _docId)}_hcm_${filterName}_filter`;
1464
- const filter = info.filter = __privateMethod(this, _DOMFilterFactory_instances, createFilter_fn).call(this, id);
1465
- __privateMethod(this, _DOMFilterFactory_instances, addGrayConversion_fn).call(this, filter);
1466
- __privateMethod(this, _DOMFilterFactory_instances, addTransferMapConversion_fn).call(this, getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter);
1467
- info.url = __privateMethod(this, _DOMFilterFactory_instances, createUrl_fn).call(this, id);
1468
- return info.url;
1469
- }
1470
- destroy(keepHCM = false) {
1471
- if (keepHCM && __privateGet(this, __hcmCache)?.size) {
1472
- return;
1473
- }
1474
- __privateGet(this, __defs)?.parentNode.parentNode.remove();
1475
- __privateSet(this, __defs, null);
1476
- __privateGet(this, __cache)?.clear();
1477
- __privateSet(this, __cache, null);
1478
- __privateGet(this, __hcmCache)?.clear();
1479
- __privateSet(this, __hcmCache, null);
1480
- __privateSet(this, _id, 0);
1481
- }
1482
- };
1483
- _baseUrl = new WeakMap();
1484
- __cache = new WeakMap();
1485
- __defs = new WeakMap();
1486
- _docId = new WeakMap();
1487
- _document = new WeakMap();
1488
- __hcmCache = new WeakMap();
1489
- _id = new WeakMap();
1490
- _DOMFilterFactory_instances = new WeakSet();
1491
- cache_get = function() {
1492
- return __privateGet(this, __cache) || __privateSet(this, __cache, /* @__PURE__ */ new Map());
1493
- };
1494
- hcmCache_get = function() {
1495
- return __privateGet(this, __hcmCache) || __privateSet(this, __hcmCache, /* @__PURE__ */ new Map());
1496
- };
1497
- defs_get = function() {
1498
- if (!__privateGet(this, __defs)) {
1499
- const div = __privateGet(this, _document).createElement("div");
1500
- const { style } = div;
1501
- style.visibility = "hidden";
1502
- style.contain = "strict";
1503
- style.width = style.height = 0;
1504
- style.position = "absolute";
1505
- style.top = style.left = 0;
1506
- style.zIndex = -1;
1507
- const svg = __privateGet(this, _document).createElementNS(SVG_NS, "svg");
1508
- svg.setAttribute("width", 0);
1509
- svg.setAttribute("height", 0);
1510
- __privateSet(this, __defs, __privateGet(this, _document).createElementNS(SVG_NS, "defs"));
1511
- div.append(svg);
1512
- svg.append(__privateGet(this, __defs));
1513
- __privateGet(this, _document).body.append(div);
1514
- }
1515
- return __privateGet(this, __defs);
1516
- };
1517
- createTables_fn = function(maps) {
1518
- if (maps.length === 1) {
1519
- const mapR2 = maps[0];
1520
- const buffer = new Array(256);
1521
- for (let i = 0; i < 256; i++) {
1522
- buffer[i] = mapR2[i] / 255;
1523
- }
1524
- const table = buffer.join(",");
1525
- return [table, table, table];
1526
- }
1527
- const [mapR, mapG, mapB] = maps;
1528
- const bufferR = new Array(256);
1529
- const bufferG = new Array(256);
1530
- const bufferB = new Array(256);
1531
- for (let i = 0; i < 256; i++) {
1532
- bufferR[i] = mapR[i] / 255;
1533
- bufferG[i] = mapG[i] / 255;
1534
- bufferB[i] = mapB[i] / 255;
1535
- }
1536
- return [bufferR.join(","), bufferG.join(","), bufferB.join(",")];
1537
- };
1538
- createUrl_fn = function(id) {
1539
- if (__privateGet(this, _baseUrl) === void 0) {
1540
- __privateSet(this, _baseUrl, "");
1541
- const url = __privateGet(this, _document).URL;
1542
- if (url !== __privateGet(this, _document).baseURI) {
1543
- if (isDataScheme(url)) {
1544
- warn('#createUrl: ignore "data:"-URL for performance reasons.');
1545
- } else {
1546
- __privateSet(this, _baseUrl, updateUrlHash(url, ""));
1547
- }
1548
- }
1549
- }
1550
- return `url(${__privateGet(this, _baseUrl)}#${id})`;
1551
- };
1552
- addLuminosityConversion_fn = function(filter) {
1553
- const feColorMatrix = __privateGet(this, _document).createElementNS(
1554
- SVG_NS,
1555
- "feColorMatrix"
1556
- );
1557
- feColorMatrix.setAttribute("type", "matrix");
1558
- feColorMatrix.setAttribute(
1559
- "values",
1560
- "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"
1561
- );
1562
- filter.append(feColorMatrix);
1563
- };
1564
- addGrayConversion_fn = function(filter) {
1565
- const feColorMatrix = __privateGet(this, _document).createElementNS(
1566
- SVG_NS,
1567
- "feColorMatrix"
1568
- );
1569
- feColorMatrix.setAttribute("type", "matrix");
1570
- feColorMatrix.setAttribute(
1571
- "values",
1572
- "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"
1573
- );
1574
- filter.append(feColorMatrix);
1575
- };
1576
- createFilter_fn = function(id) {
1577
- const filter = __privateGet(this, _document).createElementNS(SVG_NS, "filter");
1578
- filter.setAttribute("color-interpolation-filters", "sRGB");
1579
- filter.setAttribute("id", id);
1580
- __privateGet(this, _DOMFilterFactory_instances, defs_get).append(filter);
1581
- return filter;
1582
- };
1583
- appendFeFunc_fn = function(feComponentTransfer, func, table) {
1584
- const feFunc = __privateGet(this, _document).createElementNS(SVG_NS, func);
1585
- feFunc.setAttribute("type", "discrete");
1586
- feFunc.setAttribute("tableValues", table);
1587
- feComponentTransfer.append(feFunc);
1588
- };
1589
- addTransferMapConversion_fn = function(rTable, gTable, bTable, filter) {
1590
- const feComponentTransfer = __privateGet(this, _document).createElementNS(
1591
- SVG_NS,
1592
- "feComponentTransfer"
1593
- );
1594
- filter.append(feComponentTransfer);
1595
- __privateMethod(this, _DOMFilterFactory_instances, appendFeFunc_fn).call(this, feComponentTransfer, "feFuncR", rTable);
1596
- __privateMethod(this, _DOMFilterFactory_instances, appendFeFunc_fn).call(this, feComponentTransfer, "feFuncG", gTable);
1597
- __privateMethod(this, _DOMFilterFactory_instances, appendFeFunc_fn).call(this, feComponentTransfer, "feFuncB", bTable);
1598
- };
1599
- addTransferMapAlphaConversion_fn = function(aTable, filter) {
1600
- const feComponentTransfer = __privateGet(this, _document).createElementNS(
1601
- SVG_NS,
1602
- "feComponentTransfer"
1603
- );
1604
- filter.append(feComponentTransfer);
1605
- __privateMethod(this, _DOMFilterFactory_instances, appendFeFunc_fn).call(this, feComponentTransfer, "feFuncA", aTable);
1606
- };
1607
- getRGB_fn = function(color) {
1608
- __privateGet(this, _DOMFilterFactory_instances, defs_get).style.color = color;
1609
- return getRGB(getComputedStyle(__privateGet(this, _DOMFilterFactory_instances, defs_get)).getPropertyValue("color"));
1610
- };
1611
-
1612
- // src/lib/utils.ts
1613
- async function canvasToData(canvas) {
1614
- if ("toBlob" in canvas) {
1615
- const blob = await new Promise(
1616
- (resolve) => canvas.toBlob((data) => resolve(data))
1617
- );
1618
- if (!blob) {
1619
- throw new Error("Failed to generate graphics");
1620
- }
1621
- return new Uint8Array(await blob.arrayBuffer());
1622
- }
1623
- const buffer = await canvas.toBuffer("png");
1624
- return new Uint8Array(buffer);
1625
- }
1626
- async function toDataUrl(data, type = "image/png") {
1627
- if (typeof FileReader !== "undefined") {
1628
- return new Promise((resolve) => {
1629
- const reader = new FileReader();
1630
- reader.onload = () => {
1631
- resolve(reader.result);
1632
- };
1633
- reader.readAsDataURL(new Blob([data], { type }));
1634
- });
1635
- }
1636
- return `data:${type};base64,${Buffer.from(data).toString("base64")}`;
1637
- }
1638
- function colorToRgb(color) {
1639
- if (color.startsWith("#")) {
1640
- const hex = color.slice(1);
1641
- if (hex.length === 3) {
1642
- return [
1643
- Number.parseInt(hex[0] + hex[0], 16),
1644
- Number.parseInt(hex[1] + hex[1], 16),
1645
- Number.parseInt(hex[2] + hex[2], 16)
1646
- ];
1647
- }
1648
- if (hex.length === 6) {
1649
- return [
1650
- Number.parseInt(hex.slice(0, 2), 16),
1651
- Number.parseInt(hex.slice(2, 4), 16),
1652
- Number.parseInt(hex.slice(4, 6), 16)
1653
- ];
1654
- }
1655
- }
1656
- throw new Error(`Invalid color format: ${color}`);
1657
- }
1658
- function rgbToHex(r, g, b) {
1659
- const toHex = (value) => value.toString(16).padStart(2, "0");
1660
- if (Array.isArray(r)) {
1661
- return `#${toHex(r[0])}${toHex(r[1])}${toHex(r[2])}`;
1662
- }
1663
- return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
1664
- }
1665
- function parseRgbaColor(color) {
1666
- const match = color.match(
1667
- /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)$/
1668
- );
1669
- if (!match) {
1670
- return { r: 0, g: 0, b: 0, a: 1 };
1671
- }
1672
- return {
1673
- r: Number.parseInt(match[1], 10),
1674
- g: Number.parseInt(match[2], 10),
1675
- b: Number.parseInt(match[3], 10),
1676
- a: match[4] ? Number.parseFloat(match[4]) : 1
1677
- };
1678
- }
1679
- function randomUUID() {
1680
- if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
1681
- return crypto.randomUUID();
1682
- }
1683
- const hex = [...Array(36)].map(
1684
- () => Math.floor(Math.random() * 16).toString(16)
1685
- );
1686
- hex[14] = "4";
1687
- hex[19] = (Number.parseInt(hex[19], 16) & 3 | 8).toString(16);
1688
- hex[8] = hex[13] = hex[18] = hex[23] = "-";
1689
- return hex.join("");
1690
- }
1691
-
1692
- // src/lib/NodeFilterFactory.ts
1693
- var filtersRegistry = /* @__PURE__ */ new Map();
1694
- function createTables(maps) {
1695
- if (maps.length === 1) {
1696
- const mapR2 = maps[0];
1697
- const buffer = new Array(256);
1698
- for (let i = 0; i < 256; i++) {
1699
- buffer[i] = mapR2[i] / 255;
1700
- }
1701
- return [buffer, buffer, buffer];
1702
- }
1703
- const [mapR, mapG, mapB] = maps;
1704
- const bufferR = new Array(256);
1705
- const bufferG = new Array(256);
1706
- const bufferB = new Array(256);
1707
- for (let i = 0; i < 256; i++) {
1708
- bufferR[i] = mapR[i] / 255;
1709
- bufferG[i] = mapG[i] / 255;
1710
- bufferB[i] = mapB[i] / 255;
1711
- }
1712
- return [bufferR, bufferG, bufferB];
1713
- }
1714
- function createTransferMapAlphaConversion(aTable) {
1715
- return (ctx) => {
1716
- const imageData = ctx.getImageData(
1717
- 0,
1718
- 0,
1719
- ctx.canvas.width,
1720
- ctx.canvas.height
1721
- );
1722
- const data = imageData.data;
1723
- const tableSize = aTable.length;
1724
- for (let i = 0; i < data.length; i += 4) {
1725
- const alpha = data[i + 3] / 255;
1726
- const index = alpha * (tableSize - 1);
1727
- const lower = Math.floor(index);
1728
- const upper = Math.min(lower + 1, tableSize - 1);
1729
- const t = index - lower;
1730
- const newAlpha = (1 - t) * aTable[lower] + t * aTable[upper];
1731
- data[i + 3] = newAlpha * 255;
1732
- }
1733
- ctx.putImageData(imageData, 0, 0);
1734
- };
1735
- }
1736
- function createTransferMapConversion(rTable, gTable, bTable) {
1737
- return (ctx) => {
1738
- const imageData = ctx.getImageData(
1739
- 0,
1740
- 0,
1741
- ctx.canvas.width,
1742
- ctx.canvas.height
1743
- );
1744
- const data = imageData.data;
1745
- const rSize = rTable.length;
1746
- const gSize = gTable.length;
1747
- const bSize = bTable.length;
1748
- for (let i = 0; i < data.length; i += 4) {
1749
- const r = data[i] / 255;
1750
- const g = data[i + 1] / 255;
1751
- const b = data[i + 2] / 255;
1752
- const rIndex = r * (rSize - 1);
1753
- const rLower = Math.floor(rIndex);
1754
- const rUpper = Math.min(rLower + 1, rSize - 1);
1755
- const rT = rIndex - rLower;
1756
- const newR = (1 - rT) * rTable[rLower] + rT * rTable[rUpper];
1757
- const gIndex = g * (gSize - 1);
1758
- const gLower = Math.floor(gIndex);
1759
- const gUpper = Math.min(gLower + 1, gSize - 1);
1760
- const gT = gIndex - gLower;
1761
- const newG = (1 - gT) * gTable[gLower] + gT * gTable[gUpper];
1762
- const bIndex = b * (bSize - 1);
1763
- const bLower = Math.floor(bIndex);
1764
- const bUpper = Math.min(bLower + 1, bSize - 1);
1765
- const bT = bIndex - bLower;
1766
- const newB = (1 - bT) * bTable[bLower] + bT * bTable[bUpper];
1767
- data[i] = newR * 255;
1768
- data[i + 1] = newG * 255;
1769
- data[i + 2] = newB * 255;
1770
- }
1771
- ctx.putImageData(imageData, 0, 0);
1772
- };
1773
- }
1774
- function createLuminosityConversion() {
1775
- return (ctx) => {
1776
- const imageData = ctx.getImageData(
1777
- 0,
1778
- 0,
1779
- ctx.canvas.width,
1780
- ctx.canvas.height
1781
- );
1782
- const data = imageData.data;
1783
- for (let i = 0; i < data.length; i += 4) {
1784
- const r = data[i];
1785
- const g = data[i + 1];
1786
- const b = data[i + 2];
1787
- data[i] = data[i + 1] = data[i + 2] = 0;
1788
- data[i + 3] = r * 0.3 + g * 0.59 + b * 0.11;
1789
- }
1790
- ctx.putImageData(imageData, 0, 0);
1791
- };
1792
- }
1793
- function createGrayConversion() {
1794
- return (ctx) => {
1795
- const imageData = ctx.getImageData(
1796
- 0,
1797
- 0,
1798
- ctx.canvas.width,
1799
- ctx.canvas.height
1800
- );
1801
- const data = imageData.data;
1802
- for (let i = 0; i < data.length; i += 4) {
1803
- const r = data[i];
1804
- const g = data[i + 1];
1805
- const b = data[i + 2];
1806
- const gray = r * 0.2126 + g * 0.7152 + b * 0.0722;
1807
- data[i] = data[i + 1] = data[i + 2] = gray;
1808
- }
1809
- ctx.putImageData(imageData, 0, 0);
1810
- };
1811
- }
1812
- var NodeFilterFactory = class extends BaseFilterFactory {
1813
- addFilter(maps) {
1814
- if (!maps) {
1815
- return "none";
1816
- }
1817
- const [rTable, gTable, bTable] = createTables(maps);
1818
- const url = `url(#filter_${maps.length === 1 ? rTable.join("_") : `${rTable.join("_")}_${gTable.join("_")}_${bTable.join("_")}`})`;
1819
- if (!filtersRegistry.has(url)) {
1820
- filtersRegistry.set(
1821
- url,
1822
- createTransferMapConversion(rTable, gTable, bTable)
1823
- );
1824
- }
1825
- return url;
1826
- }
1827
- addHCMFilter(fgColor, bgColor) {
1828
- const fgRGB = colorToRgb(fgColor);
1829
- const bgRGB = colorToRgb(bgColor);
1830
- const url = `url(#hcm_${rgbToHex(fgRGB)}_${rgbToHex(bgRGB)})`;
1831
- if (!filtersRegistry.has(url)) {
1832
- const table = new Array(256);
1833
- for (let i = 0; i <= 255; i++) {
1834
- const x = i / 255;
1835
- table[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
1836
- }
1837
- const transferMapFilter = createTransferMapConversion(
1838
- table,
1839
- table,
1840
- table
1841
- );
1842
- const grayFilter = createGrayConversion();
1843
- const getSteps = (c, n) => {
1844
- const start = fgRGB[c] / 255;
1845
- const end = bgRGB[c] / 255;
1846
- const arr = new Array(n + 1);
1847
- for (let i = 0; i <= n; i++) {
1848
- arr[i] = start + i / n * (end - start);
1849
- }
1850
- return arr;
1851
- };
1852
- const finalTransferMap = createTransferMapConversion(
1853
- getSteps(0, 5),
1854
- getSteps(1, 5),
1855
- getSteps(2, 5)
1856
- );
1857
- filtersRegistry.set(url, (ctx) => {
1858
- transferMapFilter(ctx);
1859
- grayFilter(ctx);
1860
- finalTransferMap(ctx);
1861
- });
1862
- }
1863
- return url;
1864
- }
1865
- addAlphaFilter(map) {
1866
- const [tableA] = createTables([map]);
1867
- const url = `url(#alpha_${tableA.join("_")})`;
1868
- if (!filtersRegistry.has(url)) {
1869
- filtersRegistry.set(url, createTransferMapAlphaConversion(map));
1870
- }
1871
- return url;
1872
- }
1873
- addLuminosityFilter(map) {
1874
- const url = `url(#luminosity${map ? `_${map.join("_")}` : ""})`;
1875
- if (!filtersRegistry.has(url)) {
1876
- const tables = map ? createTables([map]) : null;
1877
- const alphaFilter = tables ? createTransferMapAlphaConversion(tables[0]) : null;
1878
- const luminosityFilter = createLuminosityConversion();
1879
- filtersRegistry.set(url, (ctx) => {
1880
- luminosityFilter(ctx);
1881
- alphaFilter?.(ctx);
1882
- });
1883
- }
1884
- return url;
1885
- }
1886
- addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {
1887
- const fgRGB = colorToRgb(fgColor);
1888
- const bgRGB = colorToRgb(bgColor);
1889
- let newFgRGB = colorToRgb(newFgColor);
1890
- let newBgRGB = colorToRgb(newBgColor);
1891
- const url = `url(#highlight_hcm_${filterName}_${rgbToHex(fgRGB)}_${rgbToHex(bgRGB)}_${rgbToHex(newFgRGB)}_${rgbToHex(newBgRGB)})`;
1892
- if (!filtersRegistry.has(url)) {
1893
- let fgGray = Math.round(
1894
- 0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]
1895
- );
1896
- let bgGray = Math.round(
1897
- 0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]
1898
- );
1899
- if (bgGray < fgGray) {
1900
- [fgGray, bgGray, newFgRGB, newBgRGB] = [
1901
- bgGray,
1902
- fgGray,
1903
- newBgRGB,
1904
- newFgRGB
1905
- ];
1906
- }
1907
- const grayFilter = createGrayConversion();
1908
- const getSteps = (fg, bg, n) => {
1909
- const arr = new Array(256);
1910
- const step = (bgGray - fgGray) / n;
1911
- const newStart = fg / 255;
1912
- const newStep = (bg - fg) / (255 * n);
1913
- let prev = 0;
1914
- for (let i = 0; i <= n; i++) {
1915
- const k = Math.round(fgGray + i * step);
1916
- const value = newStart + i * newStep;
1917
- for (let j = prev; j <= k; j++) {
1918
- arr[j] = value;
1919
- }
1920
- prev = k + 1;
1921
- }
1922
- for (let i = prev; i < 256; i++) {
1923
- arr[i] = arr[prev - 1];
1924
- }
1925
- return arr;
1926
- };
1927
- const transferMapFilter = createTransferMapConversion(
1928
- getSteps(newFgRGB[0], newBgRGB[0], 5),
1929
- getSteps(newFgRGB[1], newBgRGB[1], 5),
1930
- getSteps(newFgRGB[2], newBgRGB[2], 5)
1931
- );
1932
- filtersRegistry.set(url, (ctx) => {
1933
- grayFilter(ctx);
1934
- transferMapFilter(ctx);
1935
- });
1936
- }
1937
- return url;
1938
- }
1939
- };
1940
-
1941
- // src/lib/NodeCanvasFactory.ts
1942
- var NodeCanvasFactory = class extends BaseCanvasFactory {
1943
- _createCanvas(width, height) {
1944
- return new Canvas(width, height);
1945
- }
1946
- create(width, height) {
1947
- const factory = this;
1948
- const { canvas, context } = super.create(width, height);
1949
- const drawImage = context.drawImage;
1950
- let currentFilter = "none";
1951
- Object.defineProperty(context, "filter", {
1952
- get() {
1953
- if (currentFilter.startsWith("url(")) {
1954
- return "none";
1955
- }
1956
- return currentFilter;
1957
- },
1958
- set(value) {
1959
- currentFilter = value;
1960
- },
1961
- configurable: true
1962
- });
1963
- context.drawImage = function(src, ...args) {
1964
- const filter = filtersRegistry.get(currentFilter);
1965
- if (!filter) {
1966
- drawImage.call(this, src, ...args);
1967
- return;
1968
- }
1969
- const { canvas: canvas2, context: context2 } = factory.create(src.width, src.height);
1970
- context2.drawImage(src, 0, 0, src.width, src.height);
1971
- filter(context2);
1972
- drawImage.call(this, canvas2, ...args);
1973
- factory.destroy({
1974
- canvas: canvas2,
1975
- context: context2
1976
- });
1977
- };
1978
- return {
1979
- canvas,
1980
- context
1981
- };
1982
- }
1983
- };
1984
-
1985
- // src/lib/NodeUtils.ts
1986
- if (!globalThis.DOMMatrix) {
1987
- globalThis.DOMMatrix = NodeDOMMatrix;
1988
- }
1989
- if (!globalThis.DOMPoint) {
1990
- globalThis.DOMPoint = NodeDOMPoint;
1991
- }
1992
- if (!globalThis.ImageData) {
1993
- globalThis.ImageData = NodeImageData;
1994
- }
1995
- if (!globalThis.Path2D) {
1996
- globalThis.Path2D = NodePath2D;
1997
- }
1998
- if (!globalThis.navigator?.language) {
1999
- globalThis.navigator = {
2000
- language: "en-US",
2001
- platform: "",
2002
- userAgent: ""
2003
- };
2004
- }
2005
- async function fetchData2(url) {
2006
- const { readFile } = await import("node:fs/promises");
2007
- const data = await readFile(url);
2008
- return new Uint8Array(data);
2009
- }
2010
- var NodeCMapReaderFactory = class extends BaseCMapReaderFactory {
2011
- /**
2012
- * @ignore
2013
- */
2014
- async _fetch(url) {
2015
- return fetchData2(url);
2016
- }
2017
- };
2018
- var NodeStandardFontDataFactory = class extends BaseStandardFontDataFactory {
2019
- /**
2020
- * @ignore
2021
- */
2022
- async _fetch(url) {
2023
- return fetchData2(url);
2024
- }
2025
- };
2026
- var NodeWasmFactory = class extends BaseWasmFactory {
2027
- /**
2028
- * @ignore
2029
- */
2030
- async _fetch(url) {
2031
- return fetchData2(url);
2032
- }
2033
- };
2034
-
2035
- export {
2036
- XfaText,
2037
- XfaLayer,
2038
- SVG_NS,
2039
- PixelsPerInch,
2040
- fetchData,
2041
- PageViewport,
2042
- RenderingCancelledException,
2043
- isDataScheme,
2044
- isPdfFile,
2045
- getFilenameFromUrl,
2046
- getPdfFilenameFromUrl,
2047
- StatTimer,
2048
- isValidFetchUrl,
2049
- noContextMenu,
2050
- stopEvent,
2051
- deprecated,
2052
- PDFDateString,
2053
- getXfaPageViewport,
2054
- getRGB,
2055
- getColorValues,
2056
- getCurrentTransform,
2057
- getCurrentTransformInverse,
2058
- setLayerDimensions,
2059
- OutputScale,
2060
- SupportedImageMimeTypes,
2061
- ColorScheme,
2062
- CSSConstants,
2063
- applyOpacity,
2064
- findContrastColor,
2065
- renderRichText,
2066
- DOMCMapReaderFactory,
2067
- BaseStandardFontDataFactory,
2068
- DOMStandardFontDataFactory,
2069
- DOMWasmFactory,
2070
- DOMCanvasFactory,
2071
- DOMFilterFactory,
2072
- canvasToData,
2073
- toDataUrl,
2074
- colorToRgb,
2075
- rgbToHex,
2076
- parseRgbaColor,
2077
- randomUUID,
2078
- filtersRegistry,
2079
- NodeFilterFactory,
2080
- NodeCanvasFactory,
2081
- fetchData2,
2082
- NodeCMapReaderFactory,
2083
- NodeStandardFontDataFactory,
2084
- NodeWasmFactory
2085
- };