use-pdf-renderer
Version:
React hook for rendering PDF files as images
84 lines (76 loc) • 1.39 MB
JavaScript
import { useState, useCallback } from 'react';
import * as pdfjs from 'pdfjs-dist';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
/**
* @licstart The following is the entire license notice for the
* JavaScript code in this page
*
* Copyright 2024 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @licend The above is the entire license notice for the
* JavaScript code in this page
*/var e={d:(t,i)=>{for(var a in i)e.o(i,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:i[a]});},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},__webpack_exports__ = globalThis.pdfjsWorker = {};e.d(__webpack_exports__,{WorkerMessageHandler:()=>WorkerMessageHandler});const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],a=[.001,0,0,.001,0,0],s=1.35,r=.35,n=.25925925925925924,g=1,o=2,c=4,C=8,h=16,l=64,Q=128,E=256,u="pdfjs_internal_editor_",d=3,f=9,p=13,m=15,y={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},w=0,D=4,b=1,F=2,S=3,k=1,R=2,N=3,G=4,M=5,U=6,x=7,L=8,H=9,J=10,Y=11,v=12,K=13,T=14,q=15,O=16,W=17,j=20,X="Group",Z="R",V=1,z=2,_=4,$=16,AA=32,eA=128,tA=512,iA=1,aA=2,sA=4096,rA=8192,nA=32768,gA=65536,oA=131072,IA=1048576,cA=2097152,CA=8388608,hA=16777216,lA=1,BA=2,QA=3,EA=4,uA=5,dA={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},fA={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},pA={O:"PageOpen",C:"PageClose"},mA=1,yA=5,wA=1,DA=2,bA=3,FA=4,SA=5,kA=6,RA=7,NA=8,GA=9,MA=10,UA=11,xA=12,LA=13,HA=14,JA=15,YA=16,vA=17,KA=18,TA=19,qA=20,OA=21,PA=22,WA=23,jA=24,XA=25,ZA=26,VA=27,zA=28,_A=29,$A=30,Ae=31,ee=32,te=33,ie=34,ae=35,se=36,re=37,ne=38,ge=39,oe=40,Ie=41,ce=42,Ce=43,he=44,le=45,Be=46,Qe=47,Ee=48,ue=49,de=50,fe=51,pe=52,me=53,ye=54,we=55,De=56,be=57,Fe=58,Se=59,ke=60,Re=61,Ne=62,Ge=63,Me=64,Ue=65,xe=66,Le=67,He=68,Je=69,Ye=70,ve=71,Ke=72,Te=73,qe=74,Oe=75,Pe=76,We=77,je=80,Xe=81,Ze=83,Ve=84,ze=85,_e=86,$e=87,At=88,et=89,tt=90,it=91,at=92,st=93,rt=1,nt=2;let gt=mA;function getVerbosityLevel(){return gt}function info(e){gt>=yA&&console.log(`Info: ${e}`);}function warn(e){gt>=mA&&console.log(`Warning: ${e}`);}function unreachable(e){throw new Error(e)}function assert(e,t){e||unreachable(t);}function createValidAbsoluteUrl(e,t=null,i=null){if(!e)return null;try{if(i&&"string"==typeof e){if(i.addDefaultProtocol&&e.startsWith("www.")){const t=e.match(/\./g);t?.length>=2&&(e=`http://${e}`);}if(i.tryConvertEncoding)try{e=stringToUTF8String(e);}catch{}}const a=t?new URL(e,t):new URL(e);if(function _isValidProtocol(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return !0;default:return !1}}(a))return a}catch{}return null}function shadow(e,t,i,a=!1){Object.defineProperty(e,t,{value:i,enumerable:!a,configurable:!0,writable:!1});return i}const ot=function BaseExceptionClosure(){function BaseException(e,t){this.message=e;this.name=t;}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends ot{constructor(e,t){super(e,"PasswordException");this.code=t;}}class UnknownErrorException extends ot{constructor(e,t){super(e,"UnknownErrorException");this.details=t;}}class InvalidPDFException extends ot{constructor(e){super(e,"InvalidPDFException");}}class MissingPDFException extends ot{constructor(e){super(e,"MissingPDFException");}}class UnexpectedResponseException extends ot{constructor(e,t){super(e,"UnexpectedResponseException");this.status=t;}}class FormatError extends ot{constructor(e){super(e,"FormatError");}}class AbortException extends ot{constructor(e){super(e,"AbortException");}}function bytesToString(e){"object"==typeof e&&void 0!==e?.length||unreachable("Invalid argument for bytesToString");const t=e.length,i=8192;if(t<i)return String.fromCharCode.apply(null,e);const a=[];for(let s=0;s<t;s+=i){const r=Math.min(s+i,t),n=e.subarray(s,r);a.push(String.fromCharCode.apply(null,n));}return a.join("")}function stringToBytes(e){"string"!=typeof e&&unreachable("Invalid argument for stringToBytes");const t=e.length,i=new Uint8Array(t);for(let a=0;a<t;++a)i[a]=255&e.charCodeAt(a);return i}function string32(e){return String.fromCharCode(e>>24&255,e>>16&255,e>>8&255,255&e)}function objectSize(e){return Object.keys(e).length}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const e=new Uint8Array(4);e[0]=1;return 1===new Uint32Array(e.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return !0}catch{return !1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get platform(){return "undefined"!=typeof navigator&&"string"==typeof navigator?.platform?shadow(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:"string"==typeof navigator?.userAgent&&navigator.userAgent.includes("Firefox")}):shadow(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const It=Array.from(Array(256).keys(),(e=>e.toString(16).padStart(2,"0")));class Util{static makeHexColor(e,t,i){return `#${It[e]}${It[t]}${It[i]}`}static scaleMinMax(e,t){let i;if(e[0]){if(e[0]<0){i=t[0];t[0]=t[2];t[2]=i;}t[0]*=e[0];t[2]*=e[0];if(e[3]<0){i=t[1];t[1]=t[3];t[3]=i;}t[1]*=e[3];t[3]*=e[3];}else {i=t[0];t[0]=t[1];t[1]=i;i=t[2];t[2]=t[3];t[3]=i;if(e[1]<0){i=t[1];t[1]=t[3];t[3]=i;}t[1]*=e[1];t[3]*=e[1];if(e[2]<0){i=t[0];t[0]=t[2];t[2]=i;}t[0]*=e[2];t[2]*=e[2];}t[0]+=e[4];t[1]+=e[5];t[2]+=e[4];t[3]+=e[5];}static transform(e,t){return [e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static applyTransform(e,t){return [e[0]*t[0]+e[1]*t[2]+t[4],e[0]*t[1]+e[1]*t[3]+t[5]]}static applyInverseTransform(e,t){const i=t[0]*t[3]-t[1]*t[2];return [(e[0]*t[3]-e[1]*t[2]+t[2]*t[5]-t[4]*t[3])/i,(-e[0]*t[1]+e[1]*t[0]+t[4]*t[1]-t[5]*t[0])/i]}static getAxialAlignedBoundingBox(e,t){const i=this.applyTransform(e,t),a=this.applyTransform(e.slice(2,4),t),s=this.applyTransform([e[0],e[3]],t),r=this.applyTransform([e[2],e[1]],t);return [Math.min(i[0],a[0],s[0],r[0]),Math.min(i[1],a[1],s[1],r[1]),Math.max(i[0],a[0],s[0],r[0]),Math.max(i[1],a[1],s[1],r[1])]}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return [e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e){const t=[e[0],e[2],e[1],e[3]],i=e[0]*t[0]+e[1]*t[2],a=e[0]*t[1]+e[1]*t[3],s=e[2]*t[0]+e[3]*t[2],r=e[2]*t[1]+e[3]*t[3],n=(i+r)/2,g=Math.sqrt((i+r)**2-4*(i*r-s*a))/2,o=n+g||1,c=n-g||1;return [Math.sqrt(o),Math.sqrt(c)]}static normalizeRect(e){const t=e.slice(0);if(e[0]>e[2]){t[0]=e[2];t[2]=e[0];}if(e[1]>e[3]){t[1]=e[3];t[3]=e[1];}return t}static intersect(e,t){const i=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),a=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(i>a)return null;const s=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),r=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return s>r?null:[i,s,a,r]}static#A(e,t,i,a,s,r,n,g,o,c){if(o<=0||o>=1)return;const C=1-o,h=o*o,l=h*o,Q=C*(C*(C*e+3*o*t)+3*h*i)+l*a,E=C*(C*(C*s+3*o*r)+3*h*n)+l*g;c[0]=Math.min(c[0],Q);c[1]=Math.min(c[1],E);c[2]=Math.max(c[2],Q);c[3]=Math.max(c[3],E);}static#e(e,t,i,a,s,r,n,g,o,c,C,h){if(Math.abs(o)<1e-12){Math.abs(c)>=1e-12&&this.#A(e,t,i,a,s,r,n,g,-C/c,h);return}const l=c**2-4*C*o;if(l<0)return;const Q=Math.sqrt(l),E=2*o;this.#A(e,t,i,a,s,r,n,g,(-c+Q)/E,h);this.#A(e,t,i,a,s,r,n,g,(-c-Q)/E,h);}static bezierBoundingBox(e,t,i,a,s,r,n,g,o){if(o){o[0]=Math.min(o[0],e,n);o[1]=Math.min(o[1],t,g);o[2]=Math.max(o[2],e,n);o[3]=Math.max(o[3],t,g);}else o=[Math.min(e,n),Math.min(t,g),Math.max(e,n),Math.max(t,g)];this.#e(e,i,s,n,t,a,r,g,3*(3*(i-s)-e+n),6*(e-2*i+s),3*(i-e),o);this.#e(e,i,s,n,t,a,r,g,3*(3*(a-r)-t+g),6*(t-2*a+r),3*(a-t),o);return o}}const ct=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function stringToPDFString(e){if(e[0]>="ï"){let t;if("þ"===e[0]&&"ÿ"===e[1]){t="utf-16be";e.length%2==1&&(e=e.slice(0,-1));}else if("ÿ"===e[0]&&"þ"===e[1]){t="utf-16le";e.length%2==1&&(e=e.slice(0,-1));}else "ï"===e[0]&&"»"===e[1]&&"¿"===e[2]&&(t="utf-8");if(t)try{const i=new TextDecoder(t,{fatal:!0}),a=stringToBytes(e),s=i.decode(a);return s.includes("")?s.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,""):s}catch(e){warn(`stringToPDFString: "${e}".`);}}const t=[];for(let i=0,a=e.length;i<a;i++){const s=e.charCodeAt(i);if(27===s){for(;++i<a&&27!==e.charCodeAt(i););continue}const r=ct[s];t.push(r?String.fromCharCode(r):e.charAt(i));}return t.join("")}function stringToUTF8String(e){return decodeURIComponent(escape(e))}function utf8StringToString(e){return unescape(encodeURIComponent(e))}function isArrayEqual(e,t){if(e.length!==t.length)return !1;for(let i=0,a=e.length;i<a;i++)if(e[i]!==t[i])return !1;return !0}function getModificationDate(e=new Date){return [e.getUTCFullYear().toString(),(e.getUTCMonth()+1).toString().padStart(2,"0"),e.getUTCDate().toString().padStart(2,"0"),e.getUTCHours().toString().padStart(2,"0"),e.getUTCMinutes().toString().padStart(2,"0"),e.getUTCSeconds().toString().padStart(2,"0")].join("")}let Ct=null,ht=null;function toHexUtil(e){return Uint8Array.prototype.toHex?e.toHex():Array.from(e,(e=>It[e])).join("")}"function"!=typeof Promise.try&&(Promise.try=function(e,...t){return new Promise((i=>{i(e(...t));}))});const lt=Symbol("CIRCULAR_REF"),Bt=Symbol("EOF");let Qt=Object.create(null),Et=Object.create(null),ut=Object.create(null);class Name{constructor(e){this.name=e;}static get(e){return Et[e]||=new Name(e)}}class Cmd{constructor(e){this.cmd=e;}static get(e){return Qt[e]||=new Cmd(e)}}const dt=function nonSerializableClosure(){return dt};class Dict{constructor(e=null){this._map=new Map;this.xref=e;this.objId=null;this.suppressEncryption=!1;this.__nonSerializable__=dt;}assignXref(e){this.xref=e;}get size(){return this._map.size}get(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i));}return a instanceof Ref&&this.xref?this.xref.fetch(a,this.suppressEncryption):a}async getAsync(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i));}return a instanceof Ref&&this.xref?this.xref.fetchAsync(a,this.suppressEncryption):a}getArray(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i));}a instanceof Ref&&this.xref&&(a=this.xref.fetch(a,this.suppressEncryption));if(Array.isArray(a)){a=a.slice();for(let e=0,t=a.length;e<t;e++)a[e]instanceof Ref&&this.xref&&(a[e]=this.xref.fetch(a[e],this.suppressEncryption));}return a}getRaw(e){return this._map.get(e)}getKeys(){return [...this._map.keys()]}getRawValues(){return [...this._map.values()]}set(e,t){this._map.set(e,t);}has(e){return this._map.has(e)}*[Symbol.iterator](){for(const[e,t]of this._map)yield [e,t instanceof Ref&&this.xref?this.xref.fetch(t,this.suppressEncryption):t];}static get empty(){const e=new Dict(null);e.set=(e,t)=>{unreachable("Should not call `set` on the empty dictionary.");};return shadow(this,"empty",e)}static merge({xref:e,dictArray:t,mergeSubDicts:i=!1}){const a=new Dict(e),s=new Map;for(const e of t)if(e instanceof Dict)for(const[t,a]of e._map){let e=s.get(t);if(void 0===e){e=[];s.set(t,e);}else if(!(i&&a instanceof Dict))continue;e.push(a);}for(const[t,i]of s){if(1===i.length||!(i[0]instanceof Dict)){a._map.set(t,i[0]);continue}const s=new Dict(e);for(const e of i)for(const[t,i]of e._map)s._map.has(t)||s._map.set(t,i);s.size>0&&a._map.set(t,s);}s.clear();return a.size>0?a:Dict.empty}clone(){const e=new Dict(this.xref);for(const t of this.getKeys())e.set(t,this.getRaw(t));return e}delete(e){delete this._map[e];}}class Ref{constructor(e,t){this.num=e;this.gen=t;}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(e){const t=ut[e];if(t)return t;const i=/^(\d+)R(\d*)$/.exec(e);return i&&"0"!==i[1]?ut[e]=new Ref(parseInt(i[1]),i[2]?parseInt(i[2]):0):null}static get(e,t){const i=0===t?`${e}R`:`${e}R${t}`;return ut[i]||=new Ref(e,t)}}class RefSet{constructor(e=null){this._set=new Set(e?._set);}has(e){return this._set.has(e.toString())}put(e){this._set.add(e.toString());}remove(e){this._set.delete(e.toString());}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear();}}class RefSetCache{constructor(){this._map=new Map;}get size(){return this._map.size}get(e){return this._map.get(e.toString())}has(e){return this._map.has(e.toString())}put(e,t){this._map.set(e.toString(),t);}putAlias(e,t){this._map.set(e.toString(),this.get(t));}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear();}*values(){yield*this._map.values();}*items(){for(const[e,t]of this._map)yield [Ref.fromString(e),t];}}function isName(e,t){return e instanceof Name&&(void 0===t||e.name===t)}function isCmd(e,t){return e instanceof Cmd&&(void 0===t||e.cmd===t)}function isDict(e,t){return e instanceof Dict&&(void 0===t||isName(e.get("Type"),t))}function isRefsEqual(e,t){return e.num===t.num&&e.gen===t.gen}class BaseStream{get length(){unreachable("Abstract getter `length` accessed");}get isEmpty(){unreachable("Abstract getter `isEmpty` accessed");}get isDataLoaded(){return shadow(this,"isDataLoaded",!0)}getByte(){unreachable("Abstract method `getByte` called");}getBytes(e){unreachable("Abstract method `getBytes` called");}async getImageData(e,t){return this.getBytes(e,t)}async asyncGetBytes(){unreachable("Abstract method `asyncGetBytes` called");}get isAsync(){return !1}get canAsyncDecodeImageFromBuffer(){return !1}async getTransferableImage(){return null}peekByte(){const e=this.getByte();-1!==e&&this.pos--;return e}peekBytes(e){const t=this.getBytes(e);this.pos-=t.length;return t}getUint16(){const e=this.getByte(),t=this.getByte();return -1===e||-1===t?-1:(e<<8)+t}getInt32(){return (this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(e,t){unreachable("Abstract method `getByteRange` called");}getString(e){return bytesToString(this.getBytes(e))}skip(e){this.pos+=e||1;}reset(){unreachable("Abstract method `reset` called");}moveStart(){unreachable("Abstract method `moveStart` called");}makeSubStream(e,t,i=null){unreachable("Abstract method `makeSubStream` called");}getBaseStreams(){return null}}const ft=/^[1-9]\.\d$/,pt=2**31-1;function getLookupTableFactory(e){let t;return function(){if(e){t=Object.create(null);e(t);e=null;}return t}}class MissingDataException extends ot{constructor(e,t){super(`Missing data [${e}, ${t})`,"MissingDataException");this.begin=e;this.end=t;}}class ParserEOFException extends ot{constructor(e){super(e,"ParserEOFException");}}class XRefEntryException extends ot{constructor(e){super(e,"XRefEntryException");}}class XRefParseException extends ot{constructor(e){super(e,"XRefParseException");}}function arrayBuffersToBytes(e){const t=e.length;if(0===t)return new Uint8Array(0);if(1===t)return new Uint8Array(e[0]);let i=0;for(let a=0;a<t;a++)i+=e[a].byteLength;const a=new Uint8Array(i);let s=0;for(let i=0;i<t;i++){const t=new Uint8Array(e[i]);a.set(t,s);s+=t.byteLength;}return a}function getInheritableProperty({dict:e,key:t,getArray:i=!1,stopWhenFound:a=!0}){let s;const r=new RefSet;for(;e instanceof Dict&&(!e.objId||!r.has(e.objId));){e.objId&&r.put(e.objId);const n=i?e.getArray(t):e.get(t);if(void 0!==n){if(a)return n;(s||=[]).push(n);}e=e.get("Parent");}return s}const mt=["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM","","X","XX","XXX","XL","L","LX","LXX","LXXX","XC","","I","II","III","IV","V","VI","VII","VIII","IX"];function toRomanNumerals(e,t=!1){assert(Number.isInteger(e)&&e>0,"The number should be a positive integer.");const i="M".repeat(e/1e3|0)+mt[e%1e3/100|0]+mt[10+(e%100/10|0)]+mt[20+e%10];return t?i.toLowerCase():i}function log2(e){return e>0?Math.ceil(Math.log2(e)):0}function readInt8(e,t){return e[t]<<24>>24}function readUint16(e,t){return e[t]<<8|e[t+1]}function readUint32(e,t){return (e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function isWhiteSpace(e){return 32===e||9===e||13===e||10===e}function isNumberArray(e,t){return Array.isArray(e)?(null===t||e.length===t)&&e.every((e=>"number"==typeof e)):ArrayBuffer.isView(e)&&(0===e.length||"number"==typeof e[0])&&(null===t||e.length===t)}function lookupMatrix(e,t){return isNumberArray(e,6)?e:t}function lookupRect(e,t){return isNumberArray(e,4)?e:t}function lookupNormalRect(e,t){return isNumberArray(e,4)?Util.normalizeRect(e):t}function parseXFAPath(e){const t=/(.+)\[(\d+)\]$/;return e.split(".").map((e=>{const i=e.match(t);return i?{name:i[1],pos:parseInt(i[2],10)}:{name:e,pos:0}}))}function escapePDFName(e){const t=[];let i=0;for(let a=0,s=e.length;a<s;a++){const s=e.charCodeAt(a);if(s<33||s>126||35===s||40===s||41===s||60===s||62===s||91===s||93===s||123===s||125===s||47===s||37===s){i<a&&t.push(e.substring(i,a));t.push(`#${s.toString(16)}`);i=a+1;}}if(0===t.length)return e;i<e.length&&t.push(e.substring(i,e.length));return t.join("")}function escapeString(e){return e.replaceAll(/([()\\\n\r])/g,(e=>"\n"===e?"\\n":"\r"===e?"\\r":`\\${e}`))}function _collectJS(e,t,i,a){if(!e)return;let s=null;if(e instanceof Ref){if(a.has(e))return;s=e;a.put(s);e=t.fetch(e);}if(Array.isArray(e))for(const s of e)_collectJS(s,t,i,a);else if(e instanceof Dict){if(isName(e.get("S"),"JavaScript")){const t=e.get("JS");let a;t instanceof BaseStream?a=t.getString():"string"==typeof t&&(a=t);a&&=stringToPDFString(a).replaceAll("\0","");a&&i.push(a);}_collectJS(e.getRaw("Next"),t,i,a);}s&&a.remove(s);}function collectActions(e,t,i){const a=Object.create(null),s=getInheritableProperty({dict:t,key:"AA",stopWhenFound:!1});if(s)for(let t=s.length-1;t>=0;t--){const r=s[t];if(r instanceof Dict)for(const t of r.getKeys()){const s=i[t];if(!s)continue;const n=[];_collectJS(r.getRaw(t),e,n,new RefSet);n.length>0&&(a[s]=n);}}if(t.has("A")){const i=[];_collectJS(t.get("A"),e,i,new RefSet);i.length>0&&(a.Action=i);}return objectSize(a)>0?a:null}const yt={60:"<",62:">",38:"&",34:""",39:"'"};function*codePointIter(e){for(let t=0,i=e.length;t<i;t++){const i=e.codePointAt(t);i>55295&&(i<57344||i>65533)&&t++;yield i;}}function encodeToXmlString(e){const t=[];let i=0;for(let a=0,s=e.length;a<s;a++){const s=e.codePointAt(a);if(32<=s&&s<=126){const r=yt[s];if(r){i<a&&t.push(e.substring(i,a));t.push(r);i=a+1;}}else {i<a&&t.push(e.substring(i,a));t.push(`&#x${s.toString(16).toUpperCase()};`);s>55295&&(s<57344||s>65533)&&a++;i=a+1;}}if(0===t.length)return e;i<e.length&&t.push(e.substring(i,e.length));return t.join("")}function validateFontName(e,t=!1){const i=/^("|').*("|')$/.exec(e);if(i&&i[1]===i[2]){if(new RegExp(`[^\\\\]${i[1]}`).test(e.slice(1,-1))){t&&warn(`FontFamily contains unescaped ${i[1]}: ${e}.`);return !1}}else for(const i of e.split(/[ \t]+/))if(/^(\d|(-(\d|-)))/.test(i)||!/^[\w-\\]+$/.test(i)){t&&warn(`FontFamily contains invalid <custom-ident>: ${e}.`);return !1}return !0}function validateCSSFont(e){const t=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:i,fontWeight:a,italicAngle:s}=e;if(!validateFontName(i,!0))return !1;const r=a?a.toString():"";e.fontWeight=t.has(r)?r:"400";const n=parseFloat(s);e.italicAngle=isNaN(n)||n<-90||n>90?"14":s.toString();return !0}function recoverJsURL(e){const t=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(e);return t?.[2]?{url:t[2],newWindow:"app.launchURL"===t[1]&&"true"===t[3]}:null}function numberToString(e){if(Number.isInteger(e))return e.toString();const t=Math.round(100*e);return t%100==0?(t/100).toString():t%10==0?e.toFixed(1):e.toFixed(2)}function getNewAnnotationsMap(e){if(!e)return null;const t=new Map;for(const[i,a]of e){if(!i.startsWith(u))continue;let e=t.get(a.pageIndex);if(!e){e=[];t.set(a.pageIndex,e);}e.push(a);}return t.size>0?t:null}function stringToAsciiOrUTF16BE(e){return function isAscii(e){return /^[\x00-\x7F]*$/.test(e)}(e)?e:stringToUTF16String(e,!0)}function stringToUTF16HexString(e){const t=[];for(let i=0,a=e.length;i<a;i++){const a=e.charCodeAt(i);t.push(It[a>>8&255],It[255&a]);}return t.join("")}function stringToUTF16String(e,t=!1){const i=[];t&&i.push("þÿ");for(let t=0,a=e.length;t<a;t++){const a=e.charCodeAt(t);i.push(String.fromCharCode(a>>8&255),String.fromCharCode(255&a));}return i.join("")}function getRotationMatrix(e,t,i){switch(e){case 90:return [0,1,-1,0,t,0];case 180:return [-1,0,0,-1,t,i];case 270:return [0,-1,1,0,0,i];default:throw new Error("Invalid rotation")}}function getSizeInBytes(e){return Math.ceil(Math.ceil(Math.log2(1+e))/8)}class Stream extends BaseStream{constructor(e,t,i,a){super();this.bytes=e instanceof Uint8Array?e:new Uint8Array(e);this.start=t||0;this.pos=this.start;this.end=t+i||this.bytes.length;this.dict=a;}get length(){return this.end-this.start}get isEmpty(){return 0===this.length}getByte(){return this.pos>=this.end?-1:this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e)return t.subarray(i,a);let s=i+e;s>a&&(s=a);this.pos=s;return t.subarray(i,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);return this.bytes.subarray(e,t)}reset(){this.pos=this.start;}moveStart(){this.start=this.pos;}makeSubStream(e,t,i=null){return new Stream(this.bytes.buffer,e,t,i)}}class StringStream extends Stream{constructor(e){super(stringToBytes(e));}}class NullStream extends Stream{constructor(){super(new Uint8Array(0));}}class ChunkedStream extends Stream{constructor(e,t,i){super(new Uint8Array(e),0,e,null);this.chunkSize=t;this._loadedChunks=new Set;this.numChunks=Math.ceil(e/t);this.manager=i;this.progressiveDataLength=0;this.lastSuccessfulEnsureByteChunk=-1;}getMissingChunks(){const e=[];for(let t=0,i=this.numChunks;t<i;++t)this._loadedChunks.has(t)||e.push(t);return e}get numChunksLoaded(){return this._loadedChunks.size}get isDataLoaded(){return this.numChunksLoaded===this.numChunks}onReceiveData(e,t){const i=this.chunkSize;if(e%i!=0)throw new Error(`Bad begin offset: ${e}`);const a=e+t.byteLength;if(a%i!=0&&a!==this.bytes.length)throw new Error(`Bad end offset: ${a}`);this.bytes.set(new Uint8Array(t),e);const s=Math.floor(e/i),r=Math.floor((a-1)/i)+1;for(let e=s;e<r;++e)this._loadedChunks.add(e);}onReceiveProgressiveData(e){let t=this.progressiveDataLength;const i=Math.floor(t/this.chunkSize);this.bytes.set(new Uint8Array(e),t);t+=e.byteLength;this.progressiveDataLength=t;const a=t>=this.end?this.numChunks:Math.floor(t/this.chunkSize);for(let e=i;e<a;++e)this._loadedChunks.add(e);}ensureByte(e){if(e<this.progressiveDataLength)return;const t=Math.floor(e/this.chunkSize);if(!(t>this.numChunks)&&t!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(t))throw new MissingDataException(e,e+1);this.lastSuccessfulEnsureByteChunk=t;}}ensureRange(e,t){if(e>=t)return;if(t<=this.progressiveDataLength)return;const i=Math.floor(e/this.chunkSize);if(i>this.numChunks)return;const a=Math.min(Math.floor((t-1)/this.chunkSize)+1,this.numChunks);for(let s=i;s<a;++s)if(!this._loadedChunks.has(s))throw new MissingDataException(e,t)}nextEmptyChunk(e){const t=this.numChunks;for(let i=0;i<t;++i){const a=(e+i)%t;if(!this._loadedChunks.has(a))return a}return null}hasChunk(e){return this._loadedChunks.has(e)}getByte(){const e=this.pos;if(e>=this.end)return -1;e>=this.progressiveDataLength&&this.ensureByte(e);return this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e){a>this.progressiveDataLength&&this.ensureRange(i,a);return t.subarray(i,a)}let s=i+e;s>a&&(s=a);s>this.progressiveDataLength&&this.ensureRange(i,s);this.pos=s;return t.subarray(i,s)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);t>this.progressiveDataLength&&this.ensureRange(e,t);return this.bytes.subarray(e,t)}makeSubStream(e,t,i=null){t?e+t>this.progressiveDataLength&&this.ensureRange(e,e+t):e>=this.progressiveDataLength&&this.ensureByte(e);function ChunkedStreamSubstream(){}ChunkedStreamSubstream.prototype=Object.create(this);ChunkedStreamSubstream.prototype.getMissingChunks=function(){const e=this.chunkSize,t=Math.floor(this.start/e),i=Math.floor((this.end-1)/e)+1,a=[];for(let e=t;e<i;++e)this._loadedChunks.has(e)||a.push(e);return a};Object.defineProperty(ChunkedStreamSubstream.prototype,"isDataLoaded",{get(){return this.numChunksLoaded===this.numChunks||0===this.getMissingChunks().length},configurable:!0});const a=new ChunkedStreamSubstream;a.pos=a.start=e;a.end=e+t||this.end;a.dict=i;return a}getBaseStreams(){return [this]}}class ChunkedStreamManager{constructor(e,t){this.length=t.length;this.chunkSize=t.rangeChunkSize;this.stream=new ChunkedStream(this.length,this.chunkSize,this);this.pdfNetworkStream=e;this.disableAutoFetch=t.disableAutoFetch;this.msgHandler=t.msgHandler;this.currRequestId=0;this._chunksNeededByRequest=new Map;this._requestsByChunk=new Map;this._promisesByRequest=new Map;this.progressiveDataLength=0;this.aborted=!1;this._loadedStreamCapability=Promise.withResolvers();}sendRequest(e,t){const i=this.pdfNetworkStream.getRangeReader(e,t);i.isStreamingSupported||(i.onProgress=this.onProgress.bind(this));let a=[],s=0;return new Promise(((e,t)=>{const readChunk=({value:r,done:n})=>{try{if(n){const t=arrayBuffersToBytes(a);a=null;e(t);return}s+=r.byteLength;i.isStreamingSupported&&this.onProgress({loaded:s});a.push(r);i.read().then(readChunk,t);}catch(e){t(e);}};i.read().then(readChunk,t);})).then((t=>{this.aborted||this.onReceiveData({chunk:t,begin:e});}))}requestAllChunks(e=!1){if(!e){const e=this.stream.getMissingChunks();this._requestChunks(e);}return this._loadedStreamCapability.promise}_requestChunks(e){const t=this.currRequestId++,i=new Set;this._chunksNeededByRequest.set(t,i);for(const t of e)this.stream.hasChunk(t)||i.add(t);if(0===i.size)return Promise.resolve();const a=Promise.withResolvers();this._promisesByRequest.set(t,a);const s=[];for(const e of i){let i=this._requestsByChunk.get(e);if(!i){i=[];this._requestsByChunk.set(e,i);s.push(e);}i.push(t);}if(s.length>0){const e=this.groupChunks(s);for(const t of e){const e=t.beginChunk*this.chunkSize,i=Math.min(t.endChunk*this.chunkSize,this.length);this.sendRequest(e,i).catch(a.reject);}}return a.promise.catch((e=>{if(!this.aborted)throw e}))}getStream(){return this.stream}requestRange(e,t){t=Math.min(t,this.length);const i=this.getBeginChunk(e),a=this.getEndChunk(t),s=[];for(let e=i;e<a;++e)s.push(e);return this._requestChunks(s)}requestRanges(e=[]){const t=[];for(const i of e){const e=this.getBeginChunk(i.begin),a=this.getEndChunk(i.end);for(let i=e;i<a;++i)t.includes(i)||t.push(i);}t.sort((function(e,t){return e-t}));return this._requestChunks(t)}groupChunks(e){const t=[];let i=-1,a=-1;for(let s=0,r=e.length;s<r;++s){const r=e[s];i<0&&(i=r);if(a>=0&&a+1!==r){t.push({beginChunk:i,endChunk:a+1});i=r;}s+1===e.length&&t.push({beginChunk:i,endChunk:r+1});a=r;}return t}onProgress(e){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+e.loaded,total:this.length});}onReceiveData(e){const t=e.chunk,i=void 0===e.begin,a=i?this.progressiveDataLength:e.begin,s=a+t.byteLength,r=Math.floor(a/this.chunkSize),n=s<this.length?Math.floor(s/this.chunkSize):Math.ceil(s/this.chunkSize);if(i){this.stream.onReceiveProgressiveData(t);this.progressiveDataLength=s;}else this.stream.onReceiveData(a,t);this.stream.isDataLoaded&&this._loadedStreamCapability.resolve(this.stream);const g=[];for(let e=r;e<n;++e){const t=this._requestsByChunk.get(e);if(t){this._requestsByChunk.delete(e);for(const i of t){const t=this._chunksNeededByRequest.get(i);t.has(e)&&t.delete(e);t.size>0||g.push(i);}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let e;if(1===this.stream.numChunksLoaded){const t=this.stream.numChunks-1;this.stream.hasChunk(t)||(e=t);}else e=this.stream.nextEmptyChunk(n);Number.isInteger(e)&&this._requestChunks([e]);}for(const e of g){const t=this._promisesByRequest.get(e);this._promisesByRequest.delete(e);t.resolve();}this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize,total:this.length});}onError(e){this._loadedStreamCapability.reject(e);}getBeginChunk(e){return Math.floor(e/this.chunkSize)}getEndChunk(e){return Math.floor((e-1)/this.chunkSize)+1}abort(e){this.aborted=!0;this.pdfNetworkStream?.cancelAllRequests(e);for(const t of this._promisesByRequest.values())t.reject(e);}}class ColorSpace{constructor(e,t){this.name=e;this.numComps=t;}getRgb(e,t){const i=new Uint8ClampedArray(3);this.getRgbItem(e,t,i,0);return i}getRgbItem(e,t,i,a){unreachable("Should not call ColorSpace.getRgbItem");}getRgbBuffer(e,t,i,a,s,r,n){unreachable("Should not call ColorSpace.getRgbBuffer");}getOutputLength(e,t){unreachable("Should not call ColorSpace.getOutputLength");}isPassthrough(e){return !1}isDefaultDecode(e,t){return ColorSpace.isDefaultDecode(e,this.numComps)}fillRgb(e,t,i,a,s,r,n,g,o){const c=t*i;let C=null;const h=1<<n,l=i!==s||t!==a;if(this.isPassthrough(n))C=g;else if(1===this.numComps&&c>h&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const t=n<=8?new Uint8Array(h):new Uint16Array(h);for(let e=0;e<h;e++)t[e]=e;const i=new Uint8ClampedArray(3*h);this.getRgbBuffer(t,0,h,i,0,n,0);if(l){C=new Uint8Array(3*c);let e=0;for(let t=0;t<c;++t){const a=3*g[t];C[e++]=i[a];C[e++]=i[a+1];C[e++]=i[a+2];}}else {let t=0;for(let a=0;a<c;++a){const s=3*g[a];e[t++]=i[s];e[t++]=i[s+1];e[t++]=i[s+2];t+=o;}}}else if(l){C=new Uint8ClampedArray(3*c);this.getRgbBuffer(g,0,c,C,0,n,0);}else this.getRgbBuffer(g,0,a*r,e,0,n,o);if(C)if(l)!function resizeRgbImage(e,t,i,a,s,r,n){n=1!==n?0:n;const g=i/s,o=a/r;let c,C=0;const h=new Uint16Array(s),l=3*i;for(let e=0;e<s;e++)h[e]=3*Math.floor(e*g);for(let i=0;i<r;i++){const a=Math.floor(i*o)*l;for(let i=0;i<s;i++){c=a+h[i];t[C++]=e[c++];t[C++]=e[c++];t[C++]=e[c++];C+=n;}}}(C,e,t,i,a,s,o);else {let t=0,i=0;for(let s=0,n=a*r;s<n;s++){e[t++]=C[i++];e[t++]=C[i++];e[t++]=C[i++];t+=o;}}}get usesZeroToOneRange(){return shadow(this,"usesZeroToOneRange",!0)}static _cache(e,t,i,a){if(!i)throw new Error('ColorSpace._cache - expected "localColorSpaceCache" argument.');if(!a)throw new Error('ColorSpace._cache - expected "parsedColorSpace" argument.');let s,r;if(e instanceof Ref){r=e;e=t.fetch(e);}e instanceof Name&&(s=e.name);(s||r)&&i.set(s,r,a);}static getCached(e,t,i){if(!i)throw new Error('ColorSpace.getCached - expected "localColorSpaceCache" argument.');if(e instanceof Ref){const a=i.getByRef(e);if(a)return a;try{e=t.fetch(e);}catch(e){if(e instanceof MissingDataException)throw e}}if(e instanceof Name){const t=i.getByName(e.name);if(t)return t}return null}static async parseAsync({cs:e,xref:t,resources:i=null,pdfFunctionFactory:a,localColorSpaceCache:s}){const r=this._parse(e,t,i,a);this._cache(e,t,s,r);return r}static parse({cs:e,xref:t,resources:i=null,pdfFunctionFactory:a,localColorSpaceCache:s}){const r=this.getCached(e,t,s);if(r)return r;const n=this._parse(e,t,i,a);this._cache(e,t,s,n);return n}static _parse(e,t,i=null,a){if((e=t.fetchIfRef(e))instanceof Name)switch(e.name){case"G":case"DeviceGray":return this.singletons.gray;case"RGB":case"DeviceRGB":return this.singletons.rgb;case"DeviceRGBA":return this.singletons.rgba;case"CMYK":case"DeviceCMYK":return this.singletons.cmyk;case"Pattern":return new PatternCS(null);default:if(i instanceof Dict){const s=i.get("ColorSpace");if(s instanceof Dict){const r=s.get(e.name);if(r){if(r instanceof Name)return this._parse(r,t,i,a);e=r;break}}}warn(`Unrecognized ColorSpace: ${e.name}`);return this.singletons.gray}if(Array.isArray(e)){const s=t.fetchIfRef(e[0]).name;let r,n,g,o,c,C;switch(s){case"G":case"DeviceGray":return this.singletons.gray;case"RGB":case"DeviceRGB":return this.singletons.rgb;case"CMYK":case"DeviceCMYK":return this.singletons.cmyk;case"CalGray":r=t.fetchIfRef(e[1]);o=r.getArray("WhitePoint");c=r.getArray("BlackPoint");C=r.get("Gamma");return new CalGrayCS(o,c,C);case"CalRGB":r=t.fetchIfRef(e[1]);o=r.getArray("WhitePoint");c=r.getArray("BlackPoint");C=r.getArray("Gamma");const h=r.getArray("Matrix");return new CalRGBCS(o,c,C,h);case"ICCBased":const l=t.fetchIfRef(e[1]).dict;n=l.get("N");const Q=l.get("Alternate");if(Q){const e=this._parse(Q,t,i,a);if(e.numComps===n)return e;warn("ICCBased color space: Ignoring incorrect /Alternate entry.");}if(1===n)return this.singletons.gray;if(3===n)return this.singletons.rgb;if(4===n)return this.singletons.cmyk;break;case"Pattern":g=e[1]||null;g&&(g=this._parse(g,t,i,a));return new PatternCS(g);case"I":case"Indexed":g=this._parse(e[1],t,i,a);const E=Math.max(0,Math.min(t.fetchIfRef(e[2]),255)),u=t.fetchIfRef(e[3]);return new IndexedCS(g,E,u);case"Separation":case"DeviceN":const d=t.fetchIfRef(e[1]);n=Array.isArray(d)?d.length:1;g=this._parse(e[2],t,i,a);const f=a.create(e[3]);return new AlternateCS(n,g,f);case"Lab":r=t.fetchIfRef(e[1]);o=r.getArray("WhitePoint");c=r.getArray("BlackPoint");const p=r.getArray("Range");return new LabCS(o,c,p);default:warn(`Unimplemented ColorSpace object: ${s}`);return this.singletons.gray}}warn(`Unrecognized ColorSpace object: ${e}`);return this.singletons.gray}static isDefaultDecode(e,t){if(!Array.isArray(e))return !0;if(2*t!==e.length){warn("The decode map is not the correct length");return !0}for(let t=0,i=e.length;t<i;t+=2)if(0!==e[t]||1!==e[t+1])return !1;return !0}static get singletons(){return shadow(this,"singletons",{get gray(){return shadow(this,"gray",new DeviceGrayCS)},get rgb(){return shadow(this,"rgb",new DeviceRgbCS)},get rgba(){return shadow(this,"rgba",new DeviceRgbaCS)},get cmyk(){return shadow(this,"cmyk",new DeviceCmykCS)}})}}class AlternateCS extends ColorSpace{constructor(e,t,i){super("Alternate",e);this.base=t;this.tintFn=i;this.tmpBuf=new Float32Array(t.numComps);}getRgbItem(e,t,i,a){const s=this.tmpBuf;this.tintFn(e,t,s,0);this.base.getRgbItem(s,0,i,a);}getRgbBuffer(e,t,i,a,s,r,n){const g=this.tintFn,o=this.base,c=1/((1<<r)-1),C=o.numComps,h=o.usesZeroToOneRange,l=(o.isPassthrough(8)||!h)&&0===n;let Q=l?s:0;const E=l?a:new Uint8ClampedArray(C*i),u=this.numComps,d=new Float32Array(u),f=new Float32Array(C);let p,m;for(p=0;p<i;p++){for(m=0;m<u;m++)d[m]=e[t++]*c;g(d,0,f,0);if(h)for(m=0;m<C;m++)E[Q++]=255*f[m];else {o.getRgbItem(f,0,E,Q);Q+=C;}}l||o.getRgbBuffer(E,0,i,a,s,8,n);}getOutputLength(e,t){return this.base.getOutputLength(e*this.base.numComps/this.numComps,t)}}class PatternCS extends ColorSpace{constructor(e){super("Pattern",null);this.base=e;}isDefaultDecode(e,t){unreachable("Should not call PatternCS.isDefaultDecode");}}class IndexedCS extends ColorSpace{constructor(e,t,i){super("Indexed",1);this.base=e;const a=e.numComps*(t+1);this.lookup=new Uint8Array(a);if(i instanceof BaseStream){const e=i.getBytes(a);this.lookup.set(e);}else {if("string"!=typeof i)throw new FormatError(`IndexedCS - unrecognized lookup table: ${i}`);for(let e=0;e<a;++e)this.lookup[e]=255&i.charCodeAt(e);}}getRgbItem(e,t,i,a){const s=this.base.numComps,r=e[t]*s;this.base.getRgbBuffer(this.lookup,r,1,i,a,8,0);}getRgbBuffer(e,t,i,a,s,r,n){const g=this.base,o=g.numComps,c=g.getOutputLength(o,n),C=this.lookup;for(let r=0;r<i;++r){const i=e[t++]*o;g.getRgbBuffer(C,i,1,a,s,8,n);s+=c;}}getOutputLength(e,t){return this.base.getOutputLength(e*this.base.numComps,t)}isDefaultDecode(e,t){if(!Array.isArray(e))return !0;if(2!==e.length){warn("Decode map length is not correct");return !0}if(!Number.isInteger(t)||t<1){warn("Bits per component is not correct");return !0}return 0===e[0]&&e[1]===(1<<t)-1}}class DeviceGrayCS extends ColorSpace{constructor(){super("DeviceGray",1);}getRgbItem(e,t,i,a){const s=255*e[t];i[a]=i[a+1]=i[a+2]=s;}getRgbBuffer(e,t,i,a,s,r,n){const g=255/((1<<r)-1);let o=t,c=s;for(let t=0;t<i;++t){const t=g*e[o++];a[c++]=t;a[c++]=t;a[c++]=t;c+=n;}}getOutputLength(e,t){return e*(3+t)}}class DeviceRgbCS extends ColorSpace{constructor(){super("DeviceRGB",3);}getRgbItem(e,t,i,a){i[a]=255*e[t];i[a+1]=255*e[t+1];i[a+2]=255*e[t+2];}getRgbBuffer(e,t,i,a,s,r,n){if(8===r&&0===n){a.set(e.subarray(t,t+3*i),s);return}const g=255/((1<<r)-1);let o=t,c=s;for(let t=0;t<i;++t){a[c++]=g*e[o++];a[c++]=g*e[o++];a[c++]=g*e[o++];c+=n;}}getOutputLength(e,t){return e*(3+t)/3|0}isPassthrough(e){return 8===e}}class DeviceRgbaCS extends ColorSpace{constructor(){super("DeviceRGBA",4);}getOutputLength(e,t){return 4*e}isPassthrough(e){return 8===e}fillRgb(e,t,i,a,s,r,n,g,o){i!==s||t!==a?function resizeRgbaImage(e,t,i,a,s,r,n){const g=i/s,o=a/r;let c=0;const C=new Uint16Array(s);if(1===n){for(let e=0;e<s;e++)C[e]=Math.floor(e*g);const a=new Uint32Array(e.buffer),n=new Uint32Array(t.buffer),h=FeatureTest.isLittleEndian?16777215:4294967040;for(let e=0;e<r;e++){const t=a.subarray(Math.floor(e*o)*i);for(let e=0;e<s;e++)n[c++]|=t[C[e]]&h;}}else {const a=4,n=i*a;for(let e=0;e<s;e++)C[e]=Math.floor(e*g)*a;for(let i=0;i<r;i++){const a=e.subarray(Math.floor(i*o)*n);for(let e=0;e<s;e++){const i=C[e];t[c++]=a[i];t[c++]=a[i+1];t[c++]=a[i+2];}}}}(g,e,t,i,a,s,o):function copyRgbaImage(e,t,i){if(1===i){const i=new Uint32Array(e.buffer),a=new Uint32Array(t.buffer),s=FeatureTest.isLittleEndian?16777215:4294967040;for(let e=0,t=i.length;e<t;e++)a[e]|=i[e]&s;}else {let i=0;for(let a=0,s=e.length;a<s;a+=4){t[i++]=e[a];t[i++]=e[a+1];t[i++]=e[a+2];}}}(g,e,o);}}class DeviceCmykCS extends ColorSpace{constructor(){super("DeviceCMYK",4);}#t(e,t,i,a,s){const r=e[t]*i,n=e[t+1]*i,g=e[t+2]*i,o=e[t+3]*i;a[s]=255+r*(-4.387332384609988*r+54.48615194189176*n+18.82290502165302*g+212.25662451639585*o-285.2331026137004)+n*(1.7149763477362134*n-5.6096736904047315*g+-17.873870861415444*o-5.497006427196366)+g*(-2.5217340131683033*g-21.248923337353073*o+17.5119270841813)+o*(-21.86122147463605*o-189.48180835922747);a[s+1]=255+r*(8.841041422036149*r+60.118027045597366*n+6.871425592049007*g+31.159100130055922*o-79.2970844816548)+n*(-15.310361306967817*n+17.575251261109482*g+131.35250912493976*o-190.9453302588951)+g*(4.444339102852739*g+9.8632861493405*o-24.86741582555878)+o*(-20.737325471181034*o-187.80453709719578);a[s+2]=255+r*(.8842522430003296*r+8.078677503112928*n+30.89978309703729*g-.23883238689178934*o-14.183576799673286)+n*(10.49593273432072*n+63.02378494754052*g+50.606957656360734*o-112.23884253719248)+g*(.03296041114873217*g+115.60384449646641*o-193.58209356861505)+o*(-22.33816807309886*o-180.12613974708367);}getRgbItem(e,t,i,a){this.#t(e,t,1,i,a);}getRgbBuffer(e,t,i,a,s,r,n){const g=1/((1<<r)-1);for(let r=0;r<i;r++){this.#t(e,t,g,a,s);t+=4;s+=3+n;}}getOutputLength(e,t){return e/4*(3+t)|0}}class CalGrayCS extends ColorSpace{constructor(e,t,i){super("CalGray",1);if(!e)throw new FormatError("WhitePoint missing - required for color space CalGray");[this.XW,this.YW,this.ZW]=e;[this.XB,this.YB,this.ZB]=t||[0,0,0];this.G=i||1;if(this.XW<0||this.ZW<0||1!==this.YW)throw new FormatError(`Invalid WhitePoint components for ${this.name}, no fallback available`);if(this.XB<0||this.YB<0||this.ZB<0){info(`Invalid BlackPoint for ${this.name}, falling back to default.`);this.XB=this.YB=this.ZB=0;}0===this.XB&&0===this.YB&&0===this.ZB||warn(`${this.name}, BlackPoint: XB: ${this.XB}, YB: ${this.YB}, ZB: ${this.ZB}, only default values are supported.`);if(this.G<1){info(`Invalid Gamma: ${this.G} for ${this.name}, falling back to default.`);this.G=1;}}#t(e,t,i,a,s){const r=(e[t]*s)**this.G,n=this.YW*r,g=Math.max(295.8*n**.3333333333333333-40.8,0);i[a]=g;i[a+1]=g;i[a+2]=g;}getRgbItem(e,t,i,a){this.#t(e,t,i,a,1);}getRgbBuffer(e,t,i,a,s,r,n){const g=1/((1<<r)-1);for(let r=0;r<i;++r){this.#t(e,t,a,s,g);t+=1;s+=3+n;}}getOutputLength(e,t){return e*(3+t)}}class CalRGBCS extends ColorSpace{static#i=new Float32Array([.8951,.2664,-.1614,-.7502,1.7135,.0367,.0389,-.0685,1.0296]);static#a=new Float32Array([.9869929,-.1470543,.1599627,.4323053,.5183603,.0492912,-.0085287,.0400428,.9684867]);static#s=new Float32Array([3.2404542,-1.5371385,-.4985314,-.969266,1.8760108,.041556,.0556434,-.2040259,1.0572252]);static#r=new Float32Array([1,1,1]);static#n=new Float32Array(3);static#g=new Float32Array(3);static#o=new Float32Array(3);static#I=(24/116)**3/8;constructor(e,t,i,a){super("CalRGB",3);if(!e)throw new FormatError("WhitePoint missing - required for color space CalRGB");const[s,r,n]=this.whitePoint=e,[g,o,c]=this.blackPoint=t||new Float32Array(3);[this.GR,this.GG,this.GB]=i||new Float32Array([1,1,1]);[this.MXA,this.MYA,this.MZA,this.MXB,this.MYB,this.MZB,this.MXC,this.MYC,this.MZC]=a||new Float32Array([1,0,0,0,1,0,0,0,1]);if(s<0||n<0||1!==r)throw new FormatError(`Invalid WhitePoint components for ${this.name}, no fallback available`);if(g<0||o<0||c<0){info(`Invalid BlackPoint for ${this.name} [${g}, ${o}, ${c}], falling back to default.`);this.blackPoint=new Float32Array(3);}if(this.GR<0||this.GG<0||this.GB<0){info(`Invalid Gamma [${this.GR}, ${this.GG}, ${this.GB}] for ${this.name}, falling back to default.`);this.GR=this.GG=this.GB=1;}}#c(e,t,i){i[0]=e[0]*t[0]+e[1]*t[1]+e[2]*t[2];i[1]=e[3]*t[0]+e[4]*t[1]+e[5]*t[2];i[2]=e[6]*t[0]+e[7]*t[1]+e[8]*t[2];}#C(e,t,i){i[0]=1*t[0]/e[0];i[1]=1*t[1]/e[1];i[2]=1*t[2]/e[2];}#h(e,t,i){i[0]=.95047*t[0]/e[0];i[1]=1*t[1]/e[1];i[2]=1.08883*t[2]/e[2];}#l(e){return e<=.0031308?this.#B(0,1,12.92*e):e>=.99554525?1:this.#B(0,1,1.055*e**(1/2.4)-.055)}#B(e,t,i){return Math.max(e,Math.min(t,i))}#Q(e){return e<0?-this.#Q(-e):e>8?((e+16)/116)**3:e*CalRGBCS.#I}#E(e,t,i){if(0===e[0]&&0===e[1]&&0===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=this.#Q(0),s=(1-a)/(1-this.#Q(e[0])),r=1-s,n=(1-a)/(1-this.#Q(e[1])),g=1-n,o=(1-a)/(1-this.#Q(e[2])),c=1-o;i[0]=t[0]*s+r;i[1]=t[1]*n+g;i[2]=t[2]*o+c;}#u(e,t,i){if(1===e[0]&&1===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=i;this.#c(CalRGBCS.#i,t,a);const s=CalRGBCS.#n;this.#C(e,a,s);this.#c(CalRGBCS.#a,s,i);}#d(e,t,i){const a=i;this.#c(CalRGBCS.#i,t,a);const s=CalRGBCS.#n;this.#h(e,a,s);this.#c(CalRGBCS.#a,s,i);}#t(e,t,i,a,s){const r=this.#B(0,1,e[t]*s),n=this.#B(0,1,e[t+1]*s),g=this.#B(0,1,e[t+2]*s),o=1===r?1:r**this.GR,c=1===n?1:n**this.GG,C=1===g?1:g**this.GB,h=this.MXA*o+this.MXB*c+this.MXC*C,l=this.MYA*o+this.MYB*c+this.MYC*C,Q=this.MZA*o+this.MZB*c+this.MZC*C,E=CalRGBCS.#g;E[0]=h;E[1]=l;E[2]=Q;const u=CalRGBCS.#o;this.#u(this.whitePoint,E,u);const d=CalRGBCS.#g;this.#E(this.blackPoint,u,d);const f=CalRGBCS.#o;this.#d(CalRGBCS.#r,d,f);const p=CalRGBCS.#g;this.#c(CalRGBCS.#s,f,p);i[a]=255*this.#l(p[0]);i[a+1]=255*this.#l(p[1]);i[a+2]=255*this.#l(p[2]);}getRgbItem(e,t,i,a){this.#t(e,t,i,a,1);}getRgbBuffer(e,t,i,a,s,r,n){const g=1/((1<<r)-1);for(let r=0;r<i;++r){this.#t(e,t,a,s,g);t+=3;s+=3+n;}}getOutputLength(e,t){return e*(3+t)/3|0}}class LabCS extends ColorSpace{constructor(e,t,i){super("Lab",3);if(!e)throw new FormatError("WhitePoint missing - required for color space Lab");[this.XW,this.YW,this.ZW]=e;[this.amin,this.amax,this.bmin,this.bmax]=i||[-100,100,-100,100];[this.XB,this.YB,this.ZB]=t||[0,0,0];if(this.XW<0||this.ZW<0||1!==this.YW)throw new FormatError("Invalid WhitePoint components, no fallback available");if(this.XB<0||this.YB<0||this.ZB<0){info("Invalid BlackPoint, falling back to default");this.XB=this.YB=this.ZB=0;}if(this.amin>this.amax||this.bmin>this.bmax){info("Invalid Range, falling back to defaults");this.amin=-100;this.amax=100;this.bmin=-100;this.bmax=100;}}#f(e){return e>=6/29?e**3:108/841*(e-4/29)}#p(e,t,i,a){return i+e*(a-i)/t}#t(e,t,i,a,s){let r=e[t],n=e[t+1],g=e[t+2];if(!1!==i){r=this.#p(r,i,0,100);n=this.#p(n,i,this.amin,this.amax);g=this.#p(g,i,this.bmin,this.bmax);}n>this.amax?n=this.amax:n<this.amin&&(n=this.amin);g>this.bmax?g=this.bmax:g<this.bmin&&(g=this.bmin);const o=(r+16)/116,c=o+n/500,C=o-g/200,h=this.XW*this.#f(c),l=this.YW*this.#f(o),Q=this.ZW*this.#f(C);let E,u,d;if(this.ZW<1){E=3.1339*h+-1.617*l+-.4906*Q;u=-.9785*h+1.916*l+.0333*Q;d=.072*h+-.229*l+1.4057*Q;}else {E=3.2406*h+-1.5372*l+-.4986*Q;u=-.9689*h+1.8758*l+.0415*Q;d=.0557*h+-.204*l+1.057*Q;}a[s]=255*Math.sqrt(E);a[s+1]=255*Math.sqrt(u);a[s+2]=255*Math.sqrt(d);}getRgbItem(e,t,i,a){this.#t(e,t,!1,i,a);}getRgbBuffer(e,t,i,a,s,r,n){const g=(1<<r)-1;for(let r=0;r<i;r++){this.#t(e,t,g,a,s);t+=3;s+=3+n;}}getOutputLength(e,t){return e*(3+t)/3|0}isDefaultDecode(e,t){return !0}get usesZeroToOneRange(){return shadow(this,"usesZeroToOneRange",!1)}}function hexToInt(e,t){let i=0;for(let a=0;a<=t;a++)i=i<<8|e[a];return i>>>0}function hexToStr(e,t){return 1===t?String.fromCharCode(e[0],e[1]):3===t?String.fromCharCode(e[0],e[1],e[2],e[3]):String.fromCharCode(...e.subarray(0,t+1))}function addHex(e,t,i){let a=0;for(let s=i;s>=0;s--){a+=e[s]+t[s];e[s]=255&a;a>>=8;}}function incHex(e,t){let i=1;for(let a=t;a>=0&&i>0;a--){i+=e[a];e[a]=255&i;i>>=8;}}const wt=16;class BinaryCMapStream{constructor(e){this.buffer=e;this.pos=0;this.end=e.length;this.tmpBuf=new Uint8Array(19);}readByte(){return