@oddington/sdk 0.1.19 → 0.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +87 -63
- package/dist/browser.js +584 -474
- package/dist/index.js +6 -6
- package/dist/types/packages/sdk/src/public.d.ts +87 -35
- package/dist/types/packages/sdk/src/routine-definition-types.d.ts +53 -19
- package/dist/types/shared/app-descriptor.d.ts +21 -0
- package/dist/types/shared/app-routine-contract.d.ts +1 -0
- package/dist/types/shared/inbox-contract.d.ts +5 -1
- package/dist/types/shared/inbox-member-contract.d.ts +2 -2
- package/dist/types/shared/inbox-member-types.d.ts +5 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -20,7 +20,7 @@ ${suffix}`}function identifyRegistrationError({error,options}){var _a,_b,_c;cons
|
|
|
20
20
|
`||character==="\r")){if(character==="\r"&&value[index+1]===`
|
|
21
21
|
`)index+=1;row.push(field);if(row.some((cell)=>cell.length>0))rows.push(row);row=[];field="";continue}field+=character}if(field.length||row.length){row.push(field);if(row.some((cell)=>cell.length>0))rows.push(row)}return rows}function delimitedDataRowCount(rows,headerRow=0){return Math.max(0,rows.length-headerRow-1)}function parseDeclaredDelimitedText(value,delimiter){const rows=[];let row=[],field="",state="start";for(let index=0;index<value.length;index+=1){const character=value[index];if(state==="quoted"){if(character==='"'){if(value[index+1]==='"'){field+='"';index+=1}else state="ended"}else field+=character}else if(character===delimiter){row.push(field);field="";state="start"}else if(character==="\r"||character===`
|
|
22
22
|
`){if(character==="\r"&&value[index+1]===`
|
|
23
|
-
`)index+=1;if(row.length||field.length||state!=="start")rows.push([...row,field]);row=[];field="";state="start"}else if(character==='"'&&state==="start")state="quoted";else{if(state==="ended"||character==='"')throw new Error("Malformed CSV quoted field");field+=character;state="unquoted"}}if(state==="quoted")throw new Error("Unterminated CSV quoted field");if(row.length||field.length||state!=="start")rows.push([...row,field]);return rows}function __extends(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}function __rest2(s,e){var t={};for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0)t[p]=s[p];if(s!=null&&typeof Object.getOwnPropertySymbols==="function")for(var i=0,p=Object.getOwnPropertySymbols(s);i<p.length;i++){if(e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(s,p[i]))t[p[i]]=s[p[i]]}return t}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(result2){result2.done?resolve(result2.value):adopt(result2.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})}function __generator(thisArg,
|
|
23
|
+
`)index+=1;if(row.length||field.length||state!=="start")rows.push([...row,field]);row=[];field="";state="start"}else if(character==='"'&&state==="start")state="quoted";else{if(state==="ended"||character==='"')throw new Error("Malformed CSV quoted field");field+=character;state="unquoted"}}if(state==="quoted")throw new Error("Unterminated CSV quoted field");if(row.length||field.length||state!=="start")rows.push([...row,field]);return rows}function __extends(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}function __rest2(s,e){var t={};for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0)t[p]=s[p];if(s!=null&&typeof Object.getOwnPropertySymbols==="function")for(var i=0,p=Object.getOwnPropertySymbols(s);i<p.length;i++){if(e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(s,p[i]))t[p[i]]=s[p[i]]}return t}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(result2){result2.done?resolve(result2.value):adopt(result2.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;return g={next:verb(0),throw:verb(1),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(_)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]:undefined,done:true}}}function __spreadArrays(){for(var s=0,i=0,il=arguments.length;i<il;i++)s+=arguments[i].length;for(var r=Array(s),k=0,i=0;i<il;i++)for(var a=arguments[i],j=0,jl=a.length;j<jl;j++,k++)r[k]=a[j];return r}var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)if(b2.hasOwnProperty(p))d2[p]=b2[p]};return extendStatics(d,b)},__assign=function(){__assign=Object.assign||function __assign2(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};var init_tslib_es62=__esm(()=>{/*! *****************************************************************************
|
|
24
24
|
Copyright (c) Microsoft Corporation.
|
|
25
25
|
|
|
26
26
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -41,7 +41,7 @@ PERFORMANCE OF THIS SOFTWARE.
|
|
|
41
41
|
stream
|
|
42
42
|
`;streamString+=this.getContentsString();streamString+=`
|
|
43
43
|
endstream`;return streamString};PDFStream2.prototype.copyBytesInto=function(buffer,offset){this.updateDict();var initialOffset=offset;offset+=this.dict.copyBytesInto(buffer,offset);buffer[offset++]=CharCodes_default.Newline;buffer[offset++]=CharCodes_default.s;buffer[offset++]=CharCodes_default.t;buffer[offset++]=CharCodes_default.r;buffer[offset++]=CharCodes_default.e;buffer[offset++]=CharCodes_default.a;buffer[offset++]=CharCodes_default.m;buffer[offset++]=CharCodes_default.Newline;var contents=this.getContents();for(var idx3=0,len2=contents.length;idx3<len2;idx3++){buffer[offset++]=contents[idx3]}buffer[offset++]=CharCodes_default.Newline;buffer[offset++]=CharCodes_default.e;buffer[offset++]=CharCodes_default.n;buffer[offset++]=CharCodes_default.d;buffer[offset++]=CharCodes_default.s;buffer[offset++]=CharCodes_default.t;buffer[offset++]=CharCodes_default.r;buffer[offset++]=CharCodes_default.e;buffer[offset++]=CharCodes_default.a;buffer[offset++]=CharCodes_default.m;return offset-initialOffset};return PDFStream2}(PDFObject_default);PDFStream_default=PDFStream});var PDFRawStream,PDFRawStream_default;var init_PDFRawStream=__esm(()=>{init_tslib_es62();init_PDFStream();init_utils2();PDFRawStream=function(_super){__extends(PDFRawStream2,_super);function PDFRawStream2(dict,contents){var _this=_super.call(this,dict)||this;_this.contents=contents;return _this}PDFRawStream2.prototype.asUint8Array=function(){return this.contents.slice()};PDFRawStream2.prototype.clone=function(context2){return PDFRawStream2.of(this.dict.clone(context2),this.contents.slice())};PDFRawStream2.prototype.getContentsString=function(){return arrayAsString(this.contents)};PDFRawStream2.prototype.getContents=function(){return this.contents};PDFRawStream2.prototype.getContentsSize=function(){return this.contents.length};PDFRawStream2.of=function(dict,contents){return new PDFRawStream2(dict,contents)};return PDFRawStream2}(PDFStream_default);PDFRawStream_default=PDFRawStream});var ENFORCER3,pool2,PDFRef,PDFRef_default;var init_PDFRef=__esm(()=>{init_tslib_es62();init_errors2();init_PDFObject();init_utils2();ENFORCER3={};pool2=new Map;PDFRef=function(_super){__extends(PDFRef2,_super);function PDFRef2(enforcer,objectNumber,generationNumber){var _this=this;if(enforcer!==ENFORCER3)throw new PrivateConstructorError("PDFRef");_this=_super.call(this)||this;_this.objectNumber=objectNumber;_this.generationNumber=generationNumber;_this.tag=objectNumber+" "+generationNumber+" R";return _this}PDFRef2.prototype.clone=function(){return this};PDFRef2.prototype.toString=function(){return this.tag};PDFRef2.prototype.sizeInBytes=function(){return this.tag.length};PDFRef2.prototype.copyBytesInto=function(buffer,offset){offset+=copyStringIntoBuffer(this.tag,buffer,offset);return this.tag.length};PDFRef2.of=function(objectNumber,generationNumber){if(generationNumber===undefined){generationNumber=0}var tag=objectNumber+" "+generationNumber+" R";var instance=pool2.get(tag);if(!instance){instance=new PDFRef2(ENFORCER3,objectNumber,generationNumber);pool2.set(tag,instance)}return instance};return PDFRef2}(PDFObject_default);PDFRef_default=PDFRef});var PDFOperator,PDFOperator_default;var init_PDFOperator=__esm(()=>{init_PDFObject();init_CharCodes();init_utils2();PDFOperator=function(){function PDFOperator2(name,args){this.name=name;this.args=args||[]}PDFOperator2.prototype.clone=function(context2){var args=new Array(this.args.length);for(var idx3=0,len2=args.length;idx3<len2;idx3++){var arg=this.args[idx3];args[idx3]=arg instanceof PDFObject_default?arg.clone(context2):arg}return PDFOperator2.of(this.name,args)};PDFOperator2.prototype.toString=function(){var value="";for(var idx3=0,len2=this.args.length;idx3<len2;idx3++){value+=String(this.args[idx3])+" "}value+=this.name;return value};PDFOperator2.prototype.sizeInBytes=function(){var size=0;for(var idx3=0,len2=this.args.length;idx3<len2;idx3++){var arg=this.args[idx3];size+=(arg instanceof PDFObject_default?arg.sizeInBytes():arg.length)+1}size+=this.name.length;return size};PDFOperator2.prototype.copyBytesInto=function(buffer,offset){var initialOffset=offset;for(var idx3=0,len2=this.args.length;idx3<len2;idx3++){var arg=this.args[idx3];if(arg instanceof PDFObject_default){offset+=arg.copyBytesInto(buffer,offset)}else{offset+=copyStringIntoBuffer(arg,buffer,offset)}buffer[offset++]=CharCodes_default.Space}offset+=copyStringIntoBuffer(this.name,buffer,offset);return offset-initialOffset};PDFOperator2.of=function(name,args){return new PDFOperator2(name,args)};return PDFOperator2}();PDFOperator_default=PDFOperator});var PDFOperatorNames,PDFOperatorNames_default;var init_PDFOperatorNames=__esm(()=>{(function(PDFOperatorNames2){PDFOperatorNames2["NonStrokingColor"]="sc";PDFOperatorNames2["NonStrokingColorN"]="scn";PDFOperatorNames2["NonStrokingColorRgb"]="rg";PDFOperatorNames2["NonStrokingColorGray"]="g";PDFOperatorNames2["NonStrokingColorCmyk"]="k";PDFOperatorNames2["NonStrokingColorspace"]="cs";PDFOperatorNames2["StrokingColor"]="SC";PDFOperatorNames2["StrokingColorN"]="SCN";PDFOperatorNames2["StrokingColorRgb"]="RG";PDFOperatorNames2["StrokingColorGray"]="G";PDFOperatorNames2["StrokingColorCmyk"]="K";PDFOperatorNames2["StrokingColorspace"]="CS";PDFOperatorNames2["BeginMarkedContentSequence"]="BDC";PDFOperatorNames2["BeginMarkedContent"]="BMC";PDFOperatorNames2["EndMarkedContent"]="EMC";PDFOperatorNames2["MarkedContentPointWithProps"]="DP";PDFOperatorNames2["MarkedContentPoint"]="MP";PDFOperatorNames2["DrawObject"]="Do";PDFOperatorNames2["ConcatTransformationMatrix"]="cm";PDFOperatorNames2["PopGraphicsState"]="Q";PDFOperatorNames2["PushGraphicsState"]="q";PDFOperatorNames2["SetFlatness"]="i";PDFOperatorNames2["SetGraphicsStateParams"]="gs";PDFOperatorNames2["SetLineCapStyle"]="J";PDFOperatorNames2["SetLineDashPattern"]="d";PDFOperatorNames2["SetLineJoinStyle"]="j";PDFOperatorNames2["SetLineMiterLimit"]="M";PDFOperatorNames2["SetLineWidth"]="w";PDFOperatorNames2["SetTextMatrix"]="Tm";PDFOperatorNames2["SetRenderingIntent"]="ri";PDFOperatorNames2["AppendRectangle"]="re";PDFOperatorNames2["BeginInlineImage"]="BI";PDFOperatorNames2["BeginInlineImageData"]="ID";PDFOperatorNames2["EndInlineImage"]="EI";PDFOperatorNames2["ClipEvenOdd"]="W*";PDFOperatorNames2["ClipNonZero"]="W";PDFOperatorNames2["CloseAndStroke"]="s";PDFOperatorNames2["CloseFillEvenOddAndStroke"]="b*";PDFOperatorNames2["CloseFillNonZeroAndStroke"]="b";PDFOperatorNames2["ClosePath"]="h";PDFOperatorNames2["AppendBezierCurve"]="c";PDFOperatorNames2["CurveToReplicateFinalPoint"]="y";PDFOperatorNames2["CurveToReplicateInitialPoint"]="v";PDFOperatorNames2["EndPath"]="n";PDFOperatorNames2["FillEvenOddAndStroke"]="B*";PDFOperatorNames2["FillEvenOdd"]="f*";PDFOperatorNames2["FillNonZeroAndStroke"]="B";PDFOperatorNames2["FillNonZero"]="f";PDFOperatorNames2["LegacyFillNonZero"]="F";PDFOperatorNames2["LineTo"]="l";PDFOperatorNames2["MoveTo"]="m";PDFOperatorNames2["ShadingFill"]="sh";PDFOperatorNames2["StrokePath"]="S";PDFOperatorNames2["BeginText"]="BT";PDFOperatorNames2["EndText"]="ET";PDFOperatorNames2["MoveText"]="Td";PDFOperatorNames2["MoveTextSetLeading"]="TD";PDFOperatorNames2["NextLine"]="T*";PDFOperatorNames2["SetCharacterSpacing"]="Tc";PDFOperatorNames2["SetFontAndSize"]="Tf";PDFOperatorNames2["SetTextHorizontalScaling"]="Tz";PDFOperatorNames2["SetTextLineHeight"]="TL";PDFOperatorNames2["SetTextRenderingMode"]="Tr";PDFOperatorNames2["SetTextRise"]="Ts";PDFOperatorNames2["SetWordSpacing"]="Tw";PDFOperatorNames2["ShowText"]="Tj";PDFOperatorNames2["ShowTextAdjusted"]="TJ";PDFOperatorNames2["ShowTextLine"]="'";PDFOperatorNames2["ShowTextLineAndSpace"]='"';PDFOperatorNames2["Type3D0"]="d0";PDFOperatorNames2["Type3D1"]="d1";PDFOperatorNames2["BeginCompatibilitySection"]="BX";PDFOperatorNames2["EndCompatibilitySection"]="EX"})(PDFOperatorNames||(PDFOperatorNames={}));PDFOperatorNames_default=PDFOperatorNames});var import_pako2,PDFFlateStream,PDFFlateStream_default;var init_PDFFlateStream=__esm(()=>{init_tslib_es62();init_errors2();init_PDFName();init_PDFStream();init_utils2();import_pako2=__toESM(require_pako(),1);PDFFlateStream=function(_super){__extends(PDFFlateStream2,_super);function PDFFlateStream2(dict,encode){var _this=_super.call(this,dict)||this;_this.computeContents=function(){var unencodedContents=_this.getUnencodedContents();return _this.encode?import_pako2.default.deflate(unencodedContents):unencodedContents};_this.encode=encode;if(encode)dict.set(PDFName_default.of("Filter"),PDFName_default.of("FlateDecode"));_this.contentsCache=Cache_default.populatedBy(_this.computeContents);return _this}PDFFlateStream2.prototype.getContents=function(){return this.contentsCache.access()};PDFFlateStream2.prototype.getContentsSize=function(){return this.contentsCache.access().length};PDFFlateStream2.prototype.getUnencodedContents=function(){throw new MethodNotImplementedError(this.constructor.name,"getUnencodedContents")};return PDFFlateStream2}(PDFStream_default);PDFFlateStream_default=PDFFlateStream});var PDFContentStream,PDFContentStream_default;var init_PDFContentStream=__esm(()=>{init_tslib_es62();init_PDFFlateStream();init_CharCodes();PDFContentStream=function(_super){__extends(PDFContentStream2,_super);function PDFContentStream2(dict,operators,encode){if(encode===undefined){encode=true}var _this=_super.call(this,dict,encode)||this;_this.operators=operators;return _this}PDFContentStream2.prototype.push=function(){var _a;var operators=[];for(var _i=0;_i<arguments.length;_i++){operators[_i]=arguments[_i]}(_a=this.operators).push.apply(_a,operators)};PDFContentStream2.prototype.clone=function(context2){var operators=new Array(this.operators.length);for(var idx3=0,len2=this.operators.length;idx3<len2;idx3++){operators[idx3]=this.operators[idx3].clone(context2)}var _a=this,dict=_a.dict,encode=_a.encode;return PDFContentStream2.of(dict.clone(context2),operators,encode)};PDFContentStream2.prototype.getContentsString=function(){var value="";for(var idx3=0,len2=this.operators.length;idx3<len2;idx3++){value+=this.operators[idx3]+`
|
|
44
|
-
`}return value};PDFContentStream2.prototype.getUnencodedContents=function(){var buffer=new Uint8Array(this.getUnencodedContentsSize());var offset=0;for(var idx3=0,len2=this.operators.length;idx3<len2;idx3++){offset+=this.operators[idx3].copyBytesInto(buffer,offset);buffer[offset++]=CharCodes_default.Newline}return buffer};PDFContentStream2.prototype.getUnencodedContentsSize=function(){var size=0;for(var idx3=0,len2=this.operators.length;idx3<len2;idx3++){size+=this.operators[idx3].sizeInBytes()+1}return size};PDFContentStream2.of=function(dict,operators,encode){if(encode===undefined){encode=true}return new PDFContentStream2(dict,operators,encode)};return PDFContentStream2}(PDFFlateStream_default);PDFContentStream_default=PDFContentStream});var SimpleRNG;var init_rng=__esm(()=>{SimpleRNG=function(){function SimpleRNG2(seed){this.seed=seed}SimpleRNG2.prototype.nextInt=function(){var x=Math.sin(this.seed++)*1e4;return x-Math.floor(x)};SimpleRNG2.withSeed=function(seed){return new SimpleRNG2(seed)};return SimpleRNG2}()});var import_pako3,byAscendingObjectNumber=function(_a,_b){var a=_a[0];var b=_b[0];return a.objectNumber-b.objectNumber},PDFContext,PDFContext_default;var init_PDFContext=__esm(()=>{init_tslib_es62();init_PDFHeader();init_errors2();init_PDFArray();init_PDFBool();init_PDFDict();init_PDFName();init_PDFNull();init_PDFNumber();init_PDFObject();init_PDFRawStream();init_PDFRef();init_PDFOperator();init_PDFOperatorNames();init_PDFContentStream();init_utils2();init_rng();import_pako3=__toESM(require_pako(),1);PDFContext=function(){function PDFContext2(){this.largestObjectNumber=0;this.header=PDFHeader_default.forVersion(1,7);this.trailerInfo={};this.indirectObjects=new Map;this.rng=SimpleRNG.withSeed(1)}PDFContext2.prototype.assign=function(ref,object5){this.indirectObjects.set(ref,object5);if(ref.objectNumber>this.largestObjectNumber){this.largestObjectNumber=ref.objectNumber}};PDFContext2.prototype.nextRef=function(){this.largestObjectNumber+=1;return PDFRef_default.of(this.largestObjectNumber)};PDFContext2.prototype.register=function(object5){var ref=this.nextRef();this.assign(ref,object5);return ref};PDFContext2.prototype.delete=function(ref){return this.indirectObjects.delete(ref)};PDFContext2.prototype.lookupMaybe=function(ref){var types2=[];for(var _i=1;_i<arguments.length;_i++){types2[_i-1]=arguments[_i]}var preservePDFNull=types2.includes(PDFNull_default);var result2=ref instanceof PDFRef_default?this.indirectObjects.get(ref):ref;if(!result2||result2===PDFNull_default&&!preservePDFNull)return;for(var idx3=0,len2=types2.length;idx3<len2;idx3++){var type=types2[idx3];if(type===PDFNull_default){if(result2===PDFNull_default)return result2}else{if(result2 instanceof type)return result2}}throw new UnexpectedObjectTypeError(types2,result2)};PDFContext2.prototype.lookup=function(ref){var types2=[];for(var _i=1;_i<arguments.length;_i++){types2[_i-1]=arguments[_i]}var result2=ref instanceof PDFRef_default?this.indirectObjects.get(ref):ref;if(types2.length===0)return result2;for(var idx3=0,len2=types2.length;idx3<len2;idx3++){var type=types2[idx3];if(type===PDFNull_default){if(result2===PDFNull_default)return result2}else{if(result2 instanceof type)return result2}}throw new UnexpectedObjectTypeError(types2,result2)};PDFContext2.prototype.getObjectRef=function(pdfObject){var entries=Array.from(this.indirectObjects.entries());for(var idx3=0,len2=entries.length;idx3<len2;idx3++){var _a=entries[idx3],ref=_a[0],object5=_a[1];if(object5===pdfObject){return ref}}return};PDFContext2.prototype.enumerateIndirectObjects=function(){return Array.from(this.indirectObjects.entries()).sort(byAscendingObjectNumber)};PDFContext2.prototype.obj=function(literal){if(literal instanceof PDFObject_default){return literal}else if(literal===null||literal===undefined){return PDFNull_default}else if(typeof literal==="string"){return PDFName_default.of(literal)}else if(typeof literal==="number"){return PDFNumber_default.of(literal)}else if(typeof literal==="boolean"){return literal?PDFBool_default.True:PDFBool_default.False}else if(Array.isArray(literal)){var array3=PDFArray_default.withContext(this);for(var idx3=0,len2=literal.length;idx3<len2;idx3++){array3.push(this.obj(literal[idx3]))}return array3}else{var dict=PDFDict_default.withContext(this);var keys5=Object.keys(literal);for(var idx3=0,len2=keys5.length;idx3<len2;idx3++){var key=keys5[idx3];var value=literal[key];if(value!==undefined)dict.set(PDFName_default.of(key),this.obj(value))}return dict}};PDFContext2.prototype.stream=function(contents,dict){if(dict===undefined){dict={}}return PDFRawStream_default.of(this.obj(dict),typedArrayFor(contents))};PDFContext2.prototype.flateStream=function(contents,dict){if(dict===undefined){dict={}}return this.stream(import_pako3.default.deflate(typedArrayFor(contents)),__assign(__assign({},dict),{Filter:"FlateDecode"}))};PDFContext2.prototype.contentStream=function(operators,dict){if(dict===undefined){dict={}}return PDFContentStream_default.of(this.obj(dict),operators)};PDFContext2.prototype.formXObject=function(operators,dict){if(dict===undefined){dict={}}return this.contentStream(operators,__assign(__assign({BBox:this.obj([0,0,0,0]),Matrix:this.obj([1,0,0,1,0,0])},dict),{Type:"XObject",Subtype:"Form"}))};PDFContext2.prototype.getPushGraphicsStateContentStream=function(){if(this.pushGraphicsStateContentStreamRef){return this.pushGraphicsStateContentStreamRef}var dict=this.obj({});var op=PDFOperator_default.of(PDFOperatorNames_default.PushGraphicsState);var stream=PDFContentStream_default.of(dict,[op]);this.pushGraphicsStateContentStreamRef=this.register(stream);return this.pushGraphicsStateContentStreamRef};PDFContext2.prototype.getPopGraphicsStateContentStream=function(){if(this.popGraphicsStateContentStreamRef){return this.popGraphicsStateContentStreamRef}var dict=this.obj({});var op=PDFOperator_default.of(PDFOperatorNames_default.PopGraphicsState);var stream=PDFContentStream_default.of(dict,[op]);this.popGraphicsStateContentStreamRef=this.register(stream);return this.popGraphicsStateContentStreamRef};PDFContext2.prototype.addRandomSuffix=function(prefix,suffixLength){if(suffixLength===undefined){suffixLength=4}return prefix+"-"+Math.floor(this.rng.nextInt()*Math.pow(10,suffixLength))};PDFContext2.create=function(){return new PDFContext2};return PDFContext2}();PDFContext_default=PDFContext});var PDFPageLeaf,PDFPageLeaf_default;var init_PDFPageLeaf=__esm(()=>{init_tslib_es62();init_PDFArray();init_PDFDict();init_PDFName();init_PDFNumber();init_PDFStream();PDFPageLeaf=function(_super){__extends(PDFPageLeaf2,_super);function PDFPageLeaf2(map,context2,autoNormalizeCTM){if(autoNormalizeCTM===undefined){autoNormalizeCTM=true}var _this=_super.call(this,map,context2)||this;_this.normalized=false;_this.autoNormalizeCTM=autoNormalizeCTM;return _this}PDFPageLeaf2.prototype.clone=function(context2){var clone=PDFPageLeaf2.fromMapWithContext(new Map,context2||this.context,this.autoNormalizeCTM);var entries=this.entries();for(var idx3=0,len2=entries.length;idx3<len2;idx3++){var _a=entries[idx3],key=_a[0],value=_a[1];clone.set(key,value)}return clone};PDFPageLeaf2.prototype.Parent=function(){return this.lookupMaybe(PDFName_default.Parent,PDFDict_default)};PDFPageLeaf2.prototype.Contents=function(){return this.lookup(PDFName_default.of("Contents"))};PDFPageLeaf2.prototype.Annots=function(){return this.lookupMaybe(PDFName_default.Annots,PDFArray_default)};PDFPageLeaf2.prototype.BleedBox=function(){return this.lookupMaybe(PDFName_default.BleedBox,PDFArray_default)};PDFPageLeaf2.prototype.TrimBox=function(){return this.lookupMaybe(PDFName_default.TrimBox,PDFArray_default)};PDFPageLeaf2.prototype.ArtBox=function(){return this.lookupMaybe(PDFName_default.ArtBox,PDFArray_default)};PDFPageLeaf2.prototype.Resources=function(){var dictOrRef=this.getInheritableAttribute(PDFName_default.Resources);return this.context.lookupMaybe(dictOrRef,PDFDict_default)};PDFPageLeaf2.prototype.MediaBox=function(){var arrayOrRef=this.getInheritableAttribute(PDFName_default.MediaBox);return this.context.lookup(arrayOrRef,PDFArray_default)};PDFPageLeaf2.prototype.CropBox=function(){var arrayOrRef=this.getInheritableAttribute(PDFName_default.CropBox);return this.context.lookupMaybe(arrayOrRef,PDFArray_default)};PDFPageLeaf2.prototype.Rotate=function(){var numberOrRef=this.getInheritableAttribute(PDFName_default.Rotate);return this.context.lookupMaybe(numberOrRef,PDFNumber_default)};PDFPageLeaf2.prototype.getInheritableAttribute=function(name){var attribute;this.ascend(function(node){if(!attribute)attribute=node.get(name)});return attribute};PDFPageLeaf2.prototype.setParent=function(parentRef){this.set(PDFName_default.Parent,parentRef)};PDFPageLeaf2.prototype.addContentStream=function(contentStreamRef){var Contents=this.normalizedEntries().Contents||this.context.obj([]);this.set(PDFName_default.Contents,Contents);Contents.push(contentStreamRef)};PDFPageLeaf2.prototype.wrapContentStreams=function(startStream,endStream){var Contents=this.Contents();if(Contents instanceof PDFArray_default){Contents.insert(0,startStream);Contents.push(endStream);return true}return false};PDFPageLeaf2.prototype.addAnnot=function(annotRef){var Annots=this.normalizedEntries().Annots;Annots.push(annotRef)};PDFPageLeaf2.prototype.removeAnnot=function(annotRef){var Annots=this.normalizedEntries().Annots;var index=Annots.indexOf(annotRef);if(index!==undefined){Annots.remove(index)}};PDFPageLeaf2.prototype.setFontDictionary=function(name,fontDictRef){var Font3=this.normalizedEntries().Font;Font3.set(name,fontDictRef)};PDFPageLeaf2.prototype.newFontDictionaryKey=function(tag){var Font3=this.normalizedEntries().Font;return Font3.uniqueKey(tag)};PDFPageLeaf2.prototype.newFontDictionary=function(tag,fontDictRef){var key=this.newFontDictionaryKey(tag);this.setFontDictionary(key,fontDictRef);return key};PDFPageLeaf2.prototype.setXObject=function(name,xObjectRef){var XObject=this.normalizedEntries().XObject;XObject.set(name,xObjectRef)};PDFPageLeaf2.prototype.newXObjectKey=function(tag){var XObject=this.normalizedEntries().XObject;return XObject.uniqueKey(tag)};PDFPageLeaf2.prototype.newXObject=function(tag,xObjectRef){var key=this.newXObjectKey(tag);this.setXObject(key,xObjectRef);return key};PDFPageLeaf2.prototype.setExtGState=function(name,extGStateRef){var ExtGState=this.normalizedEntries().ExtGState;ExtGState.set(name,extGStateRef)};PDFPageLeaf2.prototype.newExtGStateKey=function(tag){var ExtGState=this.normalizedEntries().ExtGState;return ExtGState.uniqueKey(tag)};PDFPageLeaf2.prototype.newExtGState=function(tag,extGStateRef){var key=this.newExtGStateKey(tag);this.setExtGState(key,extGStateRef);return key};PDFPageLeaf2.prototype.ascend=function(visitor){visitor(this);var Parent=this.Parent();if(Parent)Parent.ascend(visitor)};PDFPageLeaf2.prototype.normalize=function(){if(this.normalized)return;var context2=this.context;var contentsRef=this.get(PDFName_default.Contents);var contents=this.context.lookup(contentsRef);if(contents instanceof PDFStream_default){this.set(PDFName_default.Contents,context2.obj([contentsRef]))}if(this.autoNormalizeCTM){this.wrapContentStreams(this.context.getPushGraphicsStateContentStream(),this.context.getPopGraphicsStateContentStream())}var dictOrRef=this.getInheritableAttribute(PDFName_default.Resources);var Resources=context2.lookupMaybe(dictOrRef,PDFDict_default)||context2.obj({});this.set(PDFName_default.Resources,Resources);var Font3=Resources.lookupMaybe(PDFName_default.Font,PDFDict_default)||context2.obj({});Resources.set(PDFName_default.Font,Font3);var XObject=Resources.lookupMaybe(PDFName_default.XObject,PDFDict_default)||context2.obj({});Resources.set(PDFName_default.XObject,XObject);var ExtGState=Resources.lookupMaybe(PDFName_default.ExtGState,PDFDict_default)||context2.obj({});Resources.set(PDFName_default.ExtGState,ExtGState);var Annots=this.Annots()||context2.obj([]);this.set(PDFName_default.Annots,Annots);this.normalized=true};PDFPageLeaf2.prototype.normalizedEntries=function(){this.normalize();var Annots=this.Annots();var Resources=this.Resources();var Contents=this.Contents();return{Annots,Resources,Contents,Font:Resources.lookup(PDFName_default.Font,PDFDict_default),XObject:Resources.lookup(PDFName_default.XObject,PDFDict_default),ExtGState:Resources.lookup(PDFName_default.ExtGState,PDFDict_default)}};PDFPageLeaf2.InheritableEntries=["Resources","MediaBox","CropBox","Rotate"];PDFPageLeaf2.withContextAndParent=function(context2,parent){var dict=new Map;dict.set(PDFName_default.Type,PDFName_default.Page);dict.set(PDFName_default.Parent,parent);dict.set(PDFName_default.Resources,context2.obj({}));dict.set(PDFName_default.MediaBox,context2.obj([0,0,612,792]));return new PDFPageLeaf2(dict,context2,false)};PDFPageLeaf2.fromMapWithContext=function(map,context2,autoNormalizeCTM){if(autoNormalizeCTM===undefined){autoNormalizeCTM=true}return new PDFPageLeaf2(map,context2,autoNormalizeCTM)};return PDFPageLeaf2}(PDFDict_default);PDFPageLeaf_default=PDFPageLeaf});var PDFObjectCopier,PDFObjectCopier_default;var init_PDFObjectCopier=__esm(()=>{init_PDFArray();init_PDFDict();init_PDFName();init_PDFRef();init_PDFStream();init_PDFPageLeaf();PDFObjectCopier=function(){function PDFObjectCopier2(src,dest){var _this=this;this.traversedObjects=new Map;this.copy=function(object5){return object5 instanceof PDFPageLeaf_default?_this.copyPDFPage(object5):object5 instanceof PDFDict_default?_this.copyPDFDict(object5):object5 instanceof PDFArray_default?_this.copyPDFArray(object5):object5 instanceof PDFStream_default?_this.copyPDFStream(object5):object5 instanceof PDFRef_default?_this.copyPDFIndirectObject(object5):object5.clone()};this.copyPDFPage=function(originalPage){var clonedPage=originalPage.clone();var InheritableEntries=PDFPageLeaf_default.InheritableEntries;for(var idx3=0,len2=InheritableEntries.length;idx3<len2;idx3++){var key=PDFName_default.of(InheritableEntries[idx3]);var value=clonedPage.getInheritableAttribute(key);if(!clonedPage.get(key)&&value)clonedPage.set(key,value)}clonedPage.delete(PDFName_default.of("Parent"));return _this.copyPDFDict(clonedPage)};this.copyPDFDict=function(originalDict){if(_this.traversedObjects.has(originalDict)){return _this.traversedObjects.get(originalDict)}var clonedDict=originalDict.clone(_this.dest);_this.traversedObjects.set(originalDict,clonedDict);var entries=originalDict.entries();for(var idx3=0,len2=entries.length;idx3<len2;idx3++){var _a=entries[idx3],key=_a[0],value=_a[1];clonedDict.set(key,_this.copy(value))}return clonedDict};this.copyPDFArray=function(originalArray){if(_this.traversedObjects.has(originalArray)){return _this.traversedObjects.get(originalArray)}var clonedArray=originalArray.clone(_this.dest);_this.traversedObjects.set(originalArray,clonedArray);for(var idx3=0,len2=originalArray.size();idx3<len2;idx3++){var value=originalArray.get(idx3);clonedArray.set(idx3,_this.copy(value))}return clonedArray};this.copyPDFStream=function(originalStream){if(_this.traversedObjects.has(originalStream)){return _this.traversedObjects.get(originalStream)}var clonedStream=originalStream.clone(_this.dest);_this.traversedObjects.set(originalStream,clonedStream);var entries=originalStream.dict.entries();for(var idx3=0,len2=entries.length;idx3<len2;idx3++){var _a=entries[idx3],key=_a[0],value=_a[1];clonedStream.dict.set(key,_this.copy(value))}return clonedStream};this.copyPDFIndirectObject=function(ref){var alreadyMapped=_this.traversedObjects.has(ref);if(!alreadyMapped){var newRef=_this.dest.nextRef();_this.traversedObjects.set(ref,newRef);var dereferencedValue=_this.src.lookup(ref);if(dereferencedValue){var cloned=_this.copy(dereferencedValue);_this.dest.assign(newRef,cloned)}}return _this.traversedObjects.get(ref)};this.src=src;this.dest=dest}PDFObjectCopier2.for=function(src,dest){return new PDFObjectCopier2(src,dest)};return PDFObjectCopier2}();PDFObjectCopier_default=PDFObjectCopier});var PDFCrossRefSection,PDFCrossRefSection_default;var init_PDFCrossRefSection=__esm(()=>{init_PDFRef();init_CharCodes();init_utils2();PDFCrossRefSection=function(){function PDFCrossRefSection2(firstEntry){this.subsections=firstEntry?[[firstEntry]]:[];this.chunkIdx=0;this.chunkLength=firstEntry?1:0}PDFCrossRefSection2.prototype.addEntry=function(ref,offset){this.append({ref,offset,deleted:false})};PDFCrossRefSection2.prototype.addDeletedEntry=function(ref,nextFreeObjectNumber){this.append({ref,offset:nextFreeObjectNumber,deleted:true})};PDFCrossRefSection2.prototype.toString=function(){var section=`xref
|
|
44
|
+
`}return value};PDFContentStream2.prototype.getUnencodedContents=function(){var buffer=new Uint8Array(this.getUnencodedContentsSize());var offset=0;for(var idx3=0,len2=this.operators.length;idx3<len2;idx3++){offset+=this.operators[idx3].copyBytesInto(buffer,offset);buffer[offset++]=CharCodes_default.Newline}return buffer};PDFContentStream2.prototype.getUnencodedContentsSize=function(){var size=0;for(var idx3=0,len2=this.operators.length;idx3<len2;idx3++){size+=this.operators[idx3].sizeInBytes()+1}return size};PDFContentStream2.of=function(dict,operators,encode){if(encode===undefined){encode=true}return new PDFContentStream2(dict,operators,encode)};return PDFContentStream2}(PDFFlateStream_default);PDFContentStream_default=PDFContentStream});var SimpleRNG;var init_rng=__esm(()=>{SimpleRNG=function(){function SimpleRNG2(seed){this.seed=seed}SimpleRNG2.prototype.nextInt=function(){var x=Math.sin(this.seed++)*1e4;return x-Math.floor(x)};SimpleRNG2.withSeed=function(seed){return new SimpleRNG2(seed)};return SimpleRNG2}()});var import_pako3,byAscendingObjectNumber=function(_a,_b){var a=_a[0];var b=_b[0];return a.objectNumber-b.objectNumber},PDFContext,PDFContext_default;var init_PDFContext=__esm(()=>{init_tslib_es62();init_PDFHeader();init_errors2();init_PDFArray();init_PDFBool();init_PDFDict();init_PDFName();init_PDFNull();init_PDFNumber();init_PDFObject();init_PDFRawStream();init_PDFRef();init_PDFOperator();init_PDFOperatorNames();init_PDFContentStream();init_utils2();init_rng();import_pako3=__toESM(require_pako(),1);PDFContext=function(){function PDFContext2(){this.largestObjectNumber=0;this.header=PDFHeader_default.forVersion(1,7);this.trailerInfo={};this.indirectObjects=new Map;this.rng=SimpleRNG.withSeed(1)}PDFContext2.prototype.assign=function(ref,object5){this.indirectObjects.set(ref,object5);if(ref.objectNumber>this.largestObjectNumber){this.largestObjectNumber=ref.objectNumber}};PDFContext2.prototype.nextRef=function(){this.largestObjectNumber+=1;return PDFRef_default.of(this.largestObjectNumber)};PDFContext2.prototype.register=function(object5){var ref=this.nextRef();this.assign(ref,object5);return ref};PDFContext2.prototype.delete=function(ref){return this.indirectObjects.delete(ref)};PDFContext2.prototype.lookupMaybe=function(ref){var types2=[];for(var _i=1;_i<arguments.length;_i++){types2[_i-1]=arguments[_i]}var preservePDFNull=types2.includes(PDFNull_default);var result2=ref instanceof PDFRef_default?this.indirectObjects.get(ref):ref;if(!result2||result2===PDFNull_default&&!preservePDFNull)return;for(var idx3=0,len2=types2.length;idx3<len2;idx3++){var type=types2[idx3];if(type===PDFNull_default){if(result2===PDFNull_default)return result2}else{if(result2 instanceof type)return result2}}throw new UnexpectedObjectTypeError(types2,result2)};PDFContext2.prototype.lookup=function(ref){var types2=[];for(var _i=1;_i<arguments.length;_i++){types2[_i-1]=arguments[_i]}var result2=ref instanceof PDFRef_default?this.indirectObjects.get(ref):ref;if(types2.length===0)return result2;for(var idx3=0,len2=types2.length;idx3<len2;idx3++){var type=types2[idx3];if(type===PDFNull_default){if(result2===PDFNull_default)return result2}else{if(result2 instanceof type)return result2}}throw new UnexpectedObjectTypeError(types2,result2)};PDFContext2.prototype.getObjectRef=function(pdfObject){var entries=Array.from(this.indirectObjects.entries());for(var idx3=0,len2=entries.length;idx3<len2;idx3++){var _a=entries[idx3],ref=_a[0],object5=_a[1];if(object5===pdfObject){return ref}}return};PDFContext2.prototype.enumerateIndirectObjects=function(){return Array.from(this.indirectObjects.entries()).sort(byAscendingObjectNumber)};PDFContext2.prototype.obj=function(literal){if(literal instanceof PDFObject_default){return literal}else if(literal===null||literal===undefined){return PDFNull_default}else if(typeof literal==="string"){return PDFName_default.of(literal)}else if(typeof literal==="number"){return PDFNumber_default.of(literal)}else if(typeof literal==="boolean"){return literal?PDFBool_default.True:PDFBool_default.False}else if(Array.isArray(literal)){var array3=PDFArray_default.withContext(this);for(var idx3=0,len2=literal.length;idx3<len2;idx3++){array3.push(this.obj(literal[idx3]))}return array3}else{var dict=PDFDict_default.withContext(this);var keys4=Object.keys(literal);for(var idx3=0,len2=keys4.length;idx3<len2;idx3++){var key=keys4[idx3];var value=literal[key];if(value!==undefined)dict.set(PDFName_default.of(key),this.obj(value))}return dict}};PDFContext2.prototype.stream=function(contents,dict){if(dict===undefined){dict={}}return PDFRawStream_default.of(this.obj(dict),typedArrayFor(contents))};PDFContext2.prototype.flateStream=function(contents,dict){if(dict===undefined){dict={}}return this.stream(import_pako3.default.deflate(typedArrayFor(contents)),__assign(__assign({},dict),{Filter:"FlateDecode"}))};PDFContext2.prototype.contentStream=function(operators,dict){if(dict===undefined){dict={}}return PDFContentStream_default.of(this.obj(dict),operators)};PDFContext2.prototype.formXObject=function(operators,dict){if(dict===undefined){dict={}}return this.contentStream(operators,__assign(__assign({BBox:this.obj([0,0,0,0]),Matrix:this.obj([1,0,0,1,0,0])},dict),{Type:"XObject",Subtype:"Form"}))};PDFContext2.prototype.getPushGraphicsStateContentStream=function(){if(this.pushGraphicsStateContentStreamRef){return this.pushGraphicsStateContentStreamRef}var dict=this.obj({});var op=PDFOperator_default.of(PDFOperatorNames_default.PushGraphicsState);var stream=PDFContentStream_default.of(dict,[op]);this.pushGraphicsStateContentStreamRef=this.register(stream);return this.pushGraphicsStateContentStreamRef};PDFContext2.prototype.getPopGraphicsStateContentStream=function(){if(this.popGraphicsStateContentStreamRef){return this.popGraphicsStateContentStreamRef}var dict=this.obj({});var op=PDFOperator_default.of(PDFOperatorNames_default.PopGraphicsState);var stream=PDFContentStream_default.of(dict,[op]);this.popGraphicsStateContentStreamRef=this.register(stream);return this.popGraphicsStateContentStreamRef};PDFContext2.prototype.addRandomSuffix=function(prefix,suffixLength){if(suffixLength===undefined){suffixLength=4}return prefix+"-"+Math.floor(this.rng.nextInt()*Math.pow(10,suffixLength))};PDFContext2.create=function(){return new PDFContext2};return PDFContext2}();PDFContext_default=PDFContext});var PDFPageLeaf,PDFPageLeaf_default;var init_PDFPageLeaf=__esm(()=>{init_tslib_es62();init_PDFArray();init_PDFDict();init_PDFName();init_PDFNumber();init_PDFStream();PDFPageLeaf=function(_super){__extends(PDFPageLeaf2,_super);function PDFPageLeaf2(map,context2,autoNormalizeCTM){if(autoNormalizeCTM===undefined){autoNormalizeCTM=true}var _this=_super.call(this,map,context2)||this;_this.normalized=false;_this.autoNormalizeCTM=autoNormalizeCTM;return _this}PDFPageLeaf2.prototype.clone=function(context2){var clone=PDFPageLeaf2.fromMapWithContext(new Map,context2||this.context,this.autoNormalizeCTM);var entries=this.entries();for(var idx3=0,len2=entries.length;idx3<len2;idx3++){var _a=entries[idx3],key=_a[0],value=_a[1];clone.set(key,value)}return clone};PDFPageLeaf2.prototype.Parent=function(){return this.lookupMaybe(PDFName_default.Parent,PDFDict_default)};PDFPageLeaf2.prototype.Contents=function(){return this.lookup(PDFName_default.of("Contents"))};PDFPageLeaf2.prototype.Annots=function(){return this.lookupMaybe(PDFName_default.Annots,PDFArray_default)};PDFPageLeaf2.prototype.BleedBox=function(){return this.lookupMaybe(PDFName_default.BleedBox,PDFArray_default)};PDFPageLeaf2.prototype.TrimBox=function(){return this.lookupMaybe(PDFName_default.TrimBox,PDFArray_default)};PDFPageLeaf2.prototype.ArtBox=function(){return this.lookupMaybe(PDFName_default.ArtBox,PDFArray_default)};PDFPageLeaf2.prototype.Resources=function(){var dictOrRef=this.getInheritableAttribute(PDFName_default.Resources);return this.context.lookupMaybe(dictOrRef,PDFDict_default)};PDFPageLeaf2.prototype.MediaBox=function(){var arrayOrRef=this.getInheritableAttribute(PDFName_default.MediaBox);return this.context.lookup(arrayOrRef,PDFArray_default)};PDFPageLeaf2.prototype.CropBox=function(){var arrayOrRef=this.getInheritableAttribute(PDFName_default.CropBox);return this.context.lookupMaybe(arrayOrRef,PDFArray_default)};PDFPageLeaf2.prototype.Rotate=function(){var numberOrRef=this.getInheritableAttribute(PDFName_default.Rotate);return this.context.lookupMaybe(numberOrRef,PDFNumber_default)};PDFPageLeaf2.prototype.getInheritableAttribute=function(name){var attribute;this.ascend(function(node){if(!attribute)attribute=node.get(name)});return attribute};PDFPageLeaf2.prototype.setParent=function(parentRef){this.set(PDFName_default.Parent,parentRef)};PDFPageLeaf2.prototype.addContentStream=function(contentStreamRef){var Contents=this.normalizedEntries().Contents||this.context.obj([]);this.set(PDFName_default.Contents,Contents);Contents.push(contentStreamRef)};PDFPageLeaf2.prototype.wrapContentStreams=function(startStream,endStream){var Contents=this.Contents();if(Contents instanceof PDFArray_default){Contents.insert(0,startStream);Contents.push(endStream);return true}return false};PDFPageLeaf2.prototype.addAnnot=function(annotRef){var Annots=this.normalizedEntries().Annots;Annots.push(annotRef)};PDFPageLeaf2.prototype.removeAnnot=function(annotRef){var Annots=this.normalizedEntries().Annots;var index=Annots.indexOf(annotRef);if(index!==undefined){Annots.remove(index)}};PDFPageLeaf2.prototype.setFontDictionary=function(name,fontDictRef){var Font3=this.normalizedEntries().Font;Font3.set(name,fontDictRef)};PDFPageLeaf2.prototype.newFontDictionaryKey=function(tag){var Font3=this.normalizedEntries().Font;return Font3.uniqueKey(tag)};PDFPageLeaf2.prototype.newFontDictionary=function(tag,fontDictRef){var key=this.newFontDictionaryKey(tag);this.setFontDictionary(key,fontDictRef);return key};PDFPageLeaf2.prototype.setXObject=function(name,xObjectRef){var XObject=this.normalizedEntries().XObject;XObject.set(name,xObjectRef)};PDFPageLeaf2.prototype.newXObjectKey=function(tag){var XObject=this.normalizedEntries().XObject;return XObject.uniqueKey(tag)};PDFPageLeaf2.prototype.newXObject=function(tag,xObjectRef){var key=this.newXObjectKey(tag);this.setXObject(key,xObjectRef);return key};PDFPageLeaf2.prototype.setExtGState=function(name,extGStateRef){var ExtGState=this.normalizedEntries().ExtGState;ExtGState.set(name,extGStateRef)};PDFPageLeaf2.prototype.newExtGStateKey=function(tag){var ExtGState=this.normalizedEntries().ExtGState;return ExtGState.uniqueKey(tag)};PDFPageLeaf2.prototype.newExtGState=function(tag,extGStateRef){var key=this.newExtGStateKey(tag);this.setExtGState(key,extGStateRef);return key};PDFPageLeaf2.prototype.ascend=function(visitor){visitor(this);var Parent=this.Parent();if(Parent)Parent.ascend(visitor)};PDFPageLeaf2.prototype.normalize=function(){if(this.normalized)return;var context2=this.context;var contentsRef=this.get(PDFName_default.Contents);var contents=this.context.lookup(contentsRef);if(contents instanceof PDFStream_default){this.set(PDFName_default.Contents,context2.obj([contentsRef]))}if(this.autoNormalizeCTM){this.wrapContentStreams(this.context.getPushGraphicsStateContentStream(),this.context.getPopGraphicsStateContentStream())}var dictOrRef=this.getInheritableAttribute(PDFName_default.Resources);var Resources=context2.lookupMaybe(dictOrRef,PDFDict_default)||context2.obj({});this.set(PDFName_default.Resources,Resources);var Font3=Resources.lookupMaybe(PDFName_default.Font,PDFDict_default)||context2.obj({});Resources.set(PDFName_default.Font,Font3);var XObject=Resources.lookupMaybe(PDFName_default.XObject,PDFDict_default)||context2.obj({});Resources.set(PDFName_default.XObject,XObject);var ExtGState=Resources.lookupMaybe(PDFName_default.ExtGState,PDFDict_default)||context2.obj({});Resources.set(PDFName_default.ExtGState,ExtGState);var Annots=this.Annots()||context2.obj([]);this.set(PDFName_default.Annots,Annots);this.normalized=true};PDFPageLeaf2.prototype.normalizedEntries=function(){this.normalize();var Annots=this.Annots();var Resources=this.Resources();var Contents=this.Contents();return{Annots,Resources,Contents,Font:Resources.lookup(PDFName_default.Font,PDFDict_default),XObject:Resources.lookup(PDFName_default.XObject,PDFDict_default),ExtGState:Resources.lookup(PDFName_default.ExtGState,PDFDict_default)}};PDFPageLeaf2.InheritableEntries=["Resources","MediaBox","CropBox","Rotate"];PDFPageLeaf2.withContextAndParent=function(context2,parent){var dict=new Map;dict.set(PDFName_default.Type,PDFName_default.Page);dict.set(PDFName_default.Parent,parent);dict.set(PDFName_default.Resources,context2.obj({}));dict.set(PDFName_default.MediaBox,context2.obj([0,0,612,792]));return new PDFPageLeaf2(dict,context2,false)};PDFPageLeaf2.fromMapWithContext=function(map,context2,autoNormalizeCTM){if(autoNormalizeCTM===undefined){autoNormalizeCTM=true}return new PDFPageLeaf2(map,context2,autoNormalizeCTM)};return PDFPageLeaf2}(PDFDict_default);PDFPageLeaf_default=PDFPageLeaf});var PDFObjectCopier,PDFObjectCopier_default;var init_PDFObjectCopier=__esm(()=>{init_PDFArray();init_PDFDict();init_PDFName();init_PDFRef();init_PDFStream();init_PDFPageLeaf();PDFObjectCopier=function(){function PDFObjectCopier2(src,dest){var _this=this;this.traversedObjects=new Map;this.copy=function(object5){return object5 instanceof PDFPageLeaf_default?_this.copyPDFPage(object5):object5 instanceof PDFDict_default?_this.copyPDFDict(object5):object5 instanceof PDFArray_default?_this.copyPDFArray(object5):object5 instanceof PDFStream_default?_this.copyPDFStream(object5):object5 instanceof PDFRef_default?_this.copyPDFIndirectObject(object5):object5.clone()};this.copyPDFPage=function(originalPage){var clonedPage=originalPage.clone();var InheritableEntries=PDFPageLeaf_default.InheritableEntries;for(var idx3=0,len2=InheritableEntries.length;idx3<len2;idx3++){var key=PDFName_default.of(InheritableEntries[idx3]);var value=clonedPage.getInheritableAttribute(key);if(!clonedPage.get(key)&&value)clonedPage.set(key,value)}clonedPage.delete(PDFName_default.of("Parent"));return _this.copyPDFDict(clonedPage)};this.copyPDFDict=function(originalDict){if(_this.traversedObjects.has(originalDict)){return _this.traversedObjects.get(originalDict)}var clonedDict=originalDict.clone(_this.dest);_this.traversedObjects.set(originalDict,clonedDict);var entries=originalDict.entries();for(var idx3=0,len2=entries.length;idx3<len2;idx3++){var _a=entries[idx3],key=_a[0],value=_a[1];clonedDict.set(key,_this.copy(value))}return clonedDict};this.copyPDFArray=function(originalArray){if(_this.traversedObjects.has(originalArray)){return _this.traversedObjects.get(originalArray)}var clonedArray=originalArray.clone(_this.dest);_this.traversedObjects.set(originalArray,clonedArray);for(var idx3=0,len2=originalArray.size();idx3<len2;idx3++){var value=originalArray.get(idx3);clonedArray.set(idx3,_this.copy(value))}return clonedArray};this.copyPDFStream=function(originalStream){if(_this.traversedObjects.has(originalStream)){return _this.traversedObjects.get(originalStream)}var clonedStream=originalStream.clone(_this.dest);_this.traversedObjects.set(originalStream,clonedStream);var entries=originalStream.dict.entries();for(var idx3=0,len2=entries.length;idx3<len2;idx3++){var _a=entries[idx3],key=_a[0],value=_a[1];clonedStream.dict.set(key,_this.copy(value))}return clonedStream};this.copyPDFIndirectObject=function(ref){var alreadyMapped=_this.traversedObjects.has(ref);if(!alreadyMapped){var newRef=_this.dest.nextRef();_this.traversedObjects.set(ref,newRef);var dereferencedValue=_this.src.lookup(ref);if(dereferencedValue){var cloned=_this.copy(dereferencedValue);_this.dest.assign(newRef,cloned)}}return _this.traversedObjects.get(ref)};this.src=src;this.dest=dest}PDFObjectCopier2.for=function(src,dest){return new PDFObjectCopier2(src,dest)};return PDFObjectCopier2}();PDFObjectCopier_default=PDFObjectCopier});var PDFCrossRefSection,PDFCrossRefSection_default;var init_PDFCrossRefSection=__esm(()=>{init_PDFRef();init_CharCodes();init_utils2();PDFCrossRefSection=function(){function PDFCrossRefSection2(firstEntry){this.subsections=firstEntry?[[firstEntry]]:[];this.chunkIdx=0;this.chunkLength=firstEntry?1:0}PDFCrossRefSection2.prototype.addEntry=function(ref,offset){this.append({ref,offset,deleted:false})};PDFCrossRefSection2.prototype.addDeletedEntry=function(ref,nextFreeObjectNumber){this.append({ref,offset:nextFreeObjectNumber,deleted:true})};PDFCrossRefSection2.prototype.toString=function(){var section=`xref
|
|
45
45
|
`;for(var rangeIdx=0,rangeLen=this.subsections.length;rangeIdx<rangeLen;rangeIdx++){var range2=this.subsections[rangeIdx];section+=range2[0].ref.objectNumber+" "+range2.length+`
|
|
46
46
|
`;for(var entryIdx=0,entryLen=range2.length;entryIdx<entryLen;entryIdx++){var entry=range2[entryIdx];section+=padStart(String(entry.offset),10,"0");section+=" ";section+=padStart(String(entry.ref.generationNumber),5,"0");section+=" ";section+=entry.deleted?"f":"n";section+=`
|
|
47
47
|
`}}return section};PDFCrossRefSection2.prototype.sizeInBytes=function(){var size=5;for(var idx3=0,len2=this.subsections.length;idx3<len2;idx3++){var subsection=this.subsections[idx3];var subsectionLength=subsection.length;var firstEntry=subsection[0];size+=2;size+=String(firstEntry.ref.objectNumber).length;size+=String(subsectionLength).length;size+=20*subsectionLength}return size};PDFCrossRefSection2.prototype.copyBytesInto=function(buffer,offset){var initialOffset=offset;buffer[offset++]=CharCodes_default.x;buffer[offset++]=CharCodes_default.r;buffer[offset++]=CharCodes_default.e;buffer[offset++]=CharCodes_default.f;buffer[offset++]=CharCodes_default.Newline;offset+=this.copySubsectionsIntoBuffer(this.subsections,buffer,offset);return offset-initialOffset};PDFCrossRefSection2.prototype.copySubsectionsIntoBuffer=function(subsections,buffer,offset){var initialOffset=offset;var length=subsections.length;for(var idx3=0;idx3<length;idx3++){var subsection=this.subsections[idx3];var firstObjectNumber=String(subsection[0].ref.objectNumber);offset+=copyStringIntoBuffer(firstObjectNumber,buffer,offset);buffer[offset++]=CharCodes_default.Space;var rangeLength=String(subsection.length);offset+=copyStringIntoBuffer(rangeLength,buffer,offset);buffer[offset++]=CharCodes_default.Newline;offset+=this.copyEntriesIntoBuffer(subsection,buffer,offset)}return offset-initialOffset};PDFCrossRefSection2.prototype.copyEntriesIntoBuffer=function(entries,buffer,offset){var length=entries.length;for(var idx3=0;idx3<length;idx3++){var entry=entries[idx3];var entryOffset=padStart(String(entry.offset),10,"0");offset+=copyStringIntoBuffer(entryOffset,buffer,offset);buffer[offset++]=CharCodes_default.Space;var entryGen=padStart(String(entry.ref.generationNumber),5,"0");offset+=copyStringIntoBuffer(entryGen,buffer,offset);buffer[offset++]=CharCodes_default.Space;buffer[offset++]=entry.deleted?CharCodes_default.f:CharCodes_default.n;buffer[offset++]=CharCodes_default.Space;buffer[offset++]=CharCodes_default.Newline}return 20*length};PDFCrossRefSection2.prototype.append=function(currEntry){if(this.chunkLength===0){this.subsections.push([currEntry]);this.chunkIdx=0;this.chunkLength=1;return}var chunk=this.subsections[this.chunkIdx];var prevEntry=chunk[this.chunkLength-1];if(currEntry.ref.objectNumber-prevEntry.ref.objectNumber>1){this.subsections.push([currEntry]);this.chunkIdx+=1;this.chunkLength=1}else{chunk.push(currEntry);this.chunkLength+=1}};PDFCrossRefSection2.create=function(){return new PDFCrossRefSection2({ref:PDFRef_default.of(0,65535),offset:0,deleted:true})};PDFCrossRefSection2.createEmpty=function(){return new PDFCrossRefSection2};return PDFCrossRefSection2}();PDFCrossRefSection_default=PDFCrossRefSection});var PDFTrailer,PDFTrailer_default;var init_PDFTrailer=__esm(()=>{init_CharCodes();init_utils2();PDFTrailer=function(){function PDFTrailer2(lastXRefOffset){this.lastXRefOffset=String(lastXRefOffset)}PDFTrailer2.prototype.toString=function(){return`startxref
|
|
@@ -68,12 +68,12 @@ endbfchar
|
|
|
68
68
|
endcmap
|
|
69
69
|
CMapName currentdict /CMap defineresource pop
|
|
70
70
|
end
|
|
71
|
-
end`},cmapHexFormat=function(){var values2=[];for(var _i=0;_i<arguments.length;_i++){values2[_i]=arguments[_i]}return"<"+values2.join("")+">"},cmapHexString=function(value){return toHexStringOfMinLength(value,4)},cmapCodePointFormat=function(codePoint){if(isWithinBMP(codePoint))return cmapHexString(codePoint);if(hasSurrogates(codePoint)){var hs=highSurrogate(codePoint);var ls=lowSurrogate(codePoint);return""+cmapHexString(hs)+cmapHexString(ls)}var hex=toHexString(codePoint);var msg="0x"+hex+" is not a valid UTF-8 or UTF-16 codepoint.";throw new Error(msg)};var init_CMap=__esm(()=>{init_utils2();init_unicode()});var makeFontFlags=function(options){var flags=0;var flipBit=function(bit){flags|=1<<bit-1};if(options.fixedPitch)flipBit(1);if(options.serif)flipBit(2);if(options.symbolic)flipBit(3);if(options.script)flipBit(4);if(options.nonsymbolic)flipBit(6);if(options.italic)flipBit(7);if(options.allCap)flipBit(17);if(options.smallCap)flipBit(18);if(options.forceBold)flipBit(19);return flags},deriveFontFlags=function(font){var familyClass=font["OS/2"]?font["OS/2"].sFamilyClass:0;var flags=makeFontFlags({fixedPitch:font.post.isFixedPitch,serif:1<=familyClass&&familyClass<=7,symbolic:true,script:familyClass===10,italic:font.head.macStyle.italic});return flags};var PDFString,PDFString_default;var init_PDFString=__esm(()=>{init_tslib_es62();init_PDFObject();init_CharCodes();init_utils2();init_errors2();PDFString=function(_super){__extends(PDFString2,_super);function PDFString2(value){var _this=_super.call(this)||this;_this.value=value;return _this}PDFString2.prototype.asBytes=function(){var bytes=[];var octal="";var escaped=false;var pushByte=function(byte2){if(byte2!==undefined)bytes.push(byte2);escaped=false};for(var idx3=0,len2=this.value.length;idx3<len2;idx3++){var char=this.value[idx3];var byte=toCharCode(char);var nextChar=this.value[idx3+1];if(!escaped){if(byte===CharCodes_default.BackSlash)escaped=true;else pushByte(byte)}else{if(byte===CharCodes_default.Newline)pushByte();else if(byte===CharCodes_default.CarriageReturn)pushByte();else if(byte===CharCodes_default.n)pushByte(CharCodes_default.Newline);else if(byte===CharCodes_default.r)pushByte(CharCodes_default.CarriageReturn);else if(byte===CharCodes_default.t)pushByte(CharCodes_default.Tab);else if(byte===CharCodes_default.b)pushByte(CharCodes_default.Backspace);else if(byte===CharCodes_default.f)pushByte(CharCodes_default.FormFeed);else if(byte===CharCodes_default.LeftParen)pushByte(CharCodes_default.LeftParen);else if(byte===CharCodes_default.RightParen)pushByte(CharCodes_default.RightParen);else if(byte===CharCodes_default.Backspace)pushByte(CharCodes_default.BackSlash);else if(byte>=CharCodes_default.Zero&&byte<=CharCodes_default.Seven){octal+=char;if(octal.length===3||!(nextChar>="0"&&nextChar<="7")){pushByte(parseInt(octal,8));octal=""}}else{pushByte(byte)}}}return new Uint8Array(bytes)};PDFString2.prototype.decodeText=function(){var bytes=this.asBytes();if(hasUtf16BOM(bytes))return utf16Decode(bytes);return pdfDocEncodingDecode(bytes)};PDFString2.prototype.decodeDate=function(){var text4=this.decodeText();var date2=parseDate(text4);if(!date2)throw new InvalidPDFDateStringError(text4);return date2};PDFString2.prototype.asString=function(){return this.value};PDFString2.prototype.clone=function(){return PDFString2.of(this.value)};PDFString2.prototype.toString=function(){return"("+this.value+")"};PDFString2.prototype.sizeInBytes=function(){return this.value.length+2};PDFString2.prototype.copyBytesInto=function(buffer,offset){buffer[offset++]=CharCodes_default.LeftParen;offset+=copyStringIntoBuffer(this.value,buffer,offset);buffer[offset++]=CharCodes_default.RightParen;return this.value.length+2};PDFString2.of=function(value){return new PDFString2(value)};PDFString2.fromDate=function(date2){var year=padStart(String(date2.getUTCFullYear()),4,"0");var month=padStart(String(date2.getUTCMonth()+1),2,"0");var day=padStart(String(date2.getUTCDate()),2,"0");var hours=padStart(String(date2.getUTCHours()),2,"0");var mins=padStart(String(date2.getUTCMinutes()),2,"0");var secs=padStart(String(date2.getUTCSeconds()),2,"0");return new PDFString2("D:"+year+month+day+hours+mins+secs+"Z")};return PDFString2}(PDFObject_default);PDFString_default=PDFString});var CustomFontEmbedder,CustomFontEmbedder_default;var init_CustomFontEmbedder=__esm(()=>{init_tslib_es62();init_CMap();init_PDFHexString();init_PDFString();init_utils2();CustomFontEmbedder=function(){function CustomFontEmbedder2(font,fontData,customName,fontFeatures){var _this=this;this.allGlyphsInFontSortedById=function(){var glyphs=new Array(_this.font.characterSet.length);for(var idx3=0,len2=glyphs.length;idx3<len2;idx3++){var codePoint=_this.font.characterSet[idx3];glyphs[idx3]=_this.font.glyphForCodePoint(codePoint)}return sortedUniq(glyphs.sort(byAscendingId),function(g){return g.id})};this.font=font;this.scale=1000/this.font.unitsPerEm;this.fontData=fontData;this.fontName=this.font.postscriptName||"Font";this.customName=customName;this.fontFeatures=fontFeatures;this.baseFontName="";this.glyphCache=Cache_default.populatedBy(this.allGlyphsInFontSortedById)}CustomFontEmbedder2.for=function(fontkit,fontData,customName,fontFeatures){return __awaiter(this,undefined,undefined,function(){var font;return __generator(this,function(_a){switch(_a.label){case 0:return[4,fontkit.create(fontData)];case 1:font=_a.sent();return[2,new CustomFontEmbedder2(font,fontData,customName,fontFeatures)]}})})};CustomFontEmbedder2.prototype.encodeText=function(text4){var glyphs=this.font.layout(text4,this.fontFeatures).glyphs;var hexCodes=new Array(glyphs.length);for(var idx3=0,len2=glyphs.length;idx3<len2;idx3++){hexCodes[idx3]=toHexStringOfMinLength(glyphs[idx3].id,4)}return PDFHexString_default.of(hexCodes.join(""))};CustomFontEmbedder2.prototype.widthOfTextAtSize=function(text4,size){var glyphs=this.font.layout(text4,this.fontFeatures).glyphs;var totalWidth=0;for(var idx3=0,len2=glyphs.length;idx3<len2;idx3++){totalWidth+=glyphs[idx3].advanceWidth*this.scale}var scale=size/1000;return totalWidth*scale};CustomFontEmbedder2.prototype.heightOfFontAtSize=function(size,options){if(options===undefined){options={}}var _a=options.descender,descender=_a===undefined?true:_a;var _b=this.font,ascent=_b.ascent,descent=_b.descent,bbox=_b.bbox;var yTop=(ascent||bbox.maxY)*this.scale;var yBottom=(descent||bbox.minY)*this.scale;var height=yTop-yBottom;if(!descender)height-=Math.abs(descent)||0;return height/1000*size};CustomFontEmbedder2.prototype.sizeOfFontAtHeight=function(height){var _a=this.font,ascent=_a.ascent,descent=_a.descent,bbox=_a.bbox;var yTop=(ascent||bbox.maxY)*this.scale;var yBottom=(descent||bbox.minY)*this.scale;return 1000*height/(yTop-yBottom)};CustomFontEmbedder2.prototype.embedIntoContext=function(context2,ref){this.baseFontName=this.customName||context2.addRandomSuffix(this.fontName);return this.embedFontDict(context2,ref)};CustomFontEmbedder2.prototype.embedFontDict=function(context2,ref){return __awaiter(this,undefined,undefined,function(){var cidFontDictRef,unicodeCMapRef,fontDict;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.embedCIDFontDict(context2)];case 1:cidFontDictRef=_a.sent();unicodeCMapRef=this.embedUnicodeCmap(context2);fontDict=context2.obj({Type:"Font",Subtype:"Type0",BaseFont:this.baseFontName,Encoding:"Identity-H",DescendantFonts:[cidFontDictRef],ToUnicode:unicodeCMapRef});if(ref){context2.assign(ref,fontDict);return[2,ref]}else{return[2,context2.register(fontDict)]}return[2]}})})};CustomFontEmbedder2.prototype.isCFF=function(){return this.font.cff};CustomFontEmbedder2.prototype.embedCIDFontDict=function(context2){return __awaiter(this,undefined,undefined,function(){var fontDescriptorRef,cidFontDict;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.embedFontDescriptor(context2)];case 1:fontDescriptorRef=_a.sent();cidFontDict=context2.obj({Type:"Font",Subtype:this.isCFF()?"CIDFontType0":"CIDFontType2",CIDToGIDMap:"Identity",BaseFont:this.baseFontName,CIDSystemInfo:{Registry:PDFString_default.of("Adobe"),Ordering:PDFString_default.of("Identity"),Supplement:0},FontDescriptor:fontDescriptorRef,W:this.computeWidths()});return[2,context2.register(cidFontDict)]}})})};CustomFontEmbedder2.prototype.embedFontDescriptor=function(context2){return __awaiter(this,undefined,undefined,function(){var fontStreamRef,scale,_a,italicAngle,ascent,descent,capHeight,xHeight,_b,minX,minY,maxX,maxY,fontDescriptor;var _c;return __generator(this,function(_d){switch(_d.label){case 0:return[4,this.embedFontStream(context2)];case 1:fontStreamRef=_d.sent();scale=this.scale;_a=this.font,italicAngle=_a.italicAngle,ascent=_a.ascent,descent=_a.descent,capHeight=_a.capHeight,xHeight=_a.xHeight;_b=this.font.bbox,minX=_b.minX,minY=_b.minY,maxX=_b.maxX,maxY=_b.maxY;fontDescriptor=context2.obj((_c={Type:"FontDescriptor",FontName:this.baseFontName,Flags:deriveFontFlags(this.font),FontBBox:[minX*scale,minY*scale,maxX*scale,maxY*scale],ItalicAngle:italicAngle,Ascent:ascent*scale,Descent:descent*scale,CapHeight:(capHeight||ascent)*scale,XHeight:(xHeight||0)*scale,StemV:0},_c[this.isCFF()?"FontFile3":"FontFile2"]=fontStreamRef,_c));return[2,context2.register(fontDescriptor)]}})})};CustomFontEmbedder2.prototype.serializeFont=function(){return __awaiter(this,undefined,undefined,function(){return __generator(this,function(_a){return[2,this.fontData]})})};CustomFontEmbedder2.prototype.embedFontStream=function(context2){return __awaiter(this,undefined,undefined,function(){var fontStream,_a,_b;return __generator(this,function(_c){switch(_c.label){case 0:_b=(_a=context2).flateStream;return[4,this.serializeFont()];case 1:fontStream=_b.apply(_a,[_c.sent(),{Subtype:this.isCFF()?"CIDFontType0C":undefined}]);return[2,context2.register(fontStream)]}})})};CustomFontEmbedder2.prototype.embedUnicodeCmap=function(context2){var cmap=createCmap(this.glyphCache.access(),this.glyphId.bind(this));var cmapStream=context2.flateStream(cmap);return context2.register(cmapStream)};CustomFontEmbedder2.prototype.glyphId=function(glyph){return glyph?glyph.id:-1};CustomFontEmbedder2.prototype.computeWidths=function(){var glyphs=this.glyphCache.access();var widths=[];var currSection=[];for(var idx3=0,len2=glyphs.length;idx3<len2;idx3++){var currGlyph=glyphs[idx3];var prevGlyph=glyphs[idx3-1];var currGlyphId=this.glyphId(currGlyph);var prevGlyphId=this.glyphId(prevGlyph);if(idx3===0){widths.push(currGlyphId)}else if(currGlyphId-prevGlyphId!==1){widths.push(currSection);widths.push(currGlyphId);currSection=[]}currSection.push(currGlyph.advanceWidth*this.scale)}widths.push(currSection);return widths};return CustomFontEmbedder2}();CustomFontEmbedder_default=CustomFontEmbedder});var CustomFontSubsetEmbedder,CustomFontSubsetEmbedder_default;var init_CustomFontSubsetEmbedder=__esm(()=>{init_tslib_es62();init_CustomFontEmbedder();init_PDFHexString();init_utils2();CustomFontSubsetEmbedder=function(_super){__extends(CustomFontSubsetEmbedder2,_super);function CustomFontSubsetEmbedder2(font,fontData,customFontName,fontFeatures){var _this=_super.call(this,font,fontData,customFontName,fontFeatures)||this;_this.subset=_this.font.createSubset();_this.glyphs=[];_this.glyphCache=Cache_default.populatedBy(function(){return _this.glyphs});_this.glyphIdMap=new Map;return _this}CustomFontSubsetEmbedder2.for=function(fontkit,fontData,customFontName,fontFeatures){return __awaiter(this,undefined,undefined,function(){var font;return __generator(this,function(_a){switch(_a.label){case 0:return[4,fontkit.create(fontData)];case 1:font=_a.sent();return[2,new CustomFontSubsetEmbedder2(font,fontData,customFontName,fontFeatures)]}})})};CustomFontSubsetEmbedder2.prototype.encodeText=function(text4){var glyphs=this.font.layout(text4,this.fontFeatures).glyphs;var hexCodes=new Array(glyphs.length);for(var idx3=0,len2=glyphs.length;idx3<len2;idx3++){var glyph=glyphs[idx3];var subsetGlyphId=this.subset.includeGlyph(glyph);this.glyphs[subsetGlyphId-1]=glyph;this.glyphIdMap.set(glyph.id,subsetGlyphId);hexCodes[idx3]=toHexStringOfMinLength(subsetGlyphId,4)}this.glyphCache.invalidate();return PDFHexString_default.of(hexCodes.join(""))};CustomFontSubsetEmbedder2.prototype.isCFF=function(){return this.subset.cff};CustomFontSubsetEmbedder2.prototype.glyphId=function(glyph){return glyph?this.glyphIdMap.get(glyph.id):-1};CustomFontSubsetEmbedder2.prototype.serializeFont=function(){var _this=this;return new Promise(function(resolve,reject){var parts=[];_this.subset.encodeStream().on("data",function(bytes){return parts.push(bytes)}).on("end",function(){return resolve(mergeUint8Arrays(parts))}).on("error",function(err){return reject(err)})})};return CustomFontSubsetEmbedder2}(CustomFontEmbedder_default);CustomFontSubsetEmbedder_default=CustomFontSubsetEmbedder});var AFRelationship,FileEmbedder,FileEmbedder_default;var init_FileEmbedder=__esm(()=>{init_tslib_es62();init_PDFString();init_PDFHexString();(function(AFRelationship2){AFRelationship2["Source"]="Source";AFRelationship2["Data"]="Data";AFRelationship2["Alternative"]="Alternative";AFRelationship2["Supplement"]="Supplement";AFRelationship2["EncryptedPayload"]="EncryptedPayload";AFRelationship2["FormData"]="EncryptedPayload";AFRelationship2["Schema"]="Schema";AFRelationship2["Unspecified"]="Unspecified"})(AFRelationship||(AFRelationship={}));FileEmbedder=function(){function FileEmbedder2(fileData,fileName,options){if(options===undefined){options={}}this.fileData=fileData;this.fileName=fileName;this.options=options}FileEmbedder2.for=function(bytes,fileName,options){if(options===undefined){options={}}return new FileEmbedder2(bytes,fileName,options)};FileEmbedder2.prototype.embedIntoContext=function(context2,ref){return __awaiter(this,undefined,undefined,function(){var _a,mimeType,description,creationDate,modificationDate,afRelationship,embeddedFileStream,embeddedFileStreamRef,fileSpecDict;return __generator(this,function(_b){_a=this.options,mimeType=_a.mimeType,description=_a.description,creationDate=_a.creationDate,modificationDate=_a.modificationDate,afRelationship=_a.afRelationship;embeddedFileStream=context2.flateStream(this.fileData,{Type:"EmbeddedFile",Subtype:mimeType!==null&&mimeType!==undefined?mimeType:undefined,Params:{Size:this.fileData.length,CreationDate:creationDate?PDFString_default.fromDate(creationDate):undefined,ModDate:modificationDate?PDFString_default.fromDate(modificationDate):undefined}});embeddedFileStreamRef=context2.register(embeddedFileStream);fileSpecDict=context2.obj({Type:"Filespec",F:PDFString_default.of(this.fileName),UF:PDFHexString_default.fromText(this.fileName),EF:{F:embeddedFileStreamRef},Desc:description?PDFHexString_default.fromText(description):undefined,AFRelationship:afRelationship!==null&&afRelationship!==undefined?afRelationship:undefined});if(ref){context2.assign(ref,fileSpecDict);return[2,ref]}else{return[2,context2.register(fileSpecDict)]}return[2]})})};return FileEmbedder2}();FileEmbedder_default=FileEmbedder});var MARKERS,ColorSpace,ChannelToColorSpace,JpegEmbedder,JpegEmbedder_default;var init_JpegEmbedder=__esm(()=>{init_tslib_es62();MARKERS=[65472,65473,65474,65475,65477,65478,65479,65480,65481,65482,65483,65484,65485,65486,65487];(function(ColorSpace2){ColorSpace2["DeviceGray"]="DeviceGray";ColorSpace2["DeviceRGB"]="DeviceRGB";ColorSpace2["DeviceCMYK"]="DeviceCMYK"})(ColorSpace||(ColorSpace={}));ChannelToColorSpace={1:ColorSpace.DeviceGray,3:ColorSpace.DeviceRGB,4:ColorSpace.DeviceCMYK};JpegEmbedder=function(){function JpegEmbedder2(imageData,bitsPerComponent,width,height,colorSpace){this.imageData=imageData;this.bitsPerComponent=bitsPerComponent;this.width=width;this.height=height;this.colorSpace=colorSpace}JpegEmbedder2.for=function(imageData){return __awaiter(this,undefined,undefined,function(){var dataView,soi,pos,marker,bitsPerComponent,height,width,channelByte,channelName,colorSpace;return __generator(this,function(_a){dataView=new DataView(imageData.buffer);soi=dataView.getUint16(0);if(soi!==65496)throw new Error("SOI not found in JPEG");pos=2;while(pos<dataView.byteLength){marker=dataView.getUint16(pos);pos+=2;if(MARKERS.includes(marker))break;pos+=dataView.getUint16(pos)}if(!MARKERS.includes(marker))throw new Error("Invalid JPEG");pos+=2;bitsPerComponent=dataView.getUint8(pos++);height=dataView.getUint16(pos);pos+=2;width=dataView.getUint16(pos);pos+=2;channelByte=dataView.getUint8(pos++);channelName=ChannelToColorSpace[channelByte];if(!channelName)throw new Error("Unknown JPEG channel.");colorSpace=channelName;return[2,new JpegEmbedder2(imageData,bitsPerComponent,width,height,colorSpace)]})})};JpegEmbedder2.prototype.embedIntoContext=function(context2,ref){return __awaiter(this,undefined,undefined,function(){var xObject;return __generator(this,function(_a){xObject=context2.stream(this.imageData,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.bitsPerComponent,Width:this.width,Height:this.height,ColorSpace:this.colorSpace,Filter:"DCTDecode",Decode:this.colorSpace===ColorSpace.DeviceCMYK?[1,0,1,0,1,0,1,0]:undefined});if(ref){context2.assign(ref,xObject);return[2,ref]}else{return[2,context2.register(xObject)]}return[2]})})};return JpegEmbedder2}();JpegEmbedder_default=JpegEmbedder});var import_pako4,UPNG,UPNG_default;var init_UPNG=__esm(()=>{import_pako4=__toESM(require_pako(),1);UPNG={};UPNG.toRGBA8=function(out){var{width:w,height:h}=out;if(out.tabs.acTL==null)return[UPNG.toRGBA8.decodeImage(out.data,w,h,out).buffer];var frms=[];if(out.frames[0].data==null)out.frames[0].data=out.data;var len2=w*h*4,img=new Uint8Array(len2),empty2=new Uint8Array(len2),prev=new Uint8Array(len2);for(var i3=0;i3<out.frames.length;i3++){var frm=out.frames[i3];var fx=frm.rect.x,fy=frm.rect.y,fw=frm.rect.width,fh=frm.rect.height;var fdata=UPNG.toRGBA8.decodeImage(frm.data,fw,fh,out);if(i3!=0)for(var j=0;j<len2;j++)prev[j]=img[j];if(frm.blend==0)UPNG._copyTile(fdata,fw,fh,img,w,h,fx,fy,0);else if(frm.blend==1)UPNG._copyTile(fdata,fw,fh,img,w,h,fx,fy,1);frms.push(img.buffer.slice(0));if(frm.dispose==0){}else if(frm.dispose==1)UPNG._copyTile(empty2,fw,fh,img,w,h,fx,fy,0);else if(frm.dispose==2)for(var j=0;j<len2;j++)img[j]=prev[j]}return frms};UPNG.toRGBA8.decodeImage=function(data2,w,h,out){var area=w*h,bpp=UPNG.decode._getBPP(out);var bpl=Math.ceil(w*bpp/8);var bf=new Uint8Array(area*4),bf32=new Uint32Array(bf.buffer);var{ctype,depth}=out;var rs=UPNG._bin.readUshort;var time=Date.now();if(ctype==6){var qarea=area<<2;if(depth==8)for(var i3=0;i3<qarea;i3+=4){bf[i3]=data2[i3];bf[i3+1]=data2[i3+1];bf[i3+2]=data2[i3+2];bf[i3+3]=data2[i3+3]}if(depth==16)for(var i3=0;i3<qarea;i3++){bf[i3]=data2[i3<<1]}}else if(ctype==2){var ts=out.tabs["tRNS"];if(ts==null){if(depth==8)for(var i3=0;i3<area;i3++){var ti=i3*3;bf32[i3]=255<<24|data2[ti+2]<<16|data2[ti+1]<<8|data2[ti]}if(depth==16)for(var i3=0;i3<area;i3++){var ti=i3*6;bf32[i3]=255<<24|data2[ti+4]<<16|data2[ti+2]<<8|data2[ti]}}else{var tr=ts[0],tg=ts[1],tb=ts[2];if(depth==8)for(var i3=0;i3<area;i3++){var qi=i3<<2,ti=i3*3;bf32[i3]=255<<24|data2[ti+2]<<16|data2[ti+1]<<8|data2[ti];if(data2[ti]==tr&&data2[ti+1]==tg&&data2[ti+2]==tb)bf[qi+3]=0}if(depth==16)for(var i3=0;i3<area;i3++){var qi=i3<<2,ti=i3*6;bf32[i3]=255<<24|data2[ti+4]<<16|data2[ti+2]<<8|data2[ti];if(rs(data2,ti)==tr&&rs(data2,ti+2)==tg&&rs(data2,ti+4)==tb)bf[qi+3]=0}}}else if(ctype==3){var p=out.tabs["PLTE"],ap=out.tabs["tRNS"],tl=ap?ap.length:0;if(depth==1)for(var y=0;y<h;y++){var s0=y*bpl,t0=y*w;for(var i3=0;i3<w;i3++){var qi=t0+i3<<2,j=data2[s0+(i3>>3)]>>7-((i3&7)<<0)&1,cj=3*j;bf[qi]=p[cj];bf[qi+1]=p[cj+1];bf[qi+2]=p[cj+2];bf[qi+3]=j<tl?ap[j]:255}}if(depth==2)for(var y=0;y<h;y++){var s0=y*bpl,t0=y*w;for(var i3=0;i3<w;i3++){var qi=t0+i3<<2,j=data2[s0+(i3>>2)]>>6-((i3&3)<<1)&3,cj=3*j;bf[qi]=p[cj];bf[qi+1]=p[cj+1];bf[qi+2]=p[cj+2];bf[qi+3]=j<tl?ap[j]:255}}if(depth==4)for(var y=0;y<h;y++){var s0=y*bpl,t0=y*w;for(var i3=0;i3<w;i3++){var qi=t0+i3<<2,j=data2[s0+(i3>>1)]>>4-((i3&1)<<2)&15,cj=3*j;bf[qi]=p[cj];bf[qi+1]=p[cj+1];bf[qi+2]=p[cj+2];bf[qi+3]=j<tl?ap[j]:255}}if(depth==8)for(var i3=0;i3<area;i3++){var qi=i3<<2,j=data2[i3],cj=3*j;bf[qi]=p[cj];bf[qi+1]=p[cj+1];bf[qi+2]=p[cj+2];bf[qi+3]=j<tl?ap[j]:255}}else if(ctype==4){if(depth==8)for(var i3=0;i3<area;i3++){var qi=i3<<2,di=i3<<1,gr=data2[di];bf[qi]=gr;bf[qi+1]=gr;bf[qi+2]=gr;bf[qi+3]=data2[di+1]}if(depth==16)for(var i3=0;i3<area;i3++){var qi=i3<<2,di=i3<<2,gr=data2[di];bf[qi]=gr;bf[qi+1]=gr;bf[qi+2]=gr;bf[qi+3]=data2[di+2]}}else if(ctype==0){var tr=out.tabs["tRNS"]?out.tabs["tRNS"]:-1;for(var y=0;y<h;y++){var off=y*bpl,to=y*w;if(depth==1)for(var x=0;x<w;x++){var gr=255*(data2[off+(x>>>3)]>>>7-(x&7)&1),al=gr==tr*255?0:255;bf32[to+x]=al<<24|gr<<16|gr<<8|gr}else if(depth==2)for(var x=0;x<w;x++){var gr=85*(data2[off+(x>>>2)]>>>6-((x&3)<<1)&3),al=gr==tr*85?0:255;bf32[to+x]=al<<24|gr<<16|gr<<8|gr}else if(depth==4)for(var x=0;x<w;x++){var gr=17*(data2[off+(x>>>1)]>>>4-((x&1)<<2)&15),al=gr==tr*17?0:255;bf32[to+x]=al<<24|gr<<16|gr<<8|gr}else if(depth==8)for(var x=0;x<w;x++){var gr=data2[off+x],al=gr==tr?0:255;bf32[to+x]=al<<24|gr<<16|gr<<8|gr}else if(depth==16)for(var x=0;x<w;x++){var gr=data2[off+(x<<1)],al=rs(data2,off+(x<<i3))==tr?0:255;bf32[to+x]=al<<24|gr<<16|gr<<8|gr}}}return bf};UPNG.decode=function(buff){var data2=new Uint8Array(buff),offset=8,bin=UPNG._bin,rUs=bin.readUshort,rUi=bin.readUint;var out={tabs:{},frames:[]};var dd=new Uint8Array(data2.length),doff=0;var fd,foff=0;var mgck=[137,80,78,71,13,10,26,10];for(var i3=0;i3<8;i3++)if(data2[i3]!=mgck[i3])throw"The input is not a PNG file!";while(offset<data2.length){var len2=bin.readUint(data2,offset);offset+=4;var type=bin.readASCII(data2,offset,4);offset+=4;if(type=="IHDR"){UPNG.decode._IHDR(data2,offset,out)}else if(type=="IDAT"){for(var i3=0;i3<len2;i3++)dd[doff+i3]=data2[offset+i3];doff+=len2}else if(type=="acTL"){out.tabs[type]={num_frames:rUi(data2,offset),num_plays:rUi(data2,offset+4)};fd=new Uint8Array(data2.length)}else if(type=="fcTL"){if(foff!=0){var fr=out.frames[out.frames.length-1];fr.data=UPNG.decode._decompress(out,fd.slice(0,foff),fr.rect.width,fr.rect.height);foff=0}var rct={x:rUi(data2,offset+12),y:rUi(data2,offset+16),width:rUi(data2,offset+4),height:rUi(data2,offset+8)};var del=rUs(data2,offset+22);del=rUs(data2,offset+20)/(del==0?100:del);var frm={rect:rct,delay:Math.round(del*1000),dispose:data2[offset+24],blend:data2[offset+25]};out.frames.push(frm)}else if(type=="fdAT"){for(var i3=0;i3<len2-4;i3++)fd[foff+i3]=data2[offset+i3+4];foff+=len2-4}else if(type=="pHYs"){out.tabs[type]=[bin.readUint(data2,offset),bin.readUint(data2,offset+4),data2[offset+8]]}else if(type=="cHRM"){out.tabs[type]=[];for(var i3=0;i3<8;i3++)out.tabs[type].push(bin.readUint(data2,offset+i3*4))}else if(type=="tEXt"){if(out.tabs[type]==null)out.tabs[type]={};var nz=bin.nextZero(data2,offset);var keyw=bin.readASCII(data2,offset,nz-offset);var text4=bin.readASCII(data2,nz+1,offset+len2-nz-1);out.tabs[type][keyw]=text4}else if(type=="iTXt"){if(out.tabs[type]==null)out.tabs[type]={};var nz=0,off=offset;nz=bin.nextZero(data2,off);var keyw=bin.readASCII(data2,off,nz-off);off=nz+1;var cflag=data2[off],cmeth=data2[off+1];off+=2;nz=bin.nextZero(data2,off);var ltag=bin.readASCII(data2,off,nz-off);off=nz+1;nz=bin.nextZero(data2,off);var tkeyw=bin.readUTF8(data2,off,nz-off);off=nz+1;var text4=bin.readUTF8(data2,off,len2-(off-offset));out.tabs[type][keyw]=text4}else if(type=="PLTE"){out.tabs[type]=bin.readBytes(data2,offset,len2)}else if(type=="hIST"){var pl=out.tabs["PLTE"].length/3;out.tabs[type]=[];for(var i3=0;i3<pl;i3++)out.tabs[type].push(rUs(data2,offset+i3*2))}else if(type=="tRNS"){if(out.ctype==3)out.tabs[type]=bin.readBytes(data2,offset,len2);else if(out.ctype==0)out.tabs[type]=rUs(data2,offset);else if(out.ctype==2)out.tabs[type]=[rUs(data2,offset),rUs(data2,offset+2),rUs(data2,offset+4)]}else if(type=="gAMA")out.tabs[type]=bin.readUint(data2,offset)/1e5;else if(type=="sRGB")out.tabs[type]=data2[offset];else if(type=="bKGD"){if(out.ctype==0||out.ctype==4)out.tabs[type]=[rUs(data2,offset)];else if(out.ctype==2||out.ctype==6)out.tabs[type]=[rUs(data2,offset),rUs(data2,offset+2),rUs(data2,offset+4)];else if(out.ctype==3)out.tabs[type]=data2[offset]}else if(type=="IEND"){break}offset+=len2;var crc=bin.readUint(data2,offset);offset+=4}if(foff!=0){var fr=out.frames[out.frames.length-1];fr.data=UPNG.decode._decompress(out,fd.slice(0,foff),fr.rect.width,fr.rect.height);foff=0}out.data=UPNG.decode._decompress(out,dd,out.width,out.height);delete out.compress;delete out.interlace;delete out.filter;return out};UPNG.decode._decompress=function(out,dd,w,h){var time=Date.now();var bpp=UPNG.decode._getBPP(out),bpl=Math.ceil(w*bpp/8),buff=new Uint8Array((bpl+1+out.interlace)*h);dd=UPNG.decode._inflate(dd,buff);var time=Date.now();if(out.interlace==0)dd=UPNG.decode._filterZero(dd,out,0,w,h);else if(out.interlace==1)dd=UPNG.decode._readInterlace(dd,out);return dd};UPNG.decode._inflate=function(data2,buff){var out=UPNG["inflateRaw"](new Uint8Array(data2.buffer,2,data2.length-6),buff);return out};UPNG.inflateRaw=function(){var H={};H.H={};H.H.N=function(N,W){var R=Uint8Array,i3=0,m=0,J=0,h=0,Q=0,X=0,u=0,w=0,d=0,v,C;if(N[0]==3&&N[1]==0)return W?W:new R(0);var V=H.H,n=V.b,A=V.e,l=V.R,M=V.n,I=V.A,e=V.Z,b=V.m,Z=W==null;if(Z)W=new R(N.length>>>2<<3);while(i3==0){i3=n(N,d,1);m=n(N,d+1,2);d+=3;if(m==0){if((d&7)!=0)d+=8-(d&7);var D=(d>>>3)+4,q=N[D-4]|N[D-3]<<8;if(Z)W=H.H.W(W,w+q);W.set(new R(N.buffer,N.byteOffset+D,q),w);d=D+q<<3;w+=q;continue}if(Z)W=H.H.W(W,w+(1<<17));if(m==1){v=b.J;C=b.h;X=(1<<9)-1;u=(1<<5)-1}if(m==2){J=A(N,d,5)+257;h=A(N,d+5,5)+1;Q=A(N,d+10,4)+4;d+=14;var E=d,j=1;for(var c=0;c<38;c+=2){b.Q[c]=0;b.Q[c+1]=0}for(var c=0;c<Q;c++){var K=A(N,d+c*3,3);b.Q[(b.X[c]<<1)+1]=K;if(K>j)j=K}d+=3*Q;M(b.Q,j);I(b.Q,j,b.u);v=b.w;C=b.d;d=l(b.u,(1<<j)-1,J+h,N,d,b.v);var r=V.V(b.v,0,J,b.C);X=(1<<r)-1;var S=V.V(b.v,J,h,b.D);u=(1<<S)-1;M(b.C,r);I(b.C,r,v);M(b.D,S);I(b.D,S,C)}while(true){var T=v[e(N,d)&X];d+=T&15;var p=T>>>4;if(p>>>8==0){W[w++]=p}else if(p==256){break}else{var z=w+p-254;if(p>264){var _=b.q[p-257];z=w+(_>>>3)+A(N,d,_&7);d+=_&7}var $=C[e(N,d)&u];d+=$&15;var s=$>>>4,Y=b.c[s],a=(Y>>>4)+n(N,d,Y&15);d+=Y&15;while(w<z){W[w]=W[w++-a];W[w]=W[w++-a];W[w]=W[w++-a];W[w]=W[w++-a]}w=z}}}return W.length==w?W:W.slice(0,w)};H.H.W=function(N,W){var R=N.length;if(W<=R)return N;var V=new Uint8Array(R<<1);V.set(N,0);return V};H.H.R=function(N,W,R,V,n,A){var l=H.H.e,M=H.H.Z,I=0;while(I<R){var e=N[M(V,n)&W];n+=e&15;var b=e>>>4;if(b<=15){A[I]=b;I++}else{var Z=0,m=0;if(b==16){m=3+l(V,n,2);n+=2;Z=A[I-1]}else if(b==17){m=3+l(V,n,3);n+=3}else if(b==18){m=11+l(V,n,7);n+=7}var J=I+m;while(I<J){A[I]=Z;I++}}}return n};H.H.V=function(N,W,R,V){var n=0,A=0,l=V.length>>>1;while(A<R){var M=N[A+W];V[A<<1]=0;V[(A<<1)+1]=M;if(M>n)n=M;A++}while(A<l){V[A<<1]=0;V[(A<<1)+1]=0;A++}return n};H.H.n=function(N,W){var R=H.H.m,V=N.length,n,A,l,M,I,e=R.j;for(var M=0;M<=W;M++)e[M]=0;for(M=1;M<V;M+=2)e[N[M]]++;var b=R.K;n=0;e[0]=0;for(A=1;A<=W;A++){n=n+e[A-1]<<1;b[A]=n}for(l=0;l<V;l+=2){I=N[l+1];if(I!=0){N[l]=b[I];b[I]++}}};H.H.A=function(N,W,R){var V=N.length,n=H.H.m,A=n.r;for(var l=0;l<V;l+=2)if(N[l+1]!=0){var M=l>>1,I=N[l+1],e=M<<4|I,b=W-I,Z=N[l]<<b,m=Z+(1<<b);while(Z!=m){var J=A[Z]>>>15-W;R[J]=e;Z++}}};H.H.l=function(N,W){var R=H.H.m.r,V=15-W;for(var n=0;n<N.length;n+=2){var A=N[n]<<W-N[n+1];N[n]=R[A]>>>V}};H.H.M=function(N,W,R){R=R<<(W&7);var V=W>>>3;N[V]|=R;N[V+1]|=R>>>8};H.H.I=function(N,W,R){R=R<<(W&7);var V=W>>>3;N[V]|=R;N[V+1]|=R>>>8;N[V+2]|=R>>>16};H.H.e=function(N,W,R){return(N[W>>>3]|N[(W>>>3)+1]<<8)>>>(W&7)&(1<<R)-1};H.H.b=function(N,W,R){return(N[W>>>3]|N[(W>>>3)+1]<<8|N[(W>>>3)+2]<<16)>>>(W&7)&(1<<R)-1};H.H.Z=function(N,W){return(N[W>>>3]|N[(W>>>3)+1]<<8|N[(W>>>3)+2]<<16)>>>(W&7)};H.H.i=function(N,W){return(N[W>>>3]|N[(W>>>3)+1]<<8|N[(W>>>3)+2]<<16|N[(W>>>3)+3]<<24)>>>(W&7)};H.H.m=function(){var N=Uint16Array,W=Uint32Array;return{K:new N(16),j:new N(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new N(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new W(32),J:new N(512),_:[],h:new N(32),$:[],w:new N(32768),C:[],v:[],d:new N(32768),D:[],u:new N(512),Q:[],r:new N(1<<15),s:new W(286),Y:new W(30),a:new W(19),t:new W(15000),k:new N(1<<16),g:new N(1<<15)}}();(function(){var N=H.H.m,W=1<<15;for(var R=0;R<W;R++){var V=R;V=(V&2863311530)>>>1|(V&1431655765)<<1;V=(V&3435973836)>>>2|(V&858993459)<<2;V=(V&4042322160)>>>4|(V&252645135)<<4;V=(V&4278255360)>>>8|(V&16711935)<<8;N.r[R]=(V>>>16|V<<16)>>>17}function n(A,l,M){while(l--!=0)A.push(0,M)}for(var R=0;R<32;R++){N.q[R]=N.S[R]<<3|N.T[R];N.c[R]=N.p[R]<<4|N.z[R]}n(N._,144,8);n(N._,255-143,9);n(N._,279-255,7);n(N._,287-279,8);H.H.n(N._,9);H.H.A(N._,9,N.J);H.H.l(N._,9);n(N.$,32,5);H.H.n(N.$,5);H.H.A(N.$,5,N.h);H.H.l(N.$,5);n(N.Q,19,0);n(N.C,286,0);n(N.D,30,0);n(N.v,320,0)})();return H.H.N}();UPNG.decode._readInterlace=function(data2,out){var{width:w,height:h}=out;var bpp=UPNG.decode._getBPP(out),cbpp=bpp>>3,bpl=Math.ceil(w*bpp/8);var img=new Uint8Array(h*bpl);var di=0;var starting_row=[0,0,4,0,2,0,1];var starting_col=[0,4,0,2,0,1,0];var row_increment=[8,8,8,4,4,2,2];var col_increment=[8,8,4,4,2,2,1];var pass=0;while(pass<7){var ri=row_increment[pass],ci=col_increment[pass];var sw=0,sh=0;var cr=starting_row[pass];while(cr<h){cr+=ri;sh++}var cc=starting_col[pass];while(cc<w){cc+=ci;sw++}var bpll=Math.ceil(sw*bpp/8);UPNG.decode._filterZero(data2,out,di,sw,sh);var y=0,row=starting_row[pass];while(row<h){var col=starting_col[pass];var cdi=di+y*bpll<<3;while(col<w){if(bpp==1){var val=data2[cdi>>3];val=val>>7-(cdi&7)&1;img[row*bpl+(col>>3)]|=val<<7-((col&7)<<0)}if(bpp==2){var val=data2[cdi>>3];val=val>>6-(cdi&7)&3;img[row*bpl+(col>>2)]|=val<<6-((col&3)<<1)}if(bpp==4){var val=data2[cdi>>3];val=val>>4-(cdi&7)&15;img[row*bpl+(col>>1)]|=val<<4-((col&1)<<2)}if(bpp>=8){var ii=row*bpl+col*cbpp;for(var j=0;j<cbpp;j++)img[ii+j]=data2[(cdi>>3)+j]}cdi+=bpp;col+=ci}y++;row+=ri}if(sw*sh!=0)di+=sh*(1+bpll);pass=pass+1}return img};UPNG.decode._getBPP=function(out){var noc=[1,null,3,1,2,null,4][out.ctype];return noc*out.depth};UPNG.decode._filterZero=function(data2,out,off,w,h){var bpp=UPNG.decode._getBPP(out),bpl=Math.ceil(w*bpp/8),paeth=UPNG.decode._paeth;bpp=Math.ceil(bpp/8);var i3=0,di=1,type=data2[off],x=0;if(type>1)data2[off]=[0,0,1][type-2];if(type==3)for(x=bpp;x<bpl;x++)data2[x+1]=data2[x+1]+(data2[x+1-bpp]>>>1)&255;for(var y=0;y<h;y++){i3=off+y*bpl;di=i3+y+1;type=data2[di-1];x=0;if(type==0)for(;x<bpl;x++)data2[i3+x]=data2[di+x];else if(type==1){for(;x<bpp;x++)data2[i3+x]=data2[di+x];for(;x<bpl;x++)data2[i3+x]=data2[di+x]+data2[i3+x-bpp]}else if(type==2){for(;x<bpl;x++)data2[i3+x]=data2[di+x]+data2[i3+x-bpl]}else if(type==3){for(;x<bpp;x++)data2[i3+x]=data2[di+x]+(data2[i3+x-bpl]>>>1);for(;x<bpl;x++)data2[i3+x]=data2[di+x]+(data2[i3+x-bpl]+data2[i3+x-bpp]>>>1)}else{for(;x<bpp;x++)data2[i3+x]=data2[di+x]+paeth(0,data2[i3+x-bpl],0);for(;x<bpl;x++)data2[i3+x]=data2[di+x]+paeth(data2[i3+x-bpp],data2[i3+x-bpl],data2[i3+x-bpp-bpl])}}return data2};UPNG.decode._paeth=function(a,b,c){var p=a+b-c,pa=p-a,pb=p-b,pc=p-c;if(pa*pa<=pb*pb&&pa*pa<=pc*pc)return a;else if(pb*pb<=pc*pc)return b;return c};UPNG.decode._IHDR=function(data2,offset,out){var bin=UPNG._bin;out.width=bin.readUint(data2,offset);offset+=4;out.height=bin.readUint(data2,offset);offset+=4;out.depth=data2[offset];offset++;out.ctype=data2[offset];offset++;out.compress=data2[offset];offset++;out.filter=data2[offset];offset++;out.interlace=data2[offset];offset++};UPNG._bin={nextZero:function(data2,p){while(data2[p]!=0)p++;return p},readUshort:function(buff,p){return buff[p]<<8|buff[p+1]},writeUshort:function(buff,p,n){buff[p]=n>>8&255;buff[p+1]=n&255},readUint:function(buff,p){return buff[p]*(256*256*256)+(buff[p+1]<<16|buff[p+2]<<8|buff[p+3])},writeUint:function(buff,p,n){buff[p]=n>>24&255;buff[p+1]=n>>16&255;buff[p+2]=n>>8&255;buff[p+3]=n&255},readASCII:function(buff,p,l){var s="";for(var i3=0;i3<l;i3++)s+=String.fromCharCode(buff[p+i3]);return s},writeASCII:function(data2,p,s){for(var i3=0;i3<s.length;i3++)data2[p+i3]=s.charCodeAt(i3)},readBytes:function(buff,p,l){var arr=[];for(var i3=0;i3<l;i3++)arr.push(buff[p+i3]);return arr},pad:function(n){return n.length<2?"0"+n:n},readUTF8:function(buff,p,l){var s="",ns;for(var i3=0;i3<l;i3++)s+="%"+UPNG._bin.pad(buff[p+i3].toString(16));try{ns=decodeURIComponent(s)}catch(e){return UPNG._bin.readASCII(buff,p,l)}return ns}};UPNG._copyTile=function(sb,sw,sh,tb,tw,th,xoff,yoff,mode){var w=Math.min(sw,tw),h=Math.min(sh,th);var si=0,ti=0;for(var y=0;y<h;y++)for(var x=0;x<w;x++){if(xoff>=0&&yoff>=0){si=y*sw+x<<2;ti=(yoff+y)*tw+xoff+x<<2}else{si=(-yoff+y)*sw-xoff+x<<2;ti=y*tw+x<<2}if(mode==0){tb[ti]=sb[si];tb[ti+1]=sb[si+1];tb[ti+2]=sb[si+2];tb[ti+3]=sb[si+3]}else if(mode==1){var fa=sb[si+3]*(1/255),fr=sb[si]*fa,fg=sb[si+1]*fa,fb=sb[si+2]*fa;var ba=tb[ti+3]*(1/255),br=tb[ti]*ba,bg=tb[ti+1]*ba,bb=tb[ti+2]*ba;var ifa=1-fa,oa=fa+ba*ifa,ioa=oa==0?0:1/oa;tb[ti+3]=255*oa;tb[ti+0]=(fr+br*ifa)*ioa;tb[ti+1]=(fg+bg*ifa)*ioa;tb[ti+2]=(fb+bb*ifa)*ioa}else if(mode==2){var fa=sb[si+3],fr=sb[si],fg=sb[si+1],fb=sb[si+2];var ba=tb[ti+3],br=tb[ti],bg=tb[ti+1],bb=tb[ti+2];if(fa==ba&&fr==br&&fg==bg&&fb==bb){tb[ti]=0;tb[ti+1]=0;tb[ti+2]=0;tb[ti+3]=0}else{tb[ti]=fr;tb[ti+1]=fg;tb[ti+2]=fb;tb[ti+3]=fa}}else if(mode==3){var fa=sb[si+3],fr=sb[si],fg=sb[si+1],fb=sb[si+2];var ba=tb[ti+3],br=tb[ti],bg=tb[ti+1],bb=tb[ti+2];if(fa==ba&&fr==br&&fg==bg&&fb==bb)continue;if(fa<220&&ba>20)return false}}return true};UPNG.encode=function(bufs,w,h,ps,dels,tabs,forbidPlte){if(ps==null)ps=0;if(forbidPlte==null)forbidPlte=false;var nimg=UPNG.encode.compress(bufs,w,h,ps,[false,false,false,0,forbidPlte]);UPNG.encode.compressPNG(nimg,-1);return UPNG.encode._main(nimg,w,h,dels,tabs)};UPNG.encodeLL=function(bufs,w,h,cc,ac,depth,dels,tabs){var nimg={ctype:0+(cc==1?0:2)+(ac==0?0:4),depth,frames:[]};var time=Date.now();var bipp=(cc+ac)*depth,bipl=bipp*w;for(var i3=0;i3<bufs.length;i3++)nimg.frames.push({rect:{x:0,y:0,width:w,height:h},img:new Uint8Array(bufs[i3]),blend:0,dispose:1,bpp:Math.ceil(bipp/8),bpl:Math.ceil(bipl/8)});UPNG.encode.compressPNG(nimg,0,true);var out=UPNG.encode._main(nimg,w,h,dels,tabs);return out};UPNG.encode._main=function(nimg,w,h,dels,tabs){if(tabs==null)tabs={};var crc=UPNG.crc.crc,wUi=UPNG._bin.writeUint,wUs=UPNG._bin.writeUshort,wAs=UPNG._bin.writeASCII;var offset=8,anim=nimg.frames.length>1,pltAlpha=false;var leng=8+(16+5+4)+(anim?20:0);if(tabs["sRGB"]!=null)leng+=8+1+4;if(tabs["pHYs"]!=null)leng+=8+9+4;if(nimg.ctype==3){var dl=nimg.plte.length;for(var i3=0;i3<dl;i3++)if(nimg.plte[i3]>>>24!=255)pltAlpha=true;leng+=8+dl*3+4+(pltAlpha?8+dl*1+4:0)}for(var j=0;j<nimg.frames.length;j++){var fr=nimg.frames[j];if(anim)leng+=38;leng+=fr.cimg.length+12;if(j!=0)leng+=4}leng+=12;var data2=new Uint8Array(leng);var wr=[137,80,78,71,13,10,26,10];for(var i3=0;i3<8;i3++)data2[i3]=wr[i3];wUi(data2,offset,13);offset+=4;wAs(data2,offset,"IHDR");offset+=4;wUi(data2,offset,w);offset+=4;wUi(data2,offset,h);offset+=4;data2[offset]=nimg.depth;offset++;data2[offset]=nimg.ctype;offset++;data2[offset]=0;offset++;data2[offset]=0;offset++;data2[offset]=0;offset++;wUi(data2,offset,crc(data2,offset-17,17));offset+=4;if(tabs["sRGB"]!=null){wUi(data2,offset,1);offset+=4;wAs(data2,offset,"sRGB");offset+=4;data2[offset]=tabs["sRGB"];offset++;wUi(data2,offset,crc(data2,offset-5,5));offset+=4}if(tabs["pHYs"]!=null){wUi(data2,offset,9);offset+=4;wAs(data2,offset,"pHYs");offset+=4;wUi(data2,offset,tabs["pHYs"][0]);offset+=4;wUi(data2,offset,tabs["pHYs"][1]);offset+=4;data2[offset]=tabs["pHYs"][2];offset++;wUi(data2,offset,crc(data2,offset-13,13));offset+=4}if(anim){wUi(data2,offset,8);offset+=4;wAs(data2,offset,"acTL");offset+=4;wUi(data2,offset,nimg.frames.length);offset+=4;wUi(data2,offset,tabs["loop"]!=null?tabs["loop"]:0);offset+=4;wUi(data2,offset,crc(data2,offset-12,12));offset+=4}if(nimg.ctype==3){var dl=nimg.plte.length;wUi(data2,offset,dl*3);offset+=4;wAs(data2,offset,"PLTE");offset+=4;for(var i3=0;i3<dl;i3++){var ti=i3*3,c=nimg.plte[i3],r=c&255,g=c>>>8&255,b=c>>>16&255;data2[offset+ti+0]=r;data2[offset+ti+1]=g;data2[offset+ti+2]=b}offset+=dl*3;wUi(data2,offset,crc(data2,offset-dl*3-4,dl*3+4));offset+=4;if(pltAlpha){wUi(data2,offset,dl);offset+=4;wAs(data2,offset,"tRNS");offset+=4;for(var i3=0;i3<dl;i3++)data2[offset+i3]=nimg.plte[i3]>>>24&255;offset+=dl;wUi(data2,offset,crc(data2,offset-dl-4,dl+4));offset+=4}}var fi=0;for(var j=0;j<nimg.frames.length;j++){var fr=nimg.frames[j];if(anim){wUi(data2,offset,26);offset+=4;wAs(data2,offset,"fcTL");offset+=4;wUi(data2,offset,fi++);offset+=4;wUi(data2,offset,fr.rect.width);offset+=4;wUi(data2,offset,fr.rect.height);offset+=4;wUi(data2,offset,fr.rect.x);offset+=4;wUi(data2,offset,fr.rect.y);offset+=4;wUs(data2,offset,dels[j]);offset+=2;wUs(data2,offset,1000);offset+=2;data2[offset]=fr.dispose;offset++;data2[offset]=fr.blend;offset++;wUi(data2,offset,crc(data2,offset-30,30));offset+=4}var imgd=fr.cimg,dl=imgd.length;wUi(data2,offset,dl+(j==0?0:4));offset+=4;var ioff=offset;wAs(data2,offset,j==0?"IDAT":"fdAT");offset+=4;if(j!=0){wUi(data2,offset,fi++);offset+=4}data2.set(imgd,offset);offset+=dl;wUi(data2,offset,crc(data2,ioff,offset-ioff));offset+=4}wUi(data2,offset,0);offset+=4;wAs(data2,offset,"IEND");offset+=4;wUi(data2,offset,crc(data2,offset-4,4));offset+=4;return data2.buffer};UPNG.encode.compressPNG=function(out,filter,levelZero){for(var i3=0;i3<out.frames.length;i3++){var frm=out.frames[i3],nw=frm.rect.width,nh=frm.rect.height;var fdata=new Uint8Array(nh*frm.bpl+nh);frm.cimg=UPNG.encode._filterZero(frm.img,nh,frm.bpp,frm.bpl,fdata,filter,levelZero)}};UPNG.encode.compress=function(bufs,w,h,ps,prms){var onlyBlend=prms[0],evenCrd=prms[1],forbidPrev=prms[2],minBits=prms[3],forbidPlte=prms[4];var ctype=6,depth=8,alphaAnd=255;for(var j=0;j<bufs.length;j++){var img=new Uint8Array(bufs[j]),ilen=img.length;for(var i3=0;i3<ilen;i3+=4)alphaAnd&=img[i3+3]}var gotAlpha=alphaAnd!=255;var frms=UPNG.encode.framize(bufs,w,h,onlyBlend,evenCrd,forbidPrev);var cmap={},plte=[],inds=[];if(ps!=0){var nbufs=[];for(var i3=0;i3<frms.length;i3++)nbufs.push(frms[i3].img.buffer);var abuf=UPNG.encode.concatRGBA(nbufs),qres=UPNG.quantize(abuf,ps);var cof=0,bb=new Uint8Array(qres.abuf);for(var i3=0;i3<frms.length;i3++){var ti=frms[i3].img,bln=ti.length;inds.push(new Uint8Array(qres.inds.buffer,cof>>2,bln>>2));for(var j=0;j<bln;j+=4){ti[j]=bb[cof+j];ti[j+1]=bb[cof+j+1];ti[j+2]=bb[cof+j+2];ti[j+3]=bb[cof+j+3]}cof+=bln}for(var i3=0;i3<qres.plte.length;i3++)plte.push(qres.plte[i3].est.rgba)}else{for(var j=0;j<frms.length;j++){var frm=frms[j],img32=new Uint32Array(frm.img.buffer),nw=frm.rect.width,ilen=img32.length;var ind=new Uint8Array(ilen);inds.push(ind);for(var i3=0;i3<ilen;i3++){var c=img32[i3];if(i3!=0&&c==img32[i3-1])ind[i3]=ind[i3-1];else if(i3>nw&&c==img32[i3-nw])ind[i3]=ind[i3-nw];else{var cmc=cmap[c];if(cmc==null){cmap[c]=cmc=plte.length;plte.push(c);if(plte.length>=300)break}ind[i3]=cmc}}}}var cc=plte.length;if(cc<=256&&forbidPlte==false){if(cc<=2)depth=1;else if(cc<=4)depth=2;else if(cc<=16)depth=4;else depth=8;depth=Math.max(depth,minBits)}for(var j=0;j<frms.length;j++){var frm=frms[j],nx=frm.rect.x,ny=frm.rect.y,nw=frm.rect.width,nh=frm.rect.height;var cimg=frm.img,cimg32=new Uint32Array(cimg.buffer);var bpl=4*nw,bpp=4;if(cc<=256&&forbidPlte==false){bpl=Math.ceil(depth*nw/8);var nimg=new Uint8Array(bpl*nh);var inj=inds[j];for(var y=0;y<nh;y++){var i3=y*bpl,ii=y*nw;if(depth==8)for(var x=0;x<nw;x++)nimg[i3+x]=inj[ii+x];else if(depth==4)for(var x=0;x<nw;x++)nimg[i3+(x>>1)]|=inj[ii+x]<<4-(x&1)*4;else if(depth==2)for(var x=0;x<nw;x++)nimg[i3+(x>>2)]|=inj[ii+x]<<6-(x&3)*2;else if(depth==1)for(var x=0;x<nw;x++)nimg[i3+(x>>3)]|=inj[ii+x]<<7-(x&7)*1}cimg=nimg;ctype=3;bpp=1}else if(gotAlpha==false&&frms.length==1){var nimg=new Uint8Array(nw*nh*3),area=nw*nh;for(var i3=0;i3<area;i3++){var ti=i3*3,qi=i3*4;nimg[ti]=cimg[qi];nimg[ti+1]=cimg[qi+1];nimg[ti+2]=cimg[qi+2]}cimg=nimg;ctype=2;bpp=3;bpl=3*nw}frm.img=cimg;frm.bpl=bpl;frm.bpp=bpp}return{ctype,depth,plte,frames:frms}};UPNG.encode.framize=function(bufs,w,h,alwaysBlend,evenCrd,forbidPrev){var frms=[];for(var j=0;j<bufs.length;j++){var cimg=new Uint8Array(bufs[j]),cimg32=new Uint32Array(cimg.buffer);var nimg;var nx=0,ny=0,nw=w,nh=h,blend=alwaysBlend?1:0;if(j!=0){var tlim=forbidPrev||alwaysBlend||j==1||frms[j-2].dispose!=0?1:2,tstp=0,tarea=1e9;for(var it=0;it<tlim;it++){var pimg=new Uint8Array(bufs[j-1-it]),p32=new Uint32Array(bufs[j-1-it]);var mix=w,miy=h,max=-1,may=-1;for(var y=0;y<h;y++)for(var x=0;x<w;x++){var i3=y*w+x;if(cimg32[i3]!=p32[i3]){if(x<mix)mix=x;if(x>max)max=x;if(y<miy)miy=y;if(y>may)may=y}}if(max==-1)mix=miy=max=may=0;if(evenCrd){if((mix&1)==1)mix--;if((miy&1)==1)miy--}var sarea=(max-mix+1)*(may-miy+1);if(sarea<tarea){tarea=sarea;tstp=it;nx=mix;ny=miy;nw=max-mix+1;nh=may-miy+1}}var pimg=new Uint8Array(bufs[j-1-tstp]);if(tstp==1)frms[j-1].dispose=2;nimg=new Uint8Array(nw*nh*4);UPNG._copyTile(pimg,w,h,nimg,nw,nh,-nx,-ny,0);blend=UPNG._copyTile(cimg,w,h,nimg,nw,nh,-nx,-ny,3)?1:0;if(blend==1)UPNG.encode._prepareDiff(cimg,w,h,nimg,{x:nx,y:ny,width:nw,height:nh});else UPNG._copyTile(cimg,w,h,nimg,nw,nh,-nx,-ny,0)}else nimg=cimg.slice(0);frms.push({rect:{x:nx,y:ny,width:nw,height:nh},img:nimg,blend,dispose:0})}if(alwaysBlend)for(var j=0;j<frms.length;j++){var frm=frms[j];if(frm.blend==1)continue;var r0=frm.rect,r1=frms[j-1].rect;var miX=Math.min(r0.x,r1.x),miY=Math.min(r0.y,r1.y);var maX=Math.max(r0.x+r0.width,r1.x+r1.width),maY=Math.max(r0.y+r0.height,r1.y+r1.height);var r={x:miX,y:miY,width:maX-miX,height:maY-miY};frms[j-1].dispose=1;if(j-1!=0)UPNG.encode._updateFrame(bufs,w,h,frms,j-1,r,evenCrd);UPNG.encode._updateFrame(bufs,w,h,frms,j,r,evenCrd)}var area=0;if(bufs.length!=1)for(var i3=0;i3<frms.length;i3++){var frm=frms[i3];area+=frm.rect.width*frm.rect.height}return frms};UPNG.encode._updateFrame=function(bufs,w,h,frms,i3,r,evenCrd){var U8=Uint8Array,U32=Uint32Array;var pimg=new U8(bufs[i3-1]),pimg32=new U32(bufs[i3-1]),nimg=i3+1<bufs.length?new U8(bufs[i3+1]):null;var cimg=new U8(bufs[i3]),cimg32=new U32(cimg.buffer);var mix=w,miy=h,max=-1,may=-1;for(var y=0;y<r.height;y++)for(var x=0;x<r.width;x++){var cx=r.x+x,cy=r.y+y;var j=cy*w+cx,cc=cimg32[j];if(cc==0||frms[i3-1].dispose==0&&pimg32[j]==cc&&(nimg==null||nimg[j*4+3]!=0)){}else{if(cx<mix)mix=cx;if(cx>max)max=cx;if(cy<miy)miy=cy;if(cy>may)may=cy}}if(max==-1)mix=miy=max=may=0;if(evenCrd){if((mix&1)==1)mix--;if((miy&1)==1)miy--}r={x:mix,y:miy,width:max-mix+1,height:may-miy+1};var fr=frms[i3];fr.rect=r;fr.blend=1;fr.img=new Uint8Array(r.width*r.height*4);if(frms[i3-1].dispose==0){UPNG._copyTile(pimg,w,h,fr.img,r.width,r.height,-r.x,-r.y,0);UPNG.encode._prepareDiff(cimg,w,h,fr.img,r)}else UPNG._copyTile(cimg,w,h,fr.img,r.width,r.height,-r.x,-r.y,0)};UPNG.encode._prepareDiff=function(cimg,w,h,nimg,rec){UPNG._copyTile(cimg,w,h,nimg,rec.width,rec.height,-rec.x,-rec.y,2)};UPNG.encode._filterZero=function(img,h,bpp,bpl,data2,filter,levelZero){var fls=[],ftry=[0,1,2,3,4];if(filter!=-1)ftry=[filter];else if(h*bpl>500000||bpp==1)ftry=[0];var opts;if(levelZero)opts={level:0};var CMPR=levelZero&&UZIP!=null?UZIP:import_pako4.default;for(var i3=0;i3<ftry.length;i3++){for(var y=0;y<h;y++)UPNG.encode._filterLine(data2,img,y,bpl,bpp,ftry[i3]);fls.push(CMPR["deflate"](data2,opts))}var ti,tsize=1e9;for(var i3=0;i3<fls.length;i3++)if(fls[i3].length<tsize){ti=i3;tsize=fls[i3].length}return fls[ti]};UPNG.encode._filterLine=function(data2,img,y,bpl,bpp,type){var i3=y*bpl,di=i3+y,paeth=UPNG.decode._paeth;data2[di]=type;di++;if(type==0){if(bpl<500)for(var x=0;x<bpl;x++)data2[di+x]=img[i3+x];else data2.set(new Uint8Array(img.buffer,i3,bpl),di)}else if(type==1){for(var x=0;x<bpp;x++)data2[di+x]=img[i3+x];for(var x=bpp;x<bpl;x++)data2[di+x]=img[i3+x]-img[i3+x-bpp]+256&255}else if(y==0){for(var x=0;x<bpp;x++)data2[di+x]=img[i3+x];if(type==2)for(var x=bpp;x<bpl;x++)data2[di+x]=img[i3+x];if(type==3)for(var x=bpp;x<bpl;x++)data2[di+x]=img[i3+x]-(img[i3+x-bpp]>>1)+256&255;if(type==4)for(var x=bpp;x<bpl;x++)data2[di+x]=img[i3+x]-paeth(img[i3+x-bpp],0,0)+256&255}else{if(type==2){for(var x=0;x<bpl;x++)data2[di+x]=img[i3+x]+256-img[i3+x-bpl]&255}if(type==3){for(var x=0;x<bpp;x++)data2[di+x]=img[i3+x]+256-(img[i3+x-bpl]>>1)&255;for(var x=bpp;x<bpl;x++)data2[di+x]=img[i3+x]+256-(img[i3+x-bpl]+img[i3+x-bpp]>>1)&255}if(type==4){for(var x=0;x<bpp;x++)data2[di+x]=img[i3+x]+256-paeth(0,img[i3+x-bpl],0)&255;for(var x=bpp;x<bpl;x++)data2[di+x]=img[i3+x]+256-paeth(img[i3+x-bpp],img[i3+x-bpl],img[i3+x-bpp-bpl])&255}}};UPNG.crc={table:function(){var tab=new Uint32Array(256);for(var n=0;n<256;n++){var c=n;for(var k=0;k<8;k++){if(c&1)c=3988292384^c>>>1;else c=c>>>1}tab[n]=c}return tab}(),update:function(c,buf,off,len2){for(var i3=0;i3<len2;i3++)c=UPNG.crc.table[(c^buf[off+i3])&255]^c>>>8;return c},crc:function(b,o,l){return UPNG.crc.update(4294967295,b,o,l)^4294967295}};UPNG.quantize=function(abuf,ps){var oimg=new Uint8Array(abuf),nimg=oimg.slice(0),nimg32=new Uint32Array(nimg.buffer);var KD=UPNG.quantize.getKDtree(nimg,ps);var root=KD[0],leafs=KD[1];var planeDst=UPNG.quantize.planeDst;var sb=oimg,tb=nimg32,len2=sb.length;var inds=new Uint8Array(oimg.length>>2);for(var i3=0;i3<len2;i3+=4){var r=sb[i3]*(1/255),g=sb[i3+1]*(1/255),b=sb[i3+2]*(1/255),a=sb[i3+3]*(1/255);var nd=UPNG.quantize.getNearest(root,r,g,b,a);inds[i3>>2]=nd.ind;tb[i3>>2]=nd.est.rgba}return{abuf:nimg.buffer,inds,plte:leafs}};UPNG.quantize.getKDtree=function(nimg,ps,err){if(err==null)err=0.0001;var nimg32=new Uint32Array(nimg.buffer);var root={i0:0,i1:nimg.length,bst:null,est:null,tdst:0,left:null,right:null};root.bst=UPNG.quantize.stats(nimg,root.i0,root.i1);root.est=UPNG.quantize.estats(root.bst);var leafs=[root];while(leafs.length<ps){var maxL=0,mi=0;for(var i3=0;i3<leafs.length;i3++)if(leafs[i3].est.L>maxL){maxL=leafs[i3].est.L;mi=i3}if(maxL<err)break;var node=leafs[mi];var s0=UPNG.quantize.splitPixels(nimg,nimg32,node.i0,node.i1,node.est.e,node.est.eMq255);var s0wrong=node.i0>=s0||node.i1<=s0;if(s0wrong){node.est.L=0;continue}var ln={i0:node.i0,i1:s0,bst:null,est:null,tdst:0,left:null,right:null};ln.bst=UPNG.quantize.stats(nimg,ln.i0,ln.i1);ln.est=UPNG.quantize.estats(ln.bst);var rn={i0:s0,i1:node.i1,bst:null,est:null,tdst:0,left:null,right:null};rn.bst={R:[],m:[],N:node.bst.N-ln.bst.N};for(var i3=0;i3<16;i3++)rn.bst.R[i3]=node.bst.R[i3]-ln.bst.R[i3];for(var i3=0;i3<4;i3++)rn.bst.m[i3]=node.bst.m[i3]-ln.bst.m[i3];rn.est=UPNG.quantize.estats(rn.bst);node.left=ln;node.right=rn;leafs[mi]=ln;leafs.push(rn)}leafs.sort(function(a,b){return b.bst.N-a.bst.N});for(var i3=0;i3<leafs.length;i3++)leafs[i3].ind=i3;return[root,leafs]};UPNG.quantize.getNearest=function(nd,r,g,b,a){if(nd.left==null){nd.tdst=UPNG.quantize.dist(nd.est.q,r,g,b,a);return nd}var planeDst=UPNG.quantize.planeDst(nd.est,r,g,b,a);var{left:node0,right:node1}=nd;if(planeDst>0){node0=nd.right;node1=nd.left}var ln=UPNG.quantize.getNearest(node0,r,g,b,a);if(ln.tdst<=planeDst*planeDst)return ln;var rn=UPNG.quantize.getNearest(node1,r,g,b,a);return rn.tdst<ln.tdst?rn:ln};UPNG.quantize.planeDst=function(est,r,g,b,a){var e=est.e;return e[0]*r+e[1]*g+e[2]*b+e[3]*a-est.eMq};UPNG.quantize.dist=function(q,r,g,b,a){var d0=r-q[0],d1=g-q[1],d2=b-q[2],d3=a-q[3];return d0*d0+d1*d1+d2*d2+d3*d3};UPNG.quantize.splitPixels=function(nimg,nimg32,i0,i1,e,eMq){var vecDot=UPNG.quantize.vecDot;i1-=4;var shfs=0;while(i0<i1){while(vecDot(nimg,i0,e)<=eMq)i0+=4;while(vecDot(nimg,i1,e)>eMq)i1-=4;if(i0>=i1)break;var t=nimg32[i0>>2];nimg32[i0>>2]=nimg32[i1>>2];nimg32[i1>>2]=t;i0+=4;i1-=4}while(vecDot(nimg,i0,e)>eMq)i0-=4;return i0+4};UPNG.quantize.vecDot=function(nimg,i3,e){return nimg[i3]*e[0]+nimg[i3+1]*e[1]+nimg[i3+2]*e[2]+nimg[i3+3]*e[3]};UPNG.quantize.stats=function(nimg,i0,i1){var R=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];var m=[0,0,0,0];var N=i1-i0>>2;for(var i3=i0;i3<i1;i3+=4){var r=nimg[i3]*(1/255),g=nimg[i3+1]*(1/255),b=nimg[i3+2]*(1/255),a=nimg[i3+3]*(1/255);m[0]+=r;m[1]+=g;m[2]+=b;m[3]+=a;R[0]+=r*r;R[1]+=r*g;R[2]+=r*b;R[3]+=r*a;R[5]+=g*g;R[6]+=g*b;R[7]+=g*a;R[10]+=b*b;R[11]+=b*a;R[15]+=a*a}R[4]=R[1];R[8]=R[2];R[9]=R[6];R[12]=R[3];R[13]=R[7];R[14]=R[11];return{R,m,N}};UPNG.quantize.estats=function(stats){var{R,m,N}=stats;var m0=m[0],m1=m[1],m2=m[2],m3=m[3],iN=N==0?0:1/N;var Rj=[R[0]-m0*m0*iN,R[1]-m0*m1*iN,R[2]-m0*m2*iN,R[3]-m0*m3*iN,R[4]-m1*m0*iN,R[5]-m1*m1*iN,R[6]-m1*m2*iN,R[7]-m1*m3*iN,R[8]-m2*m0*iN,R[9]-m2*m1*iN,R[10]-m2*m2*iN,R[11]-m2*m3*iN,R[12]-m3*m0*iN,R[13]-m3*m1*iN,R[14]-m3*m2*iN,R[15]-m3*m3*iN];var A=Rj,M=UPNG.M4;var b=[0.5,0.5,0.5,0.5],mi=0,tmi=0;if(N!=0)for(var i3=0;i3<10;i3++){b=M.multVec(A,b);tmi=Math.sqrt(M.dot(b,b));b=M.sml(1/tmi,b);if(Math.abs(tmi-mi)<0.000000001)break;mi=tmi}var q=[m0*iN,m1*iN,m2*iN,m3*iN];var eMq255=M.dot(M.sml(255,q),b);return{Cov:Rj,q,e:b,L:mi,eMq255,eMq:M.dot(b,q),rgba:(Math.round(255*q[3])<<24|Math.round(255*q[2])<<16|Math.round(255*q[1])<<8|Math.round(255*q[0])<<0)>>>0}};UPNG.M4={multVec:function(m,v){return[m[0]*v[0]+m[1]*v[1]+m[2]*v[2]+m[3]*v[3],m[4]*v[0]+m[5]*v[1]+m[6]*v[2]+m[7]*v[3],m[8]*v[0]+m[9]*v[1]+m[10]*v[2]+m[11]*v[3],m[12]*v[0]+m[13]*v[1]+m[14]*v[2]+m[15]*v[3]]},dot:function(x,y){return x[0]*y[0]+x[1]*y[1]+x[2]*y[2]+x[3]*y[3]},sml:function(a,y){return[a*y[0],a*y[1],a*y[2],a*y[3]]}};UPNG.encode.concatRGBA=function(bufs){var tlen=0;for(var i3=0;i3<bufs.length;i3++)tlen+=bufs[i3].byteLength;var nimg=new Uint8Array(tlen),noff=0;for(var i3=0;i3<bufs.length;i3++){var img=new Uint8Array(bufs[i3]),il=img.length;for(var j=0;j<il;j+=4){var r=img[j],g=img[j+1],b=img[j+2],a=img[j+3];if(a==0)r=g=b=0;nimg[noff+j]=r;nimg[noff+j+1]=g;nimg[noff+j+2]=b;nimg[noff+j+3]=a}noff+=il}return nimg.buffer};UPNG_default=UPNG});var getImageType=function(ctype){if(ctype===0)return PngType.Greyscale;if(ctype===2)return PngType.Truecolour;if(ctype===3)return PngType.IndexedColour;if(ctype===4)return PngType.GreyscaleWithAlpha;if(ctype===6)return PngType.TruecolourWithAlpha;throw new Error("Unknown color type: "+ctype)},splitAlphaChannel=function(rgbaChannel){var pixelCount=Math.floor(rgbaChannel.length/4);var rgbChannel=new Uint8Array(pixelCount*3);var alphaChannel=new Uint8Array(pixelCount*1);var rgbaOffset=0;var rgbOffset=0;var alphaOffset=0;while(rgbaOffset<rgbaChannel.length){rgbChannel[rgbOffset++]=rgbaChannel[rgbaOffset++];rgbChannel[rgbOffset++]=rgbaChannel[rgbaOffset++];rgbChannel[rgbOffset++]=rgbaChannel[rgbaOffset++];alphaChannel[alphaOffset++]=rgbaChannel[rgbaOffset++]}return{rgbChannel,alphaChannel}},PngType,PNG;var init_png=__esm(()=>{init_UPNG();(function(PngType2){PngType2["Greyscale"]="Greyscale";PngType2["Truecolour"]="Truecolour";PngType2["IndexedColour"]="IndexedColour";PngType2["GreyscaleWithAlpha"]="GreyscaleWithAlpha";PngType2["TruecolourWithAlpha"]="TruecolourWithAlpha"})(PngType||(PngType={}));PNG=function(){function PNG2(pngData){var upng=UPNG_default.decode(pngData);var frames=UPNG_default.toRGBA8(upng);if(frames.length>1)throw new Error("Animated PNGs are not supported");var frame=new Uint8Array(frames[0]);var _a=splitAlphaChannel(frame),rgbChannel=_a.rgbChannel,alphaChannel=_a.alphaChannel;this.rgbChannel=rgbChannel;var hasAlphaValues=alphaChannel.some(function(a){return a<255});if(hasAlphaValues)this.alphaChannel=alphaChannel;this.type=getImageType(upng.ctype);this.width=upng.width;this.height=upng.height;this.bitsPerComponent=8}PNG2.load=function(pngData){return new PNG2(pngData)};return PNG2}()});var PngEmbedder,PngEmbedder_default;var init_PngEmbedder=__esm(()=>{init_tslib_es62();init_png();PngEmbedder=function(){function PngEmbedder2(png){this.image=png;this.bitsPerComponent=png.bitsPerComponent;this.width=png.width;this.height=png.height;this.colorSpace="DeviceRGB"}PngEmbedder2.for=function(imageData){return __awaiter(this,undefined,undefined,function(){var png;return __generator(this,function(_a){png=PNG.load(imageData);return[2,new PngEmbedder2(png)]})})};PngEmbedder2.prototype.embedIntoContext=function(context2,ref){return __awaiter(this,undefined,undefined,function(){var SMask,xObject;return __generator(this,function(_a){SMask=this.embedAlphaChannel(context2);xObject=context2.flateStream(this.image.rgbChannel,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.image.bitsPerComponent,Width:this.image.width,Height:this.image.height,ColorSpace:this.colorSpace,SMask});if(ref){context2.assign(ref,xObject);return[2,ref]}else{return[2,context2.register(xObject)]}return[2]})})};PngEmbedder2.prototype.embedAlphaChannel=function(context2){if(!this.image.alphaChannel)return;var xObject=context2.flateStream(this.image.alphaChannel,{Type:"XObject",Subtype:"Image",Height:this.image.height,Width:this.image.width,BitsPerComponent:this.image.bitsPerComponent,ColorSpace:"DeviceGray",Decode:[0,1]});return context2.register(xObject)};return PngEmbedder2}();PngEmbedder_default=PngEmbedder});var Stream,Stream_default;var init_Stream=__esm(()=>{Stream=function(){function Stream2(buffer,start,length){this.bytes=buffer;this.start=start||0;this.pos=this.start;this.end=!!start&&!!length?start+length:this.bytes.length}Object.defineProperty(Stream2.prototype,"length",{get:function(){return this.end-this.start},enumerable:false,configurable:true});Object.defineProperty(Stream2.prototype,"isEmpty",{get:function(){return this.length===0},enumerable:false,configurable:true});Stream2.prototype.getByte=function(){if(this.pos>=this.end){return-1}return this.bytes[this.pos++]};Stream2.prototype.getUint16=function(){var b0=this.getByte();var b1=this.getByte();if(b0===-1||b1===-1){return-1}return(b0<<8)+b1};Stream2.prototype.getInt32=function(){var b0=this.getByte();var b1=this.getByte();var b2=this.getByte();var b3=this.getByte();return(b0<<24)+(b1<<16)+(b2<<8)+b3};Stream2.prototype.getBytes=function(length,forceClamped){if(forceClamped===undefined){forceClamped=false}var bytes=this.bytes;var pos=this.pos;var strEnd=this.end;if(!length){var subarray=bytes.subarray(pos,strEnd);return forceClamped?new Uint8ClampedArray(subarray):subarray}else{var end=pos+length;if(end>strEnd){end=strEnd}this.pos=end;var subarray=bytes.subarray(pos,end);return forceClamped?new Uint8ClampedArray(subarray):subarray}};Stream2.prototype.peekByte=function(){var peekedByte=this.getByte();this.pos--;return peekedByte};Stream2.prototype.peekBytes=function(length,forceClamped){if(forceClamped===undefined){forceClamped=false}var bytes=this.getBytes(length,forceClamped);this.pos-=bytes.length;return bytes};Stream2.prototype.skip=function(n){if(!n){n=1}this.pos+=n};Stream2.prototype.reset=function(){this.pos=this.start};Stream2.prototype.moveStart=function(){this.start=this.pos};Stream2.prototype.makeSubStream=function(start,length){return new Stream2(this.bytes,start,length)};Stream2.prototype.decode=function(){return this.bytes};return Stream2}();Stream_default=Stream});var emptyBuffer,DecodeStream,DecodeStream_default;var init_DecodeStream=__esm(()=>{init_errors2();init_Stream();emptyBuffer=new Uint8Array(0);DecodeStream=function(){function DecodeStream2(maybeMinBufferLength){this.pos=0;this.bufferLength=0;this.eof=false;this.buffer=emptyBuffer;this.minBufferLength=512;if(maybeMinBufferLength){while(this.minBufferLength<maybeMinBufferLength){this.minBufferLength*=2}}}Object.defineProperty(DecodeStream2.prototype,"isEmpty",{get:function(){while(!this.eof&&this.bufferLength===0){this.readBlock()}return this.bufferLength===0},enumerable:false,configurable:true});DecodeStream2.prototype.getByte=function(){var pos=this.pos;while(this.bufferLength<=pos){if(this.eof){return-1}this.readBlock()}return this.buffer[this.pos++]};DecodeStream2.prototype.getUint16=function(){var b0=this.getByte();var b1=this.getByte();if(b0===-1||b1===-1){return-1}return(b0<<8)+b1};DecodeStream2.prototype.getInt32=function(){var b0=this.getByte();var b1=this.getByte();var b2=this.getByte();var b3=this.getByte();return(b0<<24)+(b1<<16)+(b2<<8)+b3};DecodeStream2.prototype.getBytes=function(length,forceClamped){if(forceClamped===undefined){forceClamped=false}var end;var pos=this.pos;if(length){this.ensureBuffer(pos+length);end=pos+length;while(!this.eof&&this.bufferLength<end){this.readBlock()}var bufEnd=this.bufferLength;if(end>bufEnd){end=bufEnd}}else{while(!this.eof){this.readBlock()}end=this.bufferLength}this.pos=end;var subarray=this.buffer.subarray(pos,end);return forceClamped&&!(subarray instanceof Uint8ClampedArray)?new Uint8ClampedArray(subarray):subarray};DecodeStream2.prototype.peekByte=function(){var peekedByte=this.getByte();this.pos--;return peekedByte};DecodeStream2.prototype.peekBytes=function(length,forceClamped){if(forceClamped===undefined){forceClamped=false}var bytes=this.getBytes(length,forceClamped);this.pos-=bytes.length;return bytes};DecodeStream2.prototype.skip=function(n){if(!n){n=1}this.pos+=n};DecodeStream2.prototype.reset=function(){this.pos=0};DecodeStream2.prototype.makeSubStream=function(start,length){var end=start+length;while(this.bufferLength<=end&&!this.eof){this.readBlock()}return new Stream_default(this.buffer,start,length)};DecodeStream2.prototype.decode=function(){while(!this.eof)this.readBlock();return this.buffer.subarray(0,this.bufferLength)};DecodeStream2.prototype.readBlock=function(){throw new MethodNotImplementedError(this.constructor.name,"readBlock")};DecodeStream2.prototype.ensureBuffer=function(requested){var buffer=this.buffer;if(requested<=buffer.byteLength){return buffer}var size=this.minBufferLength;while(size<requested){size*=2}var buffer2=new Uint8Array(size);buffer2.set(buffer);return this.buffer=buffer2};return DecodeStream2}();DecodeStream_default=DecodeStream});var isSpace=function(ch){return ch===32||ch===9||ch===13||ch===10},Ascii85Stream,Ascii85Stream_default;var init_Ascii85Stream=__esm(()=>{init_tslib_es62();init_DecodeStream();Ascii85Stream=function(_super){__extends(Ascii85Stream2,_super);function Ascii85Stream2(stream,maybeLength){var _this=_super.call(this,maybeLength)||this;_this.stream=stream;_this.input=new Uint8Array(5);if(maybeLength){maybeLength=0.8*maybeLength}return _this}Ascii85Stream2.prototype.readBlock=function(){var TILDA_CHAR=126;var Z_LOWER_CHAR=122;var EOF=-1;var stream=this.stream;var c=stream.getByte();while(isSpace(c)){c=stream.getByte()}if(c===EOF||c===TILDA_CHAR){this.eof=true;return}var bufferLength=this.bufferLength;var buffer;var i3;if(c===Z_LOWER_CHAR){buffer=this.ensureBuffer(bufferLength+4);for(i3=0;i3<4;++i3){buffer[bufferLength+i3]=0}this.bufferLength+=4}else{var input=this.input;input[0]=c;for(i3=1;i3<5;++i3){c=stream.getByte();while(isSpace(c)){c=stream.getByte()}input[i3]=c;if(c===EOF||c===TILDA_CHAR){break}}buffer=this.ensureBuffer(bufferLength+i3-1);this.bufferLength+=i3-1;if(i3<5){for(;i3<5;++i3){input[i3]=33+84}this.eof=true}var t=0;for(i3=0;i3<5;++i3){t=t*85+(input[i3]-33)}for(i3=3;i3>=0;--i3){buffer[bufferLength+i3]=t&255;t>>=8}}};return Ascii85Stream2}(DecodeStream_default);Ascii85Stream_default=Ascii85Stream});var AsciiHexStream,AsciiHexStream_default;var init_AsciiHexStream=__esm(()=>{init_tslib_es62();init_DecodeStream();AsciiHexStream=function(_super){__extends(AsciiHexStream2,_super);function AsciiHexStream2(stream,maybeLength){var _this=_super.call(this,maybeLength)||this;_this.stream=stream;_this.firstDigit=-1;if(maybeLength){maybeLength=0.5*maybeLength}return _this}AsciiHexStream2.prototype.readBlock=function(){var UPSTREAM_BLOCK_SIZE=8000;var bytes=this.stream.getBytes(UPSTREAM_BLOCK_SIZE);if(!bytes.length){this.eof=true;return}var maxDecodeLength=bytes.length+1>>1;var buffer=this.ensureBuffer(this.bufferLength+maxDecodeLength);var bufferLength=this.bufferLength;var firstDigit=this.firstDigit;for(var i3=0,ii=bytes.length;i3<ii;i3++){var ch=bytes[i3];var digit=undefined;if(ch>=48&&ch<=57){digit=ch&15}else if(ch>=65&&ch<=70||ch>=97&&ch<=102){digit=(ch&15)+9}else if(ch===62){this.eof=true;break}else{continue}if(firstDigit<0){firstDigit=digit}else{buffer[bufferLength++]=firstDigit<<4|digit;firstDigit=-1}}if(firstDigit>=0&&this.eof){buffer[bufferLength++]=firstDigit<<4;firstDigit=-1}this.firstDigit=firstDigit;this.bufferLength=bufferLength};return AsciiHexStream2}(DecodeStream_default);AsciiHexStream_default=AsciiHexStream});var codeLenCodeMap,lengthDecode,distDecode,fixedLitCodeTab,fixedDistCodeTab,FlateStream,FlateStream_default;var init_FlateStream=__esm(()=>{init_tslib_es62();init_DecodeStream();codeLenCodeMap=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);lengthDecode=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]);distDecode=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]);fixedLitCodeTab=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,590000,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9];fixedDistCodeTab=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];FlateStream=function(_super){__extends(FlateStream2,_super);function FlateStream2(stream,maybeLength){var _this=_super.call(this,maybeLength)||this;_this.stream=stream;var cmf=stream.getByte();var flg=stream.getByte();if(cmf===-1||flg===-1){throw new Error("Invalid header in flate stream: "+cmf+", "+flg)}if((cmf&15)!==8){throw new Error("Unknown compression method in flate stream: "+cmf+", "+flg)}if(((cmf<<8)+flg)%31!==0){throw new Error("Bad FCHECK in flate stream: "+cmf+", "+flg)}if(flg&32){throw new Error("FDICT bit set in flate stream: "+cmf+", "+flg)}_this.codeSize=0;_this.codeBuf=0;return _this}FlateStream2.prototype.readBlock=function(){var buffer;var len2;var str=this.stream;var hdr=this.getBits(3);if(hdr&1){this.eof=true}hdr>>=1;if(hdr===0){var b=undefined;if((b=str.getByte())===-1){throw new Error("Bad block header in flate stream")}var blockLen=b;if((b=str.getByte())===-1){throw new Error("Bad block header in flate stream")}blockLen|=b<<8;if((b=str.getByte())===-1){throw new Error("Bad block header in flate stream")}var check=b;if((b=str.getByte())===-1){throw new Error("Bad block header in flate stream")}check|=b<<8;if(check!==(~blockLen&65535)&&(blockLen!==0||check!==0)){throw new Error("Bad uncompressed block length in flate stream")}this.codeBuf=0;this.codeSize=0;var bufferLength=this.bufferLength;buffer=this.ensureBuffer(bufferLength+blockLen);var end=bufferLength+blockLen;this.bufferLength=end;if(blockLen===0){if(str.peekByte()===-1){this.eof=true}}else{for(var n=bufferLength;n<end;++n){if((b=str.getByte())===-1){this.eof=true;break}buffer[n]=b}}return}var litCodeTable;var distCodeTable;if(hdr===1){litCodeTable=fixedLitCodeTab;distCodeTable=fixedDistCodeTab}else if(hdr===2){var numLitCodes=this.getBits(5)+257;var numDistCodes=this.getBits(5)+1;var numCodeLenCodes=this.getBits(4)+4;var codeLenCodeLengths=new Uint8Array(codeLenCodeMap.length);var i3=undefined;for(i3=0;i3<numCodeLenCodes;++i3){codeLenCodeLengths[codeLenCodeMap[i3]]=this.getBits(3)}var codeLenCodeTab=this.generateHuffmanTable(codeLenCodeLengths);len2=0;i3=0;var codes=numLitCodes+numDistCodes;var codeLengths=new Uint8Array(codes);var bitsLength=undefined;var bitsOffset=undefined;var what=undefined;while(i3<codes){var code=this.getCode(codeLenCodeTab);if(code===16){bitsLength=2;bitsOffset=3;what=len2}else if(code===17){bitsLength=3;bitsOffset=3;what=len2=0}else if(code===18){bitsLength=7;bitsOffset=11;what=len2=0}else{codeLengths[i3++]=len2=code;continue}var repeatLength=this.getBits(bitsLength)+bitsOffset;while(repeatLength-- >0){codeLengths[i3++]=what}}litCodeTable=this.generateHuffmanTable(codeLengths.subarray(0,numLitCodes));distCodeTable=this.generateHuffmanTable(codeLengths.subarray(numLitCodes,codes))}else{throw new Error("Unknown block type in flate stream")}buffer=this.buffer;var limit=buffer?buffer.length:0;var pos=this.bufferLength;while(true){var code1=this.getCode(litCodeTable);if(code1<256){if(pos+1>=limit){buffer=this.ensureBuffer(pos+1);limit=buffer.length}buffer[pos++]=code1;continue}if(code1===256){this.bufferLength=pos;return}code1-=257;code1=lengthDecode[code1];var code2=code1>>16;if(code2>0){code2=this.getBits(code2)}len2=(code1&65535)+code2;code1=this.getCode(distCodeTable);code1=distDecode[code1];code2=code1>>16;if(code2>0){code2=this.getBits(code2)}var dist=(code1&65535)+code2;if(pos+len2>=limit){buffer=this.ensureBuffer(pos+len2);limit=buffer.length}for(var k=0;k<len2;++k,++pos){buffer[pos]=buffer[pos-dist]}}};FlateStream2.prototype.getBits=function(bits){var str=this.stream;var codeSize=this.codeSize;var codeBuf=this.codeBuf;var b;while(codeSize<bits){if((b=str.getByte())===-1){throw new Error("Bad encoding in flate stream")}codeBuf|=b<<codeSize;codeSize+=8}b=codeBuf&(1<<bits)-1;this.codeBuf=codeBuf>>bits;this.codeSize=codeSize-=bits;return b};FlateStream2.prototype.getCode=function(table){var str=this.stream;var codes=table[0];var maxLen=table[1];var codeSize=this.codeSize;var codeBuf=this.codeBuf;var b;while(codeSize<maxLen){if((b=str.getByte())===-1){break}codeBuf|=b<<codeSize;codeSize+=8}var code=codes[codeBuf&(1<<maxLen)-1];if(typeof codes==="number"){console.log("FLATE:",code)}var codeLen=code>>16;var codeVal=code&65535;if(codeLen<1||codeSize<codeLen){throw new Error("Bad encoding in flate stream")}this.codeBuf=codeBuf>>codeLen;this.codeSize=codeSize-codeLen;return codeVal};FlateStream2.prototype.generateHuffmanTable=function(lengths){var n=lengths.length;var maxLen=0;var i3;for(i3=0;i3<n;++i3){if(lengths[i3]>maxLen){maxLen=lengths[i3]}}var size=1<<maxLen;var codes=new Int32Array(size);for(var len2=1,code=0,skip=2;len2<=maxLen;++len2,code<<=1,skip<<=1){for(var val=0;val<n;++val){if(lengths[val]===len2){var code2=0;var t=code;for(i3=0;i3<len2;++i3){code2=code2<<1|t&1;t>>=1}for(i3=code2;i3<size;i3+=skip){codes[i3]=len2<<16|val}++code}}}return[codes,maxLen]};return FlateStream2}(DecodeStream_default);FlateStream_default=FlateStream});var LZWStream,LZWStream_default;var init_LZWStream=__esm(()=>{init_tslib_es62();init_DecodeStream();LZWStream=function(_super){__extends(LZWStream2,_super);function LZWStream2(stream,maybeLength,earlyChange){var _this=_super.call(this,maybeLength)||this;_this.stream=stream;_this.cachedData=0;_this.bitsCached=0;var maxLzwDictionarySize=4096;var lzwState={earlyChange,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(maxLzwDictionarySize),dictionaryLengths:new Uint16Array(maxLzwDictionarySize),dictionaryPrevCodes:new Uint16Array(maxLzwDictionarySize),currentSequence:new Uint8Array(maxLzwDictionarySize),currentSequenceLength:0};for(var i3=0;i3<256;++i3){lzwState.dictionaryValues[i3]=i3;lzwState.dictionaryLengths[i3]=1}_this.lzwState=lzwState;return _this}LZWStream2.prototype.readBlock=function(){var blockSize=512;var estimatedDecodedSize=blockSize*2;var decodedSizeDelta=blockSize;var i3;var j;var q;var lzwState=this.lzwState;if(!lzwState){return}var earlyChange=lzwState.earlyChange;var nextCode=lzwState.nextCode;var dictionaryValues=lzwState.dictionaryValues;var dictionaryLengths=lzwState.dictionaryLengths;var dictionaryPrevCodes=lzwState.dictionaryPrevCodes;var codeLength=lzwState.codeLength;var prevCode=lzwState.prevCode;var currentSequence=lzwState.currentSequence;var currentSequenceLength=lzwState.currentSequenceLength;var decodedLength=0;var currentBufferLength=this.bufferLength;var buffer=this.ensureBuffer(this.bufferLength+estimatedDecodedSize);for(i3=0;i3<blockSize;i3++){var code=this.readBits(codeLength);var hasPrev=currentSequenceLength>0;if(!code||code<256){currentSequence[0]=code;currentSequenceLength=1}else if(code>=258){if(code<nextCode){currentSequenceLength=dictionaryLengths[code];for(j=currentSequenceLength-1,q=code;j>=0;j--){currentSequence[j]=dictionaryValues[q];q=dictionaryPrevCodes[q]}}else{currentSequence[currentSequenceLength++]=currentSequence[0]}}else if(code===256){codeLength=9;nextCode=258;currentSequenceLength=0;continue}else{this.eof=true;delete this.lzwState;break}if(hasPrev){dictionaryPrevCodes[nextCode]=prevCode;dictionaryLengths[nextCode]=dictionaryLengths[prevCode]+1;dictionaryValues[nextCode]=currentSequence[0];nextCode++;codeLength=nextCode+earlyChange&nextCode+earlyChange-1?codeLength:Math.min(Math.log(nextCode+earlyChange)/0.6931471805599453+1,12)|0}prevCode=code;decodedLength+=currentSequenceLength;if(estimatedDecodedSize<decodedLength){do{estimatedDecodedSize+=decodedSizeDelta}while(estimatedDecodedSize<decodedLength);buffer=this.ensureBuffer(this.bufferLength+estimatedDecodedSize)}for(j=0;j<currentSequenceLength;j++){buffer[currentBufferLength++]=currentSequence[j]}}lzwState.nextCode=nextCode;lzwState.codeLength=codeLength;lzwState.prevCode=prevCode;lzwState.currentSequenceLength=currentSequenceLength;this.bufferLength=currentBufferLength};LZWStream2.prototype.readBits=function(n){var bitsCached=this.bitsCached;var cachedData=this.cachedData;while(bitsCached<n){var c=this.stream.getByte();if(c===-1){this.eof=true;return null}cachedData=cachedData<<8|c;bitsCached+=8}this.bitsCached=bitsCached-=n;this.cachedData=cachedData;return cachedData>>>bitsCached&(1<<n)-1};return LZWStream2}(DecodeStream_default);LZWStream_default=LZWStream});var RunLengthStream,RunLengthStream_default;var init_RunLengthStream=__esm(()=>{init_tslib_es62();init_DecodeStream();RunLengthStream=function(_super){__extends(RunLengthStream2,_super);function RunLengthStream2(stream,maybeLength){var _this=_super.call(this,maybeLength)||this;_this.stream=stream;return _this}RunLengthStream2.prototype.readBlock=function(){var repeatHeader=this.stream.getBytes(2);if(!repeatHeader||repeatHeader.length<2||repeatHeader[0]===128){this.eof=true;return}var buffer;var bufferLength=this.bufferLength;var n=repeatHeader[0];if(n<128){buffer=this.ensureBuffer(bufferLength+n+1);buffer[bufferLength++]=repeatHeader[1];if(n>0){var source=this.stream.getBytes(n);buffer.set(source,bufferLength);bufferLength+=n}}else{n=257-n;var b=repeatHeader[1];buffer=this.ensureBuffer(bufferLength+n+1);for(var i3=0;i3<n;i3++){buffer[bufferLength++]=b}}this.bufferLength=bufferLength};return RunLengthStream2}(DecodeStream_default);RunLengthStream_default=RunLengthStream});var decodeStream=function(stream,encoding,params){if(encoding===PDFName_default.of("FlateDecode")){return new FlateStream_default(stream)}if(encoding===PDFName_default.of("LZWDecode")){var earlyChange=1;if(params instanceof PDFDict_default){var EarlyChange=params.lookup(PDFName_default.of("EarlyChange"));if(EarlyChange instanceof PDFNumber_default){earlyChange=EarlyChange.asNumber()}}return new LZWStream_default(stream,undefined,earlyChange)}if(encoding===PDFName_default.of("ASCII85Decode")){return new Ascii85Stream_default(stream)}if(encoding===PDFName_default.of("ASCIIHexDecode")){return new AsciiHexStream_default(stream)}if(encoding===PDFName_default.of("RunLengthDecode")){return new RunLengthStream_default(stream)}throw new UnsupportedEncodingError(encoding.asString())},decodePDFRawStream=function(_a){var{dict,contents}=_a;var stream=new Stream_default(contents);var Filter=dict.lookup(PDFName_default.of("Filter"));var DecodeParms=dict.lookup(PDFName_default.of("DecodeParms"));if(Filter instanceof PDFName_default){stream=decodeStream(stream,Filter,DecodeParms)}else if(Filter instanceof PDFArray_default){for(var idx3=0,len2=Filter.size();idx3<len2;idx3++){stream=decodeStream(stream,Filter.lookup(idx3,PDFName_default),DecodeParms&&DecodeParms.lookupMaybe(idx3,PDFDict_default))}}else if(!!Filter){throw new UnexpectedObjectTypeError([PDFName_default,PDFArray_default],Filter)}return stream};var init_decode=__esm(()=>{init_errors2();init_PDFArray();init_PDFDict();init_PDFName();init_PDFNumber();init_Ascii85Stream();init_AsciiHexStream();init_FlateStream();init_LZWStream();init_RunLengthStream();init_Stream()});var fullPageBoundingBox=function(page){var mediaBox=page.MediaBox();var width=mediaBox.lookup(2,PDFNumber_default).asNumber()-mediaBox.lookup(0,PDFNumber_default).asNumber();var height=mediaBox.lookup(3,PDFNumber_default).asNumber()-mediaBox.lookup(1,PDFNumber_default).asNumber();return{left:0,bottom:0,right:width,top:height}},boundingBoxAdjustedMatrix=function(bb){return[1,0,0,1,-bb.left,-bb.bottom]},PDFPageEmbedder,PDFPageEmbedder_default;var init_PDFPageEmbedder=__esm(()=>{init_tslib_es62();init_errors2();init_PDFNumber();init_PDFRawStream();init_PDFStream();init_decode();init_PDFContentStream();init_CharCodes();init_utils2();PDFPageEmbedder=function(){function PDFPageEmbedder2(page,boundingBox,transformationMatrix){this.page=page;var bb=boundingBox!==null&&boundingBox!==undefined?boundingBox:fullPageBoundingBox(page);this.width=bb.right-bb.left;this.height=bb.top-bb.bottom;this.boundingBox=bb;this.transformationMatrix=transformationMatrix!==null&&transformationMatrix!==undefined?transformationMatrix:boundingBoxAdjustedMatrix(bb)}PDFPageEmbedder2.for=function(page,boundingBox,transformationMatrix){return __awaiter(this,undefined,undefined,function(){return __generator(this,function(_a){return[2,new PDFPageEmbedder2(page,boundingBox,transformationMatrix)]})})};PDFPageEmbedder2.prototype.embedIntoContext=function(context2,ref){return __awaiter(this,undefined,undefined,function(){var _a,Contents,Resources,decodedContents,_b,left,bottom,right,top,xObject;return __generator(this,function(_c){_a=this.page.normalizedEntries(),Contents=_a.Contents,Resources=_a.Resources;if(!Contents)throw new MissingPageContentsEmbeddingError;decodedContents=this.decodeContents(Contents);_b=this.boundingBox,left=_b.left,bottom=_b.bottom,right=_b.right,top=_b.top;xObject=context2.flateStream(decodedContents,{Type:"XObject",Subtype:"Form",FormType:1,BBox:[left,bottom,right,top],Matrix:this.transformationMatrix,Resources});if(ref){context2.assign(ref,xObject);return[2,ref]}else{return[2,context2.register(xObject)]}return[2]})})};PDFPageEmbedder2.prototype.decodeContents=function(contents){var newline=Uint8Array.of(CharCodes_default.Newline);var decodedContents=[];for(var idx3=0,len2=contents.size();idx3<len2;idx3++){var stream=contents.lookup(idx3,PDFStream_default);var content=undefined;if(stream instanceof PDFRawStream_default){content=decodePDFRawStream(stream).decode()}else if(stream instanceof PDFContentStream_default){content=stream.getUnencodedContents()}else{throw new UnrecognizedStreamTypeError(stream)}decodedContents.push(content,newline)}return mergeIntoTypedArray.apply(undefined,decodedContents)};return PDFPageEmbedder2}();PDFPageEmbedder_default=PDFPageEmbedder});var asEnum=function(rawValue,enumType){if(rawValue===undefined)return;return enumType[rawValue]},NonFullScreenPageMode,ReadingDirection,PrintScaling,Duplex,ViewerPreferences,ViewerPreferences_default;var init_ViewerPreferences=__esm(()=>{init_PDFArray();init_PDFBool();init_PDFName();init_PDFNumber();init_utils2();(function(NonFullScreenPageMode2){NonFullScreenPageMode2["UseNone"]="UseNone";NonFullScreenPageMode2["UseOutlines"]="UseOutlines";NonFullScreenPageMode2["UseThumbs"]="UseThumbs";NonFullScreenPageMode2["UseOC"]="UseOC"})(NonFullScreenPageMode||(NonFullScreenPageMode={}));(function(ReadingDirection2){ReadingDirection2["L2R"]="L2R";ReadingDirection2["R2L"]="R2L"})(ReadingDirection||(ReadingDirection={}));(function(PrintScaling2){PrintScaling2["None"]="None";PrintScaling2["AppDefault"]="AppDefault"})(PrintScaling||(PrintScaling={}));(function(Duplex2){Duplex2["Simplex"]="Simplex";Duplex2["DuplexFlipShortEdge"]="DuplexFlipShortEdge";Duplex2["DuplexFlipLongEdge"]="DuplexFlipLongEdge"})(Duplex||(Duplex={}));ViewerPreferences=function(){function ViewerPreferences2(dict){this.dict=dict}ViewerPreferences2.prototype.lookupBool=function(key){var returnObj=this.dict.lookup(PDFName_default.of(key));if(returnObj instanceof PDFBool_default)return returnObj;return};ViewerPreferences2.prototype.lookupName=function(key){var returnObj=this.dict.lookup(PDFName_default.of(key));if(returnObj instanceof PDFName_default)return returnObj;return};ViewerPreferences2.prototype.HideToolbar=function(){return this.lookupBool("HideToolbar")};ViewerPreferences2.prototype.HideMenubar=function(){return this.lookupBool("HideMenubar")};ViewerPreferences2.prototype.HideWindowUI=function(){return this.lookupBool("HideWindowUI")};ViewerPreferences2.prototype.FitWindow=function(){return this.lookupBool("FitWindow")};ViewerPreferences2.prototype.CenterWindow=function(){return this.lookupBool("CenterWindow")};ViewerPreferences2.prototype.DisplayDocTitle=function(){return this.lookupBool("DisplayDocTitle")};ViewerPreferences2.prototype.NonFullScreenPageMode=function(){return this.lookupName("NonFullScreenPageMode")};ViewerPreferences2.prototype.Direction=function(){return this.lookupName("Direction")};ViewerPreferences2.prototype.PrintScaling=function(){return this.lookupName("PrintScaling")};ViewerPreferences2.prototype.Duplex=function(){return this.lookupName("Duplex")};ViewerPreferences2.prototype.PickTrayByPDFSize=function(){return this.lookupBool("PickTrayByPDFSize")};ViewerPreferences2.prototype.PrintPageRange=function(){var PrintPageRange=this.dict.lookup(PDFName_default.of("PrintPageRange"));if(PrintPageRange instanceof PDFArray_default)return PrintPageRange;return};ViewerPreferences2.prototype.NumCopies=function(){var NumCopies=this.dict.lookup(PDFName_default.of("NumCopies"));if(NumCopies instanceof PDFNumber_default)return NumCopies;return};ViewerPreferences2.prototype.getHideToolbar=function(){var _a,_b;return(_b=(_a=this.HideToolbar())===null||_a===undefined?undefined:_a.asBoolean())!==null&&_b!==undefined?_b:false};ViewerPreferences2.prototype.getHideMenubar=function(){var _a,_b;return(_b=(_a=this.HideMenubar())===null||_a===undefined?undefined:_a.asBoolean())!==null&&_b!==undefined?_b:false};ViewerPreferences2.prototype.getHideWindowUI=function(){var _a,_b;return(_b=(_a=this.HideWindowUI())===null||_a===undefined?undefined:_a.asBoolean())!==null&&_b!==undefined?_b:false};ViewerPreferences2.prototype.getFitWindow=function(){var _a,_b;return(_b=(_a=this.FitWindow())===null||_a===undefined?undefined:_a.asBoolean())!==null&&_b!==undefined?_b:false};ViewerPreferences2.prototype.getCenterWindow=function(){var _a,_b;return(_b=(_a=this.CenterWindow())===null||_a===undefined?undefined:_a.asBoolean())!==null&&_b!==undefined?_b:false};ViewerPreferences2.prototype.getDisplayDocTitle=function(){var _a,_b;return(_b=(_a=this.DisplayDocTitle())===null||_a===undefined?undefined:_a.asBoolean())!==null&&_b!==undefined?_b:false};ViewerPreferences2.prototype.getNonFullScreenPageMode=function(){var _a,_b;var mode=(_a=this.NonFullScreenPageMode())===null||_a===undefined?undefined:_a.decodeText();return(_b=asEnum(mode,NonFullScreenPageMode))!==null&&_b!==undefined?_b:NonFullScreenPageMode.UseNone};ViewerPreferences2.prototype.getReadingDirection=function(){var _a,_b;var direction=(_a=this.Direction())===null||_a===undefined?undefined:_a.decodeText();return(_b=asEnum(direction,ReadingDirection))!==null&&_b!==undefined?_b:ReadingDirection.L2R};ViewerPreferences2.prototype.getPrintScaling=function(){var _a,_b;var scaling=(_a=this.PrintScaling())===null||_a===undefined?undefined:_a.decodeText();return(_b=asEnum(scaling,PrintScaling))!==null&&_b!==undefined?_b:PrintScaling.AppDefault};ViewerPreferences2.prototype.getDuplex=function(){var _a;var duplex=(_a=this.Duplex())===null||_a===undefined?undefined:_a.decodeText();return asEnum(duplex,Duplex)};ViewerPreferences2.prototype.getPickTrayByPDFSize=function(){var _a;return(_a=this.PickTrayByPDFSize())===null||_a===undefined?undefined:_a.asBoolean()};ViewerPreferences2.prototype.getPrintPageRange=function(){var rng=this.PrintPageRange();if(!rng)return[];var pageRanges=[];for(var i3=0;i3<rng.size();i3+=2){var start=rng.lookup(i3,PDFNumber_default).asNumber();var end=rng.lookup(i3+1,PDFNumber_default).asNumber();pageRanges.push({start,end})}return pageRanges};ViewerPreferences2.prototype.getNumCopies=function(){var _a,_b;return(_b=(_a=this.NumCopies())===null||_a===undefined?undefined:_a.asNumber())!==null&&_b!==undefined?_b:1};ViewerPreferences2.prototype.setHideToolbar=function(hideToolbar){var HideToolbar=this.dict.context.obj(hideToolbar);this.dict.set(PDFName_default.of("HideToolbar"),HideToolbar)};ViewerPreferences2.prototype.setHideMenubar=function(hideMenubar){var HideMenubar=this.dict.context.obj(hideMenubar);this.dict.set(PDFName_default.of("HideMenubar"),HideMenubar)};ViewerPreferences2.prototype.setHideWindowUI=function(hideWindowUI){var HideWindowUI=this.dict.context.obj(hideWindowUI);this.dict.set(PDFName_default.of("HideWindowUI"),HideWindowUI)};ViewerPreferences2.prototype.setFitWindow=function(fitWindow){var FitWindow=this.dict.context.obj(fitWindow);this.dict.set(PDFName_default.of("FitWindow"),FitWindow)};ViewerPreferences2.prototype.setCenterWindow=function(centerWindow){var CenterWindow=this.dict.context.obj(centerWindow);this.dict.set(PDFName_default.of("CenterWindow"),CenterWindow)};ViewerPreferences2.prototype.setDisplayDocTitle=function(displayTitle){var DisplayDocTitle=this.dict.context.obj(displayTitle);this.dict.set(PDFName_default.of("DisplayDocTitle"),DisplayDocTitle)};ViewerPreferences2.prototype.setNonFullScreenPageMode=function(nonFullScreenPageMode){assertIsOneOf(nonFullScreenPageMode,"nonFullScreenPageMode",NonFullScreenPageMode);var mode=PDFName_default.of(nonFullScreenPageMode);this.dict.set(PDFName_default.of("NonFullScreenPageMode"),mode)};ViewerPreferences2.prototype.setReadingDirection=function(readingDirection){assertIsOneOf(readingDirection,"readingDirection",ReadingDirection);var direction=PDFName_default.of(readingDirection);this.dict.set(PDFName_default.of("Direction"),direction)};ViewerPreferences2.prototype.setPrintScaling=function(printScaling){assertIsOneOf(printScaling,"printScaling",PrintScaling);var scaling=PDFName_default.of(printScaling);this.dict.set(PDFName_default.of("PrintScaling"),scaling)};ViewerPreferences2.prototype.setDuplex=function(duplex){assertIsOneOf(duplex,"duplex",Duplex);var dup=PDFName_default.of(duplex);this.dict.set(PDFName_default.of("Duplex"),dup)};ViewerPreferences2.prototype.setPickTrayByPDFSize=function(pickTrayByPDFSize){var PickTrayByPDFSize=this.dict.context.obj(pickTrayByPDFSize);this.dict.set(PDFName_default.of("PickTrayByPDFSize"),PickTrayByPDFSize)};ViewerPreferences2.prototype.setPrintPageRange=function(printPageRange){if(!Array.isArray(printPageRange))printPageRange=[printPageRange];var flatRange=[];for(var idx3=0,len2=printPageRange.length;idx3<len2;idx3++){flatRange.push(printPageRange[idx3].start);flatRange.push(printPageRange[idx3].end)}assertEachIs(flatRange,"printPageRange",["number"]);var pageRanges=this.dict.context.obj(flatRange);this.dict.set(PDFName_default.of("PrintPageRange"),pageRanges)};ViewerPreferences2.prototype.setNumCopies=function(numCopies){assertRange(numCopies,"numCopies",1,Number.MAX_VALUE);assertInteger(numCopies,"numCopies");var NumCopies=this.dict.context.obj(numCopies);this.dict.set(PDFName_default.of("NumCopies"),NumCopies)};ViewerPreferences2.fromDict=function(dict){return new ViewerPreferences2(dict)};ViewerPreferences2.create=function(context2){var dict=context2.obj({});return new ViewerPreferences2(dict)};return ViewerPreferences2}();ViewerPreferences_default=ViewerPreferences});var tfRegex,PDFAcroField,PDFAcroField_default;var init_PDFAcroField=__esm(()=>{init_PDFDict();init_PDFString();init_PDFHexString();init_PDFName();init_PDFNumber();init_PDFArray();init_PDFRef();init_utils2();init_errors2();tfRegex=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+Tf/;PDFAcroField=function(){function PDFAcroField2(dict,ref){this.dict=dict;this.ref=ref}PDFAcroField2.prototype.T=function(){return this.dict.lookupMaybe(PDFName_default.of("T"),PDFString_default,PDFHexString_default)};PDFAcroField2.prototype.Ff=function(){var numberOrRef=this.getInheritableAttribute(PDFName_default.of("Ff"));return this.dict.context.lookupMaybe(numberOrRef,PDFNumber_default)};PDFAcroField2.prototype.V=function(){var valueOrRef=this.getInheritableAttribute(PDFName_default.of("V"));return this.dict.context.lookup(valueOrRef)};PDFAcroField2.prototype.Kids=function(){return this.dict.lookupMaybe(PDFName_default.of("Kids"),PDFArray_default)};PDFAcroField2.prototype.DA=function(){var da=this.dict.lookup(PDFName_default.of("DA"));if(da instanceof PDFString_default||da instanceof PDFHexString_default)return da;return};PDFAcroField2.prototype.setKids=function(kids){this.dict.set(PDFName_default.of("Kids"),this.dict.context.obj(kids))};PDFAcroField2.prototype.getParent=function(){var parentRef=this.dict.get(PDFName_default.of("Parent"));if(parentRef instanceof PDFRef_default){var parent_1=this.dict.lookup(PDFName_default.of("Parent"),PDFDict_default);return new PDFAcroField2(parent_1,parentRef)}return};PDFAcroField2.prototype.setParent=function(parent){if(!parent)this.dict.delete(PDFName_default.of("Parent"));else this.dict.set(PDFName_default.of("Parent"),parent)};PDFAcroField2.prototype.getFullyQualifiedName=function(){var parent=this.getParent();if(!parent)return this.getPartialName();return parent.getFullyQualifiedName()+"."+this.getPartialName()};PDFAcroField2.prototype.getPartialName=function(){var _a;return(_a=this.T())===null||_a===undefined?undefined:_a.decodeText()};PDFAcroField2.prototype.setPartialName=function(partialName){if(!partialName)this.dict.delete(PDFName_default.of("T"));else this.dict.set(PDFName_default.of("T"),PDFHexString_default.fromText(partialName))};PDFAcroField2.prototype.setDefaultAppearance=function(appearance){this.dict.set(PDFName_default.of("DA"),PDFString_default.of(appearance))};PDFAcroField2.prototype.getDefaultAppearance=function(){var DA=this.DA();if(DA instanceof PDFHexString_default){return DA.decodeText()}return DA===null||DA===undefined?undefined:DA.asString()};PDFAcroField2.prototype.setFontSize=function(fontSize){var _a;var name=(_a=this.getFullyQualifiedName())!==null&&_a!==undefined?_a:"";var da=this.getDefaultAppearance();if(!da)throw new MissingDAEntryError(name);var daMatch=findLastMatch(da,tfRegex);if(!daMatch.match)throw new MissingTfOperatorError(name);var daStart=da.slice(0,daMatch.pos-daMatch.match[0].length);var daEnd=daMatch.pos<=da.length?da.slice(daMatch.pos):"";var fontName=daMatch.match[1];var modifiedDa=daStart+" /"+fontName+" "+fontSize+" Tf "+daEnd;this.setDefaultAppearance(modifiedDa)};PDFAcroField2.prototype.getFlags=function(){var _a,_b;return(_b=(_a=this.Ff())===null||_a===undefined?undefined:_a.asNumber())!==null&&_b!==undefined?_b:0};PDFAcroField2.prototype.setFlags=function(flags){this.dict.set(PDFName_default.of("Ff"),PDFNumber_default.of(flags))};PDFAcroField2.prototype.hasFlag=function(flag){var flags=this.getFlags();return(flags&flag)!==0};PDFAcroField2.prototype.setFlag=function(flag){var flags=this.getFlags();this.setFlags(flags|flag)};PDFAcroField2.prototype.clearFlag=function(flag){var flags=this.getFlags();this.setFlags(flags&~flag)};PDFAcroField2.prototype.setFlagTo=function(flag,enable){if(enable)this.setFlag(flag);else this.clearFlag(flag)};PDFAcroField2.prototype.getInheritableAttribute=function(name){var attribute;this.ascend(function(node){if(!attribute)attribute=node.dict.get(name)});return attribute};PDFAcroField2.prototype.ascend=function(visitor){visitor(this);var parent=this.getParent();if(parent)parent.ascend(visitor)};return PDFAcroField2}();PDFAcroField_default=PDFAcroField});var BorderStyle,BorderStyle_default;var init_BorderStyle=__esm(()=>{init_PDFName();init_PDFNumber();BorderStyle=function(){function BorderStyle2(dict){this.dict=dict}BorderStyle2.prototype.W=function(){var W=this.dict.lookup(PDFName_default.of("W"));if(W instanceof PDFNumber_default)return W;return};BorderStyle2.prototype.getWidth=function(){var _a,_b;return(_b=(_a=this.W())===null||_a===undefined?undefined:_a.asNumber())!==null&&_b!==undefined?_b:1};BorderStyle2.prototype.setWidth=function(width){var W=this.dict.context.obj(width);this.dict.set(PDFName_default.of("W"),W)};BorderStyle2.fromDict=function(dict){return new BorderStyle2(dict)};return BorderStyle2}();BorderStyle_default=BorderStyle});var PDFAnnotation,PDFAnnotation_default;var init_PDFAnnotation=__esm(()=>{init_PDFDict();init_PDFName();init_PDFStream();init_PDFArray();init_PDFRef();init_PDFNumber();PDFAnnotation=function(){function PDFAnnotation2(dict){this.dict=dict}PDFAnnotation2.prototype.Rect=function(){return this.dict.lookup(PDFName_default.of("Rect"),PDFArray_default)};PDFAnnotation2.prototype.AP=function(){return this.dict.lookupMaybe(PDFName_default.of("AP"),PDFDict_default)};PDFAnnotation2.prototype.F=function(){var numberOrRef=this.dict.lookup(PDFName_default.of("F"));return this.dict.context.lookupMaybe(numberOrRef,PDFNumber_default)};PDFAnnotation2.prototype.getRectangle=function(){var _a;var Rect=this.Rect();return(_a=Rect===null||Rect===undefined?undefined:Rect.asRectangle())!==null&&_a!==undefined?_a:{x:0,y:0,width:0,height:0}};PDFAnnotation2.prototype.setRectangle=function(rect){var{x,y,width,height}=rect;var Rect=this.dict.context.obj([x,y,x+width,y+height]);this.dict.set(PDFName_default.of("Rect"),Rect)};PDFAnnotation2.prototype.getAppearanceState=function(){var AS=this.dict.lookup(PDFName_default.of("AS"));if(AS instanceof PDFName_default)return AS;return};PDFAnnotation2.prototype.setAppearanceState=function(state){this.dict.set(PDFName_default.of("AS"),state)};PDFAnnotation2.prototype.setAppearances=function(appearances){this.dict.set(PDFName_default.of("AP"),appearances)};PDFAnnotation2.prototype.ensureAP=function(){var AP=this.AP();if(!AP){AP=this.dict.context.obj({});this.dict.set(PDFName_default.of("AP"),AP)}return AP};PDFAnnotation2.prototype.getNormalAppearance=function(){var AP=this.ensureAP();var N=AP.get(PDFName_default.of("N"));if(N instanceof PDFRef_default||N instanceof PDFDict_default)return N;throw new Error("Unexpected N type: "+(N===null||N===undefined?undefined:N.constructor.name))};PDFAnnotation2.prototype.setNormalAppearance=function(appearance){var AP=this.ensureAP();AP.set(PDFName_default.of("N"),appearance)};PDFAnnotation2.prototype.setRolloverAppearance=function(appearance){var AP=this.ensureAP();AP.set(PDFName_default.of("R"),appearance)};PDFAnnotation2.prototype.setDownAppearance=function(appearance){var AP=this.ensureAP();AP.set(PDFName_default.of("D"),appearance)};PDFAnnotation2.prototype.removeRolloverAppearance=function(){var AP=this.AP();AP===null||AP===undefined||AP.delete(PDFName_default.of("R"))};PDFAnnotation2.prototype.removeDownAppearance=function(){var AP=this.AP();AP===null||AP===undefined||AP.delete(PDFName_default.of("D"))};PDFAnnotation2.prototype.getAppearances=function(){var AP=this.AP();if(!AP)return;var N=AP.lookup(PDFName_default.of("N"),PDFDict_default,PDFStream_default);var R=AP.lookupMaybe(PDFName_default.of("R"),PDFDict_default,PDFStream_default);var D=AP.lookupMaybe(PDFName_default.of("D"),PDFDict_default,PDFStream_default);return{normal:N,rollover:R,down:D}};PDFAnnotation2.prototype.getFlags=function(){var _a,_b;return(_b=(_a=this.F())===null||_a===undefined?undefined:_a.asNumber())!==null&&_b!==undefined?_b:0};PDFAnnotation2.prototype.setFlags=function(flags){this.dict.set(PDFName_default.of("F"),PDFNumber_default.of(flags))};PDFAnnotation2.prototype.hasFlag=function(flag){var flags=this.getFlags();return(flags&flag)!==0};PDFAnnotation2.prototype.setFlag=function(flag){var flags=this.getFlags();this.setFlags(flags|flag)};PDFAnnotation2.prototype.clearFlag=function(flag){var flags=this.getFlags();this.setFlags(flags&~flag)};PDFAnnotation2.prototype.setFlagTo=function(flag,enable){if(enable)this.setFlag(flag);else this.clearFlag(flag)};PDFAnnotation2.fromDict=function(dict){return new PDFAnnotation2(dict)};return PDFAnnotation2}();PDFAnnotation_default=PDFAnnotation});var AppearanceCharacteristics,AppearanceCharacteristics_default;var init_AppearanceCharacteristics=__esm(()=>{init_PDFName();init_PDFNumber();init_PDFArray();init_PDFHexString();init_PDFString();AppearanceCharacteristics=function(){function AppearanceCharacteristics2(dict){this.dict=dict}AppearanceCharacteristics2.prototype.R=function(){var R=this.dict.lookup(PDFName_default.of("R"));if(R instanceof PDFNumber_default)return R;return};AppearanceCharacteristics2.prototype.BC=function(){var BC=this.dict.lookup(PDFName_default.of("BC"));if(BC instanceof PDFArray_default)return BC;return};AppearanceCharacteristics2.prototype.BG=function(){var BG=this.dict.lookup(PDFName_default.of("BG"));if(BG instanceof PDFArray_default)return BG;return};AppearanceCharacteristics2.prototype.CA=function(){var CA=this.dict.lookup(PDFName_default.of("CA"));if(CA instanceof PDFHexString_default||CA instanceof PDFString_default)return CA;return};AppearanceCharacteristics2.prototype.RC=function(){var RC=this.dict.lookup(PDFName_default.of("RC"));if(RC instanceof PDFHexString_default||RC instanceof PDFString_default)return RC;return};AppearanceCharacteristics2.prototype.AC=function(){var AC=this.dict.lookup(PDFName_default.of("AC"));if(AC instanceof PDFHexString_default||AC instanceof PDFString_default)return AC;return};AppearanceCharacteristics2.prototype.getRotation=function(){var _a;return(_a=this.R())===null||_a===undefined?undefined:_a.asNumber()};AppearanceCharacteristics2.prototype.getBorderColor=function(){var BC=this.BC();if(!BC)return;var components=[];for(var idx3=0,len2=BC===null||BC===undefined?undefined:BC.size();idx3<len2;idx3++){var component=BC.get(idx3);if(component instanceof PDFNumber_default)components.push(component.asNumber())}return components};AppearanceCharacteristics2.prototype.getBackgroundColor=function(){var BG=this.BG();if(!BG)return;var components=[];for(var idx3=0,len2=BG===null||BG===undefined?undefined:BG.size();idx3<len2;idx3++){var component=BG.get(idx3);if(component instanceof PDFNumber_default)components.push(component.asNumber())}return components};AppearanceCharacteristics2.prototype.getCaptions=function(){var CA=this.CA();var RC=this.RC();var AC=this.AC();return{normal:CA===null||CA===undefined?undefined:CA.decodeText(),rollover:RC===null||RC===undefined?undefined:RC.decodeText(),down:AC===null||AC===undefined?undefined:AC.decodeText()}};AppearanceCharacteristics2.prototype.setRotation=function(rotation){var R=this.dict.context.obj(rotation);this.dict.set(PDFName_default.of("R"),R)};AppearanceCharacteristics2.prototype.setBorderColor=function(color){var BC=this.dict.context.obj(color);this.dict.set(PDFName_default.of("BC"),BC)};AppearanceCharacteristics2.prototype.setBackgroundColor=function(color){var BG=this.dict.context.obj(color);this.dict.set(PDFName_default.of("BG"),BG)};AppearanceCharacteristics2.prototype.setCaptions=function(captions){var CA=PDFHexString_default.fromText(captions.normal);this.dict.set(PDFName_default.of("CA"),CA);if(captions.rollover){var RC=PDFHexString_default.fromText(captions.rollover);this.dict.set(PDFName_default.of("RC"),RC)}else{this.dict.delete(PDFName_default.of("RC"))}if(captions.down){var AC=PDFHexString_default.fromText(captions.down);this.dict.set(PDFName_default.of("AC"),AC)}else{this.dict.delete(PDFName_default.of("AC"))}};AppearanceCharacteristics2.fromDict=function(dict){return new AppearanceCharacteristics2(dict)};return AppearanceCharacteristics2}();AppearanceCharacteristics_default=AppearanceCharacteristics});var PDFWidgetAnnotation,PDFWidgetAnnotation_default;var init_PDFWidgetAnnotation=__esm(()=>{init_tslib_es62();init_PDFDict();init_PDFName();init_PDFRef();init_PDFString();init_PDFHexString();init_BorderStyle();init_PDFAnnotation();init_AppearanceCharacteristics();PDFWidgetAnnotation=function(_super){__extends(PDFWidgetAnnotation2,_super);function PDFWidgetAnnotation2(){return _super!==null&&_super.apply(this,arguments)||this}PDFWidgetAnnotation2.prototype.MK=function(){var MK=this.dict.lookup(PDFName_default.of("MK"));if(MK instanceof PDFDict_default)return MK;return};PDFWidgetAnnotation2.prototype.BS=function(){var BS=this.dict.lookup(PDFName_default.of("BS"));if(BS instanceof PDFDict_default)return BS;return};PDFWidgetAnnotation2.prototype.DA=function(){var da=this.dict.lookup(PDFName_default.of("DA"));if(da instanceof PDFString_default||da instanceof PDFHexString_default)return da;return};PDFWidgetAnnotation2.prototype.P=function(){var P=this.dict.get(PDFName_default.of("P"));if(P instanceof PDFRef_default)return P;return};PDFWidgetAnnotation2.prototype.setP=function(page){this.dict.set(PDFName_default.of("P"),page)};PDFWidgetAnnotation2.prototype.setDefaultAppearance=function(appearance){this.dict.set(PDFName_default.of("DA"),PDFString_default.of(appearance))};PDFWidgetAnnotation2.prototype.getDefaultAppearance=function(){var DA=this.DA();if(DA instanceof PDFHexString_default){return DA.decodeText()}return DA===null||DA===undefined?undefined:DA.asString()};PDFWidgetAnnotation2.prototype.getAppearanceCharacteristics=function(){var MK=this.MK();if(MK)return AppearanceCharacteristics_default.fromDict(MK);return};PDFWidgetAnnotation2.prototype.getOrCreateAppearanceCharacteristics=function(){var MK=this.MK();if(MK)return AppearanceCharacteristics_default.fromDict(MK);var ac=AppearanceCharacteristics_default.fromDict(this.dict.context.obj({}));this.dict.set(PDFName_default.of("MK"),ac.dict);return ac};PDFWidgetAnnotation2.prototype.getBorderStyle=function(){var BS=this.BS();if(BS)return BorderStyle_default.fromDict(BS);return};PDFWidgetAnnotation2.prototype.getOrCreateBorderStyle=function(){var BS=this.BS();if(BS)return BorderStyle_default.fromDict(BS);var bs=BorderStyle_default.fromDict(this.dict.context.obj({}));this.dict.set(PDFName_default.of("BS"),bs.dict);return bs};PDFWidgetAnnotation2.prototype.getOnValue=function(){var _a;var normal=(_a=this.getAppearances())===null||_a===undefined?undefined:_a.normal;if(normal instanceof PDFDict_default){var keys5=normal.keys();for(var idx3=0,len2=keys5.length;idx3<len2;idx3++){var key=keys5[idx3];if(key!==PDFName_default.of("Off"))return key}}return};PDFWidgetAnnotation2.fromDict=function(dict){return new PDFWidgetAnnotation2(dict)};PDFWidgetAnnotation2.create=function(context2,parent){var dict=context2.obj({Type:"Annot",Subtype:"Widget",Rect:[0,0,0,0],Parent:parent});return new PDFWidgetAnnotation2(dict)};return PDFWidgetAnnotation2}(PDFAnnotation_default);PDFWidgetAnnotation_default=PDFWidgetAnnotation});var PDFAcroTerminal,PDFAcroTerminal_default;var init_PDFAcroTerminal=__esm(()=>{init_tslib_es62();init_PDFDict();init_PDFName();init_PDFAcroField();init_PDFWidgetAnnotation();init_errors2();PDFAcroTerminal=function(_super){__extends(PDFAcroTerminal2,_super);function PDFAcroTerminal2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroTerminal2.prototype.FT=function(){var nameOrRef=this.getInheritableAttribute(PDFName_default.of("FT"));return this.dict.context.lookup(nameOrRef,PDFName_default)};PDFAcroTerminal2.prototype.getWidgets=function(){var kidDicts=this.Kids();if(!kidDicts)return[PDFWidgetAnnotation_default.fromDict(this.dict)];var widgets=new Array(kidDicts.size());for(var idx3=0,len2=kidDicts.size();idx3<len2;idx3++){var dict=kidDicts.lookup(idx3,PDFDict_default);widgets[idx3]=PDFWidgetAnnotation_default.fromDict(dict)}return widgets};PDFAcroTerminal2.prototype.addWidget=function(ref){var Kids=this.normalizedEntries().Kids;Kids.push(ref)};PDFAcroTerminal2.prototype.removeWidget=function(idx3){var kidDicts=this.Kids();if(!kidDicts){if(idx3!==0)throw new IndexOutOfBoundsError(idx3,0,0);this.setKids([])}else{if(idx3<0||idx3>kidDicts.size()){throw new IndexOutOfBoundsError(idx3,0,kidDicts.size())}kidDicts.remove(idx3)}};PDFAcroTerminal2.prototype.normalizedEntries=function(){var Kids=this.Kids();if(!Kids){Kids=this.dict.context.obj([this.ref]);this.dict.set(PDFName_default.of("Kids"),Kids)}return{Kids}};PDFAcroTerminal2.fromDict=function(dict,ref){return new PDFAcroTerminal2(dict,ref)};return PDFAcroTerminal2}(PDFAcroField_default);PDFAcroTerminal_default=PDFAcroTerminal});var PDFAcroButton,PDFAcroButton_default;var init_PDFAcroButton=__esm(()=>{init_tslib_es62();init_PDFString();init_PDFHexString();init_PDFArray();init_PDFName();init_PDFAcroTerminal();init_errors2();PDFAcroButton=function(_super){__extends(PDFAcroButton2,_super);function PDFAcroButton2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroButton2.prototype.Opt=function(){return this.dict.lookupMaybe(PDFName_default.of("Opt"),PDFString_default,PDFHexString_default,PDFArray_default)};PDFAcroButton2.prototype.setOpt=function(opt){this.dict.set(PDFName_default.of("Opt"),this.dict.context.obj(opt))};PDFAcroButton2.prototype.getExportValues=function(){var opt=this.Opt();if(!opt)return;if(opt instanceof PDFString_default||opt instanceof PDFHexString_default){return[opt]}var values2=[];for(var idx3=0,len2=opt.size();idx3<len2;idx3++){var value=opt.lookup(idx3);if(value instanceof PDFString_default||value instanceof PDFHexString_default){values2.push(value)}}return values2};PDFAcroButton2.prototype.removeExportValue=function(idx3){var opt=this.Opt();if(!opt)return;if(opt instanceof PDFString_default||opt instanceof PDFHexString_default){if(idx3!==0)throw new IndexOutOfBoundsError(idx3,0,0);this.setOpt([])}else{if(idx3<0||idx3>opt.size()){throw new IndexOutOfBoundsError(idx3,0,opt.size())}opt.remove(idx3)}};PDFAcroButton2.prototype.normalizeExportValues=function(){var _a,_b,_c,_d;var exportValues=(_a=this.getExportValues())!==null&&_a!==undefined?_a:[];var Opt=[];var widgets=this.getWidgets();for(var idx3=0,len2=widgets.length;idx3<len2;idx3++){var widget=widgets[idx3];var exportVal=(_b=exportValues[idx3])!==null&&_b!==undefined?_b:PDFHexString_default.fromText((_d=(_c=widget.getOnValue())===null||_c===undefined?undefined:_c.decodeText())!==null&&_d!==undefined?_d:"");Opt.push(exportVal)}this.setOpt(Opt)};PDFAcroButton2.prototype.addOpt=function(opt,useExistingOptIdx){var _a;this.normalizeExportValues();var optText=opt.decodeText();var existingIdx;if(useExistingOptIdx){var exportValues=(_a=this.getExportValues())!==null&&_a!==undefined?_a:[];for(var idx3=0,len2=exportValues.length;idx3<len2;idx3++){var exportVal=exportValues[idx3];if(exportVal.decodeText()===optText)existingIdx=idx3}}var Opt=this.Opt();Opt.push(opt);return existingIdx!==null&&existingIdx!==undefined?existingIdx:Opt.size()-1};PDFAcroButton2.prototype.addWidgetWithOpt=function(widget,opt,useExistingOptIdx){var optIdx=this.addOpt(opt,useExistingOptIdx);var apStateValue=PDFName_default.of(String(optIdx));this.addWidget(widget);return apStateValue};return PDFAcroButton2}(PDFAcroTerminal_default);PDFAcroButton_default=PDFAcroButton});var PDFAcroCheckBox,PDFAcroCheckBox_default;var init_PDFAcroCheckBox=__esm(()=>{init_tslib_es62();init_PDFName();init_PDFAcroButton();init_errors2();PDFAcroCheckBox=function(_super){__extends(PDFAcroCheckBox2,_super);function PDFAcroCheckBox2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroCheckBox2.prototype.setValue=function(value){var _a;var onValue=(_a=this.getOnValue())!==null&&_a!==undefined?_a:PDFName_default.of("Yes");if(value!==onValue&&value!==PDFName_default.of("Off")){throw new InvalidAcroFieldValueError}this.dict.set(PDFName_default.of("V"),value);var widgets=this.getWidgets();for(var idx3=0,len2=widgets.length;idx3<len2;idx3++){var widget=widgets[idx3];var state=widget.getOnValue()===value?value:PDFName_default.of("Off");widget.setAppearanceState(state)}};PDFAcroCheckBox2.prototype.getValue=function(){var v=this.V();if(v instanceof PDFName_default)return v;return PDFName_default.of("Off")};PDFAcroCheckBox2.prototype.getOnValue=function(){var widget=this.getWidgets()[0];return widget===null||widget===undefined?undefined:widget.getOnValue()};PDFAcroCheckBox2.fromDict=function(dict,ref){return new PDFAcroCheckBox2(dict,ref)};PDFAcroCheckBox2.create=function(context2){var dict=context2.obj({FT:"Btn",Kids:[]});var ref=context2.register(dict);return new PDFAcroCheckBox2(dict,ref)};return PDFAcroCheckBox2}(PDFAcroButton_default);PDFAcroCheckBox_default=PDFAcroCheckBox});var flag=function(bitIndex){return 1<<bitIndex},AcroFieldFlags,AcroButtonFlags,AcroTextFlags,AcroChoiceFlags;var init_flags=__esm(()=>{(function(AcroFieldFlags2){AcroFieldFlags2[AcroFieldFlags2["ReadOnly"]=flag(1-1)]="ReadOnly";AcroFieldFlags2[AcroFieldFlags2["Required"]=flag(2-1)]="Required";AcroFieldFlags2[AcroFieldFlags2["NoExport"]=flag(3-1)]="NoExport"})(AcroFieldFlags||(AcroFieldFlags={}));(function(AcroButtonFlags2){AcroButtonFlags2[AcroButtonFlags2["NoToggleToOff"]=flag(15-1)]="NoToggleToOff";AcroButtonFlags2[AcroButtonFlags2["Radio"]=flag(16-1)]="Radio";AcroButtonFlags2[AcroButtonFlags2["PushButton"]=flag(17-1)]="PushButton";AcroButtonFlags2[AcroButtonFlags2["RadiosInUnison"]=flag(26-1)]="RadiosInUnison"})(AcroButtonFlags||(AcroButtonFlags={}));(function(AcroTextFlags2){AcroTextFlags2[AcroTextFlags2["Multiline"]=flag(13-1)]="Multiline";AcroTextFlags2[AcroTextFlags2["Password"]=flag(14-1)]="Password";AcroTextFlags2[AcroTextFlags2["FileSelect"]=flag(21-1)]="FileSelect";AcroTextFlags2[AcroTextFlags2["DoNotSpellCheck"]=flag(23-1)]="DoNotSpellCheck";AcroTextFlags2[AcroTextFlags2["DoNotScroll"]=flag(24-1)]="DoNotScroll";AcroTextFlags2[AcroTextFlags2["Comb"]=flag(25-1)]="Comb";AcroTextFlags2[AcroTextFlags2["RichText"]=flag(26-1)]="RichText"})(AcroTextFlags||(AcroTextFlags={}));(function(AcroChoiceFlags2){AcroChoiceFlags2[AcroChoiceFlags2["Combo"]=flag(18-1)]="Combo";AcroChoiceFlags2[AcroChoiceFlags2["Edit"]=flag(19-1)]="Edit";AcroChoiceFlags2[AcroChoiceFlags2["Sort"]=flag(20-1)]="Sort";AcroChoiceFlags2[AcroChoiceFlags2["MultiSelect"]=flag(22-1)]="MultiSelect";AcroChoiceFlags2[AcroChoiceFlags2["DoNotSpellCheck"]=flag(23-1)]="DoNotSpellCheck";AcroChoiceFlags2[AcroChoiceFlags2["CommitOnSelChange"]=flag(27-1)]="CommitOnSelChange"})(AcroChoiceFlags||(AcroChoiceFlags={}))});var PDFAcroChoice,PDFAcroChoice_default;var init_PDFAcroChoice=__esm(()=>{init_tslib_es62();init_PDFAcroTerminal();init_PDFHexString();init_PDFString();init_PDFArray();init_PDFName();init_flags();init_errors2();PDFAcroChoice=function(_super){__extends(PDFAcroChoice2,_super);function PDFAcroChoice2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroChoice2.prototype.setValues=function(values2){if(this.hasFlag(AcroChoiceFlags.Combo)&&!this.hasFlag(AcroChoiceFlags.Edit)&&!this.valuesAreValid(values2)){throw new InvalidAcroFieldValueError}if(values2.length===0){this.dict.delete(PDFName_default.of("V"))}if(values2.length===1){this.dict.set(PDFName_default.of("V"),values2[0])}if(values2.length>1){if(!this.hasFlag(AcroChoiceFlags.MultiSelect)){throw new MultiSelectValueError}this.dict.set(PDFName_default.of("V"),this.dict.context.obj(values2))}this.updateSelectedIndices(values2)};PDFAcroChoice2.prototype.valuesAreValid=function(values2){var options=this.getOptions();var _loop_1=function(idx4,len3){var val=values2[idx4].decodeText();if(!options.find(function(o){return val===(o.display||o.value).decodeText()})){return{value:false}}};for(var idx3=0,len2=values2.length;idx3<len2;idx3++){var state_1=_loop_1(idx3,len2);if(typeof state_1==="object")return state_1.value}return true};PDFAcroChoice2.prototype.updateSelectedIndices=function(values2){if(values2.length>1){var indices=new Array(values2.length);var options=this.getOptions();var _loop_2=function(idx4,len3){var val=values2[idx4].decodeText();indices[idx4]=options.findIndex(function(o){return val===(o.display||o.value).decodeText()})};for(var idx3=0,len2=values2.length;idx3<len2;idx3++){_loop_2(idx3,len2)}this.dict.set(PDFName_default.of("I"),this.dict.context.obj(indices.sort()))}else{this.dict.delete(PDFName_default.of("I"))}};PDFAcroChoice2.prototype.getValues=function(){var v=this.V();if(v instanceof PDFString_default||v instanceof PDFHexString_default)return[v];if(v instanceof PDFArray_default){var values2=[];for(var idx3=0,len2=v.size();idx3<len2;idx3++){var value=v.lookup(idx3);if(value instanceof PDFString_default||value instanceof PDFHexString_default){values2.push(value)}}return values2}return[]};PDFAcroChoice2.prototype.Opt=function(){return this.dict.lookupMaybe(PDFName_default.of("Opt"),PDFString_default,PDFHexString_default,PDFArray_default)};PDFAcroChoice2.prototype.setOptions=function(options){var newOpt=new Array(options.length);for(var idx3=0,len2=options.length;idx3<len2;idx3++){var _a=options[idx3],value=_a.value,display=_a.display;newOpt[idx3]=this.dict.context.obj([value,display||value])}this.dict.set(PDFName_default.of("Opt"),this.dict.context.obj(newOpt))};PDFAcroChoice2.prototype.getOptions=function(){var Opt=this.Opt();if(Opt instanceof PDFString_default||Opt instanceof PDFHexString_default){return[{value:Opt,display:Opt}]}if(Opt instanceof PDFArray_default){var res=[];for(var idx3=0,len2=Opt.size();idx3<len2;idx3++){var item=Opt.lookup(idx3);if(item instanceof PDFString_default||item instanceof PDFHexString_default){res.push({value:item,display:item})}if(item instanceof PDFArray_default){if(item.size()>0){var first=item.lookup(0,PDFString_default,PDFHexString_default);var second=item.lookupMaybe(1,PDFString_default,PDFHexString_default);res.push({value:first,display:second||first})}}}return res}return[]};return PDFAcroChoice2}(PDFAcroTerminal_default);PDFAcroChoice_default=PDFAcroChoice});var PDFAcroComboBox,PDFAcroComboBox_default;var init_PDFAcroComboBox=__esm(()=>{init_tslib_es62();init_PDFAcroChoice();init_flags();PDFAcroComboBox=function(_super){__extends(PDFAcroComboBox2,_super);function PDFAcroComboBox2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroComboBox2.fromDict=function(dict,ref){return new PDFAcroComboBox2(dict,ref)};PDFAcroComboBox2.create=function(context2){var dict=context2.obj({FT:"Ch",Ff:AcroChoiceFlags.Combo,Kids:[]});var ref=context2.register(dict);return new PDFAcroComboBox2(dict,ref)};return PDFAcroComboBox2}(PDFAcroChoice_default);PDFAcroComboBox_default=PDFAcroComboBox});var PDFAcroNonTerminal,PDFAcroNonTerminal_default;var init_PDFAcroNonTerminal=__esm(()=>{init_tslib_es62();init_PDFName();init_PDFAcroField();PDFAcroNonTerminal=function(_super){__extends(PDFAcroNonTerminal2,_super);function PDFAcroNonTerminal2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroNonTerminal2.prototype.addField=function(field){var Kids=this.normalizedEntries().Kids;Kids===null||Kids===undefined||Kids.push(field)};PDFAcroNonTerminal2.prototype.normalizedEntries=function(){var Kids=this.Kids();if(!Kids){Kids=this.dict.context.obj([]);this.dict.set(PDFName_default.of("Kids"),Kids)}return{Kids}};PDFAcroNonTerminal2.fromDict=function(dict,ref){return new PDFAcroNonTerminal2(dict,ref)};PDFAcroNonTerminal2.create=function(context2){var dict=context2.obj({});var ref=context2.register(dict);return new PDFAcroNonTerminal2(dict,ref)};return PDFAcroNonTerminal2}(PDFAcroField_default);PDFAcroNonTerminal_default=PDFAcroNonTerminal});var PDFAcroSignature,PDFAcroSignature_default;var init_PDFAcroSignature=__esm(()=>{init_tslib_es62();init_PDFAcroTerminal();PDFAcroSignature=function(_super){__extends(PDFAcroSignature2,_super);function PDFAcroSignature2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroSignature2.fromDict=function(dict,ref){return new PDFAcroSignature2(dict,ref)};return PDFAcroSignature2}(PDFAcroTerminal_default);PDFAcroSignature_default=PDFAcroSignature});var PDFAcroText,PDFAcroText_default;var init_PDFAcroText=__esm(()=>{init_tslib_es62();init_PDFNumber();init_PDFString();init_PDFHexString();init_PDFName();init_PDFAcroTerminal();PDFAcroText=function(_super){__extends(PDFAcroText2,_super);function PDFAcroText2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroText2.prototype.MaxLen=function(){var maxLen=this.dict.lookup(PDFName_default.of("MaxLen"));if(maxLen instanceof PDFNumber_default)return maxLen;return};PDFAcroText2.prototype.Q=function(){var q=this.dict.lookup(PDFName_default.of("Q"));if(q instanceof PDFNumber_default)return q;return};PDFAcroText2.prototype.setMaxLength=function(maxLength){this.dict.set(PDFName_default.of("MaxLen"),PDFNumber_default.of(maxLength))};PDFAcroText2.prototype.removeMaxLength=function(){this.dict.delete(PDFName_default.of("MaxLen"))};PDFAcroText2.prototype.getMaxLength=function(){var _a;return(_a=this.MaxLen())===null||_a===undefined?undefined:_a.asNumber()};PDFAcroText2.prototype.setQuadding=function(quadding){this.dict.set(PDFName_default.of("Q"),PDFNumber_default.of(quadding))};PDFAcroText2.prototype.getQuadding=function(){var _a;return(_a=this.Q())===null||_a===undefined?undefined:_a.asNumber()};PDFAcroText2.prototype.setValue=function(value){this.dict.set(PDFName_default.of("V"),value)};PDFAcroText2.prototype.removeValue=function(){this.dict.delete(PDFName_default.of("V"))};PDFAcroText2.prototype.getValue=function(){var v=this.V();if(v instanceof PDFString_default||v instanceof PDFHexString_default)return v;return};PDFAcroText2.fromDict=function(dict,ref){return new PDFAcroText2(dict,ref)};PDFAcroText2.create=function(context2){var dict=context2.obj({FT:"Tx",Kids:[]});var ref=context2.register(dict);return new PDFAcroText2(dict,ref)};return PDFAcroText2}(PDFAcroTerminal_default);PDFAcroText_default=PDFAcroText});var PDFAcroPushButton,PDFAcroPushButton_default;var init_PDFAcroPushButton=__esm(()=>{init_tslib_es62();init_PDFAcroButton();init_flags();PDFAcroPushButton=function(_super){__extends(PDFAcroPushButton2,_super);function PDFAcroPushButton2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroPushButton2.fromDict=function(dict,ref){return new PDFAcroPushButton2(dict,ref)};PDFAcroPushButton2.create=function(context2){var dict=context2.obj({FT:"Btn",Ff:AcroButtonFlags.PushButton,Kids:[]});var ref=context2.register(dict);return new PDFAcroPushButton2(dict,ref)};return PDFAcroPushButton2}(PDFAcroButton_default);PDFAcroPushButton_default=PDFAcroPushButton});var PDFAcroRadioButton,PDFAcroRadioButton_default;var init_PDFAcroRadioButton=__esm(()=>{init_tslib_es62();init_PDFName();init_PDFAcroButton();init_flags();init_errors2();PDFAcroRadioButton=function(_super){__extends(PDFAcroRadioButton2,_super);function PDFAcroRadioButton2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroRadioButton2.prototype.setValue=function(value){var onValues=this.getOnValues();if(!onValues.includes(value)&&value!==PDFName_default.of("Off")){throw new InvalidAcroFieldValueError}this.dict.set(PDFName_default.of("V"),value);var widgets=this.getWidgets();for(var idx3=0,len2=widgets.length;idx3<len2;idx3++){var widget=widgets[idx3];var state=widget.getOnValue()===value?value:PDFName_default.of("Off");widget.setAppearanceState(state)}};PDFAcroRadioButton2.prototype.getValue=function(){var v=this.V();if(v instanceof PDFName_default)return v;return PDFName_default.of("Off")};PDFAcroRadioButton2.prototype.getOnValues=function(){var widgets=this.getWidgets();var onValues=[];for(var idx3=0,len2=widgets.length;idx3<len2;idx3++){var onValue=widgets[idx3].getOnValue();if(onValue)onValues.push(onValue)}return onValues};PDFAcroRadioButton2.fromDict=function(dict,ref){return new PDFAcroRadioButton2(dict,ref)};PDFAcroRadioButton2.create=function(context2){var dict=context2.obj({FT:"Btn",Ff:AcroButtonFlags.Radio,Kids:[]});var ref=context2.register(dict);return new PDFAcroRadioButton2(dict,ref)};return PDFAcroRadioButton2}(PDFAcroButton_default);PDFAcroRadioButton_default=PDFAcroRadioButton});var PDFAcroListBox,PDFAcroListBox_default;var init_PDFAcroListBox=__esm(()=>{init_tslib_es62();init_PDFAcroChoice();PDFAcroListBox=function(_super){__extends(PDFAcroListBox2,_super);function PDFAcroListBox2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroListBox2.fromDict=function(dict,ref){return new PDFAcroListBox2(dict,ref)};PDFAcroListBox2.create=function(context2){var dict=context2.obj({FT:"Ch",Kids:[]});var ref=context2.register(dict);return new PDFAcroListBox2(dict,ref)};return PDFAcroListBox2}(PDFAcroChoice_default);PDFAcroListBox_default=PDFAcroListBox});var createPDFAcroFields=function(kidDicts){if(!kidDicts)return[];var kids=[];for(var idx3=0,len2=kidDicts.size();idx3<len2;idx3++){var ref=kidDicts.get(idx3);var dict=kidDicts.lookup(idx3);if(ref instanceof PDFRef_default&&dict instanceof PDFDict_default){kids.push([createPDFAcroField(dict,ref),ref])}}return kids},createPDFAcroField=function(dict,ref){var isNonTerminal=isNonTerminalAcroField(dict);if(isNonTerminal)return PDFAcroNonTerminal_default.fromDict(dict,ref);return createPDFAcroTerminal(dict,ref)},isNonTerminalAcroField=function(dict){var kids=dict.lookup(PDFName_default.of("Kids"));if(kids instanceof PDFArray_default){for(var idx3=0,len2=kids.size();idx3<len2;idx3++){var kid=kids.lookup(idx3);var kidIsField=kid instanceof PDFDict_default&&kid.has(PDFName_default.of("T"));if(kidIsField)return true}}return false},createPDFAcroTerminal=function(dict,ref){var ftNameOrRef=getInheritableAttribute(dict,PDFName_default.of("FT"));var type=dict.context.lookup(ftNameOrRef,PDFName_default);if(type===PDFName_default.of("Btn"))return createPDFAcroButton(dict,ref);if(type===PDFName_default.of("Ch"))return createPDFAcroChoice(dict,ref);if(type===PDFName_default.of("Tx"))return PDFAcroText_default.fromDict(dict,ref);if(type===PDFName_default.of("Sig"))return PDFAcroSignature_default.fromDict(dict,ref);return PDFAcroTerminal_default.fromDict(dict,ref)},createPDFAcroButton=function(dict,ref){var _a;var ffNumberOrRef=getInheritableAttribute(dict,PDFName_default.of("Ff"));var ffNumber=dict.context.lookupMaybe(ffNumberOrRef,PDFNumber_default);var flags=(_a=ffNumber===null||ffNumber===undefined?undefined:ffNumber.asNumber())!==null&&_a!==undefined?_a:0;if(flagIsSet(flags,AcroButtonFlags.PushButton)){return PDFAcroPushButton_default.fromDict(dict,ref)}else if(flagIsSet(flags,AcroButtonFlags.Radio)){return PDFAcroRadioButton_default.fromDict(dict,ref)}else{return PDFAcroCheckBox_default.fromDict(dict,ref)}},createPDFAcroChoice=function(dict,ref){var _a;var ffNumberOrRef=getInheritableAttribute(dict,PDFName_default.of("Ff"));var ffNumber=dict.context.lookupMaybe(ffNumberOrRef,PDFNumber_default);var flags=(_a=ffNumber===null||ffNumber===undefined?undefined:ffNumber.asNumber())!==null&&_a!==undefined?_a:0;if(flagIsSet(flags,AcroChoiceFlags.Combo)){return PDFAcroComboBox_default.fromDict(dict,ref)}else{return PDFAcroListBox_default.fromDict(dict,ref)}},flagIsSet=function(flags,flag2){return(flags&flag2)!==0},getInheritableAttribute=function(startNode,name){var attribute;ascend(startNode,function(node){if(!attribute)attribute=node.get(name)});return attribute},ascend=function(startNode,visitor){visitor(startNode);var Parent=startNode.lookupMaybe(PDFName_default.of("Parent"),PDFDict_default);if(Parent)ascend(Parent,visitor)};var init_utils3=__esm(()=>{init_PDFNumber();init_PDFDict();init_PDFName();init_PDFArray();init_PDFRef();init_PDFAcroTerminal();init_PDFAcroNonTerminal();init_PDFAcroSignature();init_PDFAcroText();init_PDFAcroPushButton();init_PDFAcroRadioButton();init_PDFAcroCheckBox();init_PDFAcroComboBox();init_PDFAcroListBox();init_flags()});var PDFAcroForm,PDFAcroForm_default;var init_PDFAcroForm=__esm(()=>{init_PDFDict();init_PDFArray();init_PDFName();init_PDFAcroNonTerminal();init_utils3();PDFAcroForm=function(){function PDFAcroForm2(dict){this.dict=dict}PDFAcroForm2.prototype.Fields=function(){var fields5=this.dict.lookup(PDFName_default.of("Fields"));if(fields5 instanceof PDFArray_default)return fields5;return};PDFAcroForm2.prototype.getFields=function(){var Fields=this.normalizedEntries().Fields;var fields5=new Array(Fields.size());for(var idx3=0,len2=Fields.size();idx3<len2;idx3++){var ref=Fields.get(idx3);var dict=Fields.lookup(idx3,PDFDict_default);fields5[idx3]=[createPDFAcroField(dict,ref),ref]}return fields5};PDFAcroForm2.prototype.getAllFields=function(){var allFields=[];var pushFields=function(fields5){if(!fields5)return;for(var idx3=0,len2=fields5.length;idx3<len2;idx3++){var field=fields5[idx3];allFields.push(field);var fieldModel=field[0];if(fieldModel instanceof PDFAcroNonTerminal_default){pushFields(createPDFAcroFields(fieldModel.Kids()))}}};pushFields(this.getFields());return allFields};PDFAcroForm2.prototype.addField=function(field){var Fields=this.normalizedEntries().Fields;Fields===null||Fields===undefined||Fields.push(field)};PDFAcroForm2.prototype.removeField=function(field){var parent=field.getParent();var fields5=parent===undefined?this.normalizedEntries().Fields:parent.Kids();var index=fields5===null||fields5===undefined?undefined:fields5.indexOf(field.ref);if(fields5===undefined||index===undefined){throw new Error("Tried to remove inexistent field "+field.getFullyQualifiedName())}fields5.remove(index);if(parent!==undefined&&fields5.size()===0){this.removeField(parent)}};PDFAcroForm2.prototype.normalizedEntries=function(){var Fields=this.Fields();if(!Fields){Fields=this.dict.context.obj([]);this.dict.set(PDFName_default.of("Fields"),Fields)}return{Fields}};PDFAcroForm2.fromDict=function(dict){return new PDFAcroForm2(dict)};PDFAcroForm2.create=function(context2){var dict=context2.obj({Fields:[]});return new PDFAcroForm2(dict)};return PDFAcroForm2}();PDFAcroForm_default=PDFAcroForm});var init_acroform=__esm(()=>{init_PDFAcroButton();init_PDFAcroCheckBox();init_PDFAcroChoice();init_PDFAcroComboBox();init_PDFAcroField();init_PDFAcroForm();init_PDFAcroListBox();init_PDFAcroNonTerminal();init_PDFAcroPushButton();init_PDFAcroRadioButton();init_PDFAcroSignature();init_PDFAcroTerminal();init_PDFAcroText();init_flags();init_utils3()});var PDFCatalog,PDFCatalog_default;var init_PDFCatalog=__esm(()=>{init_tslib_es62();init_PDFDict();init_PDFName();init_acroform();init_ViewerPreferences();PDFCatalog=function(_super){__extends(PDFCatalog2,_super);function PDFCatalog2(){return _super!==null&&_super.apply(this,arguments)||this}PDFCatalog2.prototype.Pages=function(){return this.lookup(PDFName_default.of("Pages"),PDFDict_default)};PDFCatalog2.prototype.AcroForm=function(){return this.lookupMaybe(PDFName_default.of("AcroForm"),PDFDict_default)};PDFCatalog2.prototype.getAcroForm=function(){var dict=this.AcroForm();if(!dict)return;return PDFAcroForm_default.fromDict(dict)};PDFCatalog2.prototype.getOrCreateAcroForm=function(){var acroForm=this.getAcroForm();if(!acroForm){acroForm=PDFAcroForm_default.create(this.context);var acroFormRef=this.context.register(acroForm.dict);this.set(PDFName_default.of("AcroForm"),acroFormRef)}return acroForm};PDFCatalog2.prototype.ViewerPreferences=function(){return this.lookupMaybe(PDFName_default.of("ViewerPreferences"),PDFDict_default)};PDFCatalog2.prototype.getViewerPreferences=function(){var dict=this.ViewerPreferences();if(!dict)return;return ViewerPreferences_default.fromDict(dict)};PDFCatalog2.prototype.getOrCreateViewerPreferences=function(){var viewerPrefs=this.getViewerPreferences();if(!viewerPrefs){viewerPrefs=ViewerPreferences_default.create(this.context);var viewerPrefsRef=this.context.register(viewerPrefs.dict);this.set(PDFName_default.of("ViewerPreferences"),viewerPrefsRef)}return viewerPrefs};PDFCatalog2.prototype.insertLeafNode=function(leafRef,index){var pagesRef=this.get(PDFName_default.of("Pages"));var maybeParentRef=this.Pages().insertLeafNode(leafRef,index);return maybeParentRef||pagesRef};PDFCatalog2.prototype.removeLeafNode=function(index){this.Pages().removeLeafNode(index)};PDFCatalog2.withContextAndPages=function(context2,pages){var dict=new Map;dict.set(PDFName_default.of("Type"),PDFName_default.of("Catalog"));dict.set(PDFName_default.of("Pages"),pages);return new PDFCatalog2(dict,context2)};PDFCatalog2.fromMapWithContext=function(map,context2){return new PDFCatalog2(map,context2)};return PDFCatalog2}(PDFDict_default);PDFCatalog_default=PDFCatalog});var PDFPageTree,PDFPageTree_default;var init_PDFPageTree=__esm(()=>{init_tslib_es62();init_PDFArray();init_PDFDict();init_PDFName();init_PDFNumber();init_PDFPageLeaf();init_errors2();PDFPageTree=function(_super){__extends(PDFPageTree2,_super);function PDFPageTree2(){return _super!==null&&_super.apply(this,arguments)||this}PDFPageTree2.prototype.Parent=function(){return this.lookup(PDFName_default.of("Parent"))};PDFPageTree2.prototype.Kids=function(){return this.lookup(PDFName_default.of("Kids"),PDFArray_default)};PDFPageTree2.prototype.Count=function(){return this.lookup(PDFName_default.of("Count"),PDFNumber_default)};PDFPageTree2.prototype.pushTreeNode=function(treeRef){var Kids=this.Kids();Kids.push(treeRef)};PDFPageTree2.prototype.pushLeafNode=function(leafRef){var Kids=this.Kids();this.insertLeafKid(Kids.size(),leafRef)};PDFPageTree2.prototype.insertLeafNode=function(leafRef,targetIndex){var Kids=this.Kids();var Count=this.Count().asNumber();if(targetIndex>Count){throw new InvalidTargetIndexError(targetIndex,Count)}var leafsRemainingUntilTarget=targetIndex;for(var idx3=0,len2=Kids.size();idx3<len2;idx3++){if(leafsRemainingUntilTarget===0){this.insertLeafKid(idx3,leafRef);return}var kidRef=Kids.get(idx3);var kid=this.context.lookup(kidRef);if(kid instanceof PDFPageTree2){if(kid.Count().asNumber()>leafsRemainingUntilTarget){return kid.insertLeafNode(leafRef,leafsRemainingUntilTarget)||kidRef}else{leafsRemainingUntilTarget-=kid.Count().asNumber()}}if(kid instanceof PDFPageLeaf_default){leafsRemainingUntilTarget-=1}}if(leafsRemainingUntilTarget===0){this.insertLeafKid(Kids.size(),leafRef);return}throw new CorruptPageTreeError(targetIndex,"insertLeafNode")};PDFPageTree2.prototype.removeLeafNode=function(targetIndex,prune){if(prune===undefined){prune=true}var Kids=this.Kids();var Count=this.Count().asNumber();if(targetIndex>=Count){throw new InvalidTargetIndexError(targetIndex,Count)}var leafsRemainingUntilTarget=targetIndex;for(var idx3=0,len2=Kids.size();idx3<len2;idx3++){var kidRef=Kids.get(idx3);var kid=this.context.lookup(kidRef);if(kid instanceof PDFPageTree2){if(kid.Count().asNumber()>leafsRemainingUntilTarget){kid.removeLeafNode(leafsRemainingUntilTarget,prune);if(prune&&kid.Kids().size()===0)Kids.remove(idx3);return}else{leafsRemainingUntilTarget-=kid.Count().asNumber()}}if(kid instanceof PDFPageLeaf_default){if(leafsRemainingUntilTarget===0){this.removeKid(idx3);return}else{leafsRemainingUntilTarget-=1}}}throw new CorruptPageTreeError(targetIndex,"removeLeafNode")};PDFPageTree2.prototype.ascend=function(visitor){visitor(this);var Parent=this.Parent();if(Parent)Parent.ascend(visitor)};PDFPageTree2.prototype.traverse=function(visitor){var Kids=this.Kids();for(var idx3=0,len2=Kids.size();idx3<len2;idx3++){var kidRef=Kids.get(idx3);var kid=this.context.lookup(kidRef);if(kid instanceof PDFPageTree2)kid.traverse(visitor);visitor(kid,kidRef)}};PDFPageTree2.prototype.insertLeafKid=function(kidIdx,leafRef){var Kids=this.Kids();this.ascend(function(node){var newCount=node.Count().asNumber()+1;node.set(PDFName_default.of("Count"),PDFNumber_default.of(newCount))});Kids.insert(kidIdx,leafRef)};PDFPageTree2.prototype.removeKid=function(kidIdx){var Kids=this.Kids();var kid=Kids.lookup(kidIdx);if(kid instanceof PDFPageLeaf_default){this.ascend(function(node){var newCount=node.Count().asNumber()-1;node.set(PDFName_default.of("Count"),PDFNumber_default.of(newCount))})}Kids.remove(kidIdx)};PDFPageTree2.withContext=function(context2,parent){var dict=new Map;dict.set(PDFName_default.of("Type"),PDFName_default.of("Pages"));dict.set(PDFName_default.of("Kids"),context2.obj([]));dict.set(PDFName_default.of("Count"),context2.obj(0));if(parent)dict.set(PDFName_default.of("Parent"),parent);return new PDFPageTree2(dict,context2)};PDFPageTree2.fromMapWithContext=function(map,context2){return new PDFPageTree2(map,context2)};return PDFPageTree2}(PDFDict_default);PDFPageTree_default=PDFPageTree});var IsDigit,IsNumericPrefix,IsNumeric,idx3,len2;var init_Numeric=__esm(()=>{init_CharCodes();IsDigit=new Uint8Array(256);IsDigit[CharCodes_default.Zero]=1;IsDigit[CharCodes_default.One]=1;IsDigit[CharCodes_default.Two]=1;IsDigit[CharCodes_default.Three]=1;IsDigit[CharCodes_default.Four]=1;IsDigit[CharCodes_default.Five]=1;IsDigit[CharCodes_default.Six]=1;IsDigit[CharCodes_default.Seven]=1;IsDigit[CharCodes_default.Eight]=1;IsDigit[CharCodes_default.Nine]=1;IsNumericPrefix=new Uint8Array(256);IsNumericPrefix[CharCodes_default.Period]=1;IsNumericPrefix[CharCodes_default.Plus]=1;IsNumericPrefix[CharCodes_default.Minus]=1;IsNumeric=new Uint8Array(256);for(idx3=0,len2=256;idx3<len2;idx3++){IsNumeric[idx3]=IsDigit[idx3]||IsNumericPrefix[idx3]?1:0}});var Newline,CarriageReturn,BaseParser,BaseParser_default;var init_BaseParser=__esm(()=>{init_errors2();init_CharCodes();init_Numeric();init_Whitespace();init_utils2();Newline=CharCodes_default.Newline;CarriageReturn=CharCodes_default.CarriageReturn;BaseParser=function(){function BaseParser2(bytes,capNumbers){if(capNumbers===undefined){capNumbers=false}this.bytes=bytes;this.capNumbers=capNumbers}BaseParser2.prototype.parseRawInt=function(){var value="";while(!this.bytes.done()){var byte=this.bytes.peek();if(!IsDigit[byte])break;value+=charFromCode(this.bytes.next())}var numberValue=Number(value);if(!value||!isFinite(numberValue)){throw new NumberParsingError(this.bytes.position(),value)}return numberValue};BaseParser2.prototype.parseRawNumber=function(){var value="";while(!this.bytes.done()){var byte=this.bytes.peek();if(!IsNumeric[byte])break;value+=charFromCode(this.bytes.next());if(byte===CharCodes_default.Period)break}while(!this.bytes.done()){var byte=this.bytes.peek();if(!IsDigit[byte])break;value+=charFromCode(this.bytes.next())}var numberValue=Number(value);if(!value||!isFinite(numberValue)){throw new NumberParsingError(this.bytes.position(),value)}if(numberValue>Number.MAX_SAFE_INTEGER){if(this.capNumbers){var msg="Parsed number that is too large for some PDF readers: "+value+", using Number.MAX_SAFE_INTEGER instead.";console.warn(msg);return Number.MAX_SAFE_INTEGER}else{var msg="Parsed number that is too large for some PDF readers: "+value+", not capping.";console.warn(msg)}}return numberValue};BaseParser2.prototype.skipWhitespace=function(){while(!this.bytes.done()&&IsWhitespace[this.bytes.peek()]){this.bytes.next()}};BaseParser2.prototype.skipLine=function(){while(!this.bytes.done()){var byte=this.bytes.peek();if(byte===Newline||byte===CarriageReturn)return;this.bytes.next()}};BaseParser2.prototype.skipComment=function(){if(this.bytes.peek()!==CharCodes_default.Percent)return false;while(!this.bytes.done()){var byte=this.bytes.peek();if(byte===Newline||byte===CarriageReturn)return true;this.bytes.next()}return true};BaseParser2.prototype.skipWhitespaceAndComments=function(){this.skipWhitespace();while(this.skipComment())this.skipWhitespace()};BaseParser2.prototype.matchKeyword=function(keyword){var initialOffset=this.bytes.offset();for(var idx4=0,len3=keyword.length;idx4<len3;idx4++){if(this.bytes.done()||this.bytes.next()!==keyword[idx4]){this.bytes.moveTo(initialOffset);return false}}return true};return BaseParser2}();BaseParser_default=BaseParser});var ByteStream,ByteStream_default;var init_ByteStream=__esm(()=>{init_errors2();init_decode();init_CharCodes();ByteStream=function(){function ByteStream2(bytes){this.idx=0;this.line=0;this.column=0;this.bytes=bytes;this.length=this.bytes.length}ByteStream2.prototype.moveTo=function(offset){this.idx=offset};ByteStream2.prototype.next=function(){var byte=this.bytes[this.idx++];if(byte===CharCodes_default.Newline){this.line+=1;this.column=0}else{this.column+=1}return byte};ByteStream2.prototype.assertNext=function(expected){if(this.peek()!==expected){throw new NextByteAssertionError(this.position(),expected,this.peek())}return this.next()};ByteStream2.prototype.peek=function(){return this.bytes[this.idx]};ByteStream2.prototype.peekAhead=function(steps){return this.bytes[this.idx+steps]};ByteStream2.prototype.peekAt=function(offset){return this.bytes[offset]};ByteStream2.prototype.done=function(){return this.idx>=this.length};ByteStream2.prototype.offset=function(){return this.idx};ByteStream2.prototype.slice=function(start,end){return this.bytes.slice(start,end)};ByteStream2.prototype.position=function(){return{line:this.line,column:this.column,offset:this.idx}};ByteStream2.of=function(bytes){return new ByteStream2(bytes)};ByteStream2.fromPDFRawStream=function(rawStream){return ByteStream2.of(decodePDFRawStream(rawStream).decode())};return ByteStream2}();ByteStream_default=ByteStream});var Space,CarriageReturn2,Newline2,stream,endstream,Keywords;var init_Keywords=__esm(()=>{init_tslib_es62();init_CharCodes();Space=CharCodes_default.Space;CarriageReturn2=CharCodes_default.CarriageReturn;Newline2=CharCodes_default.Newline;stream=[CharCodes_default.s,CharCodes_default.t,CharCodes_default.r,CharCodes_default.e,CharCodes_default.a,CharCodes_default.m];endstream=[CharCodes_default.e,CharCodes_default.n,CharCodes_default.d,CharCodes_default.s,CharCodes_default.t,CharCodes_default.r,CharCodes_default.e,CharCodes_default.a,CharCodes_default.m];Keywords={header:[CharCodes_default.Percent,CharCodes_default.P,CharCodes_default.D,CharCodes_default.F,CharCodes_default.Dash],eof:[CharCodes_default.Percent,CharCodes_default.Percent,CharCodes_default.E,CharCodes_default.O,CharCodes_default.F],obj:[CharCodes_default.o,CharCodes_default.b,CharCodes_default.j],endobj:[CharCodes_default.e,CharCodes_default.n,CharCodes_default.d,CharCodes_default.o,CharCodes_default.b,CharCodes_default.j],xref:[CharCodes_default.x,CharCodes_default.r,CharCodes_default.e,CharCodes_default.f],trailer:[CharCodes_default.t,CharCodes_default.r,CharCodes_default.a,CharCodes_default.i,CharCodes_default.l,CharCodes_default.e,CharCodes_default.r],startxref:[CharCodes_default.s,CharCodes_default.t,CharCodes_default.a,CharCodes_default.r,CharCodes_default.t,CharCodes_default.x,CharCodes_default.r,CharCodes_default.e,CharCodes_default.f],true:[CharCodes_default.t,CharCodes_default.r,CharCodes_default.u,CharCodes_default.e],false:[CharCodes_default.f,CharCodes_default.a,CharCodes_default.l,CharCodes_default.s,CharCodes_default.e],null:[CharCodes_default.n,CharCodes_default.u,CharCodes_default.l,CharCodes_default.l],stream,streamEOF1:__spreadArrays(stream,[Space,CarriageReturn2,Newline2]),streamEOF2:__spreadArrays(stream,[CarriageReturn2,Newline2]),streamEOF3:__spreadArrays(stream,[CarriageReturn2]),streamEOF4:__spreadArrays(stream,[Newline2]),endstream,EOF1endstream:__spreadArrays([CarriageReturn2,Newline2],endstream),EOF2endstream:__spreadArrays([CarriageReturn2],endstream),EOF3endstream:__spreadArrays([Newline2],endstream)}});var PDFObjectParser,PDFObjectParser_default;var init_PDFObjectParser=__esm(()=>{init_tslib_es62();init_errors2();init_PDFArray();init_PDFBool();init_PDFDict();init_PDFHexString();init_PDFName();init_PDFNull();init_PDFNumber();init_PDFRawStream();init_PDFRef();init_PDFString();init_BaseParser();init_ByteStream();init_PDFCatalog();init_PDFPageLeaf();init_PDFPageTree();init_CharCodes();init_Delimiters();init_Keywords();init_Numeric();init_Whitespace();init_utils2();PDFObjectParser=function(_super){__extends(PDFObjectParser2,_super);function PDFObjectParser2(byteStream,context2,capNumbers){if(capNumbers===undefined){capNumbers=false}var _this=_super.call(this,byteStream,capNumbers)||this;_this.context=context2;return _this}PDFObjectParser2.prototype.parseObject=function(){this.skipWhitespaceAndComments();if(this.matchKeyword(Keywords.true))return PDFBool_default.True;if(this.matchKeyword(Keywords.false))return PDFBool_default.False;if(this.matchKeyword(Keywords.null))return PDFNull_default;var byte=this.bytes.peek();if(byte===CharCodes_default.LessThan&&this.bytes.peekAhead(1)===CharCodes_default.LessThan){return this.parseDictOrStream()}if(byte===CharCodes_default.LessThan)return this.parseHexString();if(byte===CharCodes_default.LeftParen)return this.parseString();if(byte===CharCodes_default.ForwardSlash)return this.parseName();if(byte===CharCodes_default.LeftSquareBracket)return this.parseArray();if(IsNumeric[byte])return this.parseNumberOrRef();throw new PDFObjectParsingError(this.bytes.position(),byte)};PDFObjectParser2.prototype.parseNumberOrRef=function(){var firstNum=this.parseRawNumber();this.skipWhitespaceAndComments();var lookaheadStart=this.bytes.offset();if(IsDigit[this.bytes.peek()]){var secondNum=this.parseRawNumber();this.skipWhitespaceAndComments();if(this.bytes.peek()===CharCodes_default.R){this.bytes.assertNext(CharCodes_default.R);return PDFRef_default.of(firstNum,secondNum)}}this.bytes.moveTo(lookaheadStart);return PDFNumber_default.of(firstNum)};PDFObjectParser2.prototype.parseHexString=function(){var value="";this.bytes.assertNext(CharCodes_default.LessThan);while(!this.bytes.done()&&this.bytes.peek()!==CharCodes_default.GreaterThan){value+=charFromCode(this.bytes.next())}this.bytes.assertNext(CharCodes_default.GreaterThan);return PDFHexString_default.of(value)};PDFObjectParser2.prototype.parseString=function(){var nestingLvl=0;var isEscaped=false;var value="";while(!this.bytes.done()){var byte=this.bytes.next();value+=charFromCode(byte);if(!isEscaped){if(byte===CharCodes_default.LeftParen)nestingLvl+=1;if(byte===CharCodes_default.RightParen)nestingLvl-=1}if(byte===CharCodes_default.BackSlash){isEscaped=!isEscaped}else if(isEscaped){isEscaped=false}if(nestingLvl===0){return PDFString_default.of(value.substring(1,value.length-1))}}throw new UnbalancedParenthesisError(this.bytes.position())};PDFObjectParser2.prototype.parseName=function(){this.bytes.assertNext(CharCodes_default.ForwardSlash);var name="";while(!this.bytes.done()){var byte=this.bytes.peek();if(IsWhitespace[byte]||IsDelimiter[byte])break;name+=charFromCode(byte);this.bytes.next()}return PDFName_default.of(name)};PDFObjectParser2.prototype.parseArray=function(){this.bytes.assertNext(CharCodes_default.LeftSquareBracket);this.skipWhitespaceAndComments();var pdfArray=PDFArray_default.withContext(this.context);while(this.bytes.peek()!==CharCodes_default.RightSquareBracket){var element=this.parseObject();pdfArray.push(element);this.skipWhitespaceAndComments()}this.bytes.assertNext(CharCodes_default.RightSquareBracket);return pdfArray};PDFObjectParser2.prototype.parseDict=function(){this.bytes.assertNext(CharCodes_default.LessThan);this.bytes.assertNext(CharCodes_default.LessThan);this.skipWhitespaceAndComments();var dict=new Map;while(!this.bytes.done()&&this.bytes.peek()!==CharCodes_default.GreaterThan&&this.bytes.peekAhead(1)!==CharCodes_default.GreaterThan){var key=this.parseName();var value=this.parseObject();dict.set(key,value);this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments();this.bytes.assertNext(CharCodes_default.GreaterThan);this.bytes.assertNext(CharCodes_default.GreaterThan);var Type=dict.get(PDFName_default.of("Type"));if(Type===PDFName_default.of("Catalog")){return PDFCatalog_default.fromMapWithContext(dict,this.context)}else if(Type===PDFName_default.of("Pages")){return PDFPageTree_default.fromMapWithContext(dict,this.context)}else if(Type===PDFName_default.of("Page")){return PDFPageLeaf_default.fromMapWithContext(dict,this.context)}else{return PDFDict_default.fromMapWithContext(dict,this.context)}};PDFObjectParser2.prototype.parseDictOrStream=function(){var startPos=this.bytes.position();var dict=this.parseDict();this.skipWhitespaceAndComments();if(!this.matchKeyword(Keywords.streamEOF1)&&!this.matchKeyword(Keywords.streamEOF2)&&!this.matchKeyword(Keywords.streamEOF3)&&!this.matchKeyword(Keywords.streamEOF4)&&!this.matchKeyword(Keywords.stream)){return dict}var start=this.bytes.offset();var end;var Length=dict.get(PDFName_default.of("Length"));if(Length instanceof PDFNumber_default){end=start+Length.asNumber();this.bytes.moveTo(end);this.skipWhitespaceAndComments();if(!this.matchKeyword(Keywords.endstream)){this.bytes.moveTo(start);end=this.findEndOfStreamFallback(startPos)}}else{end=this.findEndOfStreamFallback(startPos)}var contents=this.bytes.slice(start,end);return PDFRawStream_default.of(dict,contents)};PDFObjectParser2.prototype.findEndOfStreamFallback=function(startPos){var nestingLvl=1;var end=this.bytes.offset();while(!this.bytes.done()){end=this.bytes.offset();if(this.matchKeyword(Keywords.stream)){nestingLvl+=1}else if(this.matchKeyword(Keywords.EOF1endstream)||this.matchKeyword(Keywords.EOF2endstream)||this.matchKeyword(Keywords.EOF3endstream)||this.matchKeyword(Keywords.endstream)){nestingLvl-=1}else{this.bytes.next()}if(nestingLvl===0)break}if(nestingLvl!==0)throw new PDFStreamParsingError(startPos);return end};PDFObjectParser2.forBytes=function(bytes,context2,capNumbers){return new PDFObjectParser2(ByteStream_default.of(bytes),context2,capNumbers)};PDFObjectParser2.forByteStream=function(byteStream,context2,capNumbers){if(capNumbers===undefined){capNumbers=false}return new PDFObjectParser2(byteStream,context2,capNumbers)};return PDFObjectParser2}(BaseParser_default);PDFObjectParser_default=PDFObjectParser});var PDFObjectStreamParser,PDFObjectStreamParser_default;var init_PDFObjectStreamParser=__esm(()=>{init_tslib_es62();init_errors2();init_PDFName();init_PDFNumber();init_PDFRef();init_ByteStream();init_PDFObjectParser();init_utils2();PDFObjectStreamParser=function(_super){__extends(PDFObjectStreamParser2,_super);function PDFObjectStreamParser2(rawStream,shouldWaitForTick){var _this=_super.call(this,ByteStream_default.fromPDFRawStream(rawStream),rawStream.dict.context)||this;var dict=rawStream.dict;_this.alreadyParsed=false;_this.shouldWaitForTick=shouldWaitForTick||function(){return false};_this.firstOffset=dict.lookup(PDFName_default.of("First"),PDFNumber_default).asNumber();_this.objectCount=dict.lookup(PDFName_default.of("N"),PDFNumber_default).asNumber();return _this}PDFObjectStreamParser2.prototype.parseIntoContext=function(){return __awaiter(this,undefined,undefined,function(){var offsetsAndObjectNumbers,idx4,len3,_a,objectNumber,offset,object5,ref;return __generator(this,function(_b){switch(_b.label){case 0:if(this.alreadyParsed){throw new ReparseError("PDFObjectStreamParser","parseIntoContext")}this.alreadyParsed=true;offsetsAndObjectNumbers=this.parseOffsetsAndObjectNumbers();idx4=0,len3=offsetsAndObjectNumbers.length;_b.label=1;case 1:if(!(idx4<len3))return[3,4];_a=offsetsAndObjectNumbers[idx4],objectNumber=_a.objectNumber,offset=_a.offset;this.bytes.moveTo(this.firstOffset+offset);object5=this.parseObject();ref=PDFRef_default.of(objectNumber,0);this.context.assign(ref,object5);if(!this.shouldWaitForTick())return[3,3];return[4,waitForTick()];case 2:_b.sent();_b.label=3;case 3:idx4++;return[3,1];case 4:return[2]}})})};PDFObjectStreamParser2.prototype.parseOffsetsAndObjectNumbers=function(){var offsetsAndObjectNumbers=[];for(var idx4=0,len3=this.objectCount;idx4<len3;idx4++){this.skipWhitespaceAndComments();var objectNumber=this.parseRawInt();this.skipWhitespaceAndComments();var offset=this.parseRawInt();offsetsAndObjectNumbers.push({objectNumber,offset})}return offsetsAndObjectNumbers};PDFObjectStreamParser2.forStream=function(rawStream,shouldWaitForTick){return new PDFObjectStreamParser2(rawStream,shouldWaitForTick)};return PDFObjectStreamParser2}(PDFObjectParser_default);PDFObjectStreamParser_default=PDFObjectStreamParser});var PDFXRefStreamParser,PDFXRefStreamParser_default;var init_PDFXRefStreamParser=__esm(()=>{init_errors2();init_PDFArray();init_PDFName();init_PDFNumber();init_PDFRef();init_ByteStream();PDFXRefStreamParser=function(){function PDFXRefStreamParser2(rawStream){this.alreadyParsed=false;this.dict=rawStream.dict;this.bytes=ByteStream_default.fromPDFRawStream(rawStream);this.context=this.dict.context;var Size=this.dict.lookup(PDFName_default.of("Size"),PDFNumber_default);var Index=this.dict.lookup(PDFName_default.of("Index"));if(Index instanceof PDFArray_default){this.subsections=[];for(var idx4=0,len3=Index.size();idx4<len3;idx4+=2){var firstObjectNumber=Index.lookup(idx4+0,PDFNumber_default).asNumber();var length_1=Index.lookup(idx4+1,PDFNumber_default).asNumber();this.subsections.push({firstObjectNumber,length:length_1})}}else{this.subsections=[{firstObjectNumber:0,length:Size.asNumber()}]}var W=this.dict.lookup(PDFName_default.of("W"),PDFArray_default);this.byteWidths=[-1,-1,-1];for(var idx4=0,len3=W.size();idx4<len3;idx4++){this.byteWidths[idx4]=W.lookup(idx4,PDFNumber_default).asNumber()}}PDFXRefStreamParser2.prototype.parseIntoContext=function(){if(this.alreadyParsed){throw new ReparseError("PDFXRefStreamParser","parseIntoContext")}this.alreadyParsed=true;this.context.trailerInfo={Root:this.dict.get(PDFName_default.of("Root")),Encrypt:this.dict.get(PDFName_default.of("Encrypt")),Info:this.dict.get(PDFName_default.of("Info")),ID:this.dict.get(PDFName_default.of("ID"))};var entries=this.parseEntries();return entries};PDFXRefStreamParser2.prototype.parseEntries=function(){var entries=[];var _a=this.byteWidths,typeFieldWidth=_a[0],offsetFieldWidth=_a[1],genFieldWidth=_a[2];for(var subsectionIdx=0,subsectionLen=this.subsections.length;subsectionIdx<subsectionLen;subsectionIdx++){var _b=this.subsections[subsectionIdx],firstObjectNumber=_b.firstObjectNumber,length_2=_b.length;for(var objIdx=0;objIdx<length_2;objIdx++){var type=0;for(var idx4=0,len3=typeFieldWidth;idx4<len3;idx4++){type=type<<8|this.bytes.next()}var offset=0;for(var idx4=0,len3=offsetFieldWidth;idx4<len3;idx4++){offset=offset<<8|this.bytes.next()}var generationNumber=0;for(var idx4=0,len3=genFieldWidth;idx4<len3;idx4++){generationNumber=generationNumber<<8|this.bytes.next()}if(typeFieldWidth===0)type=1;var objectNumber=firstObjectNumber+objIdx;var entry={ref:PDFRef_default.of(objectNumber,generationNumber),offset,deleted:type===0,inObjectStream:type===2};entries.push(entry)}}return entries};PDFXRefStreamParser2.forStream=function(rawStream){return new PDFXRefStreamParser2(rawStream)};return PDFXRefStreamParser2}();PDFXRefStreamParser_default=PDFXRefStreamParser});var PDFParser,PDFParser_default;var init_PDFParser=__esm(()=>{init_tslib_es62();init_PDFCrossRefSection();init_PDFHeader();init_PDFTrailer();init_errors2();init_PDFDict();init_PDFInvalidObject();init_PDFName();init_PDFRawStream();init_PDFRef();init_ByteStream();init_PDFObjectParser();init_PDFObjectStreamParser();init_PDFXRefStreamParser();init_PDFContext();init_CharCodes();init_Keywords();init_Numeric();init_utils2();PDFParser=function(_super){__extends(PDFParser2,_super);function PDFParser2(pdfBytes,objectsPerTick,throwOnInvalidObject,capNumbers){if(objectsPerTick===undefined){objectsPerTick=Infinity}if(throwOnInvalidObject===undefined){throwOnInvalidObject=false}if(capNumbers===undefined){capNumbers=false}var _this=_super.call(this,ByteStream_default.of(pdfBytes),PDFContext_default.create(),capNumbers)||this;_this.alreadyParsed=false;_this.parsedObjects=0;_this.shouldWaitForTick=function(){_this.parsedObjects+=1;return _this.parsedObjects%_this.objectsPerTick===0};_this.objectsPerTick=objectsPerTick;_this.throwOnInvalidObject=throwOnInvalidObject;return _this}PDFParser2.prototype.parseDocument=function(){return __awaiter(this,undefined,undefined,function(){var prevOffset,offset;return __generator(this,function(_a){switch(_a.label){case 0:if(this.alreadyParsed){throw new ReparseError("PDFParser","parseDocument")}this.alreadyParsed=true;this.context.header=this.parseHeader();_a.label=1;case 1:if(!!this.bytes.done())return[3,3];return[4,this.parseDocumentSection()];case 2:_a.sent();offset=this.bytes.offset();if(offset===prevOffset){throw new StalledParserError(this.bytes.position())}prevOffset=offset;return[3,1];case 3:this.maybeRecoverRoot();if(this.context.lookup(PDFRef_default.of(0))){console.warn("Removing parsed object: 0 0 R");this.context.delete(PDFRef_default.of(0))}return[2,this.context]}})})};PDFParser2.prototype.maybeRecoverRoot=function(){var isValidCatalog=function(obj){return obj instanceof PDFDict_default&&obj.lookup(PDFName_default.of("Type"))===PDFName_default.of("Catalog")};var catalog=this.context.lookup(this.context.trailerInfo.Root);if(!isValidCatalog(catalog)){var indirectObjects=this.context.enumerateIndirectObjects();for(var idx4=0,len3=indirectObjects.length;idx4<len3;idx4++){var _a=indirectObjects[idx4],ref=_a[0],object5=_a[1];if(isValidCatalog(object5)){this.context.trailerInfo.Root=ref}}}};PDFParser2.prototype.parseHeader=function(){while(!this.bytes.done()){if(this.matchKeyword(Keywords.header)){var major=this.parseRawInt();this.bytes.assertNext(CharCodes_default.Period);var minor=this.parseRawInt();var header=PDFHeader_default.forVersion(major,minor);this.skipBinaryHeaderComment();return header}this.bytes.next()}throw new MissingPDFHeaderError(this.bytes.position())};PDFParser2.prototype.parseIndirectObjectHeader=function(){this.skipWhitespaceAndComments();var objectNumber=this.parseRawInt();this.skipWhitespaceAndComments();var generationNumber=this.parseRawInt();this.skipWhitespaceAndComments();if(!this.matchKeyword(Keywords.obj)){throw new MissingKeywordError(this.bytes.position(),Keywords.obj)}return PDFRef_default.of(objectNumber,generationNumber)};PDFParser2.prototype.matchIndirectObjectHeader=function(){var initialOffset=this.bytes.offset();try{this.parseIndirectObjectHeader();return true}catch(e){this.bytes.moveTo(initialOffset);return false}};PDFParser2.prototype.parseIndirectObject=function(){return __awaiter(this,undefined,undefined,function(){var ref,object5;return __generator(this,function(_a){switch(_a.label){case 0:ref=this.parseIndirectObjectHeader();this.skipWhitespaceAndComments();object5=this.parseObject();this.skipWhitespaceAndComments();this.matchKeyword(Keywords.endobj);if(!(object5 instanceof PDFRawStream_default&&object5.dict.lookup(PDFName_default.of("Type"))===PDFName_default.of("ObjStm")))return[3,2];return[4,PDFObjectStreamParser_default.forStream(object5,this.shouldWaitForTick).parseIntoContext()];case 1:_a.sent();return[3,3];case 2:if(object5 instanceof PDFRawStream_default&&object5.dict.lookup(PDFName_default.of("Type"))===PDFName_default.of("XRef")){PDFXRefStreamParser_default.forStream(object5).parseIntoContext()}else{this.context.assign(ref,object5)}_a.label=3;case 3:return[2,ref]}})})};PDFParser2.prototype.tryToParseInvalidIndirectObject=function(){var startPos=this.bytes.position();var msg="Trying to parse invalid object: "+JSON.stringify(startPos)+")";if(this.throwOnInvalidObject)throw new Error(msg);console.warn(msg);var ref=this.parseIndirectObjectHeader();console.warn("Invalid object ref: "+ref);this.skipWhitespaceAndComments();var start=this.bytes.offset();var failed=true;while(!this.bytes.done()){if(this.matchKeyword(Keywords.endobj)){failed=false}if(!failed)break;this.bytes.next()}if(failed)throw new PDFInvalidObjectParsingError(startPos);var end=this.bytes.offset()-Keywords.endobj.length;var object5=PDFInvalidObject_default.of(this.bytes.slice(start,end));this.context.assign(ref,object5);return ref};PDFParser2.prototype.parseIndirectObjects=function(){return __awaiter(this,undefined,undefined,function(){var initialOffset,e_1;return __generator(this,function(_a){switch(_a.label){case 0:this.skipWhitespaceAndComments();_a.label=1;case 1:if(!(!this.bytes.done()&&IsDigit[this.bytes.peek()]))return[3,8];initialOffset=this.bytes.offset();_a.label=2;case 2:_a.trys.push([2,4,,5]);return[4,this.parseIndirectObject()];case 3:_a.sent();return[3,5];case 4:e_1=_a.sent();this.bytes.moveTo(initialOffset);this.tryToParseInvalidIndirectObject();return[3,5];case 5:this.skipWhitespaceAndComments();this.skipJibberish();if(!this.shouldWaitForTick())return[3,7];return[4,waitForTick()];case 6:_a.sent();_a.label=7;case 7:return[3,1];case 8:return[2]}})})};PDFParser2.prototype.maybeParseCrossRefSection=function(){this.skipWhitespaceAndComments();if(!this.matchKeyword(Keywords.xref))return;this.skipWhitespaceAndComments();var objectNumber=-1;var xref=PDFCrossRefSection_default.createEmpty();while(!this.bytes.done()&&IsDigit[this.bytes.peek()]){var firstInt=this.parseRawInt();this.skipWhitespaceAndComments();var secondInt=this.parseRawInt();this.skipWhitespaceAndComments();var byte=this.bytes.peek();if(byte===CharCodes_default.n||byte===CharCodes_default.f){var ref=PDFRef_default.of(objectNumber,secondInt);if(this.bytes.next()===CharCodes_default.n){xref.addEntry(ref,firstInt)}else{xref.addDeletedEntry(ref,firstInt)}objectNumber+=1}else{objectNumber=firstInt}this.skipWhitespaceAndComments()}return xref};PDFParser2.prototype.maybeParseTrailerDict=function(){this.skipWhitespaceAndComments();if(!this.matchKeyword(Keywords.trailer))return;this.skipWhitespaceAndComments();var dict=this.parseDict();var context2=this.context;context2.trailerInfo={Root:dict.get(PDFName_default.of("Root"))||context2.trailerInfo.Root,Encrypt:dict.get(PDFName_default.of("Encrypt"))||context2.trailerInfo.Encrypt,Info:dict.get(PDFName_default.of("Info"))||context2.trailerInfo.Info,ID:dict.get(PDFName_default.of("ID"))||context2.trailerInfo.ID}};PDFParser2.prototype.maybeParseTrailer=function(){this.skipWhitespaceAndComments();if(!this.matchKeyword(Keywords.startxref))return;this.skipWhitespaceAndComments();var offset=this.parseRawInt();this.skipWhitespace();this.matchKeyword(Keywords.eof);this.skipWhitespaceAndComments();this.matchKeyword(Keywords.eof);this.skipWhitespaceAndComments();return PDFTrailer_default.forLastCrossRefSectionOffset(offset)};PDFParser2.prototype.parseDocumentSection=function(){return __awaiter(this,undefined,undefined,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.parseIndirectObjects()];case 1:_a.sent();this.maybeParseCrossRefSection();this.maybeParseTrailerDict();this.maybeParseTrailer();this.skipJibberish();return[2]}})})};PDFParser2.prototype.skipJibberish=function(){this.skipWhitespaceAndComments();while(!this.bytes.done()){var initialOffset=this.bytes.offset();var byte=this.bytes.peek();var isAlphaNumeric=byte>=CharCodes_default.Space&&byte<=CharCodes_default.Tilde;if(isAlphaNumeric){if(this.matchKeyword(Keywords.xref)||this.matchKeyword(Keywords.trailer)||this.matchKeyword(Keywords.startxref)||this.matchIndirectObjectHeader()){this.bytes.moveTo(initialOffset);break}}this.bytes.next()}};PDFParser2.prototype.skipBinaryHeaderComment=function(){this.skipWhitespaceAndComments();try{var initialOffset=this.bytes.offset();this.parseIndirectObjectHeader();this.bytes.moveTo(initialOffset)}catch(e){this.bytes.next();this.skipWhitespaceAndComments()}};PDFParser2.forBytesWithOptions=function(pdfBytes,objectsPerTick,throwOnInvalidObject,capNumbers){return new PDFParser2(pdfBytes,objectsPerTick,throwOnInvalidObject,capNumbers)};return PDFParser2}(PDFObjectParser_default);PDFParser_default=PDFParser});var flag2=function(bitIndex){return 1<<bitIndex},AnnotationFlags;var init_flags2=__esm(()=>{(function(AnnotationFlags2){AnnotationFlags2[AnnotationFlags2["Invisible"]=flag2(1-1)]="Invisible";AnnotationFlags2[AnnotationFlags2["Hidden"]=flag2(2-1)]="Hidden";AnnotationFlags2[AnnotationFlags2["Print"]=flag2(3-1)]="Print";AnnotationFlags2[AnnotationFlags2["NoZoom"]=flag2(4-1)]="NoZoom";AnnotationFlags2[AnnotationFlags2["NoRotate"]=flag2(5-1)]="NoRotate";AnnotationFlags2[AnnotationFlags2["NoView"]=flag2(6-1)]="NoView";AnnotationFlags2[AnnotationFlags2["ReadOnly"]=flag2(7-1)]="ReadOnly";AnnotationFlags2[AnnotationFlags2["Locked"]=flag2(8-1)]="Locked";AnnotationFlags2[AnnotationFlags2["ToggleNoView"]=flag2(9-1)]="ToggleNoView";AnnotationFlags2[AnnotationFlags2["LockedContents"]=flag2(10-1)]="LockedContents"})(AnnotationFlags||(AnnotationFlags={}))});var init_annotation=__esm(()=>{init_PDFAnnotation();init_PDFWidgetAnnotation();init_AppearanceCharacteristics();init_flags2()});var init_core=__esm(()=>{init_CharCodes();init_PDFContext();init_PDFObjectCopier();init_PDFWriter();init_PDFStreamWriter();init_PDFHeader();init_PDFTrailer();init_PDFTrailerDict();init_PDFCrossRefSection();init_StandardFontEmbedder();init_CustomFontEmbedder();init_CustomFontSubsetEmbedder();init_FileEmbedder();init_JpegEmbedder();init_PngEmbedder();init_PDFPageEmbedder();init_ViewerPreferences();init_PDFObject();init_PDFBool();init_PDFNumber();init_PDFString();init_PDFHexString();init_PDFName();init_PDFNull();init_PDFArray();init_PDFDict();init_PDFRef();init_PDFInvalidObject();init_PDFStream();init_PDFRawStream();init_PDFCatalog();init_PDFContentStream();init_PDFCrossRefStream();init_PDFObjectStream();init_PDFPageTree();init_PDFPageLeaf();init_PDFFlateStream();init_PDFOperator();init_PDFOperatorNames();init_PDFObjectParser();init_PDFObjectStreamParser();init_PDFParser();init_PDFXRefStreamParser();init_decode();init_errors2();init_annotation();init_acroform()});var asPDFName=function(name){return name instanceof PDFName_default?name:PDFName_default.of(name)},asPDFNumber=function(num){return num instanceof PDFNumber_default?num:PDFNumber_default.of(num)},asNumber=function(num){return num instanceof PDFNumber_default?num.asNumber():num};var init_objects2=__esm(()=>{init_core()});var RotationTypes,radians=function(radianAngle){assertIs(radianAngle,"radianAngle",["number"]);return{type:RotationTypes.Radians,angle:radianAngle}},degrees=function(degreeAngle){assertIs(degreeAngle,"degreeAngle",["number"]);return{type:RotationTypes.Degrees,angle:degreeAngle}},Radians,Degrees,degreesToRadians=function(degree){return degree*Math.PI/180},radiansToDegrees=function(radian){return radian*180/Math.PI},toRadians=function(rotation){return rotation.type===Radians?rotation.angle:rotation.type===Degrees?degreesToRadians(rotation.angle):error("Invalid rotation: "+JSON.stringify(rotation))},toDegrees=function(rotation){return rotation.type===Radians?radiansToDegrees(rotation.angle):rotation.type===Degrees?rotation.angle:error("Invalid rotation: "+JSON.stringify(rotation))},reduceRotation=function(degreeAngle){if(degreeAngle===undefined){degreeAngle=0}var quadrants=degreeAngle/90%4;if(quadrants===0)return 0;if(quadrants===1)return 90;if(quadrants===2)return 180;if(quadrants===3)return 270;return 0},adjustDimsForRotation=function(dims,degreeAngle){if(degreeAngle===undefined){degreeAngle=0}var rotation=reduceRotation(degreeAngle);return rotation===90||rotation===270?{width:dims.height,height:dims.width}:{width:dims.width,height:dims.height}},rotateRectangle=function(rectangle,borderWidth,degreeAngle){if(borderWidth===undefined){borderWidth=0}if(degreeAngle===undefined){degreeAngle=0}var{x,y,width:w,height:h}=rectangle;var r=reduceRotation(degreeAngle);var b=borderWidth/2;if(r===0)return{x:x-b,y:y-b,width:w,height:h};else if(r===90)return{x:x-h+b,y:y-b,width:h,height:w};else if(r===180)return{x:x-w+b,y:y-h+b,width:w,height:h};else if(r===270)return{x:x-b,y:y-w+b,width:h,height:w};else return{x:x-b,y:y-b,width:w,height:h}};var init_rotations=__esm(()=>{init_utils2();(function(RotationTypes2){RotationTypes2["Degrees"]="degrees";RotationTypes2["Radians"]="radians"})(RotationTypes||(RotationTypes={}));Radians=RotationTypes.Radians;Degrees=RotationTypes.Degrees});var clip=function(){return PDFOperator_default.of(PDFOperatorNames_default.ClipNonZero)},clipEvenOdd=function(){return PDFOperator_default.of(PDFOperatorNames_default.ClipEvenOdd)},cos,sin,tan,concatTransformationMatrix=function(a,b,c,d,e,f){return PDFOperator_default.of(PDFOperatorNames_default.ConcatTransformationMatrix,[asPDFNumber(a),asPDFNumber(b),asPDFNumber(c),asPDFNumber(d),asPDFNumber(e),asPDFNumber(f)])},translate=function(xPos,yPos){return concatTransformationMatrix(1,0,0,1,xPos,yPos)},scale=function(xPos,yPos){return concatTransformationMatrix(xPos,0,0,yPos,0,0)},rotateRadians=function(angle){return concatTransformationMatrix(cos(asNumber(angle)),sin(asNumber(angle)),-sin(asNumber(angle)),cos(asNumber(angle)),0,0)},rotateDegrees=function(angle){return rotateRadians(degreesToRadians(asNumber(angle)))},skewRadians=function(xSkewAngle,ySkewAngle){return concatTransformationMatrix(1,tan(asNumber(xSkewAngle)),tan(asNumber(ySkewAngle)),1,0,0)},skewDegrees=function(xSkewAngle,ySkewAngle){return skewRadians(degreesToRadians(asNumber(xSkewAngle)),degreesToRadians(asNumber(ySkewAngle)))},setDashPattern=function(dashArray,dashPhase){return PDFOperator_default.of(PDFOperatorNames_default.SetLineDashPattern,["["+dashArray.map(asPDFNumber).join(" ")+"]",asPDFNumber(dashPhase)])},restoreDashPattern=function(){return setDashPattern([],0)},LineCapStyle,setLineCap=function(style){return PDFOperator_default.of(PDFOperatorNames_default.SetLineCapStyle,[asPDFNumber(style)])},LineJoinStyle,setLineJoin=function(style){return PDFOperator_default.of(PDFOperatorNames_default.SetLineJoinStyle,[asPDFNumber(style)])},setGraphicsState=function(state){return PDFOperator_default.of(PDFOperatorNames_default.SetGraphicsStateParams,[asPDFName(state)])},pushGraphicsState=function(){return PDFOperator_default.of(PDFOperatorNames_default.PushGraphicsState)},popGraphicsState=function(){return PDFOperator_default.of(PDFOperatorNames_default.PopGraphicsState)},setLineWidth=function(width){return PDFOperator_default.of(PDFOperatorNames_default.SetLineWidth,[asPDFNumber(width)])},appendBezierCurve=function(x1,y1,x2,y2,x3,y3){return PDFOperator_default.of(PDFOperatorNames_default.AppendBezierCurve,[asPDFNumber(x1),asPDFNumber(y1),asPDFNumber(x2),asPDFNumber(y2),asPDFNumber(x3),asPDFNumber(y3)])},appendQuadraticCurve=function(x1,y1,x2,y2){return PDFOperator_default.of(PDFOperatorNames_default.CurveToReplicateInitialPoint,[asPDFNumber(x1),asPDFNumber(y1),asPDFNumber(x2),asPDFNumber(y2)])},closePath=function(){return PDFOperator_default.of(PDFOperatorNames_default.ClosePath)},moveTo=function(xPos,yPos){return PDFOperator_default.of(PDFOperatorNames_default.MoveTo,[asPDFNumber(xPos),asPDFNumber(yPos)])},lineTo=function(xPos,yPos){return PDFOperator_default.of(PDFOperatorNames_default.LineTo,[asPDFNumber(xPos),asPDFNumber(yPos)])},rectangle=function(xPos,yPos,width,height){return PDFOperator_default.of(PDFOperatorNames_default.AppendRectangle,[asPDFNumber(xPos),asPDFNumber(yPos),asPDFNumber(width),asPDFNumber(height)])},square=function(xPos,yPos,size){return rectangle(xPos,yPos,size,size)},stroke=function(){return PDFOperator_default.of(PDFOperatorNames_default.StrokePath)},fill=function(){return PDFOperator_default.of(PDFOperatorNames_default.FillNonZero)},fillAndStroke=function(){return PDFOperator_default.of(PDFOperatorNames_default.FillNonZeroAndStroke)},endPath=function(){return PDFOperator_default.of(PDFOperatorNames_default.EndPath)},nextLine=function(){return PDFOperator_default.of(PDFOperatorNames_default.NextLine)},moveText=function(x,y){return PDFOperator_default.of(PDFOperatorNames_default.MoveText,[asPDFNumber(x),asPDFNumber(y)])},showText=function(text4){return PDFOperator_default.of(PDFOperatorNames_default.ShowText,[text4])},beginText=function(){return PDFOperator_default.of(PDFOperatorNames_default.BeginText)},endText=function(){return PDFOperator_default.of(PDFOperatorNames_default.EndText)},setFontAndSize=function(name,size){return PDFOperator_default.of(PDFOperatorNames_default.SetFontAndSize,[asPDFName(name),asPDFNumber(size)])},setCharacterSpacing=function(spacing){return PDFOperator_default.of(PDFOperatorNames_default.SetCharacterSpacing,[asPDFNumber(spacing)])},setWordSpacing=function(spacing){return PDFOperator_default.of(PDFOperatorNames_default.SetWordSpacing,[asPDFNumber(spacing)])},setCharacterSqueeze=function(squeeze){return PDFOperator_default.of(PDFOperatorNames_default.SetTextHorizontalScaling,[asPDFNumber(squeeze)])},setLineHeight=function(lineHeight){return PDFOperator_default.of(PDFOperatorNames_default.SetTextLineHeight,[asPDFNumber(lineHeight)])},setTextRise=function(rise){return PDFOperator_default.of(PDFOperatorNames_default.SetTextRise,[asPDFNumber(rise)])},TextRenderingMode,setTextRenderingMode=function(mode){return PDFOperator_default.of(PDFOperatorNames_default.SetTextRenderingMode,[asPDFNumber(mode)])},setTextMatrix=function(a,b,c,d,e,f){return PDFOperator_default.of(PDFOperatorNames_default.SetTextMatrix,[asPDFNumber(a),asPDFNumber(b),asPDFNumber(c),asPDFNumber(d),asPDFNumber(e),asPDFNumber(f)])},rotateAndSkewTextRadiansAndTranslate=function(rotationAngle,xSkewAngle,ySkewAngle,x,y){return setTextMatrix(cos(asNumber(rotationAngle)),sin(asNumber(rotationAngle))+tan(asNumber(xSkewAngle)),-sin(asNumber(rotationAngle))+tan(asNumber(ySkewAngle)),cos(asNumber(rotationAngle)),x,y)},rotateAndSkewTextDegreesAndTranslate=function(rotationAngle,xSkewAngle,ySkewAngle,x,y){return rotateAndSkewTextRadiansAndTranslate(degreesToRadians(asNumber(rotationAngle)),degreesToRadians(asNumber(xSkewAngle)),degreesToRadians(asNumber(ySkewAngle)),x,y)},drawObject=function(name){return PDFOperator_default.of(PDFOperatorNames_default.DrawObject,[asPDFName(name)])},setFillingGrayscaleColor=function(gray){return PDFOperator_default.of(PDFOperatorNames_default.NonStrokingColorGray,[asPDFNumber(gray)])},setStrokingGrayscaleColor=function(gray){return PDFOperator_default.of(PDFOperatorNames_default.StrokingColorGray,[asPDFNumber(gray)])},setFillingRgbColor=function(red,green,blue){return PDFOperator_default.of(PDFOperatorNames_default.NonStrokingColorRgb,[asPDFNumber(red),asPDFNumber(green),asPDFNumber(blue)])},setStrokingRgbColor=function(red,green,blue){return PDFOperator_default.of(PDFOperatorNames_default.StrokingColorRgb,[asPDFNumber(red),asPDFNumber(green),asPDFNumber(blue)])},setFillingCmykColor=function(cyan,magenta,yellow,key){return PDFOperator_default.of(PDFOperatorNames_default.NonStrokingColorCmyk,[asPDFNumber(cyan),asPDFNumber(magenta),asPDFNumber(yellow),asPDFNumber(key)])},setStrokingCmykColor=function(cyan,magenta,yellow,key){return PDFOperator_default.of(PDFOperatorNames_default.StrokingColorCmyk,[asPDFNumber(cyan),asPDFNumber(magenta),asPDFNumber(yellow),asPDFNumber(key)])},beginMarkedContent=function(tag){return PDFOperator_default.of(PDFOperatorNames_default.BeginMarkedContent,[asPDFName(tag)])},endMarkedContent=function(){return PDFOperator_default.of(PDFOperatorNames_default.EndMarkedContent)};var init_operators=__esm(()=>{init_objects2();init_rotations();init_core();cos=Math.cos;sin=Math.sin;tan=Math.tan;(function(LineCapStyle2){LineCapStyle2[LineCapStyle2["Butt"]=0]="Butt";LineCapStyle2[LineCapStyle2["Round"]=1]="Round";LineCapStyle2[LineCapStyle2["Projecting"]=2]="Projecting"})(LineCapStyle||(LineCapStyle={}));(function(LineJoinStyle2){LineJoinStyle2[LineJoinStyle2["Miter"]=0]="Miter";LineJoinStyle2[LineJoinStyle2["Round"]=1]="Round";LineJoinStyle2[LineJoinStyle2["Bevel"]=2]="Bevel"})(LineJoinStyle||(LineJoinStyle={}));(function(TextRenderingMode2){TextRenderingMode2[TextRenderingMode2["Fill"]=0]="Fill";TextRenderingMode2[TextRenderingMode2["Outline"]=1]="Outline";TextRenderingMode2[TextRenderingMode2["FillAndOutline"]=2]="FillAndOutline";TextRenderingMode2[TextRenderingMode2["Invisible"]=3]="Invisible";TextRenderingMode2[TextRenderingMode2["FillAndClip"]=4]="FillAndClip";TextRenderingMode2[TextRenderingMode2["OutlineAndClip"]=5]="OutlineAndClip";TextRenderingMode2[TextRenderingMode2["FillAndOutlineAndClip"]=6]="FillAndOutlineAndClip";TextRenderingMode2[TextRenderingMode2["Clip"]=7]="Clip"})(TextRenderingMode||(TextRenderingMode={}))});var ColorTypes,grayscale=function(gray){assertRange(gray,"gray",0,1);return{type:ColorTypes.Grayscale,gray}},rgb=function(red,green,blue){assertRange(red,"red",0,1);assertRange(green,"green",0,1);assertRange(blue,"blue",0,1);return{type:ColorTypes.RGB,red,green,blue}},cmyk=function(cyan,magenta,yellow,key){assertRange(cyan,"cyan",0,1);assertRange(magenta,"magenta",0,1);assertRange(yellow,"yellow",0,1);assertRange(key,"key",0,1);return{type:ColorTypes.CMYK,cyan,magenta,yellow,key}},Grayscale,RGB,CMYK,setFillingColor=function(color){return color.type===Grayscale?setFillingGrayscaleColor(color.gray):color.type===RGB?setFillingRgbColor(color.red,color.green,color.blue):color.type===CMYK?setFillingCmykColor(color.cyan,color.magenta,color.yellow,color.key):error("Invalid color: "+JSON.stringify(color))},setStrokingColor=function(color){return color.type===Grayscale?setStrokingGrayscaleColor(color.gray):color.type===RGB?setStrokingRgbColor(color.red,color.green,color.blue):color.type===CMYK?setStrokingCmykColor(color.cyan,color.magenta,color.yellow,color.key):error("Invalid color: "+JSON.stringify(color))},componentsToColor=function(comps,scale2){if(scale2===undefined){scale2=1}return(comps===null||comps===undefined?undefined:comps.length)===1?grayscale(comps[0]*scale2):(comps===null||comps===undefined?undefined:comps.length)===3?rgb(comps[0]*scale2,comps[1]*scale2,comps[2]*scale2):(comps===null||comps===undefined?undefined:comps.length)===4?cmyk(comps[0]*scale2,comps[1]*scale2,comps[2]*scale2,comps[3]*scale2):undefined},colorToComponents=function(color){return color.type===Grayscale?[color.gray]:color.type===RGB?[color.red,color.green,color.blue]:color.type===CMYK?[color.cyan,color.magenta,color.yellow,color.key]:error("Invalid color: "+JSON.stringify(color))};var init_colors=__esm(()=>{init_operators();init_utils2();(function(ColorTypes2){ColorTypes2["Grayscale"]="Grayscale";ColorTypes2["RGB"]="RGB";ColorTypes2["CMYK"]="CMYK"})(ColorTypes||(ColorTypes={}));Grayscale=ColorTypes.Grayscale;RGB=ColorTypes.RGB;CMYK=ColorTypes.CMYK});var cx=0,cy=0,px=0,py=0,sx=0,sy=0,parameters,parse=function(path){var cmd;var ret=[];var args=[];var curArg="";var foundDecimal=false;var params=0;for(var _i=0,path_1=path;_i<path_1.length;_i++){var c=path_1[_i];if(parameters.has(c)){params=parameters.get(c);if(cmd){if(curArg.length>0){args[args.length]=+curArg}ret[ret.length]={cmd,args};args=[];curArg="";foundDecimal=false}cmd=c}else if([" ",","].includes(c)||c==="-"&&curArg.length>0&&curArg[curArg.length-1]!=="e"||c==="."&&foundDecimal){if(curArg.length===0){continue}if(args.length===params){ret[ret.length]={cmd,args};args=[+curArg];if(cmd==="M"){cmd="L"}if(cmd==="m"){cmd="l"}}else{args[args.length]=+curArg}foundDecimal=c===".";curArg=["-","."].includes(c)?c:""}else{curArg+=c;if(c==="."){foundDecimal=true}}}if(curArg.length>0){if(args.length===params){ret[ret.length]={cmd,args};args=[+curArg];if(cmd==="M"){cmd="L"}if(cmd==="m"){cmd="l"}}else{args[args.length]=+curArg}}ret[ret.length]={cmd,args};return ret},apply=function(commands){cx=cy=px=py=sx=sy=0;var cmds=[];for(var i3=0;i3<commands.length;i3++){var c=commands[i3];if(c.cmd&&typeof runners[c.cmd]==="function"){var cmd=runners[c.cmd](c.args);if(Array.isArray(cmd)){cmds=cmds.concat(cmd)}else{cmds.push(cmd)}}}return cmds},runners,solveArc=function(x,y,coords){var rx=coords[0],ry=coords[1],rot=coords[2],large=coords[3],sweep=coords[4],ex=coords[5],ey=coords[6];var segs=arcToSegments(ex,ey,rx,ry,large,sweep,rot,x,y);var cmds=[];for(var _i=0,segs_1=segs;_i<segs_1.length;_i++){var seg=segs_1[_i];var bez=segmentToBezier.apply(undefined,seg);cmds.push(appendBezierCurve.apply(undefined,bez))}return cmds},arcToSegments=function(x,y,rx,ry,large,sweep,rotateX,ox,oy){var th=rotateX*(Math.PI/180);var sinTh=Math.sin(th);var cosTh=Math.cos(th);rx=Math.abs(rx);ry=Math.abs(ry);px=cosTh*(ox-x)*0.5+sinTh*(oy-y)*0.5;py=cosTh*(oy-y)*0.5-sinTh*(ox-x)*0.5;var pl=px*px/(rx*rx)+py*py/(ry*ry);if(pl>1){pl=Math.sqrt(pl);rx*=pl;ry*=pl}var a00=cosTh/rx;var a01=sinTh/rx;var a10=-sinTh/ry;var a11=cosTh/ry;var x0=a00*ox+a01*oy;var y0=a10*ox+a11*oy;var x1=a00*x+a01*y;var y1=a10*x+a11*y;var d=(x1-x0)*(x1-x0)+(y1-y0)*(y1-y0);var sfactorSq=1/d-0.25;if(sfactorSq<0){sfactorSq=0}var sfactor=Math.sqrt(sfactorSq);if(sweep===large){sfactor=-sfactor}var xc=0.5*(x0+x1)-sfactor*(y1-y0);var yc=0.5*(y0+y1)+sfactor*(x1-x0);var th0=Math.atan2(y0-yc,x0-xc);var th1=Math.atan2(y1-yc,x1-xc);var thArc=th1-th0;if(thArc<0&&sweep===1){thArc+=2*Math.PI}else if(thArc>0&&sweep===0){thArc-=2*Math.PI}var segments=Math.ceil(Math.abs(thArc/(Math.PI*0.5+0.001)));var result2=[];for(var i3=0;i3<segments;i3++){var th2=th0+i3*thArc/segments;var th3=th0+(i3+1)*thArc/segments;result2[i3]=[xc,yc,th2,th3,rx,ry,sinTh,cosTh]}return result2},segmentToBezier=function(cx1,cy1,th0,th1,rx,ry,sinTh,cosTh){var a00=cosTh*rx;var a01=-sinTh*ry;var a10=sinTh*rx;var a11=cosTh*ry;var thHalf=0.5*(th1-th0);var t=8/3*Math.sin(thHalf*0.5)*Math.sin(thHalf*0.5)/Math.sin(thHalf);var x1=cx1+Math.cos(th0)-t*Math.sin(th0);var y1=cy1+Math.sin(th0)+t*Math.cos(th0);var x3=cx1+Math.cos(th1);var y3=cy1+Math.sin(th1);var x2=x3+t*Math.sin(th1);var y2=y3-t*Math.cos(th1);var result2=[a00*x1+a01*y1,a10*x1+a11*y1,a00*x2+a01*y2,a10*x2+a11*y2,a00*x3+a01*y3,a10*x3+a11*y3];return result2},svgPathToOperators=function(path){return apply(parse(path))};var init_svgPath=__esm(()=>{init_operators();parameters=new Map([["A",7],["a",7],["C",6],["c",6],["H",1],["h",1],["L",2],["l",2],["M",2],["m",2],["Q",4],["q",4],["S",4],["s",4],["T",2],["t",2],["V",1],["v",1],["Z",0],["z",0]]);runners={M:function(a){cx=a[0];cy=a[1];px=py=null;sx=cx;sy=cy;return moveTo(cx,cy)},m:function(a){cx+=a[0];cy+=a[1];px=py=null;sx=cx;sy=cy;return moveTo(cx,cy)},C:function(a){cx=a[4];cy=a[5];px=a[2];py=a[3];return appendBezierCurve(a[0],a[1],a[2],a[3],a[4],a[5])},c:function(a){var cmd=appendBezierCurve(a[0]+cx,a[1]+cy,a[2]+cx,a[3]+cy,a[4]+cx,a[5]+cy);px=cx+a[2];py=cy+a[3];cx+=a[4];cy+=a[5];return cmd},S:function(a){if(px===null||py===null){px=cx;py=cy}var cmd=appendBezierCurve(cx-(px-cx),cy-(py-cy),a[0],a[1],a[2],a[3]);px=a[0];py=a[1];cx=a[2];cy=a[3];return cmd},s:function(a){if(px===null||py===null){px=cx;py=cy}var cmd=appendBezierCurve(cx-(px-cx),cy-(py-cy),cx+a[0],cy+a[1],cx+a[2],cy+a[3]);px=cx+a[0];py=cy+a[1];cx+=a[2];cy+=a[3];return cmd},Q:function(a){px=a[0];py=a[1];cx=a[2];cy=a[3];return appendQuadraticCurve(a[0],a[1],cx,cy)},q:function(a){var cmd=appendQuadraticCurve(a[0]+cx,a[1]+cy,a[2]+cx,a[3]+cy);px=cx+a[0];py=cy+a[1];cx+=a[2];cy+=a[3];return cmd},T:function(a){if(px===null||py===null){px=cx;py=cy}else{px=cx-(px-cx);py=cy-(py-cy)}var cmd=appendQuadraticCurve(px,py,a[0],a[1]);px=cx-(px-cx);py=cy-(py-cy);cx=a[0];cy=a[1];return cmd},t:function(a){if(px===null||py===null){px=cx;py=cy}else{px=cx-(px-cx);py=cy-(py-cy)}var cmd=appendQuadraticCurve(px,py,cx+a[0],cy+a[1]);cx+=a[0];cy+=a[1];return cmd},A:function(a){var cmds=solveArc(cx,cy,a);cx=a[5];cy=a[6];return cmds},a:function(a){a[5]+=cx;a[6]+=cy;var cmds=solveArc(cx,cy,a);cx=a[5];cy=a[6];return cmds},L:function(a){cx=a[0];cy=a[1];px=py=null;return lineTo(cx,cy)},l:function(a){cx+=a[0];cy+=a[1];px=py=null;return lineTo(cx,cy)},H:function(a){cx=a[0];px=py=null;return lineTo(cx,cy)},h:function(a){cx+=a[0];px=py=null;return lineTo(cx,cy)},V:function(a){cy=a[0];px=py=null;return lineTo(cx,cy)},v:function(a){cy+=a[0];px=py=null;return lineTo(cx,cy)},Z:function(){var cmd=closePath();cx=sx;cy=sy;return cmd},z:function(){var cmd=closePath();cx=sx;cy=sy;return cmd}}});var drawText=function(line,options){return[pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),beginText(),setFillingColor(options.color),setFontAndSize(options.font,options.size),rotateAndSkewTextRadiansAndTranslate(toRadians(options.rotate),toRadians(options.xSkew),toRadians(options.ySkew),options.x,options.y),showText(line),endText(),popGraphicsState()].filter(Boolean)},drawLinesOfText=function(lines,options){var operators=[pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),beginText(),setFillingColor(options.color),setFontAndSize(options.font,options.size),setLineHeight(options.lineHeight),rotateAndSkewTextRadiansAndTranslate(toRadians(options.rotate),toRadians(options.xSkew),toRadians(options.ySkew),options.x,options.y)].filter(Boolean);for(var idx4=0,len3=lines.length;idx4<len3;idx4++){operators.push(showText(lines[idx4]),nextLine())}operators.push(endText(),popGraphicsState());return operators},drawImage=function(name,options){return[pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),translate(options.x,options.y),rotateRadians(toRadians(options.rotate)),scale(options.width,options.height),skewRadians(toRadians(options.xSkew),toRadians(options.ySkew)),drawObject(name),popGraphicsState()].filter(Boolean)},drawPage=function(name,options){return[pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),translate(options.x,options.y),rotateRadians(toRadians(options.rotate)),scale(options.xScale,options.yScale),skewRadians(toRadians(options.xSkew),toRadians(options.ySkew)),drawObject(name),popGraphicsState()].filter(Boolean)},drawLine=function(options){var _a,_b;return[pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),options.color&&setStrokingColor(options.color),setLineWidth(options.thickness),setDashPattern((_a=options.dashArray)!==null&&_a!==undefined?_a:[],(_b=options.dashPhase)!==null&&_b!==undefined?_b:0),moveTo(options.start.x,options.start.y),options.lineCap&&setLineCap(options.lineCap),moveTo(options.start.x,options.start.y),lineTo(options.end.x,options.end.y),stroke(),popGraphicsState()].filter(Boolean)},drawRectangle=function(options){var _a,_b;return[pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),options.color&&setFillingColor(options.color),options.borderColor&&setStrokingColor(options.borderColor),setLineWidth(options.borderWidth),options.borderLineCap&&setLineCap(options.borderLineCap),setDashPattern((_a=options.borderDashArray)!==null&&_a!==undefined?_a:[],(_b=options.borderDashPhase)!==null&&_b!==undefined?_b:0),translate(options.x,options.y),rotateRadians(toRadians(options.rotate)),skewRadians(toRadians(options.xSkew),toRadians(options.ySkew)),moveTo(0,0),lineTo(0,options.height),lineTo(options.width,options.height),lineTo(options.width,0),closePath(),options.color&&options.borderWidth?fillAndStroke():options.color?fill():options.borderColor?stroke():closePath(),popGraphicsState()].filter(Boolean)},KAPPA,drawEllipsePath=function(config){var x=asNumber(config.x);var y=asNumber(config.y);var xScale=asNumber(config.xScale);var yScale=asNumber(config.yScale);x-=xScale;y-=yScale;var ox=xScale*KAPPA;var oy=yScale*KAPPA;var xe=x+xScale*2;var ye=y+yScale*2;var xm=x+xScale;var ym=y+yScale;return[pushGraphicsState(),moveTo(x,ym),appendBezierCurve(x,ym-oy,xm-ox,y,xm,y),appendBezierCurve(xm+ox,y,xe,ym-oy,xe,ym),appendBezierCurve(xe,ym+oy,xm+ox,ye,xm,ye),appendBezierCurve(xm-ox,ye,x,ym+oy,x,ym),popGraphicsState()]},drawEllipseCurves=function(config){var centerX=asNumber(config.x);var centerY=asNumber(config.y);var xScale=asNumber(config.xScale);var yScale=asNumber(config.yScale);var x=-xScale;var y=-yScale;var ox=xScale*KAPPA;var oy=yScale*KAPPA;var xe=x+xScale*2;var ye=y+yScale*2;var xm=x+xScale;var ym=y+yScale;return[translate(centerX,centerY),rotateRadians(toRadians(config.rotate)),moveTo(x,ym),appendBezierCurve(x,ym-oy,xm-ox,y,xm,y),appendBezierCurve(xm+ox,y,xe,ym-oy,xe,ym),appendBezierCurve(xe,ym+oy,xm+ox,ye,xm,ye),appendBezierCurve(xm-ox,ye,x,ym+oy,x,ym)]},drawEllipse=function(options){var _a,_b,_c;return __spreadArrays([pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),options.color&&setFillingColor(options.color),options.borderColor&&setStrokingColor(options.borderColor),setLineWidth(options.borderWidth),options.borderLineCap&&setLineCap(options.borderLineCap),setDashPattern((_a=options.borderDashArray)!==null&&_a!==undefined?_a:[],(_b=options.borderDashPhase)!==null&&_b!==undefined?_b:0)],options.rotate===undefined?drawEllipsePath({x:options.x,y:options.y,xScale:options.xScale,yScale:options.yScale}):drawEllipseCurves({x:options.x,y:options.y,xScale:options.xScale,yScale:options.yScale,rotate:(_c=options.rotate)!==null&&_c!==undefined?_c:degrees(0)}),[options.color&&options.borderWidth?fillAndStroke():options.color?fill():options.borderColor?stroke():closePath(),popGraphicsState()]).filter(Boolean)},drawSvgPath=function(path,options){var _a,_b,_c;return __spreadArrays([pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),translate(options.x,options.y),rotateRadians(toRadians((_a=options.rotate)!==null&&_a!==undefined?_a:degrees(0))),options.scale?scale(options.scale,-options.scale):scale(1,-1),options.color&&setFillingColor(options.color),options.borderColor&&setStrokingColor(options.borderColor),options.borderWidth&&setLineWidth(options.borderWidth),options.borderLineCap&&setLineCap(options.borderLineCap),setDashPattern((_b=options.borderDashArray)!==null&&_b!==undefined?_b:[],(_c=options.borderDashPhase)!==null&&_c!==undefined?_c:0)],svgPathToOperators(path),[options.color&&options.borderWidth?fillAndStroke():options.color?fill():options.borderColor?stroke():closePath(),popGraphicsState()]).filter(Boolean)},drawCheckMark=function(options){var size=asNumber(options.size);var p2x=-1+0.75;var p2y=-1+0.51;var p3y=1-0.525;var p3x=1-0.31;var p1x=-1+0.325;var p1y=-((p1x-p2x)*(p3x-p2x))/(p3y-p2y)+p2y;return[pushGraphicsState(),options.color&&setStrokingColor(options.color),setLineWidth(options.thickness),translate(options.x,options.y),moveTo(p1x*size,p1y*size),lineTo(p2x*size,p2y*size),lineTo(p3x*size,p3y*size),stroke(),popGraphicsState()].filter(Boolean)},rotateInPlace=function(options){return options.rotation===0?[translate(0,0),rotateDegrees(0)]:options.rotation===90?[translate(options.width,0),rotateDegrees(90)]:options.rotation===180?[translate(options.width,options.height),rotateDegrees(180)]:options.rotation===270?[translate(0,options.height),rotateDegrees(270)]:[]},drawCheckBox=function(options){var outline=drawRectangle({x:options.x,y:options.y,width:options.width,height:options.height,borderWidth:options.borderWidth,color:options.color,borderColor:options.borderColor,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)});if(!options.filled)return outline;var width=asNumber(options.width);var height=asNumber(options.height);var checkMarkSize=Math.min(width,height)/2;var checkMark=drawCheckMark({x:width/2,y:height/2,size:checkMarkSize,thickness:options.thickness,color:options.markColor});return __spreadArrays([pushGraphicsState()],outline,checkMark,[popGraphicsState()])},drawRadioButton=function(options){var width=asNumber(options.width);var height=asNumber(options.height);var outlineScale=Math.min(width,height)/2;var outline=drawEllipse({x:options.x,y:options.y,xScale:outlineScale,yScale:outlineScale,color:options.color,borderColor:options.borderColor,borderWidth:options.borderWidth});if(!options.filled)return outline;var dot=drawEllipse({x:options.x,y:options.y,xScale:outlineScale*0.45,yScale:outlineScale*0.45,color:options.dotColor,borderColor:undefined,borderWidth:0});return __spreadArrays([pushGraphicsState()],outline,dot,[popGraphicsState()])},drawButton=function(options){var x=asNumber(options.x);var y=asNumber(options.y);var width=asNumber(options.width);var height=asNumber(options.height);var background=drawRectangle({x,y,width,height,borderWidth:options.borderWidth,color:options.color,borderColor:options.borderColor,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)});var lines=drawTextLines(options.textLines,{color:options.textColor,font:options.font,size:options.fontSize,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)});return __spreadArrays([pushGraphicsState()],background,lines,[popGraphicsState()])},drawTextLines=function(lines,options){var operators=[beginText(),setFillingColor(options.color),setFontAndSize(options.font,options.size)];for(var idx4=0,len3=lines.length;idx4<len3;idx4++){var _a=lines[idx4],encoded=_a.encoded,x=_a.x,y=_a.y;operators.push(rotateAndSkewTextRadiansAndTranslate(toRadians(options.rotate),toRadians(options.xSkew),toRadians(options.ySkew),x,y),showText(encoded))}operators.push(endText());return operators},drawTextField=function(options){var x=asNumber(options.x);var y=asNumber(options.y);var width=asNumber(options.width);var height=asNumber(options.height);var borderWidth=asNumber(options.borderWidth);var padding=asNumber(options.padding);var clipX=x+borderWidth/2+padding;var clipY=y+borderWidth/2+padding;var clipWidth=width-(borderWidth/2+padding)*2;var clipHeight=height-(borderWidth/2+padding)*2;var clippingArea=[moveTo(clipX,clipY),lineTo(clipX,clipY+clipHeight),lineTo(clipX+clipWidth,clipY+clipHeight),lineTo(clipX+clipWidth,clipY),closePath(),clip(),endPath()];var background=drawRectangle({x,y,width,height,borderWidth:options.borderWidth,color:options.color,borderColor:options.borderColor,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)});var lines=drawTextLines(options.textLines,{color:options.textColor,font:options.font,size:options.fontSize,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)});var markedContent=__spreadArrays([beginMarkedContent("Tx"),pushGraphicsState()],lines,[popGraphicsState(),endMarkedContent()]);return __spreadArrays([pushGraphicsState()],background,clippingArea,markedContent,[popGraphicsState()])},drawOptionList=function(options){var x=asNumber(options.x);var y=asNumber(options.y);var width=asNumber(options.width);var height=asNumber(options.height);var lineHeight=asNumber(options.lineHeight);var borderWidth=asNumber(options.borderWidth);var padding=asNumber(options.padding);var clipX=x+borderWidth/2+padding;var clipY=y+borderWidth/2+padding;var clipWidth=width-(borderWidth/2+padding)*2;var clipHeight=height-(borderWidth/2+padding)*2;var clippingArea=[moveTo(clipX,clipY),lineTo(clipX,clipY+clipHeight),lineTo(clipX+clipWidth,clipY+clipHeight),lineTo(clipX+clipWidth,clipY),closePath(),clip(),endPath()];var background=drawRectangle({x,y,width,height,borderWidth:options.borderWidth,color:options.color,borderColor:options.borderColor,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)});var highlights=[];for(var idx4=0,len3=options.selectedLines.length;idx4<len3;idx4++){var line=options.textLines[options.selectedLines[idx4]];highlights.push.apply(highlights,drawRectangle({x:line.x-padding,y:line.y-(lineHeight-line.height)/2,width:width-borderWidth,height:line.height+(lineHeight-line.height)/2,borderWidth:0,color:options.selectedColor,borderColor:undefined,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)}))}var lines=drawTextLines(options.textLines,{color:options.textColor,font:options.font,size:options.fontSize,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)});var markedContent=__spreadArrays([beginMarkedContent("Tx"),pushGraphicsState()],lines,[popGraphicsState(),endMarkedContent()]);return __spreadArrays([pushGraphicsState()],background,highlights,clippingArea,markedContent,[popGraphicsState()])};var init_operations=__esm(()=>{init_tslib_es62();init_colors();init_operators();init_rotations();init_svgPath();init_objects2();KAPPA=4*((Math.sqrt(2)-1)/3)});var EncryptedPDFError,FontkitNotRegisteredError,ForeignPageError,RemovePageFromEmptyDocumentError,NoSuchFieldError,UnexpectedFieldTypeError,MissingOnValueCheckError,FieldAlreadyExistsError,InvalidFieldNamePartError,FieldExistsAsNonTerminalError,RichTextFieldReadError,CombedTextLayoutError,ExceededMaxLengthError,InvalidMaxLengthError;var init_errors3=__esm(()=>{init_tslib_es62();EncryptedPDFError=function(_super){__extends(EncryptedPDFError2,_super);function EncryptedPDFError2(){var _this=this;var msg="Input document to `PDFDocument.load` is encrypted. You can use `PDFDocument.load(..., { ignoreEncryption: true })` if you wish to load the document anyways.";_this=_super.call(this,msg)||this;return _this}return EncryptedPDFError2}(Error);FontkitNotRegisteredError=function(_super){__extends(FontkitNotRegisteredError2,_super);function FontkitNotRegisteredError2(){var _this=this;var msg="Input to `PDFDocument.embedFont` was a custom font, but no `fontkit` instance was found. You must register a `fontkit` instance with `PDFDocument.registerFontkit(...)` before embedding custom fonts.";_this=_super.call(this,msg)||this;return _this}return FontkitNotRegisteredError2}(Error);ForeignPageError=function(_super){__extends(ForeignPageError2,_super);function ForeignPageError2(){var _this=this;var msg="A `page` passed to `PDFDocument.addPage` or `PDFDocument.insertPage` was from a different (foreign) PDF document. If you want to copy pages from one PDFDocument to another, you must use `PDFDocument.copyPages(...)` to copy the pages before adding or inserting them.";_this=_super.call(this,msg)||this;return _this}return ForeignPageError2}(Error);RemovePageFromEmptyDocumentError=function(_super){__extends(RemovePageFromEmptyDocumentError2,_super);function RemovePageFromEmptyDocumentError2(){var _this=this;var msg="PDFDocument has no pages so `PDFDocument.removePage` cannot be called";_this=_super.call(this,msg)||this;return _this}return RemovePageFromEmptyDocumentError2}(Error);NoSuchFieldError=function(_super){__extends(NoSuchFieldError2,_super);function NoSuchFieldError2(name){var _this=this;var msg='PDFDocument has no form field with the name "'+name+'"';_this=_super.call(this,msg)||this;return _this}return NoSuchFieldError2}(Error);UnexpectedFieldTypeError=function(_super){__extends(UnexpectedFieldTypeError2,_super);function UnexpectedFieldTypeError2(name,expected,actual){var _a,_b;var _this=this;var expectedType=expected===null||expected===undefined?undefined:expected.name;var actualType=(_b=(_a=actual===null||actual===undefined?undefined:actual.constructor)===null||_a===undefined?undefined:_a.name)!==null&&_b!==undefined?_b:actual;var msg='Expected field "'+name+'" to be of type '+expectedType+", "+("but it is actually of type "+actualType);_this=_super.call(this,msg)||this;return _this}return UnexpectedFieldTypeError2}(Error);MissingOnValueCheckError=function(_super){__extends(MissingOnValueCheckError2,_super);function MissingOnValueCheckError2(onValue){var _this=this;var msg='Failed to select check box due to missing onValue: "'+onValue+'"';_this=_super.call(this,msg)||this;return _this}return MissingOnValueCheckError2}(Error);FieldAlreadyExistsError=function(_super){__extends(FieldAlreadyExistsError2,_super);function FieldAlreadyExistsError2(name){var _this=this;var msg='A field already exists with the specified name: "'+name+'"';_this=_super.call(this,msg)||this;return _this}return FieldAlreadyExistsError2}(Error);InvalidFieldNamePartError=function(_super){__extends(InvalidFieldNamePartError2,_super);function InvalidFieldNamePartError2(namePart){var _this=this;var msg='Field name contains invalid component: "'+namePart+'"';_this=_super.call(this,msg)||this;return _this}return InvalidFieldNamePartError2}(Error);FieldExistsAsNonTerminalError=function(_super){__extends(FieldExistsAsNonTerminalError2,_super);function FieldExistsAsNonTerminalError2(name){var _this=this;var msg='A non-terminal field already exists with the specified name: "'+name+'"';_this=_super.call(this,msg)||this;return _this}return FieldExistsAsNonTerminalError2}(Error);RichTextFieldReadError=function(_super){__extends(RichTextFieldReadError2,_super);function RichTextFieldReadError2(fieldName){var _this=this;var msg="Reading rich text fields is not supported: Attempted to read rich text field: "+fieldName;_this=_super.call(this,msg)||this;return _this}return RichTextFieldReadError2}(Error);CombedTextLayoutError=function(_super){__extends(CombedTextLayoutError2,_super);function CombedTextLayoutError2(lineLength,cellCount){var _this=this;var msg="Failed to layout combed text as lineLength="+lineLength+" is greater than cellCount="+cellCount;_this=_super.call(this,msg)||this;return _this}return CombedTextLayoutError2}(Error);ExceededMaxLengthError=function(_super){__extends(ExceededMaxLengthError2,_super);function ExceededMaxLengthError2(textLength,maxLength,name){var _this=this;var msg="Attempted to set text with length="+textLength+" for TextField with maxLength="+maxLength+" and name="+name;_this=_super.call(this,msg)||this;return _this}return ExceededMaxLengthError2}(Error);InvalidMaxLengthError=function(_super){__extends(InvalidMaxLengthError2,_super);function InvalidMaxLengthError2(textLength,maxLength,name){var _this=this;var msg="Attempted to set maxLength="+maxLength+", which is less than "+textLength+", the length of this field's current value (name="+name+")";_this=_super.call(this,msg)||this;return _this}return InvalidMaxLengthError2}(Error)});var TextAlignment;var init_alignment=__esm(()=>{(function(TextAlignment2){TextAlignment2[TextAlignment2["Left"]=0]="Left";TextAlignment2[TextAlignment2["Center"]=1]="Center";TextAlignment2[TextAlignment2["Right"]=2]="Right"})(TextAlignment||(TextAlignment={}))});var MIN_FONT_SIZE=4,MAX_FONT_SIZE=500,computeFontSize=function(lines,font,bounds,multiline){if(multiline===undefined){multiline=false}var fontSize=MIN_FONT_SIZE;while(fontSize<MAX_FONT_SIZE){var linesUsed=0;for(var lineIdx=0,lineLen=lines.length;lineIdx<lineLen;lineIdx++){linesUsed+=1;var line=lines[lineIdx];var words=line.split(" ");var spaceInLineRemaining=bounds.width;for(var idx4=0,len3=words.length;idx4<len3;idx4++){var isLastWord=idx4===len3-1;var word=isLastWord?words[idx4]:words[idx4]+" ";var widthOfWord=font.widthOfTextAtSize(word,fontSize);spaceInLineRemaining-=widthOfWord;if(spaceInLineRemaining<=0){linesUsed+=1;spaceInLineRemaining=bounds.width-widthOfWord}}}if(!multiline&&linesUsed>lines.length)return fontSize-1;var height=font.heightAtSize(fontSize);var lineHeight=height+height*0.2;var totalHeight=lineHeight*linesUsed;if(totalHeight>Math.abs(bounds.height))return fontSize-1;fontSize+=1}return fontSize},computeCombedFontSize=function(line,font,bounds,cellCount){var cellWidth=bounds.width/cellCount;var cellHeight=bounds.height;var fontSize=MIN_FONT_SIZE;var chars3=charSplit(line);while(fontSize<MAX_FONT_SIZE){for(var idx4=0,len3=chars3.length;idx4<len3;idx4++){var c=chars3[idx4];var tooLong=font.widthOfTextAtSize(c,fontSize)>cellWidth*0.75;if(tooLong)return fontSize-1}var height=font.heightAtSize(fontSize,{descender:false});if(height>cellHeight)return fontSize-1;fontSize+=1}return fontSize},lastIndexOfWhitespace=function(line){for(var idx4=line.length;idx4>0;idx4--){if(/\s/.test(line[idx4]))return idx4}return},splitOutLines=function(input,maxWidth,font,fontSize){var _a;var lastWhitespaceIdx=input.length;while(lastWhitespaceIdx>0){var line=input.substring(0,lastWhitespaceIdx);var encoded=font.encodeText(line);var width=font.widthOfTextAtSize(line,fontSize);if(width<maxWidth){var remainder=input.substring(lastWhitespaceIdx)||undefined;return{line,encoded,width,remainder}}lastWhitespaceIdx=(_a=lastIndexOfWhitespace(line))!==null&&_a!==undefined?_a:0}return{line:input,encoded:font.encodeText(input),width:font.widthOfTextAtSize(input,fontSize),remainder:undefined}},layoutMultilineText=function(text4,_a){var{alignment,fontSize,font,bounds}=_a;var lines=lineSplit(cleanText(text4));if(fontSize===undefined||fontSize===0){fontSize=computeFontSize(lines,font,bounds,true)}var height=font.heightAtSize(fontSize);var lineHeight=height+height*0.2;var textLines=[];var minX=bounds.x;var minY=bounds.y;var maxX=bounds.x+bounds.width;var maxY=bounds.y+bounds.height;var y=bounds.y+bounds.height;for(var idx4=0,len3=lines.length;idx4<len3;idx4++){var prevRemainder=lines[idx4];while(prevRemainder!==undefined){var _b=splitOutLines(prevRemainder,bounds.width,font,fontSize),line=_b.line,encoded=_b.encoded,width=_b.width,remainder=_b.remainder;var x=alignment===TextAlignment.Left?bounds.x:alignment===TextAlignment.Center?bounds.x+bounds.width/2-width/2:alignment===TextAlignment.Right?bounds.x+bounds.width-width:bounds.x;y-=lineHeight;if(x<minX)minX=x;if(y<minY)minY=y;if(x+width>maxX)maxX=x+width;if(y+height>maxY)maxY=y+height;textLines.push({text:line,encoded,width,height,x,y});prevRemainder=remainder===null||remainder===undefined?undefined:remainder.trim()}}return{fontSize,lineHeight,lines:textLines,bounds:{x:minX,y:minY,width:maxX-minX,height:maxY-minY}}},layoutCombedText=function(text4,_a){var{fontSize,font,bounds,cellCount}=_a;var line=mergeLines(cleanText(text4));if(line.length>cellCount){throw new CombedTextLayoutError(line.length,cellCount)}if(fontSize===undefined||fontSize===0){fontSize=computeCombedFontSize(line,font,bounds,cellCount)}var cellWidth=bounds.width/cellCount;var height=font.heightAtSize(fontSize,{descender:false});var y=bounds.y+(bounds.height/2-height/2);var cells=[];var minX=bounds.x;var minY=bounds.y;var maxX=bounds.x+bounds.width;var maxY=bounds.y+bounds.height;var cellOffset=0;var charOffset=0;while(cellOffset<cellCount){var _b=charAtIndex(line,charOffset),char=_b[0],charLength=_b[1];var encoded=font.encodeText(char);var width=font.widthOfTextAtSize(char,fontSize);var cellCenter=bounds.x+(cellWidth*cellOffset+cellWidth/2);var x=cellCenter-width/2;if(x<minX)minX=x;if(y<minY)minY=y;if(x+width>maxX)maxX=x+width;if(y+height>maxY)maxY=y+height;cells.push({text:line,encoded,width,height,x,y});cellOffset+=1;charOffset+=charLength}return{fontSize,cells,bounds:{x:minX,y:minY,width:maxX-minX,height:maxY-minY}}},layoutSinglelineText=function(text4,_a){var{alignment,fontSize,font,bounds}=_a;var line=mergeLines(cleanText(text4));if(fontSize===undefined||fontSize===0){fontSize=computeFontSize([line],font,bounds)}var encoded=font.encodeText(line);var width=font.widthOfTextAtSize(line,fontSize);var height=font.heightAtSize(fontSize,{descender:false});var x=alignment===TextAlignment.Left?bounds.x:alignment===TextAlignment.Center?bounds.x+bounds.width/2-width/2:alignment===TextAlignment.Right?bounds.x+bounds.width-width:bounds.x;var y=bounds.y+(bounds.height/2-height/2);return{fontSize,line:{text:line,encoded,width,height,x,y},bounds:{x,y,width,height}}};var init_layout=__esm(()=>{init_errors3();init_alignment();init_utils2()});var normalizeAppearance=function(appearance){if("normal"in appearance)return appearance;return{normal:appearance}},tfRegex2,getDefaultFontSize=function(field){var _a,_b;var da=(_a=field.getDefaultAppearance())!==null&&_a!==undefined?_a:"";var daMatch=(_b=findLastMatch(da,tfRegex2).match)!==null&&_b!==undefined?_b:[];var defaultFontSize=Number(daMatch[2]);return isFinite(defaultFontSize)?defaultFontSize:undefined},colorRegex,getDefaultColor=function(field){var _a;var da=(_a=field.getDefaultAppearance())!==null&&_a!==undefined?_a:"";var daMatch=findLastMatch(da,colorRegex).match;var _b=daMatch!==null&&daMatch!==undefined?daMatch:[],c1=_b[1],c2=_b[2],c3=_b[3],c4=_b[4],colorSpace=_b[5];if(colorSpace==="g"&&c1){return grayscale(Number(c1))}if(colorSpace==="rg"&&c1&&c2&&c3){return rgb(Number(c1),Number(c2),Number(c3))}if(colorSpace==="k"&&c1&&c2&&c3&&c4){return cmyk(Number(c1),Number(c2),Number(c3),Number(c4))}return},updateDefaultAppearance=function(field,color,font,fontSize){var _a;if(fontSize===undefined){fontSize=0}var da=[setFillingColor(color).toString(),setFontAndSize((_a=font===null||font===undefined?undefined:font.name)!==null&&_a!==undefined?_a:"dummy__noop",fontSize).toString()].join(`
|
|
71
|
+
end`},cmapHexFormat=function(){var values2=[];for(var _i=0;_i<arguments.length;_i++){values2[_i]=arguments[_i]}return"<"+values2.join("")+">"},cmapHexString=function(value){return toHexStringOfMinLength(value,4)},cmapCodePointFormat=function(codePoint){if(isWithinBMP(codePoint))return cmapHexString(codePoint);if(hasSurrogates(codePoint)){var hs=highSurrogate(codePoint);var ls=lowSurrogate(codePoint);return""+cmapHexString(hs)+cmapHexString(ls)}var hex=toHexString(codePoint);var msg="0x"+hex+" is not a valid UTF-8 or UTF-16 codepoint.";throw new Error(msg)};var init_CMap=__esm(()=>{init_utils2();init_unicode()});var makeFontFlags=function(options){var flags=0;var flipBit=function(bit){flags|=1<<bit-1};if(options.fixedPitch)flipBit(1);if(options.serif)flipBit(2);if(options.symbolic)flipBit(3);if(options.script)flipBit(4);if(options.nonsymbolic)flipBit(6);if(options.italic)flipBit(7);if(options.allCap)flipBit(17);if(options.smallCap)flipBit(18);if(options.forceBold)flipBit(19);return flags},deriveFontFlags=function(font){var familyClass=font["OS/2"]?font["OS/2"].sFamilyClass:0;var flags=makeFontFlags({fixedPitch:font.post.isFixedPitch,serif:1<=familyClass&&familyClass<=7,symbolic:true,script:familyClass===10,italic:font.head.macStyle.italic});return flags};var PDFString,PDFString_default;var init_PDFString=__esm(()=>{init_tslib_es62();init_PDFObject();init_CharCodes();init_utils2();init_errors2();PDFString=function(_super){__extends(PDFString2,_super);function PDFString2(value){var _this=_super.call(this)||this;_this.value=value;return _this}PDFString2.prototype.asBytes=function(){var bytes=[];var octal="";var escaped=false;var pushByte=function(byte2){if(byte2!==undefined)bytes.push(byte2);escaped=false};for(var idx3=0,len2=this.value.length;idx3<len2;idx3++){var char=this.value[idx3];var byte=toCharCode(char);var nextChar=this.value[idx3+1];if(!escaped){if(byte===CharCodes_default.BackSlash)escaped=true;else pushByte(byte)}else{if(byte===CharCodes_default.Newline)pushByte();else if(byte===CharCodes_default.CarriageReturn)pushByte();else if(byte===CharCodes_default.n)pushByte(CharCodes_default.Newline);else if(byte===CharCodes_default.r)pushByte(CharCodes_default.CarriageReturn);else if(byte===CharCodes_default.t)pushByte(CharCodes_default.Tab);else if(byte===CharCodes_default.b)pushByte(CharCodes_default.Backspace);else if(byte===CharCodes_default.f)pushByte(CharCodes_default.FormFeed);else if(byte===CharCodes_default.LeftParen)pushByte(CharCodes_default.LeftParen);else if(byte===CharCodes_default.RightParen)pushByte(CharCodes_default.RightParen);else if(byte===CharCodes_default.Backspace)pushByte(CharCodes_default.BackSlash);else if(byte>=CharCodes_default.Zero&&byte<=CharCodes_default.Seven){octal+=char;if(octal.length===3||!(nextChar>="0"&&nextChar<="7")){pushByte(parseInt(octal,8));octal=""}}else{pushByte(byte)}}}return new Uint8Array(bytes)};PDFString2.prototype.decodeText=function(){var bytes=this.asBytes();if(hasUtf16BOM(bytes))return utf16Decode(bytes);return pdfDocEncodingDecode(bytes)};PDFString2.prototype.decodeDate=function(){var text4=this.decodeText();var date2=parseDate(text4);if(!date2)throw new InvalidPDFDateStringError(text4);return date2};PDFString2.prototype.asString=function(){return this.value};PDFString2.prototype.clone=function(){return PDFString2.of(this.value)};PDFString2.prototype.toString=function(){return"("+this.value+")"};PDFString2.prototype.sizeInBytes=function(){return this.value.length+2};PDFString2.prototype.copyBytesInto=function(buffer,offset){buffer[offset++]=CharCodes_default.LeftParen;offset+=copyStringIntoBuffer(this.value,buffer,offset);buffer[offset++]=CharCodes_default.RightParen;return this.value.length+2};PDFString2.of=function(value){return new PDFString2(value)};PDFString2.fromDate=function(date2){var year=padStart(String(date2.getUTCFullYear()),4,"0");var month=padStart(String(date2.getUTCMonth()+1),2,"0");var day=padStart(String(date2.getUTCDate()),2,"0");var hours=padStart(String(date2.getUTCHours()),2,"0");var mins=padStart(String(date2.getUTCMinutes()),2,"0");var secs=padStart(String(date2.getUTCSeconds()),2,"0");return new PDFString2("D:"+year+month+day+hours+mins+secs+"Z")};return PDFString2}(PDFObject_default);PDFString_default=PDFString});var CustomFontEmbedder,CustomFontEmbedder_default;var init_CustomFontEmbedder=__esm(()=>{init_tslib_es62();init_CMap();init_PDFHexString();init_PDFString();init_utils2();CustomFontEmbedder=function(){function CustomFontEmbedder2(font,fontData,customName,fontFeatures){var _this=this;this.allGlyphsInFontSortedById=function(){var glyphs=new Array(_this.font.characterSet.length);for(var idx3=0,len2=glyphs.length;idx3<len2;idx3++){var codePoint=_this.font.characterSet[idx3];glyphs[idx3]=_this.font.glyphForCodePoint(codePoint)}return sortedUniq(glyphs.sort(byAscendingId),function(g){return g.id})};this.font=font;this.scale=1000/this.font.unitsPerEm;this.fontData=fontData;this.fontName=this.font.postscriptName||"Font";this.customName=customName;this.fontFeatures=fontFeatures;this.baseFontName="";this.glyphCache=Cache_default.populatedBy(this.allGlyphsInFontSortedById)}CustomFontEmbedder2.for=function(fontkit,fontData,customName,fontFeatures){return __awaiter(this,undefined,undefined,function(){var font;return __generator(this,function(_a){switch(_a.label){case 0:return[4,fontkit.create(fontData)];case 1:font=_a.sent();return[2,new CustomFontEmbedder2(font,fontData,customName,fontFeatures)]}})})};CustomFontEmbedder2.prototype.encodeText=function(text4){var glyphs=this.font.layout(text4,this.fontFeatures).glyphs;var hexCodes=new Array(glyphs.length);for(var idx3=0,len2=glyphs.length;idx3<len2;idx3++){hexCodes[idx3]=toHexStringOfMinLength(glyphs[idx3].id,4)}return PDFHexString_default.of(hexCodes.join(""))};CustomFontEmbedder2.prototype.widthOfTextAtSize=function(text4,size){var glyphs=this.font.layout(text4,this.fontFeatures).glyphs;var totalWidth=0;for(var idx3=0,len2=glyphs.length;idx3<len2;idx3++){totalWidth+=glyphs[idx3].advanceWidth*this.scale}var scale=size/1000;return totalWidth*scale};CustomFontEmbedder2.prototype.heightOfFontAtSize=function(size,options){if(options===undefined){options={}}var _a=options.descender,descender=_a===undefined?true:_a;var _b=this.font,ascent=_b.ascent,descent=_b.descent,bbox=_b.bbox;var yTop=(ascent||bbox.maxY)*this.scale;var yBottom=(descent||bbox.minY)*this.scale;var height=yTop-yBottom;if(!descender)height-=Math.abs(descent)||0;return height/1000*size};CustomFontEmbedder2.prototype.sizeOfFontAtHeight=function(height){var _a=this.font,ascent=_a.ascent,descent=_a.descent,bbox=_a.bbox;var yTop=(ascent||bbox.maxY)*this.scale;var yBottom=(descent||bbox.minY)*this.scale;return 1000*height/(yTop-yBottom)};CustomFontEmbedder2.prototype.embedIntoContext=function(context2,ref){this.baseFontName=this.customName||context2.addRandomSuffix(this.fontName);return this.embedFontDict(context2,ref)};CustomFontEmbedder2.prototype.embedFontDict=function(context2,ref){return __awaiter(this,undefined,undefined,function(){var cidFontDictRef,unicodeCMapRef,fontDict;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.embedCIDFontDict(context2)];case 1:cidFontDictRef=_a.sent();unicodeCMapRef=this.embedUnicodeCmap(context2);fontDict=context2.obj({Type:"Font",Subtype:"Type0",BaseFont:this.baseFontName,Encoding:"Identity-H",DescendantFonts:[cidFontDictRef],ToUnicode:unicodeCMapRef});if(ref){context2.assign(ref,fontDict);return[2,ref]}else{return[2,context2.register(fontDict)]}return[2]}})})};CustomFontEmbedder2.prototype.isCFF=function(){return this.font.cff};CustomFontEmbedder2.prototype.embedCIDFontDict=function(context2){return __awaiter(this,undefined,undefined,function(){var fontDescriptorRef,cidFontDict;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.embedFontDescriptor(context2)];case 1:fontDescriptorRef=_a.sent();cidFontDict=context2.obj({Type:"Font",Subtype:this.isCFF()?"CIDFontType0":"CIDFontType2",CIDToGIDMap:"Identity",BaseFont:this.baseFontName,CIDSystemInfo:{Registry:PDFString_default.of("Adobe"),Ordering:PDFString_default.of("Identity"),Supplement:0},FontDescriptor:fontDescriptorRef,W:this.computeWidths()});return[2,context2.register(cidFontDict)]}})})};CustomFontEmbedder2.prototype.embedFontDescriptor=function(context2){return __awaiter(this,undefined,undefined,function(){var fontStreamRef,scale,_a,italicAngle,ascent,descent,capHeight,xHeight,_b,minX,minY,maxX,maxY,fontDescriptor;var _c;return __generator(this,function(_d){switch(_d.label){case 0:return[4,this.embedFontStream(context2)];case 1:fontStreamRef=_d.sent();scale=this.scale;_a=this.font,italicAngle=_a.italicAngle,ascent=_a.ascent,descent=_a.descent,capHeight=_a.capHeight,xHeight=_a.xHeight;_b=this.font.bbox,minX=_b.minX,minY=_b.minY,maxX=_b.maxX,maxY=_b.maxY;fontDescriptor=context2.obj((_c={Type:"FontDescriptor",FontName:this.baseFontName,Flags:deriveFontFlags(this.font),FontBBox:[minX*scale,minY*scale,maxX*scale,maxY*scale],ItalicAngle:italicAngle,Ascent:ascent*scale,Descent:descent*scale,CapHeight:(capHeight||ascent)*scale,XHeight:(xHeight||0)*scale,StemV:0},_c[this.isCFF()?"FontFile3":"FontFile2"]=fontStreamRef,_c));return[2,context2.register(fontDescriptor)]}})})};CustomFontEmbedder2.prototype.serializeFont=function(){return __awaiter(this,undefined,undefined,function(){return __generator(this,function(_a){return[2,this.fontData]})})};CustomFontEmbedder2.prototype.embedFontStream=function(context2){return __awaiter(this,undefined,undefined,function(){var fontStream,_a,_b;return __generator(this,function(_c){switch(_c.label){case 0:_b=(_a=context2).flateStream;return[4,this.serializeFont()];case 1:fontStream=_b.apply(_a,[_c.sent(),{Subtype:this.isCFF()?"CIDFontType0C":undefined}]);return[2,context2.register(fontStream)]}})})};CustomFontEmbedder2.prototype.embedUnicodeCmap=function(context2){var cmap=createCmap(this.glyphCache.access(),this.glyphId.bind(this));var cmapStream=context2.flateStream(cmap);return context2.register(cmapStream)};CustomFontEmbedder2.prototype.glyphId=function(glyph){return glyph?glyph.id:-1};CustomFontEmbedder2.prototype.computeWidths=function(){var glyphs=this.glyphCache.access();var widths=[];var currSection=[];for(var idx3=0,len2=glyphs.length;idx3<len2;idx3++){var currGlyph=glyphs[idx3];var prevGlyph=glyphs[idx3-1];var currGlyphId=this.glyphId(currGlyph);var prevGlyphId=this.glyphId(prevGlyph);if(idx3===0){widths.push(currGlyphId)}else if(currGlyphId-prevGlyphId!==1){widths.push(currSection);widths.push(currGlyphId);currSection=[]}currSection.push(currGlyph.advanceWidth*this.scale)}widths.push(currSection);return widths};return CustomFontEmbedder2}();CustomFontEmbedder_default=CustomFontEmbedder});var CustomFontSubsetEmbedder,CustomFontSubsetEmbedder_default;var init_CustomFontSubsetEmbedder=__esm(()=>{init_tslib_es62();init_CustomFontEmbedder();init_PDFHexString();init_utils2();CustomFontSubsetEmbedder=function(_super){__extends(CustomFontSubsetEmbedder2,_super);function CustomFontSubsetEmbedder2(font,fontData,customFontName,fontFeatures){var _this=_super.call(this,font,fontData,customFontName,fontFeatures)||this;_this.subset=_this.font.createSubset();_this.glyphs=[];_this.glyphCache=Cache_default.populatedBy(function(){return _this.glyphs});_this.glyphIdMap=new Map;return _this}CustomFontSubsetEmbedder2.for=function(fontkit,fontData,customFontName,fontFeatures){return __awaiter(this,undefined,undefined,function(){var font;return __generator(this,function(_a){switch(_a.label){case 0:return[4,fontkit.create(fontData)];case 1:font=_a.sent();return[2,new CustomFontSubsetEmbedder2(font,fontData,customFontName,fontFeatures)]}})})};CustomFontSubsetEmbedder2.prototype.encodeText=function(text4){var glyphs=this.font.layout(text4,this.fontFeatures).glyphs;var hexCodes=new Array(glyphs.length);for(var idx3=0,len2=glyphs.length;idx3<len2;idx3++){var glyph=glyphs[idx3];var subsetGlyphId=this.subset.includeGlyph(glyph);this.glyphs[subsetGlyphId-1]=glyph;this.glyphIdMap.set(glyph.id,subsetGlyphId);hexCodes[idx3]=toHexStringOfMinLength(subsetGlyphId,4)}this.glyphCache.invalidate();return PDFHexString_default.of(hexCodes.join(""))};CustomFontSubsetEmbedder2.prototype.isCFF=function(){return this.subset.cff};CustomFontSubsetEmbedder2.prototype.glyphId=function(glyph){return glyph?this.glyphIdMap.get(glyph.id):-1};CustomFontSubsetEmbedder2.prototype.serializeFont=function(){var _this=this;return new Promise(function(resolve,reject){var parts=[];_this.subset.encodeStream().on("data",function(bytes){return parts.push(bytes)}).on("end",function(){return resolve(mergeUint8Arrays(parts))}).on("error",function(err){return reject(err)})})};return CustomFontSubsetEmbedder2}(CustomFontEmbedder_default);CustomFontSubsetEmbedder_default=CustomFontSubsetEmbedder});var AFRelationship,FileEmbedder,FileEmbedder_default;var init_FileEmbedder=__esm(()=>{init_tslib_es62();init_PDFString();init_PDFHexString();(function(AFRelationship2){AFRelationship2["Source"]="Source";AFRelationship2["Data"]="Data";AFRelationship2["Alternative"]="Alternative";AFRelationship2["Supplement"]="Supplement";AFRelationship2["EncryptedPayload"]="EncryptedPayload";AFRelationship2["FormData"]="EncryptedPayload";AFRelationship2["Schema"]="Schema";AFRelationship2["Unspecified"]="Unspecified"})(AFRelationship||(AFRelationship={}));FileEmbedder=function(){function FileEmbedder2(fileData,fileName,options){if(options===undefined){options={}}this.fileData=fileData;this.fileName=fileName;this.options=options}FileEmbedder2.for=function(bytes,fileName,options){if(options===undefined){options={}}return new FileEmbedder2(bytes,fileName,options)};FileEmbedder2.prototype.embedIntoContext=function(context2,ref){return __awaiter(this,undefined,undefined,function(){var _a,mimeType,description,creationDate,modificationDate,afRelationship,embeddedFileStream,embeddedFileStreamRef,fileSpecDict;return __generator(this,function(_b){_a=this.options,mimeType=_a.mimeType,description=_a.description,creationDate=_a.creationDate,modificationDate=_a.modificationDate,afRelationship=_a.afRelationship;embeddedFileStream=context2.flateStream(this.fileData,{Type:"EmbeddedFile",Subtype:mimeType!==null&&mimeType!==undefined?mimeType:undefined,Params:{Size:this.fileData.length,CreationDate:creationDate?PDFString_default.fromDate(creationDate):undefined,ModDate:modificationDate?PDFString_default.fromDate(modificationDate):undefined}});embeddedFileStreamRef=context2.register(embeddedFileStream);fileSpecDict=context2.obj({Type:"Filespec",F:PDFString_default.of(this.fileName),UF:PDFHexString_default.fromText(this.fileName),EF:{F:embeddedFileStreamRef},Desc:description?PDFHexString_default.fromText(description):undefined,AFRelationship:afRelationship!==null&&afRelationship!==undefined?afRelationship:undefined});if(ref){context2.assign(ref,fileSpecDict);return[2,ref]}else{return[2,context2.register(fileSpecDict)]}return[2]})})};return FileEmbedder2}();FileEmbedder_default=FileEmbedder});var MARKERS,ColorSpace,ChannelToColorSpace,JpegEmbedder,JpegEmbedder_default;var init_JpegEmbedder=__esm(()=>{init_tslib_es62();MARKERS=[65472,65473,65474,65475,65477,65478,65479,65480,65481,65482,65483,65484,65485,65486,65487];(function(ColorSpace2){ColorSpace2["DeviceGray"]="DeviceGray";ColorSpace2["DeviceRGB"]="DeviceRGB";ColorSpace2["DeviceCMYK"]="DeviceCMYK"})(ColorSpace||(ColorSpace={}));ChannelToColorSpace={1:ColorSpace.DeviceGray,3:ColorSpace.DeviceRGB,4:ColorSpace.DeviceCMYK};JpegEmbedder=function(){function JpegEmbedder2(imageData,bitsPerComponent,width,height,colorSpace){this.imageData=imageData;this.bitsPerComponent=bitsPerComponent;this.width=width;this.height=height;this.colorSpace=colorSpace}JpegEmbedder2.for=function(imageData){return __awaiter(this,undefined,undefined,function(){var dataView,soi,pos,marker,bitsPerComponent,height,width,channelByte,channelName,colorSpace;return __generator(this,function(_a){dataView=new DataView(imageData.buffer);soi=dataView.getUint16(0);if(soi!==65496)throw new Error("SOI not found in JPEG");pos=2;while(pos<dataView.byteLength){marker=dataView.getUint16(pos);pos+=2;if(MARKERS.includes(marker))break;pos+=dataView.getUint16(pos)}if(!MARKERS.includes(marker))throw new Error("Invalid JPEG");pos+=2;bitsPerComponent=dataView.getUint8(pos++);height=dataView.getUint16(pos);pos+=2;width=dataView.getUint16(pos);pos+=2;channelByte=dataView.getUint8(pos++);channelName=ChannelToColorSpace[channelByte];if(!channelName)throw new Error("Unknown JPEG channel.");colorSpace=channelName;return[2,new JpegEmbedder2(imageData,bitsPerComponent,width,height,colorSpace)]})})};JpegEmbedder2.prototype.embedIntoContext=function(context2,ref){return __awaiter(this,undefined,undefined,function(){var xObject;return __generator(this,function(_a){xObject=context2.stream(this.imageData,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.bitsPerComponent,Width:this.width,Height:this.height,ColorSpace:this.colorSpace,Filter:"DCTDecode",Decode:this.colorSpace===ColorSpace.DeviceCMYK?[1,0,1,0,1,0,1,0]:undefined});if(ref){context2.assign(ref,xObject);return[2,ref]}else{return[2,context2.register(xObject)]}return[2]})})};return JpegEmbedder2}();JpegEmbedder_default=JpegEmbedder});var import_pako4,UPNG,UPNG_default;var init_UPNG=__esm(()=>{import_pako4=__toESM(require_pako(),1);UPNG={};UPNG.toRGBA8=function(out){var{width:w,height:h}=out;if(out.tabs.acTL==null)return[UPNG.toRGBA8.decodeImage(out.data,w,h,out).buffer];var frms=[];if(out.frames[0].data==null)out.frames[0].data=out.data;var len2=w*h*4,img=new Uint8Array(len2),empty2=new Uint8Array(len2),prev=new Uint8Array(len2);for(var i3=0;i3<out.frames.length;i3++){var frm=out.frames[i3];var fx=frm.rect.x,fy=frm.rect.y,fw=frm.rect.width,fh=frm.rect.height;var fdata=UPNG.toRGBA8.decodeImage(frm.data,fw,fh,out);if(i3!=0)for(var j=0;j<len2;j++)prev[j]=img[j];if(frm.blend==0)UPNG._copyTile(fdata,fw,fh,img,w,h,fx,fy,0);else if(frm.blend==1)UPNG._copyTile(fdata,fw,fh,img,w,h,fx,fy,1);frms.push(img.buffer.slice(0));if(frm.dispose==0){}else if(frm.dispose==1)UPNG._copyTile(empty2,fw,fh,img,w,h,fx,fy,0);else if(frm.dispose==2)for(var j=0;j<len2;j++)img[j]=prev[j]}return frms};UPNG.toRGBA8.decodeImage=function(data2,w,h,out){var area=w*h,bpp=UPNG.decode._getBPP(out);var bpl=Math.ceil(w*bpp/8);var bf=new Uint8Array(area*4),bf32=new Uint32Array(bf.buffer);var{ctype,depth}=out;var rs=UPNG._bin.readUshort;var time=Date.now();if(ctype==6){var qarea=area<<2;if(depth==8)for(var i3=0;i3<qarea;i3+=4){bf[i3]=data2[i3];bf[i3+1]=data2[i3+1];bf[i3+2]=data2[i3+2];bf[i3+3]=data2[i3+3]}if(depth==16)for(var i3=0;i3<qarea;i3++){bf[i3]=data2[i3<<1]}}else if(ctype==2){var ts=out.tabs["tRNS"];if(ts==null){if(depth==8)for(var i3=0;i3<area;i3++){var ti=i3*3;bf32[i3]=255<<24|data2[ti+2]<<16|data2[ti+1]<<8|data2[ti]}if(depth==16)for(var i3=0;i3<area;i3++){var ti=i3*6;bf32[i3]=255<<24|data2[ti+4]<<16|data2[ti+2]<<8|data2[ti]}}else{var tr=ts[0],tg=ts[1],tb=ts[2];if(depth==8)for(var i3=0;i3<area;i3++){var qi=i3<<2,ti=i3*3;bf32[i3]=255<<24|data2[ti+2]<<16|data2[ti+1]<<8|data2[ti];if(data2[ti]==tr&&data2[ti+1]==tg&&data2[ti+2]==tb)bf[qi+3]=0}if(depth==16)for(var i3=0;i3<area;i3++){var qi=i3<<2,ti=i3*6;bf32[i3]=255<<24|data2[ti+4]<<16|data2[ti+2]<<8|data2[ti];if(rs(data2,ti)==tr&&rs(data2,ti+2)==tg&&rs(data2,ti+4)==tb)bf[qi+3]=0}}}else if(ctype==3){var p=out.tabs["PLTE"],ap=out.tabs["tRNS"],tl=ap?ap.length:0;if(depth==1)for(var y=0;y<h;y++){var s0=y*bpl,t0=y*w;for(var i3=0;i3<w;i3++){var qi=t0+i3<<2,j=data2[s0+(i3>>3)]>>7-((i3&7)<<0)&1,cj=3*j;bf[qi]=p[cj];bf[qi+1]=p[cj+1];bf[qi+2]=p[cj+2];bf[qi+3]=j<tl?ap[j]:255}}if(depth==2)for(var y=0;y<h;y++){var s0=y*bpl,t0=y*w;for(var i3=0;i3<w;i3++){var qi=t0+i3<<2,j=data2[s0+(i3>>2)]>>6-((i3&3)<<1)&3,cj=3*j;bf[qi]=p[cj];bf[qi+1]=p[cj+1];bf[qi+2]=p[cj+2];bf[qi+3]=j<tl?ap[j]:255}}if(depth==4)for(var y=0;y<h;y++){var s0=y*bpl,t0=y*w;for(var i3=0;i3<w;i3++){var qi=t0+i3<<2,j=data2[s0+(i3>>1)]>>4-((i3&1)<<2)&15,cj=3*j;bf[qi]=p[cj];bf[qi+1]=p[cj+1];bf[qi+2]=p[cj+2];bf[qi+3]=j<tl?ap[j]:255}}if(depth==8)for(var i3=0;i3<area;i3++){var qi=i3<<2,j=data2[i3],cj=3*j;bf[qi]=p[cj];bf[qi+1]=p[cj+1];bf[qi+2]=p[cj+2];bf[qi+3]=j<tl?ap[j]:255}}else if(ctype==4){if(depth==8)for(var i3=0;i3<area;i3++){var qi=i3<<2,di=i3<<1,gr=data2[di];bf[qi]=gr;bf[qi+1]=gr;bf[qi+2]=gr;bf[qi+3]=data2[di+1]}if(depth==16)for(var i3=0;i3<area;i3++){var qi=i3<<2,di=i3<<2,gr=data2[di];bf[qi]=gr;bf[qi+1]=gr;bf[qi+2]=gr;bf[qi+3]=data2[di+2]}}else if(ctype==0){var tr=out.tabs["tRNS"]?out.tabs["tRNS"]:-1;for(var y=0;y<h;y++){var off=y*bpl,to=y*w;if(depth==1)for(var x=0;x<w;x++){var gr=255*(data2[off+(x>>>3)]>>>7-(x&7)&1),al=gr==tr*255?0:255;bf32[to+x]=al<<24|gr<<16|gr<<8|gr}else if(depth==2)for(var x=0;x<w;x++){var gr=85*(data2[off+(x>>>2)]>>>6-((x&3)<<1)&3),al=gr==tr*85?0:255;bf32[to+x]=al<<24|gr<<16|gr<<8|gr}else if(depth==4)for(var x=0;x<w;x++){var gr=17*(data2[off+(x>>>1)]>>>4-((x&1)<<2)&15),al=gr==tr*17?0:255;bf32[to+x]=al<<24|gr<<16|gr<<8|gr}else if(depth==8)for(var x=0;x<w;x++){var gr=data2[off+x],al=gr==tr?0:255;bf32[to+x]=al<<24|gr<<16|gr<<8|gr}else if(depth==16)for(var x=0;x<w;x++){var gr=data2[off+(x<<1)],al=rs(data2,off+(x<<i3))==tr?0:255;bf32[to+x]=al<<24|gr<<16|gr<<8|gr}}}return bf};UPNG.decode=function(buff){var data2=new Uint8Array(buff),offset=8,bin=UPNG._bin,rUs=bin.readUshort,rUi=bin.readUint;var out={tabs:{},frames:[]};var dd=new Uint8Array(data2.length),doff=0;var fd,foff=0;var mgck=[137,80,78,71,13,10,26,10];for(var i3=0;i3<8;i3++)if(data2[i3]!=mgck[i3])throw"The input is not a PNG file!";while(offset<data2.length){var len2=bin.readUint(data2,offset);offset+=4;var type=bin.readASCII(data2,offset,4);offset+=4;if(type=="IHDR"){UPNG.decode._IHDR(data2,offset,out)}else if(type=="IDAT"){for(var i3=0;i3<len2;i3++)dd[doff+i3]=data2[offset+i3];doff+=len2}else if(type=="acTL"){out.tabs[type]={num_frames:rUi(data2,offset),num_plays:rUi(data2,offset+4)};fd=new Uint8Array(data2.length)}else if(type=="fcTL"){if(foff!=0){var fr=out.frames[out.frames.length-1];fr.data=UPNG.decode._decompress(out,fd.slice(0,foff),fr.rect.width,fr.rect.height);foff=0}var rct={x:rUi(data2,offset+12),y:rUi(data2,offset+16),width:rUi(data2,offset+4),height:rUi(data2,offset+8)};var del=rUs(data2,offset+22);del=rUs(data2,offset+20)/(del==0?100:del);var frm={rect:rct,delay:Math.round(del*1000),dispose:data2[offset+24],blend:data2[offset+25]};out.frames.push(frm)}else if(type=="fdAT"){for(var i3=0;i3<len2-4;i3++)fd[foff+i3]=data2[offset+i3+4];foff+=len2-4}else if(type=="pHYs"){out.tabs[type]=[bin.readUint(data2,offset),bin.readUint(data2,offset+4),data2[offset+8]]}else if(type=="cHRM"){out.tabs[type]=[];for(var i3=0;i3<8;i3++)out.tabs[type].push(bin.readUint(data2,offset+i3*4))}else if(type=="tEXt"){if(out.tabs[type]==null)out.tabs[type]={};var nz=bin.nextZero(data2,offset);var keyw=bin.readASCII(data2,offset,nz-offset);var text4=bin.readASCII(data2,nz+1,offset+len2-nz-1);out.tabs[type][keyw]=text4}else if(type=="iTXt"){if(out.tabs[type]==null)out.tabs[type]={};var nz=0,off=offset;nz=bin.nextZero(data2,off);var keyw=bin.readASCII(data2,off,nz-off);off=nz+1;var cflag=data2[off],cmeth=data2[off+1];off+=2;nz=bin.nextZero(data2,off);var ltag=bin.readASCII(data2,off,nz-off);off=nz+1;nz=bin.nextZero(data2,off);var tkeyw=bin.readUTF8(data2,off,nz-off);off=nz+1;var text4=bin.readUTF8(data2,off,len2-(off-offset));out.tabs[type][keyw]=text4}else if(type=="PLTE"){out.tabs[type]=bin.readBytes(data2,offset,len2)}else if(type=="hIST"){var pl=out.tabs["PLTE"].length/3;out.tabs[type]=[];for(var i3=0;i3<pl;i3++)out.tabs[type].push(rUs(data2,offset+i3*2))}else if(type=="tRNS"){if(out.ctype==3)out.tabs[type]=bin.readBytes(data2,offset,len2);else if(out.ctype==0)out.tabs[type]=rUs(data2,offset);else if(out.ctype==2)out.tabs[type]=[rUs(data2,offset),rUs(data2,offset+2),rUs(data2,offset+4)]}else if(type=="gAMA")out.tabs[type]=bin.readUint(data2,offset)/1e5;else if(type=="sRGB")out.tabs[type]=data2[offset];else if(type=="bKGD"){if(out.ctype==0||out.ctype==4)out.tabs[type]=[rUs(data2,offset)];else if(out.ctype==2||out.ctype==6)out.tabs[type]=[rUs(data2,offset),rUs(data2,offset+2),rUs(data2,offset+4)];else if(out.ctype==3)out.tabs[type]=data2[offset]}else if(type=="IEND"){break}offset+=len2;var crc=bin.readUint(data2,offset);offset+=4}if(foff!=0){var fr=out.frames[out.frames.length-1];fr.data=UPNG.decode._decompress(out,fd.slice(0,foff),fr.rect.width,fr.rect.height);foff=0}out.data=UPNG.decode._decompress(out,dd,out.width,out.height);delete out.compress;delete out.interlace;delete out.filter;return out};UPNG.decode._decompress=function(out,dd,w,h){var time=Date.now();var bpp=UPNG.decode._getBPP(out),bpl=Math.ceil(w*bpp/8),buff=new Uint8Array((bpl+1+out.interlace)*h);dd=UPNG.decode._inflate(dd,buff);var time=Date.now();if(out.interlace==0)dd=UPNG.decode._filterZero(dd,out,0,w,h);else if(out.interlace==1)dd=UPNG.decode._readInterlace(dd,out);return dd};UPNG.decode._inflate=function(data2,buff){var out=UPNG["inflateRaw"](new Uint8Array(data2.buffer,2,data2.length-6),buff);return out};UPNG.inflateRaw=function(){var H={};H.H={};H.H.N=function(N,W){var R=Uint8Array,i3=0,m=0,J=0,h=0,Q=0,X=0,u=0,w=0,d=0,v,C;if(N[0]==3&&N[1]==0)return W?W:new R(0);var V=H.H,n=V.b,A=V.e,l=V.R,M=V.n,I=V.A,e=V.Z,b=V.m,Z=W==null;if(Z)W=new R(N.length>>>2<<3);while(i3==0){i3=n(N,d,1);m=n(N,d+1,2);d+=3;if(m==0){if((d&7)!=0)d+=8-(d&7);var D=(d>>>3)+4,q=N[D-4]|N[D-3]<<8;if(Z)W=H.H.W(W,w+q);W.set(new R(N.buffer,N.byteOffset+D,q),w);d=D+q<<3;w+=q;continue}if(Z)W=H.H.W(W,w+(1<<17));if(m==1){v=b.J;C=b.h;X=(1<<9)-1;u=(1<<5)-1}if(m==2){J=A(N,d,5)+257;h=A(N,d+5,5)+1;Q=A(N,d+10,4)+4;d+=14;var E=d,j=1;for(var c=0;c<38;c+=2){b.Q[c]=0;b.Q[c+1]=0}for(var c=0;c<Q;c++){var K=A(N,d+c*3,3);b.Q[(b.X[c]<<1)+1]=K;if(K>j)j=K}d+=3*Q;M(b.Q,j);I(b.Q,j,b.u);v=b.w;C=b.d;d=l(b.u,(1<<j)-1,J+h,N,d,b.v);var r=V.V(b.v,0,J,b.C);X=(1<<r)-1;var S=V.V(b.v,J,h,b.D);u=(1<<S)-1;M(b.C,r);I(b.C,r,v);M(b.D,S);I(b.D,S,C)}while(true){var T=v[e(N,d)&X];d+=T&15;var p=T>>>4;if(p>>>8==0){W[w++]=p}else if(p==256){break}else{var z=w+p-254;if(p>264){var _=b.q[p-257];z=w+(_>>>3)+A(N,d,_&7);d+=_&7}var $=C[e(N,d)&u];d+=$&15;var s=$>>>4,Y=b.c[s],a=(Y>>>4)+n(N,d,Y&15);d+=Y&15;while(w<z){W[w]=W[w++-a];W[w]=W[w++-a];W[w]=W[w++-a];W[w]=W[w++-a]}w=z}}}return W.length==w?W:W.slice(0,w)};H.H.W=function(N,W){var R=N.length;if(W<=R)return N;var V=new Uint8Array(R<<1);V.set(N,0);return V};H.H.R=function(N,W,R,V,n,A){var l=H.H.e,M=H.H.Z,I=0;while(I<R){var e=N[M(V,n)&W];n+=e&15;var b=e>>>4;if(b<=15){A[I]=b;I++}else{var Z=0,m=0;if(b==16){m=3+l(V,n,2);n+=2;Z=A[I-1]}else if(b==17){m=3+l(V,n,3);n+=3}else if(b==18){m=11+l(V,n,7);n+=7}var J=I+m;while(I<J){A[I]=Z;I++}}}return n};H.H.V=function(N,W,R,V){var n=0,A=0,l=V.length>>>1;while(A<R){var M=N[A+W];V[A<<1]=0;V[(A<<1)+1]=M;if(M>n)n=M;A++}while(A<l){V[A<<1]=0;V[(A<<1)+1]=0;A++}return n};H.H.n=function(N,W){var R=H.H.m,V=N.length,n,A,l,M,I,e=R.j;for(var M=0;M<=W;M++)e[M]=0;for(M=1;M<V;M+=2)e[N[M]]++;var b=R.K;n=0;e[0]=0;for(A=1;A<=W;A++){n=n+e[A-1]<<1;b[A]=n}for(l=0;l<V;l+=2){I=N[l+1];if(I!=0){N[l]=b[I];b[I]++}}};H.H.A=function(N,W,R){var V=N.length,n=H.H.m,A=n.r;for(var l=0;l<V;l+=2)if(N[l+1]!=0){var M=l>>1,I=N[l+1],e=M<<4|I,b=W-I,Z=N[l]<<b,m=Z+(1<<b);while(Z!=m){var J=A[Z]>>>15-W;R[J]=e;Z++}}};H.H.l=function(N,W){var R=H.H.m.r,V=15-W;for(var n=0;n<N.length;n+=2){var A=N[n]<<W-N[n+1];N[n]=R[A]>>>V}};H.H.M=function(N,W,R){R=R<<(W&7);var V=W>>>3;N[V]|=R;N[V+1]|=R>>>8};H.H.I=function(N,W,R){R=R<<(W&7);var V=W>>>3;N[V]|=R;N[V+1]|=R>>>8;N[V+2]|=R>>>16};H.H.e=function(N,W,R){return(N[W>>>3]|N[(W>>>3)+1]<<8)>>>(W&7)&(1<<R)-1};H.H.b=function(N,W,R){return(N[W>>>3]|N[(W>>>3)+1]<<8|N[(W>>>3)+2]<<16)>>>(W&7)&(1<<R)-1};H.H.Z=function(N,W){return(N[W>>>3]|N[(W>>>3)+1]<<8|N[(W>>>3)+2]<<16)>>>(W&7)};H.H.i=function(N,W){return(N[W>>>3]|N[(W>>>3)+1]<<8|N[(W>>>3)+2]<<16|N[(W>>>3)+3]<<24)>>>(W&7)};H.H.m=function(){var N=Uint16Array,W=Uint32Array;return{K:new N(16),j:new N(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new N(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new W(32),J:new N(512),_:[],h:new N(32),$:[],w:new N(32768),C:[],v:[],d:new N(32768),D:[],u:new N(512),Q:[],r:new N(1<<15),s:new W(286),Y:new W(30),a:new W(19),t:new W(15000),k:new N(1<<16),g:new N(1<<15)}}();(function(){var N=H.H.m,W=1<<15;for(var R=0;R<W;R++){var V=R;V=(V&2863311530)>>>1|(V&1431655765)<<1;V=(V&3435973836)>>>2|(V&858993459)<<2;V=(V&4042322160)>>>4|(V&252645135)<<4;V=(V&4278255360)>>>8|(V&16711935)<<8;N.r[R]=(V>>>16|V<<16)>>>17}function n(A,l,M){while(l--!=0)A.push(0,M)}for(var R=0;R<32;R++){N.q[R]=N.S[R]<<3|N.T[R];N.c[R]=N.p[R]<<4|N.z[R]}n(N._,144,8);n(N._,255-143,9);n(N._,279-255,7);n(N._,287-279,8);H.H.n(N._,9);H.H.A(N._,9,N.J);H.H.l(N._,9);n(N.$,32,5);H.H.n(N.$,5);H.H.A(N.$,5,N.h);H.H.l(N.$,5);n(N.Q,19,0);n(N.C,286,0);n(N.D,30,0);n(N.v,320,0)})();return H.H.N}();UPNG.decode._readInterlace=function(data2,out){var{width:w,height:h}=out;var bpp=UPNG.decode._getBPP(out),cbpp=bpp>>3,bpl=Math.ceil(w*bpp/8);var img=new Uint8Array(h*bpl);var di=0;var starting_row=[0,0,4,0,2,0,1];var starting_col=[0,4,0,2,0,1,0];var row_increment=[8,8,8,4,4,2,2];var col_increment=[8,8,4,4,2,2,1];var pass=0;while(pass<7){var ri=row_increment[pass],ci=col_increment[pass];var sw=0,sh=0;var cr=starting_row[pass];while(cr<h){cr+=ri;sh++}var cc=starting_col[pass];while(cc<w){cc+=ci;sw++}var bpll=Math.ceil(sw*bpp/8);UPNG.decode._filterZero(data2,out,di,sw,sh);var y=0,row=starting_row[pass];while(row<h){var col=starting_col[pass];var cdi=di+y*bpll<<3;while(col<w){if(bpp==1){var val=data2[cdi>>3];val=val>>7-(cdi&7)&1;img[row*bpl+(col>>3)]|=val<<7-((col&7)<<0)}if(bpp==2){var val=data2[cdi>>3];val=val>>6-(cdi&7)&3;img[row*bpl+(col>>2)]|=val<<6-((col&3)<<1)}if(bpp==4){var val=data2[cdi>>3];val=val>>4-(cdi&7)&15;img[row*bpl+(col>>1)]|=val<<4-((col&1)<<2)}if(bpp>=8){var ii=row*bpl+col*cbpp;for(var j=0;j<cbpp;j++)img[ii+j]=data2[(cdi>>3)+j]}cdi+=bpp;col+=ci}y++;row+=ri}if(sw*sh!=0)di+=sh*(1+bpll);pass=pass+1}return img};UPNG.decode._getBPP=function(out){var noc=[1,null,3,1,2,null,4][out.ctype];return noc*out.depth};UPNG.decode._filterZero=function(data2,out,off,w,h){var bpp=UPNG.decode._getBPP(out),bpl=Math.ceil(w*bpp/8),paeth=UPNG.decode._paeth;bpp=Math.ceil(bpp/8);var i3=0,di=1,type=data2[off],x=0;if(type>1)data2[off]=[0,0,1][type-2];if(type==3)for(x=bpp;x<bpl;x++)data2[x+1]=data2[x+1]+(data2[x+1-bpp]>>>1)&255;for(var y=0;y<h;y++){i3=off+y*bpl;di=i3+y+1;type=data2[di-1];x=0;if(type==0)for(;x<bpl;x++)data2[i3+x]=data2[di+x];else if(type==1){for(;x<bpp;x++)data2[i3+x]=data2[di+x];for(;x<bpl;x++)data2[i3+x]=data2[di+x]+data2[i3+x-bpp]}else if(type==2){for(;x<bpl;x++)data2[i3+x]=data2[di+x]+data2[i3+x-bpl]}else if(type==3){for(;x<bpp;x++)data2[i3+x]=data2[di+x]+(data2[i3+x-bpl]>>>1);for(;x<bpl;x++)data2[i3+x]=data2[di+x]+(data2[i3+x-bpl]+data2[i3+x-bpp]>>>1)}else{for(;x<bpp;x++)data2[i3+x]=data2[di+x]+paeth(0,data2[i3+x-bpl],0);for(;x<bpl;x++)data2[i3+x]=data2[di+x]+paeth(data2[i3+x-bpp],data2[i3+x-bpl],data2[i3+x-bpp-bpl])}}return data2};UPNG.decode._paeth=function(a,b,c){var p=a+b-c,pa=p-a,pb=p-b,pc=p-c;if(pa*pa<=pb*pb&&pa*pa<=pc*pc)return a;else if(pb*pb<=pc*pc)return b;return c};UPNG.decode._IHDR=function(data2,offset,out){var bin=UPNG._bin;out.width=bin.readUint(data2,offset);offset+=4;out.height=bin.readUint(data2,offset);offset+=4;out.depth=data2[offset];offset++;out.ctype=data2[offset];offset++;out.compress=data2[offset];offset++;out.filter=data2[offset];offset++;out.interlace=data2[offset];offset++};UPNG._bin={nextZero:function(data2,p){while(data2[p]!=0)p++;return p},readUshort:function(buff,p){return buff[p]<<8|buff[p+1]},writeUshort:function(buff,p,n){buff[p]=n>>8&255;buff[p+1]=n&255},readUint:function(buff,p){return buff[p]*(256*256*256)+(buff[p+1]<<16|buff[p+2]<<8|buff[p+3])},writeUint:function(buff,p,n){buff[p]=n>>24&255;buff[p+1]=n>>16&255;buff[p+2]=n>>8&255;buff[p+3]=n&255},readASCII:function(buff,p,l){var s="";for(var i3=0;i3<l;i3++)s+=String.fromCharCode(buff[p+i3]);return s},writeASCII:function(data2,p,s){for(var i3=0;i3<s.length;i3++)data2[p+i3]=s.charCodeAt(i3)},readBytes:function(buff,p,l){var arr=[];for(var i3=0;i3<l;i3++)arr.push(buff[p+i3]);return arr},pad:function(n){return n.length<2?"0"+n:n},readUTF8:function(buff,p,l){var s="",ns;for(var i3=0;i3<l;i3++)s+="%"+UPNG._bin.pad(buff[p+i3].toString(16));try{ns=decodeURIComponent(s)}catch(e){return UPNG._bin.readASCII(buff,p,l)}return ns}};UPNG._copyTile=function(sb,sw,sh,tb,tw,th,xoff,yoff,mode){var w=Math.min(sw,tw),h=Math.min(sh,th);var si=0,ti=0;for(var y=0;y<h;y++)for(var x=0;x<w;x++){if(xoff>=0&&yoff>=0){si=y*sw+x<<2;ti=(yoff+y)*tw+xoff+x<<2}else{si=(-yoff+y)*sw-xoff+x<<2;ti=y*tw+x<<2}if(mode==0){tb[ti]=sb[si];tb[ti+1]=sb[si+1];tb[ti+2]=sb[si+2];tb[ti+3]=sb[si+3]}else if(mode==1){var fa=sb[si+3]*(1/255),fr=sb[si]*fa,fg=sb[si+1]*fa,fb=sb[si+2]*fa;var ba=tb[ti+3]*(1/255),br=tb[ti]*ba,bg=tb[ti+1]*ba,bb=tb[ti+2]*ba;var ifa=1-fa,oa=fa+ba*ifa,ioa=oa==0?0:1/oa;tb[ti+3]=255*oa;tb[ti+0]=(fr+br*ifa)*ioa;tb[ti+1]=(fg+bg*ifa)*ioa;tb[ti+2]=(fb+bb*ifa)*ioa}else if(mode==2){var fa=sb[si+3],fr=sb[si],fg=sb[si+1],fb=sb[si+2];var ba=tb[ti+3],br=tb[ti],bg=tb[ti+1],bb=tb[ti+2];if(fa==ba&&fr==br&&fg==bg&&fb==bb){tb[ti]=0;tb[ti+1]=0;tb[ti+2]=0;tb[ti+3]=0}else{tb[ti]=fr;tb[ti+1]=fg;tb[ti+2]=fb;tb[ti+3]=fa}}else if(mode==3){var fa=sb[si+3],fr=sb[si],fg=sb[si+1],fb=sb[si+2];var ba=tb[ti+3],br=tb[ti],bg=tb[ti+1],bb=tb[ti+2];if(fa==ba&&fr==br&&fg==bg&&fb==bb)continue;if(fa<220&&ba>20)return false}}return true};UPNG.encode=function(bufs,w,h,ps,dels,tabs,forbidPlte){if(ps==null)ps=0;if(forbidPlte==null)forbidPlte=false;var nimg=UPNG.encode.compress(bufs,w,h,ps,[false,false,false,0,forbidPlte]);UPNG.encode.compressPNG(nimg,-1);return UPNG.encode._main(nimg,w,h,dels,tabs)};UPNG.encodeLL=function(bufs,w,h,cc,ac,depth,dels,tabs){var nimg={ctype:0+(cc==1?0:2)+(ac==0?0:4),depth,frames:[]};var time=Date.now();var bipp=(cc+ac)*depth,bipl=bipp*w;for(var i3=0;i3<bufs.length;i3++)nimg.frames.push({rect:{x:0,y:0,width:w,height:h},img:new Uint8Array(bufs[i3]),blend:0,dispose:1,bpp:Math.ceil(bipp/8),bpl:Math.ceil(bipl/8)});UPNG.encode.compressPNG(nimg,0,true);var out=UPNG.encode._main(nimg,w,h,dels,tabs);return out};UPNG.encode._main=function(nimg,w,h,dels,tabs){if(tabs==null)tabs={};var crc=UPNG.crc.crc,wUi=UPNG._bin.writeUint,wUs=UPNG._bin.writeUshort,wAs=UPNG._bin.writeASCII;var offset=8,anim=nimg.frames.length>1,pltAlpha=false;var leng=8+(16+5+4)+(anim?20:0);if(tabs["sRGB"]!=null)leng+=8+1+4;if(tabs["pHYs"]!=null)leng+=8+9+4;if(nimg.ctype==3){var dl=nimg.plte.length;for(var i3=0;i3<dl;i3++)if(nimg.plte[i3]>>>24!=255)pltAlpha=true;leng+=8+dl*3+4+(pltAlpha?8+dl*1+4:0)}for(var j=0;j<nimg.frames.length;j++){var fr=nimg.frames[j];if(anim)leng+=38;leng+=fr.cimg.length+12;if(j!=0)leng+=4}leng+=12;var data2=new Uint8Array(leng);var wr=[137,80,78,71,13,10,26,10];for(var i3=0;i3<8;i3++)data2[i3]=wr[i3];wUi(data2,offset,13);offset+=4;wAs(data2,offset,"IHDR");offset+=4;wUi(data2,offset,w);offset+=4;wUi(data2,offset,h);offset+=4;data2[offset]=nimg.depth;offset++;data2[offset]=nimg.ctype;offset++;data2[offset]=0;offset++;data2[offset]=0;offset++;data2[offset]=0;offset++;wUi(data2,offset,crc(data2,offset-17,17));offset+=4;if(tabs["sRGB"]!=null){wUi(data2,offset,1);offset+=4;wAs(data2,offset,"sRGB");offset+=4;data2[offset]=tabs["sRGB"];offset++;wUi(data2,offset,crc(data2,offset-5,5));offset+=4}if(tabs["pHYs"]!=null){wUi(data2,offset,9);offset+=4;wAs(data2,offset,"pHYs");offset+=4;wUi(data2,offset,tabs["pHYs"][0]);offset+=4;wUi(data2,offset,tabs["pHYs"][1]);offset+=4;data2[offset]=tabs["pHYs"][2];offset++;wUi(data2,offset,crc(data2,offset-13,13));offset+=4}if(anim){wUi(data2,offset,8);offset+=4;wAs(data2,offset,"acTL");offset+=4;wUi(data2,offset,nimg.frames.length);offset+=4;wUi(data2,offset,tabs["loop"]!=null?tabs["loop"]:0);offset+=4;wUi(data2,offset,crc(data2,offset-12,12));offset+=4}if(nimg.ctype==3){var dl=nimg.plte.length;wUi(data2,offset,dl*3);offset+=4;wAs(data2,offset,"PLTE");offset+=4;for(var i3=0;i3<dl;i3++){var ti=i3*3,c=nimg.plte[i3],r=c&255,g=c>>>8&255,b=c>>>16&255;data2[offset+ti+0]=r;data2[offset+ti+1]=g;data2[offset+ti+2]=b}offset+=dl*3;wUi(data2,offset,crc(data2,offset-dl*3-4,dl*3+4));offset+=4;if(pltAlpha){wUi(data2,offset,dl);offset+=4;wAs(data2,offset,"tRNS");offset+=4;for(var i3=0;i3<dl;i3++)data2[offset+i3]=nimg.plte[i3]>>>24&255;offset+=dl;wUi(data2,offset,crc(data2,offset-dl-4,dl+4));offset+=4}}var fi=0;for(var j=0;j<nimg.frames.length;j++){var fr=nimg.frames[j];if(anim){wUi(data2,offset,26);offset+=4;wAs(data2,offset,"fcTL");offset+=4;wUi(data2,offset,fi++);offset+=4;wUi(data2,offset,fr.rect.width);offset+=4;wUi(data2,offset,fr.rect.height);offset+=4;wUi(data2,offset,fr.rect.x);offset+=4;wUi(data2,offset,fr.rect.y);offset+=4;wUs(data2,offset,dels[j]);offset+=2;wUs(data2,offset,1000);offset+=2;data2[offset]=fr.dispose;offset++;data2[offset]=fr.blend;offset++;wUi(data2,offset,crc(data2,offset-30,30));offset+=4}var imgd=fr.cimg,dl=imgd.length;wUi(data2,offset,dl+(j==0?0:4));offset+=4;var ioff=offset;wAs(data2,offset,j==0?"IDAT":"fdAT");offset+=4;if(j!=0){wUi(data2,offset,fi++);offset+=4}data2.set(imgd,offset);offset+=dl;wUi(data2,offset,crc(data2,ioff,offset-ioff));offset+=4}wUi(data2,offset,0);offset+=4;wAs(data2,offset,"IEND");offset+=4;wUi(data2,offset,crc(data2,offset-4,4));offset+=4;return data2.buffer};UPNG.encode.compressPNG=function(out,filter,levelZero){for(var i3=0;i3<out.frames.length;i3++){var frm=out.frames[i3],nw=frm.rect.width,nh=frm.rect.height;var fdata=new Uint8Array(nh*frm.bpl+nh);frm.cimg=UPNG.encode._filterZero(frm.img,nh,frm.bpp,frm.bpl,fdata,filter,levelZero)}};UPNG.encode.compress=function(bufs,w,h,ps,prms){var onlyBlend=prms[0],evenCrd=prms[1],forbidPrev=prms[2],minBits=prms[3],forbidPlte=prms[4];var ctype=6,depth=8,alphaAnd=255;for(var j=0;j<bufs.length;j++){var img=new Uint8Array(bufs[j]),ilen=img.length;for(var i3=0;i3<ilen;i3+=4)alphaAnd&=img[i3+3]}var gotAlpha=alphaAnd!=255;var frms=UPNG.encode.framize(bufs,w,h,onlyBlend,evenCrd,forbidPrev);var cmap={},plte=[],inds=[];if(ps!=0){var nbufs=[];for(var i3=0;i3<frms.length;i3++)nbufs.push(frms[i3].img.buffer);var abuf=UPNG.encode.concatRGBA(nbufs),qres=UPNG.quantize(abuf,ps);var cof=0,bb=new Uint8Array(qres.abuf);for(var i3=0;i3<frms.length;i3++){var ti=frms[i3].img,bln=ti.length;inds.push(new Uint8Array(qres.inds.buffer,cof>>2,bln>>2));for(var j=0;j<bln;j+=4){ti[j]=bb[cof+j];ti[j+1]=bb[cof+j+1];ti[j+2]=bb[cof+j+2];ti[j+3]=bb[cof+j+3]}cof+=bln}for(var i3=0;i3<qres.plte.length;i3++)plte.push(qres.plte[i3].est.rgba)}else{for(var j=0;j<frms.length;j++){var frm=frms[j],img32=new Uint32Array(frm.img.buffer),nw=frm.rect.width,ilen=img32.length;var ind=new Uint8Array(ilen);inds.push(ind);for(var i3=0;i3<ilen;i3++){var c=img32[i3];if(i3!=0&&c==img32[i3-1])ind[i3]=ind[i3-1];else if(i3>nw&&c==img32[i3-nw])ind[i3]=ind[i3-nw];else{var cmc=cmap[c];if(cmc==null){cmap[c]=cmc=plte.length;plte.push(c);if(plte.length>=300)break}ind[i3]=cmc}}}}var cc=plte.length;if(cc<=256&&forbidPlte==false){if(cc<=2)depth=1;else if(cc<=4)depth=2;else if(cc<=16)depth=4;else depth=8;depth=Math.max(depth,minBits)}for(var j=0;j<frms.length;j++){var frm=frms[j],nx=frm.rect.x,ny=frm.rect.y,nw=frm.rect.width,nh=frm.rect.height;var cimg=frm.img,cimg32=new Uint32Array(cimg.buffer);var bpl=4*nw,bpp=4;if(cc<=256&&forbidPlte==false){bpl=Math.ceil(depth*nw/8);var nimg=new Uint8Array(bpl*nh);var inj=inds[j];for(var y=0;y<nh;y++){var i3=y*bpl,ii=y*nw;if(depth==8)for(var x=0;x<nw;x++)nimg[i3+x]=inj[ii+x];else if(depth==4)for(var x=0;x<nw;x++)nimg[i3+(x>>1)]|=inj[ii+x]<<4-(x&1)*4;else if(depth==2)for(var x=0;x<nw;x++)nimg[i3+(x>>2)]|=inj[ii+x]<<6-(x&3)*2;else if(depth==1)for(var x=0;x<nw;x++)nimg[i3+(x>>3)]|=inj[ii+x]<<7-(x&7)*1}cimg=nimg;ctype=3;bpp=1}else if(gotAlpha==false&&frms.length==1){var nimg=new Uint8Array(nw*nh*3),area=nw*nh;for(var i3=0;i3<area;i3++){var ti=i3*3,qi=i3*4;nimg[ti]=cimg[qi];nimg[ti+1]=cimg[qi+1];nimg[ti+2]=cimg[qi+2]}cimg=nimg;ctype=2;bpp=3;bpl=3*nw}frm.img=cimg;frm.bpl=bpl;frm.bpp=bpp}return{ctype,depth,plte,frames:frms}};UPNG.encode.framize=function(bufs,w,h,alwaysBlend,evenCrd,forbidPrev){var frms=[];for(var j=0;j<bufs.length;j++){var cimg=new Uint8Array(bufs[j]),cimg32=new Uint32Array(cimg.buffer);var nimg;var nx=0,ny=0,nw=w,nh=h,blend=alwaysBlend?1:0;if(j!=0){var tlim=forbidPrev||alwaysBlend||j==1||frms[j-2].dispose!=0?1:2,tstp=0,tarea=1e9;for(var it=0;it<tlim;it++){var pimg=new Uint8Array(bufs[j-1-it]),p32=new Uint32Array(bufs[j-1-it]);var mix=w,miy=h,max=-1,may=-1;for(var y=0;y<h;y++)for(var x=0;x<w;x++){var i3=y*w+x;if(cimg32[i3]!=p32[i3]){if(x<mix)mix=x;if(x>max)max=x;if(y<miy)miy=y;if(y>may)may=y}}if(max==-1)mix=miy=max=may=0;if(evenCrd){if((mix&1)==1)mix--;if((miy&1)==1)miy--}var sarea=(max-mix+1)*(may-miy+1);if(sarea<tarea){tarea=sarea;tstp=it;nx=mix;ny=miy;nw=max-mix+1;nh=may-miy+1}}var pimg=new Uint8Array(bufs[j-1-tstp]);if(tstp==1)frms[j-1].dispose=2;nimg=new Uint8Array(nw*nh*4);UPNG._copyTile(pimg,w,h,nimg,nw,nh,-nx,-ny,0);blend=UPNG._copyTile(cimg,w,h,nimg,nw,nh,-nx,-ny,3)?1:0;if(blend==1)UPNG.encode._prepareDiff(cimg,w,h,nimg,{x:nx,y:ny,width:nw,height:nh});else UPNG._copyTile(cimg,w,h,nimg,nw,nh,-nx,-ny,0)}else nimg=cimg.slice(0);frms.push({rect:{x:nx,y:ny,width:nw,height:nh},img:nimg,blend,dispose:0})}if(alwaysBlend)for(var j=0;j<frms.length;j++){var frm=frms[j];if(frm.blend==1)continue;var r0=frm.rect,r1=frms[j-1].rect;var miX=Math.min(r0.x,r1.x),miY=Math.min(r0.y,r1.y);var maX=Math.max(r0.x+r0.width,r1.x+r1.width),maY=Math.max(r0.y+r0.height,r1.y+r1.height);var r={x:miX,y:miY,width:maX-miX,height:maY-miY};frms[j-1].dispose=1;if(j-1!=0)UPNG.encode._updateFrame(bufs,w,h,frms,j-1,r,evenCrd);UPNG.encode._updateFrame(bufs,w,h,frms,j,r,evenCrd)}var area=0;if(bufs.length!=1)for(var i3=0;i3<frms.length;i3++){var frm=frms[i3];area+=frm.rect.width*frm.rect.height}return frms};UPNG.encode._updateFrame=function(bufs,w,h,frms,i3,r,evenCrd){var U8=Uint8Array,U32=Uint32Array;var pimg=new U8(bufs[i3-1]),pimg32=new U32(bufs[i3-1]),nimg=i3+1<bufs.length?new U8(bufs[i3+1]):null;var cimg=new U8(bufs[i3]),cimg32=new U32(cimg.buffer);var mix=w,miy=h,max=-1,may=-1;for(var y=0;y<r.height;y++)for(var x=0;x<r.width;x++){var cx=r.x+x,cy=r.y+y;var j=cy*w+cx,cc=cimg32[j];if(cc==0||frms[i3-1].dispose==0&&pimg32[j]==cc&&(nimg==null||nimg[j*4+3]!=0)){}else{if(cx<mix)mix=cx;if(cx>max)max=cx;if(cy<miy)miy=cy;if(cy>may)may=cy}}if(max==-1)mix=miy=max=may=0;if(evenCrd){if((mix&1)==1)mix--;if((miy&1)==1)miy--}r={x:mix,y:miy,width:max-mix+1,height:may-miy+1};var fr=frms[i3];fr.rect=r;fr.blend=1;fr.img=new Uint8Array(r.width*r.height*4);if(frms[i3-1].dispose==0){UPNG._copyTile(pimg,w,h,fr.img,r.width,r.height,-r.x,-r.y,0);UPNG.encode._prepareDiff(cimg,w,h,fr.img,r)}else UPNG._copyTile(cimg,w,h,fr.img,r.width,r.height,-r.x,-r.y,0)};UPNG.encode._prepareDiff=function(cimg,w,h,nimg,rec){UPNG._copyTile(cimg,w,h,nimg,rec.width,rec.height,-rec.x,-rec.y,2)};UPNG.encode._filterZero=function(img,h,bpp,bpl,data2,filter,levelZero){var fls=[],ftry=[0,1,2,3,4];if(filter!=-1)ftry=[filter];else if(h*bpl>500000||bpp==1)ftry=[0];var opts;if(levelZero)opts={level:0};var CMPR=levelZero&&UZIP!=null?UZIP:import_pako4.default;for(var i3=0;i3<ftry.length;i3++){for(var y=0;y<h;y++)UPNG.encode._filterLine(data2,img,y,bpl,bpp,ftry[i3]);fls.push(CMPR["deflate"](data2,opts))}var ti,tsize=1e9;for(var i3=0;i3<fls.length;i3++)if(fls[i3].length<tsize){ti=i3;tsize=fls[i3].length}return fls[ti]};UPNG.encode._filterLine=function(data2,img,y,bpl,bpp,type){var i3=y*bpl,di=i3+y,paeth=UPNG.decode._paeth;data2[di]=type;di++;if(type==0){if(bpl<500)for(var x=0;x<bpl;x++)data2[di+x]=img[i3+x];else data2.set(new Uint8Array(img.buffer,i3,bpl),di)}else if(type==1){for(var x=0;x<bpp;x++)data2[di+x]=img[i3+x];for(var x=bpp;x<bpl;x++)data2[di+x]=img[i3+x]-img[i3+x-bpp]+256&255}else if(y==0){for(var x=0;x<bpp;x++)data2[di+x]=img[i3+x];if(type==2)for(var x=bpp;x<bpl;x++)data2[di+x]=img[i3+x];if(type==3)for(var x=bpp;x<bpl;x++)data2[di+x]=img[i3+x]-(img[i3+x-bpp]>>1)+256&255;if(type==4)for(var x=bpp;x<bpl;x++)data2[di+x]=img[i3+x]-paeth(img[i3+x-bpp],0,0)+256&255}else{if(type==2){for(var x=0;x<bpl;x++)data2[di+x]=img[i3+x]+256-img[i3+x-bpl]&255}if(type==3){for(var x=0;x<bpp;x++)data2[di+x]=img[i3+x]+256-(img[i3+x-bpl]>>1)&255;for(var x=bpp;x<bpl;x++)data2[di+x]=img[i3+x]+256-(img[i3+x-bpl]+img[i3+x-bpp]>>1)&255}if(type==4){for(var x=0;x<bpp;x++)data2[di+x]=img[i3+x]+256-paeth(0,img[i3+x-bpl],0)&255;for(var x=bpp;x<bpl;x++)data2[di+x]=img[i3+x]+256-paeth(img[i3+x-bpp],img[i3+x-bpl],img[i3+x-bpp-bpl])&255}}};UPNG.crc={table:function(){var tab=new Uint32Array(256);for(var n=0;n<256;n++){var c=n;for(var k=0;k<8;k++){if(c&1)c=3988292384^c>>>1;else c=c>>>1}tab[n]=c}return tab}(),update:function(c,buf,off,len2){for(var i3=0;i3<len2;i3++)c=UPNG.crc.table[(c^buf[off+i3])&255]^c>>>8;return c},crc:function(b,o,l){return UPNG.crc.update(4294967295,b,o,l)^4294967295}};UPNG.quantize=function(abuf,ps){var oimg=new Uint8Array(abuf),nimg=oimg.slice(0),nimg32=new Uint32Array(nimg.buffer);var KD=UPNG.quantize.getKDtree(nimg,ps);var root=KD[0],leafs=KD[1];var planeDst=UPNG.quantize.planeDst;var sb=oimg,tb=nimg32,len2=sb.length;var inds=new Uint8Array(oimg.length>>2);for(var i3=0;i3<len2;i3+=4){var r=sb[i3]*(1/255),g=sb[i3+1]*(1/255),b=sb[i3+2]*(1/255),a=sb[i3+3]*(1/255);var nd=UPNG.quantize.getNearest(root,r,g,b,a);inds[i3>>2]=nd.ind;tb[i3>>2]=nd.est.rgba}return{abuf:nimg.buffer,inds,plte:leafs}};UPNG.quantize.getKDtree=function(nimg,ps,err){if(err==null)err=0.0001;var nimg32=new Uint32Array(nimg.buffer);var root={i0:0,i1:nimg.length,bst:null,est:null,tdst:0,left:null,right:null};root.bst=UPNG.quantize.stats(nimg,root.i0,root.i1);root.est=UPNG.quantize.estats(root.bst);var leafs=[root];while(leafs.length<ps){var maxL=0,mi=0;for(var i3=0;i3<leafs.length;i3++)if(leafs[i3].est.L>maxL){maxL=leafs[i3].est.L;mi=i3}if(maxL<err)break;var node=leafs[mi];var s0=UPNG.quantize.splitPixels(nimg,nimg32,node.i0,node.i1,node.est.e,node.est.eMq255);var s0wrong=node.i0>=s0||node.i1<=s0;if(s0wrong){node.est.L=0;continue}var ln={i0:node.i0,i1:s0,bst:null,est:null,tdst:0,left:null,right:null};ln.bst=UPNG.quantize.stats(nimg,ln.i0,ln.i1);ln.est=UPNG.quantize.estats(ln.bst);var rn={i0:s0,i1:node.i1,bst:null,est:null,tdst:0,left:null,right:null};rn.bst={R:[],m:[],N:node.bst.N-ln.bst.N};for(var i3=0;i3<16;i3++)rn.bst.R[i3]=node.bst.R[i3]-ln.bst.R[i3];for(var i3=0;i3<4;i3++)rn.bst.m[i3]=node.bst.m[i3]-ln.bst.m[i3];rn.est=UPNG.quantize.estats(rn.bst);node.left=ln;node.right=rn;leafs[mi]=ln;leafs.push(rn)}leafs.sort(function(a,b){return b.bst.N-a.bst.N});for(var i3=0;i3<leafs.length;i3++)leafs[i3].ind=i3;return[root,leafs]};UPNG.quantize.getNearest=function(nd,r,g,b,a){if(nd.left==null){nd.tdst=UPNG.quantize.dist(nd.est.q,r,g,b,a);return nd}var planeDst=UPNG.quantize.planeDst(nd.est,r,g,b,a);var{left:node0,right:node1}=nd;if(planeDst>0){node0=nd.right;node1=nd.left}var ln=UPNG.quantize.getNearest(node0,r,g,b,a);if(ln.tdst<=planeDst*planeDst)return ln;var rn=UPNG.quantize.getNearest(node1,r,g,b,a);return rn.tdst<ln.tdst?rn:ln};UPNG.quantize.planeDst=function(est,r,g,b,a){var e=est.e;return e[0]*r+e[1]*g+e[2]*b+e[3]*a-est.eMq};UPNG.quantize.dist=function(q,r,g,b,a){var d0=r-q[0],d1=g-q[1],d2=b-q[2],d3=a-q[3];return d0*d0+d1*d1+d2*d2+d3*d3};UPNG.quantize.splitPixels=function(nimg,nimg32,i0,i1,e,eMq){var vecDot=UPNG.quantize.vecDot;i1-=4;var shfs=0;while(i0<i1){while(vecDot(nimg,i0,e)<=eMq)i0+=4;while(vecDot(nimg,i1,e)>eMq)i1-=4;if(i0>=i1)break;var t=nimg32[i0>>2];nimg32[i0>>2]=nimg32[i1>>2];nimg32[i1>>2]=t;i0+=4;i1-=4}while(vecDot(nimg,i0,e)>eMq)i0-=4;return i0+4};UPNG.quantize.vecDot=function(nimg,i3,e){return nimg[i3]*e[0]+nimg[i3+1]*e[1]+nimg[i3+2]*e[2]+nimg[i3+3]*e[3]};UPNG.quantize.stats=function(nimg,i0,i1){var R=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];var m=[0,0,0,0];var N=i1-i0>>2;for(var i3=i0;i3<i1;i3+=4){var r=nimg[i3]*(1/255),g=nimg[i3+1]*(1/255),b=nimg[i3+2]*(1/255),a=nimg[i3+3]*(1/255);m[0]+=r;m[1]+=g;m[2]+=b;m[3]+=a;R[0]+=r*r;R[1]+=r*g;R[2]+=r*b;R[3]+=r*a;R[5]+=g*g;R[6]+=g*b;R[7]+=g*a;R[10]+=b*b;R[11]+=b*a;R[15]+=a*a}R[4]=R[1];R[8]=R[2];R[9]=R[6];R[12]=R[3];R[13]=R[7];R[14]=R[11];return{R,m,N}};UPNG.quantize.estats=function(stats){var{R,m,N}=stats;var m0=m[0],m1=m[1],m2=m[2],m3=m[3],iN=N==0?0:1/N;var Rj=[R[0]-m0*m0*iN,R[1]-m0*m1*iN,R[2]-m0*m2*iN,R[3]-m0*m3*iN,R[4]-m1*m0*iN,R[5]-m1*m1*iN,R[6]-m1*m2*iN,R[7]-m1*m3*iN,R[8]-m2*m0*iN,R[9]-m2*m1*iN,R[10]-m2*m2*iN,R[11]-m2*m3*iN,R[12]-m3*m0*iN,R[13]-m3*m1*iN,R[14]-m3*m2*iN,R[15]-m3*m3*iN];var A=Rj,M=UPNG.M4;var b=[0.5,0.5,0.5,0.5],mi=0,tmi=0;if(N!=0)for(var i3=0;i3<10;i3++){b=M.multVec(A,b);tmi=Math.sqrt(M.dot(b,b));b=M.sml(1/tmi,b);if(Math.abs(tmi-mi)<0.000000001)break;mi=tmi}var q=[m0*iN,m1*iN,m2*iN,m3*iN];var eMq255=M.dot(M.sml(255,q),b);return{Cov:Rj,q,e:b,L:mi,eMq255,eMq:M.dot(b,q),rgba:(Math.round(255*q[3])<<24|Math.round(255*q[2])<<16|Math.round(255*q[1])<<8|Math.round(255*q[0])<<0)>>>0}};UPNG.M4={multVec:function(m,v){return[m[0]*v[0]+m[1]*v[1]+m[2]*v[2]+m[3]*v[3],m[4]*v[0]+m[5]*v[1]+m[6]*v[2]+m[7]*v[3],m[8]*v[0]+m[9]*v[1]+m[10]*v[2]+m[11]*v[3],m[12]*v[0]+m[13]*v[1]+m[14]*v[2]+m[15]*v[3]]},dot:function(x,y){return x[0]*y[0]+x[1]*y[1]+x[2]*y[2]+x[3]*y[3]},sml:function(a,y){return[a*y[0],a*y[1],a*y[2],a*y[3]]}};UPNG.encode.concatRGBA=function(bufs){var tlen=0;for(var i3=0;i3<bufs.length;i3++)tlen+=bufs[i3].byteLength;var nimg=new Uint8Array(tlen),noff=0;for(var i3=0;i3<bufs.length;i3++){var img=new Uint8Array(bufs[i3]),il=img.length;for(var j=0;j<il;j+=4){var r=img[j],g=img[j+1],b=img[j+2],a=img[j+3];if(a==0)r=g=b=0;nimg[noff+j]=r;nimg[noff+j+1]=g;nimg[noff+j+2]=b;nimg[noff+j+3]=a}noff+=il}return nimg.buffer};UPNG_default=UPNG});var getImageType=function(ctype){if(ctype===0)return PngType.Greyscale;if(ctype===2)return PngType.Truecolour;if(ctype===3)return PngType.IndexedColour;if(ctype===4)return PngType.GreyscaleWithAlpha;if(ctype===6)return PngType.TruecolourWithAlpha;throw new Error("Unknown color type: "+ctype)},splitAlphaChannel=function(rgbaChannel){var pixelCount=Math.floor(rgbaChannel.length/4);var rgbChannel=new Uint8Array(pixelCount*3);var alphaChannel=new Uint8Array(pixelCount*1);var rgbaOffset=0;var rgbOffset=0;var alphaOffset=0;while(rgbaOffset<rgbaChannel.length){rgbChannel[rgbOffset++]=rgbaChannel[rgbaOffset++];rgbChannel[rgbOffset++]=rgbaChannel[rgbaOffset++];rgbChannel[rgbOffset++]=rgbaChannel[rgbaOffset++];alphaChannel[alphaOffset++]=rgbaChannel[rgbaOffset++]}return{rgbChannel,alphaChannel}},PngType,PNG;var init_png=__esm(()=>{init_UPNG();(function(PngType2){PngType2["Greyscale"]="Greyscale";PngType2["Truecolour"]="Truecolour";PngType2["IndexedColour"]="IndexedColour";PngType2["GreyscaleWithAlpha"]="GreyscaleWithAlpha";PngType2["TruecolourWithAlpha"]="TruecolourWithAlpha"})(PngType||(PngType={}));PNG=function(){function PNG2(pngData){var upng=UPNG_default.decode(pngData);var frames=UPNG_default.toRGBA8(upng);if(frames.length>1)throw new Error("Animated PNGs are not supported");var frame=new Uint8Array(frames[0]);var _a=splitAlphaChannel(frame),rgbChannel=_a.rgbChannel,alphaChannel=_a.alphaChannel;this.rgbChannel=rgbChannel;var hasAlphaValues=alphaChannel.some(function(a){return a<255});if(hasAlphaValues)this.alphaChannel=alphaChannel;this.type=getImageType(upng.ctype);this.width=upng.width;this.height=upng.height;this.bitsPerComponent=8}PNG2.load=function(pngData){return new PNG2(pngData)};return PNG2}()});var PngEmbedder,PngEmbedder_default;var init_PngEmbedder=__esm(()=>{init_tslib_es62();init_png();PngEmbedder=function(){function PngEmbedder2(png){this.image=png;this.bitsPerComponent=png.bitsPerComponent;this.width=png.width;this.height=png.height;this.colorSpace="DeviceRGB"}PngEmbedder2.for=function(imageData){return __awaiter(this,undefined,undefined,function(){var png;return __generator(this,function(_a){png=PNG.load(imageData);return[2,new PngEmbedder2(png)]})})};PngEmbedder2.prototype.embedIntoContext=function(context2,ref){return __awaiter(this,undefined,undefined,function(){var SMask,xObject;return __generator(this,function(_a){SMask=this.embedAlphaChannel(context2);xObject=context2.flateStream(this.image.rgbChannel,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.image.bitsPerComponent,Width:this.image.width,Height:this.image.height,ColorSpace:this.colorSpace,SMask});if(ref){context2.assign(ref,xObject);return[2,ref]}else{return[2,context2.register(xObject)]}return[2]})})};PngEmbedder2.prototype.embedAlphaChannel=function(context2){if(!this.image.alphaChannel)return;var xObject=context2.flateStream(this.image.alphaChannel,{Type:"XObject",Subtype:"Image",Height:this.image.height,Width:this.image.width,BitsPerComponent:this.image.bitsPerComponent,ColorSpace:"DeviceGray",Decode:[0,1]});return context2.register(xObject)};return PngEmbedder2}();PngEmbedder_default=PngEmbedder});var Stream,Stream_default;var init_Stream=__esm(()=>{Stream=function(){function Stream2(buffer,start,length){this.bytes=buffer;this.start=start||0;this.pos=this.start;this.end=!!start&&!!length?start+length:this.bytes.length}Object.defineProperty(Stream2.prototype,"length",{get:function(){return this.end-this.start},enumerable:false,configurable:true});Object.defineProperty(Stream2.prototype,"isEmpty",{get:function(){return this.length===0},enumerable:false,configurable:true});Stream2.prototype.getByte=function(){if(this.pos>=this.end){return-1}return this.bytes[this.pos++]};Stream2.prototype.getUint16=function(){var b0=this.getByte();var b1=this.getByte();if(b0===-1||b1===-1){return-1}return(b0<<8)+b1};Stream2.prototype.getInt32=function(){var b0=this.getByte();var b1=this.getByte();var b2=this.getByte();var b3=this.getByte();return(b0<<24)+(b1<<16)+(b2<<8)+b3};Stream2.prototype.getBytes=function(length,forceClamped){if(forceClamped===undefined){forceClamped=false}var bytes=this.bytes;var pos=this.pos;var strEnd=this.end;if(!length){var subarray=bytes.subarray(pos,strEnd);return forceClamped?new Uint8ClampedArray(subarray):subarray}else{var end=pos+length;if(end>strEnd){end=strEnd}this.pos=end;var subarray=bytes.subarray(pos,end);return forceClamped?new Uint8ClampedArray(subarray):subarray}};Stream2.prototype.peekByte=function(){var peekedByte=this.getByte();this.pos--;return peekedByte};Stream2.prototype.peekBytes=function(length,forceClamped){if(forceClamped===undefined){forceClamped=false}var bytes=this.getBytes(length,forceClamped);this.pos-=bytes.length;return bytes};Stream2.prototype.skip=function(n){if(!n){n=1}this.pos+=n};Stream2.prototype.reset=function(){this.pos=this.start};Stream2.prototype.moveStart=function(){this.start=this.pos};Stream2.prototype.makeSubStream=function(start,length){return new Stream2(this.bytes,start,length)};Stream2.prototype.decode=function(){return this.bytes};return Stream2}();Stream_default=Stream});var emptyBuffer,DecodeStream,DecodeStream_default;var init_DecodeStream=__esm(()=>{init_errors2();init_Stream();emptyBuffer=new Uint8Array(0);DecodeStream=function(){function DecodeStream2(maybeMinBufferLength){this.pos=0;this.bufferLength=0;this.eof=false;this.buffer=emptyBuffer;this.minBufferLength=512;if(maybeMinBufferLength){while(this.minBufferLength<maybeMinBufferLength){this.minBufferLength*=2}}}Object.defineProperty(DecodeStream2.prototype,"isEmpty",{get:function(){while(!this.eof&&this.bufferLength===0){this.readBlock()}return this.bufferLength===0},enumerable:false,configurable:true});DecodeStream2.prototype.getByte=function(){var pos=this.pos;while(this.bufferLength<=pos){if(this.eof){return-1}this.readBlock()}return this.buffer[this.pos++]};DecodeStream2.prototype.getUint16=function(){var b0=this.getByte();var b1=this.getByte();if(b0===-1||b1===-1){return-1}return(b0<<8)+b1};DecodeStream2.prototype.getInt32=function(){var b0=this.getByte();var b1=this.getByte();var b2=this.getByte();var b3=this.getByte();return(b0<<24)+(b1<<16)+(b2<<8)+b3};DecodeStream2.prototype.getBytes=function(length,forceClamped){if(forceClamped===undefined){forceClamped=false}var end;var pos=this.pos;if(length){this.ensureBuffer(pos+length);end=pos+length;while(!this.eof&&this.bufferLength<end){this.readBlock()}var bufEnd=this.bufferLength;if(end>bufEnd){end=bufEnd}}else{while(!this.eof){this.readBlock()}end=this.bufferLength}this.pos=end;var subarray=this.buffer.subarray(pos,end);return forceClamped&&!(subarray instanceof Uint8ClampedArray)?new Uint8ClampedArray(subarray):subarray};DecodeStream2.prototype.peekByte=function(){var peekedByte=this.getByte();this.pos--;return peekedByte};DecodeStream2.prototype.peekBytes=function(length,forceClamped){if(forceClamped===undefined){forceClamped=false}var bytes=this.getBytes(length,forceClamped);this.pos-=bytes.length;return bytes};DecodeStream2.prototype.skip=function(n){if(!n){n=1}this.pos+=n};DecodeStream2.prototype.reset=function(){this.pos=0};DecodeStream2.prototype.makeSubStream=function(start,length){var end=start+length;while(this.bufferLength<=end&&!this.eof){this.readBlock()}return new Stream_default(this.buffer,start,length)};DecodeStream2.prototype.decode=function(){while(!this.eof)this.readBlock();return this.buffer.subarray(0,this.bufferLength)};DecodeStream2.prototype.readBlock=function(){throw new MethodNotImplementedError(this.constructor.name,"readBlock")};DecodeStream2.prototype.ensureBuffer=function(requested){var buffer=this.buffer;if(requested<=buffer.byteLength){return buffer}var size=this.minBufferLength;while(size<requested){size*=2}var buffer2=new Uint8Array(size);buffer2.set(buffer);return this.buffer=buffer2};return DecodeStream2}();DecodeStream_default=DecodeStream});var isSpace=function(ch){return ch===32||ch===9||ch===13||ch===10},Ascii85Stream,Ascii85Stream_default;var init_Ascii85Stream=__esm(()=>{init_tslib_es62();init_DecodeStream();Ascii85Stream=function(_super){__extends(Ascii85Stream2,_super);function Ascii85Stream2(stream,maybeLength){var _this=_super.call(this,maybeLength)||this;_this.stream=stream;_this.input=new Uint8Array(5);if(maybeLength){maybeLength=0.8*maybeLength}return _this}Ascii85Stream2.prototype.readBlock=function(){var TILDA_CHAR=126;var Z_LOWER_CHAR=122;var EOF=-1;var stream=this.stream;var c=stream.getByte();while(isSpace(c)){c=stream.getByte()}if(c===EOF||c===TILDA_CHAR){this.eof=true;return}var bufferLength=this.bufferLength;var buffer;var i3;if(c===Z_LOWER_CHAR){buffer=this.ensureBuffer(bufferLength+4);for(i3=0;i3<4;++i3){buffer[bufferLength+i3]=0}this.bufferLength+=4}else{var input=this.input;input[0]=c;for(i3=1;i3<5;++i3){c=stream.getByte();while(isSpace(c)){c=stream.getByte()}input[i3]=c;if(c===EOF||c===TILDA_CHAR){break}}buffer=this.ensureBuffer(bufferLength+i3-1);this.bufferLength+=i3-1;if(i3<5){for(;i3<5;++i3){input[i3]=33+84}this.eof=true}var t=0;for(i3=0;i3<5;++i3){t=t*85+(input[i3]-33)}for(i3=3;i3>=0;--i3){buffer[bufferLength+i3]=t&255;t>>=8}}};return Ascii85Stream2}(DecodeStream_default);Ascii85Stream_default=Ascii85Stream});var AsciiHexStream,AsciiHexStream_default;var init_AsciiHexStream=__esm(()=>{init_tslib_es62();init_DecodeStream();AsciiHexStream=function(_super){__extends(AsciiHexStream2,_super);function AsciiHexStream2(stream,maybeLength){var _this=_super.call(this,maybeLength)||this;_this.stream=stream;_this.firstDigit=-1;if(maybeLength){maybeLength=0.5*maybeLength}return _this}AsciiHexStream2.prototype.readBlock=function(){var UPSTREAM_BLOCK_SIZE=8000;var bytes=this.stream.getBytes(UPSTREAM_BLOCK_SIZE);if(!bytes.length){this.eof=true;return}var maxDecodeLength=bytes.length+1>>1;var buffer=this.ensureBuffer(this.bufferLength+maxDecodeLength);var bufferLength=this.bufferLength;var firstDigit=this.firstDigit;for(var i3=0,ii=bytes.length;i3<ii;i3++){var ch=bytes[i3];var digit=undefined;if(ch>=48&&ch<=57){digit=ch&15}else if(ch>=65&&ch<=70||ch>=97&&ch<=102){digit=(ch&15)+9}else if(ch===62){this.eof=true;break}else{continue}if(firstDigit<0){firstDigit=digit}else{buffer[bufferLength++]=firstDigit<<4|digit;firstDigit=-1}}if(firstDigit>=0&&this.eof){buffer[bufferLength++]=firstDigit<<4;firstDigit=-1}this.firstDigit=firstDigit;this.bufferLength=bufferLength};return AsciiHexStream2}(DecodeStream_default);AsciiHexStream_default=AsciiHexStream});var codeLenCodeMap,lengthDecode,distDecode,fixedLitCodeTab,fixedDistCodeTab,FlateStream,FlateStream_default;var init_FlateStream=__esm(()=>{init_tslib_es62();init_DecodeStream();codeLenCodeMap=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);lengthDecode=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]);distDecode=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]);fixedLitCodeTab=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,590000,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9];fixedDistCodeTab=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];FlateStream=function(_super){__extends(FlateStream2,_super);function FlateStream2(stream,maybeLength){var _this=_super.call(this,maybeLength)||this;_this.stream=stream;var cmf=stream.getByte();var flg=stream.getByte();if(cmf===-1||flg===-1){throw new Error("Invalid header in flate stream: "+cmf+", "+flg)}if((cmf&15)!==8){throw new Error("Unknown compression method in flate stream: "+cmf+", "+flg)}if(((cmf<<8)+flg)%31!==0){throw new Error("Bad FCHECK in flate stream: "+cmf+", "+flg)}if(flg&32){throw new Error("FDICT bit set in flate stream: "+cmf+", "+flg)}_this.codeSize=0;_this.codeBuf=0;return _this}FlateStream2.prototype.readBlock=function(){var buffer;var len2;var str=this.stream;var hdr=this.getBits(3);if(hdr&1){this.eof=true}hdr>>=1;if(hdr===0){var b=undefined;if((b=str.getByte())===-1){throw new Error("Bad block header in flate stream")}var blockLen=b;if((b=str.getByte())===-1){throw new Error("Bad block header in flate stream")}blockLen|=b<<8;if((b=str.getByte())===-1){throw new Error("Bad block header in flate stream")}var check=b;if((b=str.getByte())===-1){throw new Error("Bad block header in flate stream")}check|=b<<8;if(check!==(~blockLen&65535)&&(blockLen!==0||check!==0)){throw new Error("Bad uncompressed block length in flate stream")}this.codeBuf=0;this.codeSize=0;var bufferLength=this.bufferLength;buffer=this.ensureBuffer(bufferLength+blockLen);var end=bufferLength+blockLen;this.bufferLength=end;if(blockLen===0){if(str.peekByte()===-1){this.eof=true}}else{for(var n=bufferLength;n<end;++n){if((b=str.getByte())===-1){this.eof=true;break}buffer[n]=b}}return}var litCodeTable;var distCodeTable;if(hdr===1){litCodeTable=fixedLitCodeTab;distCodeTable=fixedDistCodeTab}else if(hdr===2){var numLitCodes=this.getBits(5)+257;var numDistCodes=this.getBits(5)+1;var numCodeLenCodes=this.getBits(4)+4;var codeLenCodeLengths=new Uint8Array(codeLenCodeMap.length);var i3=undefined;for(i3=0;i3<numCodeLenCodes;++i3){codeLenCodeLengths[codeLenCodeMap[i3]]=this.getBits(3)}var codeLenCodeTab=this.generateHuffmanTable(codeLenCodeLengths);len2=0;i3=0;var codes=numLitCodes+numDistCodes;var codeLengths=new Uint8Array(codes);var bitsLength=undefined;var bitsOffset=undefined;var what=undefined;while(i3<codes){var code=this.getCode(codeLenCodeTab);if(code===16){bitsLength=2;bitsOffset=3;what=len2}else if(code===17){bitsLength=3;bitsOffset=3;what=len2=0}else if(code===18){bitsLength=7;bitsOffset=11;what=len2=0}else{codeLengths[i3++]=len2=code;continue}var repeatLength=this.getBits(bitsLength)+bitsOffset;while(repeatLength-- >0){codeLengths[i3++]=what}}litCodeTable=this.generateHuffmanTable(codeLengths.subarray(0,numLitCodes));distCodeTable=this.generateHuffmanTable(codeLengths.subarray(numLitCodes,codes))}else{throw new Error("Unknown block type in flate stream")}buffer=this.buffer;var limit=buffer?buffer.length:0;var pos=this.bufferLength;while(true){var code1=this.getCode(litCodeTable);if(code1<256){if(pos+1>=limit){buffer=this.ensureBuffer(pos+1);limit=buffer.length}buffer[pos++]=code1;continue}if(code1===256){this.bufferLength=pos;return}code1-=257;code1=lengthDecode[code1];var code2=code1>>16;if(code2>0){code2=this.getBits(code2)}len2=(code1&65535)+code2;code1=this.getCode(distCodeTable);code1=distDecode[code1];code2=code1>>16;if(code2>0){code2=this.getBits(code2)}var dist=(code1&65535)+code2;if(pos+len2>=limit){buffer=this.ensureBuffer(pos+len2);limit=buffer.length}for(var k=0;k<len2;++k,++pos){buffer[pos]=buffer[pos-dist]}}};FlateStream2.prototype.getBits=function(bits){var str=this.stream;var codeSize=this.codeSize;var codeBuf=this.codeBuf;var b;while(codeSize<bits){if((b=str.getByte())===-1){throw new Error("Bad encoding in flate stream")}codeBuf|=b<<codeSize;codeSize+=8}b=codeBuf&(1<<bits)-1;this.codeBuf=codeBuf>>bits;this.codeSize=codeSize-=bits;return b};FlateStream2.prototype.getCode=function(table){var str=this.stream;var codes=table[0];var maxLen=table[1];var codeSize=this.codeSize;var codeBuf=this.codeBuf;var b;while(codeSize<maxLen){if((b=str.getByte())===-1){break}codeBuf|=b<<codeSize;codeSize+=8}var code=codes[codeBuf&(1<<maxLen)-1];if(typeof codes==="number"){console.log("FLATE:",code)}var codeLen=code>>16;var codeVal=code&65535;if(codeLen<1||codeSize<codeLen){throw new Error("Bad encoding in flate stream")}this.codeBuf=codeBuf>>codeLen;this.codeSize=codeSize-codeLen;return codeVal};FlateStream2.prototype.generateHuffmanTable=function(lengths){var n=lengths.length;var maxLen=0;var i3;for(i3=0;i3<n;++i3){if(lengths[i3]>maxLen){maxLen=lengths[i3]}}var size=1<<maxLen;var codes=new Int32Array(size);for(var len2=1,code=0,skip=2;len2<=maxLen;++len2,code<<=1,skip<<=1){for(var val=0;val<n;++val){if(lengths[val]===len2){var code2=0;var t=code;for(i3=0;i3<len2;++i3){code2=code2<<1|t&1;t>>=1}for(i3=code2;i3<size;i3+=skip){codes[i3]=len2<<16|val}++code}}}return[codes,maxLen]};return FlateStream2}(DecodeStream_default);FlateStream_default=FlateStream});var LZWStream,LZWStream_default;var init_LZWStream=__esm(()=>{init_tslib_es62();init_DecodeStream();LZWStream=function(_super){__extends(LZWStream2,_super);function LZWStream2(stream,maybeLength,earlyChange){var _this=_super.call(this,maybeLength)||this;_this.stream=stream;_this.cachedData=0;_this.bitsCached=0;var maxLzwDictionarySize=4096;var lzwState={earlyChange,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(maxLzwDictionarySize),dictionaryLengths:new Uint16Array(maxLzwDictionarySize),dictionaryPrevCodes:new Uint16Array(maxLzwDictionarySize),currentSequence:new Uint8Array(maxLzwDictionarySize),currentSequenceLength:0};for(var i3=0;i3<256;++i3){lzwState.dictionaryValues[i3]=i3;lzwState.dictionaryLengths[i3]=1}_this.lzwState=lzwState;return _this}LZWStream2.prototype.readBlock=function(){var blockSize=512;var estimatedDecodedSize=blockSize*2;var decodedSizeDelta=blockSize;var i3;var j;var q;var lzwState=this.lzwState;if(!lzwState){return}var earlyChange=lzwState.earlyChange;var nextCode=lzwState.nextCode;var dictionaryValues=lzwState.dictionaryValues;var dictionaryLengths=lzwState.dictionaryLengths;var dictionaryPrevCodes=lzwState.dictionaryPrevCodes;var codeLength=lzwState.codeLength;var prevCode=lzwState.prevCode;var currentSequence=lzwState.currentSequence;var currentSequenceLength=lzwState.currentSequenceLength;var decodedLength=0;var currentBufferLength=this.bufferLength;var buffer=this.ensureBuffer(this.bufferLength+estimatedDecodedSize);for(i3=0;i3<blockSize;i3++){var code=this.readBits(codeLength);var hasPrev=currentSequenceLength>0;if(!code||code<256){currentSequence[0]=code;currentSequenceLength=1}else if(code>=258){if(code<nextCode){currentSequenceLength=dictionaryLengths[code];for(j=currentSequenceLength-1,q=code;j>=0;j--){currentSequence[j]=dictionaryValues[q];q=dictionaryPrevCodes[q]}}else{currentSequence[currentSequenceLength++]=currentSequence[0]}}else if(code===256){codeLength=9;nextCode=258;currentSequenceLength=0;continue}else{this.eof=true;delete this.lzwState;break}if(hasPrev){dictionaryPrevCodes[nextCode]=prevCode;dictionaryLengths[nextCode]=dictionaryLengths[prevCode]+1;dictionaryValues[nextCode]=currentSequence[0];nextCode++;codeLength=nextCode+earlyChange&nextCode+earlyChange-1?codeLength:Math.min(Math.log(nextCode+earlyChange)/0.6931471805599453+1,12)|0}prevCode=code;decodedLength+=currentSequenceLength;if(estimatedDecodedSize<decodedLength){do{estimatedDecodedSize+=decodedSizeDelta}while(estimatedDecodedSize<decodedLength);buffer=this.ensureBuffer(this.bufferLength+estimatedDecodedSize)}for(j=0;j<currentSequenceLength;j++){buffer[currentBufferLength++]=currentSequence[j]}}lzwState.nextCode=nextCode;lzwState.codeLength=codeLength;lzwState.prevCode=prevCode;lzwState.currentSequenceLength=currentSequenceLength;this.bufferLength=currentBufferLength};LZWStream2.prototype.readBits=function(n){var bitsCached=this.bitsCached;var cachedData=this.cachedData;while(bitsCached<n){var c=this.stream.getByte();if(c===-1){this.eof=true;return null}cachedData=cachedData<<8|c;bitsCached+=8}this.bitsCached=bitsCached-=n;this.cachedData=cachedData;return cachedData>>>bitsCached&(1<<n)-1};return LZWStream2}(DecodeStream_default);LZWStream_default=LZWStream});var RunLengthStream,RunLengthStream_default;var init_RunLengthStream=__esm(()=>{init_tslib_es62();init_DecodeStream();RunLengthStream=function(_super){__extends(RunLengthStream2,_super);function RunLengthStream2(stream,maybeLength){var _this=_super.call(this,maybeLength)||this;_this.stream=stream;return _this}RunLengthStream2.prototype.readBlock=function(){var repeatHeader=this.stream.getBytes(2);if(!repeatHeader||repeatHeader.length<2||repeatHeader[0]===128){this.eof=true;return}var buffer;var bufferLength=this.bufferLength;var n=repeatHeader[0];if(n<128){buffer=this.ensureBuffer(bufferLength+n+1);buffer[bufferLength++]=repeatHeader[1];if(n>0){var source=this.stream.getBytes(n);buffer.set(source,bufferLength);bufferLength+=n}}else{n=257-n;var b=repeatHeader[1];buffer=this.ensureBuffer(bufferLength+n+1);for(var i3=0;i3<n;i3++){buffer[bufferLength++]=b}}this.bufferLength=bufferLength};return RunLengthStream2}(DecodeStream_default);RunLengthStream_default=RunLengthStream});var decodeStream=function(stream,encoding,params){if(encoding===PDFName_default.of("FlateDecode")){return new FlateStream_default(stream)}if(encoding===PDFName_default.of("LZWDecode")){var earlyChange=1;if(params instanceof PDFDict_default){var EarlyChange=params.lookup(PDFName_default.of("EarlyChange"));if(EarlyChange instanceof PDFNumber_default){earlyChange=EarlyChange.asNumber()}}return new LZWStream_default(stream,undefined,earlyChange)}if(encoding===PDFName_default.of("ASCII85Decode")){return new Ascii85Stream_default(stream)}if(encoding===PDFName_default.of("ASCIIHexDecode")){return new AsciiHexStream_default(stream)}if(encoding===PDFName_default.of("RunLengthDecode")){return new RunLengthStream_default(stream)}throw new UnsupportedEncodingError(encoding.asString())},decodePDFRawStream=function(_a){var{dict,contents}=_a;var stream=new Stream_default(contents);var Filter=dict.lookup(PDFName_default.of("Filter"));var DecodeParms=dict.lookup(PDFName_default.of("DecodeParms"));if(Filter instanceof PDFName_default){stream=decodeStream(stream,Filter,DecodeParms)}else if(Filter instanceof PDFArray_default){for(var idx3=0,len2=Filter.size();idx3<len2;idx3++){stream=decodeStream(stream,Filter.lookup(idx3,PDFName_default),DecodeParms&&DecodeParms.lookupMaybe(idx3,PDFDict_default))}}else if(!!Filter){throw new UnexpectedObjectTypeError([PDFName_default,PDFArray_default],Filter)}return stream};var init_decode=__esm(()=>{init_errors2();init_PDFArray();init_PDFDict();init_PDFName();init_PDFNumber();init_Ascii85Stream();init_AsciiHexStream();init_FlateStream();init_LZWStream();init_RunLengthStream();init_Stream()});var fullPageBoundingBox=function(page){var mediaBox=page.MediaBox();var width=mediaBox.lookup(2,PDFNumber_default).asNumber()-mediaBox.lookup(0,PDFNumber_default).asNumber();var height=mediaBox.lookup(3,PDFNumber_default).asNumber()-mediaBox.lookup(1,PDFNumber_default).asNumber();return{left:0,bottom:0,right:width,top:height}},boundingBoxAdjustedMatrix=function(bb){return[1,0,0,1,-bb.left,-bb.bottom]},PDFPageEmbedder,PDFPageEmbedder_default;var init_PDFPageEmbedder=__esm(()=>{init_tslib_es62();init_errors2();init_PDFNumber();init_PDFRawStream();init_PDFStream();init_decode();init_PDFContentStream();init_CharCodes();init_utils2();PDFPageEmbedder=function(){function PDFPageEmbedder2(page,boundingBox,transformationMatrix){this.page=page;var bb=boundingBox!==null&&boundingBox!==undefined?boundingBox:fullPageBoundingBox(page);this.width=bb.right-bb.left;this.height=bb.top-bb.bottom;this.boundingBox=bb;this.transformationMatrix=transformationMatrix!==null&&transformationMatrix!==undefined?transformationMatrix:boundingBoxAdjustedMatrix(bb)}PDFPageEmbedder2.for=function(page,boundingBox,transformationMatrix){return __awaiter(this,undefined,undefined,function(){return __generator(this,function(_a){return[2,new PDFPageEmbedder2(page,boundingBox,transformationMatrix)]})})};PDFPageEmbedder2.prototype.embedIntoContext=function(context2,ref){return __awaiter(this,undefined,undefined,function(){var _a,Contents,Resources,decodedContents,_b,left,bottom,right,top,xObject;return __generator(this,function(_c){_a=this.page.normalizedEntries(),Contents=_a.Contents,Resources=_a.Resources;if(!Contents)throw new MissingPageContentsEmbeddingError;decodedContents=this.decodeContents(Contents);_b=this.boundingBox,left=_b.left,bottom=_b.bottom,right=_b.right,top=_b.top;xObject=context2.flateStream(decodedContents,{Type:"XObject",Subtype:"Form",FormType:1,BBox:[left,bottom,right,top],Matrix:this.transformationMatrix,Resources});if(ref){context2.assign(ref,xObject);return[2,ref]}else{return[2,context2.register(xObject)]}return[2]})})};PDFPageEmbedder2.prototype.decodeContents=function(contents){var newline=Uint8Array.of(CharCodes_default.Newline);var decodedContents=[];for(var idx3=0,len2=contents.size();idx3<len2;idx3++){var stream=contents.lookup(idx3,PDFStream_default);var content=undefined;if(stream instanceof PDFRawStream_default){content=decodePDFRawStream(stream).decode()}else if(stream instanceof PDFContentStream_default){content=stream.getUnencodedContents()}else{throw new UnrecognizedStreamTypeError(stream)}decodedContents.push(content,newline)}return mergeIntoTypedArray.apply(undefined,decodedContents)};return PDFPageEmbedder2}();PDFPageEmbedder_default=PDFPageEmbedder});var asEnum=function(rawValue,enumType){if(rawValue===undefined)return;return enumType[rawValue]},NonFullScreenPageMode,ReadingDirection,PrintScaling,Duplex,ViewerPreferences,ViewerPreferences_default;var init_ViewerPreferences=__esm(()=>{init_PDFArray();init_PDFBool();init_PDFName();init_PDFNumber();init_utils2();(function(NonFullScreenPageMode2){NonFullScreenPageMode2["UseNone"]="UseNone";NonFullScreenPageMode2["UseOutlines"]="UseOutlines";NonFullScreenPageMode2["UseThumbs"]="UseThumbs";NonFullScreenPageMode2["UseOC"]="UseOC"})(NonFullScreenPageMode||(NonFullScreenPageMode={}));(function(ReadingDirection2){ReadingDirection2["L2R"]="L2R";ReadingDirection2["R2L"]="R2L"})(ReadingDirection||(ReadingDirection={}));(function(PrintScaling2){PrintScaling2["None"]="None";PrintScaling2["AppDefault"]="AppDefault"})(PrintScaling||(PrintScaling={}));(function(Duplex2){Duplex2["Simplex"]="Simplex";Duplex2["DuplexFlipShortEdge"]="DuplexFlipShortEdge";Duplex2["DuplexFlipLongEdge"]="DuplexFlipLongEdge"})(Duplex||(Duplex={}));ViewerPreferences=function(){function ViewerPreferences2(dict){this.dict=dict}ViewerPreferences2.prototype.lookupBool=function(key){var returnObj=this.dict.lookup(PDFName_default.of(key));if(returnObj instanceof PDFBool_default)return returnObj;return};ViewerPreferences2.prototype.lookupName=function(key){var returnObj=this.dict.lookup(PDFName_default.of(key));if(returnObj instanceof PDFName_default)return returnObj;return};ViewerPreferences2.prototype.HideToolbar=function(){return this.lookupBool("HideToolbar")};ViewerPreferences2.prototype.HideMenubar=function(){return this.lookupBool("HideMenubar")};ViewerPreferences2.prototype.HideWindowUI=function(){return this.lookupBool("HideWindowUI")};ViewerPreferences2.prototype.FitWindow=function(){return this.lookupBool("FitWindow")};ViewerPreferences2.prototype.CenterWindow=function(){return this.lookupBool("CenterWindow")};ViewerPreferences2.prototype.DisplayDocTitle=function(){return this.lookupBool("DisplayDocTitle")};ViewerPreferences2.prototype.NonFullScreenPageMode=function(){return this.lookupName("NonFullScreenPageMode")};ViewerPreferences2.prototype.Direction=function(){return this.lookupName("Direction")};ViewerPreferences2.prototype.PrintScaling=function(){return this.lookupName("PrintScaling")};ViewerPreferences2.prototype.Duplex=function(){return this.lookupName("Duplex")};ViewerPreferences2.prototype.PickTrayByPDFSize=function(){return this.lookupBool("PickTrayByPDFSize")};ViewerPreferences2.prototype.PrintPageRange=function(){var PrintPageRange=this.dict.lookup(PDFName_default.of("PrintPageRange"));if(PrintPageRange instanceof PDFArray_default)return PrintPageRange;return};ViewerPreferences2.prototype.NumCopies=function(){var NumCopies=this.dict.lookup(PDFName_default.of("NumCopies"));if(NumCopies instanceof PDFNumber_default)return NumCopies;return};ViewerPreferences2.prototype.getHideToolbar=function(){var _a,_b;return(_b=(_a=this.HideToolbar())===null||_a===undefined?undefined:_a.asBoolean())!==null&&_b!==undefined?_b:false};ViewerPreferences2.prototype.getHideMenubar=function(){var _a,_b;return(_b=(_a=this.HideMenubar())===null||_a===undefined?undefined:_a.asBoolean())!==null&&_b!==undefined?_b:false};ViewerPreferences2.prototype.getHideWindowUI=function(){var _a,_b;return(_b=(_a=this.HideWindowUI())===null||_a===undefined?undefined:_a.asBoolean())!==null&&_b!==undefined?_b:false};ViewerPreferences2.prototype.getFitWindow=function(){var _a,_b;return(_b=(_a=this.FitWindow())===null||_a===undefined?undefined:_a.asBoolean())!==null&&_b!==undefined?_b:false};ViewerPreferences2.prototype.getCenterWindow=function(){var _a,_b;return(_b=(_a=this.CenterWindow())===null||_a===undefined?undefined:_a.asBoolean())!==null&&_b!==undefined?_b:false};ViewerPreferences2.prototype.getDisplayDocTitle=function(){var _a,_b;return(_b=(_a=this.DisplayDocTitle())===null||_a===undefined?undefined:_a.asBoolean())!==null&&_b!==undefined?_b:false};ViewerPreferences2.prototype.getNonFullScreenPageMode=function(){var _a,_b;var mode=(_a=this.NonFullScreenPageMode())===null||_a===undefined?undefined:_a.decodeText();return(_b=asEnum(mode,NonFullScreenPageMode))!==null&&_b!==undefined?_b:NonFullScreenPageMode.UseNone};ViewerPreferences2.prototype.getReadingDirection=function(){var _a,_b;var direction=(_a=this.Direction())===null||_a===undefined?undefined:_a.decodeText();return(_b=asEnum(direction,ReadingDirection))!==null&&_b!==undefined?_b:ReadingDirection.L2R};ViewerPreferences2.prototype.getPrintScaling=function(){var _a,_b;var scaling=(_a=this.PrintScaling())===null||_a===undefined?undefined:_a.decodeText();return(_b=asEnum(scaling,PrintScaling))!==null&&_b!==undefined?_b:PrintScaling.AppDefault};ViewerPreferences2.prototype.getDuplex=function(){var _a;var duplex=(_a=this.Duplex())===null||_a===undefined?undefined:_a.decodeText();return asEnum(duplex,Duplex)};ViewerPreferences2.prototype.getPickTrayByPDFSize=function(){var _a;return(_a=this.PickTrayByPDFSize())===null||_a===undefined?undefined:_a.asBoolean()};ViewerPreferences2.prototype.getPrintPageRange=function(){var rng=this.PrintPageRange();if(!rng)return[];var pageRanges=[];for(var i3=0;i3<rng.size();i3+=2){var start=rng.lookup(i3,PDFNumber_default).asNumber();var end=rng.lookup(i3+1,PDFNumber_default).asNumber();pageRanges.push({start,end})}return pageRanges};ViewerPreferences2.prototype.getNumCopies=function(){var _a,_b;return(_b=(_a=this.NumCopies())===null||_a===undefined?undefined:_a.asNumber())!==null&&_b!==undefined?_b:1};ViewerPreferences2.prototype.setHideToolbar=function(hideToolbar){var HideToolbar=this.dict.context.obj(hideToolbar);this.dict.set(PDFName_default.of("HideToolbar"),HideToolbar)};ViewerPreferences2.prototype.setHideMenubar=function(hideMenubar){var HideMenubar=this.dict.context.obj(hideMenubar);this.dict.set(PDFName_default.of("HideMenubar"),HideMenubar)};ViewerPreferences2.prototype.setHideWindowUI=function(hideWindowUI){var HideWindowUI=this.dict.context.obj(hideWindowUI);this.dict.set(PDFName_default.of("HideWindowUI"),HideWindowUI)};ViewerPreferences2.prototype.setFitWindow=function(fitWindow){var FitWindow=this.dict.context.obj(fitWindow);this.dict.set(PDFName_default.of("FitWindow"),FitWindow)};ViewerPreferences2.prototype.setCenterWindow=function(centerWindow){var CenterWindow=this.dict.context.obj(centerWindow);this.dict.set(PDFName_default.of("CenterWindow"),CenterWindow)};ViewerPreferences2.prototype.setDisplayDocTitle=function(displayTitle){var DisplayDocTitle=this.dict.context.obj(displayTitle);this.dict.set(PDFName_default.of("DisplayDocTitle"),DisplayDocTitle)};ViewerPreferences2.prototype.setNonFullScreenPageMode=function(nonFullScreenPageMode){assertIsOneOf(nonFullScreenPageMode,"nonFullScreenPageMode",NonFullScreenPageMode);var mode=PDFName_default.of(nonFullScreenPageMode);this.dict.set(PDFName_default.of("NonFullScreenPageMode"),mode)};ViewerPreferences2.prototype.setReadingDirection=function(readingDirection){assertIsOneOf(readingDirection,"readingDirection",ReadingDirection);var direction=PDFName_default.of(readingDirection);this.dict.set(PDFName_default.of("Direction"),direction)};ViewerPreferences2.prototype.setPrintScaling=function(printScaling){assertIsOneOf(printScaling,"printScaling",PrintScaling);var scaling=PDFName_default.of(printScaling);this.dict.set(PDFName_default.of("PrintScaling"),scaling)};ViewerPreferences2.prototype.setDuplex=function(duplex){assertIsOneOf(duplex,"duplex",Duplex);var dup=PDFName_default.of(duplex);this.dict.set(PDFName_default.of("Duplex"),dup)};ViewerPreferences2.prototype.setPickTrayByPDFSize=function(pickTrayByPDFSize){var PickTrayByPDFSize=this.dict.context.obj(pickTrayByPDFSize);this.dict.set(PDFName_default.of("PickTrayByPDFSize"),PickTrayByPDFSize)};ViewerPreferences2.prototype.setPrintPageRange=function(printPageRange){if(!Array.isArray(printPageRange))printPageRange=[printPageRange];var flatRange=[];for(var idx3=0,len2=printPageRange.length;idx3<len2;idx3++){flatRange.push(printPageRange[idx3].start);flatRange.push(printPageRange[idx3].end)}assertEachIs(flatRange,"printPageRange",["number"]);var pageRanges=this.dict.context.obj(flatRange);this.dict.set(PDFName_default.of("PrintPageRange"),pageRanges)};ViewerPreferences2.prototype.setNumCopies=function(numCopies){assertRange(numCopies,"numCopies",1,Number.MAX_VALUE);assertInteger(numCopies,"numCopies");var NumCopies=this.dict.context.obj(numCopies);this.dict.set(PDFName_default.of("NumCopies"),NumCopies)};ViewerPreferences2.fromDict=function(dict){return new ViewerPreferences2(dict)};ViewerPreferences2.create=function(context2){var dict=context2.obj({});return new ViewerPreferences2(dict)};return ViewerPreferences2}();ViewerPreferences_default=ViewerPreferences});var tfRegex,PDFAcroField,PDFAcroField_default;var init_PDFAcroField=__esm(()=>{init_PDFDict();init_PDFString();init_PDFHexString();init_PDFName();init_PDFNumber();init_PDFArray();init_PDFRef();init_utils2();init_errors2();tfRegex=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+Tf/;PDFAcroField=function(){function PDFAcroField2(dict,ref){this.dict=dict;this.ref=ref}PDFAcroField2.prototype.T=function(){return this.dict.lookupMaybe(PDFName_default.of("T"),PDFString_default,PDFHexString_default)};PDFAcroField2.prototype.Ff=function(){var numberOrRef=this.getInheritableAttribute(PDFName_default.of("Ff"));return this.dict.context.lookupMaybe(numberOrRef,PDFNumber_default)};PDFAcroField2.prototype.V=function(){var valueOrRef=this.getInheritableAttribute(PDFName_default.of("V"));return this.dict.context.lookup(valueOrRef)};PDFAcroField2.prototype.Kids=function(){return this.dict.lookupMaybe(PDFName_default.of("Kids"),PDFArray_default)};PDFAcroField2.prototype.DA=function(){var da=this.dict.lookup(PDFName_default.of("DA"));if(da instanceof PDFString_default||da instanceof PDFHexString_default)return da;return};PDFAcroField2.prototype.setKids=function(kids){this.dict.set(PDFName_default.of("Kids"),this.dict.context.obj(kids))};PDFAcroField2.prototype.getParent=function(){var parentRef=this.dict.get(PDFName_default.of("Parent"));if(parentRef instanceof PDFRef_default){var parent_1=this.dict.lookup(PDFName_default.of("Parent"),PDFDict_default);return new PDFAcroField2(parent_1,parentRef)}return};PDFAcroField2.prototype.setParent=function(parent){if(!parent)this.dict.delete(PDFName_default.of("Parent"));else this.dict.set(PDFName_default.of("Parent"),parent)};PDFAcroField2.prototype.getFullyQualifiedName=function(){var parent=this.getParent();if(!parent)return this.getPartialName();return parent.getFullyQualifiedName()+"."+this.getPartialName()};PDFAcroField2.prototype.getPartialName=function(){var _a;return(_a=this.T())===null||_a===undefined?undefined:_a.decodeText()};PDFAcroField2.prototype.setPartialName=function(partialName){if(!partialName)this.dict.delete(PDFName_default.of("T"));else this.dict.set(PDFName_default.of("T"),PDFHexString_default.fromText(partialName))};PDFAcroField2.prototype.setDefaultAppearance=function(appearance){this.dict.set(PDFName_default.of("DA"),PDFString_default.of(appearance))};PDFAcroField2.prototype.getDefaultAppearance=function(){var DA=this.DA();if(DA instanceof PDFHexString_default){return DA.decodeText()}return DA===null||DA===undefined?undefined:DA.asString()};PDFAcroField2.prototype.setFontSize=function(fontSize){var _a;var name=(_a=this.getFullyQualifiedName())!==null&&_a!==undefined?_a:"";var da=this.getDefaultAppearance();if(!da)throw new MissingDAEntryError(name);var daMatch=findLastMatch(da,tfRegex);if(!daMatch.match)throw new MissingTfOperatorError(name);var daStart=da.slice(0,daMatch.pos-daMatch.match[0].length);var daEnd=daMatch.pos<=da.length?da.slice(daMatch.pos):"";var fontName=daMatch.match[1];var modifiedDa=daStart+" /"+fontName+" "+fontSize+" Tf "+daEnd;this.setDefaultAppearance(modifiedDa)};PDFAcroField2.prototype.getFlags=function(){var _a,_b;return(_b=(_a=this.Ff())===null||_a===undefined?undefined:_a.asNumber())!==null&&_b!==undefined?_b:0};PDFAcroField2.prototype.setFlags=function(flags){this.dict.set(PDFName_default.of("Ff"),PDFNumber_default.of(flags))};PDFAcroField2.prototype.hasFlag=function(flag){var flags=this.getFlags();return(flags&flag)!==0};PDFAcroField2.prototype.setFlag=function(flag){var flags=this.getFlags();this.setFlags(flags|flag)};PDFAcroField2.prototype.clearFlag=function(flag){var flags=this.getFlags();this.setFlags(flags&~flag)};PDFAcroField2.prototype.setFlagTo=function(flag,enable){if(enable)this.setFlag(flag);else this.clearFlag(flag)};PDFAcroField2.prototype.getInheritableAttribute=function(name){var attribute;this.ascend(function(node){if(!attribute)attribute=node.dict.get(name)});return attribute};PDFAcroField2.prototype.ascend=function(visitor){visitor(this);var parent=this.getParent();if(parent)parent.ascend(visitor)};return PDFAcroField2}();PDFAcroField_default=PDFAcroField});var BorderStyle,BorderStyle_default;var init_BorderStyle=__esm(()=>{init_PDFName();init_PDFNumber();BorderStyle=function(){function BorderStyle2(dict){this.dict=dict}BorderStyle2.prototype.W=function(){var W=this.dict.lookup(PDFName_default.of("W"));if(W instanceof PDFNumber_default)return W;return};BorderStyle2.prototype.getWidth=function(){var _a,_b;return(_b=(_a=this.W())===null||_a===undefined?undefined:_a.asNumber())!==null&&_b!==undefined?_b:1};BorderStyle2.prototype.setWidth=function(width){var W=this.dict.context.obj(width);this.dict.set(PDFName_default.of("W"),W)};BorderStyle2.fromDict=function(dict){return new BorderStyle2(dict)};return BorderStyle2}();BorderStyle_default=BorderStyle});var PDFAnnotation,PDFAnnotation_default;var init_PDFAnnotation=__esm(()=>{init_PDFDict();init_PDFName();init_PDFStream();init_PDFArray();init_PDFRef();init_PDFNumber();PDFAnnotation=function(){function PDFAnnotation2(dict){this.dict=dict}PDFAnnotation2.prototype.Rect=function(){return this.dict.lookup(PDFName_default.of("Rect"),PDFArray_default)};PDFAnnotation2.prototype.AP=function(){return this.dict.lookupMaybe(PDFName_default.of("AP"),PDFDict_default)};PDFAnnotation2.prototype.F=function(){var numberOrRef=this.dict.lookup(PDFName_default.of("F"));return this.dict.context.lookupMaybe(numberOrRef,PDFNumber_default)};PDFAnnotation2.prototype.getRectangle=function(){var _a;var Rect=this.Rect();return(_a=Rect===null||Rect===undefined?undefined:Rect.asRectangle())!==null&&_a!==undefined?_a:{x:0,y:0,width:0,height:0}};PDFAnnotation2.prototype.setRectangle=function(rect){var{x,y,width,height}=rect;var Rect=this.dict.context.obj([x,y,x+width,y+height]);this.dict.set(PDFName_default.of("Rect"),Rect)};PDFAnnotation2.prototype.getAppearanceState=function(){var AS=this.dict.lookup(PDFName_default.of("AS"));if(AS instanceof PDFName_default)return AS;return};PDFAnnotation2.prototype.setAppearanceState=function(state){this.dict.set(PDFName_default.of("AS"),state)};PDFAnnotation2.prototype.setAppearances=function(appearances){this.dict.set(PDFName_default.of("AP"),appearances)};PDFAnnotation2.prototype.ensureAP=function(){var AP=this.AP();if(!AP){AP=this.dict.context.obj({});this.dict.set(PDFName_default.of("AP"),AP)}return AP};PDFAnnotation2.prototype.getNormalAppearance=function(){var AP=this.ensureAP();var N=AP.get(PDFName_default.of("N"));if(N instanceof PDFRef_default||N instanceof PDFDict_default)return N;throw new Error("Unexpected N type: "+(N===null||N===undefined?undefined:N.constructor.name))};PDFAnnotation2.prototype.setNormalAppearance=function(appearance){var AP=this.ensureAP();AP.set(PDFName_default.of("N"),appearance)};PDFAnnotation2.prototype.setRolloverAppearance=function(appearance){var AP=this.ensureAP();AP.set(PDFName_default.of("R"),appearance)};PDFAnnotation2.prototype.setDownAppearance=function(appearance){var AP=this.ensureAP();AP.set(PDFName_default.of("D"),appearance)};PDFAnnotation2.prototype.removeRolloverAppearance=function(){var AP=this.AP();AP===null||AP===undefined||AP.delete(PDFName_default.of("R"))};PDFAnnotation2.prototype.removeDownAppearance=function(){var AP=this.AP();AP===null||AP===undefined||AP.delete(PDFName_default.of("D"))};PDFAnnotation2.prototype.getAppearances=function(){var AP=this.AP();if(!AP)return;var N=AP.lookup(PDFName_default.of("N"),PDFDict_default,PDFStream_default);var R=AP.lookupMaybe(PDFName_default.of("R"),PDFDict_default,PDFStream_default);var D=AP.lookupMaybe(PDFName_default.of("D"),PDFDict_default,PDFStream_default);return{normal:N,rollover:R,down:D}};PDFAnnotation2.prototype.getFlags=function(){var _a,_b;return(_b=(_a=this.F())===null||_a===undefined?undefined:_a.asNumber())!==null&&_b!==undefined?_b:0};PDFAnnotation2.prototype.setFlags=function(flags){this.dict.set(PDFName_default.of("F"),PDFNumber_default.of(flags))};PDFAnnotation2.prototype.hasFlag=function(flag){var flags=this.getFlags();return(flags&flag)!==0};PDFAnnotation2.prototype.setFlag=function(flag){var flags=this.getFlags();this.setFlags(flags|flag)};PDFAnnotation2.prototype.clearFlag=function(flag){var flags=this.getFlags();this.setFlags(flags&~flag)};PDFAnnotation2.prototype.setFlagTo=function(flag,enable){if(enable)this.setFlag(flag);else this.clearFlag(flag)};PDFAnnotation2.fromDict=function(dict){return new PDFAnnotation2(dict)};return PDFAnnotation2}();PDFAnnotation_default=PDFAnnotation});var AppearanceCharacteristics,AppearanceCharacteristics_default;var init_AppearanceCharacteristics=__esm(()=>{init_PDFName();init_PDFNumber();init_PDFArray();init_PDFHexString();init_PDFString();AppearanceCharacteristics=function(){function AppearanceCharacteristics2(dict){this.dict=dict}AppearanceCharacteristics2.prototype.R=function(){var R=this.dict.lookup(PDFName_default.of("R"));if(R instanceof PDFNumber_default)return R;return};AppearanceCharacteristics2.prototype.BC=function(){var BC=this.dict.lookup(PDFName_default.of("BC"));if(BC instanceof PDFArray_default)return BC;return};AppearanceCharacteristics2.prototype.BG=function(){var BG=this.dict.lookup(PDFName_default.of("BG"));if(BG instanceof PDFArray_default)return BG;return};AppearanceCharacteristics2.prototype.CA=function(){var CA=this.dict.lookup(PDFName_default.of("CA"));if(CA instanceof PDFHexString_default||CA instanceof PDFString_default)return CA;return};AppearanceCharacteristics2.prototype.RC=function(){var RC=this.dict.lookup(PDFName_default.of("RC"));if(RC instanceof PDFHexString_default||RC instanceof PDFString_default)return RC;return};AppearanceCharacteristics2.prototype.AC=function(){var AC=this.dict.lookup(PDFName_default.of("AC"));if(AC instanceof PDFHexString_default||AC instanceof PDFString_default)return AC;return};AppearanceCharacteristics2.prototype.getRotation=function(){var _a;return(_a=this.R())===null||_a===undefined?undefined:_a.asNumber()};AppearanceCharacteristics2.prototype.getBorderColor=function(){var BC=this.BC();if(!BC)return;var components=[];for(var idx3=0,len2=BC===null||BC===undefined?undefined:BC.size();idx3<len2;idx3++){var component=BC.get(idx3);if(component instanceof PDFNumber_default)components.push(component.asNumber())}return components};AppearanceCharacteristics2.prototype.getBackgroundColor=function(){var BG=this.BG();if(!BG)return;var components=[];for(var idx3=0,len2=BG===null||BG===undefined?undefined:BG.size();idx3<len2;idx3++){var component=BG.get(idx3);if(component instanceof PDFNumber_default)components.push(component.asNumber())}return components};AppearanceCharacteristics2.prototype.getCaptions=function(){var CA=this.CA();var RC=this.RC();var AC=this.AC();return{normal:CA===null||CA===undefined?undefined:CA.decodeText(),rollover:RC===null||RC===undefined?undefined:RC.decodeText(),down:AC===null||AC===undefined?undefined:AC.decodeText()}};AppearanceCharacteristics2.prototype.setRotation=function(rotation){var R=this.dict.context.obj(rotation);this.dict.set(PDFName_default.of("R"),R)};AppearanceCharacteristics2.prototype.setBorderColor=function(color){var BC=this.dict.context.obj(color);this.dict.set(PDFName_default.of("BC"),BC)};AppearanceCharacteristics2.prototype.setBackgroundColor=function(color){var BG=this.dict.context.obj(color);this.dict.set(PDFName_default.of("BG"),BG)};AppearanceCharacteristics2.prototype.setCaptions=function(captions){var CA=PDFHexString_default.fromText(captions.normal);this.dict.set(PDFName_default.of("CA"),CA);if(captions.rollover){var RC=PDFHexString_default.fromText(captions.rollover);this.dict.set(PDFName_default.of("RC"),RC)}else{this.dict.delete(PDFName_default.of("RC"))}if(captions.down){var AC=PDFHexString_default.fromText(captions.down);this.dict.set(PDFName_default.of("AC"),AC)}else{this.dict.delete(PDFName_default.of("AC"))}};AppearanceCharacteristics2.fromDict=function(dict){return new AppearanceCharacteristics2(dict)};return AppearanceCharacteristics2}();AppearanceCharacteristics_default=AppearanceCharacteristics});var PDFWidgetAnnotation,PDFWidgetAnnotation_default;var init_PDFWidgetAnnotation=__esm(()=>{init_tslib_es62();init_PDFDict();init_PDFName();init_PDFRef();init_PDFString();init_PDFHexString();init_BorderStyle();init_PDFAnnotation();init_AppearanceCharacteristics();PDFWidgetAnnotation=function(_super){__extends(PDFWidgetAnnotation2,_super);function PDFWidgetAnnotation2(){return _super!==null&&_super.apply(this,arguments)||this}PDFWidgetAnnotation2.prototype.MK=function(){var MK=this.dict.lookup(PDFName_default.of("MK"));if(MK instanceof PDFDict_default)return MK;return};PDFWidgetAnnotation2.prototype.BS=function(){var BS=this.dict.lookup(PDFName_default.of("BS"));if(BS instanceof PDFDict_default)return BS;return};PDFWidgetAnnotation2.prototype.DA=function(){var da=this.dict.lookup(PDFName_default.of("DA"));if(da instanceof PDFString_default||da instanceof PDFHexString_default)return da;return};PDFWidgetAnnotation2.prototype.P=function(){var P=this.dict.get(PDFName_default.of("P"));if(P instanceof PDFRef_default)return P;return};PDFWidgetAnnotation2.prototype.setP=function(page){this.dict.set(PDFName_default.of("P"),page)};PDFWidgetAnnotation2.prototype.setDefaultAppearance=function(appearance){this.dict.set(PDFName_default.of("DA"),PDFString_default.of(appearance))};PDFWidgetAnnotation2.prototype.getDefaultAppearance=function(){var DA=this.DA();if(DA instanceof PDFHexString_default){return DA.decodeText()}return DA===null||DA===undefined?undefined:DA.asString()};PDFWidgetAnnotation2.prototype.getAppearanceCharacteristics=function(){var MK=this.MK();if(MK)return AppearanceCharacteristics_default.fromDict(MK);return};PDFWidgetAnnotation2.prototype.getOrCreateAppearanceCharacteristics=function(){var MK=this.MK();if(MK)return AppearanceCharacteristics_default.fromDict(MK);var ac=AppearanceCharacteristics_default.fromDict(this.dict.context.obj({}));this.dict.set(PDFName_default.of("MK"),ac.dict);return ac};PDFWidgetAnnotation2.prototype.getBorderStyle=function(){var BS=this.BS();if(BS)return BorderStyle_default.fromDict(BS);return};PDFWidgetAnnotation2.prototype.getOrCreateBorderStyle=function(){var BS=this.BS();if(BS)return BorderStyle_default.fromDict(BS);var bs=BorderStyle_default.fromDict(this.dict.context.obj({}));this.dict.set(PDFName_default.of("BS"),bs.dict);return bs};PDFWidgetAnnotation2.prototype.getOnValue=function(){var _a;var normal=(_a=this.getAppearances())===null||_a===undefined?undefined:_a.normal;if(normal instanceof PDFDict_default){var keys4=normal.keys();for(var idx3=0,len2=keys4.length;idx3<len2;idx3++){var key=keys4[idx3];if(key!==PDFName_default.of("Off"))return key}}return};PDFWidgetAnnotation2.fromDict=function(dict){return new PDFWidgetAnnotation2(dict)};PDFWidgetAnnotation2.create=function(context2,parent){var dict=context2.obj({Type:"Annot",Subtype:"Widget",Rect:[0,0,0,0],Parent:parent});return new PDFWidgetAnnotation2(dict)};return PDFWidgetAnnotation2}(PDFAnnotation_default);PDFWidgetAnnotation_default=PDFWidgetAnnotation});var PDFAcroTerminal,PDFAcroTerminal_default;var init_PDFAcroTerminal=__esm(()=>{init_tslib_es62();init_PDFDict();init_PDFName();init_PDFAcroField();init_PDFWidgetAnnotation();init_errors2();PDFAcroTerminal=function(_super){__extends(PDFAcroTerminal2,_super);function PDFAcroTerminal2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroTerminal2.prototype.FT=function(){var nameOrRef=this.getInheritableAttribute(PDFName_default.of("FT"));return this.dict.context.lookup(nameOrRef,PDFName_default)};PDFAcroTerminal2.prototype.getWidgets=function(){var kidDicts=this.Kids();if(!kidDicts)return[PDFWidgetAnnotation_default.fromDict(this.dict)];var widgets=new Array(kidDicts.size());for(var idx3=0,len2=kidDicts.size();idx3<len2;idx3++){var dict=kidDicts.lookup(idx3,PDFDict_default);widgets[idx3]=PDFWidgetAnnotation_default.fromDict(dict)}return widgets};PDFAcroTerminal2.prototype.addWidget=function(ref){var Kids=this.normalizedEntries().Kids;Kids.push(ref)};PDFAcroTerminal2.prototype.removeWidget=function(idx3){var kidDicts=this.Kids();if(!kidDicts){if(idx3!==0)throw new IndexOutOfBoundsError(idx3,0,0);this.setKids([])}else{if(idx3<0||idx3>kidDicts.size()){throw new IndexOutOfBoundsError(idx3,0,kidDicts.size())}kidDicts.remove(idx3)}};PDFAcroTerminal2.prototype.normalizedEntries=function(){var Kids=this.Kids();if(!Kids){Kids=this.dict.context.obj([this.ref]);this.dict.set(PDFName_default.of("Kids"),Kids)}return{Kids}};PDFAcroTerminal2.fromDict=function(dict,ref){return new PDFAcroTerminal2(dict,ref)};return PDFAcroTerminal2}(PDFAcroField_default);PDFAcroTerminal_default=PDFAcroTerminal});var PDFAcroButton,PDFAcroButton_default;var init_PDFAcroButton=__esm(()=>{init_tslib_es62();init_PDFString();init_PDFHexString();init_PDFArray();init_PDFName();init_PDFAcroTerminal();init_errors2();PDFAcroButton=function(_super){__extends(PDFAcroButton2,_super);function PDFAcroButton2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroButton2.prototype.Opt=function(){return this.dict.lookupMaybe(PDFName_default.of("Opt"),PDFString_default,PDFHexString_default,PDFArray_default)};PDFAcroButton2.prototype.setOpt=function(opt){this.dict.set(PDFName_default.of("Opt"),this.dict.context.obj(opt))};PDFAcroButton2.prototype.getExportValues=function(){var opt=this.Opt();if(!opt)return;if(opt instanceof PDFString_default||opt instanceof PDFHexString_default){return[opt]}var values2=[];for(var idx3=0,len2=opt.size();idx3<len2;idx3++){var value=opt.lookup(idx3);if(value instanceof PDFString_default||value instanceof PDFHexString_default){values2.push(value)}}return values2};PDFAcroButton2.prototype.removeExportValue=function(idx3){var opt=this.Opt();if(!opt)return;if(opt instanceof PDFString_default||opt instanceof PDFHexString_default){if(idx3!==0)throw new IndexOutOfBoundsError(idx3,0,0);this.setOpt([])}else{if(idx3<0||idx3>opt.size()){throw new IndexOutOfBoundsError(idx3,0,opt.size())}opt.remove(idx3)}};PDFAcroButton2.prototype.normalizeExportValues=function(){var _a,_b,_c,_d;var exportValues=(_a=this.getExportValues())!==null&&_a!==undefined?_a:[];var Opt=[];var widgets=this.getWidgets();for(var idx3=0,len2=widgets.length;idx3<len2;idx3++){var widget=widgets[idx3];var exportVal=(_b=exportValues[idx3])!==null&&_b!==undefined?_b:PDFHexString_default.fromText((_d=(_c=widget.getOnValue())===null||_c===undefined?undefined:_c.decodeText())!==null&&_d!==undefined?_d:"");Opt.push(exportVal)}this.setOpt(Opt)};PDFAcroButton2.prototype.addOpt=function(opt,useExistingOptIdx){var _a;this.normalizeExportValues();var optText=opt.decodeText();var existingIdx;if(useExistingOptIdx){var exportValues=(_a=this.getExportValues())!==null&&_a!==undefined?_a:[];for(var idx3=0,len2=exportValues.length;idx3<len2;idx3++){var exportVal=exportValues[idx3];if(exportVal.decodeText()===optText)existingIdx=idx3}}var Opt=this.Opt();Opt.push(opt);return existingIdx!==null&&existingIdx!==undefined?existingIdx:Opt.size()-1};PDFAcroButton2.prototype.addWidgetWithOpt=function(widget,opt,useExistingOptIdx){var optIdx=this.addOpt(opt,useExistingOptIdx);var apStateValue=PDFName_default.of(String(optIdx));this.addWidget(widget);return apStateValue};return PDFAcroButton2}(PDFAcroTerminal_default);PDFAcroButton_default=PDFAcroButton});var PDFAcroCheckBox,PDFAcroCheckBox_default;var init_PDFAcroCheckBox=__esm(()=>{init_tslib_es62();init_PDFName();init_PDFAcroButton();init_errors2();PDFAcroCheckBox=function(_super){__extends(PDFAcroCheckBox2,_super);function PDFAcroCheckBox2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroCheckBox2.prototype.setValue=function(value){var _a;var onValue=(_a=this.getOnValue())!==null&&_a!==undefined?_a:PDFName_default.of("Yes");if(value!==onValue&&value!==PDFName_default.of("Off")){throw new InvalidAcroFieldValueError}this.dict.set(PDFName_default.of("V"),value);var widgets=this.getWidgets();for(var idx3=0,len2=widgets.length;idx3<len2;idx3++){var widget=widgets[idx3];var state=widget.getOnValue()===value?value:PDFName_default.of("Off");widget.setAppearanceState(state)}};PDFAcroCheckBox2.prototype.getValue=function(){var v=this.V();if(v instanceof PDFName_default)return v;return PDFName_default.of("Off")};PDFAcroCheckBox2.prototype.getOnValue=function(){var widget=this.getWidgets()[0];return widget===null||widget===undefined?undefined:widget.getOnValue()};PDFAcroCheckBox2.fromDict=function(dict,ref){return new PDFAcroCheckBox2(dict,ref)};PDFAcroCheckBox2.create=function(context2){var dict=context2.obj({FT:"Btn",Kids:[]});var ref=context2.register(dict);return new PDFAcroCheckBox2(dict,ref)};return PDFAcroCheckBox2}(PDFAcroButton_default);PDFAcroCheckBox_default=PDFAcroCheckBox});var flag=function(bitIndex){return 1<<bitIndex},AcroFieldFlags,AcroButtonFlags,AcroTextFlags,AcroChoiceFlags;var init_flags=__esm(()=>{(function(AcroFieldFlags2){AcroFieldFlags2[AcroFieldFlags2["ReadOnly"]=flag(1-1)]="ReadOnly";AcroFieldFlags2[AcroFieldFlags2["Required"]=flag(2-1)]="Required";AcroFieldFlags2[AcroFieldFlags2["NoExport"]=flag(3-1)]="NoExport"})(AcroFieldFlags||(AcroFieldFlags={}));(function(AcroButtonFlags2){AcroButtonFlags2[AcroButtonFlags2["NoToggleToOff"]=flag(15-1)]="NoToggleToOff";AcroButtonFlags2[AcroButtonFlags2["Radio"]=flag(16-1)]="Radio";AcroButtonFlags2[AcroButtonFlags2["PushButton"]=flag(17-1)]="PushButton";AcroButtonFlags2[AcroButtonFlags2["RadiosInUnison"]=flag(26-1)]="RadiosInUnison"})(AcroButtonFlags||(AcroButtonFlags={}));(function(AcroTextFlags2){AcroTextFlags2[AcroTextFlags2["Multiline"]=flag(13-1)]="Multiline";AcroTextFlags2[AcroTextFlags2["Password"]=flag(14-1)]="Password";AcroTextFlags2[AcroTextFlags2["FileSelect"]=flag(21-1)]="FileSelect";AcroTextFlags2[AcroTextFlags2["DoNotSpellCheck"]=flag(23-1)]="DoNotSpellCheck";AcroTextFlags2[AcroTextFlags2["DoNotScroll"]=flag(24-1)]="DoNotScroll";AcroTextFlags2[AcroTextFlags2["Comb"]=flag(25-1)]="Comb";AcroTextFlags2[AcroTextFlags2["RichText"]=flag(26-1)]="RichText"})(AcroTextFlags||(AcroTextFlags={}));(function(AcroChoiceFlags2){AcroChoiceFlags2[AcroChoiceFlags2["Combo"]=flag(18-1)]="Combo";AcroChoiceFlags2[AcroChoiceFlags2["Edit"]=flag(19-1)]="Edit";AcroChoiceFlags2[AcroChoiceFlags2["Sort"]=flag(20-1)]="Sort";AcroChoiceFlags2[AcroChoiceFlags2["MultiSelect"]=flag(22-1)]="MultiSelect";AcroChoiceFlags2[AcroChoiceFlags2["DoNotSpellCheck"]=flag(23-1)]="DoNotSpellCheck";AcroChoiceFlags2[AcroChoiceFlags2["CommitOnSelChange"]=flag(27-1)]="CommitOnSelChange"})(AcroChoiceFlags||(AcroChoiceFlags={}))});var PDFAcroChoice,PDFAcroChoice_default;var init_PDFAcroChoice=__esm(()=>{init_tslib_es62();init_PDFAcroTerminal();init_PDFHexString();init_PDFString();init_PDFArray();init_PDFName();init_flags();init_errors2();PDFAcroChoice=function(_super){__extends(PDFAcroChoice2,_super);function PDFAcroChoice2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroChoice2.prototype.setValues=function(values2){if(this.hasFlag(AcroChoiceFlags.Combo)&&!this.hasFlag(AcroChoiceFlags.Edit)&&!this.valuesAreValid(values2)){throw new InvalidAcroFieldValueError}if(values2.length===0){this.dict.delete(PDFName_default.of("V"))}if(values2.length===1){this.dict.set(PDFName_default.of("V"),values2[0])}if(values2.length>1){if(!this.hasFlag(AcroChoiceFlags.MultiSelect)){throw new MultiSelectValueError}this.dict.set(PDFName_default.of("V"),this.dict.context.obj(values2))}this.updateSelectedIndices(values2)};PDFAcroChoice2.prototype.valuesAreValid=function(values2){var options=this.getOptions();var _loop_1=function(idx4,len3){var val=values2[idx4].decodeText();if(!options.find(function(o){return val===(o.display||o.value).decodeText()})){return{value:false}}};for(var idx3=0,len2=values2.length;idx3<len2;idx3++){var state_1=_loop_1(idx3,len2);if(typeof state_1==="object")return state_1.value}return true};PDFAcroChoice2.prototype.updateSelectedIndices=function(values2){if(values2.length>1){var indices=new Array(values2.length);var options=this.getOptions();var _loop_2=function(idx4,len3){var val=values2[idx4].decodeText();indices[idx4]=options.findIndex(function(o){return val===(o.display||o.value).decodeText()})};for(var idx3=0,len2=values2.length;idx3<len2;idx3++){_loop_2(idx3,len2)}this.dict.set(PDFName_default.of("I"),this.dict.context.obj(indices.sort()))}else{this.dict.delete(PDFName_default.of("I"))}};PDFAcroChoice2.prototype.getValues=function(){var v=this.V();if(v instanceof PDFString_default||v instanceof PDFHexString_default)return[v];if(v instanceof PDFArray_default){var values2=[];for(var idx3=0,len2=v.size();idx3<len2;idx3++){var value=v.lookup(idx3);if(value instanceof PDFString_default||value instanceof PDFHexString_default){values2.push(value)}}return values2}return[]};PDFAcroChoice2.prototype.Opt=function(){return this.dict.lookupMaybe(PDFName_default.of("Opt"),PDFString_default,PDFHexString_default,PDFArray_default)};PDFAcroChoice2.prototype.setOptions=function(options){var newOpt=new Array(options.length);for(var idx3=0,len2=options.length;idx3<len2;idx3++){var _a=options[idx3],value=_a.value,display=_a.display;newOpt[idx3]=this.dict.context.obj([value,display||value])}this.dict.set(PDFName_default.of("Opt"),this.dict.context.obj(newOpt))};PDFAcroChoice2.prototype.getOptions=function(){var Opt=this.Opt();if(Opt instanceof PDFString_default||Opt instanceof PDFHexString_default){return[{value:Opt,display:Opt}]}if(Opt instanceof PDFArray_default){var res=[];for(var idx3=0,len2=Opt.size();idx3<len2;idx3++){var item=Opt.lookup(idx3);if(item instanceof PDFString_default||item instanceof PDFHexString_default){res.push({value:item,display:item})}if(item instanceof PDFArray_default){if(item.size()>0){var first=item.lookup(0,PDFString_default,PDFHexString_default);var second=item.lookupMaybe(1,PDFString_default,PDFHexString_default);res.push({value:first,display:second||first})}}}return res}return[]};return PDFAcroChoice2}(PDFAcroTerminal_default);PDFAcroChoice_default=PDFAcroChoice});var PDFAcroComboBox,PDFAcroComboBox_default;var init_PDFAcroComboBox=__esm(()=>{init_tslib_es62();init_PDFAcroChoice();init_flags();PDFAcroComboBox=function(_super){__extends(PDFAcroComboBox2,_super);function PDFAcroComboBox2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroComboBox2.fromDict=function(dict,ref){return new PDFAcroComboBox2(dict,ref)};PDFAcroComboBox2.create=function(context2){var dict=context2.obj({FT:"Ch",Ff:AcroChoiceFlags.Combo,Kids:[]});var ref=context2.register(dict);return new PDFAcroComboBox2(dict,ref)};return PDFAcroComboBox2}(PDFAcroChoice_default);PDFAcroComboBox_default=PDFAcroComboBox});var PDFAcroNonTerminal,PDFAcroNonTerminal_default;var init_PDFAcroNonTerminal=__esm(()=>{init_tslib_es62();init_PDFName();init_PDFAcroField();PDFAcroNonTerminal=function(_super){__extends(PDFAcroNonTerminal2,_super);function PDFAcroNonTerminal2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroNonTerminal2.prototype.addField=function(field){var Kids=this.normalizedEntries().Kids;Kids===null||Kids===undefined||Kids.push(field)};PDFAcroNonTerminal2.prototype.normalizedEntries=function(){var Kids=this.Kids();if(!Kids){Kids=this.dict.context.obj([]);this.dict.set(PDFName_default.of("Kids"),Kids)}return{Kids}};PDFAcroNonTerminal2.fromDict=function(dict,ref){return new PDFAcroNonTerminal2(dict,ref)};PDFAcroNonTerminal2.create=function(context2){var dict=context2.obj({});var ref=context2.register(dict);return new PDFAcroNonTerminal2(dict,ref)};return PDFAcroNonTerminal2}(PDFAcroField_default);PDFAcroNonTerminal_default=PDFAcroNonTerminal});var PDFAcroSignature,PDFAcroSignature_default;var init_PDFAcroSignature=__esm(()=>{init_tslib_es62();init_PDFAcroTerminal();PDFAcroSignature=function(_super){__extends(PDFAcroSignature2,_super);function PDFAcroSignature2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroSignature2.fromDict=function(dict,ref){return new PDFAcroSignature2(dict,ref)};return PDFAcroSignature2}(PDFAcroTerminal_default);PDFAcroSignature_default=PDFAcroSignature});var PDFAcroText,PDFAcroText_default;var init_PDFAcroText=__esm(()=>{init_tslib_es62();init_PDFNumber();init_PDFString();init_PDFHexString();init_PDFName();init_PDFAcroTerminal();PDFAcroText=function(_super){__extends(PDFAcroText2,_super);function PDFAcroText2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroText2.prototype.MaxLen=function(){var maxLen=this.dict.lookup(PDFName_default.of("MaxLen"));if(maxLen instanceof PDFNumber_default)return maxLen;return};PDFAcroText2.prototype.Q=function(){var q=this.dict.lookup(PDFName_default.of("Q"));if(q instanceof PDFNumber_default)return q;return};PDFAcroText2.prototype.setMaxLength=function(maxLength){this.dict.set(PDFName_default.of("MaxLen"),PDFNumber_default.of(maxLength))};PDFAcroText2.prototype.removeMaxLength=function(){this.dict.delete(PDFName_default.of("MaxLen"))};PDFAcroText2.prototype.getMaxLength=function(){var _a;return(_a=this.MaxLen())===null||_a===undefined?undefined:_a.asNumber()};PDFAcroText2.prototype.setQuadding=function(quadding){this.dict.set(PDFName_default.of("Q"),PDFNumber_default.of(quadding))};PDFAcroText2.prototype.getQuadding=function(){var _a;return(_a=this.Q())===null||_a===undefined?undefined:_a.asNumber()};PDFAcroText2.prototype.setValue=function(value){this.dict.set(PDFName_default.of("V"),value)};PDFAcroText2.prototype.removeValue=function(){this.dict.delete(PDFName_default.of("V"))};PDFAcroText2.prototype.getValue=function(){var v=this.V();if(v instanceof PDFString_default||v instanceof PDFHexString_default)return v;return};PDFAcroText2.fromDict=function(dict,ref){return new PDFAcroText2(dict,ref)};PDFAcroText2.create=function(context2){var dict=context2.obj({FT:"Tx",Kids:[]});var ref=context2.register(dict);return new PDFAcroText2(dict,ref)};return PDFAcroText2}(PDFAcroTerminal_default);PDFAcroText_default=PDFAcroText});var PDFAcroPushButton,PDFAcroPushButton_default;var init_PDFAcroPushButton=__esm(()=>{init_tslib_es62();init_PDFAcroButton();init_flags();PDFAcroPushButton=function(_super){__extends(PDFAcroPushButton2,_super);function PDFAcroPushButton2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroPushButton2.fromDict=function(dict,ref){return new PDFAcroPushButton2(dict,ref)};PDFAcroPushButton2.create=function(context2){var dict=context2.obj({FT:"Btn",Ff:AcroButtonFlags.PushButton,Kids:[]});var ref=context2.register(dict);return new PDFAcroPushButton2(dict,ref)};return PDFAcroPushButton2}(PDFAcroButton_default);PDFAcroPushButton_default=PDFAcroPushButton});var PDFAcroRadioButton,PDFAcroRadioButton_default;var init_PDFAcroRadioButton=__esm(()=>{init_tslib_es62();init_PDFName();init_PDFAcroButton();init_flags();init_errors2();PDFAcroRadioButton=function(_super){__extends(PDFAcroRadioButton2,_super);function PDFAcroRadioButton2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroRadioButton2.prototype.setValue=function(value){var onValues=this.getOnValues();if(!onValues.includes(value)&&value!==PDFName_default.of("Off")){throw new InvalidAcroFieldValueError}this.dict.set(PDFName_default.of("V"),value);var widgets=this.getWidgets();for(var idx3=0,len2=widgets.length;idx3<len2;idx3++){var widget=widgets[idx3];var state=widget.getOnValue()===value?value:PDFName_default.of("Off");widget.setAppearanceState(state)}};PDFAcroRadioButton2.prototype.getValue=function(){var v=this.V();if(v instanceof PDFName_default)return v;return PDFName_default.of("Off")};PDFAcroRadioButton2.prototype.getOnValues=function(){var widgets=this.getWidgets();var onValues=[];for(var idx3=0,len2=widgets.length;idx3<len2;idx3++){var onValue=widgets[idx3].getOnValue();if(onValue)onValues.push(onValue)}return onValues};PDFAcroRadioButton2.fromDict=function(dict,ref){return new PDFAcroRadioButton2(dict,ref)};PDFAcroRadioButton2.create=function(context2){var dict=context2.obj({FT:"Btn",Ff:AcroButtonFlags.Radio,Kids:[]});var ref=context2.register(dict);return new PDFAcroRadioButton2(dict,ref)};return PDFAcroRadioButton2}(PDFAcroButton_default);PDFAcroRadioButton_default=PDFAcroRadioButton});var PDFAcroListBox,PDFAcroListBox_default;var init_PDFAcroListBox=__esm(()=>{init_tslib_es62();init_PDFAcroChoice();PDFAcroListBox=function(_super){__extends(PDFAcroListBox2,_super);function PDFAcroListBox2(){return _super!==null&&_super.apply(this,arguments)||this}PDFAcroListBox2.fromDict=function(dict,ref){return new PDFAcroListBox2(dict,ref)};PDFAcroListBox2.create=function(context2){var dict=context2.obj({FT:"Ch",Kids:[]});var ref=context2.register(dict);return new PDFAcroListBox2(dict,ref)};return PDFAcroListBox2}(PDFAcroChoice_default);PDFAcroListBox_default=PDFAcroListBox});var createPDFAcroFields=function(kidDicts){if(!kidDicts)return[];var kids=[];for(var idx3=0,len2=kidDicts.size();idx3<len2;idx3++){var ref=kidDicts.get(idx3);var dict=kidDicts.lookup(idx3);if(ref instanceof PDFRef_default&&dict instanceof PDFDict_default){kids.push([createPDFAcroField(dict,ref),ref])}}return kids},createPDFAcroField=function(dict,ref){var isNonTerminal=isNonTerminalAcroField(dict);if(isNonTerminal)return PDFAcroNonTerminal_default.fromDict(dict,ref);return createPDFAcroTerminal(dict,ref)},isNonTerminalAcroField=function(dict){var kids=dict.lookup(PDFName_default.of("Kids"));if(kids instanceof PDFArray_default){for(var idx3=0,len2=kids.size();idx3<len2;idx3++){var kid=kids.lookup(idx3);var kidIsField=kid instanceof PDFDict_default&&kid.has(PDFName_default.of("T"));if(kidIsField)return true}}return false},createPDFAcroTerminal=function(dict,ref){var ftNameOrRef=getInheritableAttribute(dict,PDFName_default.of("FT"));var type=dict.context.lookup(ftNameOrRef,PDFName_default);if(type===PDFName_default.of("Btn"))return createPDFAcroButton(dict,ref);if(type===PDFName_default.of("Ch"))return createPDFAcroChoice(dict,ref);if(type===PDFName_default.of("Tx"))return PDFAcroText_default.fromDict(dict,ref);if(type===PDFName_default.of("Sig"))return PDFAcroSignature_default.fromDict(dict,ref);return PDFAcroTerminal_default.fromDict(dict,ref)},createPDFAcroButton=function(dict,ref){var _a;var ffNumberOrRef=getInheritableAttribute(dict,PDFName_default.of("Ff"));var ffNumber=dict.context.lookupMaybe(ffNumberOrRef,PDFNumber_default);var flags=(_a=ffNumber===null||ffNumber===undefined?undefined:ffNumber.asNumber())!==null&&_a!==undefined?_a:0;if(flagIsSet(flags,AcroButtonFlags.PushButton)){return PDFAcroPushButton_default.fromDict(dict,ref)}else if(flagIsSet(flags,AcroButtonFlags.Radio)){return PDFAcroRadioButton_default.fromDict(dict,ref)}else{return PDFAcroCheckBox_default.fromDict(dict,ref)}},createPDFAcroChoice=function(dict,ref){var _a;var ffNumberOrRef=getInheritableAttribute(dict,PDFName_default.of("Ff"));var ffNumber=dict.context.lookupMaybe(ffNumberOrRef,PDFNumber_default);var flags=(_a=ffNumber===null||ffNumber===undefined?undefined:ffNumber.asNumber())!==null&&_a!==undefined?_a:0;if(flagIsSet(flags,AcroChoiceFlags.Combo)){return PDFAcroComboBox_default.fromDict(dict,ref)}else{return PDFAcroListBox_default.fromDict(dict,ref)}},flagIsSet=function(flags,flag2){return(flags&flag2)!==0},getInheritableAttribute=function(startNode,name){var attribute;ascend(startNode,function(node){if(!attribute)attribute=node.get(name)});return attribute},ascend=function(startNode,visitor){visitor(startNode);var Parent=startNode.lookupMaybe(PDFName_default.of("Parent"),PDFDict_default);if(Parent)ascend(Parent,visitor)};var init_utils3=__esm(()=>{init_PDFNumber();init_PDFDict();init_PDFName();init_PDFArray();init_PDFRef();init_PDFAcroTerminal();init_PDFAcroNonTerminal();init_PDFAcroSignature();init_PDFAcroText();init_PDFAcroPushButton();init_PDFAcroRadioButton();init_PDFAcroCheckBox();init_PDFAcroComboBox();init_PDFAcroListBox();init_flags()});var PDFAcroForm,PDFAcroForm_default;var init_PDFAcroForm=__esm(()=>{init_PDFDict();init_PDFArray();init_PDFName();init_PDFAcroNonTerminal();init_utils3();PDFAcroForm=function(){function PDFAcroForm2(dict){this.dict=dict}PDFAcroForm2.prototype.Fields=function(){var fields6=this.dict.lookup(PDFName_default.of("Fields"));if(fields6 instanceof PDFArray_default)return fields6;return};PDFAcroForm2.prototype.getFields=function(){var Fields=this.normalizedEntries().Fields;var fields6=new Array(Fields.size());for(var idx3=0,len2=Fields.size();idx3<len2;idx3++){var ref=Fields.get(idx3);var dict=Fields.lookup(idx3,PDFDict_default);fields6[idx3]=[createPDFAcroField(dict,ref),ref]}return fields6};PDFAcroForm2.prototype.getAllFields=function(){var allFields=[];var pushFields=function(fields6){if(!fields6)return;for(var idx3=0,len2=fields6.length;idx3<len2;idx3++){var field=fields6[idx3];allFields.push(field);var fieldModel=field[0];if(fieldModel instanceof PDFAcroNonTerminal_default){pushFields(createPDFAcroFields(fieldModel.Kids()))}}};pushFields(this.getFields());return allFields};PDFAcroForm2.prototype.addField=function(field){var Fields=this.normalizedEntries().Fields;Fields===null||Fields===undefined||Fields.push(field)};PDFAcroForm2.prototype.removeField=function(field){var parent=field.getParent();var fields6=parent===undefined?this.normalizedEntries().Fields:parent.Kids();var index=fields6===null||fields6===undefined?undefined:fields6.indexOf(field.ref);if(fields6===undefined||index===undefined){throw new Error("Tried to remove inexistent field "+field.getFullyQualifiedName())}fields6.remove(index);if(parent!==undefined&&fields6.size()===0){this.removeField(parent)}};PDFAcroForm2.prototype.normalizedEntries=function(){var Fields=this.Fields();if(!Fields){Fields=this.dict.context.obj([]);this.dict.set(PDFName_default.of("Fields"),Fields)}return{Fields}};PDFAcroForm2.fromDict=function(dict){return new PDFAcroForm2(dict)};PDFAcroForm2.create=function(context2){var dict=context2.obj({Fields:[]});return new PDFAcroForm2(dict)};return PDFAcroForm2}();PDFAcroForm_default=PDFAcroForm});var init_acroform=__esm(()=>{init_PDFAcroButton();init_PDFAcroCheckBox();init_PDFAcroChoice();init_PDFAcroComboBox();init_PDFAcroField();init_PDFAcroForm();init_PDFAcroListBox();init_PDFAcroNonTerminal();init_PDFAcroPushButton();init_PDFAcroRadioButton();init_PDFAcroSignature();init_PDFAcroTerminal();init_PDFAcroText();init_flags();init_utils3()});var PDFCatalog,PDFCatalog_default;var init_PDFCatalog=__esm(()=>{init_tslib_es62();init_PDFDict();init_PDFName();init_acroform();init_ViewerPreferences();PDFCatalog=function(_super){__extends(PDFCatalog2,_super);function PDFCatalog2(){return _super!==null&&_super.apply(this,arguments)||this}PDFCatalog2.prototype.Pages=function(){return this.lookup(PDFName_default.of("Pages"),PDFDict_default)};PDFCatalog2.prototype.AcroForm=function(){return this.lookupMaybe(PDFName_default.of("AcroForm"),PDFDict_default)};PDFCatalog2.prototype.getAcroForm=function(){var dict=this.AcroForm();if(!dict)return;return PDFAcroForm_default.fromDict(dict)};PDFCatalog2.prototype.getOrCreateAcroForm=function(){var acroForm=this.getAcroForm();if(!acroForm){acroForm=PDFAcroForm_default.create(this.context);var acroFormRef=this.context.register(acroForm.dict);this.set(PDFName_default.of("AcroForm"),acroFormRef)}return acroForm};PDFCatalog2.prototype.ViewerPreferences=function(){return this.lookupMaybe(PDFName_default.of("ViewerPreferences"),PDFDict_default)};PDFCatalog2.prototype.getViewerPreferences=function(){var dict=this.ViewerPreferences();if(!dict)return;return ViewerPreferences_default.fromDict(dict)};PDFCatalog2.prototype.getOrCreateViewerPreferences=function(){var viewerPrefs=this.getViewerPreferences();if(!viewerPrefs){viewerPrefs=ViewerPreferences_default.create(this.context);var viewerPrefsRef=this.context.register(viewerPrefs.dict);this.set(PDFName_default.of("ViewerPreferences"),viewerPrefsRef)}return viewerPrefs};PDFCatalog2.prototype.insertLeafNode=function(leafRef,index){var pagesRef=this.get(PDFName_default.of("Pages"));var maybeParentRef=this.Pages().insertLeafNode(leafRef,index);return maybeParentRef||pagesRef};PDFCatalog2.prototype.removeLeafNode=function(index){this.Pages().removeLeafNode(index)};PDFCatalog2.withContextAndPages=function(context2,pages){var dict=new Map;dict.set(PDFName_default.of("Type"),PDFName_default.of("Catalog"));dict.set(PDFName_default.of("Pages"),pages);return new PDFCatalog2(dict,context2)};PDFCatalog2.fromMapWithContext=function(map,context2){return new PDFCatalog2(map,context2)};return PDFCatalog2}(PDFDict_default);PDFCatalog_default=PDFCatalog});var PDFPageTree,PDFPageTree_default;var init_PDFPageTree=__esm(()=>{init_tslib_es62();init_PDFArray();init_PDFDict();init_PDFName();init_PDFNumber();init_PDFPageLeaf();init_errors2();PDFPageTree=function(_super){__extends(PDFPageTree2,_super);function PDFPageTree2(){return _super!==null&&_super.apply(this,arguments)||this}PDFPageTree2.prototype.Parent=function(){return this.lookup(PDFName_default.of("Parent"))};PDFPageTree2.prototype.Kids=function(){return this.lookup(PDFName_default.of("Kids"),PDFArray_default)};PDFPageTree2.prototype.Count=function(){return this.lookup(PDFName_default.of("Count"),PDFNumber_default)};PDFPageTree2.prototype.pushTreeNode=function(treeRef){var Kids=this.Kids();Kids.push(treeRef)};PDFPageTree2.prototype.pushLeafNode=function(leafRef){var Kids=this.Kids();this.insertLeafKid(Kids.size(),leafRef)};PDFPageTree2.prototype.insertLeafNode=function(leafRef,targetIndex){var Kids=this.Kids();var Count=this.Count().asNumber();if(targetIndex>Count){throw new InvalidTargetIndexError(targetIndex,Count)}var leafsRemainingUntilTarget=targetIndex;for(var idx3=0,len2=Kids.size();idx3<len2;idx3++){if(leafsRemainingUntilTarget===0){this.insertLeafKid(idx3,leafRef);return}var kidRef=Kids.get(idx3);var kid=this.context.lookup(kidRef);if(kid instanceof PDFPageTree2){if(kid.Count().asNumber()>leafsRemainingUntilTarget){return kid.insertLeafNode(leafRef,leafsRemainingUntilTarget)||kidRef}else{leafsRemainingUntilTarget-=kid.Count().asNumber()}}if(kid instanceof PDFPageLeaf_default){leafsRemainingUntilTarget-=1}}if(leafsRemainingUntilTarget===0){this.insertLeafKid(Kids.size(),leafRef);return}throw new CorruptPageTreeError(targetIndex,"insertLeafNode")};PDFPageTree2.prototype.removeLeafNode=function(targetIndex,prune){if(prune===undefined){prune=true}var Kids=this.Kids();var Count=this.Count().asNumber();if(targetIndex>=Count){throw new InvalidTargetIndexError(targetIndex,Count)}var leafsRemainingUntilTarget=targetIndex;for(var idx3=0,len2=Kids.size();idx3<len2;idx3++){var kidRef=Kids.get(idx3);var kid=this.context.lookup(kidRef);if(kid instanceof PDFPageTree2){if(kid.Count().asNumber()>leafsRemainingUntilTarget){kid.removeLeafNode(leafsRemainingUntilTarget,prune);if(prune&&kid.Kids().size()===0)Kids.remove(idx3);return}else{leafsRemainingUntilTarget-=kid.Count().asNumber()}}if(kid instanceof PDFPageLeaf_default){if(leafsRemainingUntilTarget===0){this.removeKid(idx3);return}else{leafsRemainingUntilTarget-=1}}}throw new CorruptPageTreeError(targetIndex,"removeLeafNode")};PDFPageTree2.prototype.ascend=function(visitor){visitor(this);var Parent=this.Parent();if(Parent)Parent.ascend(visitor)};PDFPageTree2.prototype.traverse=function(visitor){var Kids=this.Kids();for(var idx3=0,len2=Kids.size();idx3<len2;idx3++){var kidRef=Kids.get(idx3);var kid=this.context.lookup(kidRef);if(kid instanceof PDFPageTree2)kid.traverse(visitor);visitor(kid,kidRef)}};PDFPageTree2.prototype.insertLeafKid=function(kidIdx,leafRef){var Kids=this.Kids();this.ascend(function(node){var newCount=node.Count().asNumber()+1;node.set(PDFName_default.of("Count"),PDFNumber_default.of(newCount))});Kids.insert(kidIdx,leafRef)};PDFPageTree2.prototype.removeKid=function(kidIdx){var Kids=this.Kids();var kid=Kids.lookup(kidIdx);if(kid instanceof PDFPageLeaf_default){this.ascend(function(node){var newCount=node.Count().asNumber()-1;node.set(PDFName_default.of("Count"),PDFNumber_default.of(newCount))})}Kids.remove(kidIdx)};PDFPageTree2.withContext=function(context2,parent){var dict=new Map;dict.set(PDFName_default.of("Type"),PDFName_default.of("Pages"));dict.set(PDFName_default.of("Kids"),context2.obj([]));dict.set(PDFName_default.of("Count"),context2.obj(0));if(parent)dict.set(PDFName_default.of("Parent"),parent);return new PDFPageTree2(dict,context2)};PDFPageTree2.fromMapWithContext=function(map,context2){return new PDFPageTree2(map,context2)};return PDFPageTree2}(PDFDict_default);PDFPageTree_default=PDFPageTree});var IsDigit,IsNumericPrefix,IsNumeric,idx3,len2;var init_Numeric=__esm(()=>{init_CharCodes();IsDigit=new Uint8Array(256);IsDigit[CharCodes_default.Zero]=1;IsDigit[CharCodes_default.One]=1;IsDigit[CharCodes_default.Two]=1;IsDigit[CharCodes_default.Three]=1;IsDigit[CharCodes_default.Four]=1;IsDigit[CharCodes_default.Five]=1;IsDigit[CharCodes_default.Six]=1;IsDigit[CharCodes_default.Seven]=1;IsDigit[CharCodes_default.Eight]=1;IsDigit[CharCodes_default.Nine]=1;IsNumericPrefix=new Uint8Array(256);IsNumericPrefix[CharCodes_default.Period]=1;IsNumericPrefix[CharCodes_default.Plus]=1;IsNumericPrefix[CharCodes_default.Minus]=1;IsNumeric=new Uint8Array(256);for(idx3=0,len2=256;idx3<len2;idx3++){IsNumeric[idx3]=IsDigit[idx3]||IsNumericPrefix[idx3]?1:0}});var Newline,CarriageReturn,BaseParser,BaseParser_default;var init_BaseParser=__esm(()=>{init_errors2();init_CharCodes();init_Numeric();init_Whitespace();init_utils2();Newline=CharCodes_default.Newline;CarriageReturn=CharCodes_default.CarriageReturn;BaseParser=function(){function BaseParser2(bytes,capNumbers){if(capNumbers===undefined){capNumbers=false}this.bytes=bytes;this.capNumbers=capNumbers}BaseParser2.prototype.parseRawInt=function(){var value="";while(!this.bytes.done()){var byte=this.bytes.peek();if(!IsDigit[byte])break;value+=charFromCode(this.bytes.next())}var numberValue=Number(value);if(!value||!isFinite(numberValue)){throw new NumberParsingError(this.bytes.position(),value)}return numberValue};BaseParser2.prototype.parseRawNumber=function(){var value="";while(!this.bytes.done()){var byte=this.bytes.peek();if(!IsNumeric[byte])break;value+=charFromCode(this.bytes.next());if(byte===CharCodes_default.Period)break}while(!this.bytes.done()){var byte=this.bytes.peek();if(!IsDigit[byte])break;value+=charFromCode(this.bytes.next())}var numberValue=Number(value);if(!value||!isFinite(numberValue)){throw new NumberParsingError(this.bytes.position(),value)}if(numberValue>Number.MAX_SAFE_INTEGER){if(this.capNumbers){var msg="Parsed number that is too large for some PDF readers: "+value+", using Number.MAX_SAFE_INTEGER instead.";console.warn(msg);return Number.MAX_SAFE_INTEGER}else{var msg="Parsed number that is too large for some PDF readers: "+value+", not capping.";console.warn(msg)}}return numberValue};BaseParser2.prototype.skipWhitespace=function(){while(!this.bytes.done()&&IsWhitespace[this.bytes.peek()]){this.bytes.next()}};BaseParser2.prototype.skipLine=function(){while(!this.bytes.done()){var byte=this.bytes.peek();if(byte===Newline||byte===CarriageReturn)return;this.bytes.next()}};BaseParser2.prototype.skipComment=function(){if(this.bytes.peek()!==CharCodes_default.Percent)return false;while(!this.bytes.done()){var byte=this.bytes.peek();if(byte===Newline||byte===CarriageReturn)return true;this.bytes.next()}return true};BaseParser2.prototype.skipWhitespaceAndComments=function(){this.skipWhitespace();while(this.skipComment())this.skipWhitespace()};BaseParser2.prototype.matchKeyword=function(keyword){var initialOffset=this.bytes.offset();for(var idx4=0,len3=keyword.length;idx4<len3;idx4++){if(this.bytes.done()||this.bytes.next()!==keyword[idx4]){this.bytes.moveTo(initialOffset);return false}}return true};return BaseParser2}();BaseParser_default=BaseParser});var ByteStream,ByteStream_default;var init_ByteStream=__esm(()=>{init_errors2();init_decode();init_CharCodes();ByteStream=function(){function ByteStream2(bytes){this.idx=0;this.line=0;this.column=0;this.bytes=bytes;this.length=this.bytes.length}ByteStream2.prototype.moveTo=function(offset){this.idx=offset};ByteStream2.prototype.next=function(){var byte=this.bytes[this.idx++];if(byte===CharCodes_default.Newline){this.line+=1;this.column=0}else{this.column+=1}return byte};ByteStream2.prototype.assertNext=function(expected){if(this.peek()!==expected){throw new NextByteAssertionError(this.position(),expected,this.peek())}return this.next()};ByteStream2.prototype.peek=function(){return this.bytes[this.idx]};ByteStream2.prototype.peekAhead=function(steps){return this.bytes[this.idx+steps]};ByteStream2.prototype.peekAt=function(offset){return this.bytes[offset]};ByteStream2.prototype.done=function(){return this.idx>=this.length};ByteStream2.prototype.offset=function(){return this.idx};ByteStream2.prototype.slice=function(start,end){return this.bytes.slice(start,end)};ByteStream2.prototype.position=function(){return{line:this.line,column:this.column,offset:this.idx}};ByteStream2.of=function(bytes){return new ByteStream2(bytes)};ByteStream2.fromPDFRawStream=function(rawStream){return ByteStream2.of(decodePDFRawStream(rawStream).decode())};return ByteStream2}();ByteStream_default=ByteStream});var Space,CarriageReturn2,Newline2,stream,endstream,Keywords;var init_Keywords=__esm(()=>{init_tslib_es62();init_CharCodes();Space=CharCodes_default.Space;CarriageReturn2=CharCodes_default.CarriageReturn;Newline2=CharCodes_default.Newline;stream=[CharCodes_default.s,CharCodes_default.t,CharCodes_default.r,CharCodes_default.e,CharCodes_default.a,CharCodes_default.m];endstream=[CharCodes_default.e,CharCodes_default.n,CharCodes_default.d,CharCodes_default.s,CharCodes_default.t,CharCodes_default.r,CharCodes_default.e,CharCodes_default.a,CharCodes_default.m];Keywords={header:[CharCodes_default.Percent,CharCodes_default.P,CharCodes_default.D,CharCodes_default.F,CharCodes_default.Dash],eof:[CharCodes_default.Percent,CharCodes_default.Percent,CharCodes_default.E,CharCodes_default.O,CharCodes_default.F],obj:[CharCodes_default.o,CharCodes_default.b,CharCodes_default.j],endobj:[CharCodes_default.e,CharCodes_default.n,CharCodes_default.d,CharCodes_default.o,CharCodes_default.b,CharCodes_default.j],xref:[CharCodes_default.x,CharCodes_default.r,CharCodes_default.e,CharCodes_default.f],trailer:[CharCodes_default.t,CharCodes_default.r,CharCodes_default.a,CharCodes_default.i,CharCodes_default.l,CharCodes_default.e,CharCodes_default.r],startxref:[CharCodes_default.s,CharCodes_default.t,CharCodes_default.a,CharCodes_default.r,CharCodes_default.t,CharCodes_default.x,CharCodes_default.r,CharCodes_default.e,CharCodes_default.f],true:[CharCodes_default.t,CharCodes_default.r,CharCodes_default.u,CharCodes_default.e],false:[CharCodes_default.f,CharCodes_default.a,CharCodes_default.l,CharCodes_default.s,CharCodes_default.e],null:[CharCodes_default.n,CharCodes_default.u,CharCodes_default.l,CharCodes_default.l],stream,streamEOF1:__spreadArrays(stream,[Space,CarriageReturn2,Newline2]),streamEOF2:__spreadArrays(stream,[CarriageReturn2,Newline2]),streamEOF3:__spreadArrays(stream,[CarriageReturn2]),streamEOF4:__spreadArrays(stream,[Newline2]),endstream,EOF1endstream:__spreadArrays([CarriageReturn2,Newline2],endstream),EOF2endstream:__spreadArrays([CarriageReturn2],endstream),EOF3endstream:__spreadArrays([Newline2],endstream)}});var PDFObjectParser,PDFObjectParser_default;var init_PDFObjectParser=__esm(()=>{init_tslib_es62();init_errors2();init_PDFArray();init_PDFBool();init_PDFDict();init_PDFHexString();init_PDFName();init_PDFNull();init_PDFNumber();init_PDFRawStream();init_PDFRef();init_PDFString();init_BaseParser();init_ByteStream();init_PDFCatalog();init_PDFPageLeaf();init_PDFPageTree();init_CharCodes();init_Delimiters();init_Keywords();init_Numeric();init_Whitespace();init_utils2();PDFObjectParser=function(_super){__extends(PDFObjectParser2,_super);function PDFObjectParser2(byteStream,context2,capNumbers){if(capNumbers===undefined){capNumbers=false}var _this=_super.call(this,byteStream,capNumbers)||this;_this.context=context2;return _this}PDFObjectParser2.prototype.parseObject=function(){this.skipWhitespaceAndComments();if(this.matchKeyword(Keywords.true))return PDFBool_default.True;if(this.matchKeyword(Keywords.false))return PDFBool_default.False;if(this.matchKeyword(Keywords.null))return PDFNull_default;var byte=this.bytes.peek();if(byte===CharCodes_default.LessThan&&this.bytes.peekAhead(1)===CharCodes_default.LessThan){return this.parseDictOrStream()}if(byte===CharCodes_default.LessThan)return this.parseHexString();if(byte===CharCodes_default.LeftParen)return this.parseString();if(byte===CharCodes_default.ForwardSlash)return this.parseName();if(byte===CharCodes_default.LeftSquareBracket)return this.parseArray();if(IsNumeric[byte])return this.parseNumberOrRef();throw new PDFObjectParsingError(this.bytes.position(),byte)};PDFObjectParser2.prototype.parseNumberOrRef=function(){var firstNum=this.parseRawNumber();this.skipWhitespaceAndComments();var lookaheadStart=this.bytes.offset();if(IsDigit[this.bytes.peek()]){var secondNum=this.parseRawNumber();this.skipWhitespaceAndComments();if(this.bytes.peek()===CharCodes_default.R){this.bytes.assertNext(CharCodes_default.R);return PDFRef_default.of(firstNum,secondNum)}}this.bytes.moveTo(lookaheadStart);return PDFNumber_default.of(firstNum)};PDFObjectParser2.prototype.parseHexString=function(){var value="";this.bytes.assertNext(CharCodes_default.LessThan);while(!this.bytes.done()&&this.bytes.peek()!==CharCodes_default.GreaterThan){value+=charFromCode(this.bytes.next())}this.bytes.assertNext(CharCodes_default.GreaterThan);return PDFHexString_default.of(value)};PDFObjectParser2.prototype.parseString=function(){var nestingLvl=0;var isEscaped=false;var value="";while(!this.bytes.done()){var byte=this.bytes.next();value+=charFromCode(byte);if(!isEscaped){if(byte===CharCodes_default.LeftParen)nestingLvl+=1;if(byte===CharCodes_default.RightParen)nestingLvl-=1}if(byte===CharCodes_default.BackSlash){isEscaped=!isEscaped}else if(isEscaped){isEscaped=false}if(nestingLvl===0){return PDFString_default.of(value.substring(1,value.length-1))}}throw new UnbalancedParenthesisError(this.bytes.position())};PDFObjectParser2.prototype.parseName=function(){this.bytes.assertNext(CharCodes_default.ForwardSlash);var name="";while(!this.bytes.done()){var byte=this.bytes.peek();if(IsWhitespace[byte]||IsDelimiter[byte])break;name+=charFromCode(byte);this.bytes.next()}return PDFName_default.of(name)};PDFObjectParser2.prototype.parseArray=function(){this.bytes.assertNext(CharCodes_default.LeftSquareBracket);this.skipWhitespaceAndComments();var pdfArray=PDFArray_default.withContext(this.context);while(this.bytes.peek()!==CharCodes_default.RightSquareBracket){var element=this.parseObject();pdfArray.push(element);this.skipWhitespaceAndComments()}this.bytes.assertNext(CharCodes_default.RightSquareBracket);return pdfArray};PDFObjectParser2.prototype.parseDict=function(){this.bytes.assertNext(CharCodes_default.LessThan);this.bytes.assertNext(CharCodes_default.LessThan);this.skipWhitespaceAndComments();var dict=new Map;while(!this.bytes.done()&&this.bytes.peek()!==CharCodes_default.GreaterThan&&this.bytes.peekAhead(1)!==CharCodes_default.GreaterThan){var key=this.parseName();var value=this.parseObject();dict.set(key,value);this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments();this.bytes.assertNext(CharCodes_default.GreaterThan);this.bytes.assertNext(CharCodes_default.GreaterThan);var Type=dict.get(PDFName_default.of("Type"));if(Type===PDFName_default.of("Catalog")){return PDFCatalog_default.fromMapWithContext(dict,this.context)}else if(Type===PDFName_default.of("Pages")){return PDFPageTree_default.fromMapWithContext(dict,this.context)}else if(Type===PDFName_default.of("Page")){return PDFPageLeaf_default.fromMapWithContext(dict,this.context)}else{return PDFDict_default.fromMapWithContext(dict,this.context)}};PDFObjectParser2.prototype.parseDictOrStream=function(){var startPos=this.bytes.position();var dict=this.parseDict();this.skipWhitespaceAndComments();if(!this.matchKeyword(Keywords.streamEOF1)&&!this.matchKeyword(Keywords.streamEOF2)&&!this.matchKeyword(Keywords.streamEOF3)&&!this.matchKeyword(Keywords.streamEOF4)&&!this.matchKeyword(Keywords.stream)){return dict}var start=this.bytes.offset();var end;var Length=dict.get(PDFName_default.of("Length"));if(Length instanceof PDFNumber_default){end=start+Length.asNumber();this.bytes.moveTo(end);this.skipWhitespaceAndComments();if(!this.matchKeyword(Keywords.endstream)){this.bytes.moveTo(start);end=this.findEndOfStreamFallback(startPos)}}else{end=this.findEndOfStreamFallback(startPos)}var contents=this.bytes.slice(start,end);return PDFRawStream_default.of(dict,contents)};PDFObjectParser2.prototype.findEndOfStreamFallback=function(startPos){var nestingLvl=1;var end=this.bytes.offset();while(!this.bytes.done()){end=this.bytes.offset();if(this.matchKeyword(Keywords.stream)){nestingLvl+=1}else if(this.matchKeyword(Keywords.EOF1endstream)||this.matchKeyword(Keywords.EOF2endstream)||this.matchKeyword(Keywords.EOF3endstream)||this.matchKeyword(Keywords.endstream)){nestingLvl-=1}else{this.bytes.next()}if(nestingLvl===0)break}if(nestingLvl!==0)throw new PDFStreamParsingError(startPos);return end};PDFObjectParser2.forBytes=function(bytes,context2,capNumbers){return new PDFObjectParser2(ByteStream_default.of(bytes),context2,capNumbers)};PDFObjectParser2.forByteStream=function(byteStream,context2,capNumbers){if(capNumbers===undefined){capNumbers=false}return new PDFObjectParser2(byteStream,context2,capNumbers)};return PDFObjectParser2}(BaseParser_default);PDFObjectParser_default=PDFObjectParser});var PDFObjectStreamParser,PDFObjectStreamParser_default;var init_PDFObjectStreamParser=__esm(()=>{init_tslib_es62();init_errors2();init_PDFName();init_PDFNumber();init_PDFRef();init_ByteStream();init_PDFObjectParser();init_utils2();PDFObjectStreamParser=function(_super){__extends(PDFObjectStreamParser2,_super);function PDFObjectStreamParser2(rawStream,shouldWaitForTick){var _this=_super.call(this,ByteStream_default.fromPDFRawStream(rawStream),rawStream.dict.context)||this;var dict=rawStream.dict;_this.alreadyParsed=false;_this.shouldWaitForTick=shouldWaitForTick||function(){return false};_this.firstOffset=dict.lookup(PDFName_default.of("First"),PDFNumber_default).asNumber();_this.objectCount=dict.lookup(PDFName_default.of("N"),PDFNumber_default).asNumber();return _this}PDFObjectStreamParser2.prototype.parseIntoContext=function(){return __awaiter(this,undefined,undefined,function(){var offsetsAndObjectNumbers,idx4,len3,_a,objectNumber,offset,object5,ref;return __generator(this,function(_b){switch(_b.label){case 0:if(this.alreadyParsed){throw new ReparseError("PDFObjectStreamParser","parseIntoContext")}this.alreadyParsed=true;offsetsAndObjectNumbers=this.parseOffsetsAndObjectNumbers();idx4=0,len3=offsetsAndObjectNumbers.length;_b.label=1;case 1:if(!(idx4<len3))return[3,4];_a=offsetsAndObjectNumbers[idx4],objectNumber=_a.objectNumber,offset=_a.offset;this.bytes.moveTo(this.firstOffset+offset);object5=this.parseObject();ref=PDFRef_default.of(objectNumber,0);this.context.assign(ref,object5);if(!this.shouldWaitForTick())return[3,3];return[4,waitForTick()];case 2:_b.sent();_b.label=3;case 3:idx4++;return[3,1];case 4:return[2]}})})};PDFObjectStreamParser2.prototype.parseOffsetsAndObjectNumbers=function(){var offsetsAndObjectNumbers=[];for(var idx4=0,len3=this.objectCount;idx4<len3;idx4++){this.skipWhitespaceAndComments();var objectNumber=this.parseRawInt();this.skipWhitespaceAndComments();var offset=this.parseRawInt();offsetsAndObjectNumbers.push({objectNumber,offset})}return offsetsAndObjectNumbers};PDFObjectStreamParser2.forStream=function(rawStream,shouldWaitForTick){return new PDFObjectStreamParser2(rawStream,shouldWaitForTick)};return PDFObjectStreamParser2}(PDFObjectParser_default);PDFObjectStreamParser_default=PDFObjectStreamParser});var PDFXRefStreamParser,PDFXRefStreamParser_default;var init_PDFXRefStreamParser=__esm(()=>{init_errors2();init_PDFArray();init_PDFName();init_PDFNumber();init_PDFRef();init_ByteStream();PDFXRefStreamParser=function(){function PDFXRefStreamParser2(rawStream){this.alreadyParsed=false;this.dict=rawStream.dict;this.bytes=ByteStream_default.fromPDFRawStream(rawStream);this.context=this.dict.context;var Size=this.dict.lookup(PDFName_default.of("Size"),PDFNumber_default);var Index=this.dict.lookup(PDFName_default.of("Index"));if(Index instanceof PDFArray_default){this.subsections=[];for(var idx4=0,len3=Index.size();idx4<len3;idx4+=2){var firstObjectNumber=Index.lookup(idx4+0,PDFNumber_default).asNumber();var length_1=Index.lookup(idx4+1,PDFNumber_default).asNumber();this.subsections.push({firstObjectNumber,length:length_1})}}else{this.subsections=[{firstObjectNumber:0,length:Size.asNumber()}]}var W=this.dict.lookup(PDFName_default.of("W"),PDFArray_default);this.byteWidths=[-1,-1,-1];for(var idx4=0,len3=W.size();idx4<len3;idx4++){this.byteWidths[idx4]=W.lookup(idx4,PDFNumber_default).asNumber()}}PDFXRefStreamParser2.prototype.parseIntoContext=function(){if(this.alreadyParsed){throw new ReparseError("PDFXRefStreamParser","parseIntoContext")}this.alreadyParsed=true;this.context.trailerInfo={Root:this.dict.get(PDFName_default.of("Root")),Encrypt:this.dict.get(PDFName_default.of("Encrypt")),Info:this.dict.get(PDFName_default.of("Info")),ID:this.dict.get(PDFName_default.of("ID"))};var entries=this.parseEntries();return entries};PDFXRefStreamParser2.prototype.parseEntries=function(){var entries=[];var _a=this.byteWidths,typeFieldWidth=_a[0],offsetFieldWidth=_a[1],genFieldWidth=_a[2];for(var subsectionIdx=0,subsectionLen=this.subsections.length;subsectionIdx<subsectionLen;subsectionIdx++){var _b=this.subsections[subsectionIdx],firstObjectNumber=_b.firstObjectNumber,length_2=_b.length;for(var objIdx=0;objIdx<length_2;objIdx++){var type=0;for(var idx4=0,len3=typeFieldWidth;idx4<len3;idx4++){type=type<<8|this.bytes.next()}var offset=0;for(var idx4=0,len3=offsetFieldWidth;idx4<len3;idx4++){offset=offset<<8|this.bytes.next()}var generationNumber=0;for(var idx4=0,len3=genFieldWidth;idx4<len3;idx4++){generationNumber=generationNumber<<8|this.bytes.next()}if(typeFieldWidth===0)type=1;var objectNumber=firstObjectNumber+objIdx;var entry={ref:PDFRef_default.of(objectNumber,generationNumber),offset,deleted:type===0,inObjectStream:type===2};entries.push(entry)}}return entries};PDFXRefStreamParser2.forStream=function(rawStream){return new PDFXRefStreamParser2(rawStream)};return PDFXRefStreamParser2}();PDFXRefStreamParser_default=PDFXRefStreamParser});var PDFParser,PDFParser_default;var init_PDFParser=__esm(()=>{init_tslib_es62();init_PDFCrossRefSection();init_PDFHeader();init_PDFTrailer();init_errors2();init_PDFDict();init_PDFInvalidObject();init_PDFName();init_PDFRawStream();init_PDFRef();init_ByteStream();init_PDFObjectParser();init_PDFObjectStreamParser();init_PDFXRefStreamParser();init_PDFContext();init_CharCodes();init_Keywords();init_Numeric();init_utils2();PDFParser=function(_super){__extends(PDFParser2,_super);function PDFParser2(pdfBytes,objectsPerTick,throwOnInvalidObject,capNumbers){if(objectsPerTick===undefined){objectsPerTick=Infinity}if(throwOnInvalidObject===undefined){throwOnInvalidObject=false}if(capNumbers===undefined){capNumbers=false}var _this=_super.call(this,ByteStream_default.of(pdfBytes),PDFContext_default.create(),capNumbers)||this;_this.alreadyParsed=false;_this.parsedObjects=0;_this.shouldWaitForTick=function(){_this.parsedObjects+=1;return _this.parsedObjects%_this.objectsPerTick===0};_this.objectsPerTick=objectsPerTick;_this.throwOnInvalidObject=throwOnInvalidObject;return _this}PDFParser2.prototype.parseDocument=function(){return __awaiter(this,undefined,undefined,function(){var prevOffset,offset;return __generator(this,function(_a){switch(_a.label){case 0:if(this.alreadyParsed){throw new ReparseError("PDFParser","parseDocument")}this.alreadyParsed=true;this.context.header=this.parseHeader();_a.label=1;case 1:if(!!this.bytes.done())return[3,3];return[4,this.parseDocumentSection()];case 2:_a.sent();offset=this.bytes.offset();if(offset===prevOffset){throw new StalledParserError(this.bytes.position())}prevOffset=offset;return[3,1];case 3:this.maybeRecoverRoot();if(this.context.lookup(PDFRef_default.of(0))){console.warn("Removing parsed object: 0 0 R");this.context.delete(PDFRef_default.of(0))}return[2,this.context]}})})};PDFParser2.prototype.maybeRecoverRoot=function(){var isValidCatalog=function(obj){return obj instanceof PDFDict_default&&obj.lookup(PDFName_default.of("Type"))===PDFName_default.of("Catalog")};var catalog=this.context.lookup(this.context.trailerInfo.Root);if(!isValidCatalog(catalog)){var indirectObjects=this.context.enumerateIndirectObjects();for(var idx4=0,len3=indirectObjects.length;idx4<len3;idx4++){var _a=indirectObjects[idx4],ref=_a[0],object5=_a[1];if(isValidCatalog(object5)){this.context.trailerInfo.Root=ref}}}};PDFParser2.prototype.parseHeader=function(){while(!this.bytes.done()){if(this.matchKeyword(Keywords.header)){var major=this.parseRawInt();this.bytes.assertNext(CharCodes_default.Period);var minor=this.parseRawInt();var header=PDFHeader_default.forVersion(major,minor);this.skipBinaryHeaderComment();return header}this.bytes.next()}throw new MissingPDFHeaderError(this.bytes.position())};PDFParser2.prototype.parseIndirectObjectHeader=function(){this.skipWhitespaceAndComments();var objectNumber=this.parseRawInt();this.skipWhitespaceAndComments();var generationNumber=this.parseRawInt();this.skipWhitespaceAndComments();if(!this.matchKeyword(Keywords.obj)){throw new MissingKeywordError(this.bytes.position(),Keywords.obj)}return PDFRef_default.of(objectNumber,generationNumber)};PDFParser2.prototype.matchIndirectObjectHeader=function(){var initialOffset=this.bytes.offset();try{this.parseIndirectObjectHeader();return true}catch(e){this.bytes.moveTo(initialOffset);return false}};PDFParser2.prototype.parseIndirectObject=function(){return __awaiter(this,undefined,undefined,function(){var ref,object5;return __generator(this,function(_a){switch(_a.label){case 0:ref=this.parseIndirectObjectHeader();this.skipWhitespaceAndComments();object5=this.parseObject();this.skipWhitespaceAndComments();this.matchKeyword(Keywords.endobj);if(!(object5 instanceof PDFRawStream_default&&object5.dict.lookup(PDFName_default.of("Type"))===PDFName_default.of("ObjStm")))return[3,2];return[4,PDFObjectStreamParser_default.forStream(object5,this.shouldWaitForTick).parseIntoContext()];case 1:_a.sent();return[3,3];case 2:if(object5 instanceof PDFRawStream_default&&object5.dict.lookup(PDFName_default.of("Type"))===PDFName_default.of("XRef")){PDFXRefStreamParser_default.forStream(object5).parseIntoContext()}else{this.context.assign(ref,object5)}_a.label=3;case 3:return[2,ref]}})})};PDFParser2.prototype.tryToParseInvalidIndirectObject=function(){var startPos=this.bytes.position();var msg="Trying to parse invalid object: "+JSON.stringify(startPos)+")";if(this.throwOnInvalidObject)throw new Error(msg);console.warn(msg);var ref=this.parseIndirectObjectHeader();console.warn("Invalid object ref: "+ref);this.skipWhitespaceAndComments();var start=this.bytes.offset();var failed=true;while(!this.bytes.done()){if(this.matchKeyword(Keywords.endobj)){failed=false}if(!failed)break;this.bytes.next()}if(failed)throw new PDFInvalidObjectParsingError(startPos);var end=this.bytes.offset()-Keywords.endobj.length;var object5=PDFInvalidObject_default.of(this.bytes.slice(start,end));this.context.assign(ref,object5);return ref};PDFParser2.prototype.parseIndirectObjects=function(){return __awaiter(this,undefined,undefined,function(){var initialOffset,e_1;return __generator(this,function(_a){switch(_a.label){case 0:this.skipWhitespaceAndComments();_a.label=1;case 1:if(!(!this.bytes.done()&&IsDigit[this.bytes.peek()]))return[3,8];initialOffset=this.bytes.offset();_a.label=2;case 2:_a.trys.push([2,4,,5]);return[4,this.parseIndirectObject()];case 3:_a.sent();return[3,5];case 4:e_1=_a.sent();this.bytes.moveTo(initialOffset);this.tryToParseInvalidIndirectObject();return[3,5];case 5:this.skipWhitespaceAndComments();this.skipJibberish();if(!this.shouldWaitForTick())return[3,7];return[4,waitForTick()];case 6:_a.sent();_a.label=7;case 7:return[3,1];case 8:return[2]}})})};PDFParser2.prototype.maybeParseCrossRefSection=function(){this.skipWhitespaceAndComments();if(!this.matchKeyword(Keywords.xref))return;this.skipWhitespaceAndComments();var objectNumber=-1;var xref=PDFCrossRefSection_default.createEmpty();while(!this.bytes.done()&&IsDigit[this.bytes.peek()]){var firstInt=this.parseRawInt();this.skipWhitespaceAndComments();var secondInt=this.parseRawInt();this.skipWhitespaceAndComments();var byte=this.bytes.peek();if(byte===CharCodes_default.n||byte===CharCodes_default.f){var ref=PDFRef_default.of(objectNumber,secondInt);if(this.bytes.next()===CharCodes_default.n){xref.addEntry(ref,firstInt)}else{xref.addDeletedEntry(ref,firstInt)}objectNumber+=1}else{objectNumber=firstInt}this.skipWhitespaceAndComments()}return xref};PDFParser2.prototype.maybeParseTrailerDict=function(){this.skipWhitespaceAndComments();if(!this.matchKeyword(Keywords.trailer))return;this.skipWhitespaceAndComments();var dict=this.parseDict();var context2=this.context;context2.trailerInfo={Root:dict.get(PDFName_default.of("Root"))||context2.trailerInfo.Root,Encrypt:dict.get(PDFName_default.of("Encrypt"))||context2.trailerInfo.Encrypt,Info:dict.get(PDFName_default.of("Info"))||context2.trailerInfo.Info,ID:dict.get(PDFName_default.of("ID"))||context2.trailerInfo.ID}};PDFParser2.prototype.maybeParseTrailer=function(){this.skipWhitespaceAndComments();if(!this.matchKeyword(Keywords.startxref))return;this.skipWhitespaceAndComments();var offset=this.parseRawInt();this.skipWhitespace();this.matchKeyword(Keywords.eof);this.skipWhitespaceAndComments();this.matchKeyword(Keywords.eof);this.skipWhitespaceAndComments();return PDFTrailer_default.forLastCrossRefSectionOffset(offset)};PDFParser2.prototype.parseDocumentSection=function(){return __awaiter(this,undefined,undefined,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.parseIndirectObjects()];case 1:_a.sent();this.maybeParseCrossRefSection();this.maybeParseTrailerDict();this.maybeParseTrailer();this.skipJibberish();return[2]}})})};PDFParser2.prototype.skipJibberish=function(){this.skipWhitespaceAndComments();while(!this.bytes.done()){var initialOffset=this.bytes.offset();var byte=this.bytes.peek();var isAlphaNumeric=byte>=CharCodes_default.Space&&byte<=CharCodes_default.Tilde;if(isAlphaNumeric){if(this.matchKeyword(Keywords.xref)||this.matchKeyword(Keywords.trailer)||this.matchKeyword(Keywords.startxref)||this.matchIndirectObjectHeader()){this.bytes.moveTo(initialOffset);break}}this.bytes.next()}};PDFParser2.prototype.skipBinaryHeaderComment=function(){this.skipWhitespaceAndComments();try{var initialOffset=this.bytes.offset();this.parseIndirectObjectHeader();this.bytes.moveTo(initialOffset)}catch(e){this.bytes.next();this.skipWhitespaceAndComments()}};PDFParser2.forBytesWithOptions=function(pdfBytes,objectsPerTick,throwOnInvalidObject,capNumbers){return new PDFParser2(pdfBytes,objectsPerTick,throwOnInvalidObject,capNumbers)};return PDFParser2}(PDFObjectParser_default);PDFParser_default=PDFParser});var flag2=function(bitIndex){return 1<<bitIndex},AnnotationFlags;var init_flags2=__esm(()=>{(function(AnnotationFlags2){AnnotationFlags2[AnnotationFlags2["Invisible"]=flag2(1-1)]="Invisible";AnnotationFlags2[AnnotationFlags2["Hidden"]=flag2(2-1)]="Hidden";AnnotationFlags2[AnnotationFlags2["Print"]=flag2(3-1)]="Print";AnnotationFlags2[AnnotationFlags2["NoZoom"]=flag2(4-1)]="NoZoom";AnnotationFlags2[AnnotationFlags2["NoRotate"]=flag2(5-1)]="NoRotate";AnnotationFlags2[AnnotationFlags2["NoView"]=flag2(6-1)]="NoView";AnnotationFlags2[AnnotationFlags2["ReadOnly"]=flag2(7-1)]="ReadOnly";AnnotationFlags2[AnnotationFlags2["Locked"]=flag2(8-1)]="Locked";AnnotationFlags2[AnnotationFlags2["ToggleNoView"]=flag2(9-1)]="ToggleNoView";AnnotationFlags2[AnnotationFlags2["LockedContents"]=flag2(10-1)]="LockedContents"})(AnnotationFlags||(AnnotationFlags={}))});var init_annotation=__esm(()=>{init_PDFAnnotation();init_PDFWidgetAnnotation();init_AppearanceCharacteristics();init_flags2()});var init_core=__esm(()=>{init_CharCodes();init_PDFContext();init_PDFObjectCopier();init_PDFWriter();init_PDFStreamWriter();init_PDFHeader();init_PDFTrailer();init_PDFTrailerDict();init_PDFCrossRefSection();init_StandardFontEmbedder();init_CustomFontEmbedder();init_CustomFontSubsetEmbedder();init_FileEmbedder();init_JpegEmbedder();init_PngEmbedder();init_PDFPageEmbedder();init_ViewerPreferences();init_PDFObject();init_PDFBool();init_PDFNumber();init_PDFString();init_PDFHexString();init_PDFName();init_PDFNull();init_PDFArray();init_PDFDict();init_PDFRef();init_PDFInvalidObject();init_PDFStream();init_PDFRawStream();init_PDFCatalog();init_PDFContentStream();init_PDFCrossRefStream();init_PDFObjectStream();init_PDFPageTree();init_PDFPageLeaf();init_PDFFlateStream();init_PDFOperator();init_PDFOperatorNames();init_PDFObjectParser();init_PDFObjectStreamParser();init_PDFParser();init_PDFXRefStreamParser();init_decode();init_errors2();init_annotation();init_acroform()});var asPDFName=function(name){return name instanceof PDFName_default?name:PDFName_default.of(name)},asPDFNumber=function(num){return num instanceof PDFNumber_default?num:PDFNumber_default.of(num)},asNumber=function(num){return num instanceof PDFNumber_default?num.asNumber():num};var init_objects2=__esm(()=>{init_core()});var RotationTypes,radians=function(radianAngle){assertIs(radianAngle,"radianAngle",["number"]);return{type:RotationTypes.Radians,angle:radianAngle}},degrees=function(degreeAngle){assertIs(degreeAngle,"degreeAngle",["number"]);return{type:RotationTypes.Degrees,angle:degreeAngle}},Radians,Degrees,degreesToRadians=function(degree){return degree*Math.PI/180},radiansToDegrees=function(radian){return radian*180/Math.PI},toRadians=function(rotation){return rotation.type===Radians?rotation.angle:rotation.type===Degrees?degreesToRadians(rotation.angle):error("Invalid rotation: "+JSON.stringify(rotation))},toDegrees=function(rotation){return rotation.type===Radians?radiansToDegrees(rotation.angle):rotation.type===Degrees?rotation.angle:error("Invalid rotation: "+JSON.stringify(rotation))},reduceRotation=function(degreeAngle){if(degreeAngle===undefined){degreeAngle=0}var quadrants=degreeAngle/90%4;if(quadrants===0)return 0;if(quadrants===1)return 90;if(quadrants===2)return 180;if(quadrants===3)return 270;return 0},adjustDimsForRotation=function(dims,degreeAngle){if(degreeAngle===undefined){degreeAngle=0}var rotation=reduceRotation(degreeAngle);return rotation===90||rotation===270?{width:dims.height,height:dims.width}:{width:dims.width,height:dims.height}},rotateRectangle=function(rectangle,borderWidth,degreeAngle){if(borderWidth===undefined){borderWidth=0}if(degreeAngle===undefined){degreeAngle=0}var{x,y,width:w,height:h}=rectangle;var r=reduceRotation(degreeAngle);var b=borderWidth/2;if(r===0)return{x:x-b,y:y-b,width:w,height:h};else if(r===90)return{x:x-h+b,y:y-b,width:h,height:w};else if(r===180)return{x:x-w+b,y:y-h+b,width:w,height:h};else if(r===270)return{x:x-b,y:y-w+b,width:h,height:w};else return{x:x-b,y:y-b,width:w,height:h}};var init_rotations=__esm(()=>{init_utils2();(function(RotationTypes2){RotationTypes2["Degrees"]="degrees";RotationTypes2["Radians"]="radians"})(RotationTypes||(RotationTypes={}));Radians=RotationTypes.Radians;Degrees=RotationTypes.Degrees});var clip=function(){return PDFOperator_default.of(PDFOperatorNames_default.ClipNonZero)},clipEvenOdd=function(){return PDFOperator_default.of(PDFOperatorNames_default.ClipEvenOdd)},cos,sin,tan,concatTransformationMatrix=function(a,b,c,d,e,f){return PDFOperator_default.of(PDFOperatorNames_default.ConcatTransformationMatrix,[asPDFNumber(a),asPDFNumber(b),asPDFNumber(c),asPDFNumber(d),asPDFNumber(e),asPDFNumber(f)])},translate=function(xPos,yPos){return concatTransformationMatrix(1,0,0,1,xPos,yPos)},scale=function(xPos,yPos){return concatTransformationMatrix(xPos,0,0,yPos,0,0)},rotateRadians=function(angle){return concatTransformationMatrix(cos(asNumber(angle)),sin(asNumber(angle)),-sin(asNumber(angle)),cos(asNumber(angle)),0,0)},rotateDegrees=function(angle){return rotateRadians(degreesToRadians(asNumber(angle)))},skewRadians=function(xSkewAngle,ySkewAngle){return concatTransformationMatrix(1,tan(asNumber(xSkewAngle)),tan(asNumber(ySkewAngle)),1,0,0)},skewDegrees=function(xSkewAngle,ySkewAngle){return skewRadians(degreesToRadians(asNumber(xSkewAngle)),degreesToRadians(asNumber(ySkewAngle)))},setDashPattern=function(dashArray,dashPhase){return PDFOperator_default.of(PDFOperatorNames_default.SetLineDashPattern,["["+dashArray.map(asPDFNumber).join(" ")+"]",asPDFNumber(dashPhase)])},restoreDashPattern=function(){return setDashPattern([],0)},LineCapStyle,setLineCap=function(style){return PDFOperator_default.of(PDFOperatorNames_default.SetLineCapStyle,[asPDFNumber(style)])},LineJoinStyle,setLineJoin=function(style){return PDFOperator_default.of(PDFOperatorNames_default.SetLineJoinStyle,[asPDFNumber(style)])},setGraphicsState=function(state){return PDFOperator_default.of(PDFOperatorNames_default.SetGraphicsStateParams,[asPDFName(state)])},pushGraphicsState=function(){return PDFOperator_default.of(PDFOperatorNames_default.PushGraphicsState)},popGraphicsState=function(){return PDFOperator_default.of(PDFOperatorNames_default.PopGraphicsState)},setLineWidth=function(width){return PDFOperator_default.of(PDFOperatorNames_default.SetLineWidth,[asPDFNumber(width)])},appendBezierCurve=function(x1,y1,x2,y2,x3,y3){return PDFOperator_default.of(PDFOperatorNames_default.AppendBezierCurve,[asPDFNumber(x1),asPDFNumber(y1),asPDFNumber(x2),asPDFNumber(y2),asPDFNumber(x3),asPDFNumber(y3)])},appendQuadraticCurve=function(x1,y1,x2,y2){return PDFOperator_default.of(PDFOperatorNames_default.CurveToReplicateInitialPoint,[asPDFNumber(x1),asPDFNumber(y1),asPDFNumber(x2),asPDFNumber(y2)])},closePath=function(){return PDFOperator_default.of(PDFOperatorNames_default.ClosePath)},moveTo=function(xPos,yPos){return PDFOperator_default.of(PDFOperatorNames_default.MoveTo,[asPDFNumber(xPos),asPDFNumber(yPos)])},lineTo=function(xPos,yPos){return PDFOperator_default.of(PDFOperatorNames_default.LineTo,[asPDFNumber(xPos),asPDFNumber(yPos)])},rectangle=function(xPos,yPos,width,height){return PDFOperator_default.of(PDFOperatorNames_default.AppendRectangle,[asPDFNumber(xPos),asPDFNumber(yPos),asPDFNumber(width),asPDFNumber(height)])},square=function(xPos,yPos,size){return rectangle(xPos,yPos,size,size)},stroke=function(){return PDFOperator_default.of(PDFOperatorNames_default.StrokePath)},fill=function(){return PDFOperator_default.of(PDFOperatorNames_default.FillNonZero)},fillAndStroke=function(){return PDFOperator_default.of(PDFOperatorNames_default.FillNonZeroAndStroke)},endPath=function(){return PDFOperator_default.of(PDFOperatorNames_default.EndPath)},nextLine=function(){return PDFOperator_default.of(PDFOperatorNames_default.NextLine)},moveText=function(x,y){return PDFOperator_default.of(PDFOperatorNames_default.MoveText,[asPDFNumber(x),asPDFNumber(y)])},showText=function(text4){return PDFOperator_default.of(PDFOperatorNames_default.ShowText,[text4])},beginText=function(){return PDFOperator_default.of(PDFOperatorNames_default.BeginText)},endText=function(){return PDFOperator_default.of(PDFOperatorNames_default.EndText)},setFontAndSize=function(name,size){return PDFOperator_default.of(PDFOperatorNames_default.SetFontAndSize,[asPDFName(name),asPDFNumber(size)])},setCharacterSpacing=function(spacing){return PDFOperator_default.of(PDFOperatorNames_default.SetCharacterSpacing,[asPDFNumber(spacing)])},setWordSpacing=function(spacing){return PDFOperator_default.of(PDFOperatorNames_default.SetWordSpacing,[asPDFNumber(spacing)])},setCharacterSqueeze=function(squeeze){return PDFOperator_default.of(PDFOperatorNames_default.SetTextHorizontalScaling,[asPDFNumber(squeeze)])},setLineHeight=function(lineHeight){return PDFOperator_default.of(PDFOperatorNames_default.SetTextLineHeight,[asPDFNumber(lineHeight)])},setTextRise=function(rise){return PDFOperator_default.of(PDFOperatorNames_default.SetTextRise,[asPDFNumber(rise)])},TextRenderingMode,setTextRenderingMode=function(mode){return PDFOperator_default.of(PDFOperatorNames_default.SetTextRenderingMode,[asPDFNumber(mode)])},setTextMatrix=function(a,b,c,d,e,f){return PDFOperator_default.of(PDFOperatorNames_default.SetTextMatrix,[asPDFNumber(a),asPDFNumber(b),asPDFNumber(c),asPDFNumber(d),asPDFNumber(e),asPDFNumber(f)])},rotateAndSkewTextRadiansAndTranslate=function(rotationAngle,xSkewAngle,ySkewAngle,x,y){return setTextMatrix(cos(asNumber(rotationAngle)),sin(asNumber(rotationAngle))+tan(asNumber(xSkewAngle)),-sin(asNumber(rotationAngle))+tan(asNumber(ySkewAngle)),cos(asNumber(rotationAngle)),x,y)},rotateAndSkewTextDegreesAndTranslate=function(rotationAngle,xSkewAngle,ySkewAngle,x,y){return rotateAndSkewTextRadiansAndTranslate(degreesToRadians(asNumber(rotationAngle)),degreesToRadians(asNumber(xSkewAngle)),degreesToRadians(asNumber(ySkewAngle)),x,y)},drawObject=function(name){return PDFOperator_default.of(PDFOperatorNames_default.DrawObject,[asPDFName(name)])},setFillingGrayscaleColor=function(gray){return PDFOperator_default.of(PDFOperatorNames_default.NonStrokingColorGray,[asPDFNumber(gray)])},setStrokingGrayscaleColor=function(gray){return PDFOperator_default.of(PDFOperatorNames_default.StrokingColorGray,[asPDFNumber(gray)])},setFillingRgbColor=function(red,green,blue){return PDFOperator_default.of(PDFOperatorNames_default.NonStrokingColorRgb,[asPDFNumber(red),asPDFNumber(green),asPDFNumber(blue)])},setStrokingRgbColor=function(red,green,blue){return PDFOperator_default.of(PDFOperatorNames_default.StrokingColorRgb,[asPDFNumber(red),asPDFNumber(green),asPDFNumber(blue)])},setFillingCmykColor=function(cyan,magenta,yellow,key){return PDFOperator_default.of(PDFOperatorNames_default.NonStrokingColorCmyk,[asPDFNumber(cyan),asPDFNumber(magenta),asPDFNumber(yellow),asPDFNumber(key)])},setStrokingCmykColor=function(cyan,magenta,yellow,key){return PDFOperator_default.of(PDFOperatorNames_default.StrokingColorCmyk,[asPDFNumber(cyan),asPDFNumber(magenta),asPDFNumber(yellow),asPDFNumber(key)])},beginMarkedContent=function(tag){return PDFOperator_default.of(PDFOperatorNames_default.BeginMarkedContent,[asPDFName(tag)])},endMarkedContent=function(){return PDFOperator_default.of(PDFOperatorNames_default.EndMarkedContent)};var init_operators=__esm(()=>{init_objects2();init_rotations();init_core();cos=Math.cos;sin=Math.sin;tan=Math.tan;(function(LineCapStyle2){LineCapStyle2[LineCapStyle2["Butt"]=0]="Butt";LineCapStyle2[LineCapStyle2["Round"]=1]="Round";LineCapStyle2[LineCapStyle2["Projecting"]=2]="Projecting"})(LineCapStyle||(LineCapStyle={}));(function(LineJoinStyle2){LineJoinStyle2[LineJoinStyle2["Miter"]=0]="Miter";LineJoinStyle2[LineJoinStyle2["Round"]=1]="Round";LineJoinStyle2[LineJoinStyle2["Bevel"]=2]="Bevel"})(LineJoinStyle||(LineJoinStyle={}));(function(TextRenderingMode2){TextRenderingMode2[TextRenderingMode2["Fill"]=0]="Fill";TextRenderingMode2[TextRenderingMode2["Outline"]=1]="Outline";TextRenderingMode2[TextRenderingMode2["FillAndOutline"]=2]="FillAndOutline";TextRenderingMode2[TextRenderingMode2["Invisible"]=3]="Invisible";TextRenderingMode2[TextRenderingMode2["FillAndClip"]=4]="FillAndClip";TextRenderingMode2[TextRenderingMode2["OutlineAndClip"]=5]="OutlineAndClip";TextRenderingMode2[TextRenderingMode2["FillAndOutlineAndClip"]=6]="FillAndOutlineAndClip";TextRenderingMode2[TextRenderingMode2["Clip"]=7]="Clip"})(TextRenderingMode||(TextRenderingMode={}))});var ColorTypes,grayscale=function(gray){assertRange(gray,"gray",0,1);return{type:ColorTypes.Grayscale,gray}},rgb=function(red,green,blue){assertRange(red,"red",0,1);assertRange(green,"green",0,1);assertRange(blue,"blue",0,1);return{type:ColorTypes.RGB,red,green,blue}},cmyk=function(cyan,magenta,yellow,key){assertRange(cyan,"cyan",0,1);assertRange(magenta,"magenta",0,1);assertRange(yellow,"yellow",0,1);assertRange(key,"key",0,1);return{type:ColorTypes.CMYK,cyan,magenta,yellow,key}},Grayscale,RGB,CMYK,setFillingColor=function(color){return color.type===Grayscale?setFillingGrayscaleColor(color.gray):color.type===RGB?setFillingRgbColor(color.red,color.green,color.blue):color.type===CMYK?setFillingCmykColor(color.cyan,color.magenta,color.yellow,color.key):error("Invalid color: "+JSON.stringify(color))},setStrokingColor=function(color){return color.type===Grayscale?setStrokingGrayscaleColor(color.gray):color.type===RGB?setStrokingRgbColor(color.red,color.green,color.blue):color.type===CMYK?setStrokingCmykColor(color.cyan,color.magenta,color.yellow,color.key):error("Invalid color: "+JSON.stringify(color))},componentsToColor=function(comps,scale2){if(scale2===undefined){scale2=1}return(comps===null||comps===undefined?undefined:comps.length)===1?grayscale(comps[0]*scale2):(comps===null||comps===undefined?undefined:comps.length)===3?rgb(comps[0]*scale2,comps[1]*scale2,comps[2]*scale2):(comps===null||comps===undefined?undefined:comps.length)===4?cmyk(comps[0]*scale2,comps[1]*scale2,comps[2]*scale2,comps[3]*scale2):undefined},colorToComponents=function(color){return color.type===Grayscale?[color.gray]:color.type===RGB?[color.red,color.green,color.blue]:color.type===CMYK?[color.cyan,color.magenta,color.yellow,color.key]:error("Invalid color: "+JSON.stringify(color))};var init_colors=__esm(()=>{init_operators();init_utils2();(function(ColorTypes2){ColorTypes2["Grayscale"]="Grayscale";ColorTypes2["RGB"]="RGB";ColorTypes2["CMYK"]="CMYK"})(ColorTypes||(ColorTypes={}));Grayscale=ColorTypes.Grayscale;RGB=ColorTypes.RGB;CMYK=ColorTypes.CMYK});var cx=0,cy=0,px=0,py=0,sx=0,sy=0,parameters,parse=function(path){var cmd;var ret=[];var args=[];var curArg="";var foundDecimal=false;var params=0;for(var _i=0,path_1=path;_i<path_1.length;_i++){var c=path_1[_i];if(parameters.has(c)){params=parameters.get(c);if(cmd){if(curArg.length>0){args[args.length]=+curArg}ret[ret.length]={cmd,args};args=[];curArg="";foundDecimal=false}cmd=c}else if([" ",","].includes(c)||c==="-"&&curArg.length>0&&curArg[curArg.length-1]!=="e"||c==="."&&foundDecimal){if(curArg.length===0){continue}if(args.length===params){ret[ret.length]={cmd,args};args=[+curArg];if(cmd==="M"){cmd="L"}if(cmd==="m"){cmd="l"}}else{args[args.length]=+curArg}foundDecimal=c===".";curArg=["-","."].includes(c)?c:""}else{curArg+=c;if(c==="."){foundDecimal=true}}}if(curArg.length>0){if(args.length===params){ret[ret.length]={cmd,args};args=[+curArg];if(cmd==="M"){cmd="L"}if(cmd==="m"){cmd="l"}}else{args[args.length]=+curArg}}ret[ret.length]={cmd,args};return ret},apply=function(commands){cx=cy=px=py=sx=sy=0;var cmds=[];for(var i3=0;i3<commands.length;i3++){var c=commands[i3];if(c.cmd&&typeof runners[c.cmd]==="function"){var cmd=runners[c.cmd](c.args);if(Array.isArray(cmd)){cmds=cmds.concat(cmd)}else{cmds.push(cmd)}}}return cmds},runners,solveArc=function(x,y,coords){var rx=coords[0],ry=coords[1],rot=coords[2],large=coords[3],sweep=coords[4],ex=coords[5],ey=coords[6];var segs=arcToSegments(ex,ey,rx,ry,large,sweep,rot,x,y);var cmds=[];for(var _i=0,segs_1=segs;_i<segs_1.length;_i++){var seg=segs_1[_i];var bez=segmentToBezier.apply(undefined,seg);cmds.push(appendBezierCurve.apply(undefined,bez))}return cmds},arcToSegments=function(x,y,rx,ry,large,sweep,rotateX,ox,oy){var th=rotateX*(Math.PI/180);var sinTh=Math.sin(th);var cosTh=Math.cos(th);rx=Math.abs(rx);ry=Math.abs(ry);px=cosTh*(ox-x)*0.5+sinTh*(oy-y)*0.5;py=cosTh*(oy-y)*0.5-sinTh*(ox-x)*0.5;var pl=px*px/(rx*rx)+py*py/(ry*ry);if(pl>1){pl=Math.sqrt(pl);rx*=pl;ry*=pl}var a00=cosTh/rx;var a01=sinTh/rx;var a10=-sinTh/ry;var a11=cosTh/ry;var x0=a00*ox+a01*oy;var y0=a10*ox+a11*oy;var x1=a00*x+a01*y;var y1=a10*x+a11*y;var d=(x1-x0)*(x1-x0)+(y1-y0)*(y1-y0);var sfactorSq=1/d-0.25;if(sfactorSq<0){sfactorSq=0}var sfactor=Math.sqrt(sfactorSq);if(sweep===large){sfactor=-sfactor}var xc=0.5*(x0+x1)-sfactor*(y1-y0);var yc=0.5*(y0+y1)+sfactor*(x1-x0);var th0=Math.atan2(y0-yc,x0-xc);var th1=Math.atan2(y1-yc,x1-xc);var thArc=th1-th0;if(thArc<0&&sweep===1){thArc+=2*Math.PI}else if(thArc>0&&sweep===0){thArc-=2*Math.PI}var segments=Math.ceil(Math.abs(thArc/(Math.PI*0.5+0.001)));var result2=[];for(var i3=0;i3<segments;i3++){var th2=th0+i3*thArc/segments;var th3=th0+(i3+1)*thArc/segments;result2[i3]=[xc,yc,th2,th3,rx,ry,sinTh,cosTh]}return result2},segmentToBezier=function(cx1,cy1,th0,th1,rx,ry,sinTh,cosTh){var a00=cosTh*rx;var a01=-sinTh*ry;var a10=sinTh*rx;var a11=cosTh*ry;var thHalf=0.5*(th1-th0);var t=8/3*Math.sin(thHalf*0.5)*Math.sin(thHalf*0.5)/Math.sin(thHalf);var x1=cx1+Math.cos(th0)-t*Math.sin(th0);var y1=cy1+Math.sin(th0)+t*Math.cos(th0);var x3=cx1+Math.cos(th1);var y3=cy1+Math.sin(th1);var x2=x3+t*Math.sin(th1);var y2=y3-t*Math.cos(th1);var result2=[a00*x1+a01*y1,a10*x1+a11*y1,a00*x2+a01*y2,a10*x2+a11*y2,a00*x3+a01*y3,a10*x3+a11*y3];return result2},svgPathToOperators=function(path){return apply(parse(path))};var init_svgPath=__esm(()=>{init_operators();parameters=new Map([["A",7],["a",7],["C",6],["c",6],["H",1],["h",1],["L",2],["l",2],["M",2],["m",2],["Q",4],["q",4],["S",4],["s",4],["T",2],["t",2],["V",1],["v",1],["Z",0],["z",0]]);runners={M:function(a){cx=a[0];cy=a[1];px=py=null;sx=cx;sy=cy;return moveTo(cx,cy)},m:function(a){cx+=a[0];cy+=a[1];px=py=null;sx=cx;sy=cy;return moveTo(cx,cy)},C:function(a){cx=a[4];cy=a[5];px=a[2];py=a[3];return appendBezierCurve(a[0],a[1],a[2],a[3],a[4],a[5])},c:function(a){var cmd=appendBezierCurve(a[0]+cx,a[1]+cy,a[2]+cx,a[3]+cy,a[4]+cx,a[5]+cy);px=cx+a[2];py=cy+a[3];cx+=a[4];cy+=a[5];return cmd},S:function(a){if(px===null||py===null){px=cx;py=cy}var cmd=appendBezierCurve(cx-(px-cx),cy-(py-cy),a[0],a[1],a[2],a[3]);px=a[0];py=a[1];cx=a[2];cy=a[3];return cmd},s:function(a){if(px===null||py===null){px=cx;py=cy}var cmd=appendBezierCurve(cx-(px-cx),cy-(py-cy),cx+a[0],cy+a[1],cx+a[2],cy+a[3]);px=cx+a[0];py=cy+a[1];cx+=a[2];cy+=a[3];return cmd},Q:function(a){px=a[0];py=a[1];cx=a[2];cy=a[3];return appendQuadraticCurve(a[0],a[1],cx,cy)},q:function(a){var cmd=appendQuadraticCurve(a[0]+cx,a[1]+cy,a[2]+cx,a[3]+cy);px=cx+a[0];py=cy+a[1];cx+=a[2];cy+=a[3];return cmd},T:function(a){if(px===null||py===null){px=cx;py=cy}else{px=cx-(px-cx);py=cy-(py-cy)}var cmd=appendQuadraticCurve(px,py,a[0],a[1]);px=cx-(px-cx);py=cy-(py-cy);cx=a[0];cy=a[1];return cmd},t:function(a){if(px===null||py===null){px=cx;py=cy}else{px=cx-(px-cx);py=cy-(py-cy)}var cmd=appendQuadraticCurve(px,py,cx+a[0],cy+a[1]);cx+=a[0];cy+=a[1];return cmd},A:function(a){var cmds=solveArc(cx,cy,a);cx=a[5];cy=a[6];return cmds},a:function(a){a[5]+=cx;a[6]+=cy;var cmds=solveArc(cx,cy,a);cx=a[5];cy=a[6];return cmds},L:function(a){cx=a[0];cy=a[1];px=py=null;return lineTo(cx,cy)},l:function(a){cx+=a[0];cy+=a[1];px=py=null;return lineTo(cx,cy)},H:function(a){cx=a[0];px=py=null;return lineTo(cx,cy)},h:function(a){cx+=a[0];px=py=null;return lineTo(cx,cy)},V:function(a){cy=a[0];px=py=null;return lineTo(cx,cy)},v:function(a){cy+=a[0];px=py=null;return lineTo(cx,cy)},Z:function(){var cmd=closePath();cx=sx;cy=sy;return cmd},z:function(){var cmd=closePath();cx=sx;cy=sy;return cmd}}});var drawText=function(line,options){return[pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),beginText(),setFillingColor(options.color),setFontAndSize(options.font,options.size),rotateAndSkewTextRadiansAndTranslate(toRadians(options.rotate),toRadians(options.xSkew),toRadians(options.ySkew),options.x,options.y),showText(line),endText(),popGraphicsState()].filter(Boolean)},drawLinesOfText=function(lines,options){var operators=[pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),beginText(),setFillingColor(options.color),setFontAndSize(options.font,options.size),setLineHeight(options.lineHeight),rotateAndSkewTextRadiansAndTranslate(toRadians(options.rotate),toRadians(options.xSkew),toRadians(options.ySkew),options.x,options.y)].filter(Boolean);for(var idx4=0,len3=lines.length;idx4<len3;idx4++){operators.push(showText(lines[idx4]),nextLine())}operators.push(endText(),popGraphicsState());return operators},drawImage=function(name,options){return[pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),translate(options.x,options.y),rotateRadians(toRadians(options.rotate)),scale(options.width,options.height),skewRadians(toRadians(options.xSkew),toRadians(options.ySkew)),drawObject(name),popGraphicsState()].filter(Boolean)},drawPage=function(name,options){return[pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),translate(options.x,options.y),rotateRadians(toRadians(options.rotate)),scale(options.xScale,options.yScale),skewRadians(toRadians(options.xSkew),toRadians(options.ySkew)),drawObject(name),popGraphicsState()].filter(Boolean)},drawLine=function(options){var _a,_b;return[pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),options.color&&setStrokingColor(options.color),setLineWidth(options.thickness),setDashPattern((_a=options.dashArray)!==null&&_a!==undefined?_a:[],(_b=options.dashPhase)!==null&&_b!==undefined?_b:0),moveTo(options.start.x,options.start.y),options.lineCap&&setLineCap(options.lineCap),moveTo(options.start.x,options.start.y),lineTo(options.end.x,options.end.y),stroke(),popGraphicsState()].filter(Boolean)},drawRectangle=function(options){var _a,_b;return[pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),options.color&&setFillingColor(options.color),options.borderColor&&setStrokingColor(options.borderColor),setLineWidth(options.borderWidth),options.borderLineCap&&setLineCap(options.borderLineCap),setDashPattern((_a=options.borderDashArray)!==null&&_a!==undefined?_a:[],(_b=options.borderDashPhase)!==null&&_b!==undefined?_b:0),translate(options.x,options.y),rotateRadians(toRadians(options.rotate)),skewRadians(toRadians(options.xSkew),toRadians(options.ySkew)),moveTo(0,0),lineTo(0,options.height),lineTo(options.width,options.height),lineTo(options.width,0),closePath(),options.color&&options.borderWidth?fillAndStroke():options.color?fill():options.borderColor?stroke():closePath(),popGraphicsState()].filter(Boolean)},KAPPA,drawEllipsePath=function(config){var x=asNumber(config.x);var y=asNumber(config.y);var xScale=asNumber(config.xScale);var yScale=asNumber(config.yScale);x-=xScale;y-=yScale;var ox=xScale*KAPPA;var oy=yScale*KAPPA;var xe=x+xScale*2;var ye=y+yScale*2;var xm=x+xScale;var ym=y+yScale;return[pushGraphicsState(),moveTo(x,ym),appendBezierCurve(x,ym-oy,xm-ox,y,xm,y),appendBezierCurve(xm+ox,y,xe,ym-oy,xe,ym),appendBezierCurve(xe,ym+oy,xm+ox,ye,xm,ye),appendBezierCurve(xm-ox,ye,x,ym+oy,x,ym),popGraphicsState()]},drawEllipseCurves=function(config){var centerX=asNumber(config.x);var centerY=asNumber(config.y);var xScale=asNumber(config.xScale);var yScale=asNumber(config.yScale);var x=-xScale;var y=-yScale;var ox=xScale*KAPPA;var oy=yScale*KAPPA;var xe=x+xScale*2;var ye=y+yScale*2;var xm=x+xScale;var ym=y+yScale;return[translate(centerX,centerY),rotateRadians(toRadians(config.rotate)),moveTo(x,ym),appendBezierCurve(x,ym-oy,xm-ox,y,xm,y),appendBezierCurve(xm+ox,y,xe,ym-oy,xe,ym),appendBezierCurve(xe,ym+oy,xm+ox,ye,xm,ye),appendBezierCurve(xm-ox,ye,x,ym+oy,x,ym)]},drawEllipse=function(options){var _a,_b,_c;return __spreadArrays([pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),options.color&&setFillingColor(options.color),options.borderColor&&setStrokingColor(options.borderColor),setLineWidth(options.borderWidth),options.borderLineCap&&setLineCap(options.borderLineCap),setDashPattern((_a=options.borderDashArray)!==null&&_a!==undefined?_a:[],(_b=options.borderDashPhase)!==null&&_b!==undefined?_b:0)],options.rotate===undefined?drawEllipsePath({x:options.x,y:options.y,xScale:options.xScale,yScale:options.yScale}):drawEllipseCurves({x:options.x,y:options.y,xScale:options.xScale,yScale:options.yScale,rotate:(_c=options.rotate)!==null&&_c!==undefined?_c:degrees(0)}),[options.color&&options.borderWidth?fillAndStroke():options.color?fill():options.borderColor?stroke():closePath(),popGraphicsState()]).filter(Boolean)},drawSvgPath=function(path,options){var _a,_b,_c;return __spreadArrays([pushGraphicsState(),options.graphicsState&&setGraphicsState(options.graphicsState),translate(options.x,options.y),rotateRadians(toRadians((_a=options.rotate)!==null&&_a!==undefined?_a:degrees(0))),options.scale?scale(options.scale,-options.scale):scale(1,-1),options.color&&setFillingColor(options.color),options.borderColor&&setStrokingColor(options.borderColor),options.borderWidth&&setLineWidth(options.borderWidth),options.borderLineCap&&setLineCap(options.borderLineCap),setDashPattern((_b=options.borderDashArray)!==null&&_b!==undefined?_b:[],(_c=options.borderDashPhase)!==null&&_c!==undefined?_c:0)],svgPathToOperators(path),[options.color&&options.borderWidth?fillAndStroke():options.color?fill():options.borderColor?stroke():closePath(),popGraphicsState()]).filter(Boolean)},drawCheckMark=function(options){var size=asNumber(options.size);var p2x=-1+0.75;var p2y=-1+0.51;var p3y=1-0.525;var p3x=1-0.31;var p1x=-1+0.325;var p1y=-((p1x-p2x)*(p3x-p2x))/(p3y-p2y)+p2y;return[pushGraphicsState(),options.color&&setStrokingColor(options.color),setLineWidth(options.thickness),translate(options.x,options.y),moveTo(p1x*size,p1y*size),lineTo(p2x*size,p2y*size),lineTo(p3x*size,p3y*size),stroke(),popGraphicsState()].filter(Boolean)},rotateInPlace=function(options){return options.rotation===0?[translate(0,0),rotateDegrees(0)]:options.rotation===90?[translate(options.width,0),rotateDegrees(90)]:options.rotation===180?[translate(options.width,options.height),rotateDegrees(180)]:options.rotation===270?[translate(0,options.height),rotateDegrees(270)]:[]},drawCheckBox=function(options){var outline=drawRectangle({x:options.x,y:options.y,width:options.width,height:options.height,borderWidth:options.borderWidth,color:options.color,borderColor:options.borderColor,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)});if(!options.filled)return outline;var width=asNumber(options.width);var height=asNumber(options.height);var checkMarkSize=Math.min(width,height)/2;var checkMark=drawCheckMark({x:width/2,y:height/2,size:checkMarkSize,thickness:options.thickness,color:options.markColor});return __spreadArrays([pushGraphicsState()],outline,checkMark,[popGraphicsState()])},drawRadioButton=function(options){var width=asNumber(options.width);var height=asNumber(options.height);var outlineScale=Math.min(width,height)/2;var outline=drawEllipse({x:options.x,y:options.y,xScale:outlineScale,yScale:outlineScale,color:options.color,borderColor:options.borderColor,borderWidth:options.borderWidth});if(!options.filled)return outline;var dot=drawEllipse({x:options.x,y:options.y,xScale:outlineScale*0.45,yScale:outlineScale*0.45,color:options.dotColor,borderColor:undefined,borderWidth:0});return __spreadArrays([pushGraphicsState()],outline,dot,[popGraphicsState()])},drawButton=function(options){var x=asNumber(options.x);var y=asNumber(options.y);var width=asNumber(options.width);var height=asNumber(options.height);var background=drawRectangle({x,y,width,height,borderWidth:options.borderWidth,color:options.color,borderColor:options.borderColor,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)});var lines=drawTextLines(options.textLines,{color:options.textColor,font:options.font,size:options.fontSize,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)});return __spreadArrays([pushGraphicsState()],background,lines,[popGraphicsState()])},drawTextLines=function(lines,options){var operators=[beginText(),setFillingColor(options.color),setFontAndSize(options.font,options.size)];for(var idx4=0,len3=lines.length;idx4<len3;idx4++){var _a=lines[idx4],encoded=_a.encoded,x=_a.x,y=_a.y;operators.push(rotateAndSkewTextRadiansAndTranslate(toRadians(options.rotate),toRadians(options.xSkew),toRadians(options.ySkew),x,y),showText(encoded))}operators.push(endText());return operators},drawTextField=function(options){var x=asNumber(options.x);var y=asNumber(options.y);var width=asNumber(options.width);var height=asNumber(options.height);var borderWidth=asNumber(options.borderWidth);var padding=asNumber(options.padding);var clipX=x+borderWidth/2+padding;var clipY=y+borderWidth/2+padding;var clipWidth=width-(borderWidth/2+padding)*2;var clipHeight=height-(borderWidth/2+padding)*2;var clippingArea=[moveTo(clipX,clipY),lineTo(clipX,clipY+clipHeight),lineTo(clipX+clipWidth,clipY+clipHeight),lineTo(clipX+clipWidth,clipY),closePath(),clip(),endPath()];var background=drawRectangle({x,y,width,height,borderWidth:options.borderWidth,color:options.color,borderColor:options.borderColor,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)});var lines=drawTextLines(options.textLines,{color:options.textColor,font:options.font,size:options.fontSize,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)});var markedContent=__spreadArrays([beginMarkedContent("Tx"),pushGraphicsState()],lines,[popGraphicsState(),endMarkedContent()]);return __spreadArrays([pushGraphicsState()],background,clippingArea,markedContent,[popGraphicsState()])},drawOptionList=function(options){var x=asNumber(options.x);var y=asNumber(options.y);var width=asNumber(options.width);var height=asNumber(options.height);var lineHeight=asNumber(options.lineHeight);var borderWidth=asNumber(options.borderWidth);var padding=asNumber(options.padding);var clipX=x+borderWidth/2+padding;var clipY=y+borderWidth/2+padding;var clipWidth=width-(borderWidth/2+padding)*2;var clipHeight=height-(borderWidth/2+padding)*2;var clippingArea=[moveTo(clipX,clipY),lineTo(clipX,clipY+clipHeight),lineTo(clipX+clipWidth,clipY+clipHeight),lineTo(clipX+clipWidth,clipY),closePath(),clip(),endPath()];var background=drawRectangle({x,y,width,height,borderWidth:options.borderWidth,color:options.color,borderColor:options.borderColor,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)});var highlights=[];for(var idx4=0,len3=options.selectedLines.length;idx4<len3;idx4++){var line=options.textLines[options.selectedLines[idx4]];highlights.push.apply(highlights,drawRectangle({x:line.x-padding,y:line.y-(lineHeight-line.height)/2,width:width-borderWidth,height:line.height+(lineHeight-line.height)/2,borderWidth:0,color:options.selectedColor,borderColor:undefined,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)}))}var lines=drawTextLines(options.textLines,{color:options.textColor,font:options.font,size:options.fontSize,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)});var markedContent=__spreadArrays([beginMarkedContent("Tx"),pushGraphicsState()],lines,[popGraphicsState(),endMarkedContent()]);return __spreadArrays([pushGraphicsState()],background,highlights,clippingArea,markedContent,[popGraphicsState()])};var init_operations=__esm(()=>{init_tslib_es62();init_colors();init_operators();init_rotations();init_svgPath();init_objects2();KAPPA=4*((Math.sqrt(2)-1)/3)});var EncryptedPDFError,FontkitNotRegisteredError,ForeignPageError,RemovePageFromEmptyDocumentError,NoSuchFieldError,UnexpectedFieldTypeError,MissingOnValueCheckError,FieldAlreadyExistsError,InvalidFieldNamePartError,FieldExistsAsNonTerminalError,RichTextFieldReadError,CombedTextLayoutError,ExceededMaxLengthError,InvalidMaxLengthError;var init_errors3=__esm(()=>{init_tslib_es62();EncryptedPDFError=function(_super){__extends(EncryptedPDFError2,_super);function EncryptedPDFError2(){var _this=this;var msg="Input document to `PDFDocument.load` is encrypted. You can use `PDFDocument.load(..., { ignoreEncryption: true })` if you wish to load the document anyways.";_this=_super.call(this,msg)||this;return _this}return EncryptedPDFError2}(Error);FontkitNotRegisteredError=function(_super){__extends(FontkitNotRegisteredError2,_super);function FontkitNotRegisteredError2(){var _this=this;var msg="Input to `PDFDocument.embedFont` was a custom font, but no `fontkit` instance was found. You must register a `fontkit` instance with `PDFDocument.registerFontkit(...)` before embedding custom fonts.";_this=_super.call(this,msg)||this;return _this}return FontkitNotRegisteredError2}(Error);ForeignPageError=function(_super){__extends(ForeignPageError2,_super);function ForeignPageError2(){var _this=this;var msg="A `page` passed to `PDFDocument.addPage` or `PDFDocument.insertPage` was from a different (foreign) PDF document. If you want to copy pages from one PDFDocument to another, you must use `PDFDocument.copyPages(...)` to copy the pages before adding or inserting them.";_this=_super.call(this,msg)||this;return _this}return ForeignPageError2}(Error);RemovePageFromEmptyDocumentError=function(_super){__extends(RemovePageFromEmptyDocumentError2,_super);function RemovePageFromEmptyDocumentError2(){var _this=this;var msg="PDFDocument has no pages so `PDFDocument.removePage` cannot be called";_this=_super.call(this,msg)||this;return _this}return RemovePageFromEmptyDocumentError2}(Error);NoSuchFieldError=function(_super){__extends(NoSuchFieldError2,_super);function NoSuchFieldError2(name){var _this=this;var msg='PDFDocument has no form field with the name "'+name+'"';_this=_super.call(this,msg)||this;return _this}return NoSuchFieldError2}(Error);UnexpectedFieldTypeError=function(_super){__extends(UnexpectedFieldTypeError2,_super);function UnexpectedFieldTypeError2(name,expected,actual){var _a,_b;var _this=this;var expectedType=expected===null||expected===undefined?undefined:expected.name;var actualType=(_b=(_a=actual===null||actual===undefined?undefined:actual.constructor)===null||_a===undefined?undefined:_a.name)!==null&&_b!==undefined?_b:actual;var msg='Expected field "'+name+'" to be of type '+expectedType+", "+("but it is actually of type "+actualType);_this=_super.call(this,msg)||this;return _this}return UnexpectedFieldTypeError2}(Error);MissingOnValueCheckError=function(_super){__extends(MissingOnValueCheckError2,_super);function MissingOnValueCheckError2(onValue){var _this=this;var msg='Failed to select check box due to missing onValue: "'+onValue+'"';_this=_super.call(this,msg)||this;return _this}return MissingOnValueCheckError2}(Error);FieldAlreadyExistsError=function(_super){__extends(FieldAlreadyExistsError2,_super);function FieldAlreadyExistsError2(name){var _this=this;var msg='A field already exists with the specified name: "'+name+'"';_this=_super.call(this,msg)||this;return _this}return FieldAlreadyExistsError2}(Error);InvalidFieldNamePartError=function(_super){__extends(InvalidFieldNamePartError2,_super);function InvalidFieldNamePartError2(namePart){var _this=this;var msg='Field name contains invalid component: "'+namePart+'"';_this=_super.call(this,msg)||this;return _this}return InvalidFieldNamePartError2}(Error);FieldExistsAsNonTerminalError=function(_super){__extends(FieldExistsAsNonTerminalError2,_super);function FieldExistsAsNonTerminalError2(name){var _this=this;var msg='A non-terminal field already exists with the specified name: "'+name+'"';_this=_super.call(this,msg)||this;return _this}return FieldExistsAsNonTerminalError2}(Error);RichTextFieldReadError=function(_super){__extends(RichTextFieldReadError2,_super);function RichTextFieldReadError2(fieldName){var _this=this;var msg="Reading rich text fields is not supported: Attempted to read rich text field: "+fieldName;_this=_super.call(this,msg)||this;return _this}return RichTextFieldReadError2}(Error);CombedTextLayoutError=function(_super){__extends(CombedTextLayoutError2,_super);function CombedTextLayoutError2(lineLength,cellCount){var _this=this;var msg="Failed to layout combed text as lineLength="+lineLength+" is greater than cellCount="+cellCount;_this=_super.call(this,msg)||this;return _this}return CombedTextLayoutError2}(Error);ExceededMaxLengthError=function(_super){__extends(ExceededMaxLengthError2,_super);function ExceededMaxLengthError2(textLength,maxLength,name){var _this=this;var msg="Attempted to set text with length="+textLength+" for TextField with maxLength="+maxLength+" and name="+name;_this=_super.call(this,msg)||this;return _this}return ExceededMaxLengthError2}(Error);InvalidMaxLengthError=function(_super){__extends(InvalidMaxLengthError2,_super);function InvalidMaxLengthError2(textLength,maxLength,name){var _this=this;var msg="Attempted to set maxLength="+maxLength+", which is less than "+textLength+", the length of this field's current value (name="+name+")";_this=_super.call(this,msg)||this;return _this}return InvalidMaxLengthError2}(Error)});var TextAlignment;var init_alignment=__esm(()=>{(function(TextAlignment2){TextAlignment2[TextAlignment2["Left"]=0]="Left";TextAlignment2[TextAlignment2["Center"]=1]="Center";TextAlignment2[TextAlignment2["Right"]=2]="Right"})(TextAlignment||(TextAlignment={}))});var MIN_FONT_SIZE=4,MAX_FONT_SIZE=500,computeFontSize=function(lines,font,bounds,multiline){if(multiline===undefined){multiline=false}var fontSize=MIN_FONT_SIZE;while(fontSize<MAX_FONT_SIZE){var linesUsed=0;for(var lineIdx=0,lineLen=lines.length;lineIdx<lineLen;lineIdx++){linesUsed+=1;var line=lines[lineIdx];var words=line.split(" ");var spaceInLineRemaining=bounds.width;for(var idx4=0,len3=words.length;idx4<len3;idx4++){var isLastWord=idx4===len3-1;var word=isLastWord?words[idx4]:words[idx4]+" ";var widthOfWord=font.widthOfTextAtSize(word,fontSize);spaceInLineRemaining-=widthOfWord;if(spaceInLineRemaining<=0){linesUsed+=1;spaceInLineRemaining=bounds.width-widthOfWord}}}if(!multiline&&linesUsed>lines.length)return fontSize-1;var height=font.heightAtSize(fontSize);var lineHeight=height+height*0.2;var totalHeight=lineHeight*linesUsed;if(totalHeight>Math.abs(bounds.height))return fontSize-1;fontSize+=1}return fontSize},computeCombedFontSize=function(line,font,bounds,cellCount){var cellWidth=bounds.width/cellCount;var cellHeight=bounds.height;var fontSize=MIN_FONT_SIZE;var chars3=charSplit(line);while(fontSize<MAX_FONT_SIZE){for(var idx4=0,len3=chars3.length;idx4<len3;idx4++){var c=chars3[idx4];var tooLong=font.widthOfTextAtSize(c,fontSize)>cellWidth*0.75;if(tooLong)return fontSize-1}var height=font.heightAtSize(fontSize,{descender:false});if(height>cellHeight)return fontSize-1;fontSize+=1}return fontSize},lastIndexOfWhitespace=function(line){for(var idx4=line.length;idx4>0;idx4--){if(/\s/.test(line[idx4]))return idx4}return},splitOutLines=function(input,maxWidth,font,fontSize){var _a;var lastWhitespaceIdx=input.length;while(lastWhitespaceIdx>0){var line=input.substring(0,lastWhitespaceIdx);var encoded=font.encodeText(line);var width=font.widthOfTextAtSize(line,fontSize);if(width<maxWidth){var remainder=input.substring(lastWhitespaceIdx)||undefined;return{line,encoded,width,remainder}}lastWhitespaceIdx=(_a=lastIndexOfWhitespace(line))!==null&&_a!==undefined?_a:0}return{line:input,encoded:font.encodeText(input),width:font.widthOfTextAtSize(input,fontSize),remainder:undefined}},layoutMultilineText=function(text4,_a){var{alignment,fontSize,font,bounds}=_a;var lines=lineSplit(cleanText(text4));if(fontSize===undefined||fontSize===0){fontSize=computeFontSize(lines,font,bounds,true)}var height=font.heightAtSize(fontSize);var lineHeight=height+height*0.2;var textLines=[];var minX=bounds.x;var minY=bounds.y;var maxX=bounds.x+bounds.width;var maxY=bounds.y+bounds.height;var y=bounds.y+bounds.height;for(var idx4=0,len3=lines.length;idx4<len3;idx4++){var prevRemainder=lines[idx4];while(prevRemainder!==undefined){var _b=splitOutLines(prevRemainder,bounds.width,font,fontSize),line=_b.line,encoded=_b.encoded,width=_b.width,remainder=_b.remainder;var x=alignment===TextAlignment.Left?bounds.x:alignment===TextAlignment.Center?bounds.x+bounds.width/2-width/2:alignment===TextAlignment.Right?bounds.x+bounds.width-width:bounds.x;y-=lineHeight;if(x<minX)minX=x;if(y<minY)minY=y;if(x+width>maxX)maxX=x+width;if(y+height>maxY)maxY=y+height;textLines.push({text:line,encoded,width,height,x,y});prevRemainder=remainder===null||remainder===undefined?undefined:remainder.trim()}}return{fontSize,lineHeight,lines:textLines,bounds:{x:minX,y:minY,width:maxX-minX,height:maxY-minY}}},layoutCombedText=function(text4,_a){var{fontSize,font,bounds,cellCount}=_a;var line=mergeLines(cleanText(text4));if(line.length>cellCount){throw new CombedTextLayoutError(line.length,cellCount)}if(fontSize===undefined||fontSize===0){fontSize=computeCombedFontSize(line,font,bounds,cellCount)}var cellWidth=bounds.width/cellCount;var height=font.heightAtSize(fontSize,{descender:false});var y=bounds.y+(bounds.height/2-height/2);var cells=[];var minX=bounds.x;var minY=bounds.y;var maxX=bounds.x+bounds.width;var maxY=bounds.y+bounds.height;var cellOffset=0;var charOffset=0;while(cellOffset<cellCount){var _b=charAtIndex(line,charOffset),char=_b[0],charLength=_b[1];var encoded=font.encodeText(char);var width=font.widthOfTextAtSize(char,fontSize);var cellCenter=bounds.x+(cellWidth*cellOffset+cellWidth/2);var x=cellCenter-width/2;if(x<minX)minX=x;if(y<minY)minY=y;if(x+width>maxX)maxX=x+width;if(y+height>maxY)maxY=y+height;cells.push({text:line,encoded,width,height,x,y});cellOffset+=1;charOffset+=charLength}return{fontSize,cells,bounds:{x:minX,y:minY,width:maxX-minX,height:maxY-minY}}},layoutSinglelineText=function(text4,_a){var{alignment,fontSize,font,bounds}=_a;var line=mergeLines(cleanText(text4));if(fontSize===undefined||fontSize===0){fontSize=computeFontSize([line],font,bounds)}var encoded=font.encodeText(line);var width=font.widthOfTextAtSize(line,fontSize);var height=font.heightAtSize(fontSize,{descender:false});var x=alignment===TextAlignment.Left?bounds.x:alignment===TextAlignment.Center?bounds.x+bounds.width/2-width/2:alignment===TextAlignment.Right?bounds.x+bounds.width-width:bounds.x;var y=bounds.y+(bounds.height/2-height/2);return{fontSize,line:{text:line,encoded,width,height,x,y},bounds:{x,y,width,height}}};var init_layout=__esm(()=>{init_errors3();init_alignment();init_utils2()});var normalizeAppearance=function(appearance){if("normal"in appearance)return appearance;return{normal:appearance}},tfRegex2,getDefaultFontSize=function(field){var _a,_b;var da=(_a=field.getDefaultAppearance())!==null&&_a!==undefined?_a:"";var daMatch=(_b=findLastMatch(da,tfRegex2).match)!==null&&_b!==undefined?_b:[];var defaultFontSize=Number(daMatch[2]);return isFinite(defaultFontSize)?defaultFontSize:undefined},colorRegex,getDefaultColor=function(field){var _a;var da=(_a=field.getDefaultAppearance())!==null&&_a!==undefined?_a:"";var daMatch=findLastMatch(da,colorRegex).match;var _b=daMatch!==null&&daMatch!==undefined?daMatch:[],c1=_b[1],c2=_b[2],c3=_b[3],c4=_b[4],colorSpace=_b[5];if(colorSpace==="g"&&c1){return grayscale(Number(c1))}if(colorSpace==="rg"&&c1&&c2&&c3){return rgb(Number(c1),Number(c2),Number(c3))}if(colorSpace==="k"&&c1&&c2&&c3&&c4){return cmyk(Number(c1),Number(c2),Number(c3),Number(c4))}return},updateDefaultAppearance=function(field,color,font,fontSize){var _a;if(fontSize===undefined){fontSize=0}var da=[setFillingColor(color).toString(),setFontAndSize((_a=font===null||font===undefined?undefined:font.name)!==null&&_a!==undefined?_a:"dummy__noop",fontSize).toString()].join(`
|
|
72
72
|
`);field.setDefaultAppearance(da)},defaultCheckBoxAppearanceProvider=function(checkBox,widget){var _a,_b,_c;var widgetColor=getDefaultColor(widget);var fieldColor=getDefaultColor(checkBox.acroField);var rectangle2=widget.getRectangle();var ap=widget.getAppearanceCharacteristics();var bs=widget.getBorderStyle();var borderWidth=(_a=bs===null||bs===undefined?undefined:bs.getWidth())!==null&&_a!==undefined?_a:0;var rotation=reduceRotation(ap===null||ap===undefined?undefined:ap.getRotation());var _d=adjustDimsForRotation(rectangle2,rotation),width=_d.width,height=_d.height;var rotate=rotateInPlace(__assign(__assign({},rectangle2),{rotation}));var black=rgb(0,0,0);var borderColor=(_b=componentsToColor(ap===null||ap===undefined?undefined:ap.getBorderColor()))!==null&&_b!==undefined?_b:black;var normalBackgroundColor=componentsToColor(ap===null||ap===undefined?undefined:ap.getBackgroundColor());var downBackgroundColor=componentsToColor(ap===null||ap===undefined?undefined:ap.getBackgroundColor(),0.8);var textColor=(_c=widgetColor!==null&&widgetColor!==undefined?widgetColor:fieldColor)!==null&&_c!==undefined?_c:black;if(widgetColor){updateDefaultAppearance(widget,textColor)}else{updateDefaultAppearance(checkBox.acroField,textColor)}var options={x:0+borderWidth/2,y:0+borderWidth/2,width:width-borderWidth,height:height-borderWidth,thickness:1.5,borderWidth,borderColor,markColor:textColor};return{normal:{on:__spreadArrays(rotate,drawCheckBox(__assign(__assign({},options),{color:normalBackgroundColor,filled:true}))),off:__spreadArrays(rotate,drawCheckBox(__assign(__assign({},options),{color:normalBackgroundColor,filled:false})))},down:{on:__spreadArrays(rotate,drawCheckBox(__assign(__assign({},options),{color:downBackgroundColor,filled:true}))),off:__spreadArrays(rotate,drawCheckBox(__assign(__assign({},options),{color:downBackgroundColor,filled:false})))}}},defaultRadioGroupAppearanceProvider=function(radioGroup,widget){var _a,_b,_c;var widgetColor=getDefaultColor(widget);var fieldColor=getDefaultColor(radioGroup.acroField);var rectangle2=widget.getRectangle();var ap=widget.getAppearanceCharacteristics();var bs=widget.getBorderStyle();var borderWidth=(_a=bs===null||bs===undefined?undefined:bs.getWidth())!==null&&_a!==undefined?_a:0;var rotation=reduceRotation(ap===null||ap===undefined?undefined:ap.getRotation());var _d=adjustDimsForRotation(rectangle2,rotation),width=_d.width,height=_d.height;var rotate=rotateInPlace(__assign(__assign({},rectangle2),{rotation}));var black=rgb(0,0,0);var borderColor=(_b=componentsToColor(ap===null||ap===undefined?undefined:ap.getBorderColor()))!==null&&_b!==undefined?_b:black;var normalBackgroundColor=componentsToColor(ap===null||ap===undefined?undefined:ap.getBackgroundColor());var downBackgroundColor=componentsToColor(ap===null||ap===undefined?undefined:ap.getBackgroundColor(),0.8);var textColor=(_c=widgetColor!==null&&widgetColor!==undefined?widgetColor:fieldColor)!==null&&_c!==undefined?_c:black;if(widgetColor){updateDefaultAppearance(widget,textColor)}else{updateDefaultAppearance(radioGroup.acroField,textColor)}var options={x:width/2,y:height/2,width:width-borderWidth,height:height-borderWidth,borderWidth,borderColor,dotColor:textColor};return{normal:{on:__spreadArrays(rotate,drawRadioButton(__assign(__assign({},options),{color:normalBackgroundColor,filled:true}))),off:__spreadArrays(rotate,drawRadioButton(__assign(__assign({},options),{color:normalBackgroundColor,filled:false})))},down:{on:__spreadArrays(rotate,drawRadioButton(__assign(__assign({},options),{color:downBackgroundColor,filled:true}))),off:__spreadArrays(rotate,drawRadioButton(__assign(__assign({},options),{color:downBackgroundColor,filled:false})))}}},defaultButtonAppearanceProvider=function(button,widget,font){var _a,_b,_c,_d,_e;var widgetColor=getDefaultColor(widget);var fieldColor=getDefaultColor(button.acroField);var widgetFontSize=getDefaultFontSize(widget);var fieldFontSize=getDefaultFontSize(button.acroField);var rectangle2=widget.getRectangle();var ap=widget.getAppearanceCharacteristics();var bs=widget.getBorderStyle();var captions=ap===null||ap===undefined?undefined:ap.getCaptions();var normalText=(_a=captions===null||captions===undefined?undefined:captions.normal)!==null&&_a!==undefined?_a:"";var downText=(_c=(_b=captions===null||captions===undefined?undefined:captions.down)!==null&&_b!==undefined?_b:normalText)!==null&&_c!==undefined?_c:"";var borderWidth=(_d=bs===null||bs===undefined?undefined:bs.getWidth())!==null&&_d!==undefined?_d:0;var rotation=reduceRotation(ap===null||ap===undefined?undefined:ap.getRotation());var _f=adjustDimsForRotation(rectangle2,rotation),width=_f.width,height=_f.height;var rotate=rotateInPlace(__assign(__assign({},rectangle2),{rotation}));var black=rgb(0,0,0);var borderColor=componentsToColor(ap===null||ap===undefined?undefined:ap.getBorderColor());var normalBackgroundColor=componentsToColor(ap===null||ap===undefined?undefined:ap.getBackgroundColor());var downBackgroundColor=componentsToColor(ap===null||ap===undefined?undefined:ap.getBackgroundColor(),0.8);var bounds={x:borderWidth,y:borderWidth,width:width-borderWidth*2,height:height-borderWidth*2};var normalLayout=layoutSinglelineText(normalText,{alignment:TextAlignment.Center,fontSize:widgetFontSize!==null&&widgetFontSize!==undefined?widgetFontSize:fieldFontSize,font,bounds});var downLayout=layoutSinglelineText(downText,{alignment:TextAlignment.Center,fontSize:widgetFontSize!==null&&widgetFontSize!==undefined?widgetFontSize:fieldFontSize,font,bounds});var fontSize=Math.min(normalLayout.fontSize,downLayout.fontSize);var textColor=(_e=widgetColor!==null&&widgetColor!==undefined?widgetColor:fieldColor)!==null&&_e!==undefined?_e:black;if(widgetColor||widgetFontSize!==undefined){updateDefaultAppearance(widget,textColor,font,fontSize)}else{updateDefaultAppearance(button.acroField,textColor,font,fontSize)}var options={x:0+borderWidth/2,y:0+borderWidth/2,width:width-borderWidth,height:height-borderWidth,borderWidth,borderColor,textColor,font:font.name,fontSize};return{normal:__spreadArrays(rotate,drawButton(__assign(__assign({},options),{color:normalBackgroundColor,textLines:[normalLayout.line]}))),down:__spreadArrays(rotate,drawButton(__assign(__assign({},options),{color:downBackgroundColor,textLines:[downLayout.line]})))}},defaultTextFieldAppearanceProvider=function(textField,widget,font){var _a,_b,_c,_d;var widgetColor=getDefaultColor(widget);var fieldColor=getDefaultColor(textField.acroField);var widgetFontSize=getDefaultFontSize(widget);var fieldFontSize=getDefaultFontSize(textField.acroField);var rectangle2=widget.getRectangle();var ap=widget.getAppearanceCharacteristics();var bs=widget.getBorderStyle();var text4=(_a=textField.getText())!==null&&_a!==undefined?_a:"";var borderWidth=(_b=bs===null||bs===undefined?undefined:bs.getWidth())!==null&&_b!==undefined?_b:0;var rotation=reduceRotation(ap===null||ap===undefined?undefined:ap.getRotation());var _e=adjustDimsForRotation(rectangle2,rotation),width=_e.width,height=_e.height;var rotate=rotateInPlace(__assign(__assign({},rectangle2),{rotation}));var black=rgb(0,0,0);var borderColor=componentsToColor(ap===null||ap===undefined?undefined:ap.getBorderColor());var normalBackgroundColor=componentsToColor(ap===null||ap===undefined?undefined:ap.getBackgroundColor());var textLines;var fontSize;var padding=textField.isCombed()?0:1;var bounds={x:borderWidth+padding,y:borderWidth+padding,width:width-(borderWidth+padding)*2,height:height-(borderWidth+padding)*2};if(textField.isMultiline()){var layout=layoutMultilineText(text4,{alignment:textField.getAlignment(),fontSize:widgetFontSize!==null&&widgetFontSize!==undefined?widgetFontSize:fieldFontSize,font,bounds});textLines=layout.lines;fontSize=layout.fontSize}else if(textField.isCombed()){var layout=layoutCombedText(text4,{fontSize:widgetFontSize!==null&&widgetFontSize!==undefined?widgetFontSize:fieldFontSize,font,bounds,cellCount:(_c=textField.getMaxLength())!==null&&_c!==undefined?_c:0});textLines=layout.cells;fontSize=layout.fontSize}else{var layout=layoutSinglelineText(text4,{alignment:textField.getAlignment(),fontSize:widgetFontSize!==null&&widgetFontSize!==undefined?widgetFontSize:fieldFontSize,font,bounds});textLines=[layout.line];fontSize=layout.fontSize}var textColor=(_d=widgetColor!==null&&widgetColor!==undefined?widgetColor:fieldColor)!==null&&_d!==undefined?_d:black;if(widgetColor||widgetFontSize!==undefined){updateDefaultAppearance(widget,textColor,font,fontSize)}else{updateDefaultAppearance(textField.acroField,textColor,font,fontSize)}var options={x:0+borderWidth/2,y:0+borderWidth/2,width:width-borderWidth,height:height-borderWidth,borderWidth:borderWidth!==null&&borderWidth!==undefined?borderWidth:0,borderColor,textColor,font:font.name,fontSize,color:normalBackgroundColor,textLines,padding};return __spreadArrays(rotate,drawTextField(options))},defaultDropdownAppearanceProvider=function(dropdown,widget,font){var _a,_b,_c;var widgetColor=getDefaultColor(widget);var fieldColor=getDefaultColor(dropdown.acroField);var widgetFontSize=getDefaultFontSize(widget);var fieldFontSize=getDefaultFontSize(dropdown.acroField);var rectangle2=widget.getRectangle();var ap=widget.getAppearanceCharacteristics();var bs=widget.getBorderStyle();var text4=(_a=dropdown.getSelected()[0])!==null&&_a!==undefined?_a:"";var borderWidth=(_b=bs===null||bs===undefined?undefined:bs.getWidth())!==null&&_b!==undefined?_b:0;var rotation=reduceRotation(ap===null||ap===undefined?undefined:ap.getRotation());var _d=adjustDimsForRotation(rectangle2,rotation),width=_d.width,height=_d.height;var rotate=rotateInPlace(__assign(__assign({},rectangle2),{rotation}));var black=rgb(0,0,0);var borderColor=componentsToColor(ap===null||ap===undefined?undefined:ap.getBorderColor());var normalBackgroundColor=componentsToColor(ap===null||ap===undefined?undefined:ap.getBackgroundColor());var padding=1;var bounds={x:borderWidth+padding,y:borderWidth+padding,width:width-(borderWidth+padding)*2,height:height-(borderWidth+padding)*2};var _e=layoutSinglelineText(text4,{alignment:TextAlignment.Left,fontSize:widgetFontSize!==null&&widgetFontSize!==undefined?widgetFontSize:fieldFontSize,font,bounds}),line=_e.line,fontSize=_e.fontSize;var textColor=(_c=widgetColor!==null&&widgetColor!==undefined?widgetColor:fieldColor)!==null&&_c!==undefined?_c:black;if(widgetColor||widgetFontSize!==undefined){updateDefaultAppearance(widget,textColor,font,fontSize)}else{updateDefaultAppearance(dropdown.acroField,textColor,font,fontSize)}var options={x:0+borderWidth/2,y:0+borderWidth/2,width:width-borderWidth,height:height-borderWidth,borderWidth:borderWidth!==null&&borderWidth!==undefined?borderWidth:0,borderColor,textColor,font:font.name,fontSize,color:normalBackgroundColor,textLines:[line],padding};return __spreadArrays(rotate,drawTextField(options))},defaultOptionListAppearanceProvider=function(optionList,widget,font){var _a,_b;var widgetColor=getDefaultColor(widget);var fieldColor=getDefaultColor(optionList.acroField);var widgetFontSize=getDefaultFontSize(widget);var fieldFontSize=getDefaultFontSize(optionList.acroField);var rectangle2=widget.getRectangle();var ap=widget.getAppearanceCharacteristics();var bs=widget.getBorderStyle();var borderWidth=(_a=bs===null||bs===undefined?undefined:bs.getWidth())!==null&&_a!==undefined?_a:0;var rotation=reduceRotation(ap===null||ap===undefined?undefined:ap.getRotation());var _c=adjustDimsForRotation(rectangle2,rotation),width=_c.width,height=_c.height;var rotate=rotateInPlace(__assign(__assign({},rectangle2),{rotation}));var black=rgb(0,0,0);var borderColor=componentsToColor(ap===null||ap===undefined?undefined:ap.getBorderColor());var normalBackgroundColor=componentsToColor(ap===null||ap===undefined?undefined:ap.getBackgroundColor());var options=optionList.getOptions();var selected=optionList.getSelected();if(optionList.isSorted())options.sort();var text4="";for(var idx4=0,len3=options.length;idx4<len3;idx4++){text4+=options[idx4];if(idx4<len3-1)text4+=`
|
|
73
73
|
`}var padding=1;var bounds={x:borderWidth+padding,y:borderWidth+padding,width:width-(borderWidth+padding)*2,height:height-(borderWidth+padding)*2};var _d=layoutMultilineText(text4,{alignment:TextAlignment.Left,fontSize:widgetFontSize!==null&&widgetFontSize!==undefined?widgetFontSize:fieldFontSize,font,bounds}),lines=_d.lines,fontSize=_d.fontSize,lineHeight=_d.lineHeight;var selectedLines=[];for(var idx4=0,len3=lines.length;idx4<len3;idx4++){var line=lines[idx4];if(selected.includes(line.text))selectedLines.push(idx4)}var blue=rgb(153/255,193/255,218/255);var textColor=(_b=widgetColor!==null&&widgetColor!==undefined?widgetColor:fieldColor)!==null&&_b!==undefined?_b:black;if(widgetColor||widgetFontSize!==undefined){updateDefaultAppearance(widget,textColor,font,fontSize)}else{updateDefaultAppearance(optionList.acroField,textColor,font,fontSize)}return __spreadArrays(rotate,drawOptionList({x:0+borderWidth/2,y:0+borderWidth/2,width:width-borderWidth,height:height-borderWidth,borderWidth:borderWidth!==null&&borderWidth!==undefined?borderWidth:0,borderColor,textColor,font:font.name,fontSize,color:normalBackgroundColor,textLines:lines,lineHeight,selectedColor:blue,selectedLines,padding}))};var init_appearances=__esm(()=>{init_tslib_es62();init_operations();init_colors();init_rotations();init_layout();init_alignment();init_operators();init_utils2();tfRegex2=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/;colorRegex=/(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/});var PDFEmbeddedPage,PDFEmbeddedPage_default;var init_PDFEmbeddedPage=__esm(()=>{init_tslib_es62();init_PDFDocument();init_core();init_utils2();PDFEmbeddedPage=function(){function PDFEmbeddedPage2(ref,doc,embedder){this.alreadyEmbedded=false;assertIs(ref,"ref",[[PDFRef_default,"PDFRef"]]);assertIs(doc,"doc",[[PDFDocument_default,"PDFDocument"]]);assertIs(embedder,"embedder",[[PDFPageEmbedder_default,"PDFPageEmbedder"]]);this.ref=ref;this.doc=doc;this.width=embedder.width;this.height=embedder.height;this.embedder=embedder}PDFEmbeddedPage2.prototype.scale=function(factor){assertIs(factor,"factor",["number"]);return{width:this.width*factor,height:this.height*factor}};PDFEmbeddedPage2.prototype.size=function(){return this.scale(1)};PDFEmbeddedPage2.prototype.embed=function(){return __awaiter(this,undefined,undefined,function(){return __generator(this,function(_a){switch(_a.label){case 0:if(!!this.alreadyEmbedded)return[3,2];return[4,this.embedder.embedIntoContext(this.doc.context,this.ref)];case 1:_a.sent();this.alreadyEmbedded=true;_a.label=2;case 2:return[2]}})})};PDFEmbeddedPage2.of=function(ref,doc,embedder){return new PDFEmbeddedPage2(ref,doc,embedder)};return PDFEmbeddedPage2}();PDFEmbeddedPage_default=PDFEmbeddedPage});var PDFFont,PDFFont_default;var init_PDFFont=__esm(()=>{init_tslib_es62();init_PDFDocument();init_core();init_utils2();PDFFont=function(){function PDFFont2(ref,doc,embedder){this.modified=true;assertIs(ref,"ref",[[PDFRef_default,"PDFRef"]]);assertIs(doc,"doc",[[PDFDocument_default,"PDFDocument"]]);assertIs(embedder,"embedder",[[CustomFontEmbedder_default,"CustomFontEmbedder"],[StandardFontEmbedder_default,"StandardFontEmbedder"]]);this.ref=ref;this.doc=doc;this.name=embedder.fontName;this.embedder=embedder}PDFFont2.prototype.encodeText=function(text4){assertIs(text4,"text",["string"]);this.modified=true;return this.embedder.encodeText(text4)};PDFFont2.prototype.widthOfTextAtSize=function(text4,size){assertIs(text4,"text",["string"]);assertIs(size,"size",["number"]);return this.embedder.widthOfTextAtSize(text4,size)};PDFFont2.prototype.heightAtSize=function(size,options){var _a;assertIs(size,"size",["number"]);assertOrUndefined(options===null||options===undefined?undefined:options.descender,"options.descender",["boolean"]);return this.embedder.heightOfFontAtSize(size,{descender:(_a=options===null||options===undefined?undefined:options.descender)!==null&&_a!==undefined?_a:true})};PDFFont2.prototype.sizeAtHeight=function(height){assertIs(height,"height",["number"]);return this.embedder.sizeOfFontAtHeight(height)};PDFFont2.prototype.getCharacterSet=function(){if(this.embedder instanceof StandardFontEmbedder_default){return this.embedder.encoding.supportedCodePoints}else{return this.embedder.font.characterSet}};PDFFont2.prototype.embed=function(){return __awaiter(this,undefined,undefined,function(){return __generator(this,function(_a){switch(_a.label){case 0:if(!this.modified)return[3,2];return[4,this.embedder.embedIntoContext(this.doc.context,this.ref)];case 1:_a.sent();this.modified=false;_a.label=2;case 2:return[2]}})})};PDFFont2.of=function(ref,doc,embedder){return new PDFFont2(ref,doc,embedder)};return PDFFont2}();PDFFont_default=PDFFont});var PDFImage,PDFImage_default;var init_PDFImage=__esm(()=>{init_tslib_es62();init_PDFDocument();init_core();init_utils2();PDFImage=function(){function PDFImage2(ref,doc,embedder){assertIs(ref,"ref",[[PDFRef_default,"PDFRef"]]);assertIs(doc,"doc",[[PDFDocument_default,"PDFDocument"]]);assertIs(embedder,"embedder",[[JpegEmbedder_default,"JpegEmbedder"],[PngEmbedder_default,"PngEmbedder"]]);this.ref=ref;this.doc=doc;this.width=embedder.width;this.height=embedder.height;this.embedder=embedder}PDFImage2.prototype.scale=function(factor){assertIs(factor,"factor",["number"]);return{width:this.width*factor,height:this.height*factor}};PDFImage2.prototype.scaleToFit=function(width,height){assertIs(width,"width",["number"]);assertIs(height,"height",["number"]);var imgWidthScale=width/this.width;var imgHeightScale=height/this.height;var scale2=Math.min(imgWidthScale,imgHeightScale);return this.scale(scale2)};PDFImage2.prototype.size=function(){return this.scale(1)};PDFImage2.prototype.embed=function(){return __awaiter(this,undefined,undefined,function(){var _a,doc,ref;return __generator(this,function(_b){switch(_b.label){case 0:if(!this.embedder)return[2];if(!this.embedTask){_a=this,doc=_a.doc,ref=_a.ref;this.embedTask=this.embedder.embedIntoContext(doc.context,ref)}return[4,this.embedTask];case 1:_b.sent();this.embedder=undefined;return[2]}})})};PDFImage2.of=function(ref,doc,embedder){return new PDFImage2(ref,doc,embedder)};return PDFImage2}();PDFImage_default=PDFImage});var ImageAlignment;var init_alignment2=__esm(()=>{(function(ImageAlignment2){ImageAlignment2[ImageAlignment2["Left"]=0]="Left";ImageAlignment2[ImageAlignment2["Center"]=1]="Center";ImageAlignment2[ImageAlignment2["Right"]=2]="Right"})(ImageAlignment||(ImageAlignment={}))});var init_image=__esm(()=>{init_alignment2()});var assertFieldAppearanceOptions=function(options){assertOrUndefined(options===null||options===undefined?undefined:options.x,"options.x",["number"]);assertOrUndefined(options===null||options===undefined?undefined:options.y,"options.y",["number"]);assertOrUndefined(options===null||options===undefined?undefined:options.width,"options.width",["number"]);assertOrUndefined(options===null||options===undefined?undefined:options.height,"options.height",["number"]);assertOrUndefined(options===null||options===undefined?undefined:options.textColor,"options.textColor",[[Object,"Color"]]);assertOrUndefined(options===null||options===undefined?undefined:options.backgroundColor,"options.backgroundColor",[[Object,"Color"]]);assertOrUndefined(options===null||options===undefined?undefined:options.borderColor,"options.borderColor",[[Object,"Color"]]);assertOrUndefined(options===null||options===undefined?undefined:options.borderWidth,"options.borderWidth",["number"]);assertOrUndefined(options===null||options===undefined?undefined:options.rotate,"options.rotate",[[Object,"Rotation"]])},PDFField,PDFField_default;var init_PDFField=__esm(()=>{init_tslib_es62();init_PDFDocument();init_colors();init_rotations();init_core();init_utils2();init_image();init_operations();PDFField=function(){function PDFField2(acroField,ref,doc){assertIs(acroField,"acroField",[[PDFAcroTerminal_default,"PDFAcroTerminal"]]);assertIs(ref,"ref",[[PDFRef_default,"PDFRef"]]);assertIs(doc,"doc",[[PDFDocument_default,"PDFDocument"]]);this.acroField=acroField;this.ref=ref;this.doc=doc}PDFField2.prototype.getName=function(){var _a;return(_a=this.acroField.getFullyQualifiedName())!==null&&_a!==undefined?_a:""};PDFField2.prototype.isReadOnly=function(){return this.acroField.hasFlag(AcroFieldFlags.ReadOnly)};PDFField2.prototype.enableReadOnly=function(){this.acroField.setFlagTo(AcroFieldFlags.ReadOnly,true)};PDFField2.prototype.disableReadOnly=function(){this.acroField.setFlagTo(AcroFieldFlags.ReadOnly,false)};PDFField2.prototype.isRequired=function(){return this.acroField.hasFlag(AcroFieldFlags.Required)};PDFField2.prototype.enableRequired=function(){this.acroField.setFlagTo(AcroFieldFlags.Required,true)};PDFField2.prototype.disableRequired=function(){this.acroField.setFlagTo(AcroFieldFlags.Required,false)};PDFField2.prototype.isExported=function(){return!this.acroField.hasFlag(AcroFieldFlags.NoExport)};PDFField2.prototype.enableExporting=function(){this.acroField.setFlagTo(AcroFieldFlags.NoExport,false)};PDFField2.prototype.disableExporting=function(){this.acroField.setFlagTo(AcroFieldFlags.NoExport,true)};PDFField2.prototype.needsAppearancesUpdate=function(){throw new MethodNotImplementedError(this.constructor.name,"needsAppearancesUpdate")};PDFField2.prototype.defaultUpdateAppearances=function(_font){throw new MethodNotImplementedError(this.constructor.name,"defaultUpdateAppearances")};PDFField2.prototype.markAsDirty=function(){this.doc.getForm().markFieldAsDirty(this.ref)};PDFField2.prototype.markAsClean=function(){this.doc.getForm().markFieldAsClean(this.ref)};PDFField2.prototype.isDirty=function(){return this.doc.getForm().fieldIsDirty(this.ref)};PDFField2.prototype.createWidget=function(options){var _a;var textColor=options.textColor;var backgroundColor=options.backgroundColor;var borderColor=options.borderColor;var borderWidth=options.borderWidth;var degreesAngle=toDegrees(options.rotate);var caption=options.caption;var x=options.x;var y=options.y;var width=options.width+borderWidth;var height=options.height+borderWidth;var hidden=Boolean(options.hidden);var pageRef=options.page;assertMultiple(degreesAngle,"degreesAngle",90);var widget=PDFWidgetAnnotation_default.create(this.doc.context,this.ref);var rect=rotateRectangle({x,y,width,height},borderWidth,degreesAngle);widget.setRectangle(rect);if(pageRef)widget.setP(pageRef);var ac=widget.getOrCreateAppearanceCharacteristics();if(backgroundColor){ac.setBackgroundColor(colorToComponents(backgroundColor))}ac.setRotation(degreesAngle);if(caption)ac.setCaptions({normal:caption});if(borderColor)ac.setBorderColor(colorToComponents(borderColor));var bs=widget.getOrCreateBorderStyle();if(borderWidth!==undefined)bs.setWidth(borderWidth);widget.setFlagTo(AnnotationFlags.Print,true);widget.setFlagTo(AnnotationFlags.Hidden,hidden);widget.setFlagTo(AnnotationFlags.Invisible,false);if(textColor){var da=(_a=this.acroField.getDefaultAppearance())!==null&&_a!==undefined?_a:"";var newDa=da+`
|
|
74
|
-
`+setFillingColor(textColor).toString();this.acroField.setDefaultAppearance(newDa)}return widget};PDFField2.prototype.updateWidgetAppearanceWithFont=function(widget,font,_a){var{normal,rollover,down}=_a;this.updateWidgetAppearances(widget,{normal:this.createAppearanceStream(widget,normal,font),rollover:rollover&&this.createAppearanceStream(widget,rollover,font),down:down&&this.createAppearanceStream(widget,down,font)})};PDFField2.prototype.updateOnOffWidgetAppearance=function(widget,onValue,_a){var{normal,rollover,down}=_a;this.updateWidgetAppearances(widget,{normal:this.createAppearanceDict(widget,normal,onValue),rollover:rollover&&this.createAppearanceDict(widget,rollover,onValue),down:down&&this.createAppearanceDict(widget,down,onValue)})};PDFField2.prototype.updateWidgetAppearances=function(widget,_a){var{normal,rollover,down}=_a;widget.setNormalAppearance(normal);if(rollover){widget.setRolloverAppearance(rollover)}else{widget.removeRolloverAppearance()}if(down){widget.setDownAppearance(down)}else{widget.removeDownAppearance()}};PDFField2.prototype.createAppearanceStream=function(widget,appearance,font){var _a;var context2=this.acroField.dict.context;var _b=widget.getRectangle(),width=_b.width,height=_b.height;var Resources=font&&{Font:(_a={},_a[font.name]=font.ref,_a)};var stream2=context2.formXObject(appearance,{Resources,BBox:context2.obj([0,0,width,height]),Matrix:context2.obj([1,0,0,1,0,0])});var streamRef=context2.register(stream2);return streamRef};PDFField2.prototype.createImageAppearanceStream=function(widget,image,alignment2){var _a;var _b;var context2=this.acroField.dict.context;var rectangle2=widget.getRectangle();var ap=widget.getAppearanceCharacteristics();var bs=widget.getBorderStyle();var borderWidth=(_b=bs===null||bs===undefined?undefined:bs.getWidth())!==null&&_b!==undefined?_b:0;var rotation=reduceRotation(ap===null||ap===undefined?undefined:ap.getRotation());var rotate=rotateInPlace(__assign(__assign({},rectangle2),{rotation}));var adj=adjustDimsForRotation(rectangle2,rotation);var imageDims=image.scaleToFit(adj.width-borderWidth*2,adj.height-borderWidth*2);var options={x:borderWidth,y:borderWidth,width:imageDims.width,height:imageDims.height,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)};if(alignment2===ImageAlignment.Center){options.x+=(adj.width-borderWidth*2)/2-imageDims.width/2;options.y+=(adj.height-borderWidth*2)/2-imageDims.height/2}else if(alignment2===ImageAlignment.Right){options.x=adj.width-borderWidth-imageDims.width;options.y=adj.height-borderWidth-imageDims.height}var imageName=this.doc.context.addRandomSuffix("Image",10);var appearance=__spreadArrays(rotate,drawImage(imageName,options));var Resources={XObject:(_a={},_a[imageName]=image.ref,_a)};var stream2=context2.formXObject(appearance,{Resources,BBox:context2.obj([0,0,rectangle2.width,rectangle2.height]),Matrix:context2.obj([1,0,0,1,0,0])});return context2.register(stream2)};PDFField2.prototype.createAppearanceDict=function(widget,appearance,onValue){var context2=this.acroField.dict.context;var onStreamRef=this.createAppearanceStream(widget,appearance.on);var offStreamRef=this.createAppearanceStream(widget,appearance.off);var appearanceDict=context2.obj({});appearanceDict.set(onValue,onStreamRef);appearanceDict.set(PDFName_default.of("Off"),offStreamRef);return appearanceDict};return PDFField2}();PDFField_default=PDFField});var PDFCheckBox,PDFCheckBox_default;var init_PDFCheckBox=__esm(()=>{init_tslib_es62();init_PDFPage();init_appearances();init_colors();init_rotations();init_PDFField();init_core();init_utils2();PDFCheckBox=function(_super){__extends(PDFCheckBox2,_super);function PDFCheckBox2(acroCheckBox,ref,doc){var _this=_super.call(this,acroCheckBox,ref,doc)||this;assertIs(acroCheckBox,"acroCheckBox",[[PDFAcroCheckBox_default,"PDFAcroCheckBox"]]);_this.acroField=acroCheckBox;return _this}PDFCheckBox2.prototype.check=function(){var _a;var onValue=(_a=this.acroField.getOnValue())!==null&&_a!==undefined?_a:PDFName_default.of("Yes");this.markAsDirty();this.acroField.setValue(onValue)};PDFCheckBox2.prototype.uncheck=function(){this.markAsDirty();this.acroField.setValue(PDFName_default.of("Off"))};PDFCheckBox2.prototype.isChecked=function(){var onValue=this.acroField.getOnValue();return!!onValue&&onValue===this.acroField.getValue()};PDFCheckBox2.prototype.addToPage=function(page,options){var _a,_b,_c,_d,_e,_f;assertIs(page,"page",[[PDFPage_default,"PDFPage"]]);assertFieldAppearanceOptions(options);if(!options)options={};if(!("textColor"in options))options.textColor=rgb(0,0,0);if(!("backgroundColor"in options))options.backgroundColor=rgb(1,1,1);if(!("borderColor"in options))options.borderColor=rgb(0,0,0);if(!("borderWidth"in options))options.borderWidth=1;var widget=this.createWidget({x:(_a=options.x)!==null&&_a!==undefined?_a:0,y:(_b=options.y)!==null&&_b!==undefined?_b:0,width:(_c=options.width)!==null&&_c!==undefined?_c:50,height:(_d=options.height)!==null&&_d!==undefined?_d:50,textColor:options.textColor,backgroundColor:options.backgroundColor,borderColor:options.borderColor,borderWidth:(_e=options.borderWidth)!==null&&_e!==undefined?_e:0,rotate:(_f=options.rotate)!==null&&_f!==undefined?_f:degrees(0),hidden:options.hidden,page:page.ref});var widgetRef=this.doc.context.register(widget.dict);this.acroField.addWidget(widgetRef);widget.setAppearanceState(PDFName_default.of("Off"));this.updateWidgetAppearance(widget,PDFName_default.of("Yes"));page.node.addAnnot(widgetRef)};PDFCheckBox2.prototype.needsAppearancesUpdate=function(){var _a;var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var state=widget.getAppearanceState();var normal=(_a=widget.getAppearances())===null||_a===undefined?undefined:_a.normal;if(!(normal instanceof PDFDict_default))return true;if(state&&!normal.has(state))return true}return false};PDFCheckBox2.prototype.defaultUpdateAppearances=function(){this.updateAppearances()};PDFCheckBox2.prototype.updateAppearances=function(provider2){var _a;assertOrUndefined(provider2,"provider",[Function]);var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var onValue=(_a=widget.getOnValue())!==null&&_a!==undefined?_a:PDFName_default.of("Yes");if(!onValue)continue;this.updateWidgetAppearance(widget,onValue,provider2)}this.markAsClean()};PDFCheckBox2.prototype.updateWidgetAppearance=function(widget,onValue,provider2){var apProvider=provider2!==null&&provider2!==undefined?provider2:defaultCheckBoxAppearanceProvider;var appearances=normalizeAppearance(apProvider(this,widget));this.updateOnOffWidgetAppearance(widget,onValue,appearances)};PDFCheckBox2.of=function(acroCheckBox,ref,doc){return new PDFCheckBox2(acroCheckBox,ref,doc)};return PDFCheckBox2}(PDFField_default);PDFCheckBox_default=PDFCheckBox});var PDFDropdown,PDFDropdown_default;var init_PDFDropdown=__esm(()=>{init_tslib_es62();init_PDFPage();init_PDFFont();init_PDFField();init_appearances();init_colors();init_rotations();init_core();init_utils2();PDFDropdown=function(_super){__extends(PDFDropdown2,_super);function PDFDropdown2(acroComboBox,ref,doc){var _this=_super.call(this,acroComboBox,ref,doc)||this;assertIs(acroComboBox,"acroComboBox",[[PDFAcroComboBox_default,"PDFAcroComboBox"]]);_this.acroField=acroComboBox;return _this}PDFDropdown2.prototype.getOptions=function(){var rawOptions=this.acroField.getOptions();var options=new Array(rawOptions.length);for(var idx4=0,len3=options.length;idx4<len3;idx4++){var _a=rawOptions[idx4],display=_a.display,value=_a.value;options[idx4]=(display!==null&&display!==undefined?display:value).decodeText()}return options};PDFDropdown2.prototype.getSelected=function(){var values2=this.acroField.getValues();var selected=new Array(values2.length);for(var idx4=0,len3=values2.length;idx4<len3;idx4++){selected[idx4]=values2[idx4].decodeText()}return selected};PDFDropdown2.prototype.setOptions=function(options){assertIs(options,"options",[Array]);var optionObjects=new Array(options.length);for(var idx4=0,len3=options.length;idx4<len3;idx4++){optionObjects[idx4]={value:PDFHexString_default.fromText(options[idx4])}}this.acroField.setOptions(optionObjects)};PDFDropdown2.prototype.addOptions=function(options){assertIs(options,"options",["string",Array]);var optionsArr=Array.isArray(options)?options:[options];var existingOptions=this.acroField.getOptions();var newOptions=new Array(optionsArr.length);for(var idx4=0,len3=optionsArr.length;idx4<len3;idx4++){newOptions[idx4]={value:PDFHexString_default.fromText(optionsArr[idx4])}}this.acroField.setOptions(existingOptions.concat(newOptions))};PDFDropdown2.prototype.select=function(options,merge){if(merge===undefined){merge=false}assertIs(options,"options",["string",Array]);assertIs(merge,"merge",["boolean"]);var optionsArr=Array.isArray(options)?options:[options];var validOptions=this.getOptions();var hasCustomOption=optionsArr.find(function(option){return!validOptions.includes(option)});if(hasCustomOption)this.enableEditing();this.markAsDirty();if(optionsArr.length>1||optionsArr.length===1&&merge){this.enableMultiselect()}var values2=new Array(optionsArr.length);for(var idx4=0,len3=optionsArr.length;idx4<len3;idx4++){values2[idx4]=PDFHexString_default.fromText(optionsArr[idx4])}if(merge){var existingValues=this.acroField.getValues();this.acroField.setValues(existingValues.concat(values2))}else{this.acroField.setValues(values2)}};PDFDropdown2.prototype.clear=function(){this.markAsDirty();this.acroField.setValues([])};PDFDropdown2.prototype.setFontSize=function(fontSize){assertPositive(fontSize,"fontSize");this.acroField.setFontSize(fontSize);this.markAsDirty()};PDFDropdown2.prototype.isEditable=function(){return this.acroField.hasFlag(AcroChoiceFlags.Edit)};PDFDropdown2.prototype.enableEditing=function(){this.acroField.setFlagTo(AcroChoiceFlags.Edit,true)};PDFDropdown2.prototype.disableEditing=function(){this.acroField.setFlagTo(AcroChoiceFlags.Edit,false)};PDFDropdown2.prototype.isSorted=function(){return this.acroField.hasFlag(AcroChoiceFlags.Sort)};PDFDropdown2.prototype.enableSorting=function(){this.acroField.setFlagTo(AcroChoiceFlags.Sort,true)};PDFDropdown2.prototype.disableSorting=function(){this.acroField.setFlagTo(AcroChoiceFlags.Sort,false)};PDFDropdown2.prototype.isMultiselect=function(){return this.acroField.hasFlag(AcroChoiceFlags.MultiSelect)};PDFDropdown2.prototype.enableMultiselect=function(){this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect,true)};PDFDropdown2.prototype.disableMultiselect=function(){this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect,false)};PDFDropdown2.prototype.isSpellChecked=function(){return!this.acroField.hasFlag(AcroChoiceFlags.DoNotSpellCheck)};PDFDropdown2.prototype.enableSpellChecking=function(){this.acroField.setFlagTo(AcroChoiceFlags.DoNotSpellCheck,false)};PDFDropdown2.prototype.disableSpellChecking=function(){this.acroField.setFlagTo(AcroChoiceFlags.DoNotSpellCheck,true)};PDFDropdown2.prototype.isSelectOnClick=function(){return this.acroField.hasFlag(AcroChoiceFlags.CommitOnSelChange)};PDFDropdown2.prototype.enableSelectOnClick=function(){this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange,true)};PDFDropdown2.prototype.disableSelectOnClick=function(){this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange,false)};PDFDropdown2.prototype.addToPage=function(page,options){var _a,_b,_c,_d,_e,_f,_g;assertIs(page,"page",[[PDFPage_default,"PDFPage"]]);assertFieldAppearanceOptions(options);if(!options)options={};if(!("textColor"in options))options.textColor=rgb(0,0,0);if(!("backgroundColor"in options))options.backgroundColor=rgb(1,1,1);if(!("borderColor"in options))options.borderColor=rgb(0,0,0);if(!("borderWidth"in options))options.borderWidth=1;var widget=this.createWidget({x:(_a=options.x)!==null&&_a!==undefined?_a:0,y:(_b=options.y)!==null&&_b!==undefined?_b:0,width:(_c=options.width)!==null&&_c!==undefined?_c:200,height:(_d=options.height)!==null&&_d!==undefined?_d:50,textColor:options.textColor,backgroundColor:options.backgroundColor,borderColor:options.borderColor,borderWidth:(_e=options.borderWidth)!==null&&_e!==undefined?_e:0,rotate:(_f=options.rotate)!==null&&_f!==undefined?_f:degrees(0),hidden:options.hidden,page:page.ref});var widgetRef=this.doc.context.register(widget.dict);this.acroField.addWidget(widgetRef);var font=(_g=options.font)!==null&&_g!==undefined?_g:this.doc.getForm().getDefaultFont();this.updateWidgetAppearance(widget,font);page.node.addAnnot(widgetRef)};PDFDropdown2.prototype.needsAppearancesUpdate=function(){var _a;if(this.isDirty())return true;var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var hasAppearances=((_a=widget.getAppearances())===null||_a===undefined?undefined:_a.normal)instanceof PDFStream_default;if(!hasAppearances)return true}return false};PDFDropdown2.prototype.defaultUpdateAppearances=function(font){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);this.updateAppearances(font)};PDFDropdown2.prototype.updateAppearances=function(font,provider2){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);assertOrUndefined(provider2,"provider",[Function]);var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];this.updateWidgetAppearance(widget,font,provider2)}this.markAsClean()};PDFDropdown2.prototype.updateWidgetAppearance=function(widget,font,provider2){var apProvider=provider2!==null&&provider2!==undefined?provider2:defaultDropdownAppearanceProvider;var appearances=normalizeAppearance(apProvider(this,widget,font));this.updateWidgetAppearanceWithFont(widget,font,appearances)};PDFDropdown2.of=function(acroComboBox,ref,doc){return new PDFDropdown2(acroComboBox,ref,doc)};return PDFDropdown2}(PDFField_default);PDFDropdown_default=PDFDropdown});var PDFOptionList,PDFOptionList_default;var init_PDFOptionList=__esm(()=>{init_tslib_es62();init_PDFPage();init_PDFFont();init_PDFField();init_appearances();init_colors();init_rotations();init_core();init_utils2();PDFOptionList=function(_super){__extends(PDFOptionList2,_super);function PDFOptionList2(acroListBox,ref,doc){var _this=_super.call(this,acroListBox,ref,doc)||this;assertIs(acroListBox,"acroListBox",[[PDFAcroListBox_default,"PDFAcroListBox"]]);_this.acroField=acroListBox;return _this}PDFOptionList2.prototype.getOptions=function(){var rawOptions=this.acroField.getOptions();var options=new Array(rawOptions.length);for(var idx4=0,len3=options.length;idx4<len3;idx4++){var _a=rawOptions[idx4],display=_a.display,value=_a.value;options[idx4]=(display!==null&&display!==undefined?display:value).decodeText()}return options};PDFOptionList2.prototype.getSelected=function(){var values2=this.acroField.getValues();var selected=new Array(values2.length);for(var idx4=0,len3=values2.length;idx4<len3;idx4++){selected[idx4]=values2[idx4].decodeText()}return selected};PDFOptionList2.prototype.setOptions=function(options){assertIs(options,"options",[Array]);this.markAsDirty();var optionObjects=new Array(options.length);for(var idx4=0,len3=options.length;idx4<len3;idx4++){optionObjects[idx4]={value:PDFHexString_default.fromText(options[idx4])}}this.acroField.setOptions(optionObjects)};PDFOptionList2.prototype.addOptions=function(options){assertIs(options,"options",["string",Array]);this.markAsDirty();var optionsArr=Array.isArray(options)?options:[options];var existingOptions=this.acroField.getOptions();var newOptions=new Array(optionsArr.length);for(var idx4=0,len3=optionsArr.length;idx4<len3;idx4++){newOptions[idx4]={value:PDFHexString_default.fromText(optionsArr[idx4])}}this.acroField.setOptions(existingOptions.concat(newOptions))};PDFOptionList2.prototype.select=function(options,merge){if(merge===undefined){merge=false}assertIs(options,"options",["string",Array]);assertIs(merge,"merge",["boolean"]);var optionsArr=Array.isArray(options)?options:[options];var validOptions=this.getOptions();assertIsSubset(optionsArr,"option",validOptions);this.markAsDirty();if(optionsArr.length>1||optionsArr.length===1&&merge){this.enableMultiselect()}var values2=new Array(optionsArr.length);for(var idx4=0,len3=optionsArr.length;idx4<len3;idx4++){values2[idx4]=PDFHexString_default.fromText(optionsArr[idx4])}if(merge){var existingValues=this.acroField.getValues();this.acroField.setValues(existingValues.concat(values2))}else{this.acroField.setValues(values2)}};PDFOptionList2.prototype.clear=function(){this.markAsDirty();this.acroField.setValues([])};PDFOptionList2.prototype.setFontSize=function(fontSize){assertPositive(fontSize,"fontSize");this.acroField.setFontSize(fontSize);this.markAsDirty()};PDFOptionList2.prototype.isSorted=function(){return this.acroField.hasFlag(AcroChoiceFlags.Sort)};PDFOptionList2.prototype.enableSorting=function(){this.acroField.setFlagTo(AcroChoiceFlags.Sort,true)};PDFOptionList2.prototype.disableSorting=function(){this.acroField.setFlagTo(AcroChoiceFlags.Sort,false)};PDFOptionList2.prototype.isMultiselect=function(){return this.acroField.hasFlag(AcroChoiceFlags.MultiSelect)};PDFOptionList2.prototype.enableMultiselect=function(){this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect,true)};PDFOptionList2.prototype.disableMultiselect=function(){this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect,false)};PDFOptionList2.prototype.isSelectOnClick=function(){return this.acroField.hasFlag(AcroChoiceFlags.CommitOnSelChange)};PDFOptionList2.prototype.enableSelectOnClick=function(){this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange,true)};PDFOptionList2.prototype.disableSelectOnClick=function(){this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange,false)};PDFOptionList2.prototype.addToPage=function(page,options){var _a,_b,_c,_d,_e,_f,_g;assertIs(page,"page",[[PDFPage_default,"PDFPage"]]);assertFieldAppearanceOptions(options);if(!options)options={};if(!("textColor"in options))options.textColor=rgb(0,0,0);if(!("backgroundColor"in options))options.backgroundColor=rgb(1,1,1);if(!("borderColor"in options))options.borderColor=rgb(0,0,0);if(!("borderWidth"in options))options.borderWidth=1;var widget=this.createWidget({x:(_a=options.x)!==null&&_a!==undefined?_a:0,y:(_b=options.y)!==null&&_b!==undefined?_b:0,width:(_c=options.width)!==null&&_c!==undefined?_c:200,height:(_d=options.height)!==null&&_d!==undefined?_d:100,textColor:options.textColor,backgroundColor:options.backgroundColor,borderColor:options.borderColor,borderWidth:(_e=options.borderWidth)!==null&&_e!==undefined?_e:0,rotate:(_f=options.rotate)!==null&&_f!==undefined?_f:degrees(0),hidden:options.hidden,page:page.ref});var widgetRef=this.doc.context.register(widget.dict);this.acroField.addWidget(widgetRef);var font=(_g=options.font)!==null&&_g!==undefined?_g:this.doc.getForm().getDefaultFont();this.updateWidgetAppearance(widget,font);page.node.addAnnot(widgetRef)};PDFOptionList2.prototype.needsAppearancesUpdate=function(){var _a;if(this.isDirty())return true;var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var hasAppearances=((_a=widget.getAppearances())===null||_a===undefined?undefined:_a.normal)instanceof PDFStream_default;if(!hasAppearances)return true}return false};PDFOptionList2.prototype.defaultUpdateAppearances=function(font){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);this.updateAppearances(font)};PDFOptionList2.prototype.updateAppearances=function(font,provider2){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);assertOrUndefined(provider2,"provider",[Function]);var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];this.updateWidgetAppearance(widget,font,provider2)}this.markAsClean()};PDFOptionList2.prototype.updateWidgetAppearance=function(widget,font,provider2){var apProvider=provider2!==null&&provider2!==undefined?provider2:defaultOptionListAppearanceProvider;var appearances=normalizeAppearance(apProvider(this,widget,font));this.updateWidgetAppearanceWithFont(widget,font,appearances)};PDFOptionList2.of=function(acroListBox,ref,doc){return new PDFOptionList2(acroListBox,ref,doc)};return PDFOptionList2}(PDFField_default);PDFOptionList_default=PDFOptionList});var PDFRadioGroup,PDFRadioGroup_default;var init_PDFRadioGroup=__esm(()=>{init_tslib_es62();init_PDFPage();init_PDFField();init_appearances();init_colors();init_rotations();init_core();init_utils2();PDFRadioGroup=function(_super){__extends(PDFRadioGroup2,_super);function PDFRadioGroup2(acroRadioButton,ref,doc){var _this=_super.call(this,acroRadioButton,ref,doc)||this;assertIs(acroRadioButton,"acroRadioButton",[[PDFAcroRadioButton_default,"PDFAcroRadioButton"]]);_this.acroField=acroRadioButton;return _this}PDFRadioGroup2.prototype.getOptions=function(){var exportValues=this.acroField.getExportValues();if(exportValues){var exportOptions=new Array(exportValues.length);for(var idx4=0,len3=exportValues.length;idx4<len3;idx4++){exportOptions[idx4]=exportValues[idx4].decodeText()}return exportOptions}var onValues=this.acroField.getOnValues();var onOptions=new Array(onValues.length);for(var idx4=0,len3=onOptions.length;idx4<len3;idx4++){onOptions[idx4]=onValues[idx4].decodeText()}return onOptions};PDFRadioGroup2.prototype.getSelected=function(){var value=this.acroField.getValue();if(value===PDFName_default.of("Off"))return;var exportValues=this.acroField.getExportValues();if(exportValues){var onValues=this.acroField.getOnValues();for(var idx4=0,len3=onValues.length;idx4<len3;idx4++){if(onValues[idx4]===value)return exportValues[idx4].decodeText()}}return value.decodeText()};PDFRadioGroup2.prototype.select=function(option){assertIs(option,"option",["string"]);var validOptions=this.getOptions();assertIsOneOf(option,"option",validOptions);this.markAsDirty();var onValues=this.acroField.getOnValues();var exportValues=this.acroField.getExportValues();if(exportValues){for(var idx4=0,len3=exportValues.length;idx4<len3;idx4++){if(exportValues[idx4].decodeText()===option){this.acroField.setValue(onValues[idx4])}}}else{for(var idx4=0,len3=onValues.length;idx4<len3;idx4++){var value=onValues[idx4];if(value.decodeText()===option)this.acroField.setValue(value)}}};PDFRadioGroup2.prototype.clear=function(){this.markAsDirty();this.acroField.setValue(PDFName_default.of("Off"))};PDFRadioGroup2.prototype.isOffToggleable=function(){return!this.acroField.hasFlag(AcroButtonFlags.NoToggleToOff)};PDFRadioGroup2.prototype.enableOffToggling=function(){this.acroField.setFlagTo(AcroButtonFlags.NoToggleToOff,false)};PDFRadioGroup2.prototype.disableOffToggling=function(){this.acroField.setFlagTo(AcroButtonFlags.NoToggleToOff,true)};PDFRadioGroup2.prototype.isMutuallyExclusive=function(){return!this.acroField.hasFlag(AcroButtonFlags.RadiosInUnison)};PDFRadioGroup2.prototype.enableMutualExclusion=function(){this.acroField.setFlagTo(AcroButtonFlags.RadiosInUnison,false)};PDFRadioGroup2.prototype.disableMutualExclusion=function(){this.acroField.setFlagTo(AcroButtonFlags.RadiosInUnison,true)};PDFRadioGroup2.prototype.addOptionToPage=function(option,page,options){var _a,_b,_c,_d,_e,_f,_g,_h,_j;assertIs(option,"option",["string"]);assertIs(page,"page",[[PDFPage_default,"PDFPage"]]);assertFieldAppearanceOptions(options);var widget=this.createWidget({x:(_a=options===null||options===undefined?undefined:options.x)!==null&&_a!==undefined?_a:0,y:(_b=options===null||options===undefined?undefined:options.y)!==null&&_b!==undefined?_b:0,width:(_c=options===null||options===undefined?undefined:options.width)!==null&&_c!==undefined?_c:50,height:(_d=options===null||options===undefined?undefined:options.height)!==null&&_d!==undefined?_d:50,textColor:(_e=options===null||options===undefined?undefined:options.textColor)!==null&&_e!==undefined?_e:rgb(0,0,0),backgroundColor:(_f=options===null||options===undefined?undefined:options.backgroundColor)!==null&&_f!==undefined?_f:rgb(1,1,1),borderColor:(_g=options===null||options===undefined?undefined:options.borderColor)!==null&&_g!==undefined?_g:rgb(0,0,0),borderWidth:(_h=options===null||options===undefined?undefined:options.borderWidth)!==null&&_h!==undefined?_h:1,rotate:(_j=options===null||options===undefined?undefined:options.rotate)!==null&&_j!==undefined?_j:degrees(0),hidden:options===null||options===undefined?undefined:options.hidden,page:page.ref});var widgetRef=this.doc.context.register(widget.dict);var apStateValue=this.acroField.addWidgetWithOpt(widgetRef,PDFHexString_default.fromText(option),!this.isMutuallyExclusive());widget.setAppearanceState(PDFName_default.of("Off"));this.updateWidgetAppearance(widget,apStateValue);page.node.addAnnot(widgetRef)};PDFRadioGroup2.prototype.needsAppearancesUpdate=function(){var _a;var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var state=widget.getAppearanceState();var normal=(_a=widget.getAppearances())===null||_a===undefined?undefined:_a.normal;if(!(normal instanceof PDFDict_default))return true;if(state&&!normal.has(state))return true}return false};PDFRadioGroup2.prototype.defaultUpdateAppearances=function(){this.updateAppearances()};PDFRadioGroup2.prototype.updateAppearances=function(provider2){assertOrUndefined(provider2,"provider",[Function]);var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var onValue=widget.getOnValue();if(!onValue)continue;this.updateWidgetAppearance(widget,onValue,provider2)}};PDFRadioGroup2.prototype.updateWidgetAppearance=function(widget,onValue,provider2){var apProvider=provider2!==null&&provider2!==undefined?provider2:defaultRadioGroupAppearanceProvider;var appearances=normalizeAppearance(apProvider(this,widget));this.updateOnOffWidgetAppearance(widget,onValue,appearances)};PDFRadioGroup2.of=function(acroRadioButton,ref,doc){return new PDFRadioGroup2(acroRadioButton,ref,doc)};return PDFRadioGroup2}(PDFField_default);PDFRadioGroup_default=PDFRadioGroup});var PDFSignature,PDFSignature_default;var init_PDFSignature=__esm(()=>{init_tslib_es62();init_PDFField();init_core();init_utils2();PDFSignature=function(_super){__extends(PDFSignature2,_super);function PDFSignature2(acroSignature,ref,doc){var _this=_super.call(this,acroSignature,ref,doc)||this;assertIs(acroSignature,"acroSignature",[[PDFAcroSignature_default,"PDFAcroSignature"]]);_this.acroField=acroSignature;return _this}PDFSignature2.prototype.needsAppearancesUpdate=function(){return false};PDFSignature2.of=function(acroSignature,ref,doc){return new PDFSignature2(acroSignature,ref,doc)};return PDFSignature2}(PDFField_default);PDFSignature_default=PDFSignature});var PDFTextField,PDFTextField_default;var init_PDFTextField=__esm(()=>{init_tslib_es62();init_PDFPage();init_PDFFont();init_PDFField();init_appearances();init_colors();init_rotations();init_errors3();init_alignment2();init_alignment();init_core();init_utils2();PDFTextField=function(_super){__extends(PDFTextField2,_super);function PDFTextField2(acroText,ref,doc){var _this=_super.call(this,acroText,ref,doc)||this;assertIs(acroText,"acroText",[[PDFAcroText_default,"PDFAcroText"]]);_this.acroField=acroText;return _this}PDFTextField2.prototype.getText=function(){var value=this.acroField.getValue();if(!value&&this.isRichFormatted()){throw new RichTextFieldReadError(this.getName())}return value===null||value===undefined?undefined:value.decodeText()};PDFTextField2.prototype.setText=function(text4){assertOrUndefined(text4,"text",["string"]);var maxLength=this.getMaxLength();if(maxLength!==undefined&&text4&&text4.length>maxLength){throw new ExceededMaxLengthError(text4.length,maxLength,this.getName())}this.markAsDirty();this.disableRichFormatting();if(text4){this.acroField.setValue(PDFHexString_default.fromText(text4))}else{this.acroField.removeValue()}};PDFTextField2.prototype.getAlignment=function(){var quadding=this.acroField.getQuadding();return quadding===0?TextAlignment.Left:quadding===1?TextAlignment.Center:quadding===2?TextAlignment.Right:TextAlignment.Left};PDFTextField2.prototype.setAlignment=function(alignment2){assertIsOneOf(alignment2,"alignment",TextAlignment);this.markAsDirty();this.acroField.setQuadding(alignment2)};PDFTextField2.prototype.getMaxLength=function(){return this.acroField.getMaxLength()};PDFTextField2.prototype.setMaxLength=function(maxLength){assertRangeOrUndefined(maxLength,"maxLength",0,Number.MAX_SAFE_INTEGER);this.markAsDirty();if(maxLength===undefined){this.acroField.removeMaxLength()}else{var text4=this.getText();if(text4&&text4.length>maxLength){throw new InvalidMaxLengthError(text4.length,maxLength,this.getName())}this.acroField.setMaxLength(maxLength)}};PDFTextField2.prototype.removeMaxLength=function(){this.markAsDirty();this.acroField.removeMaxLength()};PDFTextField2.prototype.setImage=function(image){var fieldAlignment=this.getAlignment();var alignment2=fieldAlignment===TextAlignment.Center?ImageAlignment.Center:fieldAlignment===TextAlignment.Right?ImageAlignment.Right:ImageAlignment.Left;var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var streamRef=this.createImageAppearanceStream(widget,image,alignment2);this.updateWidgetAppearances(widget,{normal:streamRef})}this.markAsClean()};PDFTextField2.prototype.setFontSize=function(fontSize){assertPositive(fontSize,"fontSize");this.acroField.setFontSize(fontSize);this.markAsDirty()};PDFTextField2.prototype.isMultiline=function(){return this.acroField.hasFlag(AcroTextFlags.Multiline)};PDFTextField2.prototype.enableMultiline=function(){this.markAsDirty();this.acroField.setFlagTo(AcroTextFlags.Multiline,true)};PDFTextField2.prototype.disableMultiline=function(){this.markAsDirty();this.acroField.setFlagTo(AcroTextFlags.Multiline,false)};PDFTextField2.prototype.isPassword=function(){return this.acroField.hasFlag(AcroTextFlags.Password)};PDFTextField2.prototype.enablePassword=function(){this.acroField.setFlagTo(AcroTextFlags.Password,true)};PDFTextField2.prototype.disablePassword=function(){this.acroField.setFlagTo(AcroTextFlags.Password,false)};PDFTextField2.prototype.isFileSelector=function(){return this.acroField.hasFlag(AcroTextFlags.FileSelect)};PDFTextField2.prototype.enableFileSelection=function(){this.acroField.setFlagTo(AcroTextFlags.FileSelect,true)};PDFTextField2.prototype.disableFileSelection=function(){this.acroField.setFlagTo(AcroTextFlags.FileSelect,false)};PDFTextField2.prototype.isSpellChecked=function(){return!this.acroField.hasFlag(AcroTextFlags.DoNotSpellCheck)};PDFTextField2.prototype.enableSpellChecking=function(){this.acroField.setFlagTo(AcroTextFlags.DoNotSpellCheck,false)};PDFTextField2.prototype.disableSpellChecking=function(){this.acroField.setFlagTo(AcroTextFlags.DoNotSpellCheck,true)};PDFTextField2.prototype.isScrollable=function(){return!this.acroField.hasFlag(AcroTextFlags.DoNotScroll)};PDFTextField2.prototype.enableScrolling=function(){this.acroField.setFlagTo(AcroTextFlags.DoNotScroll,false)};PDFTextField2.prototype.disableScrolling=function(){this.acroField.setFlagTo(AcroTextFlags.DoNotScroll,true)};PDFTextField2.prototype.isCombed=function(){return this.acroField.hasFlag(AcroTextFlags.Comb)&&!this.isMultiline()&&!this.isPassword()&&!this.isFileSelector()&&this.getMaxLength()!==undefined};PDFTextField2.prototype.enableCombing=function(){if(this.getMaxLength()===undefined){var msg="PDFTextFields must have a max length in order to be combed";console.warn(msg)}this.markAsDirty();this.disableMultiline();this.disablePassword();this.disableFileSelection();this.acroField.setFlagTo(AcroTextFlags.Comb,true)};PDFTextField2.prototype.disableCombing=function(){this.markAsDirty();this.acroField.setFlagTo(AcroTextFlags.Comb,false)};PDFTextField2.prototype.isRichFormatted=function(){return this.acroField.hasFlag(AcroTextFlags.RichText)};PDFTextField2.prototype.enableRichFormatting=function(){this.acroField.setFlagTo(AcroTextFlags.RichText,true)};PDFTextField2.prototype.disableRichFormatting=function(){this.acroField.setFlagTo(AcroTextFlags.RichText,false)};PDFTextField2.prototype.addToPage=function(page,options){var _a,_b,_c,_d,_e,_f,_g;assertIs(page,"page",[[PDFPage_default,"PDFPage"]]);assertFieldAppearanceOptions(options);if(!options)options={};if(!("textColor"in options))options.textColor=rgb(0,0,0);if(!("backgroundColor"in options))options.backgroundColor=rgb(1,1,1);if(!("borderColor"in options))options.borderColor=rgb(0,0,0);if(!("borderWidth"in options))options.borderWidth=1;var widget=this.createWidget({x:(_a=options.x)!==null&&_a!==undefined?_a:0,y:(_b=options.y)!==null&&_b!==undefined?_b:0,width:(_c=options.width)!==null&&_c!==undefined?_c:200,height:(_d=options.height)!==null&&_d!==undefined?_d:50,textColor:options.textColor,backgroundColor:options.backgroundColor,borderColor:options.borderColor,borderWidth:(_e=options.borderWidth)!==null&&_e!==undefined?_e:0,rotate:(_f=options.rotate)!==null&&_f!==undefined?_f:degrees(0),hidden:options.hidden,page:page.ref});var widgetRef=this.doc.context.register(widget.dict);this.acroField.addWidget(widgetRef);var font=(_g=options.font)!==null&&_g!==undefined?_g:this.doc.getForm().getDefaultFont();this.updateWidgetAppearance(widget,font);page.node.addAnnot(widgetRef)};PDFTextField2.prototype.needsAppearancesUpdate=function(){var _a;if(this.isDirty())return true;var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var hasAppearances=((_a=widget.getAppearances())===null||_a===undefined?undefined:_a.normal)instanceof PDFStream_default;if(!hasAppearances)return true}return false};PDFTextField2.prototype.defaultUpdateAppearances=function(font){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);this.updateAppearances(font)};PDFTextField2.prototype.updateAppearances=function(font,provider2){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);assertOrUndefined(provider2,"provider",[Function]);var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];this.updateWidgetAppearance(widget,font,provider2)}this.markAsClean()};PDFTextField2.prototype.updateWidgetAppearance=function(widget,font,provider2){var apProvider=provider2!==null&&provider2!==undefined?provider2:defaultTextFieldAppearanceProvider;var appearances=normalizeAppearance(apProvider(this,widget,font));this.updateWidgetAppearanceWithFont(widget,font,appearances)};PDFTextField2.of=function(acroText,ref,doc){return new PDFTextField2(acroText,ref,doc)};return PDFTextField2}(PDFField_default);PDFTextField_default=PDFTextField});var StandardFonts;var init_StandardFonts=__esm(()=>{(function(StandardFonts2){StandardFonts2["Courier"]="Courier";StandardFonts2["CourierBold"]="Courier-Bold";StandardFonts2["CourierOblique"]="Courier-Oblique";StandardFonts2["CourierBoldOblique"]="Courier-BoldOblique";StandardFonts2["Helvetica"]="Helvetica";StandardFonts2["HelveticaBold"]="Helvetica-Bold";StandardFonts2["HelveticaOblique"]="Helvetica-Oblique";StandardFonts2["HelveticaBoldOblique"]="Helvetica-BoldOblique";StandardFonts2["TimesRoman"]="Times-Roman";StandardFonts2["TimesRomanBold"]="Times-Bold";StandardFonts2["TimesRomanItalic"]="Times-Italic";StandardFonts2["TimesRomanBoldItalic"]="Times-BoldItalic";StandardFonts2["Symbol"]="Symbol";StandardFonts2["ZapfDingbats"]="ZapfDingbats"})(StandardFonts||(StandardFonts={}))});var PDFForm,PDFForm_default,convertToPDFField=function(field,ref,doc){if(field instanceof PDFAcroPushButton_default)return PDFButton_default.of(field,ref,doc);if(field instanceof PDFAcroCheckBox_default)return PDFCheckBox_default.of(field,ref,doc);if(field instanceof PDFAcroComboBox_default)return PDFDropdown_default.of(field,ref,doc);if(field instanceof PDFAcroListBox_default)return PDFOptionList_default.of(field,ref,doc);if(field instanceof PDFAcroText_default)return PDFTextField_default.of(field,ref,doc);if(field instanceof PDFAcroRadioButton_default){return PDFRadioGroup_default.of(field,ref,doc)}if(field instanceof PDFAcroSignature_default){return PDFSignature_default.of(field,ref,doc)}return},splitFieldName=function(fullyQualifiedName){if(fullyQualifiedName.length===0){throw new Error("PDF field names must not be empty strings")}var parts=fullyQualifiedName.split(".");for(var idx4=0,len3=parts.length;idx4<len3;idx4++){if(parts[idx4]===""){throw new Error('Periods in PDF field names must be separated by at least one character: "'+fullyQualifiedName+'"')}}if(parts.length===1)return{nonTerminal:[],terminal:parts[0]};return{nonTerminal:parts.slice(0,parts.length-1),terminal:parts[parts.length-1]}},addFieldToParent=function(_a,_b,partialName){var parent=_a[0],parentRef=_a[1];var field=_b[0],fieldRef=_b[1];var entries=parent.normalizedEntries();var fields5=createPDFAcroFields("Kids"in entries?entries.Kids:entries.Fields);for(var idx4=0,len3=fields5.length;idx4<len3;idx4++){if(fields5[idx4][0].getPartialName()===partialName){throw new FieldAlreadyExistsError(partialName)}}parent.addField(fieldRef);field.setParent(parentRef)};var init_PDFForm=__esm(()=>{init_tslib_es62();init_PDFDocument();init_PDFButton();init_PDFCheckBox();init_PDFDropdown();init_PDFOptionList();init_PDFRadioGroup();init_PDFSignature();init_PDFTextField();init_errors3();init_PDFFont();init_StandardFonts();init_operations();init_operators();init_core();init_utils2();PDFForm=function(){function PDFForm2(acroForm,doc){var _this=this;this.embedDefaultFont=function(){return _this.doc.embedStandardFont(StandardFonts.Helvetica)};assertIs(acroForm,"acroForm",[[PDFAcroForm_default,"PDFAcroForm"]]);assertIs(doc,"doc",[[PDFDocument_default,"PDFDocument"]]);this.acroForm=acroForm;this.doc=doc;this.dirtyFields=new Set;this.defaultFontCache=Cache_default.populatedBy(this.embedDefaultFont)}PDFForm2.prototype.hasXFA=function(){return this.acroForm.dict.has(PDFName_default.of("XFA"))};PDFForm2.prototype.deleteXFA=function(){this.acroForm.dict.delete(PDFName_default.of("XFA"))};PDFForm2.prototype.getFields=function(){var allFields=this.acroForm.getAllFields();var fields5=[];for(var idx4=0,len3=allFields.length;idx4<len3;idx4++){var _a=allFields[idx4],acroField=_a[0],ref=_a[1];var field=convertToPDFField(acroField,ref,this.doc);if(field)fields5.push(field)}return fields5};PDFForm2.prototype.getFieldMaybe=function(name){assertIs(name,"name",["string"]);var fields5=this.getFields();for(var idx4=0,len3=fields5.length;idx4<len3;idx4++){var field=fields5[idx4];if(field.getName()===name)return field}return};PDFForm2.prototype.getField=function(name){assertIs(name,"name",["string"]);var field=this.getFieldMaybe(name);if(field)return field;throw new NoSuchFieldError(name)};PDFForm2.prototype.getButton=function(name){assertIs(name,"name",["string"]);var field=this.getField(name);if(field instanceof PDFButton_default)return field;throw new UnexpectedFieldTypeError(name,PDFButton_default,field)};PDFForm2.prototype.getCheckBox=function(name){assertIs(name,"name",["string"]);var field=this.getField(name);if(field instanceof PDFCheckBox_default)return field;throw new UnexpectedFieldTypeError(name,PDFCheckBox_default,field)};PDFForm2.prototype.getDropdown=function(name){assertIs(name,"name",["string"]);var field=this.getField(name);if(field instanceof PDFDropdown_default)return field;throw new UnexpectedFieldTypeError(name,PDFDropdown_default,field)};PDFForm2.prototype.getOptionList=function(name){assertIs(name,"name",["string"]);var field=this.getField(name);if(field instanceof PDFOptionList_default)return field;throw new UnexpectedFieldTypeError(name,PDFOptionList_default,field)};PDFForm2.prototype.getRadioGroup=function(name){assertIs(name,"name",["string"]);var field=this.getField(name);if(field instanceof PDFRadioGroup_default)return field;throw new UnexpectedFieldTypeError(name,PDFRadioGroup_default,field)};PDFForm2.prototype.getSignature=function(name){assertIs(name,"name",["string"]);var field=this.getField(name);if(field instanceof PDFSignature_default)return field;throw new UnexpectedFieldTypeError(name,PDFSignature_default,field)};PDFForm2.prototype.getTextField=function(name){assertIs(name,"name",["string"]);var field=this.getField(name);if(field instanceof PDFTextField_default)return field;throw new UnexpectedFieldTypeError(name,PDFTextField_default,field)};PDFForm2.prototype.createButton=function(name){assertIs(name,"name",["string"]);var nameParts=splitFieldName(name);var parent=this.findOrCreateNonTerminals(nameParts.nonTerminal);var button=PDFAcroPushButton_default.create(this.doc.context);button.setPartialName(nameParts.terminal);addFieldToParent(parent,[button,button.ref],nameParts.terminal);return PDFButton_default.of(button,button.ref,this.doc)};PDFForm2.prototype.createCheckBox=function(name){assertIs(name,"name",["string"]);var nameParts=splitFieldName(name);var parent=this.findOrCreateNonTerminals(nameParts.nonTerminal);var checkBox=PDFAcroCheckBox_default.create(this.doc.context);checkBox.setPartialName(nameParts.terminal);addFieldToParent(parent,[checkBox,checkBox.ref],nameParts.terminal);return PDFCheckBox_default.of(checkBox,checkBox.ref,this.doc)};PDFForm2.prototype.createDropdown=function(name){assertIs(name,"name",["string"]);var nameParts=splitFieldName(name);var parent=this.findOrCreateNonTerminals(nameParts.nonTerminal);var comboBox=PDFAcroComboBox_default.create(this.doc.context);comboBox.setPartialName(nameParts.terminal);addFieldToParent(parent,[comboBox,comboBox.ref],nameParts.terminal);return PDFDropdown_default.of(comboBox,comboBox.ref,this.doc)};PDFForm2.prototype.createOptionList=function(name){assertIs(name,"name",["string"]);var nameParts=splitFieldName(name);var parent=this.findOrCreateNonTerminals(nameParts.nonTerminal);var listBox=PDFAcroListBox_default.create(this.doc.context);listBox.setPartialName(nameParts.terminal);addFieldToParent(parent,[listBox,listBox.ref],nameParts.terminal);return PDFOptionList_default.of(listBox,listBox.ref,this.doc)};PDFForm2.prototype.createRadioGroup=function(name){assertIs(name,"name",["string"]);var nameParts=splitFieldName(name);var parent=this.findOrCreateNonTerminals(nameParts.nonTerminal);var radioButton=PDFAcroRadioButton_default.create(this.doc.context);radioButton.setPartialName(nameParts.terminal);addFieldToParent(parent,[radioButton,radioButton.ref],nameParts.terminal);return PDFRadioGroup_default.of(radioButton,radioButton.ref,this.doc)};PDFForm2.prototype.createTextField=function(name){assertIs(name,"name",["string"]);var nameParts=splitFieldName(name);var parent=this.findOrCreateNonTerminals(nameParts.nonTerminal);var text4=PDFAcroText_default.create(this.doc.context);text4.setPartialName(nameParts.terminal);addFieldToParent(parent,[text4,text4.ref],nameParts.terminal);return PDFTextField_default.of(text4,text4.ref,this.doc)};PDFForm2.prototype.flatten=function(options){if(options===undefined){options={updateFieldAppearances:true}}if(options.updateFieldAppearances){this.updateFieldAppearances()}var fields5=this.getFields();for(var i3=0,lenFields=fields5.length;i3<lenFields;i3++){var field=fields5[i3];var widgets=field.acroField.getWidgets();for(var j=0,lenWidgets=widgets.length;j<lenWidgets;j++){var widget=widgets[j];var page=this.findWidgetPage(widget);var widgetRef=this.findWidgetAppearanceRef(field,widget);var xObjectKey=page.node.newXObject("FlatWidget",widgetRef);var rectangle2=widget.getRectangle();var operators=__spreadArrays([pushGraphicsState(),translate(rectangle2.x,rectangle2.y)],rotateInPlace(__assign(__assign({},rectangle2),{rotation:0})),[drawObject(xObjectKey),popGraphicsState()]).filter(Boolean);page.pushOperators.apply(page,operators)}this.removeField(field)}};PDFForm2.prototype.removeField=function(field){var widgets=field.acroField.getWidgets();var pages=new Set;for(var i3=0,len3=widgets.length;i3<len3;i3++){var widget=widgets[i3];var widgetRef=this.findWidgetAppearanceRef(field,widget);var page=this.findWidgetPage(widget);pages.add(page);page.node.removeAnnot(widgetRef)}pages.forEach(function(page2){return page2.node.removeAnnot(field.ref)});this.acroForm.removeField(field.acroField);var fieldKids=field.acroField.normalizedEntries().Kids;var kidsCount=fieldKids.size();for(var childIndex=0;childIndex<kidsCount;childIndex++){var child=fieldKids.get(childIndex);if(child instanceof PDFRef_default){this.doc.context.delete(child)}}this.doc.context.delete(field.ref)};PDFForm2.prototype.updateFieldAppearances=function(font){assertOrUndefined(font,"font",[[PDFFont_default,"PDFFont"]]);font=font!==null&&font!==undefined?font:this.getDefaultFont();var fields5=this.getFields();for(var idx4=0,len3=fields5.length;idx4<len3;idx4++){var field=fields5[idx4];if(field.needsAppearancesUpdate()){field.defaultUpdateAppearances(font)}}};PDFForm2.prototype.markFieldAsDirty=function(fieldRef){assertOrUndefined(fieldRef,"fieldRef",[[PDFRef_default,"PDFRef"]]);this.dirtyFields.add(fieldRef)};PDFForm2.prototype.markFieldAsClean=function(fieldRef){assertOrUndefined(fieldRef,"fieldRef",[[PDFRef_default,"PDFRef"]]);this.dirtyFields.delete(fieldRef)};PDFForm2.prototype.fieldIsDirty=function(fieldRef){assertOrUndefined(fieldRef,"fieldRef",[[PDFRef_default,"PDFRef"]]);return this.dirtyFields.has(fieldRef)};PDFForm2.prototype.getDefaultFont=function(){return this.defaultFontCache.access()};PDFForm2.prototype.findWidgetPage=function(widget){var pageRef=widget.P();var page=this.doc.getPages().find(function(x){return x.ref===pageRef});if(page===undefined){var widgetRef=this.doc.context.getObjectRef(widget.dict);if(widgetRef===undefined){throw new Error("Could not find PDFRef for PDFObject")}page=this.doc.findPageForAnnotationRef(widgetRef);if(page===undefined){throw new Error("Could not find page for PDFRef "+widgetRef)}}return page};PDFForm2.prototype.findWidgetAppearanceRef=function(field,widget){var _a;var refOrDict=widget.getNormalAppearance();if(refOrDict instanceof PDFDict_default&&(field instanceof PDFCheckBox_default||field instanceof PDFRadioGroup_default)){var value=field.acroField.getValue();var ref=(_a=refOrDict.get(value))!==null&&_a!==undefined?_a:refOrDict.get(PDFName_default.of("Off"));if(ref instanceof PDFRef_default){refOrDict=ref}}if(!(refOrDict instanceof PDFRef_default)){var name_1=field.getName();throw new Error("Failed to extract appearance ref for: "+name_1)}return refOrDict};PDFForm2.prototype.findOrCreateNonTerminals=function(partialNames){var nonTerminal=[this.acroForm];for(var idx4=0,len3=partialNames.length;idx4<len3;idx4++){var namePart=partialNames[idx4];if(!namePart)throw new InvalidFieldNamePartError(namePart);var parent_1=nonTerminal[0],parentRef=nonTerminal[1];var res=this.findNonTerminal(namePart,parent_1);if(res){nonTerminal=res}else{var node=PDFAcroNonTerminal_default.create(this.doc.context);node.setPartialName(namePart);node.setParent(parentRef);var nodeRef=this.doc.context.register(node.dict);parent_1.addField(nodeRef);nonTerminal=[node,nodeRef]}}return nonTerminal};PDFForm2.prototype.findNonTerminal=function(partialName,parent){var fields5=parent instanceof PDFAcroForm_default?this.acroForm.getFields():createPDFAcroFields(parent.Kids());for(var idx4=0,len3=fields5.length;idx4<len3;idx4++){var _a=fields5[idx4],field=_a[0],ref=_a[1];if(field.getPartialName()===partialName){if(field instanceof PDFAcroNonTerminal_default)return[field,ref];throw new FieldAlreadyExistsError(partialName)}}return};PDFForm2.of=function(acroForm,doc){return new PDFForm2(acroForm,doc)};return PDFForm2}();PDFForm_default=PDFForm});var PageSizes;var init_sizes=__esm(()=>{PageSizes={"4A0":[4767.87,6740.79],"2A0":[3370.39,4767.87],A0:[2383.94,3370.39],A1:[1683.78,2383.94],A2:[1190.55,1683.78],A3:[841.89,1190.55],A4:[595.28,841.89],A5:[419.53,595.28],A6:[297.64,419.53],A7:[209.76,297.64],A8:[147.4,209.76],A9:[104.88,147.4],A10:[73.7,104.88],B0:[2834.65,4008.19],B1:[2004.09,2834.65],B2:[1417.32,2004.09],B3:[1000.63,1417.32],B4:[708.66,1000.63],B5:[498.9,708.66],B6:[354.33,498.9],B7:[249.45,354.33],B8:[175.75,249.45],B9:[124.72,175.75],B10:[87.87,124.72],C0:[2599.37,3676.54],C1:[1836.85,2599.37],C2:[1298.27,1836.85],C3:[918.43,1298.27],C4:[649.13,918.43],C5:[459.21,649.13],C6:[323.15,459.21],C7:[229.61,323.15],C8:[161.57,229.61],C9:[113.39,161.57],C10:[79.37,113.39],RA0:[2437.8,3458.27],RA1:[1729.13,2437.8],RA2:[1218.9,1729.13],RA3:[864.57,1218.9],RA4:[609.45,864.57],SRA0:[2551.18,3628.35],SRA1:[1814.17,2551.18],SRA2:[1275.59,1814.17],SRA3:[907.09,1275.59],SRA4:[637.8,907.09],Executive:[521.86,756],Folio:[612,936],Legal:[612,1008],Letter:[612,792],Tabloid:[792,1224]}});var ParseSpeeds;var init_PDFDocumentOptions=__esm(()=>{(function(ParseSpeeds2){ParseSpeeds2[ParseSpeeds2["Fastest"]=Infinity]="Fastest";ParseSpeeds2[ParseSpeeds2["Fast"]=1500]="Fast";ParseSpeeds2[ParseSpeeds2["Medium"]=500]="Medium";ParseSpeeds2[ParseSpeeds2["Slow"]=100]="Slow"})(ParseSpeeds||(ParseSpeeds={}))});var PDFEmbeddedFile,PDFEmbeddedFile_default;var init_PDFEmbeddedFile=__esm(()=>{init_tslib_es62();init_core();PDFEmbeddedFile=function(){function PDFEmbeddedFile2(ref,doc,embedder){this.alreadyEmbedded=false;this.ref=ref;this.doc=doc;this.embedder=embedder}PDFEmbeddedFile2.prototype.embed=function(){return __awaiter(this,undefined,undefined,function(){var ref,Names,EmbeddedFiles,EFNames,AF;return __generator(this,function(_a){switch(_a.label){case 0:if(!!this.alreadyEmbedded)return[3,2];return[4,this.embedder.embedIntoContext(this.doc.context,this.ref)];case 1:ref=_a.sent();if(!this.doc.catalog.has(PDFName_default.of("Names"))){this.doc.catalog.set(PDFName_default.of("Names"),this.doc.context.obj({}))}Names=this.doc.catalog.lookup(PDFName_default.of("Names"),PDFDict_default);if(!Names.has(PDFName_default.of("EmbeddedFiles"))){Names.set(PDFName_default.of("EmbeddedFiles"),this.doc.context.obj({}))}EmbeddedFiles=Names.lookup(PDFName_default.of("EmbeddedFiles"),PDFDict_default);if(!EmbeddedFiles.has(PDFName_default.of("Names"))){EmbeddedFiles.set(PDFName_default.of("Names"),this.doc.context.obj([]))}EFNames=EmbeddedFiles.lookup(PDFName_default.of("Names"),PDFArray_default);EFNames.push(PDFHexString_default.fromText(this.embedder.fileName));EFNames.push(ref);if(!this.doc.catalog.has(PDFName_default.of("AF"))){this.doc.catalog.set(PDFName_default.of("AF"),this.doc.context.obj([]))}AF=this.doc.catalog.lookup(PDFName_default.of("AF"),PDFArray_default);AF.push(ref);this.alreadyEmbedded=true;_a.label=2;case 2:return[2]}})})};PDFEmbeddedFile2.of=function(ref,doc,embedder){return new PDFEmbeddedFile2(ref,doc,embedder)};return PDFEmbeddedFile2}();PDFEmbeddedFile_default=PDFEmbeddedFile});var PDFJavaScript,PDFJavaScript_default;var init_PDFJavaScript=__esm(()=>{init_tslib_es62();init_core();PDFJavaScript=function(){function PDFJavaScript2(ref,doc,embedder){this.alreadyEmbedded=false;this.ref=ref;this.doc=doc;this.embedder=embedder}PDFJavaScript2.prototype.embed=function(){return __awaiter(this,undefined,undefined,function(){var _a,catalog,context2,ref,Names,Javascript,JSNames;return __generator(this,function(_b){switch(_b.label){case 0:if(!!this.alreadyEmbedded)return[3,2];_a=this.doc,catalog=_a.catalog,context2=_a.context;return[4,this.embedder.embedIntoContext(this.doc.context,this.ref)];case 1:ref=_b.sent();if(!catalog.has(PDFName_default.of("Names"))){catalog.set(PDFName_default.of("Names"),context2.obj({}))}Names=catalog.lookup(PDFName_default.of("Names"),PDFDict_default);if(!Names.has(PDFName_default.of("JavaScript"))){Names.set(PDFName_default.of("JavaScript"),context2.obj({}))}Javascript=Names.lookup(PDFName_default.of("JavaScript"),PDFDict_default);if(!Javascript.has(PDFName_default.of("Names"))){Javascript.set(PDFName_default.of("Names"),context2.obj([]))}JSNames=Javascript.lookup(PDFName_default.of("Names"),PDFArray_default);JSNames.push(PDFHexString_default.fromText(this.embedder.scriptName));JSNames.push(ref);this.alreadyEmbedded=true;_b.label=2;case 2:return[2]}})})};PDFJavaScript2.of=function(ref,doc,embedder){return new PDFJavaScript2(ref,doc,embedder)};return PDFJavaScript2}();PDFJavaScript_default=PDFJavaScript});var JavaScriptEmbedder,JavaScriptEmbedder_default;var init_JavaScriptEmbedder=__esm(()=>{init_tslib_es62();init_PDFHexString();JavaScriptEmbedder=function(){function JavaScriptEmbedder2(script,scriptName){this.script=script;this.scriptName=scriptName}JavaScriptEmbedder2.for=function(script,scriptName){return new JavaScriptEmbedder2(script,scriptName)};JavaScriptEmbedder2.prototype.embedIntoContext=function(context2,ref){return __awaiter(this,undefined,undefined,function(){var jsActionDict;return __generator(this,function(_a){jsActionDict=context2.obj({Type:"Action",S:"JavaScript",JS:PDFHexString_default.fromText(this.script)});if(ref){context2.assign(ref,jsActionDict);return[2,ref]}else{return[2,context2.register(jsActionDict)]}return[2]})})};return JavaScriptEmbedder2}();JavaScriptEmbedder_default=JavaScriptEmbedder});function assertIsLiteralOrHexString(pdfObject){if(!(pdfObject instanceof PDFHexString_default)&&!(pdfObject instanceof PDFString_default)){throw new UnexpectedObjectTypeError([PDFHexString_default,PDFString_default],pdfObject)}}var PDFDocument,PDFDocument_default;var init_PDFDocument=__esm(()=>{init_tslib_es62();init_errors3();init_PDFEmbeddedPage();init_PDFFont();init_PDFImage();init_PDFPage();init_PDFForm();init_sizes();init_core();init_PDFDocumentOptions();init_utils2();init_FileEmbedder();init_PDFEmbeddedFile();init_PDFJavaScript();init_JavaScriptEmbedder();PDFDocument=function(){function PDFDocument2(context2,ignoreEncryption,updateMetadata){var _this=this;this.defaultWordBreaks=[" "];this.computePages=function(){var pages=[];_this.catalog.Pages().traverse(function(node,ref){if(node instanceof PDFPageLeaf_default){var page=_this.pageMap.get(node);if(!page){page=PDFPage_default.of(node,ref,_this);_this.pageMap.set(node,page)}pages.push(page)}});return pages};this.getOrCreateForm=function(){var acroForm=_this.catalog.getOrCreateAcroForm();return PDFForm_default.of(acroForm,_this)};assertIs(context2,"context",[[PDFContext_default,"PDFContext"]]);assertIs(ignoreEncryption,"ignoreEncryption",["boolean"]);this.context=context2;this.catalog=context2.lookup(context2.trailerInfo.Root);this.isEncrypted=!!context2.lookup(context2.trailerInfo.Encrypt);this.pageCache=Cache_default.populatedBy(this.computePages);this.pageMap=new Map;this.formCache=Cache_default.populatedBy(this.getOrCreateForm);this.fonts=[];this.images=[];this.embeddedPages=[];this.embeddedFiles=[];this.javaScripts=[];if(!ignoreEncryption&&this.isEncrypted)throw new EncryptedPDFError;if(updateMetadata)this.updateInfoDict()}PDFDocument2.load=function(pdf,options){if(options===undefined){options={}}return __awaiter(this,undefined,undefined,function(){var _a,ignoreEncryption,_b,parseSpeed,_c,throwOnInvalidObject,_d,updateMetadata,_e,capNumbers,bytes,context2;return __generator(this,function(_f){switch(_f.label){case 0:_a=options.ignoreEncryption,ignoreEncryption=_a===undefined?false:_a,_b=options.parseSpeed,parseSpeed=_b===undefined?ParseSpeeds.Slow:_b,_c=options.throwOnInvalidObject,throwOnInvalidObject=_c===undefined?false:_c,_d=options.updateMetadata,updateMetadata=_d===undefined?true:_d,_e=options.capNumbers,capNumbers=_e===undefined?false:_e;assertIs(pdf,"pdf",["string",Uint8Array,ArrayBuffer]);assertIs(ignoreEncryption,"ignoreEncryption",["boolean"]);assertIs(parseSpeed,"parseSpeed",["number"]);assertIs(throwOnInvalidObject,"throwOnInvalidObject",["boolean"]);bytes=toUint8Array(pdf);return[4,PDFParser_default.forBytesWithOptions(bytes,parseSpeed,throwOnInvalidObject,capNumbers).parseDocument()];case 1:context2=_f.sent();return[2,new PDFDocument2(context2,ignoreEncryption,updateMetadata)]}})})};PDFDocument2.create=function(options){if(options===undefined){options={}}return __awaiter(this,undefined,undefined,function(){var _a,updateMetadata,context2,pageTree,pageTreeRef,catalog;return __generator(this,function(_b){_a=options.updateMetadata,updateMetadata=_a===undefined?true:_a;context2=PDFContext_default.create();pageTree=PDFPageTree_default.withContext(context2);pageTreeRef=context2.register(pageTree);catalog=PDFCatalog_default.withContextAndPages(context2,pageTreeRef);context2.trailerInfo.Root=context2.register(catalog);return[2,new PDFDocument2(context2,false,updateMetadata)]})})};PDFDocument2.prototype.registerFontkit=function(fontkit){this.fontkit=fontkit};PDFDocument2.prototype.getForm=function(){var form=this.formCache.access();if(form.hasXFA()){console.warn("Removing XFA form data as pdf-lib does not support reading or writing XFA");form.deleteXFA()}return form};PDFDocument2.prototype.getTitle=function(){var title=this.getInfoDict().lookup(PDFName_default.Title);if(!title)return;assertIsLiteralOrHexString(title);return title.decodeText()};PDFDocument2.prototype.getAuthor=function(){var author=this.getInfoDict().lookup(PDFName_default.Author);if(!author)return;assertIsLiteralOrHexString(author);return author.decodeText()};PDFDocument2.prototype.getSubject=function(){var subject=this.getInfoDict().lookup(PDFName_default.Subject);if(!subject)return;assertIsLiteralOrHexString(subject);return subject.decodeText()};PDFDocument2.prototype.getKeywords=function(){var keywords=this.getInfoDict().lookup(PDFName_default.Keywords);if(!keywords)return;assertIsLiteralOrHexString(keywords);return keywords.decodeText()};PDFDocument2.prototype.getCreator=function(){var creator=this.getInfoDict().lookup(PDFName_default.Creator);if(!creator)return;assertIsLiteralOrHexString(creator);return creator.decodeText()};PDFDocument2.prototype.getProducer=function(){var producer=this.getInfoDict().lookup(PDFName_default.Producer);if(!producer)return;assertIsLiteralOrHexString(producer);return producer.decodeText()};PDFDocument2.prototype.getCreationDate=function(){var creationDate=this.getInfoDict().lookup(PDFName_default.CreationDate);if(!creationDate)return;assertIsLiteralOrHexString(creationDate);return creationDate.decodeDate()};PDFDocument2.prototype.getModificationDate=function(){var modificationDate=this.getInfoDict().lookup(PDFName_default.ModDate);if(!modificationDate)return;assertIsLiteralOrHexString(modificationDate);return modificationDate.decodeDate()};PDFDocument2.prototype.setTitle=function(title,options){assertIs(title,"title",["string"]);var key=PDFName_default.of("Title");this.getInfoDict().set(key,PDFHexString_default.fromText(title));if(options===null||options===undefined?undefined:options.showInWindowTitleBar){var prefs=this.catalog.getOrCreateViewerPreferences();prefs.setDisplayDocTitle(true)}};PDFDocument2.prototype.setAuthor=function(author){assertIs(author,"author",["string"]);var key=PDFName_default.of("Author");this.getInfoDict().set(key,PDFHexString_default.fromText(author))};PDFDocument2.prototype.setSubject=function(subject){assertIs(subject,"author",["string"]);var key=PDFName_default.of("Subject");this.getInfoDict().set(key,PDFHexString_default.fromText(subject))};PDFDocument2.prototype.setKeywords=function(keywords){assertIs(keywords,"keywords",[Array]);var key=PDFName_default.of("Keywords");this.getInfoDict().set(key,PDFHexString_default.fromText(keywords.join(" ")))};PDFDocument2.prototype.setCreator=function(creator){assertIs(creator,"creator",["string"]);var key=PDFName_default.of("Creator");this.getInfoDict().set(key,PDFHexString_default.fromText(creator))};PDFDocument2.prototype.setProducer=function(producer){assertIs(producer,"creator",["string"]);var key=PDFName_default.of("Producer");this.getInfoDict().set(key,PDFHexString_default.fromText(producer))};PDFDocument2.prototype.setLanguage=function(language){assertIs(language,"language",["string"]);var key=PDFName_default.of("Lang");this.catalog.set(key,PDFString_default.of(language))};PDFDocument2.prototype.setCreationDate=function(creationDate){assertIs(creationDate,"creationDate",[[Date,"Date"]]);var key=PDFName_default.of("CreationDate");this.getInfoDict().set(key,PDFString_default.fromDate(creationDate))};PDFDocument2.prototype.setModificationDate=function(modificationDate){assertIs(modificationDate,"modificationDate",[[Date,"Date"]]);var key=PDFName_default.of("ModDate");this.getInfoDict().set(key,PDFString_default.fromDate(modificationDate))};PDFDocument2.prototype.getPageCount=function(){if(this.pageCount===undefined)this.pageCount=this.getPages().length;return this.pageCount};PDFDocument2.prototype.getPages=function(){return this.pageCache.access()};PDFDocument2.prototype.getPage=function(index){var pages=this.getPages();assertRange(index,"index",0,pages.length-1);return pages[index]};PDFDocument2.prototype.getPageIndices=function(){return range(0,this.getPageCount())};PDFDocument2.prototype.removePage=function(index){var pageCount=this.getPageCount();if(this.pageCount===0)throw new RemovePageFromEmptyDocumentError;assertRange(index,"index",0,pageCount-1);this.catalog.removeLeafNode(index);this.pageCount=pageCount-1};PDFDocument2.prototype.addPage=function(page){assertIs(page,"page",["undefined",[PDFPage_default,"PDFPage"],Array]);return this.insertPage(this.getPageCount(),page)};PDFDocument2.prototype.insertPage=function(index,page){var pageCount=this.getPageCount();assertRange(index,"index",0,pageCount);assertIs(page,"page",["undefined",[PDFPage_default,"PDFPage"],Array]);if(!page||Array.isArray(page)){var dims=Array.isArray(page)?page:PageSizes.A4;page=PDFPage_default.create(this);page.setSize.apply(page,dims)}else if(page.doc!==this){throw new ForeignPageError}var parentRef=this.catalog.insertLeafNode(page.ref,index);page.node.setParent(parentRef);this.pageMap.set(page.node,page);this.pageCache.invalidate();this.pageCount=pageCount+1;return page};PDFDocument2.prototype.copyPages=function(srcDoc,indices){return __awaiter(this,undefined,undefined,function(){var copier,srcPages,copiedPages,idx4,len3,srcPage,copiedPage,ref;return __generator(this,function(_a){switch(_a.label){case 0:assertIs(srcDoc,"srcDoc",[[PDFDocument2,"PDFDocument"]]);assertIs(indices,"indices",[Array]);return[4,srcDoc.flush()];case 1:_a.sent();copier=PDFObjectCopier_default.for(srcDoc.context,this.context);srcPages=srcDoc.getPages();copiedPages=new Array(indices.length);for(idx4=0,len3=indices.length;idx4<len3;idx4++){srcPage=srcPages[indices[idx4]];copiedPage=copier.copy(srcPage.node);ref=this.context.register(copiedPage);copiedPages[idx4]=PDFPage_default.of(copiedPage,ref,this)}return[2,copiedPages]}})})};PDFDocument2.prototype.copy=function(){return __awaiter(this,undefined,undefined,function(){var pdfCopy,contentPages,idx4,len3;return __generator(this,function(_a){switch(_a.label){case 0:return[4,PDFDocument2.create()];case 1:pdfCopy=_a.sent();return[4,pdfCopy.copyPages(this,this.getPageIndices())];case 2:contentPages=_a.sent();for(idx4=0,len3=contentPages.length;idx4<len3;idx4++){pdfCopy.addPage(contentPages[idx4])}if(this.getAuthor()!==undefined){pdfCopy.setAuthor(this.getAuthor())}if(this.getCreationDate()!==undefined){pdfCopy.setCreationDate(this.getCreationDate())}if(this.getCreator()!==undefined){pdfCopy.setCreator(this.getCreator())}if(this.getModificationDate()!==undefined){pdfCopy.setModificationDate(this.getModificationDate())}if(this.getProducer()!==undefined){pdfCopy.setProducer(this.getProducer())}if(this.getSubject()!==undefined){pdfCopy.setSubject(this.getSubject())}if(this.getTitle()!==undefined){pdfCopy.setTitle(this.getTitle())}pdfCopy.defaultWordBreaks=this.defaultWordBreaks;return[2,pdfCopy]}})})};PDFDocument2.prototype.addJavaScript=function(name,script){assertIs(name,"name",["string"]);assertIs(script,"script",["string"]);var embedder=JavaScriptEmbedder_default.for(script,name);var ref=this.context.nextRef();var javaScript=PDFJavaScript_default.of(ref,this,embedder);this.javaScripts.push(javaScript)};PDFDocument2.prototype.attach=function(attachment,name,options){if(options===undefined){options={}}return __awaiter(this,undefined,undefined,function(){var bytes,embedder,ref,embeddedFile;return __generator(this,function(_a){assertIs(attachment,"attachment",["string",Uint8Array,ArrayBuffer]);assertIs(name,"name",["string"]);assertOrUndefined(options.mimeType,"mimeType",["string"]);assertOrUndefined(options.description,"description",["string"]);assertOrUndefined(options.creationDate,"options.creationDate",[Date]);assertOrUndefined(options.modificationDate,"options.modificationDate",[Date]);assertIsOneOfOrUndefined(options.afRelationship,"options.afRelationship",AFRelationship);bytes=toUint8Array(attachment);embedder=FileEmbedder_default.for(bytes,name,options);ref=this.context.nextRef();embeddedFile=PDFEmbeddedFile_default.of(ref,this,embedder);this.embeddedFiles.push(embeddedFile);return[2]})})};PDFDocument2.prototype.embedFont=function(font,options){if(options===undefined){options={}}return __awaiter(this,undefined,undefined,function(){var _a,subset,customName,features,embedder,bytes,fontkit,_b,ref,pdfFont;return __generator(this,function(_c){switch(_c.label){case 0:_a=options.subset,subset=_a===undefined?false:_a,customName=options.customName,features=options.features;assertIs(font,"font",["string",Uint8Array,ArrayBuffer]);assertIs(subset,"subset",["boolean"]);if(!isStandardFont(font))return[3,1];embedder=StandardFontEmbedder_default.for(font,customName);return[3,7];case 1:if(!canBeConvertedToUint8Array(font))return[3,6];bytes=toUint8Array(font);fontkit=this.assertFontkit();if(!subset)return[3,3];return[4,CustomFontSubsetEmbedder_default.for(fontkit,bytes,customName,features)];case 2:_b=_c.sent();return[3,5];case 3:return[4,CustomFontEmbedder_default.for(fontkit,bytes,customName,features)];case 4:_b=_c.sent();_c.label=5;case 5:embedder=_b;return[3,7];case 6:throw new TypeError("`font` must be one of `StandardFonts | string | Uint8Array | ArrayBuffer`");case 7:ref=this.context.nextRef();pdfFont=PDFFont_default.of(ref,this,embedder);this.fonts.push(pdfFont);return[2,pdfFont]}})})};PDFDocument2.prototype.embedStandardFont=function(font,customName){assertIs(font,"font",["string"]);if(!isStandardFont(font)){throw new TypeError("`font` must be one of type `StandardFonts`")}var embedder=StandardFontEmbedder_default.for(font,customName);var ref=this.context.nextRef();var pdfFont=PDFFont_default.of(ref,this,embedder);this.fonts.push(pdfFont);return pdfFont};PDFDocument2.prototype.embedJpg=function(jpg){return __awaiter(this,undefined,undefined,function(){var bytes,embedder,ref,pdfImage;return __generator(this,function(_a){switch(_a.label){case 0:assertIs(jpg,"jpg",["string",Uint8Array,ArrayBuffer]);bytes=toUint8Array(jpg);return[4,JpegEmbedder_default.for(bytes)];case 1:embedder=_a.sent();ref=this.context.nextRef();pdfImage=PDFImage_default.of(ref,this,embedder);this.images.push(pdfImage);return[2,pdfImage]}})})};PDFDocument2.prototype.embedPng=function(png){return __awaiter(this,undefined,undefined,function(){var bytes,embedder,ref,pdfImage;return __generator(this,function(_a){switch(_a.label){case 0:assertIs(png,"png",["string",Uint8Array,ArrayBuffer]);bytes=toUint8Array(png);return[4,PngEmbedder_default.for(bytes)];case 1:embedder=_a.sent();ref=this.context.nextRef();pdfImage=PDFImage_default.of(ref,this,embedder);this.images.push(pdfImage);return[2,pdfImage]}})})};PDFDocument2.prototype.embedPdf=function(pdf,indices){if(indices===undefined){indices=[0]}return __awaiter(this,undefined,undefined,function(){var srcDoc,_a,srcPages;return __generator(this,function(_b){switch(_b.label){case 0:assertIs(pdf,"pdf",["string",Uint8Array,ArrayBuffer,[PDFDocument2,"PDFDocument"]]);assertIs(indices,"indices",[Array]);if(!(pdf instanceof PDFDocument2))return[3,1];_a=pdf;return[3,3];case 1:return[4,PDFDocument2.load(pdf)];case 2:_a=_b.sent();_b.label=3;case 3:srcDoc=_a;srcPages=pluckIndices(srcDoc.getPages(),indices);return[2,this.embedPages(srcPages)]}})})};PDFDocument2.prototype.embedPage=function(page,boundingBox,transformationMatrix){return __awaiter(this,undefined,undefined,function(){var embeddedPage;return __generator(this,function(_a){switch(_a.label){case 0:assertIs(page,"page",[[PDFPage_default,"PDFPage"]]);return[4,this.embedPages([page],[boundingBox],[transformationMatrix])];case 1:embeddedPage=_a.sent()[0];return[2,embeddedPage]}})})};PDFDocument2.prototype.embedPages=function(pages,boundingBoxes,transformationMatrices){if(boundingBoxes===undefined){boundingBoxes=[]}if(transformationMatrices===undefined){transformationMatrices=[]}return __awaiter(this,undefined,undefined,function(){var idx4,len3,currPage,nextPage,context2,maybeCopyPage,embeddedPages,idx4,len3,page,box,matrix,embedder,ref;var _a;return __generator(this,function(_b){switch(_b.label){case 0:if(pages.length===0)return[2,[]];for(idx4=0,len3=pages.length-1;idx4<len3;idx4++){currPage=pages[idx4];nextPage=pages[idx4+1];if(currPage.node.context!==nextPage.node.context){throw new PageEmbeddingMismatchedContextError}}context2=pages[0].node.context;maybeCopyPage=context2===this.context?function(p){return p}:PDFObjectCopier_default.for(context2,this.context).copy;embeddedPages=new Array(pages.length);idx4=0,len3=pages.length;_b.label=1;case 1:if(!(idx4<len3))return[3,4];page=maybeCopyPage(pages[idx4].node);box=boundingBoxes[idx4];matrix=transformationMatrices[idx4];return[4,PDFPageEmbedder_default.for(page,box,matrix)];case 2:embedder=_b.sent();ref=this.context.nextRef();embeddedPages[idx4]=PDFEmbeddedPage_default.of(ref,this,embedder);_b.label=3;case 3:idx4++;return[3,1];case 4:(_a=this.embeddedPages).push.apply(_a,embeddedPages);return[2,embeddedPages]}})})};PDFDocument2.prototype.flush=function(){return __awaiter(this,undefined,undefined,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.embedAll(this.fonts)];case 1:_a.sent();return[4,this.embedAll(this.images)];case 2:_a.sent();return[4,this.embedAll(this.embeddedPages)];case 3:_a.sent();return[4,this.embedAll(this.embeddedFiles)];case 4:_a.sent();return[4,this.embedAll(this.javaScripts)];case 5:_a.sent();return[2]}})})};PDFDocument2.prototype.save=function(options){if(options===undefined){options={}}return __awaiter(this,undefined,undefined,function(){var _a,useObjectStreams,_b,addDefaultPage,_c,objectsPerTick,_d,updateFieldAppearances,form,Writer;return __generator(this,function(_e){switch(_e.label){case 0:_a=options.useObjectStreams,useObjectStreams=_a===undefined?true:_a,_b=options.addDefaultPage,addDefaultPage=_b===undefined?true:_b,_c=options.objectsPerTick,objectsPerTick=_c===undefined?50:_c,_d=options.updateFieldAppearances,updateFieldAppearances=_d===undefined?true:_d;assertIs(useObjectStreams,"useObjectStreams",["boolean"]);assertIs(addDefaultPage,"addDefaultPage",["boolean"]);assertIs(objectsPerTick,"objectsPerTick",["number"]);assertIs(updateFieldAppearances,"updateFieldAppearances",["boolean"]);if(addDefaultPage&&this.getPageCount()===0)this.addPage();if(updateFieldAppearances){form=this.formCache.getValue();if(form)form.updateFieldAppearances()}return[4,this.flush()];case 1:_e.sent();Writer=useObjectStreams?PDFStreamWriter_default:PDFWriter_default;return[2,Writer.forContext(this.context,objectsPerTick).serializeToBuffer()]}})})};PDFDocument2.prototype.saveAsBase64=function(options){if(options===undefined){options={}}return __awaiter(this,undefined,undefined,function(){var _a,dataUri,otherOptions,bytes,base642;return __generator(this,function(_b){switch(_b.label){case 0:_a=options.dataUri,dataUri=_a===undefined?false:_a,otherOptions=__rest2(options,["dataUri"]);assertIs(dataUri,"dataUri",["boolean"]);return[4,this.save(otherOptions)];case 1:bytes=_b.sent();base642=encodeToBase64(bytes);return[2,dataUri?"data:application/pdf;base64,"+base642:base642]}})})};PDFDocument2.prototype.findPageForAnnotationRef=function(ref){var pages=this.getPages();for(var idx4=0,len3=pages.length;idx4<len3;idx4++){var page=pages[idx4];var annotations=page.node.Annots();if((annotations===null||annotations===undefined?undefined:annotations.indexOf(ref))!==undefined){return page}}return};PDFDocument2.prototype.embedAll=function(embeddables){return __awaiter(this,undefined,undefined,function(){var idx4,len3;return __generator(this,function(_a){switch(_a.label){case 0:idx4=0,len3=embeddables.length;_a.label=1;case 1:if(!(idx4<len3))return[3,4];return[4,embeddables[idx4].embed()];case 2:_a.sent();_a.label=3;case 3:idx4++;return[3,1];case 4:return[2]}})})};PDFDocument2.prototype.updateInfoDict=function(){var pdfLib="pdf-lib (https://github.com/Hopding/pdf-lib)";var now=new Date;var info=this.getInfoDict();this.setProducer(pdfLib);this.setModificationDate(now);if(!info.get(PDFName_default.of("Creator")))this.setCreator(pdfLib);if(!info.get(PDFName_default.of("CreationDate")))this.setCreationDate(now)};PDFDocument2.prototype.getInfoDict=function(){var existingInfo=this.context.lookup(this.context.trailerInfo.Info);if(existingInfo instanceof PDFDict_default)return existingInfo;var newInfo=this.context.obj({});this.context.trailerInfo.Info=this.context.register(newInfo);return newInfo};PDFDocument2.prototype.assertFontkit=function(){if(!this.fontkit)throw new FontkitNotRegisteredError;return this.fontkit};return PDFDocument2}();PDFDocument_default=PDFDocument});var BlendMode;var init_PDFPageOptions=__esm(()=>{(function(BlendMode2){BlendMode2["Normal"]="Normal";BlendMode2["Multiply"]="Multiply";BlendMode2["Screen"]="Screen";BlendMode2["Overlay"]="Overlay";BlendMode2["Darken"]="Darken";BlendMode2["Lighten"]="Lighten";BlendMode2["ColorDodge"]="ColorDodge";BlendMode2["ColorBurn"]="ColorBurn";BlendMode2["HardLight"]="HardLight";BlendMode2["SoftLight"]="SoftLight";BlendMode2["Difference"]="Difference";BlendMode2["Exclusion"]="Exclusion"})(BlendMode||(BlendMode={}))});var PDFPage,PDFPage_default;var init_PDFPage=__esm(()=>{init_tslib_es62();init_colors();init_operations();init_operators();init_PDFDocument();init_PDFEmbeddedPage();init_PDFFont();init_PDFImage();init_PDFPageOptions();init_rotations();init_StandardFonts();init_core();init_utils2();PDFPage=function(){function PDFPage2(leafNode,ref,doc){this.fontSize=24;this.fontColor=rgb(0,0,0);this.lineHeight=24;this.x=0;this.y=0;assertIs(leafNode,"leafNode",[[PDFPageLeaf_default,"PDFPageLeaf"]]);assertIs(ref,"ref",[[PDFRef_default,"PDFRef"]]);assertIs(doc,"doc",[[PDFDocument_default,"PDFDocument"]]);this.node=leafNode;this.ref=ref;this.doc=doc}PDFPage2.prototype.setRotation=function(angle){var degreesAngle=toDegrees(angle);assertMultiple(degreesAngle,"degreesAngle",90);this.node.set(PDFName_default.of("Rotate"),this.doc.context.obj(degreesAngle))};PDFPage2.prototype.getRotation=function(){var Rotate=this.node.Rotate();return degrees(Rotate?Rotate.asNumber():0)};PDFPage2.prototype.setSize=function(width,height){assertIs(width,"width",["number"]);assertIs(height,"height",["number"]);var mediaBox=this.getMediaBox();this.setMediaBox(mediaBox.x,mediaBox.y,width,height);var cropBox=this.getCropBox();var bleedBox=this.getBleedBox();var trimBox=this.getTrimBox();var artBox=this.getArtBox();var hasCropBox=this.node.CropBox();var hasBleedBox=this.node.BleedBox();var hasTrimBox=this.node.TrimBox();var hasArtBox=this.node.ArtBox();if(hasCropBox&&rectanglesAreEqual(cropBox,mediaBox)){this.setCropBox(mediaBox.x,mediaBox.y,width,height)}if(hasBleedBox&&rectanglesAreEqual(bleedBox,mediaBox)){this.setBleedBox(mediaBox.x,mediaBox.y,width,height)}if(hasTrimBox&&rectanglesAreEqual(trimBox,mediaBox)){this.setTrimBox(mediaBox.x,mediaBox.y,width,height)}if(hasArtBox&&rectanglesAreEqual(artBox,mediaBox)){this.setArtBox(mediaBox.x,mediaBox.y,width,height)}};PDFPage2.prototype.setWidth=function(width){assertIs(width,"width",["number"]);this.setSize(width,this.getSize().height)};PDFPage2.prototype.setHeight=function(height){assertIs(height,"height",["number"]);this.setSize(this.getSize().width,height)};PDFPage2.prototype.setMediaBox=function(x,y,width,height){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);assertIs(width,"width",["number"]);assertIs(height,"height",["number"]);var mediaBox=this.doc.context.obj([x,y,x+width,y+height]);this.node.set(PDFName_default.MediaBox,mediaBox)};PDFPage2.prototype.setCropBox=function(x,y,width,height){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);assertIs(width,"width",["number"]);assertIs(height,"height",["number"]);var cropBox=this.doc.context.obj([x,y,x+width,y+height]);this.node.set(PDFName_default.CropBox,cropBox)};PDFPage2.prototype.setBleedBox=function(x,y,width,height){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);assertIs(width,"width",["number"]);assertIs(height,"height",["number"]);var bleedBox=this.doc.context.obj([x,y,x+width,y+height]);this.node.set(PDFName_default.BleedBox,bleedBox)};PDFPage2.prototype.setTrimBox=function(x,y,width,height){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);assertIs(width,"width",["number"]);assertIs(height,"height",["number"]);var trimBox=this.doc.context.obj([x,y,x+width,y+height]);this.node.set(PDFName_default.TrimBox,trimBox)};PDFPage2.prototype.setArtBox=function(x,y,width,height){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);assertIs(width,"width",["number"]);assertIs(height,"height",["number"]);var artBox=this.doc.context.obj([x,y,x+width,y+height]);this.node.set(PDFName_default.ArtBox,artBox)};PDFPage2.prototype.getSize=function(){var _a=this.getMediaBox(),width=_a.width,height=_a.height;return{width,height}};PDFPage2.prototype.getWidth=function(){return this.getSize().width};PDFPage2.prototype.getHeight=function(){return this.getSize().height};PDFPage2.prototype.getMediaBox=function(){var mediaBox=this.node.MediaBox();return mediaBox.asRectangle()};PDFPage2.prototype.getCropBox=function(){var _a;var cropBox=this.node.CropBox();return(_a=cropBox===null||cropBox===undefined?undefined:cropBox.asRectangle())!==null&&_a!==undefined?_a:this.getMediaBox()};PDFPage2.prototype.getBleedBox=function(){var _a;var bleedBox=this.node.BleedBox();return(_a=bleedBox===null||bleedBox===undefined?undefined:bleedBox.asRectangle())!==null&&_a!==undefined?_a:this.getCropBox()};PDFPage2.prototype.getTrimBox=function(){var _a;var trimBox=this.node.TrimBox();return(_a=trimBox===null||trimBox===undefined?undefined:trimBox.asRectangle())!==null&&_a!==undefined?_a:this.getCropBox()};PDFPage2.prototype.getArtBox=function(){var _a;var artBox=this.node.ArtBox();return(_a=artBox===null||artBox===undefined?undefined:artBox.asRectangle())!==null&&_a!==undefined?_a:this.getCropBox()};PDFPage2.prototype.translateContent=function(x,y){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);this.node.normalize();this.getContentStream();var start=this.createContentStream(pushGraphicsState(),translate(x,y));var startRef=this.doc.context.register(start);var end=this.createContentStream(popGraphicsState());var endRef=this.doc.context.register(end);this.node.wrapContentStreams(startRef,endRef)};PDFPage2.prototype.scale=function(x,y){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);this.setSize(this.getWidth()*x,this.getHeight()*y);this.scaleContent(x,y);this.scaleAnnotations(x,y)};PDFPage2.prototype.scaleContent=function(x,y){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);this.node.normalize();this.getContentStream();var start=this.createContentStream(pushGraphicsState(),scale(x,y));var startRef=this.doc.context.register(start);var end=this.createContentStream(popGraphicsState());var endRef=this.doc.context.register(end);this.node.wrapContentStreams(startRef,endRef)};PDFPage2.prototype.scaleAnnotations=function(x,y){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);var annots=this.node.Annots();if(!annots)return;for(var idx4=0;idx4<annots.size();idx4++){var annot=annots.lookup(idx4);if(annot instanceof PDFDict_default)this.scaleAnnot(annot,x,y)}};PDFPage2.prototype.resetPosition=function(){this.getContentStream(false);this.x=0;this.y=0};PDFPage2.prototype.setFont=function(font){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);this.font=font;this.fontKey=this.node.newFontDictionary(this.font.name,this.font.ref)};PDFPage2.prototype.setFontSize=function(fontSize){assertIs(fontSize,"fontSize",["number"]);this.fontSize=fontSize};PDFPage2.prototype.setFontColor=function(fontColor){assertIs(fontColor,"fontColor",[[Object,"Color"]]);this.fontColor=fontColor};PDFPage2.prototype.setLineHeight=function(lineHeight){assertIs(lineHeight,"lineHeight",["number"]);this.lineHeight=lineHeight};PDFPage2.prototype.getPosition=function(){return{x:this.x,y:this.y}};PDFPage2.prototype.getX=function(){return this.x};PDFPage2.prototype.getY=function(){return this.y};PDFPage2.prototype.moveTo=function(x,y){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);this.x=x;this.y=y};PDFPage2.prototype.moveDown=function(yDecrease){assertIs(yDecrease,"yDecrease",["number"]);this.y-=yDecrease};PDFPage2.prototype.moveUp=function(yIncrease){assertIs(yIncrease,"yIncrease",["number"]);this.y+=yIncrease};PDFPage2.prototype.moveLeft=function(xDecrease){assertIs(xDecrease,"xDecrease",["number"]);this.x-=xDecrease};PDFPage2.prototype.moveRight=function(xIncrease){assertIs(xIncrease,"xIncrease",["number"]);this.x+=xIncrease};PDFPage2.prototype.pushOperators=function(){var operator=[];for(var _i=0;_i<arguments.length;_i++){operator[_i]=arguments[_i]}assertEachIs(operator,"operator",[[PDFOperator_default,"PDFOperator"]]);var contentStream=this.getContentStream();contentStream.push.apply(contentStream,operator)};PDFPage2.prototype.drawText=function(text4,options){var _a,_b,_c,_d,_e,_f,_g;if(options===undefined){options={}}assertIs(text4,"text",["string"]);assertOrUndefined(options.color,"options.color",[[Object,"Color"]]);assertRangeOrUndefined(options.opacity,"opacity.opacity",0,1);assertOrUndefined(options.font,"options.font",[[PDFFont_default,"PDFFont"]]);assertOrUndefined(options.size,"options.size",["number"]);assertOrUndefined(options.rotate,"options.rotate",[[Object,"Rotation"]]);assertOrUndefined(options.xSkew,"options.xSkew",[[Object,"Rotation"]]);assertOrUndefined(options.ySkew,"options.ySkew",[[Object,"Rotation"]]);assertOrUndefined(options.x,"options.x",["number"]);assertOrUndefined(options.y,"options.y",["number"]);assertOrUndefined(options.lineHeight,"options.lineHeight",["number"]);assertOrUndefined(options.maxWidth,"options.maxWidth",["number"]);assertOrUndefined(options.wordBreaks,"options.wordBreaks",[Array]);assertIsOneOfOrUndefined(options.blendMode,"options.blendMode",BlendMode);var _h=this.setOrEmbedFont(options.font),oldFont=_h.oldFont,newFont=_h.newFont,newFontKey=_h.newFontKey;var fontSize=options.size||this.fontSize;var wordBreaks=options.wordBreaks||this.doc.defaultWordBreaks;var textWidth=function(t){return newFont.widthOfTextAtSize(t,fontSize)};var lines=options.maxWidth===undefined?lineSplit(cleanText(text4)):breakTextIntoLines(text4,wordBreaks,options.maxWidth,textWidth);var encodedLines=new Array(lines.length);for(var idx4=0,len3=lines.length;idx4<len3;idx4++){encodedLines[idx4]=newFont.encodeText(lines[idx4])}var graphicsStateKey=this.maybeEmbedGraphicsState({opacity:options.opacity,blendMode:options.blendMode});var contentStream=this.getContentStream();contentStream.push.apply(contentStream,drawLinesOfText(encodedLines,{color:(_a=options.color)!==null&&_a!==undefined?_a:this.fontColor,font:newFontKey,size:fontSize,rotate:(_b=options.rotate)!==null&&_b!==undefined?_b:degrees(0),xSkew:(_c=options.xSkew)!==null&&_c!==undefined?_c:degrees(0),ySkew:(_d=options.ySkew)!==null&&_d!==undefined?_d:degrees(0),x:(_e=options.x)!==null&&_e!==undefined?_e:this.x,y:(_f=options.y)!==null&&_f!==undefined?_f:this.y,lineHeight:(_g=options.lineHeight)!==null&&_g!==undefined?_g:this.lineHeight,graphicsState:graphicsStateKey}));if(options.font){if(oldFont)this.setFont(oldFont);else this.resetFont()}};PDFPage2.prototype.drawImage=function(image,options){var _a,_b,_c,_d,_e,_f,_g;if(options===undefined){options={}}assertIs(image,"image",[[PDFImage_default,"PDFImage"]]);assertOrUndefined(options.x,"options.x",["number"]);assertOrUndefined(options.y,"options.y",["number"]);assertOrUndefined(options.width,"options.width",["number"]);assertOrUndefined(options.height,"options.height",["number"]);assertOrUndefined(options.rotate,"options.rotate",[[Object,"Rotation"]]);assertOrUndefined(options.xSkew,"options.xSkew",[[Object,"Rotation"]]);assertOrUndefined(options.ySkew,"options.ySkew",[[Object,"Rotation"]]);assertRangeOrUndefined(options.opacity,"opacity.opacity",0,1);assertIsOneOfOrUndefined(options.blendMode,"options.blendMode",BlendMode);var xObjectKey=this.node.newXObject("Image",image.ref);var graphicsStateKey=this.maybeEmbedGraphicsState({opacity:options.opacity,blendMode:options.blendMode});var contentStream=this.getContentStream();contentStream.push.apply(contentStream,drawImage(xObjectKey,{x:(_a=options.x)!==null&&_a!==undefined?_a:this.x,y:(_b=options.y)!==null&&_b!==undefined?_b:this.y,width:(_c=options.width)!==null&&_c!==undefined?_c:image.size().width,height:(_d=options.height)!==null&&_d!==undefined?_d:image.size().height,rotate:(_e=options.rotate)!==null&&_e!==undefined?_e:degrees(0),xSkew:(_f=options.xSkew)!==null&&_f!==undefined?_f:degrees(0),ySkew:(_g=options.ySkew)!==null&&_g!==undefined?_g:degrees(0),graphicsState:graphicsStateKey}))};PDFPage2.prototype.drawPage=function(embeddedPage,options){var _a,_b,_c,_d,_e;if(options===undefined){options={}}assertIs(embeddedPage,"embeddedPage",[[PDFEmbeddedPage_default,"PDFEmbeddedPage"]]);assertOrUndefined(options.x,"options.x",["number"]);assertOrUndefined(options.y,"options.y",["number"]);assertOrUndefined(options.xScale,"options.xScale",["number"]);assertOrUndefined(options.yScale,"options.yScale",["number"]);assertOrUndefined(options.width,"options.width",["number"]);assertOrUndefined(options.height,"options.height",["number"]);assertOrUndefined(options.rotate,"options.rotate",[[Object,"Rotation"]]);assertOrUndefined(options.xSkew,"options.xSkew",[[Object,"Rotation"]]);assertOrUndefined(options.ySkew,"options.ySkew",[[Object,"Rotation"]]);assertRangeOrUndefined(options.opacity,"opacity.opacity",0,1);assertIsOneOfOrUndefined(options.blendMode,"options.blendMode",BlendMode);var xObjectKey=this.node.newXObject("EmbeddedPdfPage",embeddedPage.ref);var graphicsStateKey=this.maybeEmbedGraphicsState({opacity:options.opacity,blendMode:options.blendMode});var xScale=options.width!==undefined?options.width/embeddedPage.width:options.xScale!==undefined?options.xScale:1;var yScale=options.height!==undefined?options.height/embeddedPage.height:options.yScale!==undefined?options.yScale:1;var contentStream=this.getContentStream();contentStream.push.apply(contentStream,drawPage(xObjectKey,{x:(_a=options.x)!==null&&_a!==undefined?_a:this.x,y:(_b=options.y)!==null&&_b!==undefined?_b:this.y,xScale,yScale,rotate:(_c=options.rotate)!==null&&_c!==undefined?_c:degrees(0),xSkew:(_d=options.xSkew)!==null&&_d!==undefined?_d:degrees(0),ySkew:(_e=options.ySkew)!==null&&_e!==undefined?_e:degrees(0),graphicsState:graphicsStateKey}))};PDFPage2.prototype.drawSvgPath=function(path,options){var _a,_b,_c,_d,_e,_f,_g,_h,_j;if(options===undefined){options={}}assertIs(path,"path",["string"]);assertOrUndefined(options.x,"options.x",["number"]);assertOrUndefined(options.y,"options.y",["number"]);assertOrUndefined(options.scale,"options.scale",["number"]);assertOrUndefined(options.rotate,"options.rotate",[[Object,"Rotation"]]);assertOrUndefined(options.borderWidth,"options.borderWidth",["number"]);assertOrUndefined(options.color,"options.color",[[Object,"Color"]]);assertRangeOrUndefined(options.opacity,"opacity.opacity",0,1);assertOrUndefined(options.borderColor,"options.borderColor",[[Object,"Color"]]);assertOrUndefined(options.borderDashArray,"options.borderDashArray",[Array]);assertOrUndefined(options.borderDashPhase,"options.borderDashPhase",["number"]);assertIsOneOfOrUndefined(options.borderLineCap,"options.borderLineCap",LineCapStyle);assertRangeOrUndefined(options.borderOpacity,"options.borderOpacity",0,1);assertIsOneOfOrUndefined(options.blendMode,"options.blendMode",BlendMode);var graphicsStateKey=this.maybeEmbedGraphicsState({opacity:options.opacity,borderOpacity:options.borderOpacity,blendMode:options.blendMode});if(!("color"in options)&&!("borderColor"in options)){options.borderColor=rgb(0,0,0)}var contentStream=this.getContentStream();contentStream.push.apply(contentStream,drawSvgPath(path,{x:(_a=options.x)!==null&&_a!==undefined?_a:this.x,y:(_b=options.y)!==null&&_b!==undefined?_b:this.y,scale:options.scale,rotate:(_c=options.rotate)!==null&&_c!==undefined?_c:degrees(0),color:(_d=options.color)!==null&&_d!==undefined?_d:undefined,borderColor:(_e=options.borderColor)!==null&&_e!==undefined?_e:undefined,borderWidth:(_f=options.borderWidth)!==null&&_f!==undefined?_f:0,borderDashArray:(_g=options.borderDashArray)!==null&&_g!==undefined?_g:undefined,borderDashPhase:(_h=options.borderDashPhase)!==null&&_h!==undefined?_h:undefined,borderLineCap:(_j=options.borderLineCap)!==null&&_j!==undefined?_j:undefined,graphicsState:graphicsStateKey}))};PDFPage2.prototype.drawLine=function(options){var _a,_b,_c,_d,_e;assertIs(options.start,"options.start",[[Object,"{ x: number, y: number }"]]);assertIs(options.end,"options.end",[[Object,"{ x: number, y: number }"]]);assertIs(options.start.x,"options.start.x",["number"]);assertIs(options.start.y,"options.start.y",["number"]);assertIs(options.end.x,"options.end.x",["number"]);assertIs(options.end.y,"options.end.y",["number"]);assertOrUndefined(options.thickness,"options.thickness",["number"]);assertOrUndefined(options.color,"options.color",[[Object,"Color"]]);assertOrUndefined(options.dashArray,"options.dashArray",[Array]);assertOrUndefined(options.dashPhase,"options.dashPhase",["number"]);assertIsOneOfOrUndefined(options.lineCap,"options.lineCap",LineCapStyle);assertRangeOrUndefined(options.opacity,"opacity.opacity",0,1);assertIsOneOfOrUndefined(options.blendMode,"options.blendMode",BlendMode);var graphicsStateKey=this.maybeEmbedGraphicsState({borderOpacity:options.opacity,blendMode:options.blendMode});if(!("color"in options)){options.color=rgb(0,0,0)}var contentStream=this.getContentStream();contentStream.push.apply(contentStream,drawLine({start:options.start,end:options.end,thickness:(_a=options.thickness)!==null&&_a!==undefined?_a:1,color:(_b=options.color)!==null&&_b!==undefined?_b:undefined,dashArray:(_c=options.dashArray)!==null&&_c!==undefined?_c:undefined,dashPhase:(_d=options.dashPhase)!==null&&_d!==undefined?_d:undefined,lineCap:(_e=options.lineCap)!==null&&_e!==undefined?_e:undefined,graphicsState:graphicsStateKey}))};PDFPage2.prototype.drawRectangle=function(options){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o;if(options===undefined){options={}}assertOrUndefined(options.x,"options.x",["number"]);assertOrUndefined(options.y,"options.y",["number"]);assertOrUndefined(options.width,"options.width",["number"]);assertOrUndefined(options.height,"options.height",["number"]);assertOrUndefined(options.rotate,"options.rotate",[[Object,"Rotation"]]);assertOrUndefined(options.xSkew,"options.xSkew",[[Object,"Rotation"]]);assertOrUndefined(options.ySkew,"options.ySkew",[[Object,"Rotation"]]);assertOrUndefined(options.borderWidth,"options.borderWidth",["number"]);assertOrUndefined(options.color,"options.color",[[Object,"Color"]]);assertRangeOrUndefined(options.opacity,"opacity.opacity",0,1);assertOrUndefined(options.borderColor,"options.borderColor",[[Object,"Color"]]);assertOrUndefined(options.borderDashArray,"options.borderDashArray",[Array]);assertOrUndefined(options.borderDashPhase,"options.borderDashPhase",["number"]);assertIsOneOfOrUndefined(options.borderLineCap,"options.borderLineCap",LineCapStyle);assertRangeOrUndefined(options.borderOpacity,"options.borderOpacity",0,1);assertIsOneOfOrUndefined(options.blendMode,"options.blendMode",BlendMode);var graphicsStateKey=this.maybeEmbedGraphicsState({opacity:options.opacity,borderOpacity:options.borderOpacity,blendMode:options.blendMode});if(!("color"in options)&&!("borderColor"in options)){options.color=rgb(0,0,0)}var contentStream=this.getContentStream();contentStream.push.apply(contentStream,drawRectangle({x:(_a=options.x)!==null&&_a!==undefined?_a:this.x,y:(_b=options.y)!==null&&_b!==undefined?_b:this.y,width:(_c=options.width)!==null&&_c!==undefined?_c:150,height:(_d=options.height)!==null&&_d!==undefined?_d:100,rotate:(_e=options.rotate)!==null&&_e!==undefined?_e:degrees(0),xSkew:(_f=options.xSkew)!==null&&_f!==undefined?_f:degrees(0),ySkew:(_g=options.ySkew)!==null&&_g!==undefined?_g:degrees(0),borderWidth:(_h=options.borderWidth)!==null&&_h!==undefined?_h:0,color:(_j=options.color)!==null&&_j!==undefined?_j:undefined,borderColor:(_k=options.borderColor)!==null&&_k!==undefined?_k:undefined,borderDashArray:(_l=options.borderDashArray)!==null&&_l!==undefined?_l:undefined,borderDashPhase:(_m=options.borderDashPhase)!==null&&_m!==undefined?_m:undefined,graphicsState:graphicsStateKey,borderLineCap:(_o=options.borderLineCap)!==null&&_o!==undefined?_o:undefined}))};PDFPage2.prototype.drawSquare=function(options){if(options===undefined){options={}}var size=options.size;assertOrUndefined(size,"size",["number"]);this.drawRectangle(__assign(__assign({},options),{width:size,height:size}))};PDFPage2.prototype.drawEllipse=function(options){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l;if(options===undefined){options={}}assertOrUndefined(options.x,"options.x",["number"]);assertOrUndefined(options.y,"options.y",["number"]);assertOrUndefined(options.xScale,"options.xScale",["number"]);assertOrUndefined(options.yScale,"options.yScale",["number"]);assertOrUndefined(options.rotate,"options.rotate",[[Object,"Rotation"]]);assertOrUndefined(options.color,"options.color",[[Object,"Color"]]);assertRangeOrUndefined(options.opacity,"opacity.opacity",0,1);assertOrUndefined(options.borderColor,"options.borderColor",[[Object,"Color"]]);assertRangeOrUndefined(options.borderOpacity,"options.borderOpacity",0,1);assertOrUndefined(options.borderWidth,"options.borderWidth",["number"]);assertOrUndefined(options.borderDashArray,"options.borderDashArray",[Array]);assertOrUndefined(options.borderDashPhase,"options.borderDashPhase",["number"]);assertIsOneOfOrUndefined(options.borderLineCap,"options.borderLineCap",LineCapStyle);assertIsOneOfOrUndefined(options.blendMode,"options.blendMode",BlendMode);var graphicsStateKey=this.maybeEmbedGraphicsState({opacity:options.opacity,borderOpacity:options.borderOpacity,blendMode:options.blendMode});if(!("color"in options)&&!("borderColor"in options)){options.color=rgb(0,0,0)}var contentStream=this.getContentStream();contentStream.push.apply(contentStream,drawEllipse({x:(_a=options.x)!==null&&_a!==undefined?_a:this.x,y:(_b=options.y)!==null&&_b!==undefined?_b:this.y,xScale:(_c=options.xScale)!==null&&_c!==undefined?_c:100,yScale:(_d=options.yScale)!==null&&_d!==undefined?_d:100,rotate:(_e=options.rotate)!==null&&_e!==undefined?_e:undefined,color:(_f=options.color)!==null&&_f!==undefined?_f:undefined,borderColor:(_g=options.borderColor)!==null&&_g!==undefined?_g:undefined,borderWidth:(_h=options.borderWidth)!==null&&_h!==undefined?_h:0,borderDashArray:(_j=options.borderDashArray)!==null&&_j!==undefined?_j:undefined,borderDashPhase:(_k=options.borderDashPhase)!==null&&_k!==undefined?_k:undefined,borderLineCap:(_l=options.borderLineCap)!==null&&_l!==undefined?_l:undefined,graphicsState:graphicsStateKey}))};PDFPage2.prototype.drawCircle=function(options){if(options===undefined){options={}}var _a=options.size,size=_a===undefined?100:_a;assertOrUndefined(size,"size",["number"]);this.drawEllipse(__assign(__assign({},options),{xScale:size,yScale:size}))};PDFPage2.prototype.setOrEmbedFont=function(font){var oldFont=this.font;var oldFontKey=this.fontKey;if(font)this.setFont(font);else this.getFont();var newFont=this.font;var newFontKey=this.fontKey;return{oldFont,oldFontKey,newFont,newFontKey}};PDFPage2.prototype.getFont=function(){if(!this.font||!this.fontKey){var font=this.doc.embedStandardFont(StandardFonts.Helvetica);this.setFont(font)}return[this.font,this.fontKey]};PDFPage2.prototype.resetFont=function(){this.font=undefined;this.fontKey=undefined};PDFPage2.prototype.getContentStream=function(useExisting){if(useExisting===undefined){useExisting=true}if(useExisting&&this.contentStream)return this.contentStream;this.contentStream=this.createContentStream();this.contentStreamRef=this.doc.context.register(this.contentStream);this.node.addContentStream(this.contentStreamRef);return this.contentStream};PDFPage2.prototype.createContentStream=function(){var operators=[];for(var _i=0;_i<arguments.length;_i++){operators[_i]=arguments[_i]}var dict=this.doc.context.obj({});var contentStream=PDFContentStream_default.of(dict,operators);return contentStream};PDFPage2.prototype.maybeEmbedGraphicsState=function(options){var{opacity,borderOpacity,blendMode}=options;if(opacity===undefined&&borderOpacity===undefined&&blendMode===undefined){return}var graphicsState=this.doc.context.obj({Type:"ExtGState",ca:opacity,CA:borderOpacity,BM:blendMode});var key=this.node.newExtGState("GS",graphicsState);return key};PDFPage2.prototype.scaleAnnot=function(annot,x,y){var selectors=["RD","CL","Vertices","QuadPoints","L","Rect"];for(var idx4=0,len3=selectors.length;idx4<len3;idx4++){var list=annot.lookup(PDFName_default.of(selectors[idx4]));if(list instanceof PDFArray_default)list.scalePDFNumbers(x,y)}var inkLists=annot.lookup(PDFName_default.of("InkList"));if(inkLists instanceof PDFArray_default){for(var idx4=0,len3=inkLists.size();idx4<len3;idx4++){var arr=inkLists.lookup(idx4);if(arr instanceof PDFArray_default)arr.scalePDFNumbers(x,y)}}};PDFPage2.of=function(leafNode,ref,doc){return new PDFPage2(leafNode,ref,doc)};PDFPage2.create=function(doc){assertIs(doc,"doc",[[PDFDocument_default,"PDFDocument"]]);var dummyRef=PDFRef_default.of(-1);var pageLeaf=PDFPageLeaf_default.withContextAndParent(doc.context,dummyRef);var pageRef=doc.context.register(pageLeaf);return new PDFPage2(pageLeaf,pageRef,doc)};return PDFPage2}();PDFPage_default=PDFPage});var PDFButton,PDFButton_default;var init_PDFButton=__esm(()=>{init_tslib_es62();init_PDFPage();init_PDFFont();init_alignment2();init_appearances();init_PDFField();init_colors();init_rotations();init_core();init_utils2();PDFButton=function(_super){__extends(PDFButton2,_super);function PDFButton2(acroPushButton,ref,doc){var _this=_super.call(this,acroPushButton,ref,doc)||this;assertIs(acroPushButton,"acroButton",[[PDFAcroPushButton_default,"PDFAcroPushButton"]]);_this.acroField=acroPushButton;return _this}PDFButton2.prototype.setImage=function(image,alignment2){if(alignment2===undefined){alignment2=ImageAlignment.Center}var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var streamRef=this.createImageAppearanceStream(widget,image,alignment2);this.updateWidgetAppearances(widget,{normal:streamRef})}this.markAsClean()};PDFButton2.prototype.setFontSize=function(fontSize){assertPositive(fontSize,"fontSize");this.acroField.setFontSize(fontSize);this.markAsDirty()};PDFButton2.prototype.addToPage=function(text4,page,options){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l;assertOrUndefined(text4,"text",["string"]);assertOrUndefined(page,"page",[[PDFPage_default,"PDFPage"]]);assertFieldAppearanceOptions(options);var widget=this.createWidget({x:((_a=options===null||options===undefined?undefined:options.x)!==null&&_a!==undefined?_a:0)-((_b=options===null||options===undefined?undefined:options.borderWidth)!==null&&_b!==undefined?_b:0)/2,y:((_c=options===null||options===undefined?undefined:options.y)!==null&&_c!==undefined?_c:0)-((_d=options===null||options===undefined?undefined:options.borderWidth)!==null&&_d!==undefined?_d:0)/2,width:(_e=options===null||options===undefined?undefined:options.width)!==null&&_e!==undefined?_e:100,height:(_f=options===null||options===undefined?undefined:options.height)!==null&&_f!==undefined?_f:50,textColor:(_g=options===null||options===undefined?undefined:options.textColor)!==null&&_g!==undefined?_g:rgb(0,0,0),backgroundColor:(_h=options===null||options===undefined?undefined:options.backgroundColor)!==null&&_h!==undefined?_h:rgb(0.75,0.75,0.75),borderColor:options===null||options===undefined?undefined:options.borderColor,borderWidth:(_j=options===null||options===undefined?undefined:options.borderWidth)!==null&&_j!==undefined?_j:0,rotate:(_k=options===null||options===undefined?undefined:options.rotate)!==null&&_k!==undefined?_k:degrees(0),caption:text4,hidden:options===null||options===undefined?undefined:options.hidden,page:page.ref});var widgetRef=this.doc.context.register(widget.dict);this.acroField.addWidget(widgetRef);var font=(_l=options===null||options===undefined?undefined:options.font)!==null&&_l!==undefined?_l:this.doc.getForm().getDefaultFont();this.updateWidgetAppearance(widget,font);page.node.addAnnot(widgetRef)};PDFButton2.prototype.needsAppearancesUpdate=function(){var _a;if(this.isDirty())return true;var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var hasAppearances=((_a=widget.getAppearances())===null||_a===undefined?undefined:_a.normal)instanceof PDFStream_default;if(!hasAppearances)return true}return false};PDFButton2.prototype.defaultUpdateAppearances=function(font){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);this.updateAppearances(font)};PDFButton2.prototype.updateAppearances=function(font,provider2){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);assertOrUndefined(provider2,"provider",[Function]);var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];this.updateWidgetAppearance(widget,font,provider2)}};PDFButton2.prototype.updateWidgetAppearance=function(widget,font,provider2){var apProvider=provider2!==null&&provider2!==undefined?provider2:defaultButtonAppearanceProvider;var appearances=normalizeAppearance(apProvider(this,widget,font));this.updateWidgetAppearanceWithFont(widget,font,appearances)};PDFButton2.of=function(acroPushButton,ref,doc){return new PDFButton2(acroPushButton,ref,doc)};return PDFButton2}(PDFField_default);PDFButton_default=PDFButton});var init_form=__esm(()=>{init_PDFButton();init_PDFCheckBox();init_PDFDropdown();init_PDFField();init_PDFForm();init_PDFOptionList();init_PDFRadioGroup();init_PDFSignature();init_PDFTextField();init_appearances()});var init_text=__esm(()=>{init_alignment();init_layout()});var init_api=__esm(()=>{init_PDFDocument();init_PDFFont();init_PDFImage();init_PDFPage();init_PDFEmbeddedPage();init_PDFJavaScript();init_form();init_text();init_colors();init_errors3();init_image();init_objects2();init_operations();init_operators();init_rotations();init_sizes();init_PDFPageOptions();init_PDFDocumentOptions();init_StandardFonts()});var exports_es={};__export(exports_es,{waitForTick:()=>waitForTick,values:()=>values,utf8Encode:()=>utf8Encode,utf16Encode:()=>utf16Encode,utf16Decode:()=>utf16Decode,typedArrayFor:()=>typedArrayFor,translate:()=>translate,toUint8Array:()=>toUint8Array,toRadians:()=>toRadians,toHexStringOfMinLength:()=>toHexStringOfMinLength,toHexString:()=>toHexString,toDegrees:()=>toDegrees,toCodePoint:()=>toCodePoint,toCharCode:()=>toCharCode,sum:()=>sum,stroke:()=>stroke,square:()=>square,sortedUniq:()=>sortedUniq,skewRadians:()=>skewRadians,skewDegrees:()=>skewDegrees,sizeInBytes:()=>sizeInBytes,singleQuote:()=>singleQuote,showText:()=>showText,setWordSpacing:()=>setWordSpacing,setTextRise:()=>setTextRise,setTextRenderingMode:()=>setTextRenderingMode,setTextMatrix:()=>setTextMatrix,setStrokingRgbColor:()=>setStrokingRgbColor,setStrokingGrayscaleColor:()=>setStrokingGrayscaleColor,setStrokingColor:()=>setStrokingColor,setStrokingCmykColor:()=>setStrokingCmykColor,setLineWidth:()=>setLineWidth,setLineJoin:()=>setLineJoin,setLineHeight:()=>setLineHeight,setLineCap:()=>setLineCap,setGraphicsState:()=>setGraphicsState,setFontAndSize:()=>setFontAndSize,setFillingRgbColor:()=>setFillingRgbColor,setFillingGrayscaleColor:()=>setFillingGrayscaleColor,setFillingColor:()=>setFillingColor,setFillingCmykColor:()=>setFillingCmykColor,setDashPattern:()=>setDashPattern,setCharacterSqueeze:()=>setCharacterSqueeze,setCharacterSpacing:()=>setCharacterSpacing,scale:()=>scale,rotateRectangle:()=>rotateRectangle,rotateRadians:()=>rotateRadians,rotateInPlace:()=>rotateInPlace,rotateDegrees:()=>rotateDegrees,rotateAndSkewTextRadiansAndTranslate:()=>rotateAndSkewTextRadiansAndTranslate,rotateAndSkewTextDegreesAndTranslate:()=>rotateAndSkewTextDegreesAndTranslate,rgb:()=>rgb,reverseArray:()=>reverseArray,restoreDashPattern:()=>restoreDashPattern,reduceRotation:()=>reduceRotation,rectanglesAreEqual:()=>rectanglesAreEqual,rectangle:()=>rectangle,range:()=>range,radiansToDegrees:()=>radiansToDegrees,radians:()=>radians,pushGraphicsState:()=>pushGraphicsState,popGraphicsState:()=>popGraphicsState,pluckIndices:()=>pluckIndices,pdfDocEncodingDecode:()=>pdfDocEncodingDecode,parseDate:()=>parseDate,padStart:()=>padStart,numberToString:()=>numberToString,normalizeAppearance:()=>normalizeAppearance,nextLine:()=>nextLine,newlineChars:()=>newlineChars,moveTo:()=>moveTo,moveText:()=>moveText,mergeUint8Arrays:()=>mergeUint8Arrays,mergeLines:()=>mergeLines,mergeIntoTypedArray:()=>mergeIntoTypedArray,lowSurrogate:()=>lowSurrogate,lineTo:()=>lineTo,lineSplit:()=>lineSplit,layoutSinglelineText:()=>layoutSinglelineText,layoutMultilineText:()=>layoutMultilineText,layoutCombedText:()=>layoutCombedText,last:()=>last,isWithinBMP:()=>isWithinBMP,isType:()=>isType,isStandardFont:()=>isStandardFont,isNewlineChar:()=>isNewlineChar,highSurrogate:()=>highSurrogate,hasUtf16BOM:()=>hasUtf16BOM,hasSurrogates:()=>hasSurrogates,grayscale:()=>grayscale,getType:()=>getType,findLastMatch:()=>findLastMatch,fillAndStroke:()=>fillAndStroke,fill:()=>fill,escapedNewlineChars:()=>escapedNewlineChars,escapeRegExp:()=>escapeRegExp,error:()=>error,endText:()=>endText,endPath:()=>endPath,endMarkedContent:()=>endMarkedContent,encodeToBase64:()=>encodeToBase64,drawTextLines:()=>drawTextLines,drawTextField:()=>drawTextField,drawText:()=>drawText,drawSvgPath:()=>drawSvgPath,drawRectangle:()=>drawRectangle,drawRadioButton:()=>drawRadioButton,drawPage:()=>drawPage,drawOptionList:()=>drawOptionList,drawObject:()=>drawObject,drawLinesOfText:()=>drawLinesOfText,drawLine:()=>drawLine,drawImage:()=>drawImage,drawEllipsePath:()=>drawEllipsePath,drawEllipse:()=>drawEllipse,drawCheckMark:()=>drawCheckMark,drawCheckBox:()=>drawCheckBox,drawButton:()=>drawButton,degreesToRadians:()=>degreesToRadians,degrees:()=>degrees,defaultTextFieldAppearanceProvider:()=>defaultTextFieldAppearanceProvider,defaultRadioGroupAppearanceProvider:()=>defaultRadioGroupAppearanceProvider,defaultOptionListAppearanceProvider:()=>defaultOptionListAppearanceProvider,defaultDropdownAppearanceProvider:()=>defaultDropdownAppearanceProvider,defaultCheckBoxAppearanceProvider:()=>defaultCheckBoxAppearanceProvider,defaultButtonAppearanceProvider:()=>defaultButtonAppearanceProvider,decodePDFRawStream:()=>decodePDFRawStream,decodeFromBase64DataUri:()=>decodeFromBase64DataUri,decodeFromBase64:()=>decodeFromBase64,createValueErrorMsg:()=>createValueErrorMsg,createTypeErrorMsg:()=>createTypeErrorMsg,createPDFAcroFields:()=>createPDFAcroFields,createPDFAcroField:()=>createPDFAcroField,copyStringIntoBuffer:()=>copyStringIntoBuffer,concatTransformationMatrix:()=>concatTransformationMatrix,componentsToColor:()=>componentsToColor,colorToComponents:()=>colorToComponents,cmyk:()=>cmyk,closePath:()=>closePath,clipEvenOdd:()=>clipEvenOdd,clip:()=>clip,cleanText:()=>cleanText,charSplit:()=>charSplit,charFromHexCode:()=>charFromHexCode,charFromCode:()=>charFromCode,charAtIndex:()=>charAtIndex,canBeConvertedToUint8Array:()=>canBeConvertedToUint8Array,bytesFor:()=>bytesFor,byAscendingId:()=>byAscendingId,breakTextIntoLines:()=>breakTextIntoLines,beginText:()=>beginText,beginMarkedContent:()=>beginMarkedContent,backtick:()=>backtick,assertRangeOrUndefined:()=>assertRangeOrUndefined,assertRange:()=>assertRange,assertPositive:()=>assertPositive,assertOrUndefined:()=>assertOrUndefined,assertMultiple:()=>assertMultiple,assertIsSubset:()=>assertIsSubset,assertIsOneOfOrUndefined:()=>assertIsOneOfOrUndefined,assertIsOneOf:()=>assertIsOneOf,assertIs:()=>assertIs,assertInteger:()=>assertInteger,assertEachIs:()=>assertEachIs,asPDFNumber:()=>asPDFNumber,asPDFName:()=>asPDFName,asNumber:()=>asNumber,arrayAsString:()=>arrayAsString,appendQuadraticCurve:()=>appendQuadraticCurve,appendBezierCurve:()=>appendBezierCurve,adjustDimsForRotation:()=>adjustDimsForRotation,addRandomSuffix:()=>addRandomSuffix,ViewerPreferences:()=>ViewerPreferences_default,UnsupportedEncodingError:()=>UnsupportedEncodingError,UnrecognizedStreamTypeError:()=>UnrecognizedStreamTypeError,UnexpectedObjectTypeError:()=>UnexpectedObjectTypeError,UnexpectedFieldTypeError:()=>UnexpectedFieldTypeError,UnbalancedParenthesisError:()=>UnbalancedParenthesisError,TextRenderingMode:()=>TextRenderingMode,TextAlignment:()=>TextAlignment,StandardFonts:()=>StandardFonts,StandardFontValues:()=>StandardFontValues,StandardFontEmbedder:()=>StandardFontEmbedder_default,StalledParserError:()=>StalledParserError,RotationTypes:()=>RotationTypes,RichTextFieldReadError:()=>RichTextFieldReadError,ReparseError:()=>ReparseError,RemovePageFromEmptyDocumentError:()=>RemovePageFromEmptyDocumentError,ReadingDirection:()=>ReadingDirection,PrivateConstructorError:()=>PrivateConstructorError,PrintScaling:()=>PrintScaling,PngEmbedder:()=>PngEmbedder_default,ParseSpeeds:()=>ParseSpeeds,PageSizes:()=>PageSizes,PageEmbeddingMismatchedContextError:()=>PageEmbeddingMismatchedContextError,PDFXRefStreamParser:()=>PDFXRefStreamParser_default,PDFWriter:()=>PDFWriter_default,PDFWidgetAnnotation:()=>PDFWidgetAnnotation_default,PDFTrailerDict:()=>PDFTrailerDict_default,PDFTrailer:()=>PDFTrailer_default,PDFTextField:()=>PDFTextField_default,PDFString:()=>PDFString_default,PDFStreamWriter:()=>PDFStreamWriter_default,PDFStreamParsingError:()=>PDFStreamParsingError,PDFStream:()=>PDFStream_default,PDFSignature:()=>PDFSignature_default,PDFRef:()=>PDFRef_default,PDFRawStream:()=>PDFRawStream_default,PDFRadioGroup:()=>PDFRadioGroup_default,PDFParsingError:()=>PDFParsingError,PDFParser:()=>PDFParser_default,PDFPageTree:()=>PDFPageTree_default,PDFPageLeaf:()=>PDFPageLeaf_default,PDFPageEmbedder:()=>PDFPageEmbedder_default,PDFPage:()=>PDFPage_default,PDFOptionList:()=>PDFOptionList_default,PDFOperatorNames:()=>PDFOperatorNames_default,PDFOperator:()=>PDFOperator_default,PDFObjectStreamParser:()=>PDFObjectStreamParser_default,PDFObjectStream:()=>PDFObjectStream_default,PDFObjectParsingError:()=>PDFObjectParsingError,PDFObjectParser:()=>PDFObjectParser_default,PDFObjectCopier:()=>PDFObjectCopier_default,PDFObject:()=>PDFObject_default,PDFNumber:()=>PDFNumber_default,PDFNull:()=>PDFNull_default,PDFName:()=>PDFName_default,PDFJavaScript:()=>PDFJavaScript_default,PDFInvalidObjectParsingError:()=>PDFInvalidObjectParsingError,PDFInvalidObject:()=>PDFInvalidObject_default,PDFImage:()=>PDFImage_default,PDFHexString:()=>PDFHexString_default,PDFHeader:()=>PDFHeader_default,PDFForm:()=>PDFForm_default,PDFFont:()=>PDFFont_default,PDFFlateStream:()=>PDFFlateStream_default,PDFField:()=>PDFField_default,PDFEmbeddedPage:()=>PDFEmbeddedPage_default,PDFDropdown:()=>PDFDropdown_default,PDFDocument:()=>PDFDocument_default,PDFDict:()=>PDFDict_default,PDFCrossRefStream:()=>PDFCrossRefStream_default,PDFCrossRefSection:()=>PDFCrossRefSection_default,PDFContext:()=>PDFContext_default,PDFContentStream:()=>PDFContentStream_default,PDFCheckBox:()=>PDFCheckBox_default,PDFCatalog:()=>PDFCatalog_default,PDFButton:()=>PDFButton_default,PDFBool:()=>PDFBool_default,PDFArrayIsNotRectangleError:()=>PDFArrayIsNotRectangleError,PDFArray:()=>PDFArray_default,PDFAnnotation:()=>PDFAnnotation_default,PDFAcroText:()=>PDFAcroText_default,PDFAcroTerminal:()=>PDFAcroTerminal_default,PDFAcroSignature:()=>PDFAcroSignature_default,PDFAcroRadioButton:()=>PDFAcroRadioButton_default,PDFAcroPushButton:()=>PDFAcroPushButton_default,PDFAcroNonTerminal:()=>PDFAcroNonTerminal_default,PDFAcroListBox:()=>PDFAcroListBox_default,PDFAcroForm:()=>PDFAcroForm_default,PDFAcroField:()=>PDFAcroField_default,PDFAcroComboBox:()=>PDFAcroComboBox_default,PDFAcroChoice:()=>PDFAcroChoice_default,PDFAcroCheckBox:()=>PDFAcroCheckBox_default,PDFAcroButton:()=>PDFAcroButton_default,NumberParsingError:()=>NumberParsingError,NonFullScreenPageMode:()=>NonFullScreenPageMode,NoSuchFieldError:()=>NoSuchFieldError,NextByteAssertionError:()=>NextByteAssertionError,MultiSelectValueError:()=>MultiSelectValueError,MissingTfOperatorError:()=>MissingTfOperatorError,MissingPageContentsEmbeddingError:()=>MissingPageContentsEmbeddingError,MissingPDFHeaderError:()=>MissingPDFHeaderError,MissingOnValueCheckError:()=>MissingOnValueCheckError,MissingKeywordError:()=>MissingKeywordError,MissingDAEntryError:()=>MissingDAEntryError,MissingCatalogError:()=>MissingCatalogError,MethodNotImplementedError:()=>MethodNotImplementedError,LineJoinStyle:()=>LineJoinStyle,LineCapStyle:()=>LineCapStyle,JpegEmbedder:()=>JpegEmbedder_default,InvalidTargetIndexError:()=>InvalidTargetIndexError,InvalidPDFDateStringError:()=>InvalidPDFDateStringError,InvalidMaxLengthError:()=>InvalidMaxLengthError,InvalidFieldNamePartError:()=>InvalidFieldNamePartError,InvalidAcroFieldValueError:()=>InvalidAcroFieldValueError,IndexOutOfBoundsError:()=>IndexOutOfBoundsError,ImageAlignment:()=>ImageAlignment,ForeignPageError:()=>ForeignPageError,FontkitNotRegisteredError:()=>FontkitNotRegisteredError,FileEmbedder:()=>FileEmbedder_default,FieldExistsAsNonTerminalError:()=>FieldExistsAsNonTerminalError,FieldAlreadyExistsError:()=>FieldAlreadyExistsError,ExceededMaxLengthError:()=>ExceededMaxLengthError,EncryptedPDFError:()=>EncryptedPDFError,Duplex:()=>Duplex,CustomFontSubsetEmbedder:()=>CustomFontSubsetEmbedder_default,CustomFontEmbedder:()=>CustomFontEmbedder_default,CorruptPageTreeError:()=>CorruptPageTreeError,CombedTextLayoutError:()=>CombedTextLayoutError,ColorTypes:()=>ColorTypes,CharCodes:()=>CharCodes_default,Cache:()=>Cache_default,BlendMode:()=>BlendMode,AppearanceCharacteristics:()=>AppearanceCharacteristics_default,AnnotationFlags:()=>AnnotationFlags,AcroTextFlags:()=>AcroTextFlags,AcroFieldFlags:()=>AcroFieldFlags,AcroChoiceFlags:()=>AcroChoiceFlags,AcroButtonFlags:()=>AcroButtonFlags,AFRelationship:()=>AFRelationship});var init_es2=__esm(()=>{init_api();init_core();init_utils2()});function validateFileAddOptions(value){const v=serializable(value);if(!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some((k)=>!["path","name","csv"].includes(k))||typeof v.path!=="string"||!v.path||v.path!==v.path.trim()||/[\\\x00-\x1f]/.test(v.path)||v.path.split("/").some((part)=>!part||part==="."||part==="..")||/^[A-Za-z]:/.test(v.path))throw new InboxContractError("File path must be relative to the configured working root");if(v.name!==undefined&&(typeof v.name!=="string"||!v.name||v.name!==v.name.trim()||v.name.length>255||/[\x00-\x1f\x7f/\\]/.test(v.name)))throw new InboxContractError("File name must be a safe filename");if(v.csv!==undefined)validateCsvHints(v.csv);return v}function validateCsvHints(value){const v=serializable(value);if(!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some((k)=>!["encoding","delimiter","headerRow"].includes(k))||v.encoding!==undefined&&!["utf-8","windows-1252"].includes(v.encoding)||v.delimiter!==undefined&&![",",";","\t"].includes(v.delimiter)||v.headerRow!==undefined&&(!Number.isSafeInteger(v.headerRow)||v.headerRow<0))throw new InboxContractError("Invalid CSV parsing hints");return v}function csvRows(bytes,details){let decoded;try{decoded=new TextDecoder(details.encoding,{fatal:true}).decode(bytes)}catch{throw new InboxContractError("CSV does not match its encoding")}if(/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(decoded))throw new InboxContractError("CSV contains binary bytes");let rows;try{rows=parseDelimitedText(decoded,details.delimiter)}catch{throw new InboxContractError("CSV contains malformed quoted fields")}if(details.headerRow>=rows.length||rows[details.headerRow].every((cell)=>!cell.trim())||delimitedDataRowCount(rows,details.headerRow)!==details.dataRows||rows.slice(details.headerRow+1).some((row)=>row.length!==rows[details.headerRow].length))throw new InboxContractError("CSV header, column shape or row count differs from bytes");return rows}async function pdfDetails(bytes){if(!/^%PDF-(1\.[0-7]|2\.0)[\r\n]/.test(new TextDecoder().decode(bytes.slice(0,16)))||!/%%EOF\s*$/.test(new TextDecoder().decode(bytes.slice(-1024))))throw new InboxContractError("PDF signature or end marker is missing");try{const{PDFDocument:PDFDocument2}=await Promise.resolve().then(() => (init_es2(),exports_es));const pdf=await PDFDocument2.load(bytes,{updateMetadata:false,throwOnInvalidObject:true});const pages=pdf.getPages();if(!pages.length||pages.some((page)=>!Number.isFinite(page.getWidth())||!Number.isFinite(page.getHeight())||page.getWidth()<=0||page.getHeight()<=0))throw new Error("Invalid page tree");return{kind:"pdf",pages:pages.length}}catch{throw new InboxContractError("PDF bytes could not be verified")}}async function deriveInboxFile(bytes,name,csv){if(bytes.length>26214400)throw new InboxContractError("File exceeds supported size");let details={kind:"other"},mediaType="application/octet-stream";const isPdf=new TextDecoder().decode(bytes.slice(0,5))==="%PDF-";if(isPdf){if(csv)throw new InboxContractError("CSV hints do not match PDF bytes");try{details=await pdfDetails(bytes);mediaType="application/pdf"}catch{}}else if(csv||/\.csv$/i.test(name)){const hints=csv===undefined?{}:validateCsvHints(csv);let encoding=hints.encoding;if(!encoding){try{new TextDecoder("utf-8",{fatal:true}).decode(bytes);encoding="utf-8"}catch{encoding="windows-1252"}}const decoded=new TextDecoder(encoding,{fatal:true}).decode(bytes),headerRow=hints.headerRow??0;const delimiters=hints.delimiter?[hints.delimiter]:[",",";","\t"];const candidates=delimiters.flatMap((delimiter)=>{try{const rows=parseDelimitedText(decoded,delimiter);const d={kind:"csv",encoding,delimiter,headerRow,dataRows:delimitedDataRowCount(rows,headerRow)};csvRows(bytes,d);return[{details:d,width:rows[headerRow].length}]}catch{return[]}}).sort((a,b)=>b.width-a.width);if(!candidates.length||!csv&&candidates[0].width<2){if(csv)throw new InboxContractError("CSV hints do not match file bytes")}else{details=candidates[0].details;mediaType="text/csv"}}const sha2562=[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(bytes)))].map((n)=>n.toString(16).padStart(2,"0")).join("");const{id:_id,...file2}=validateInboxFile({id:crypto.randomUUID(),name,mediaType,size:bytes.length,sha256:sha2562,details});return file2}async function verifyInboxFile(bytes,value){const file2=validateInboxFile(value);const derived=await deriveInboxFile(bytes,file2.name,file2.details.kind==="csv"?{encoding:file2.details.encoding,delimiter:file2.details.delimiter,headerRow:file2.details.headerRow}:undefined);const expectedDetails=file2.details.kind==="pdf"&&file2.details.pages===undefined&&derived.details.kind==="pdf"?{kind:"pdf"}:derived.details;if(file2.sha256!==derived.sha256||file2.size!==derived.size||file2.mediaType!==derived.mediaType||JSON.stringify(file2.details)!==JSON.stringify(expectedDetails))throw new InboxContractError("Retained file integrity or type metadata changed");return file2}var init_inbox_files=__esm(()=>{init_inbox_contract()});var exports_inbox_publication_file={};__export(exports_inbox_publication_file,{readInboxPublicationFile:()=>readInboxPublicationFile});async function readInboxPublicationFile(checkout,options){const{readFile,realpath}=await import("node:fs/promises");const{isAbsolute,relative,resolve,sep}=await import("node:path");const{path}=validateFileAddOptions(options);const root=await realpath(checkout),file2=await realpath(resolve(root,path));const rel=relative(root,file2);if(rel===".."||rel.startsWith(`..${sep}`)||isAbsolute(rel))throw new Error("Inbox file escapes working root");return new Uint8Array(await readFile(file2))}var init_inbox_publication_file=__esm(()=>{init_inbox_files()});init_inbox_contract();var REPOSITORY=/^[a-z0-9][a-z0-9._/-]{0,127}$/;function validRepositoryAlias(value){return typeof value==="string"&&REPOSITORY.test(value)&&!value.includes("//")&&!value.includes("..")}var RECORD_READ_INPUT_LIMIT=1024*1024;var RECORD_CAPTURE_OUTPUT_LIMIT=25*1024*1024;function validRecordRef(value){return typeof value==="string"&&value.length<=512&&/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(value)}function validateRecordRead(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new InboxContractError("Invalid selected-record read");const input=value;if(Object.keys(input).some((key)=>!["repository","refs","atCommit"].includes(key))||!validRepositoryAlias(input.repository)||!Array.isArray(input.refs)||!input.refs.length||input.refs.length>1e4||input.refs.some((ref)=>!validRecordRef(ref))||new Set(input.refs).size!==input.refs.length||input.atCommit!==undefined&&(typeof input.atCommit!=="string"||!/^[0-9a-f]{40}$/.test(input.atCommit)))throw new InboxContractError("Invalid selected-record read");return{repository:input.repository,refs:[...input.refs],...input.atCommit===undefined?{}:{atCommit:input.atCommit}}}class FileOperationError extends Error{code;status;retryable;constructor(code,status,retryable=false){super(code);this.code=code;this.status=status;this.retryable=retryable}}var FILE_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;var FILE_ORIGINAL_MAX_BYTES=5*1024**3;function parseFileDescriptor(value){const invalid=()=>{throw new FileOperationError("unavailable",503,true)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const f=value;if(Object.keys(f).sort().join(",")!=="details,enrichments,id,mediaType,name,path,sha256,size"||typeof f.id!=="string"||!FILE_ID_PATTERN.test(f.id)||!safeFileName(f.name)||!safeFilePath(f.path)||!Number.isSafeInteger(f.size)||f.size<0||f.size>FILE_ORIGINAL_MAX_BYTES||typeof f.sha256!=="string"||!/^[0-9a-f]{64}$/.test(f.sha256)||!f.enrichments||typeof f.enrichments!=="object"||Array.isArray(f.enrichments)||!f.details||typeof f.details!=="object"||Array.isArray(f.details))return invalid();const d=f.details;if(d.kind==="other"){if(Object.keys(d).length!==1||f.mediaType!=="application/octet-stream")return invalid()}else if(d.kind==="csv"){if(Object.keys(d).sort().join(",")!=="dataRows,delimiter,encoding,headerRow,kind"||f.mediaType!=="text/csv"||!["utf-8","windows-1252"].includes(d.encoding)||![",",";","\t"].includes(d.delimiter)||!Number.isSafeInteger(d.headerRow)||d.headerRow<1||!Number.isSafeInteger(d.dataRows)||d.dataRows<0)return invalid()}else if(d.kind==="pdf"){if(f.mediaType!=="application/pdf"||Object.keys(d).some((key)=>!["kind","pages"].includes(key))||"pages"in d&&(!Number.isSafeInteger(d.pages)||d.pages<1))return invalid()}else return invalid();for(const[name,descriptor]of Object.entries(f.enrichments)){if(!safeEnrichmentName(name))return invalid();parseEnrichmentDescriptor(descriptor)}if(new TextEncoder().encode(JSON.stringify(f)).byteLength>16*1024)return invalid();return f}function parseEnrichmentDescriptor(value){const invalid=()=>{throw new FileOperationError("unavailable",503,true)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const d=value;if(Object.keys(d).sort().join(",")!=="mediaType,sha256,size"||!["application/octet-stream","text/plain","text/markdown","application/json"].includes(d.mediaType)||!Number.isSafeInteger(d.size)||d.size<0||d.size>16*1024*1024||typeof d.sha256!=="string"||!/^[0-9a-f]{64}$/.test(d.sha256))return invalid();return d}function safeEnrichmentName(value){return safeFileName(value)&&!/^original(?:\.|$)/i.test(value)}function parseFileEnrichMetadata(value,maxBytes){const invalid=()=>{throw new FileOperationError("invalid_input",400)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const d=value;if(Object.keys(d).some((key)=>!["name","size","mediaType","replace"].includes(key))||!safeEnrichmentName(d.name)||!Number.isSafeInteger(d.size)||d.size<0||d.mediaType!==undefined&&(typeof d.mediaType!=="string"||d.mediaType.length>255||/[\u0000-\u001f\u007f]/.test(d.mediaType))||d.replace!==undefined&&(typeof d.replace!=="string"||!/^[0-9a-f]{64}$/.test(d.replace)))return invalid();if(d.size>maxBytes)throw new FileOperationError("request_too_large",413);return d}function safeFileName(value){return typeof value==="string"&&value.length>0&&value.length<=255&&value===value.trim()&&value!=="."&&value!==".."&&!/[\u0000-\u001f\u007f-\u009f/\\:*?"<>|]/u.test(value)&&!/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(value)&&!/[. ]$/.test(value)&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value)}function safeFilePath(value){return typeof value==="string"&&value.length<=1024&&value.split("/").every(safeFileName)}function parseFileCreateMetadata(value,maxBytes){const invalid=()=>{throw new FileOperationError("invalid_input",400)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const input=value;if(Object.keys(input).some((key)=>!["name","path","storage","csv","inputMediaType","size","requestKey"].includes(key)))return invalid();const path=input.path===undefined?"Files":input.path;if(!safeFileName(input.name)||!safeFilePath(path)||path.split("/")[0].toLowerCase()===".os")return invalid();if(input.storage!==undefined&&input.storage!=="remote"&&input.storage!=="local")return invalid();if(input.inputMediaType!==undefined&&input.inputMediaType!=="application/pdf")return invalid();if(!Number.isSafeInteger(input.size)||input.size<0)return invalid();if(input.size>maxBytes)throw new FileOperationError("request_too_large",413);if(typeof input.requestKey!=="string"||input.requestKey.length<1||input.requestKey.length>256||input.requestKey!==input.requestKey.trim()||/[\u0000-\u001f\u007f]/.test(input.requestKey))return invalid();let csv;if(input.csv!==undefined){if(!input.csv||typeof input.csv!=="object"||Array.isArray(input.csv))return invalid();const hints=input.csv;if(Object.keys(hints).some((key)=>!["encoding","delimiter","headerRow"].includes(key)))return invalid();const encoding=hints.encoding===undefined?"utf-8":hints.encoding;const delimiter=hints.delimiter===undefined?",":hints.delimiter;const headerRow=hints.headerRow===undefined?1:hints.headerRow;if(encoding!=="utf-8"&&encoding!=="windows-1252"||![",",";","\t"].includes(delimiter)||!Number.isSafeInteger(headerRow)||headerRow<1||headerRow>1e5)return invalid();csv={encoding,delimiter,headerRow}}return{name:input.name,path,...input.storage?{storage:input.storage}:{},...input.inputMediaType==="application/pdf"?{inputMediaType:input.inputMediaType}:{},...csv?{csv}:{},size:input.size,requestKey:input.requestKey}}class AppRoutineContractError extends Error{code;constructor(code){super(code);this.code=code}}var propertyName=/^[a-z][A-Za-z0-9]*(?![\s\S])/;var stepId=/^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/;var routineName=/^[a-z0-9][a-z0-9-]{0,62}(?![\s\S])/;var owns=(value,key)=>Object.hasOwn(value,key);var invalidContract=()=>{throw new AppRoutineContractError("invalid_contract")};var invalidValue=()=>{throw new AppRoutineContractError("invalid_value")};function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)&&(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null)}function fields2(value,required,optional=[]){return required.every((key)=>owns(value,key))&&Object.keys(value).every((key)=>required.includes(key)||optional.includes(key))}function denseArray(value){return Array.isArray(value)&&Object.keys(value).length===value.length&&Array.from({length:value.length},(_,index)=>owns(value,String(index))).every(Boolean)}function parseAppRoutineContract(value){let properties=0;function schema(value2,depth=1){if(depth>8||!record(value2))return invalidContract();switch(value2.type){case"object":{if(!fields2(value2,["type","properties","additionalProperties"],["required"])||value2.additionalProperties!==false||!record(value2.properties))return invalidContract();const entries=Object.entries(value2.properties);properties+=entries.length;if(properties>64||entries.some(([key])=>!propertyName.test(key)))return invalidContract();let required;if(owns(value2,"required")){if(!denseArray(value2.required)||value2.required.some((key)=>typeof key!=="string"||!owns(value2.properties,key))||new Set(value2.required).size!==value2.required.length)return invalidContract();required=[...value2.required]}return{type:"object",properties:Object.fromEntries(entries.map(([key,child])=>[key,schema(child,depth+1)])),...required===undefined?{}:{required},additionalProperties:false}}case"array":if(!fields2(value2,["type","items","maxItems"])||!Number.isSafeInteger(value2.maxItems)||value2.maxItems<1||value2.maxItems>64)return invalidContract();return{type:"array",items:schema(value2.items,depth+1),maxItems:value2.maxItems};case"boolean":case"file":if(!fields2(value2,["type"]))return invalidContract();return{type:value2.type};case"string":if(!fields2(value2,["type"],["maxLength"])||owns(value2,"maxLength")&&(!Number.isSafeInteger(value2.maxLength)||value2.maxLength<0||value2.maxLength>4096))return invalidContract();return{type:"string",...owns(value2,"maxLength")?{maxLength:value2.maxLength}:{}};case"integer":case"number":{const validNumber=value2.type==="integer"?Number.isSafeInteger:Number.isFinite;if(!fields2(value2,["type"],["minimum","maximum"])||owns(value2,"minimum")&&!validNumber(value2.minimum)||owns(value2,"maximum")&&!validNumber(value2.maximum)||owns(value2,"minimum")&&owns(value2,"maximum")&&value2.minimum>value2.maximum)return invalidContract();return{type:value2.type,...owns(value2,"minimum")?{minimum:value2.minimum}:{},...owns(value2,"maximum")?{maximum:value2.maximum}:{}}}default:return invalidContract()}}if(!record(value)||!fields2(value,["routine","input","steps"],["result"])||typeof value.routine!=="string"||!routineName.test(value.routine)||!denseArray(value.steps)||value.steps.length<1||value.steps.length>64)return invalidContract();const input=schema(value.input);const result=owns(value,"result")?schema(value.result):undefined;const ids=new Set;const steps=value.steps.map((step)=>{if(!record(step)||!fields2(step,["id"],["summary"])||typeof step.id!=="string"||!stepId.test(step.id)||ids.has(step.id))return invalidContract();ids.add(step.id);return{id:step.id,...owns(step,"summary")?{summary:schema(step.summary)}:{}}});return{routine:value.routine,input,steps,...result===undefined?{}:{result}}}function jsonData(value,ancestors=new Set){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return;if(!record(value)&&!denseArray(value))return invalidValue();if(ancestors.has(value))return invalidValue();ancestors.add(value);for(const child of Object.values(value))jsonData(child,ancestors);ancestors.delete(value)}function validateRoutineSchemaValue(schema,value){switch(schema.type){case"object":if(!record(value)||(schema.required??[]).some((key)=>!owns(value,key))||Object.keys(value).some((key)=>!owns(schema.properties,key)))return invalidValue();for(const[key,child]of Object.entries(value))validateRoutineSchemaValue(schema.properties[key],child);return;case"array":if(!denseArray(value)||value.length>schema.maxItems)return invalidValue();for(const child of value)validateRoutineSchemaValue(schema.items,child);return;case"boolean":if(typeof value!=="boolean")return invalidValue();return;case"string":if(typeof value!=="string"||Array.from(value).length>(schema.maxLength??4096))return invalidValue();return;case"integer":case"number":if(typeof value!=="number"||!(schema.type==="integer"?Number.isSafeInteger(value):Number.isFinite(value))||schema.minimum!==undefined&&value<schema.minimum||schema.maximum!==undefined&&value>schema.maximum)return invalidValue();return;case"file":try{jsonData(value);parseFileDescriptor(value)}catch{return invalidValue()}}}function boundedValue(schema,value){validateRoutineSchemaValue(schema,value);if(new TextEncoder().encode(JSON.stringify(value)).byteLength>16*1024)return invalidValue()}function validateAppRoutineInput(contract,value){boundedValue(contract.input,value)}function validateAppRoutineResult(contract,value){if(contract.result===undefined){if(value!==undefined)return invalidValue()}else boundedValue(contract.result,value)}function validateAppRoutineStep(contract,id2,summary){const step=contract.steps.find((step2)=>step2.id===id2);if(!step)return invalidValue();if(step.summary===undefined){if(summary!==undefined)return invalidValue()}else validateRoutineSchemaValue(step.summary,summary)}var LIMIT=256*1024;var invalid=()=>{throw new AppRoutineContractError("invalid_value")};var invalidContract2=()=>{throw new AppRoutineContractError("invalid_contract")};var empty={type:"object",properties:{},required:[],additionalProperties:false};function freeze(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))freeze(child);Object.freeze(value)}return value}function json(value,ancestors=new Set){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return;if(!value||typeof value!=="object"||ancestors.has(value))return invalid();const array2=Array.isArray(value);if(!array2&&Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)return invalid();const keys2=Reflect.ownKeys(value);if(array2&&(keys2.length!==value.length+1||!Array.from({length:value.length},(_,index)=>Object.hasOwn(value,index)).every(Boolean)))return invalid();ancestors.add(value);for(const key of keys2){if(array2&&key==="length")continue;if(typeof key!=="string")return invalid();const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor.enumerable||!Object.hasOwn(descriptor,"value"))return invalid();json(descriptor.value,ancestors)}ancestors.delete(value)}function capture(schema,value){json(value);validateRoutineSchemaValue(schema,value);const encoded=JSON.stringify(value);if(new TextEncoder().encode(encoded).byteLength>LIMIT)return invalid();return freeze(JSON.parse(encoded))}function declaration(value){try{json(value)}catch{return invalidContract2()}return freeze(parseAppRoutineContract({routine:"definition",input:value,steps:[{id:"inspect"}]}).input)}var schema={object(properties){return declaration({type:"object",properties,required:Object.keys(properties),additionalProperties:false})},array(items,options){return declaration({type:"array",items,maxItems:options.maxItems})},string(options={}){return declaration({type:"string",...options})},integer(options={}){return declaration({type:"integer",...options})},number(options={}){return declaration({type:"number",...options})},boolean(){return declaration({type:"boolean"})}};var file=()=>declaration({type:"file"});var definitions=new WeakMap;var defineRoutine=(definition)=>{if(!definition||typeof definition!=="object"||Object.getPrototypeOf(definition)!==Object.prototype||Reflect.ownKeys(definition).some((key)=>typeof key!=="string"||!["input","steps","result","run"].includes(key)||!Object.getOwnPropertyDescriptor(definition,key).enumerable||!Object.hasOwn(Object.getOwnPropertyDescriptor(definition,key),"value"))||typeof definition.run!=="function")return invalidContract2();try{for(const key of["input","steps","result"]){if(definition[key]!==undefined)json(definition[key])}}catch{return invalidContract2()}if(definition.steps!==undefined&&(!definition.steps||typeof definition.steps!=="object"||Array.isArray(definition.steps)))return invalidContract2();const steps=definition.steps===undefined?[]:Object.entries(definition.steps).map(([id2,summary])=>({id:id2,...summary===null?{}:{summary}}));const parsed=parseAppRoutineContract({routine:"definition",input:definition.input===undefined?empty:definition.input,steps:steps.length?steps:[{id:"inspect"}],...definition.result===undefined?{}:{result:definition.result}});const contract=freeze({input:parsed.input,steps:steps.length?parsed.steps:[],...parsed.result===undefined?{}:{result:parsed.result}});const captured=Object.freeze({...definition,...definition.input===undefined?{}:{input:contract.input},...definition.steps===undefined?{}:{steps:freeze(Object.fromEntries(contract.steps.map((step)=>[step.id,step.summary??null])))},...definition.result===undefined?{}:{result:contract.result},run:(input,os)=>executeRoutineDefinition(captured,input,os)});definitions.set(captured,{contract,run:definition.run});return captured};function inspectRoutineDefinition(definition){if(!definition||typeof definition!=="object")return invalidContract2();const registered=definitions.get(definition);if(!registered)return invalidContract2();return registered.contract}function captureRoutineInput(definition,input){return capture(inspectRoutineDefinition(definition).input,input)}async function executeRoutineDefinition(definition,input,runtime){const captured=captureRoutineInput(definition,input);const{contract,run}=definitions.get(definition);let active=true,broken=false;let reports=Promise.resolve();const os=Object.freeze({...runtime,run:freeze({...runtime.run}),async artifact(input2){if(!active)throw new Error("Run authority ended");if(!runtime.artifact)throw new Error("Run artifact transport unavailable");return runtime.artifact(input2)},step(id2,...summary){if(!active||broken||summary.length>1){broken=true;return Promise.reject(new AppRoutineContractError("invalid_value"))}let value;try{const step=contract.steps.find((step2)=>step2.id===id2);if(!step)return invalid();if(step.summary===undefined){if(summary.length)return invalid()}else value=capture(step.summary,summary[0])}catch(error){broken=true;return Promise.reject(error)}const report=reports.then(()=>{if(broken)return invalid();return runtime.step(id2,value)});reports=report.catch(()=>{broken=true});return report}});try{const result=await run(captured,os);active=false;await reports;if(broken)return invalid();if(contract.result!==undefined)return capture(contract.result,result);if(result!==undefined)return invalid();return}finally{active=false}}class DataOperationError extends Error{code;retryable;effect;component;constructor(code,retryable=false,effect,component){super(`Data operation failed: ${code}`);this.code=code;this.retryable=retryable;this.effect=effect;this.component=component;this.name="DataOperationError"}}var invalid2=()=>{throw new DataOperationError("invalid_query")};var historyText=(value)=>typeof value==="string"&&!/[\u0000\uD800-\uDFFF]/u.test(value);function historyVersion(value){return historyText(value)&&value.length>0&&new TextEncoder().encode(value).length<=1024&&!/[\u0000-\u001f\u007f-\u009f]/.test(value)&&!/^[0-9a-f]{40}$/i.test(value)}function historyProperties(value){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))return invalid2();const descriptors=Object.getOwnPropertyDescriptors(value);if(Reflect.ownKeys(value).some((key)=>typeof key!=="string"||!descriptors[key]?.enumerable||!Object.hasOwn(descriptors[key],"value")))return invalid2();return descriptors}var historyCollection=(value)=>typeof value==="string"&&value.length<=512&&/^[_a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(value);var historyCursor=(value)=>typeof value==="string"&&value.length<=128*1024&&/^history-cursor-v1\.[A-Za-z0-9_-]{1,64}\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+$/.test(value);function historyArray(value){if(!Array.isArray(value)||Object.getPrototypeOf(value)!==Array.prototype)return invalid2();const descriptors=Object.getOwnPropertyDescriptors(value);if(Reflect.ownKeys(value).length!==value.length+1)return invalid2();const result=[];for(let i=0;i<value.length;i++){const descriptor=descriptors[i];if(!descriptor?.enumerable||!Object.hasOwn(descriptor,"value"))return invalid2();result.push(descriptor.value)}return result}function captureOptions(value,changes){if(value===undefined)return{};const descriptors=historyProperties(value),result={};const allowed=changes?["collections","refs","from","through","limit","after"]:["limit","before"];if(Object.keys(descriptors).some((key)=>!allowed.includes(key)))return invalid2();for(const key of allowed){if(!Object.hasOwn(descriptors,key))continue;const scalar=descriptors[key].value;if(key==="collections"||key==="refs"){const values=historyArray(scalar);if(!values.length||values.length>(key==="collections"?16:100)||!values.every(key==="collections"?historyCollection:validRecordRef)||new Set(values).size!==values.length)return invalid2();result[key]=values}else if(key==="limit"){if(!Number.isInteger(scalar)||scalar<1||scalar>(changes?500:100))return invalid2();result.limit=scalar}else{if(!(key==="after"?historyCursor(scalar):historyVersion(scalar)))return invalid2();result[key]=scalar}}return result}var captureHistoryListOptions=(value)=>captureOptions(value,false);var captureHistoryChangesOptions=(value)=>captureOptions(value,true);function captureHistoryInstant(value){if(!historyText(value)||value.length>1024)return invalid2();const match=/^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?([Zz]|([+-])(\d{2}):(\d{2}))$/.exec(value);if(!match)return invalid2();const[year,month,day,hour,minute,second]=match.slice(1,7).map(Number);const days=new Date(Date.UTC(year,month,0));days.setUTCFullYear(year);if(year<1||month<1||month>12||day<1||day>days.getUTCDate()||hour>23||minute>59||second>59||Number(match[9]??0)>23||Number(match[10]??0)>59)return invalid2();return value}var invalid3=()=>{throw new DataOperationError("invalid_query")};function captureRecordsSearchInput(query,options){if(!historyText(query))return invalid3();const length=[...query.trim()].length;if(length<1||length>256)return invalid3();if(options===undefined)return{query};const descriptors=historyProperties(options);if(Object.keys(descriptors).some((key)=>!["collections","limit"].includes(key)))return invalid3();const captured={};if(Object.hasOwn(descriptors,"collections")){const supplied=descriptors.collections.value;if(!Array.isArray(supplied)||supplied.length<1||supplied.length>16||Reflect.ownKeys(supplied).length!==supplied.length+1)return invalid3();const collections=[];for(let index=0;index<supplied.length;index++){const descriptor=Object.getOwnPropertyDescriptor(supplied,String(index));if(!descriptor?.enumerable||!Object.hasOwn(descriptor,"value")||!historyText(descriptor.value))return invalid3();collections.push(descriptor.value)}if(new Set(collections).size!==collections.length)return invalid3();captured.collections=collections}if(Object.hasOwn(descriptors,"limit")){const supplied=descriptors.limit.value;if(!Number.isInteger(supplied)||supplied<1||supplied>100)return invalid3();captured.limit=supplied}return{query,options:captured}}var DATA_REQUEST_LIMIT=256*1024;var invalidChange=()=>{throw new DataOperationError("invalid_change",false,"unapplied")};function mapping(value){try{historyProperties(value);return value}catch{return invalidChange()}}function captureValue(value,ancestors=new Set,depth=0){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return value;if(!value||typeof value!=="object"||ancestors.has(value)||depth>32)return invalidChange();ancestors.add(value);try{if(Array.isArray(value)){if(value.length>1e5||Object.keys(value).length!==value.length||Object.getOwnPropertySymbols(value).length)return invalidChange();return Array.from(value,(item)=>captureValue(item,ancestors,depth+1))}return Object.fromEntries(Object.entries(mapping(value)).map(([key,item])=>{if(["__proto__","constructor","prototype"].includes(key))return invalidChange();return[key,captureValue(item,ancestors,depth+1)]}))}finally{ancestors.delete(value)}}function captureDataDelete(record2){const identity=mapping(record2);if(!validRecordRef(identity.$ref)||typeof identity.$version!=="string"||!identity.$version.length||identity.$version.length>512)return invalidChange();return{ref:identity.$ref,expectedVersion:identity.$version}}function captureDataUpdate(record2,set){const identity=captureDataDelete(record2),fields3=mapping(set);if(!Object.keys(fields3).length||Object.keys(fields3).some((key)=>key.startsWith("$")||["id","type"].includes(key)))return invalidChange();return{...identity,set:captureValue(fields3)}}function captureIdentities(value,update,allowEmpty=true){if(!Array.isArray(value)||!allowEmpty&&!value.length||value.length>1e4)return invalidChange();const captured=value.map((item)=>{const row=mapping(item);if(Object.keys(row).sort().join(",")!==(update?"expectedVersion,ref,set":"expectedVersion,ref"))return invalidChange();const identity={$ref:row.ref,$version:row.expectedVersion};return update?captureDataUpdate(identity,row.set):captureDataDelete(identity)});if(new Set(captured.map((item)=>item.ref)).size!==captured.length)return invalidChange();return captured}function captureDataUpdates(value,allowEmpty=false){return captureIdentities(value,true,allowEmpty)}function captureDataCreate(value){const row=mapping(value);if(!validRecordRef(row.$ref)||Object.keys(row).some((key)=>key.startsWith("$")&&!["$ref","$filing"].includes(key)))return invalidChange();const{$ref:ref,$filing,...fields3}=row;let filing;if($filing!==undefined){const components=mapping($filing);if(Object.entries(components).some(([name,value2])=>!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name)||["constructor","prototype"].includes(name)||typeof value2!=="string"||!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(value2)))return invalidChange();filing={...components}}return{ref,fields:captureValue(fields3),...filing?{filing}:{}}}function captureDataChanges(updatesValue,createsValue=[],deletesValue=[]){const updates=captureDataUpdates(updatesValue,true);if(!Array.isArray(createsValue)||createsValue.length>1e4)return invalidChange();const creates=createsValue.map((item)=>{const row=mapping(item);if(Object.keys(row).some((key)=>!["ref","fields","filing"].includes(key))||!Object.hasOwn(row,"ref")||!Object.hasOwn(row,"fields"))return invalidChange();const fields3=mapping(row.fields);if(Object.keys(fields3).some((key)=>key.startsWith("$")))return invalidChange();return captureDataCreate({...fields3,$ref:row.ref,...Object.hasOwn(row,"filing")?{$filing:row.filing}:{}})});const deletes=captureIdentities(deletesValue,false);const refs=[...updates,...creates,...deletes].map((item)=>item.ref);if(!refs.length||refs.length>1e4||new Set(refs).size!==refs.length)return invalidChange();return{updates,creates,deletes}}function checkDataRequestSize(input){if(new TextEncoder().encode(JSON.stringify(input)).byteLength>DATA_REQUEST_LIMIT)throw new DataOperationError("request_too_large",false,"unapplied")}function dataTransportError(status,value){const failures={400:["invalid_query","invalid_change"],401:["unauthenticated"],403:["access_denied"],409:["conflict","publication_pending"],413:["request_too_large"],429:["capacity"],503:["unavailable","publication_pending"]};const error=value&&typeof value==="object"&&"error"in value?value.error:undefined;const row=error&&typeof error==="object"?error:undefined;const code=failures[status]?.find((allowed)=>allowed===row?.code)??"unavailable";const effect=["unapplied","uncertain","applied"].includes(String(row?.effect))?row.effect:undefined;return new DataOperationError(code,["capacity","unavailable","publication_pending"].includes(code),code==="conflict"?"unapplied":effect,code==="invalid_change"&&typeof row?.component==="string"&&/^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/.test(row.component)?row.component:undefined)}var AUTH_ORIGIN="https://auth.oddington.ai";function oddingtonOrigin(environment=process.env){const value=environment.ODDINGTON_OS_ORIGIN??AUTH_ORIGIN;const url=new URL(value);if(url.protocol!=="https:"&&url.hostname!=="127.0.0.1")throw new Error("ODDINGTON_OS_ORIGIN must use HTTPS");return url.origin}var nodeRequest;var nodeReadable;if(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__){({request:nodeRequest}=await import("node:http"));({Readable:nodeReadable}=await import("node:stream"))}function privateRoutineRequest(environment=typeof __ODDINGTON_BROWSER__!=="undefined"&&__ODDINGTON_BROWSER__?{}:typeof process==="undefined"?{}:process.env){if(typeof __ODDINGTON_BROWSER__!=="undefined"&&__ODDINGTON_BROWSER__)return;const prepared=["ODDINGTON_ROUTINE_LOCAL","ODDINGTON_ROUTINE_LOCAL_SOCKET","ODDINGTON_ROUTINE_LOCAL_TOKEN"].some((key)=>environment[key]!==undefined);const managed=["ODDINGTON_FILES_SOCKET","ODDINGTON_FILES_TOKEN"].some((key)=>environment[key]!==undefined);if(!prepared&&!managed)return;const socket=prepared?environment.ODDINGTON_ROUTINE_LOCAL_SOCKET:environment.ODDINGTON_FILES_SOCKET;const token=prepared?environment.ODDINGTON_ROUTINE_LOCAL_TOKEN:environment.ODDINGTON_FILES_TOKEN;const request=localRoutineRequest(prepared?environment:{ODDINGTON_ROUTINE_LOCAL:"1",ODDINGTON_ROUTINE_LOCAL_SOCKET:socket,ODDINGTON_ROUTINE_LOCAL_TOKEN:token});const isCurrent=()=>prepared?environment.ODDINGTON_ROUTINE_LOCAL==="1"&&environment.ODDINGTON_ROUTINE_LOCAL_SOCKET===socket&&environment.ODDINGTON_ROUTINE_LOCAL_TOKEN===token:environment.ODDINGTON_FILES_SOCKET===socket&&environment.ODDINGTON_FILES_TOKEN===token;if(!nodeRequest||!nodeReadable)throw new Error("Files transport unavailable");const httpRequest=nodeRequest,Readable=nodeReadable;const files=async(suffix,init,signal)=>{if(!isCurrent())throw new FileOperationError("unsupported_context",400);const tcp=/^tcp:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/.exec(socket);const endpoint=tcp?{hostname:"127.0.0.1",port:Number(tcp[1])}:{socketPath:socket};const id2=crypto.randomUUID();if(init.body instanceof ReadableStream||suffix===""&&init.method==="POST"){await new Promise((resolve,reject)=>{const admission=httpRequest({...endpoint,path:"/files/admit",method:"POST",timeout:30000,signal,agent:false,headers:{...Object.fromEntries(new Headers(init.headers)),authorization:`Bearer ${token}`,"x-oddington-files-suffix":encodeURIComponent(suffix),"x-oddington-files-method":init.method??"GET"}},(response)=>{const bytes=Buffer.alloc(16384);let size=0;response.on("data",(chunk)=>{size+=chunk.length;if(size>16384)response.destroy(new Error("Files admission result exceeds supported size"));else bytes.set(chunk,size-chunk.length)});response.once("error",reject);response.once("end",()=>{if(response.statusCode===204){resolve();return}try{const value=JSON.parse(bytes.subarray(0,size).toString());const code=value?.error?.code;const status=response.statusCode??503;if(["invalid_input","request_too_large","unsupported_context","access_denied","capacity","unavailable"].includes(code))reject(new FileOperationError(code,status,code==="capacity"||code==="unavailable"));else reject(new FileOperationError("unavailable",503,true))}catch{reject(new FileOperationError("unavailable",503,true))}})});admission.once("error",()=>reject(new FileOperationError("unavailable",503,true)));admission.once("timeout",()=>admission.destroy(new Error("Files admission stalled")));admission.end()});if(!isCurrent())throw new FileOperationError("unsupported_context",400)}let cancellation;const cancelCall=()=>cancellation??=new Promise((resolve,reject)=>{const cancel=httpRequest({...endpoint,path:"/files/cancel",method:"POST",timeout:30000,headers:{authorization:`Bearer ${token}`,"x-oddington-files-call":id2}},(response)=>{response.resume();response.once("end",resolve);response.once("error",reject)});cancel.once("error",reject);cancel.once("timeout",()=>cancel.destroy(new Error("Files cancellation stalled")));cancel.end()});let pumping=Promise.resolve();let sourceReader;const result=new Promise((resolve,reject)=>{const call=httpRequest({...endpoint,path:"/files/stream",method:"POST",headers:{...Object.fromEntries(new Headers(init.headers)),authorization:`Bearer ${token}`,"x-oddington-files-call":id2,"x-oddington-files-suffix":encodeURIComponent(suffix),"x-oddington-files-method":init.method??"GET"},signal,timeout:30000,agent:false},async(response)=>{try{call.setTimeout(0);if((response.statusCode??503)>=400){await sourceReader?.cancel().catch(()=>{});call.end()}await pumping;if(!isCurrent()){response.destroy();reject(new FileOperationError("unsupported_context",400));return}const headers=new Headers;for(const[key,value]of Object.entries(response.headers))if(value!==undefined)headers.set(key,Array.isArray(value)?value.join(", "):value);const source=Readable.toWeb(response,{strategy:{highWaterMark:65536,size:(chunk)=>chunk.byteLength}});const reader=source.getReader();if(response.statusCode===204){const timer=setTimeout(()=>response.destroy(new Error("Files completion stalled")),30000);try{if(!(await reader.read()).done)throw new FileOperationError("unavailable",503,true);if(!isCurrent())throw new FileOperationError("unsupported_context",400);resolve(new Response(null,{status:204,headers}))}finally{clearTimeout(timer);reader.releaseLock()}return}let closed=false;const body=new ReadableStream({async pull(controller){let timer;try{if(!isCurrent())throw new FileOperationError("unsupported_context",400);timer=setTimeout(()=>response.destroy(new Error("Files delivery stalled")),30000);const next=await reader.read();if(closed)return;if(next.done){closed=true;reader.releaseLock();controller.close()}else controller.enqueue(next.value)}catch(error){closed=true;controller.error(error);await cancelCall().catch(()=>{});response.socket?.destroy();response.destroy();await reader.cancel(error).catch(()=>{});reader.releaseLock()}finally{clearTimeout(timer)}},async cancel(reason){closed=true;await cancelCall().catch(()=>{});response.socket?.destroy();response.destroy();call.destroy();await reader.cancel(reason).catch(()=>{});reader.releaseLock()}},{highWaterMark:0});resolve(new Response(body,{status:response.statusCode??503,headers}))}catch(error){response.destroy();reject(error instanceof FileOperationError?error:new FileOperationError("unavailable",503,true))}});call.on("error",(error)=>{cancelCall().catch(()=>{});reject(error instanceof FileOperationError?error:new FileOperationError("unavailable",503,true))});call.on("timeout",()=>call.destroy(new Error("Files I/O stalled")));call.on("information",()=>call.setTimeout(30000));if(init.body instanceof ReadableStream){call.flushHeaders();const reader=sourceReader=init.body.getReader();const abort=()=>{reader.cancel(signal.reason).catch(()=>{})};signal.addEventListener("abort",abort,{once:true});call.once("close",abort);pumping=(async()=>{try{for(;;){const next=await reader.read();if(next.done)break;if(!(next.value instanceof Uint8Array))throw new FileOperationError("invalid_input",400);if(!isCurrent())throw new FileOperationError("unsupported_context",400);for(let offset=0;offset<next.value.byteLength;offset+=262144){if(call.destroyed)throw new Error("Files parent disconnected");await new Promise((done,fail2)=>{const closed=()=>fail2(new Error("Files parent disconnected"));call.once("close",closed);call.write(next.value.subarray(offset,offset+262144),(error)=>{call.removeListener("close",closed);error?fail2(error):done()})})}}call.end()}catch(error){call.destroy(error instanceof Error?error:new Error("Files transport failed"))}finally{await reader.cancel().catch(()=>{});signal.removeEventListener("abort",abort);call.removeListener("close",abort);reader.releaseLock()}})()}else call.end(init.body===undefined?undefined:Buffer.from(init.body))});try{return await result}finally{await pumping}};return{request,files,isCurrent,identity:`private:${socket}`}}function localRoutineRequest(environment=typeof __ODDINGTON_BROWSER__!=="undefined"&&__ODDINGTON_BROWSER__?{}:typeof process==="undefined"?{}:process.env){if(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__){const{ODDINGTON_ROUTINE_LOCAL:mode,ODDINGTON_ROUTINE_LOCAL_SOCKET:socket,ODDINGTON_ROUTINE_LOCAL_TOKEN:token}=environment;if(mode===undefined&&socket===undefined&&token===undefined)return;if(mode!=="1"||!socket||!token||!/^[0-9a-f]{64}$/.test(token))throw new Error("Preparation transport unavailable; nothing can publish");const tcp=/^tcp:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/.exec(socket);const endpoint=tcp&&tcp[0]===socket&&Number(tcp[1])<=65535?{hostname:"127.0.0.1",port:Number(tcp[1])}:socket.startsWith("/")&&!socket.startsWith("//")&&!socket.includes("\x00")?{socketPath:socket}:undefined;if(!endpoint)throw new Error("Preparation transport unavailable; nothing can publish");return async(operation,input)=>{const{request}=await import("node:http");return await new Promise((resolve,reject)=>{const call=request({...endpoint,path:`/${operation}`,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${token}`},timeout:120000},(response)=>{const bytes=Buffer.alloc(33554432);let size=0;response.on("data",(chunk)=>{size+=chunk.length;if(size>33554432){response.destroy();reject(new Error("Local result exceeds supported size"))}else bytes.set(chunk,size-chunk.length)});response.on("error",reject);response.on("end",()=>{try{const result=JSON.parse(bytes.subarray(0,size).toString());if(response.statusCode!==200){if(operation==="files/request"){const error=result.error;const status=response.statusCode??503;const codes=["invalid_input","unsupported_context","unauthenticated","access_denied","request_too_large","conflict","local_only","integrity","unavailable","capacity","method_not_allowed"];if(error?.code&&codes.includes(error.code))throw new FileOperationError(error.code,status,error.code==="capacity"||error.code==="unavailable");throw new FileOperationError("unavailable",503,true)}if(operation==="data/query"){throw dataTransportError(response.statusCode??0,result)}throw new Error(typeof result.error==="string"?result.error:"Preparation failed")}resolve(result)}catch(error){reject(error)}})});call.on("error",()=>reject(operation==="data/query"?dataTransportError(503,{error:{code:"unavailable"}}):new Error("Preparation transport unavailable; nothing was published")));call.on("timeout",()=>call.destroy(new Error("Preparation timed out")));call.end(JSON.stringify(input))})}}}var installed;var ended=false;function routineTransport(){if(ended||installed&&!installed.isCurrent())throw new Error("Routine authority ended");return installed}var memberContext;function installMemberContext(resolve){memberContext=resolve;return()=>{if(memberContext===resolve)memberContext=undefined}}async function resolveAppContext(){const host=memberContext;if(!host)throw new Error("App context unavailable.");const context=await host();if(host!==memberContext||!context.isCurrent()||context.expiresAt<=Date.now()||context.kind!=="local"&&(typeof context.accessToken!=="string"||!/^[^\s]{1,8192}$/.test(context.accessToken))){throw new Error("App context unavailable.")}return context}async function resolveDataContext(){try{if(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__){const installed2=routineTransport();if(installed2)return{local:installed2.request};const local=localRoutineRequest();if(local)return{local};const managed=privateRoutineRequest();if(managed)return{local:managed.request}}const host=memberContext;if(host!==undefined){const context=await host();if(host!==memberContext||!context.isCurrent()||context.expiresAt<=Date.now())throw new Error;if(context.kind==="local")return{local:context.requestData};if(!context||!Number.isFinite(context.expiresAt)||context.expiresAt<=Date.now()||typeof context.accessToken!=="string"||!/^[^\s]{1,8192}$/.test(context.accessToken))throw new Error;return checked(context.workspace,context.endpoint,{authorization:`Bearer ${context.accessToken}`})}if(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__){const environment=typeof process==="undefined"?undefined:process.env;if(!environment||!/^[0-9a-f]{64}$/.test(environment.ODDINGTON_ROUTINE_RUN??""))throw new Error;return checked(environment.ODDINGTON_ROUTINE_WORKSPACE,oddingtonOrigin(environment),{"x-oddington-run":environment.ODDINGTON_ROUTINE_RUN})}throw new Error}catch{throw new DataOperationError("context_unavailable")}}async function resolveFilesContext(){try{const environment=typeof __ODDINGTON_BROWSER__!=="undefined"&&__ODDINGTON_BROWSER__?{}:typeof process==="undefined"?{}:process.env;if(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__){const installed2=routineTransport();if(installed2)return{url:"private:installed",headers:{},isCurrent:installed2.isCurrent,local:installed2.request,localFiles:installed2.files};const local=privateRoutineRequest(environment);if(local)return{url:local.identity,headers:{},isCurrent:local.isCurrent,local:local.request,localFiles:local.files}}const host=memberContext;if(host){const context=await host();if(context.kind==="local")throw new Error;if(!Number.isFinite(context.expiresAt)||context.expiresAt<=Date.now()||typeof context.accessToken!=="string"||!/^[^\s]{1,8192}$/.test(context.accessToken))throw new Error;return{...filesContext(context.workspace,context.endpoint,{authorization:`Bearer ${context.accessToken}`}),isCurrent:context.isCurrent,local:undefined,localFiles:undefined}}if(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__){if(!/^[0-9a-f]{64}$/.test(environment.ODDINGTON_ROUTINE_RUN??""))throw new Error;const workspace=environment.ODDINGTON_ROUTINE_WORKSPACE;return{...filesContext(workspace,`https://${workspace}.oddington.ai`,{"x-oddington-run":environment.ODDINGTON_ROUTINE_RUN}),local:undefined,localFiles:undefined}}throw new Error}catch{throw new FileOperationError("unsupported_context",400)}}function filesContext(workspace,endpoint,headers){if(!workspace||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(workspace)||workspace.length>63||["auth","www","api","os"].includes(workspace)||endpoint!==`https://${workspace}.oddington.ai`)throw new Error;return{url:`${endpoint}/api/files`,headers:{...headers,"x-oddington-workspace":workspace},isCurrent:()=>true}}function checked(workspace,endpoint,headers){if(!workspace||!/^[a-z0-9][a-z0-9-]{0,127}$/.test(workspace))throw new Error;const origin=new URL(endpoint);if(origin.protocol!=="https:"||origin.username||origin.password||origin.search||origin.hash||origin.pathname!=="/")throw new Error;return{url:`${origin.origin}/api/data`,headers:{...headers,"x-oddington-workspace":workspace}}}var data={repository(repository){async function send(input){const context=await resolveDataContext();const envelope={repository,...input};checkDataRequestSize(envelope);if("local"in context)return await context.local("data/query",envelope);try{const response=await fetch(context.url,{method:"POST",redirect:"error",cache:"no-store",headers:{"content-type":"application/json",...context.headers},body:JSON.stringify(envelope)});const result=await response.json();if(!response.ok){throw dataTransportError(response.status,result)}return result}catch(error){if(error instanceof DataOperationError)throw error;throw new DataOperationError("unavailable",true)}}return{collections:{list:()=>send({operation:"collections.list"}),schema:(name)=>send({operation:"collections.schema",name})},records:{select:(query)=>send({operation:"records.select",query}),search:async(query,options)=>send({operation:"records.search",...captureRecordsSearchInput(query,options)})},history:{list:async(options)=>send({operation:"history.list",options:captureHistoryListOptions(options)}),at:async(instant)=>send({operation:"history.at",instant:captureHistoryInstant(instant)}),changes:async(options)=>send({operation:"history.changes",options:captureHistoryChangesOptions(options)})},changes(){let updates=[],creates=[],deletes=[],publicationId;let pending,confirmed;const assertMutable=()=>{if(publicationId)throw new DataOperationError("invalid_change",false,"unapplied")};const snapshot=(nextUpdates=updates,nextCreates=creates,nextDeletes=deletes)=>{const{updates:updates2,creates:creates2,deletes:deletes2}=captureDataChanges(nextUpdates,nextCreates,nextDeletes);const input={updates:updates2,...creates2.length?{creates:creates2}:{},...deletes2.length?{deletes:deletes2}:{}};checkDataRequestSize({repository,operation:"changes.publish",...input,publicationId:publicationId??"00000000-0000-4000-8000-000000000000"});return input};return{create(record2){assertMutable();const next=[...creates,captureDataCreate(record2)];snapshot(updates,next,deletes);creates=next},update(record2,set){assertMutable();const next=[...updates,captureDataUpdate(record2,set)];snapshot(next,creates,deletes);updates=next},delete(record2){assertMutable();const next=[...deletes,captureDataDelete(record2)];snapshot(updates,creates,next);deletes=next},async validate(){await send({operation:"changes.validate",...snapshot()})},publish(){if(confirmed)return Promise.resolve(structuredClone(confirmed));if(!pending){let captured;try{captured=snapshot()}catch(error){return Promise.reject(error)}publicationId??=routineTransport()?.key("data")??crypto.randomUUID();pending=send({operation:"changes.publish",...captured,publicationId}).then((result)=>{confirmed=structuredClone(result);return result}).catch((error)=>{if(error instanceof DataOperationError)throw new DataOperationError(error.code,error.retryable,error.effect??(["unavailable","publication_pending"].includes(error.code)?"uncertain":"unapplied"),error.component);throw new DataOperationError("unavailable",true,"uncertain")}).finally(()=>{pending=undefined})}return pending.then((result)=>structuredClone(result))}}}}}};var MAX_BYTES=16*1024*1024;var PART_BYTES=8*1024*1024;var METADATA_BYTES=4096;var RESULT_BYTES=16*1024;var CONTROL_RESULT_BYTES=128*1024;var TIMEOUT_MS=30000;var MAX_ACTIVE=4;var ATTEMPTS=2;var active=0;var invalid4=()=>new FileOperationError("invalid_input",400);var unavailable=()=>new FileOperationError("unavailable",503,true);var failures={400:["invalid_input","unsupported_context"],401:["unauthenticated"],403:["access_denied"],405:["method_not_allowed"],409:["conflict","local_only"],413:["request_too_large"],429:["capacity"],503:["integrity","unavailable"]};async function boundedBytes(stream,limit){if(!stream)return new Uint8Array;const reader=stream.getReader();const bytes=new Uint8Array(limit);let size=0;try{for(;;){const{done,value}=await reader.read();if(done)break;if(!(value instanceof Uint8Array))throw invalid4();size+=value.byteLength;if(size>limit)throw new FileOperationError("request_too_large",413);bytes.set(value,size-value.byteLength)}}finally{reader.releaseLock()}return bytes.slice(0,size)}async function timed(work,parent,timeout=TIMEOUT_MS){const controller=new AbortController;let timer;let abort;const expiry=new Promise((_,reject)=>{abort=()=>{controller.abort();reject(unavailable())};timer=setTimeout(abort,timeout);parent?.addEventListener("abort",abort,{once:true});if(parent?.aborted)abort()});try{return await Promise.race([work(controller.signal),expiry])}finally{clearTimeout(timer);parent?.removeEventListener("abort",abort)}}async function result(response,maximum=RESULT_BYTES){try{const bytes=await boundedBytes(response.body,maximum);return JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes))}catch{throw unavailable()}}async function hostedContent(url,init,parent,upstream=fetch){const delivery=new AbortController;const abort=()=>delivery.abort(parent.reason);parent.addEventListener("abort",abort,{once:true});if(parent.aborted)abort();const detach=()=>parent.removeEventListener("abort",abort);try{const response=await upstream(url,{...init,signal:delivery.signal});if(delivery.signal.aborted){response.body?.cancel().catch(()=>{});throw unavailable()}if(!response.body){detach();return response}const source=response.body;let reader;let settled=false;const cancel=async(reason)=>{if(settled)return;settled=true;detach();delivery.abort(reason);try{await(reader?reader.cancel(reason):source.cancel(reason))}catch(error){if(error!==delivery.signal.reason&&!(error instanceof Error&&error.name==="AbortError"))throw error}finally{reader?.releaseLock()}};const body=new ReadableStream({async pull(controller){try{reader??=source.getReader();const{done,value}=await reader.read();if(settled)return;if(done){settled=true;detach();reader.releaseLock();controller.close()}else controller.enqueue(value)}catch(error){if(settled)return;controller.error(error);await cancel(error).catch(()=>{})}},cancel},{highWaterMark:0});const wrapped=new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers});for(const key of["url","redirected","type"])Object.defineProperty(wrapped,key,{value:response[key]});return wrapped}catch(error){detach();delivery.abort(error);throw error}}async function send(suffix,init,descriptor,initial,parent){const original=initial;const checkCurrent=(context=original)=>{if(parent?.aborted)throw unavailable();if(!original.isCurrent()||context.url!==original.url)throw new FileOperationError("unsupported_context",400)};for(let attempt=0;attempt<ATTEMPTS;attempt++){checkCurrent();const context=await resolveFilesContext();checkCurrent(context);try{const response=(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__)&&context.localFiles?await context.localFiles(suffix,init,parent):await(async()=>{const url=`${context.url}${suffix}`;const request={...init,signal:parent,headers:{...context.headers,...init.headers},redirect:"error",cache:"no-store"};return descriptor?fetch(url,request):hostedContent(url,request,parent)})();if(!response.ok){const value2=await result(response);const error=value2&&typeof value2==="object"&&"error"in value2?value2.error:undefined;const received=error&&typeof error==="object"&&"code"in error?error.code:undefined;const code=failures[response.status]?.find((code2)=>code2===received);throw code?new FileOperationError(code,response.status,code==="capacity"||code==="unavailable"):unavailable()}if(response.status!==(descriptor===204?204:200)||descriptor===204&&response.body!==null){response.body?.cancel().catch(()=>{});throw unavailable()}try{checkCurrent()}catch(error){response.body?.cancel().catch(()=>{});throw error}if(descriptor===204)return;if(!descriptor)return response;const value=await result(response,descriptor==="control"?CONTROL_RESULT_BYTES:RESULT_BYTES);if(descriptor==="control"){checkCurrent();return value}let parsed;if(descriptor==="enrichment"){if(!value||typeof value!=="object"||Array.isArray(value))throw unavailable();const{name,...metadata}=value;if(!safeEnrichmentName(name))throw unavailable();parsed={name,...parseEnrichmentDescriptor(metadata)}}else parsed=parseFileDescriptor(value);checkCurrent();return parsed}catch(error){const failure=error instanceof FileOperationError?error:unavailable();if(init.body instanceof ReadableStream||!failure.retryable||attempt+1===ATTEMPTS)throw failure}}throw unavailable()}function idPath(id2){if(typeof id2!=="string"||!FILE_ID_PATTERN.test(id2))throw invalid4();return`/${id2}`}async function multipartCreate(input,metadata,exchange,release=()=>{active--},upload){const route=upload?`${idPath(upload.file.id)}/upload/multipart`:"/multipart";let ticket;let reader;let chunk,offset=0;const receipts=[];const pending=new Set;const request=(work,timeout=TIMEOUT_MS)=>timed((signal)=>{const task=work(signal);pending.add(task);task.then(()=>pending.delete(task),()=>pending.delete(task));return task},undefined,timeout);const control=(body)=>({method:"POST",headers:{"content-type":"application/json",...ticket?{"x-oddington-transfer":ticket}:{}},body:JSON.stringify(body)});try{const start=await request((signal)=>exchange(`${route}/start`,control(upload?.file??metadata),"control",signal));if(!start||typeof start!=="object"||Array.isArray(start))throw unavailable();const session=start;if(Object.keys(session).sort().join(",")!=="partBytes,ticket"||session.partBytes!==PART_BYTES||typeof session.ticket!=="string"||!session.ticket||session.ticket.length>64*1024)throw unavailable();ticket=session.ticket;if(input.file instanceof ReadableStream)reader=input.file.getReader();let lastProgress=Date.now();const next=async()=>{try{if(Date.now()-lastProgress>=TIMEOUT_MS)throw unavailable();const value=await request(()=>reader.read(),Math.max(1,TIMEOUT_MS-(Date.now()-lastProgress)));if(value.value?.byteLength)lastProgress=Date.now();return value}catch(error){await reader.cancel(error).catch(()=>{});throw error}};for(let sent=0,partNumber=1;sent<metadata.size||metadata.size===0&&partNumber===1;partNumber++){const length=Math.min(PART_BYTES,metadata.size-sent);let part;if(input.file instanceof Uint8Array)part=input.file.subarray(sent,sent+length).slice();else if(input.file instanceof Blob){const slice=input.file.slice(sent,sent+length);part=new Uint8Array(await request(()=>slice.arrayBuffer()))}else{part=new Uint8Array(length);let filled=0;while(filled<length){if(!chunk||offset===chunk.byteLength){chunk=undefined;offset=0;const value2=await next();if(value2.done)throw invalid4();if(!(value2.value instanceof Uint8Array))throw invalid4();chunk=value2.value;if(chunk.byteLength>metadata.size-sent-filled)throw invalid4()}const take=Math.min(length-filled,chunk.byteLength-offset);part.set(chunk.subarray(offset,offset+take),filled);filled+=take;offset+=take;if(offset===chunk.byteLength){chunk=undefined;offset=0}}}if(part.byteLength!==length)throw invalid4();if(reader&&sent+length===metadata.size){lastProgress=Date.now();for(;;){const value2=await next();if(value2.done)break;if(!(value2.value instanceof Uint8Array)||value2.value.byteLength)throw invalid4()}}const value=await request((signal)=>exchange(`${route}/part`,{method:"POST",headers:{"content-type":"application/octet-stream","x-oddington-transfer":ticket,"x-oddington-part":String(partNumber)},body:part.buffer},"control",signal));part=undefined;const receipt=value;if(!receipt||typeof receipt!=="object"||Object.keys(receipt).sort().join(",")!=="etag,partNumber"||receipt.partNumber!==partNumber||typeof receipt.etag!=="string"||!receipt.etag||receipt.etag.length>256||/[\u0000-\u001f\u007f]/.test(receipt.etag))throw unavailable();receipts.push({partNumber,etag:receipt.etag});sent+=length;lastProgress=Date.now()}if(upload)for(const name of Object.keys(upload.file.enrichments)){const bytes=await request(()=>upload.enrichment(name));if(bytes.byteLength!==upload.file.enrichments[name].size||bytes.byteLength>MAX_BYTES)throw invalid4();await request((signal)=>exchange(`${route}/enrichments/${encodeURIComponent(name)}`,{method:"POST",headers:{"content-type":"application/octet-stream","x-oddington-transfer":ticket},body:bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.byteLength)},"control",signal))}await upload?.beforeComplete();const completion=control({parts:receipts});if(new TextEncoder().encode(completion.body).byteLength>128*1024)throw unavailable();return parseFileDescriptor(await request((signal)=>exchange(`${route}/complete`,completion,true,signal),TIMEOUT_MS+Math.ceil(metadata.size/(1024*1024))*1000))}catch(error){if(reader)await reader.cancel(error).catch(()=>{});if(ticket)await request((signal)=>exchange(`${route}/abort`,control({}),"control",signal)).catch(()=>{});throw error instanceof FileOperationError?error:unavailable()}finally{chunk=undefined;reader?.releaseLock();if(pending.size)Promise.allSettled([...pending]).then(release);else release()}}async function operation(work,initial,parent){const context=initial??await resolveFilesContext();if(active>=MAX_ACTIVE)throw new FileOperationError("capacity",429,true);active++;const execute=async(signal)=>{try{return await work(context,signal)}finally{active--}};if((typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__)&&context.localFiles)return execute(parent??new AbortController().signal);return timed(execute,parent).catch((error)=>{throw error instanceof FileOperationError?error:unavailable()})}function contentPath(id2,name){const path=idPath(id2);if(name===undefined)return`${path}/content`;if(!safeEnrichmentName(name))throw invalid4();return`${path}/enrichments/${encodeURIComponent(name)}/content`}async function read(id2,names){const context=await resolveFilesContext();idPath(id2);if(names===undefined||typeof names==="string"){const path=contentPath(id2,names);return operation((context2,signal)=>send(path,{method:"GET"},false,context2,signal),context)}if(!Array.isArray(names))throw invalid4();const distinct=[];const seen=new Set;for(const name of names){if(typeof name!=="string"||!safeEnrichmentName(name))throw invalid4();if(seen.has(name))continue;if(seen.size===16)throw invalid4();seen.add(name);distinct.push(name)}const paths=distinct.map((name)=>contentPath(id2,name));return timed(async(parent)=>{const responses={};try{for(let i=0;i<paths.length;i++){const response=await operation((context2,signal)=>send(paths[i],{method:"GET"},false,context2,signal),context,parent);Object.defineProperty(responses,distinct[i],{value:response,enumerable:true})}if(!context.isCurrent())throw new FileOperationError("unsupported_context",400);return responses}catch(error){for(const response of Object.values(responses))response.body?.cancel().catch(()=>{});throw error}})}var files={delete(id2){return operation((context,signal)=>send(idPath(id2),{method:"DELETE"},204,context,signal))},async upload(id2){return operation(async(context,signal)=>{const file2=await send(`${idPath(id2)}/upload`,{method:"POST"},true,context,signal);if(file2.id!==id2)throw unavailable();return file2})},async create(input,options){const context=await resolveFilesContext();if(!input||typeof input!=="object"||Array.isArray(input)||Object.keys(input).some((key)=>!["file","size","path","name","storage","csv"].includes(key))||options!==undefined&&(!options||typeof options!=="object"||Array.isArray(options)||Object.keys(options).some((key)=>key!=="requestKey")))throw invalid4();const blob=input.file instanceof Blob;const array2=input.file instanceof Uint8Array;const stream=input.file instanceof ReadableStream;if(!blob&&!array2&&!stream)throw invalid4();const intrinsic=blob?input.file.size:array2?input.file.byteLength:undefined;if(intrinsic!==undefined&&input.size!==undefined&&input.size!==intrinsic)throw invalid4();let name=input.name;if(name===undefined&&blob&&"name"in input.file&&typeof input.file.name==="string"){name=typeof globalThis.File!=="undefined"&&input.file instanceof globalThis.File?input.file.name:input.file.name.split(/[\\/]/).at(-1)}const metadata=parseFileCreateMetadata({name,size:intrinsic??input.size,path:input.path,storage:input.storage,csv:input.csv,...blob&&input.file.type==="application/pdf"?{inputMediaType:"application/pdf"}:{},requestKey:options?.requestKey===undefined?routineTransport()?.key("files")??crypto.randomUUID():options.requestKey},FILE_ORIGINAL_MAX_BYTES);if(!context.local&&metadata.storage==="local")throw new FileOperationError("unsupported_context",400);const header=encodeURIComponent(JSON.stringify(metadata));if(new TextEncoder().encode(header).byteLength>METADATA_BYTES)throw invalid4();if(active>=MAX_ACTIVE)throw new FileOperationError("capacity",429,true);active++;if((typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__)&&context.localFiles&&!routineTransport()&&metadata.size>MAX_BYTES){const controller=new AbortController;const file2=input.file;let offset=0;const body=file2 instanceof ReadableStream?file2:file2 instanceof Blob?file2.stream():new ReadableStream({pull(controller2){if(offset===file2.byteLength){controller2.close();return}const end=Math.min(offset+256*1024,file2.byteLength);controller2.enqueue(file2.subarray(offset,end));offset=end}},{highWaterMark:0});try{return await send("",{method:"POST",headers:{"content-type":"application/octet-stream","x-oddington-file":header},body},true,context,controller.signal)}finally{active--}}if(metadata.size>MAX_BYTES)return multipartCreate(input,metadata,(suffix,init,kind,signal)=>kind===true?send(suffix,init,true,context,signal):send(suffix,init,"control",context,signal));return timed(async(signal)=>{try{const bytes=array2?input.file.slice():await boundedBytes(blob?input.file.stream():input.file,metadata.size);if(bytes.byteLength!==metadata.size)throw invalid4();if(signal.aborted)throw unavailable();return await send("",{method:"POST",headers:{"content-type":"application/octet-stream","x-oddington-file":header},body:bytes.buffer},true,context,signal)}finally{active--}}).catch((error)=>{throw error instanceof FileOperationError?error:unavailable()})},async enrich(input){const context=await resolveFilesContext();if(!input||typeof input!=="object"||Array.isArray(input)||Object.keys(input).some((key)=>!["file","name","content","mediaType","replace"].includes(key))||typeof input.content!=="string"&&!(input.content instanceof Uint8Array))throw invalid4();const path=`${idPath(input.file)}/enrichments`;if(typeof input.content==="string"?input.content.length>MAX_BYTES:input.content.byteLength>MAX_BYTES)throw new FileOperationError("request_too_large",413);return operation(async(context2,signal)=>{let bytes;if(typeof input.content==="string"){const buffer=new Uint8Array(Math.min(MAX_BYTES,input.content.length*3));const encoded=new TextEncoder().encodeInto(input.content,buffer);if(encoded.read!==input.content.length)throw new FileOperationError("request_too_large",413);bytes=buffer.slice(0,encoded.written)}else bytes=input.content.slice();const metadata=parseFileEnrichMetadata({name:input.name,size:bytes.byteLength,...input.mediaType===undefined?{}:{mediaType:input.mediaType},...input.replace===undefined?{}:{replace:input.replace}},MAX_BYTES);const header=encodeURIComponent(JSON.stringify(metadata));if(new TextEncoder().encode(header).byteLength>METADATA_BYTES)throw invalid4();const result2=await send(path,{method:"POST",headers:{"content-type":"application/octet-stream","x-oddington-enrichment":header},body:bytes.buffer},"enrichment",context2,signal);if(result2.name!==metadata.name)throw unavailable();return result2},context)},async get(id2){return operation((context,signal)=>send(idPath(id2),{method:"GET"},true,context,signal))},read};function validGoogleScopes(value){return Array.isArray(value)&&value.length>0&&value.length<=32&&value.every((scope)=>typeof scope==="string"&&scope.length<=256&&/^(https:\/\/www\.googleapis\.com\/auth\/[A-Za-z0-9._-]+|https:\/\/mail\.google\.com\/|openid|email|profile)$/.test(scope))&&new Set(value).size===value.length}var ROUTINE_CONNECTION_CREDENTIALS_ENV="ODDINGTON_ROUTINE_CONNECTION_CREDENTIALS";var connectionUuid=(v)=>typeof v==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(v);function parseConnectionLease(raw,now=Date.now()){const v=raw;if(!v||typeof v!=="object"||Array.isArray(v)||!connectionUuid(v.connectionId)||!connectionUuid(v.runId)||typeof v.name!=="string"||!/^[a-z0-9][a-z0-9-]{0,62}$/.test(v.name)||typeof v.accessToken!=="string"||!/^[A-Za-z0-9._~+/-]{1,8192}={0,2}$/.test(v.accessToken))throw new Error("Invalid connection credential");if(v.provider==="gmail"){if(Object.keys(v).sort().join(",")!=="accessToken,accountEmail,connectionId,expiresAt,name,provider,runId,scopes"||typeof v.accountEmail!=="string"||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.accountEmail)||!validGoogleScopes(v.scopes)||typeof v.expiresAt!=="string"||!Number.isFinite(Date.parse(v.expiresAt))||Date.parse(v.expiresAt)<=now+60000||Date.parse(v.expiresAt)>now+3600000)throw new Error("Invalid connection credential");return v}if(v.provider==="airtable"&&Object.keys(v).sort().join(",")==="accessToken,baseId,connectionId,name,provider,runExpiresAt,runId"&&typeof v.baseId==="string"&&/^app[A-Za-z0-9]+$/.test(v.baseId)&&typeof v.runExpiresAt==="string"&&Number.isFinite(Date.parse(v.runExpiresAt))&&Date.parse(v.runExpiresAt)>now+60000&&Date.parse(v.runExpiresAt)<=now+15*60000)return v;throw new Error("Invalid connection credential")}init_inbox_contract();class AirtableOperationError extends Error{effect;receipts;constructor(message,effect="unapplied",receipts=[]){super(message);this.effect=effect;this.receipts=receipts;this.name="AirtableOperationError"}}var recordId=(v)=>typeof v==="string"&&/^rec[A-Za-z0-9]+$/.test(v);var tableId=(v)=>typeof v==="string"&&/^tbl[A-Za-z0-9]+$/.test(v);function fail2(message){throw new AirtableOperationError(message)}function object2(v){if(!v||typeof v!=="object"||Array.isArray(v)||![null,Object.prototype].includes(Object.getPrototypeOf(v)))fail2("Invalid Airtable data");return v}function keys2(v,allowed,required=allowed){if(Object.keys(v).some((k)=>!allowed.includes(k))||required.some((k)=>!Object.hasOwn(v,k)))fail2("Invalid Airtable input")}function text2(v){return typeof v==="string"&&v.length>0&&v.length<=1024}function fields3(v,nonempty=false){const result2=object2(v);if(nonempty&&!Object.keys(result2).length||Object.keys(result2).some((k)=>!text2(k)))fail2("Invalid Airtable fields");try{return serializable(result2)}catch{return fail2("Invalid Airtable fields")}}function record2(v){const r=object2(v);if(!recordId(r.id)||r.createdTime!==undefined&&(typeof r.createdTime!=="string"||!Number.isFinite(Date.parse(r.createdTime))))fail2("Malformed Airtable record");return{id:r.id,...r.createdTime===undefined?{}:{createdTime:r.createdTime},fields:fields3(r.fields)}}function equal(a,b){if(a===b)return true;if(!a||!b||typeof a!=="object"||typeof b!=="object"||Array.isArray(a)!==Array.isArray(b))return false;const left=Object.keys(a),right=Object.keys(b);return left.length===right.length&&left.every((k)=>Object.hasOwn(b,k)&&equal(a[k],b[k]))}function createConnections(transport){return{airtable(name){if(typeof name!=="string"||!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name))fail2("Invalid Airtable connection name");const call=(operation2,input)=>transport(name,operation2,input);return{tables:{list:async()=>await call("tables.list",{})},records:{list:async(input)=>await call("records.list",input),get:async(input)=>await call("records.get",input),create:async(input)=>await call("records.create",input),update:async(input)=>await call("records.update",input),delete:async(input)=>await call("records.delete",input)}}}}}async function executeAirtableOperation(authority,operation2,raw,options={}){const{name,baseId,accessToken}=authority;if(!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name)||!/^app[A-Za-z0-9]+$/.test(baseId)||!/^[A-Za-z0-9._~+/-]{1,8192}={0,2}$/.test(accessToken))fail2("Airtable connection unavailable");let input;try{input=object2(serializable(raw))}catch{return fail2("Invalid Airtable input")}const mutation=["records.create","records.update","records.delete"].includes(operation2);const receipt=(ids2)=>({provider:"airtable",connection:`airtable/${name}`,baseId,table:input.table,operation:operation2.slice(8),records:ids2.map((id2)=>({id:id2}))});async function request(path2,init={},write=false){let response;try{response=await(options.fetch??fetch)(`https://api.airtable.com/v0/${path2}`,{...init,headers:{authorization:`Bearer ${accessToken}`,"content-type":"application/json"},redirect:"manual",signal:options.signal?AbortSignal.any([options.signal,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})}catch{throw new AirtableOperationError("Airtable request acknowledgment unavailable",write?"uncertain":"unapplied")}if(!response.ok){await response.body?.cancel().catch(()=>{});throw new AirtableOperationError("Airtable request rejected",write&&(response.status>=500||response.status===408||response.status<400)?"uncertain":"unapplied")}try{if(!response.headers.get("content-type")?.toLowerCase().includes("application/json"))throw new Error;const value=object2(await response.json());const safe=serializable(value);if(Object.hasOwn(value,"error")||JSON.stringify(safe).includes(accessToken))throw new Error;return value}catch{throw new AirtableOperationError("Malformed Airtable acknowledgment",write?"uncertain":"unapplied")}}if(operation2==="tables.list"){keys2(input,[]);const tables=[],seen=new Set;let offset;do{const query2=new URLSearchParams(offset?{offset}:{});const page=await request(`meta/bases/${baseId}/tables?${query2}`);if(!Array.isArray(page.tables))fail2("Malformed Airtable tables");for(const value of page.tables){const t=object2(value);if(!tableId(t.id)||!text2(t.name)||!text2(t.primaryFieldId)||!Array.isArray(t.fields)||tables.some((existing)=>existing.id===t.id))fail2("Malformed Airtable table");const metadata=t.fields.map((value2)=>{const f=object2(value2);if(typeof f.id!=="string"||!/^fld[A-Za-z0-9]+$/.test(f.id)||!text2(f.name)||!text2(f.type))fail2("Malformed Airtable field");return{id:f.id,name:f.name,type:f.type,...f.options===undefined?{}:{options:serializable(f.options)}}});if(!metadata.some((f)=>f.id===t.primaryFieldId)||new Set(metadata.map((f)=>f.id)).size!==metadata.length)fail2("Malformed Airtable fields");tables.push({id:t.id,name:t.name,primaryFieldId:t.primaryFieldId,fields:metadata})}offset=nextOffset(page.offset,seen)}while(offset);return tables}if(!text2(input.table)||input.table==="."||input.table==="..")fail2("Invalid Airtable table");if(mutation&&!tableId(input.table))fail2("Airtable writes require a stable table ID");const path=`${baseId}/${encodeURIComponent(input.table)}`;if(operation2==="records.get"){keys2(input,["table","id"]);if(!recordId(input.id))fail2("Invalid Airtable record ID");const result3=record2(await request(`${path}/${input.id}`));if(result3.id!==input.id)fail2("Malformed Airtable record");return result3}if(operation2==="records.list"){keys2(input,["table","fields"],["table"]);if(input.fields!==undefined&&(!Array.isArray(input.fields)||!input.fields.length||input.fields.some((f)=>!text2(f))||new Set(input.fields).size!==input.fields.length))fail2("Invalid Airtable field selection");const records2=[],ids2=new Set,seen=new Set;let offset;do{const query2=new URLSearchParams;for(const field of input.fields??[])query2.append("fields[]",field);if(offset)query2.set("offset",offset);const page=await request(`${path}?${query2}`);if(!Array.isArray(page.records))fail2("Malformed Airtable records");for(const value of page.records){const r=record2(value);if(ids2.has(r.id))fail2("Malformed Airtable pagination");ids2.add(r.id);records2.push(r)}offset=nextOffset(page.offset,seen)}while(offset);return records2}if(!mutation)fail2("Unsupported Airtable operation");keys2(input,["table","records"]);if(!Array.isArray(input.records)||!input.records.length||input.records.length>10)fail2("Invalid Airtable batch");const kind=operation2.slice(8),ids=new Set;const records=input.records.map((value)=>{const r=object2(value);keys2(r,kind==="create"?["fields"]:kind==="update"?["id","expected","set"]:["id","expected"]);if(kind==="create")return{fields:fields3(r.fields,true)};if(!recordId(r.id)||ids.has(r.id))fail2("Invalid Airtable batch record ID");ids.add(r.id);const set=kind==="update"?fields3(r.set,true):undefined;if(set&&Object.values(set).some((value2)=>value2===null))fail2("Airtable guard null cannot be an update value");return{id:r.id,expected:fields3(r.expected),...set?{set}:{}}});for(const r of records){if(!("id"in r))continue;const current=record2(await request(`${path}/${r.id}`));if(current.id!==r.id)fail2("Malformed Airtable record");for(const[key,value]of Object.entries(r.expected)){if(value===null?Object.hasOwn(current.fields,key):!Object.hasOwn(current.fields,key)||!equal(current.fields[key],value))fail2("Airtable reviewed values are stale")}}await options.beforeMutation?.();const query=new URLSearchParams;if(kind==="delete")for(const id2 of ids)query.append("records[]",id2);const result2=await request(`${path}${kind==="delete"?`?${query}`:""}`,{method:kind==="create"?"POST":kind==="update"?"PATCH":"DELETE",...kind==="delete"?{}:{body:JSON.stringify({records:records.map((r)=>("id"in r)?{id:r.id,fields:r.set}:r)})}},true);const acknowledged=[],returned=[];try{if(!Array.isArray(result2.records))throw new Error;for(const value of result2.records){const r=object2(value);if(!recordId(r.id)||acknowledged.includes(r.id)||kind!=="create"&&!ids.has(r.id)||kind==="delete"&&r.deleted!==true)throw new Error;acknowledged.push(r.id);if(kind!=="delete")returned.push(record2(r))}if(acknowledged.length!==records.length)throw new Error}catch{throw new AirtableOperationError("Incomplete Airtable mutation acknowledgment",acknowledged.length?"partial":"uncertain",acknowledged.length?[receipt(acknowledged)]:[])}return{receipt:receipt(acknowledged),...kind==="delete"?{}:{records:returned}}}function nextOffset(value,seen){if(value===undefined)return;if(!text2(value)||seen.has(value))fail2("Malformed Airtable pagination");seen.add(value);return value}init_inbox_contract();var MANAGED_CONNECTION_CAPABILITY_ENV="ODDINGTON_MANAGED_CONNECTION_CAPABILITY";function managedConnections(capability){const endpoint=new URL(capability.endpoint);if(endpoint.protocol!=="http:"||endpoint.hostname!=="127.0.0.1"||!endpoint.port||endpoint.pathname!=="/"||endpoint.search||endpoint.hash||endpoint.username||endpoint.password||!/^[0-9a-f-]{36}$/.test(capability.token))throw new AirtableOperationError("Airtable capability unavailable");const transport=async(name,operation2,input)=>{let safeInput;try{safeInput=serializable(input)}catch{safeInput=null}try{const response=await fetch(new URL("airtable",endpoint),{method:"POST",redirect:"error",headers:{authorization:`Bearer ${capability.token}`,"content-type":"application/json"},body:JSON.stringify({name,operation:operation2,input:safeInput}),signal:AbortSignal.timeout(125000)});const value=await response.json();if(!response.ok)throw new AirtableOperationError("Airtable operation failed; the execution retains its evidence",value.effect==="partial"||value.effect==="uncertain"?value.effect:"unapplied",value.receipts??[]);return value}catch(error){if(error instanceof AirtableOperationError)throw error;throw new AirtableOperationError("Airtable parent acknowledgment unavailable",["records.create","records.update","records.delete"].includes(operation2)?"uncertain":"unapplied")}};return createConnections(transport)}var observer;function observeLocalRoutineEffects(value){observer=value}async function reportLocalRoutineEffect(value){await observer?.(value)}init_inbox_contract();var connections=createConnections(async(name,operation2,input)=>{try{const installed2=routineTransport();if(installed2)return await installed2.request("airtable",{name,operation:operation2,input:serializable(input)});const managed=process.env[MANAGED_CONNECTION_CAPABILITY_ENV];if(managed){const client=managedConnections(JSON.parse(managed)).airtable(name);if(operation2==="tables.list")return await client.tables.list();return await client.records[operation2.slice(8)](input)}const raw=JSON.parse(process.env[ROUTINE_CONNECTION_CREDENTIALS_ENV]??"[]");if(!Array.isArray(raw))throw new Error;const leases=raw.map((value)=>parseConnectionLease(value));if(leases.some((lease2)=>lease2.provider!=="airtable")||new Set(leases.map((lease2)=>lease2.name)).size!==leases.length)throw new Error;const lease=leases.find((lease2)=>lease2.name===name);if(!lease||lease.provider!=="airtable")throw new Error;const writing=["records.create","records.update","records.delete"].includes(operation2);const captured=serializable(input);let result2;try{result2=await executeAirtableOperation(lease,operation2,captured)}catch(error){if(writing&&error instanceof AirtableOperationError)await reportLocalRoutineEffect({type:"effect",connection:`airtable/${name}`,operation:operation2,input:captured,effect:error.effect,receipts:error.receipts});throw error}if(writing)await reportLocalRoutineEffect({type:"effect",connection:`airtable/${name}`,operation:operation2,input:captured,effect:"confirmed",receipts:[result2.receipt]});return result2}catch(error){if(error instanceof AirtableOperationError)throw error;throw new AirtableOperationError("Airtable connection unavailable")}});var LOCAL_ROUTINE_VALUE_BYTES=256*1024;if((typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__)&&typeof process!=="undefined"&&process.env.ODDINGTON_LOCAL_ROUTINE_HOST==="1"){Object.defineProperty(globalThis,Symbol.for("oddington.private.local-routine-host"),{value:async()=>{const{readSync,closeSync}=await import("node:fs");const{Socket}=await import("node:net");const{pathToFileURL}=await import("node:url");const chunks=[];let size=0;for(;;){const chunk=Buffer.alloc(4096),count=readSync(4,chunk,0,chunk.length,null);if(!count)break;if((size+=count)>524288)throw new Error("Invalid routine bootstrap");chunks.push(chunk.subarray(0,count))}closeSync(4);const bootstrap=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(Buffer.concat(chunks)));const channel=new Socket({fd:3,readable:true,writable:true});let sequence=0,broken=false,settled=false;let pending;let buffer="";const fail3=()=>{broken=true;pending?.reject();pending=undefined;channel.destroy();if(!settled){if(process.platform!=="win32"){try{process.kill(-process.pid,"SIGKILL")}catch{}}process.exit(1)}};channel.on("error",fail3);channel.on("end",fail3);channel.on("close",fail3);channel.on("data",(bytes)=>{buffer+=bytes.toString("utf8");if(Buffer.byteLength(buffer)>1024)return fail3();const end=buffer.indexOf(`
|
|
74
|
+
`+setFillingColor(textColor).toString();this.acroField.setDefaultAppearance(newDa)}return widget};PDFField2.prototype.updateWidgetAppearanceWithFont=function(widget,font,_a){var{normal,rollover,down}=_a;this.updateWidgetAppearances(widget,{normal:this.createAppearanceStream(widget,normal,font),rollover:rollover&&this.createAppearanceStream(widget,rollover,font),down:down&&this.createAppearanceStream(widget,down,font)})};PDFField2.prototype.updateOnOffWidgetAppearance=function(widget,onValue,_a){var{normal,rollover,down}=_a;this.updateWidgetAppearances(widget,{normal:this.createAppearanceDict(widget,normal,onValue),rollover:rollover&&this.createAppearanceDict(widget,rollover,onValue),down:down&&this.createAppearanceDict(widget,down,onValue)})};PDFField2.prototype.updateWidgetAppearances=function(widget,_a){var{normal,rollover,down}=_a;widget.setNormalAppearance(normal);if(rollover){widget.setRolloverAppearance(rollover)}else{widget.removeRolloverAppearance()}if(down){widget.setDownAppearance(down)}else{widget.removeDownAppearance()}};PDFField2.prototype.createAppearanceStream=function(widget,appearance,font){var _a;var context2=this.acroField.dict.context;var _b=widget.getRectangle(),width=_b.width,height=_b.height;var Resources=font&&{Font:(_a={},_a[font.name]=font.ref,_a)};var stream2=context2.formXObject(appearance,{Resources,BBox:context2.obj([0,0,width,height]),Matrix:context2.obj([1,0,0,1,0,0])});var streamRef=context2.register(stream2);return streamRef};PDFField2.prototype.createImageAppearanceStream=function(widget,image,alignment2){var _a;var _b;var context2=this.acroField.dict.context;var rectangle2=widget.getRectangle();var ap=widget.getAppearanceCharacteristics();var bs=widget.getBorderStyle();var borderWidth=(_b=bs===null||bs===undefined?undefined:bs.getWidth())!==null&&_b!==undefined?_b:0;var rotation=reduceRotation(ap===null||ap===undefined?undefined:ap.getRotation());var rotate=rotateInPlace(__assign(__assign({},rectangle2),{rotation}));var adj=adjustDimsForRotation(rectangle2,rotation);var imageDims=image.scaleToFit(adj.width-borderWidth*2,adj.height-borderWidth*2);var options={x:borderWidth,y:borderWidth,width:imageDims.width,height:imageDims.height,rotate:degrees(0),xSkew:degrees(0),ySkew:degrees(0)};if(alignment2===ImageAlignment.Center){options.x+=(adj.width-borderWidth*2)/2-imageDims.width/2;options.y+=(adj.height-borderWidth*2)/2-imageDims.height/2}else if(alignment2===ImageAlignment.Right){options.x=adj.width-borderWidth-imageDims.width;options.y=adj.height-borderWidth-imageDims.height}var imageName=this.doc.context.addRandomSuffix("Image",10);var appearance=__spreadArrays(rotate,drawImage(imageName,options));var Resources={XObject:(_a={},_a[imageName]=image.ref,_a)};var stream2=context2.formXObject(appearance,{Resources,BBox:context2.obj([0,0,rectangle2.width,rectangle2.height]),Matrix:context2.obj([1,0,0,1,0,0])});return context2.register(stream2)};PDFField2.prototype.createAppearanceDict=function(widget,appearance,onValue){var context2=this.acroField.dict.context;var onStreamRef=this.createAppearanceStream(widget,appearance.on);var offStreamRef=this.createAppearanceStream(widget,appearance.off);var appearanceDict=context2.obj({});appearanceDict.set(onValue,onStreamRef);appearanceDict.set(PDFName_default.of("Off"),offStreamRef);return appearanceDict};return PDFField2}();PDFField_default=PDFField});var PDFCheckBox,PDFCheckBox_default;var init_PDFCheckBox=__esm(()=>{init_tslib_es62();init_PDFPage();init_appearances();init_colors();init_rotations();init_PDFField();init_core();init_utils2();PDFCheckBox=function(_super){__extends(PDFCheckBox2,_super);function PDFCheckBox2(acroCheckBox,ref,doc){var _this=_super.call(this,acroCheckBox,ref,doc)||this;assertIs(acroCheckBox,"acroCheckBox",[[PDFAcroCheckBox_default,"PDFAcroCheckBox"]]);_this.acroField=acroCheckBox;return _this}PDFCheckBox2.prototype.check=function(){var _a;var onValue=(_a=this.acroField.getOnValue())!==null&&_a!==undefined?_a:PDFName_default.of("Yes");this.markAsDirty();this.acroField.setValue(onValue)};PDFCheckBox2.prototype.uncheck=function(){this.markAsDirty();this.acroField.setValue(PDFName_default.of("Off"))};PDFCheckBox2.prototype.isChecked=function(){var onValue=this.acroField.getOnValue();return!!onValue&&onValue===this.acroField.getValue()};PDFCheckBox2.prototype.addToPage=function(page,options){var _a,_b,_c,_d,_e,_f;assertIs(page,"page",[[PDFPage_default,"PDFPage"]]);assertFieldAppearanceOptions(options);if(!options)options={};if(!("textColor"in options))options.textColor=rgb(0,0,0);if(!("backgroundColor"in options))options.backgroundColor=rgb(1,1,1);if(!("borderColor"in options))options.borderColor=rgb(0,0,0);if(!("borderWidth"in options))options.borderWidth=1;var widget=this.createWidget({x:(_a=options.x)!==null&&_a!==undefined?_a:0,y:(_b=options.y)!==null&&_b!==undefined?_b:0,width:(_c=options.width)!==null&&_c!==undefined?_c:50,height:(_d=options.height)!==null&&_d!==undefined?_d:50,textColor:options.textColor,backgroundColor:options.backgroundColor,borderColor:options.borderColor,borderWidth:(_e=options.borderWidth)!==null&&_e!==undefined?_e:0,rotate:(_f=options.rotate)!==null&&_f!==undefined?_f:degrees(0),hidden:options.hidden,page:page.ref});var widgetRef=this.doc.context.register(widget.dict);this.acroField.addWidget(widgetRef);widget.setAppearanceState(PDFName_default.of("Off"));this.updateWidgetAppearance(widget,PDFName_default.of("Yes"));page.node.addAnnot(widgetRef)};PDFCheckBox2.prototype.needsAppearancesUpdate=function(){var _a;var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var state=widget.getAppearanceState();var normal=(_a=widget.getAppearances())===null||_a===undefined?undefined:_a.normal;if(!(normal instanceof PDFDict_default))return true;if(state&&!normal.has(state))return true}return false};PDFCheckBox2.prototype.defaultUpdateAppearances=function(){this.updateAppearances()};PDFCheckBox2.prototype.updateAppearances=function(provider2){var _a;assertOrUndefined(provider2,"provider",[Function]);var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var onValue=(_a=widget.getOnValue())!==null&&_a!==undefined?_a:PDFName_default.of("Yes");if(!onValue)continue;this.updateWidgetAppearance(widget,onValue,provider2)}this.markAsClean()};PDFCheckBox2.prototype.updateWidgetAppearance=function(widget,onValue,provider2){var apProvider=provider2!==null&&provider2!==undefined?provider2:defaultCheckBoxAppearanceProvider;var appearances=normalizeAppearance(apProvider(this,widget));this.updateOnOffWidgetAppearance(widget,onValue,appearances)};PDFCheckBox2.of=function(acroCheckBox,ref,doc){return new PDFCheckBox2(acroCheckBox,ref,doc)};return PDFCheckBox2}(PDFField_default);PDFCheckBox_default=PDFCheckBox});var PDFDropdown,PDFDropdown_default;var init_PDFDropdown=__esm(()=>{init_tslib_es62();init_PDFPage();init_PDFFont();init_PDFField();init_appearances();init_colors();init_rotations();init_core();init_utils2();PDFDropdown=function(_super){__extends(PDFDropdown2,_super);function PDFDropdown2(acroComboBox,ref,doc){var _this=_super.call(this,acroComboBox,ref,doc)||this;assertIs(acroComboBox,"acroComboBox",[[PDFAcroComboBox_default,"PDFAcroComboBox"]]);_this.acroField=acroComboBox;return _this}PDFDropdown2.prototype.getOptions=function(){var rawOptions=this.acroField.getOptions();var options=new Array(rawOptions.length);for(var idx4=0,len3=options.length;idx4<len3;idx4++){var _a=rawOptions[idx4],display=_a.display,value=_a.value;options[idx4]=(display!==null&&display!==undefined?display:value).decodeText()}return options};PDFDropdown2.prototype.getSelected=function(){var values2=this.acroField.getValues();var selected=new Array(values2.length);for(var idx4=0,len3=values2.length;idx4<len3;idx4++){selected[idx4]=values2[idx4].decodeText()}return selected};PDFDropdown2.prototype.setOptions=function(options){assertIs(options,"options",[Array]);var optionObjects=new Array(options.length);for(var idx4=0,len3=options.length;idx4<len3;idx4++){optionObjects[idx4]={value:PDFHexString_default.fromText(options[idx4])}}this.acroField.setOptions(optionObjects)};PDFDropdown2.prototype.addOptions=function(options){assertIs(options,"options",["string",Array]);var optionsArr=Array.isArray(options)?options:[options];var existingOptions=this.acroField.getOptions();var newOptions=new Array(optionsArr.length);for(var idx4=0,len3=optionsArr.length;idx4<len3;idx4++){newOptions[idx4]={value:PDFHexString_default.fromText(optionsArr[idx4])}}this.acroField.setOptions(existingOptions.concat(newOptions))};PDFDropdown2.prototype.select=function(options,merge){if(merge===undefined){merge=false}assertIs(options,"options",["string",Array]);assertIs(merge,"merge",["boolean"]);var optionsArr=Array.isArray(options)?options:[options];var validOptions=this.getOptions();var hasCustomOption=optionsArr.find(function(option){return!validOptions.includes(option)});if(hasCustomOption)this.enableEditing();this.markAsDirty();if(optionsArr.length>1||optionsArr.length===1&&merge){this.enableMultiselect()}var values2=new Array(optionsArr.length);for(var idx4=0,len3=optionsArr.length;idx4<len3;idx4++){values2[idx4]=PDFHexString_default.fromText(optionsArr[idx4])}if(merge){var existingValues=this.acroField.getValues();this.acroField.setValues(existingValues.concat(values2))}else{this.acroField.setValues(values2)}};PDFDropdown2.prototype.clear=function(){this.markAsDirty();this.acroField.setValues([])};PDFDropdown2.prototype.setFontSize=function(fontSize){assertPositive(fontSize,"fontSize");this.acroField.setFontSize(fontSize);this.markAsDirty()};PDFDropdown2.prototype.isEditable=function(){return this.acroField.hasFlag(AcroChoiceFlags.Edit)};PDFDropdown2.prototype.enableEditing=function(){this.acroField.setFlagTo(AcroChoiceFlags.Edit,true)};PDFDropdown2.prototype.disableEditing=function(){this.acroField.setFlagTo(AcroChoiceFlags.Edit,false)};PDFDropdown2.prototype.isSorted=function(){return this.acroField.hasFlag(AcroChoiceFlags.Sort)};PDFDropdown2.prototype.enableSorting=function(){this.acroField.setFlagTo(AcroChoiceFlags.Sort,true)};PDFDropdown2.prototype.disableSorting=function(){this.acroField.setFlagTo(AcroChoiceFlags.Sort,false)};PDFDropdown2.prototype.isMultiselect=function(){return this.acroField.hasFlag(AcroChoiceFlags.MultiSelect)};PDFDropdown2.prototype.enableMultiselect=function(){this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect,true)};PDFDropdown2.prototype.disableMultiselect=function(){this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect,false)};PDFDropdown2.prototype.isSpellChecked=function(){return!this.acroField.hasFlag(AcroChoiceFlags.DoNotSpellCheck)};PDFDropdown2.prototype.enableSpellChecking=function(){this.acroField.setFlagTo(AcroChoiceFlags.DoNotSpellCheck,false)};PDFDropdown2.prototype.disableSpellChecking=function(){this.acroField.setFlagTo(AcroChoiceFlags.DoNotSpellCheck,true)};PDFDropdown2.prototype.isSelectOnClick=function(){return this.acroField.hasFlag(AcroChoiceFlags.CommitOnSelChange)};PDFDropdown2.prototype.enableSelectOnClick=function(){this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange,true)};PDFDropdown2.prototype.disableSelectOnClick=function(){this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange,false)};PDFDropdown2.prototype.addToPage=function(page,options){var _a,_b,_c,_d,_e,_f,_g;assertIs(page,"page",[[PDFPage_default,"PDFPage"]]);assertFieldAppearanceOptions(options);if(!options)options={};if(!("textColor"in options))options.textColor=rgb(0,0,0);if(!("backgroundColor"in options))options.backgroundColor=rgb(1,1,1);if(!("borderColor"in options))options.borderColor=rgb(0,0,0);if(!("borderWidth"in options))options.borderWidth=1;var widget=this.createWidget({x:(_a=options.x)!==null&&_a!==undefined?_a:0,y:(_b=options.y)!==null&&_b!==undefined?_b:0,width:(_c=options.width)!==null&&_c!==undefined?_c:200,height:(_d=options.height)!==null&&_d!==undefined?_d:50,textColor:options.textColor,backgroundColor:options.backgroundColor,borderColor:options.borderColor,borderWidth:(_e=options.borderWidth)!==null&&_e!==undefined?_e:0,rotate:(_f=options.rotate)!==null&&_f!==undefined?_f:degrees(0),hidden:options.hidden,page:page.ref});var widgetRef=this.doc.context.register(widget.dict);this.acroField.addWidget(widgetRef);var font=(_g=options.font)!==null&&_g!==undefined?_g:this.doc.getForm().getDefaultFont();this.updateWidgetAppearance(widget,font);page.node.addAnnot(widgetRef)};PDFDropdown2.prototype.needsAppearancesUpdate=function(){var _a;if(this.isDirty())return true;var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var hasAppearances=((_a=widget.getAppearances())===null||_a===undefined?undefined:_a.normal)instanceof PDFStream_default;if(!hasAppearances)return true}return false};PDFDropdown2.prototype.defaultUpdateAppearances=function(font){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);this.updateAppearances(font)};PDFDropdown2.prototype.updateAppearances=function(font,provider2){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);assertOrUndefined(provider2,"provider",[Function]);var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];this.updateWidgetAppearance(widget,font,provider2)}this.markAsClean()};PDFDropdown2.prototype.updateWidgetAppearance=function(widget,font,provider2){var apProvider=provider2!==null&&provider2!==undefined?provider2:defaultDropdownAppearanceProvider;var appearances=normalizeAppearance(apProvider(this,widget,font));this.updateWidgetAppearanceWithFont(widget,font,appearances)};PDFDropdown2.of=function(acroComboBox,ref,doc){return new PDFDropdown2(acroComboBox,ref,doc)};return PDFDropdown2}(PDFField_default);PDFDropdown_default=PDFDropdown});var PDFOptionList,PDFOptionList_default;var init_PDFOptionList=__esm(()=>{init_tslib_es62();init_PDFPage();init_PDFFont();init_PDFField();init_appearances();init_colors();init_rotations();init_core();init_utils2();PDFOptionList=function(_super){__extends(PDFOptionList2,_super);function PDFOptionList2(acroListBox,ref,doc){var _this=_super.call(this,acroListBox,ref,doc)||this;assertIs(acroListBox,"acroListBox",[[PDFAcroListBox_default,"PDFAcroListBox"]]);_this.acroField=acroListBox;return _this}PDFOptionList2.prototype.getOptions=function(){var rawOptions=this.acroField.getOptions();var options=new Array(rawOptions.length);for(var idx4=0,len3=options.length;idx4<len3;idx4++){var _a=rawOptions[idx4],display=_a.display,value=_a.value;options[idx4]=(display!==null&&display!==undefined?display:value).decodeText()}return options};PDFOptionList2.prototype.getSelected=function(){var values2=this.acroField.getValues();var selected=new Array(values2.length);for(var idx4=0,len3=values2.length;idx4<len3;idx4++){selected[idx4]=values2[idx4].decodeText()}return selected};PDFOptionList2.prototype.setOptions=function(options){assertIs(options,"options",[Array]);this.markAsDirty();var optionObjects=new Array(options.length);for(var idx4=0,len3=options.length;idx4<len3;idx4++){optionObjects[idx4]={value:PDFHexString_default.fromText(options[idx4])}}this.acroField.setOptions(optionObjects)};PDFOptionList2.prototype.addOptions=function(options){assertIs(options,"options",["string",Array]);this.markAsDirty();var optionsArr=Array.isArray(options)?options:[options];var existingOptions=this.acroField.getOptions();var newOptions=new Array(optionsArr.length);for(var idx4=0,len3=optionsArr.length;idx4<len3;idx4++){newOptions[idx4]={value:PDFHexString_default.fromText(optionsArr[idx4])}}this.acroField.setOptions(existingOptions.concat(newOptions))};PDFOptionList2.prototype.select=function(options,merge){if(merge===undefined){merge=false}assertIs(options,"options",["string",Array]);assertIs(merge,"merge",["boolean"]);var optionsArr=Array.isArray(options)?options:[options];var validOptions=this.getOptions();assertIsSubset(optionsArr,"option",validOptions);this.markAsDirty();if(optionsArr.length>1||optionsArr.length===1&&merge){this.enableMultiselect()}var values2=new Array(optionsArr.length);for(var idx4=0,len3=optionsArr.length;idx4<len3;idx4++){values2[idx4]=PDFHexString_default.fromText(optionsArr[idx4])}if(merge){var existingValues=this.acroField.getValues();this.acroField.setValues(existingValues.concat(values2))}else{this.acroField.setValues(values2)}};PDFOptionList2.prototype.clear=function(){this.markAsDirty();this.acroField.setValues([])};PDFOptionList2.prototype.setFontSize=function(fontSize){assertPositive(fontSize,"fontSize");this.acroField.setFontSize(fontSize);this.markAsDirty()};PDFOptionList2.prototype.isSorted=function(){return this.acroField.hasFlag(AcroChoiceFlags.Sort)};PDFOptionList2.prototype.enableSorting=function(){this.acroField.setFlagTo(AcroChoiceFlags.Sort,true)};PDFOptionList2.prototype.disableSorting=function(){this.acroField.setFlagTo(AcroChoiceFlags.Sort,false)};PDFOptionList2.prototype.isMultiselect=function(){return this.acroField.hasFlag(AcroChoiceFlags.MultiSelect)};PDFOptionList2.prototype.enableMultiselect=function(){this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect,true)};PDFOptionList2.prototype.disableMultiselect=function(){this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect,false)};PDFOptionList2.prototype.isSelectOnClick=function(){return this.acroField.hasFlag(AcroChoiceFlags.CommitOnSelChange)};PDFOptionList2.prototype.enableSelectOnClick=function(){this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange,true)};PDFOptionList2.prototype.disableSelectOnClick=function(){this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange,false)};PDFOptionList2.prototype.addToPage=function(page,options){var _a,_b,_c,_d,_e,_f,_g;assertIs(page,"page",[[PDFPage_default,"PDFPage"]]);assertFieldAppearanceOptions(options);if(!options)options={};if(!("textColor"in options))options.textColor=rgb(0,0,0);if(!("backgroundColor"in options))options.backgroundColor=rgb(1,1,1);if(!("borderColor"in options))options.borderColor=rgb(0,0,0);if(!("borderWidth"in options))options.borderWidth=1;var widget=this.createWidget({x:(_a=options.x)!==null&&_a!==undefined?_a:0,y:(_b=options.y)!==null&&_b!==undefined?_b:0,width:(_c=options.width)!==null&&_c!==undefined?_c:200,height:(_d=options.height)!==null&&_d!==undefined?_d:100,textColor:options.textColor,backgroundColor:options.backgroundColor,borderColor:options.borderColor,borderWidth:(_e=options.borderWidth)!==null&&_e!==undefined?_e:0,rotate:(_f=options.rotate)!==null&&_f!==undefined?_f:degrees(0),hidden:options.hidden,page:page.ref});var widgetRef=this.doc.context.register(widget.dict);this.acroField.addWidget(widgetRef);var font=(_g=options.font)!==null&&_g!==undefined?_g:this.doc.getForm().getDefaultFont();this.updateWidgetAppearance(widget,font);page.node.addAnnot(widgetRef)};PDFOptionList2.prototype.needsAppearancesUpdate=function(){var _a;if(this.isDirty())return true;var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var hasAppearances=((_a=widget.getAppearances())===null||_a===undefined?undefined:_a.normal)instanceof PDFStream_default;if(!hasAppearances)return true}return false};PDFOptionList2.prototype.defaultUpdateAppearances=function(font){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);this.updateAppearances(font)};PDFOptionList2.prototype.updateAppearances=function(font,provider2){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);assertOrUndefined(provider2,"provider",[Function]);var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];this.updateWidgetAppearance(widget,font,provider2)}this.markAsClean()};PDFOptionList2.prototype.updateWidgetAppearance=function(widget,font,provider2){var apProvider=provider2!==null&&provider2!==undefined?provider2:defaultOptionListAppearanceProvider;var appearances=normalizeAppearance(apProvider(this,widget,font));this.updateWidgetAppearanceWithFont(widget,font,appearances)};PDFOptionList2.of=function(acroListBox,ref,doc){return new PDFOptionList2(acroListBox,ref,doc)};return PDFOptionList2}(PDFField_default);PDFOptionList_default=PDFOptionList});var PDFRadioGroup,PDFRadioGroup_default;var init_PDFRadioGroup=__esm(()=>{init_tslib_es62();init_PDFPage();init_PDFField();init_appearances();init_colors();init_rotations();init_core();init_utils2();PDFRadioGroup=function(_super){__extends(PDFRadioGroup2,_super);function PDFRadioGroup2(acroRadioButton,ref,doc){var _this=_super.call(this,acroRadioButton,ref,doc)||this;assertIs(acroRadioButton,"acroRadioButton",[[PDFAcroRadioButton_default,"PDFAcroRadioButton"]]);_this.acroField=acroRadioButton;return _this}PDFRadioGroup2.prototype.getOptions=function(){var exportValues=this.acroField.getExportValues();if(exportValues){var exportOptions=new Array(exportValues.length);for(var idx4=0,len3=exportValues.length;idx4<len3;idx4++){exportOptions[idx4]=exportValues[idx4].decodeText()}return exportOptions}var onValues=this.acroField.getOnValues();var onOptions=new Array(onValues.length);for(var idx4=0,len3=onOptions.length;idx4<len3;idx4++){onOptions[idx4]=onValues[idx4].decodeText()}return onOptions};PDFRadioGroup2.prototype.getSelected=function(){var value=this.acroField.getValue();if(value===PDFName_default.of("Off"))return;var exportValues=this.acroField.getExportValues();if(exportValues){var onValues=this.acroField.getOnValues();for(var idx4=0,len3=onValues.length;idx4<len3;idx4++){if(onValues[idx4]===value)return exportValues[idx4].decodeText()}}return value.decodeText()};PDFRadioGroup2.prototype.select=function(option){assertIs(option,"option",["string"]);var validOptions=this.getOptions();assertIsOneOf(option,"option",validOptions);this.markAsDirty();var onValues=this.acroField.getOnValues();var exportValues=this.acroField.getExportValues();if(exportValues){for(var idx4=0,len3=exportValues.length;idx4<len3;idx4++){if(exportValues[idx4].decodeText()===option){this.acroField.setValue(onValues[idx4])}}}else{for(var idx4=0,len3=onValues.length;idx4<len3;idx4++){var value=onValues[idx4];if(value.decodeText()===option)this.acroField.setValue(value)}}};PDFRadioGroup2.prototype.clear=function(){this.markAsDirty();this.acroField.setValue(PDFName_default.of("Off"))};PDFRadioGroup2.prototype.isOffToggleable=function(){return!this.acroField.hasFlag(AcroButtonFlags.NoToggleToOff)};PDFRadioGroup2.prototype.enableOffToggling=function(){this.acroField.setFlagTo(AcroButtonFlags.NoToggleToOff,false)};PDFRadioGroup2.prototype.disableOffToggling=function(){this.acroField.setFlagTo(AcroButtonFlags.NoToggleToOff,true)};PDFRadioGroup2.prototype.isMutuallyExclusive=function(){return!this.acroField.hasFlag(AcroButtonFlags.RadiosInUnison)};PDFRadioGroup2.prototype.enableMutualExclusion=function(){this.acroField.setFlagTo(AcroButtonFlags.RadiosInUnison,false)};PDFRadioGroup2.prototype.disableMutualExclusion=function(){this.acroField.setFlagTo(AcroButtonFlags.RadiosInUnison,true)};PDFRadioGroup2.prototype.addOptionToPage=function(option,page,options){var _a,_b,_c,_d,_e,_f,_g,_h,_j;assertIs(option,"option",["string"]);assertIs(page,"page",[[PDFPage_default,"PDFPage"]]);assertFieldAppearanceOptions(options);var widget=this.createWidget({x:(_a=options===null||options===undefined?undefined:options.x)!==null&&_a!==undefined?_a:0,y:(_b=options===null||options===undefined?undefined:options.y)!==null&&_b!==undefined?_b:0,width:(_c=options===null||options===undefined?undefined:options.width)!==null&&_c!==undefined?_c:50,height:(_d=options===null||options===undefined?undefined:options.height)!==null&&_d!==undefined?_d:50,textColor:(_e=options===null||options===undefined?undefined:options.textColor)!==null&&_e!==undefined?_e:rgb(0,0,0),backgroundColor:(_f=options===null||options===undefined?undefined:options.backgroundColor)!==null&&_f!==undefined?_f:rgb(1,1,1),borderColor:(_g=options===null||options===undefined?undefined:options.borderColor)!==null&&_g!==undefined?_g:rgb(0,0,0),borderWidth:(_h=options===null||options===undefined?undefined:options.borderWidth)!==null&&_h!==undefined?_h:1,rotate:(_j=options===null||options===undefined?undefined:options.rotate)!==null&&_j!==undefined?_j:degrees(0),hidden:options===null||options===undefined?undefined:options.hidden,page:page.ref});var widgetRef=this.doc.context.register(widget.dict);var apStateValue=this.acroField.addWidgetWithOpt(widgetRef,PDFHexString_default.fromText(option),!this.isMutuallyExclusive());widget.setAppearanceState(PDFName_default.of("Off"));this.updateWidgetAppearance(widget,apStateValue);page.node.addAnnot(widgetRef)};PDFRadioGroup2.prototype.needsAppearancesUpdate=function(){var _a;var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var state=widget.getAppearanceState();var normal=(_a=widget.getAppearances())===null||_a===undefined?undefined:_a.normal;if(!(normal instanceof PDFDict_default))return true;if(state&&!normal.has(state))return true}return false};PDFRadioGroup2.prototype.defaultUpdateAppearances=function(){this.updateAppearances()};PDFRadioGroup2.prototype.updateAppearances=function(provider2){assertOrUndefined(provider2,"provider",[Function]);var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var onValue=widget.getOnValue();if(!onValue)continue;this.updateWidgetAppearance(widget,onValue,provider2)}};PDFRadioGroup2.prototype.updateWidgetAppearance=function(widget,onValue,provider2){var apProvider=provider2!==null&&provider2!==undefined?provider2:defaultRadioGroupAppearanceProvider;var appearances=normalizeAppearance(apProvider(this,widget));this.updateOnOffWidgetAppearance(widget,onValue,appearances)};PDFRadioGroup2.of=function(acroRadioButton,ref,doc){return new PDFRadioGroup2(acroRadioButton,ref,doc)};return PDFRadioGroup2}(PDFField_default);PDFRadioGroup_default=PDFRadioGroup});var PDFSignature,PDFSignature_default;var init_PDFSignature=__esm(()=>{init_tslib_es62();init_PDFField();init_core();init_utils2();PDFSignature=function(_super){__extends(PDFSignature2,_super);function PDFSignature2(acroSignature,ref,doc){var _this=_super.call(this,acroSignature,ref,doc)||this;assertIs(acroSignature,"acroSignature",[[PDFAcroSignature_default,"PDFAcroSignature"]]);_this.acroField=acroSignature;return _this}PDFSignature2.prototype.needsAppearancesUpdate=function(){return false};PDFSignature2.of=function(acroSignature,ref,doc){return new PDFSignature2(acroSignature,ref,doc)};return PDFSignature2}(PDFField_default);PDFSignature_default=PDFSignature});var PDFTextField,PDFTextField_default;var init_PDFTextField=__esm(()=>{init_tslib_es62();init_PDFPage();init_PDFFont();init_PDFField();init_appearances();init_colors();init_rotations();init_errors3();init_alignment2();init_alignment();init_core();init_utils2();PDFTextField=function(_super){__extends(PDFTextField2,_super);function PDFTextField2(acroText,ref,doc){var _this=_super.call(this,acroText,ref,doc)||this;assertIs(acroText,"acroText",[[PDFAcroText_default,"PDFAcroText"]]);_this.acroField=acroText;return _this}PDFTextField2.prototype.getText=function(){var value=this.acroField.getValue();if(!value&&this.isRichFormatted()){throw new RichTextFieldReadError(this.getName())}return value===null||value===undefined?undefined:value.decodeText()};PDFTextField2.prototype.setText=function(text4){assertOrUndefined(text4,"text",["string"]);var maxLength=this.getMaxLength();if(maxLength!==undefined&&text4&&text4.length>maxLength){throw new ExceededMaxLengthError(text4.length,maxLength,this.getName())}this.markAsDirty();this.disableRichFormatting();if(text4){this.acroField.setValue(PDFHexString_default.fromText(text4))}else{this.acroField.removeValue()}};PDFTextField2.prototype.getAlignment=function(){var quadding=this.acroField.getQuadding();return quadding===0?TextAlignment.Left:quadding===1?TextAlignment.Center:quadding===2?TextAlignment.Right:TextAlignment.Left};PDFTextField2.prototype.setAlignment=function(alignment2){assertIsOneOf(alignment2,"alignment",TextAlignment);this.markAsDirty();this.acroField.setQuadding(alignment2)};PDFTextField2.prototype.getMaxLength=function(){return this.acroField.getMaxLength()};PDFTextField2.prototype.setMaxLength=function(maxLength){assertRangeOrUndefined(maxLength,"maxLength",0,Number.MAX_SAFE_INTEGER);this.markAsDirty();if(maxLength===undefined){this.acroField.removeMaxLength()}else{var text4=this.getText();if(text4&&text4.length>maxLength){throw new InvalidMaxLengthError(text4.length,maxLength,this.getName())}this.acroField.setMaxLength(maxLength)}};PDFTextField2.prototype.removeMaxLength=function(){this.markAsDirty();this.acroField.removeMaxLength()};PDFTextField2.prototype.setImage=function(image){var fieldAlignment=this.getAlignment();var alignment2=fieldAlignment===TextAlignment.Center?ImageAlignment.Center:fieldAlignment===TextAlignment.Right?ImageAlignment.Right:ImageAlignment.Left;var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var streamRef=this.createImageAppearanceStream(widget,image,alignment2);this.updateWidgetAppearances(widget,{normal:streamRef})}this.markAsClean()};PDFTextField2.prototype.setFontSize=function(fontSize){assertPositive(fontSize,"fontSize");this.acroField.setFontSize(fontSize);this.markAsDirty()};PDFTextField2.prototype.isMultiline=function(){return this.acroField.hasFlag(AcroTextFlags.Multiline)};PDFTextField2.prototype.enableMultiline=function(){this.markAsDirty();this.acroField.setFlagTo(AcroTextFlags.Multiline,true)};PDFTextField2.prototype.disableMultiline=function(){this.markAsDirty();this.acroField.setFlagTo(AcroTextFlags.Multiline,false)};PDFTextField2.prototype.isPassword=function(){return this.acroField.hasFlag(AcroTextFlags.Password)};PDFTextField2.prototype.enablePassword=function(){this.acroField.setFlagTo(AcroTextFlags.Password,true)};PDFTextField2.prototype.disablePassword=function(){this.acroField.setFlagTo(AcroTextFlags.Password,false)};PDFTextField2.prototype.isFileSelector=function(){return this.acroField.hasFlag(AcroTextFlags.FileSelect)};PDFTextField2.prototype.enableFileSelection=function(){this.acroField.setFlagTo(AcroTextFlags.FileSelect,true)};PDFTextField2.prototype.disableFileSelection=function(){this.acroField.setFlagTo(AcroTextFlags.FileSelect,false)};PDFTextField2.prototype.isSpellChecked=function(){return!this.acroField.hasFlag(AcroTextFlags.DoNotSpellCheck)};PDFTextField2.prototype.enableSpellChecking=function(){this.acroField.setFlagTo(AcroTextFlags.DoNotSpellCheck,false)};PDFTextField2.prototype.disableSpellChecking=function(){this.acroField.setFlagTo(AcroTextFlags.DoNotSpellCheck,true)};PDFTextField2.prototype.isScrollable=function(){return!this.acroField.hasFlag(AcroTextFlags.DoNotScroll)};PDFTextField2.prototype.enableScrolling=function(){this.acroField.setFlagTo(AcroTextFlags.DoNotScroll,false)};PDFTextField2.prototype.disableScrolling=function(){this.acroField.setFlagTo(AcroTextFlags.DoNotScroll,true)};PDFTextField2.prototype.isCombed=function(){return this.acroField.hasFlag(AcroTextFlags.Comb)&&!this.isMultiline()&&!this.isPassword()&&!this.isFileSelector()&&this.getMaxLength()!==undefined};PDFTextField2.prototype.enableCombing=function(){if(this.getMaxLength()===undefined){var msg="PDFTextFields must have a max length in order to be combed";console.warn(msg)}this.markAsDirty();this.disableMultiline();this.disablePassword();this.disableFileSelection();this.acroField.setFlagTo(AcroTextFlags.Comb,true)};PDFTextField2.prototype.disableCombing=function(){this.markAsDirty();this.acroField.setFlagTo(AcroTextFlags.Comb,false)};PDFTextField2.prototype.isRichFormatted=function(){return this.acroField.hasFlag(AcroTextFlags.RichText)};PDFTextField2.prototype.enableRichFormatting=function(){this.acroField.setFlagTo(AcroTextFlags.RichText,true)};PDFTextField2.prototype.disableRichFormatting=function(){this.acroField.setFlagTo(AcroTextFlags.RichText,false)};PDFTextField2.prototype.addToPage=function(page,options){var _a,_b,_c,_d,_e,_f,_g;assertIs(page,"page",[[PDFPage_default,"PDFPage"]]);assertFieldAppearanceOptions(options);if(!options)options={};if(!("textColor"in options))options.textColor=rgb(0,0,0);if(!("backgroundColor"in options))options.backgroundColor=rgb(1,1,1);if(!("borderColor"in options))options.borderColor=rgb(0,0,0);if(!("borderWidth"in options))options.borderWidth=1;var widget=this.createWidget({x:(_a=options.x)!==null&&_a!==undefined?_a:0,y:(_b=options.y)!==null&&_b!==undefined?_b:0,width:(_c=options.width)!==null&&_c!==undefined?_c:200,height:(_d=options.height)!==null&&_d!==undefined?_d:50,textColor:options.textColor,backgroundColor:options.backgroundColor,borderColor:options.borderColor,borderWidth:(_e=options.borderWidth)!==null&&_e!==undefined?_e:0,rotate:(_f=options.rotate)!==null&&_f!==undefined?_f:degrees(0),hidden:options.hidden,page:page.ref});var widgetRef=this.doc.context.register(widget.dict);this.acroField.addWidget(widgetRef);var font=(_g=options.font)!==null&&_g!==undefined?_g:this.doc.getForm().getDefaultFont();this.updateWidgetAppearance(widget,font);page.node.addAnnot(widgetRef)};PDFTextField2.prototype.needsAppearancesUpdate=function(){var _a;if(this.isDirty())return true;var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var hasAppearances=((_a=widget.getAppearances())===null||_a===undefined?undefined:_a.normal)instanceof PDFStream_default;if(!hasAppearances)return true}return false};PDFTextField2.prototype.defaultUpdateAppearances=function(font){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);this.updateAppearances(font)};PDFTextField2.prototype.updateAppearances=function(font,provider2){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);assertOrUndefined(provider2,"provider",[Function]);var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];this.updateWidgetAppearance(widget,font,provider2)}this.markAsClean()};PDFTextField2.prototype.updateWidgetAppearance=function(widget,font,provider2){var apProvider=provider2!==null&&provider2!==undefined?provider2:defaultTextFieldAppearanceProvider;var appearances=normalizeAppearance(apProvider(this,widget,font));this.updateWidgetAppearanceWithFont(widget,font,appearances)};PDFTextField2.of=function(acroText,ref,doc){return new PDFTextField2(acroText,ref,doc)};return PDFTextField2}(PDFField_default);PDFTextField_default=PDFTextField});var StandardFonts;var init_StandardFonts=__esm(()=>{(function(StandardFonts2){StandardFonts2["Courier"]="Courier";StandardFonts2["CourierBold"]="Courier-Bold";StandardFonts2["CourierOblique"]="Courier-Oblique";StandardFonts2["CourierBoldOblique"]="Courier-BoldOblique";StandardFonts2["Helvetica"]="Helvetica";StandardFonts2["HelveticaBold"]="Helvetica-Bold";StandardFonts2["HelveticaOblique"]="Helvetica-Oblique";StandardFonts2["HelveticaBoldOblique"]="Helvetica-BoldOblique";StandardFonts2["TimesRoman"]="Times-Roman";StandardFonts2["TimesRomanBold"]="Times-Bold";StandardFonts2["TimesRomanItalic"]="Times-Italic";StandardFonts2["TimesRomanBoldItalic"]="Times-BoldItalic";StandardFonts2["Symbol"]="Symbol";StandardFonts2["ZapfDingbats"]="ZapfDingbats"})(StandardFonts||(StandardFonts={}))});var PDFForm,PDFForm_default,convertToPDFField=function(field,ref,doc){if(field instanceof PDFAcroPushButton_default)return PDFButton_default.of(field,ref,doc);if(field instanceof PDFAcroCheckBox_default)return PDFCheckBox_default.of(field,ref,doc);if(field instanceof PDFAcroComboBox_default)return PDFDropdown_default.of(field,ref,doc);if(field instanceof PDFAcroListBox_default)return PDFOptionList_default.of(field,ref,doc);if(field instanceof PDFAcroText_default)return PDFTextField_default.of(field,ref,doc);if(field instanceof PDFAcroRadioButton_default){return PDFRadioGroup_default.of(field,ref,doc)}if(field instanceof PDFAcroSignature_default){return PDFSignature_default.of(field,ref,doc)}return},splitFieldName=function(fullyQualifiedName){if(fullyQualifiedName.length===0){throw new Error("PDF field names must not be empty strings")}var parts=fullyQualifiedName.split(".");for(var idx4=0,len3=parts.length;idx4<len3;idx4++){if(parts[idx4]===""){throw new Error('Periods in PDF field names must be separated by at least one character: "'+fullyQualifiedName+'"')}}if(parts.length===1)return{nonTerminal:[],terminal:parts[0]};return{nonTerminal:parts.slice(0,parts.length-1),terminal:parts[parts.length-1]}},addFieldToParent=function(_a,_b,partialName){var parent=_a[0],parentRef=_a[1];var field=_b[0],fieldRef=_b[1];var entries=parent.normalizedEntries();var fields6=createPDFAcroFields("Kids"in entries?entries.Kids:entries.Fields);for(var idx4=0,len3=fields6.length;idx4<len3;idx4++){if(fields6[idx4][0].getPartialName()===partialName){throw new FieldAlreadyExistsError(partialName)}}parent.addField(fieldRef);field.setParent(parentRef)};var init_PDFForm=__esm(()=>{init_tslib_es62();init_PDFDocument();init_PDFButton();init_PDFCheckBox();init_PDFDropdown();init_PDFOptionList();init_PDFRadioGroup();init_PDFSignature();init_PDFTextField();init_errors3();init_PDFFont();init_StandardFonts();init_operations();init_operators();init_core();init_utils2();PDFForm=function(){function PDFForm2(acroForm,doc){var _this=this;this.embedDefaultFont=function(){return _this.doc.embedStandardFont(StandardFonts.Helvetica)};assertIs(acroForm,"acroForm",[[PDFAcroForm_default,"PDFAcroForm"]]);assertIs(doc,"doc",[[PDFDocument_default,"PDFDocument"]]);this.acroForm=acroForm;this.doc=doc;this.dirtyFields=new Set;this.defaultFontCache=Cache_default.populatedBy(this.embedDefaultFont)}PDFForm2.prototype.hasXFA=function(){return this.acroForm.dict.has(PDFName_default.of("XFA"))};PDFForm2.prototype.deleteXFA=function(){this.acroForm.dict.delete(PDFName_default.of("XFA"))};PDFForm2.prototype.getFields=function(){var allFields=this.acroForm.getAllFields();var fields6=[];for(var idx4=0,len3=allFields.length;idx4<len3;idx4++){var _a=allFields[idx4],acroField=_a[0],ref=_a[1];var field=convertToPDFField(acroField,ref,this.doc);if(field)fields6.push(field)}return fields6};PDFForm2.prototype.getFieldMaybe=function(name){assertIs(name,"name",["string"]);var fields6=this.getFields();for(var idx4=0,len3=fields6.length;idx4<len3;idx4++){var field=fields6[idx4];if(field.getName()===name)return field}return};PDFForm2.prototype.getField=function(name){assertIs(name,"name",["string"]);var field=this.getFieldMaybe(name);if(field)return field;throw new NoSuchFieldError(name)};PDFForm2.prototype.getButton=function(name){assertIs(name,"name",["string"]);var field=this.getField(name);if(field instanceof PDFButton_default)return field;throw new UnexpectedFieldTypeError(name,PDFButton_default,field)};PDFForm2.prototype.getCheckBox=function(name){assertIs(name,"name",["string"]);var field=this.getField(name);if(field instanceof PDFCheckBox_default)return field;throw new UnexpectedFieldTypeError(name,PDFCheckBox_default,field)};PDFForm2.prototype.getDropdown=function(name){assertIs(name,"name",["string"]);var field=this.getField(name);if(field instanceof PDFDropdown_default)return field;throw new UnexpectedFieldTypeError(name,PDFDropdown_default,field)};PDFForm2.prototype.getOptionList=function(name){assertIs(name,"name",["string"]);var field=this.getField(name);if(field instanceof PDFOptionList_default)return field;throw new UnexpectedFieldTypeError(name,PDFOptionList_default,field)};PDFForm2.prototype.getRadioGroup=function(name){assertIs(name,"name",["string"]);var field=this.getField(name);if(field instanceof PDFRadioGroup_default)return field;throw new UnexpectedFieldTypeError(name,PDFRadioGroup_default,field)};PDFForm2.prototype.getSignature=function(name){assertIs(name,"name",["string"]);var field=this.getField(name);if(field instanceof PDFSignature_default)return field;throw new UnexpectedFieldTypeError(name,PDFSignature_default,field)};PDFForm2.prototype.getTextField=function(name){assertIs(name,"name",["string"]);var field=this.getField(name);if(field instanceof PDFTextField_default)return field;throw new UnexpectedFieldTypeError(name,PDFTextField_default,field)};PDFForm2.prototype.createButton=function(name){assertIs(name,"name",["string"]);var nameParts=splitFieldName(name);var parent=this.findOrCreateNonTerminals(nameParts.nonTerminal);var button=PDFAcroPushButton_default.create(this.doc.context);button.setPartialName(nameParts.terminal);addFieldToParent(parent,[button,button.ref],nameParts.terminal);return PDFButton_default.of(button,button.ref,this.doc)};PDFForm2.prototype.createCheckBox=function(name){assertIs(name,"name",["string"]);var nameParts=splitFieldName(name);var parent=this.findOrCreateNonTerminals(nameParts.nonTerminal);var checkBox=PDFAcroCheckBox_default.create(this.doc.context);checkBox.setPartialName(nameParts.terminal);addFieldToParent(parent,[checkBox,checkBox.ref],nameParts.terminal);return PDFCheckBox_default.of(checkBox,checkBox.ref,this.doc)};PDFForm2.prototype.createDropdown=function(name){assertIs(name,"name",["string"]);var nameParts=splitFieldName(name);var parent=this.findOrCreateNonTerminals(nameParts.nonTerminal);var comboBox=PDFAcroComboBox_default.create(this.doc.context);comboBox.setPartialName(nameParts.terminal);addFieldToParent(parent,[comboBox,comboBox.ref],nameParts.terminal);return PDFDropdown_default.of(comboBox,comboBox.ref,this.doc)};PDFForm2.prototype.createOptionList=function(name){assertIs(name,"name",["string"]);var nameParts=splitFieldName(name);var parent=this.findOrCreateNonTerminals(nameParts.nonTerminal);var listBox=PDFAcroListBox_default.create(this.doc.context);listBox.setPartialName(nameParts.terminal);addFieldToParent(parent,[listBox,listBox.ref],nameParts.terminal);return PDFOptionList_default.of(listBox,listBox.ref,this.doc)};PDFForm2.prototype.createRadioGroup=function(name){assertIs(name,"name",["string"]);var nameParts=splitFieldName(name);var parent=this.findOrCreateNonTerminals(nameParts.nonTerminal);var radioButton=PDFAcroRadioButton_default.create(this.doc.context);radioButton.setPartialName(nameParts.terminal);addFieldToParent(parent,[radioButton,radioButton.ref],nameParts.terminal);return PDFRadioGroup_default.of(radioButton,radioButton.ref,this.doc)};PDFForm2.prototype.createTextField=function(name){assertIs(name,"name",["string"]);var nameParts=splitFieldName(name);var parent=this.findOrCreateNonTerminals(nameParts.nonTerminal);var text4=PDFAcroText_default.create(this.doc.context);text4.setPartialName(nameParts.terminal);addFieldToParent(parent,[text4,text4.ref],nameParts.terminal);return PDFTextField_default.of(text4,text4.ref,this.doc)};PDFForm2.prototype.flatten=function(options){if(options===undefined){options={updateFieldAppearances:true}}if(options.updateFieldAppearances){this.updateFieldAppearances()}var fields6=this.getFields();for(var i3=0,lenFields=fields6.length;i3<lenFields;i3++){var field=fields6[i3];var widgets=field.acroField.getWidgets();for(var j=0,lenWidgets=widgets.length;j<lenWidgets;j++){var widget=widgets[j];var page=this.findWidgetPage(widget);var widgetRef=this.findWidgetAppearanceRef(field,widget);var xObjectKey=page.node.newXObject("FlatWidget",widgetRef);var rectangle2=widget.getRectangle();var operators=__spreadArrays([pushGraphicsState(),translate(rectangle2.x,rectangle2.y)],rotateInPlace(__assign(__assign({},rectangle2),{rotation:0})),[drawObject(xObjectKey),popGraphicsState()]).filter(Boolean);page.pushOperators.apply(page,operators)}this.removeField(field)}};PDFForm2.prototype.removeField=function(field){var widgets=field.acroField.getWidgets();var pages=new Set;for(var i3=0,len3=widgets.length;i3<len3;i3++){var widget=widgets[i3];var widgetRef=this.findWidgetAppearanceRef(field,widget);var page=this.findWidgetPage(widget);pages.add(page);page.node.removeAnnot(widgetRef)}pages.forEach(function(page2){return page2.node.removeAnnot(field.ref)});this.acroForm.removeField(field.acroField);var fieldKids=field.acroField.normalizedEntries().Kids;var kidsCount=fieldKids.size();for(var childIndex=0;childIndex<kidsCount;childIndex++){var child=fieldKids.get(childIndex);if(child instanceof PDFRef_default){this.doc.context.delete(child)}}this.doc.context.delete(field.ref)};PDFForm2.prototype.updateFieldAppearances=function(font){assertOrUndefined(font,"font",[[PDFFont_default,"PDFFont"]]);font=font!==null&&font!==undefined?font:this.getDefaultFont();var fields6=this.getFields();for(var idx4=0,len3=fields6.length;idx4<len3;idx4++){var field=fields6[idx4];if(field.needsAppearancesUpdate()){field.defaultUpdateAppearances(font)}}};PDFForm2.prototype.markFieldAsDirty=function(fieldRef){assertOrUndefined(fieldRef,"fieldRef",[[PDFRef_default,"PDFRef"]]);this.dirtyFields.add(fieldRef)};PDFForm2.prototype.markFieldAsClean=function(fieldRef){assertOrUndefined(fieldRef,"fieldRef",[[PDFRef_default,"PDFRef"]]);this.dirtyFields.delete(fieldRef)};PDFForm2.prototype.fieldIsDirty=function(fieldRef){assertOrUndefined(fieldRef,"fieldRef",[[PDFRef_default,"PDFRef"]]);return this.dirtyFields.has(fieldRef)};PDFForm2.prototype.getDefaultFont=function(){return this.defaultFontCache.access()};PDFForm2.prototype.findWidgetPage=function(widget){var pageRef=widget.P();var page=this.doc.getPages().find(function(x){return x.ref===pageRef});if(page===undefined){var widgetRef=this.doc.context.getObjectRef(widget.dict);if(widgetRef===undefined){throw new Error("Could not find PDFRef for PDFObject")}page=this.doc.findPageForAnnotationRef(widgetRef);if(page===undefined){throw new Error("Could not find page for PDFRef "+widgetRef)}}return page};PDFForm2.prototype.findWidgetAppearanceRef=function(field,widget){var _a;var refOrDict=widget.getNormalAppearance();if(refOrDict instanceof PDFDict_default&&(field instanceof PDFCheckBox_default||field instanceof PDFRadioGroup_default)){var value=field.acroField.getValue();var ref=(_a=refOrDict.get(value))!==null&&_a!==undefined?_a:refOrDict.get(PDFName_default.of("Off"));if(ref instanceof PDFRef_default){refOrDict=ref}}if(!(refOrDict instanceof PDFRef_default)){var name_1=field.getName();throw new Error("Failed to extract appearance ref for: "+name_1)}return refOrDict};PDFForm2.prototype.findOrCreateNonTerminals=function(partialNames){var nonTerminal=[this.acroForm];for(var idx4=0,len3=partialNames.length;idx4<len3;idx4++){var namePart=partialNames[idx4];if(!namePart)throw new InvalidFieldNamePartError(namePart);var parent_1=nonTerminal[0],parentRef=nonTerminal[1];var res=this.findNonTerminal(namePart,parent_1);if(res){nonTerminal=res}else{var node=PDFAcroNonTerminal_default.create(this.doc.context);node.setPartialName(namePart);node.setParent(parentRef);var nodeRef=this.doc.context.register(node.dict);parent_1.addField(nodeRef);nonTerminal=[node,nodeRef]}}return nonTerminal};PDFForm2.prototype.findNonTerminal=function(partialName,parent){var fields6=parent instanceof PDFAcroForm_default?this.acroForm.getFields():createPDFAcroFields(parent.Kids());for(var idx4=0,len3=fields6.length;idx4<len3;idx4++){var _a=fields6[idx4],field=_a[0],ref=_a[1];if(field.getPartialName()===partialName){if(field instanceof PDFAcroNonTerminal_default)return[field,ref];throw new FieldAlreadyExistsError(partialName)}}return};PDFForm2.of=function(acroForm,doc){return new PDFForm2(acroForm,doc)};return PDFForm2}();PDFForm_default=PDFForm});var PageSizes;var init_sizes=__esm(()=>{PageSizes={"4A0":[4767.87,6740.79],"2A0":[3370.39,4767.87],A0:[2383.94,3370.39],A1:[1683.78,2383.94],A2:[1190.55,1683.78],A3:[841.89,1190.55],A4:[595.28,841.89],A5:[419.53,595.28],A6:[297.64,419.53],A7:[209.76,297.64],A8:[147.4,209.76],A9:[104.88,147.4],A10:[73.7,104.88],B0:[2834.65,4008.19],B1:[2004.09,2834.65],B2:[1417.32,2004.09],B3:[1000.63,1417.32],B4:[708.66,1000.63],B5:[498.9,708.66],B6:[354.33,498.9],B7:[249.45,354.33],B8:[175.75,249.45],B9:[124.72,175.75],B10:[87.87,124.72],C0:[2599.37,3676.54],C1:[1836.85,2599.37],C2:[1298.27,1836.85],C3:[918.43,1298.27],C4:[649.13,918.43],C5:[459.21,649.13],C6:[323.15,459.21],C7:[229.61,323.15],C8:[161.57,229.61],C9:[113.39,161.57],C10:[79.37,113.39],RA0:[2437.8,3458.27],RA1:[1729.13,2437.8],RA2:[1218.9,1729.13],RA3:[864.57,1218.9],RA4:[609.45,864.57],SRA0:[2551.18,3628.35],SRA1:[1814.17,2551.18],SRA2:[1275.59,1814.17],SRA3:[907.09,1275.59],SRA4:[637.8,907.09],Executive:[521.86,756],Folio:[612,936],Legal:[612,1008],Letter:[612,792],Tabloid:[792,1224]}});var ParseSpeeds;var init_PDFDocumentOptions=__esm(()=>{(function(ParseSpeeds2){ParseSpeeds2[ParseSpeeds2["Fastest"]=Infinity]="Fastest";ParseSpeeds2[ParseSpeeds2["Fast"]=1500]="Fast";ParseSpeeds2[ParseSpeeds2["Medium"]=500]="Medium";ParseSpeeds2[ParseSpeeds2["Slow"]=100]="Slow"})(ParseSpeeds||(ParseSpeeds={}))});var PDFEmbeddedFile,PDFEmbeddedFile_default;var init_PDFEmbeddedFile=__esm(()=>{init_tslib_es62();init_core();PDFEmbeddedFile=function(){function PDFEmbeddedFile2(ref,doc,embedder){this.alreadyEmbedded=false;this.ref=ref;this.doc=doc;this.embedder=embedder}PDFEmbeddedFile2.prototype.embed=function(){return __awaiter(this,undefined,undefined,function(){var ref,Names,EmbeddedFiles,EFNames,AF;return __generator(this,function(_a){switch(_a.label){case 0:if(!!this.alreadyEmbedded)return[3,2];return[4,this.embedder.embedIntoContext(this.doc.context,this.ref)];case 1:ref=_a.sent();if(!this.doc.catalog.has(PDFName_default.of("Names"))){this.doc.catalog.set(PDFName_default.of("Names"),this.doc.context.obj({}))}Names=this.doc.catalog.lookup(PDFName_default.of("Names"),PDFDict_default);if(!Names.has(PDFName_default.of("EmbeddedFiles"))){Names.set(PDFName_default.of("EmbeddedFiles"),this.doc.context.obj({}))}EmbeddedFiles=Names.lookup(PDFName_default.of("EmbeddedFiles"),PDFDict_default);if(!EmbeddedFiles.has(PDFName_default.of("Names"))){EmbeddedFiles.set(PDFName_default.of("Names"),this.doc.context.obj([]))}EFNames=EmbeddedFiles.lookup(PDFName_default.of("Names"),PDFArray_default);EFNames.push(PDFHexString_default.fromText(this.embedder.fileName));EFNames.push(ref);if(!this.doc.catalog.has(PDFName_default.of("AF"))){this.doc.catalog.set(PDFName_default.of("AF"),this.doc.context.obj([]))}AF=this.doc.catalog.lookup(PDFName_default.of("AF"),PDFArray_default);AF.push(ref);this.alreadyEmbedded=true;_a.label=2;case 2:return[2]}})})};PDFEmbeddedFile2.of=function(ref,doc,embedder){return new PDFEmbeddedFile2(ref,doc,embedder)};return PDFEmbeddedFile2}();PDFEmbeddedFile_default=PDFEmbeddedFile});var PDFJavaScript,PDFJavaScript_default;var init_PDFJavaScript=__esm(()=>{init_tslib_es62();init_core();PDFJavaScript=function(){function PDFJavaScript2(ref,doc,embedder){this.alreadyEmbedded=false;this.ref=ref;this.doc=doc;this.embedder=embedder}PDFJavaScript2.prototype.embed=function(){return __awaiter(this,undefined,undefined,function(){var _a,catalog,context2,ref,Names,Javascript,JSNames;return __generator(this,function(_b){switch(_b.label){case 0:if(!!this.alreadyEmbedded)return[3,2];_a=this.doc,catalog=_a.catalog,context2=_a.context;return[4,this.embedder.embedIntoContext(this.doc.context,this.ref)];case 1:ref=_b.sent();if(!catalog.has(PDFName_default.of("Names"))){catalog.set(PDFName_default.of("Names"),context2.obj({}))}Names=catalog.lookup(PDFName_default.of("Names"),PDFDict_default);if(!Names.has(PDFName_default.of("JavaScript"))){Names.set(PDFName_default.of("JavaScript"),context2.obj({}))}Javascript=Names.lookup(PDFName_default.of("JavaScript"),PDFDict_default);if(!Javascript.has(PDFName_default.of("Names"))){Javascript.set(PDFName_default.of("Names"),context2.obj([]))}JSNames=Javascript.lookup(PDFName_default.of("Names"),PDFArray_default);JSNames.push(PDFHexString_default.fromText(this.embedder.scriptName));JSNames.push(ref);this.alreadyEmbedded=true;_b.label=2;case 2:return[2]}})})};PDFJavaScript2.of=function(ref,doc,embedder){return new PDFJavaScript2(ref,doc,embedder)};return PDFJavaScript2}();PDFJavaScript_default=PDFJavaScript});var JavaScriptEmbedder,JavaScriptEmbedder_default;var init_JavaScriptEmbedder=__esm(()=>{init_tslib_es62();init_PDFHexString();JavaScriptEmbedder=function(){function JavaScriptEmbedder2(script,scriptName){this.script=script;this.scriptName=scriptName}JavaScriptEmbedder2.for=function(script,scriptName){return new JavaScriptEmbedder2(script,scriptName)};JavaScriptEmbedder2.prototype.embedIntoContext=function(context2,ref){return __awaiter(this,undefined,undefined,function(){var jsActionDict;return __generator(this,function(_a){jsActionDict=context2.obj({Type:"Action",S:"JavaScript",JS:PDFHexString_default.fromText(this.script)});if(ref){context2.assign(ref,jsActionDict);return[2,ref]}else{return[2,context2.register(jsActionDict)]}return[2]})})};return JavaScriptEmbedder2}();JavaScriptEmbedder_default=JavaScriptEmbedder});function assertIsLiteralOrHexString(pdfObject){if(!(pdfObject instanceof PDFHexString_default)&&!(pdfObject instanceof PDFString_default)){throw new UnexpectedObjectTypeError([PDFHexString_default,PDFString_default],pdfObject)}}var PDFDocument,PDFDocument_default;var init_PDFDocument=__esm(()=>{init_tslib_es62();init_errors3();init_PDFEmbeddedPage();init_PDFFont();init_PDFImage();init_PDFPage();init_PDFForm();init_sizes();init_core();init_PDFDocumentOptions();init_utils2();init_FileEmbedder();init_PDFEmbeddedFile();init_PDFJavaScript();init_JavaScriptEmbedder();PDFDocument=function(){function PDFDocument2(context2,ignoreEncryption,updateMetadata){var _this=this;this.defaultWordBreaks=[" "];this.computePages=function(){var pages=[];_this.catalog.Pages().traverse(function(node,ref){if(node instanceof PDFPageLeaf_default){var page=_this.pageMap.get(node);if(!page){page=PDFPage_default.of(node,ref,_this);_this.pageMap.set(node,page)}pages.push(page)}});return pages};this.getOrCreateForm=function(){var acroForm=_this.catalog.getOrCreateAcroForm();return PDFForm_default.of(acroForm,_this)};assertIs(context2,"context",[[PDFContext_default,"PDFContext"]]);assertIs(ignoreEncryption,"ignoreEncryption",["boolean"]);this.context=context2;this.catalog=context2.lookup(context2.trailerInfo.Root);this.isEncrypted=!!context2.lookup(context2.trailerInfo.Encrypt);this.pageCache=Cache_default.populatedBy(this.computePages);this.pageMap=new Map;this.formCache=Cache_default.populatedBy(this.getOrCreateForm);this.fonts=[];this.images=[];this.embeddedPages=[];this.embeddedFiles=[];this.javaScripts=[];if(!ignoreEncryption&&this.isEncrypted)throw new EncryptedPDFError;if(updateMetadata)this.updateInfoDict()}PDFDocument2.load=function(pdf,options){if(options===undefined){options={}}return __awaiter(this,undefined,undefined,function(){var _a,ignoreEncryption,_b,parseSpeed,_c,throwOnInvalidObject,_d,updateMetadata,_e,capNumbers,bytes,context2;return __generator(this,function(_f){switch(_f.label){case 0:_a=options.ignoreEncryption,ignoreEncryption=_a===undefined?false:_a,_b=options.parseSpeed,parseSpeed=_b===undefined?ParseSpeeds.Slow:_b,_c=options.throwOnInvalidObject,throwOnInvalidObject=_c===undefined?false:_c,_d=options.updateMetadata,updateMetadata=_d===undefined?true:_d,_e=options.capNumbers,capNumbers=_e===undefined?false:_e;assertIs(pdf,"pdf",["string",Uint8Array,ArrayBuffer]);assertIs(ignoreEncryption,"ignoreEncryption",["boolean"]);assertIs(parseSpeed,"parseSpeed",["number"]);assertIs(throwOnInvalidObject,"throwOnInvalidObject",["boolean"]);bytes=toUint8Array(pdf);return[4,PDFParser_default.forBytesWithOptions(bytes,parseSpeed,throwOnInvalidObject,capNumbers).parseDocument()];case 1:context2=_f.sent();return[2,new PDFDocument2(context2,ignoreEncryption,updateMetadata)]}})})};PDFDocument2.create=function(options){if(options===undefined){options={}}return __awaiter(this,undefined,undefined,function(){var _a,updateMetadata,context2,pageTree,pageTreeRef,catalog;return __generator(this,function(_b){_a=options.updateMetadata,updateMetadata=_a===undefined?true:_a;context2=PDFContext_default.create();pageTree=PDFPageTree_default.withContext(context2);pageTreeRef=context2.register(pageTree);catalog=PDFCatalog_default.withContextAndPages(context2,pageTreeRef);context2.trailerInfo.Root=context2.register(catalog);return[2,new PDFDocument2(context2,false,updateMetadata)]})})};PDFDocument2.prototype.registerFontkit=function(fontkit){this.fontkit=fontkit};PDFDocument2.prototype.getForm=function(){var form=this.formCache.access();if(form.hasXFA()){console.warn("Removing XFA form data as pdf-lib does not support reading or writing XFA");form.deleteXFA()}return form};PDFDocument2.prototype.getTitle=function(){var title2=this.getInfoDict().lookup(PDFName_default.Title);if(!title2)return;assertIsLiteralOrHexString(title2);return title2.decodeText()};PDFDocument2.prototype.getAuthor=function(){var author=this.getInfoDict().lookup(PDFName_default.Author);if(!author)return;assertIsLiteralOrHexString(author);return author.decodeText()};PDFDocument2.prototype.getSubject=function(){var subject=this.getInfoDict().lookup(PDFName_default.Subject);if(!subject)return;assertIsLiteralOrHexString(subject);return subject.decodeText()};PDFDocument2.prototype.getKeywords=function(){var keywords=this.getInfoDict().lookup(PDFName_default.Keywords);if(!keywords)return;assertIsLiteralOrHexString(keywords);return keywords.decodeText()};PDFDocument2.prototype.getCreator=function(){var creator=this.getInfoDict().lookup(PDFName_default.Creator);if(!creator)return;assertIsLiteralOrHexString(creator);return creator.decodeText()};PDFDocument2.prototype.getProducer=function(){var producer=this.getInfoDict().lookup(PDFName_default.Producer);if(!producer)return;assertIsLiteralOrHexString(producer);return producer.decodeText()};PDFDocument2.prototype.getCreationDate=function(){var creationDate=this.getInfoDict().lookup(PDFName_default.CreationDate);if(!creationDate)return;assertIsLiteralOrHexString(creationDate);return creationDate.decodeDate()};PDFDocument2.prototype.getModificationDate=function(){var modificationDate=this.getInfoDict().lookup(PDFName_default.ModDate);if(!modificationDate)return;assertIsLiteralOrHexString(modificationDate);return modificationDate.decodeDate()};PDFDocument2.prototype.setTitle=function(title2,options){assertIs(title2,"title",["string"]);var key=PDFName_default.of("Title");this.getInfoDict().set(key,PDFHexString_default.fromText(title2));if(options===null||options===undefined?undefined:options.showInWindowTitleBar){var prefs=this.catalog.getOrCreateViewerPreferences();prefs.setDisplayDocTitle(true)}};PDFDocument2.prototype.setAuthor=function(author){assertIs(author,"author",["string"]);var key=PDFName_default.of("Author");this.getInfoDict().set(key,PDFHexString_default.fromText(author))};PDFDocument2.prototype.setSubject=function(subject){assertIs(subject,"author",["string"]);var key=PDFName_default.of("Subject");this.getInfoDict().set(key,PDFHexString_default.fromText(subject))};PDFDocument2.prototype.setKeywords=function(keywords){assertIs(keywords,"keywords",[Array]);var key=PDFName_default.of("Keywords");this.getInfoDict().set(key,PDFHexString_default.fromText(keywords.join(" ")))};PDFDocument2.prototype.setCreator=function(creator){assertIs(creator,"creator",["string"]);var key=PDFName_default.of("Creator");this.getInfoDict().set(key,PDFHexString_default.fromText(creator))};PDFDocument2.prototype.setProducer=function(producer){assertIs(producer,"creator",["string"]);var key=PDFName_default.of("Producer");this.getInfoDict().set(key,PDFHexString_default.fromText(producer))};PDFDocument2.prototype.setLanguage=function(language){assertIs(language,"language",["string"]);var key=PDFName_default.of("Lang");this.catalog.set(key,PDFString_default.of(language))};PDFDocument2.prototype.setCreationDate=function(creationDate){assertIs(creationDate,"creationDate",[[Date,"Date"]]);var key=PDFName_default.of("CreationDate");this.getInfoDict().set(key,PDFString_default.fromDate(creationDate))};PDFDocument2.prototype.setModificationDate=function(modificationDate){assertIs(modificationDate,"modificationDate",[[Date,"Date"]]);var key=PDFName_default.of("ModDate");this.getInfoDict().set(key,PDFString_default.fromDate(modificationDate))};PDFDocument2.prototype.getPageCount=function(){if(this.pageCount===undefined)this.pageCount=this.getPages().length;return this.pageCount};PDFDocument2.prototype.getPages=function(){return this.pageCache.access()};PDFDocument2.prototype.getPage=function(index){var pages=this.getPages();assertRange(index,"index",0,pages.length-1);return pages[index]};PDFDocument2.prototype.getPageIndices=function(){return range(0,this.getPageCount())};PDFDocument2.prototype.removePage=function(index){var pageCount=this.getPageCount();if(this.pageCount===0)throw new RemovePageFromEmptyDocumentError;assertRange(index,"index",0,pageCount-1);this.catalog.removeLeafNode(index);this.pageCount=pageCount-1};PDFDocument2.prototype.addPage=function(page){assertIs(page,"page",["undefined",[PDFPage_default,"PDFPage"],Array]);return this.insertPage(this.getPageCount(),page)};PDFDocument2.prototype.insertPage=function(index,page){var pageCount=this.getPageCount();assertRange(index,"index",0,pageCount);assertIs(page,"page",["undefined",[PDFPage_default,"PDFPage"],Array]);if(!page||Array.isArray(page)){var dims=Array.isArray(page)?page:PageSizes.A4;page=PDFPage_default.create(this);page.setSize.apply(page,dims)}else if(page.doc!==this){throw new ForeignPageError}var parentRef=this.catalog.insertLeafNode(page.ref,index);page.node.setParent(parentRef);this.pageMap.set(page.node,page);this.pageCache.invalidate();this.pageCount=pageCount+1;return page};PDFDocument2.prototype.copyPages=function(srcDoc,indices){return __awaiter(this,undefined,undefined,function(){var copier,srcPages,copiedPages,idx4,len3,srcPage,copiedPage,ref;return __generator(this,function(_a){switch(_a.label){case 0:assertIs(srcDoc,"srcDoc",[[PDFDocument2,"PDFDocument"]]);assertIs(indices,"indices",[Array]);return[4,srcDoc.flush()];case 1:_a.sent();copier=PDFObjectCopier_default.for(srcDoc.context,this.context);srcPages=srcDoc.getPages();copiedPages=new Array(indices.length);for(idx4=0,len3=indices.length;idx4<len3;idx4++){srcPage=srcPages[indices[idx4]];copiedPage=copier.copy(srcPage.node);ref=this.context.register(copiedPage);copiedPages[idx4]=PDFPage_default.of(copiedPage,ref,this)}return[2,copiedPages]}})})};PDFDocument2.prototype.copy=function(){return __awaiter(this,undefined,undefined,function(){var pdfCopy,contentPages,idx4,len3;return __generator(this,function(_a){switch(_a.label){case 0:return[4,PDFDocument2.create()];case 1:pdfCopy=_a.sent();return[4,pdfCopy.copyPages(this,this.getPageIndices())];case 2:contentPages=_a.sent();for(idx4=0,len3=contentPages.length;idx4<len3;idx4++){pdfCopy.addPage(contentPages[idx4])}if(this.getAuthor()!==undefined){pdfCopy.setAuthor(this.getAuthor())}if(this.getCreationDate()!==undefined){pdfCopy.setCreationDate(this.getCreationDate())}if(this.getCreator()!==undefined){pdfCopy.setCreator(this.getCreator())}if(this.getModificationDate()!==undefined){pdfCopy.setModificationDate(this.getModificationDate())}if(this.getProducer()!==undefined){pdfCopy.setProducer(this.getProducer())}if(this.getSubject()!==undefined){pdfCopy.setSubject(this.getSubject())}if(this.getTitle()!==undefined){pdfCopy.setTitle(this.getTitle())}pdfCopy.defaultWordBreaks=this.defaultWordBreaks;return[2,pdfCopy]}})})};PDFDocument2.prototype.addJavaScript=function(name,script){assertIs(name,"name",["string"]);assertIs(script,"script",["string"]);var embedder=JavaScriptEmbedder_default.for(script,name);var ref=this.context.nextRef();var javaScript=PDFJavaScript_default.of(ref,this,embedder);this.javaScripts.push(javaScript)};PDFDocument2.prototype.attach=function(attachment,name,options){if(options===undefined){options={}}return __awaiter(this,undefined,undefined,function(){var bytes,embedder,ref,embeddedFile;return __generator(this,function(_a){assertIs(attachment,"attachment",["string",Uint8Array,ArrayBuffer]);assertIs(name,"name",["string"]);assertOrUndefined(options.mimeType,"mimeType",["string"]);assertOrUndefined(options.description,"description",["string"]);assertOrUndefined(options.creationDate,"options.creationDate",[Date]);assertOrUndefined(options.modificationDate,"options.modificationDate",[Date]);assertIsOneOfOrUndefined(options.afRelationship,"options.afRelationship",AFRelationship);bytes=toUint8Array(attachment);embedder=FileEmbedder_default.for(bytes,name,options);ref=this.context.nextRef();embeddedFile=PDFEmbeddedFile_default.of(ref,this,embedder);this.embeddedFiles.push(embeddedFile);return[2]})})};PDFDocument2.prototype.embedFont=function(font,options){if(options===undefined){options={}}return __awaiter(this,undefined,undefined,function(){var _a,subset,customName,features,embedder,bytes,fontkit,_b,ref,pdfFont;return __generator(this,function(_c){switch(_c.label){case 0:_a=options.subset,subset=_a===undefined?false:_a,customName=options.customName,features=options.features;assertIs(font,"font",["string",Uint8Array,ArrayBuffer]);assertIs(subset,"subset",["boolean"]);if(!isStandardFont(font))return[3,1];embedder=StandardFontEmbedder_default.for(font,customName);return[3,7];case 1:if(!canBeConvertedToUint8Array(font))return[3,6];bytes=toUint8Array(font);fontkit=this.assertFontkit();if(!subset)return[3,3];return[4,CustomFontSubsetEmbedder_default.for(fontkit,bytes,customName,features)];case 2:_b=_c.sent();return[3,5];case 3:return[4,CustomFontEmbedder_default.for(fontkit,bytes,customName,features)];case 4:_b=_c.sent();_c.label=5;case 5:embedder=_b;return[3,7];case 6:throw new TypeError("`font` must be one of `StandardFonts | string | Uint8Array | ArrayBuffer`");case 7:ref=this.context.nextRef();pdfFont=PDFFont_default.of(ref,this,embedder);this.fonts.push(pdfFont);return[2,pdfFont]}})})};PDFDocument2.prototype.embedStandardFont=function(font,customName){assertIs(font,"font",["string"]);if(!isStandardFont(font)){throw new TypeError("`font` must be one of type `StandardFonts`")}var embedder=StandardFontEmbedder_default.for(font,customName);var ref=this.context.nextRef();var pdfFont=PDFFont_default.of(ref,this,embedder);this.fonts.push(pdfFont);return pdfFont};PDFDocument2.prototype.embedJpg=function(jpg){return __awaiter(this,undefined,undefined,function(){var bytes,embedder,ref,pdfImage;return __generator(this,function(_a){switch(_a.label){case 0:assertIs(jpg,"jpg",["string",Uint8Array,ArrayBuffer]);bytes=toUint8Array(jpg);return[4,JpegEmbedder_default.for(bytes)];case 1:embedder=_a.sent();ref=this.context.nextRef();pdfImage=PDFImage_default.of(ref,this,embedder);this.images.push(pdfImage);return[2,pdfImage]}})})};PDFDocument2.prototype.embedPng=function(png){return __awaiter(this,undefined,undefined,function(){var bytes,embedder,ref,pdfImage;return __generator(this,function(_a){switch(_a.label){case 0:assertIs(png,"png",["string",Uint8Array,ArrayBuffer]);bytes=toUint8Array(png);return[4,PngEmbedder_default.for(bytes)];case 1:embedder=_a.sent();ref=this.context.nextRef();pdfImage=PDFImage_default.of(ref,this,embedder);this.images.push(pdfImage);return[2,pdfImage]}})})};PDFDocument2.prototype.embedPdf=function(pdf,indices){if(indices===undefined){indices=[0]}return __awaiter(this,undefined,undefined,function(){var srcDoc,_a,srcPages;return __generator(this,function(_b){switch(_b.label){case 0:assertIs(pdf,"pdf",["string",Uint8Array,ArrayBuffer,[PDFDocument2,"PDFDocument"]]);assertIs(indices,"indices",[Array]);if(!(pdf instanceof PDFDocument2))return[3,1];_a=pdf;return[3,3];case 1:return[4,PDFDocument2.load(pdf)];case 2:_a=_b.sent();_b.label=3;case 3:srcDoc=_a;srcPages=pluckIndices(srcDoc.getPages(),indices);return[2,this.embedPages(srcPages)]}})})};PDFDocument2.prototype.embedPage=function(page,boundingBox,transformationMatrix){return __awaiter(this,undefined,undefined,function(){var embeddedPage;return __generator(this,function(_a){switch(_a.label){case 0:assertIs(page,"page",[[PDFPage_default,"PDFPage"]]);return[4,this.embedPages([page],[boundingBox],[transformationMatrix])];case 1:embeddedPage=_a.sent()[0];return[2,embeddedPage]}})})};PDFDocument2.prototype.embedPages=function(pages,boundingBoxes,transformationMatrices){if(boundingBoxes===undefined){boundingBoxes=[]}if(transformationMatrices===undefined){transformationMatrices=[]}return __awaiter(this,undefined,undefined,function(){var idx4,len3,currPage,nextPage,context2,maybeCopyPage,embeddedPages,idx4,len3,page,box,matrix,embedder,ref;var _a;return __generator(this,function(_b){switch(_b.label){case 0:if(pages.length===0)return[2,[]];for(idx4=0,len3=pages.length-1;idx4<len3;idx4++){currPage=pages[idx4];nextPage=pages[idx4+1];if(currPage.node.context!==nextPage.node.context){throw new PageEmbeddingMismatchedContextError}}context2=pages[0].node.context;maybeCopyPage=context2===this.context?function(p){return p}:PDFObjectCopier_default.for(context2,this.context).copy;embeddedPages=new Array(pages.length);idx4=0,len3=pages.length;_b.label=1;case 1:if(!(idx4<len3))return[3,4];page=maybeCopyPage(pages[idx4].node);box=boundingBoxes[idx4];matrix=transformationMatrices[idx4];return[4,PDFPageEmbedder_default.for(page,box,matrix)];case 2:embedder=_b.sent();ref=this.context.nextRef();embeddedPages[idx4]=PDFEmbeddedPage_default.of(ref,this,embedder);_b.label=3;case 3:idx4++;return[3,1];case 4:(_a=this.embeddedPages).push.apply(_a,embeddedPages);return[2,embeddedPages]}})})};PDFDocument2.prototype.flush=function(){return __awaiter(this,undefined,undefined,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.embedAll(this.fonts)];case 1:_a.sent();return[4,this.embedAll(this.images)];case 2:_a.sent();return[4,this.embedAll(this.embeddedPages)];case 3:_a.sent();return[4,this.embedAll(this.embeddedFiles)];case 4:_a.sent();return[4,this.embedAll(this.javaScripts)];case 5:_a.sent();return[2]}})})};PDFDocument2.prototype.save=function(options){if(options===undefined){options={}}return __awaiter(this,undefined,undefined,function(){var _a,useObjectStreams,_b,addDefaultPage,_c,objectsPerTick,_d,updateFieldAppearances,form,Writer;return __generator(this,function(_e){switch(_e.label){case 0:_a=options.useObjectStreams,useObjectStreams=_a===undefined?true:_a,_b=options.addDefaultPage,addDefaultPage=_b===undefined?true:_b,_c=options.objectsPerTick,objectsPerTick=_c===undefined?50:_c,_d=options.updateFieldAppearances,updateFieldAppearances=_d===undefined?true:_d;assertIs(useObjectStreams,"useObjectStreams",["boolean"]);assertIs(addDefaultPage,"addDefaultPage",["boolean"]);assertIs(objectsPerTick,"objectsPerTick",["number"]);assertIs(updateFieldAppearances,"updateFieldAppearances",["boolean"]);if(addDefaultPage&&this.getPageCount()===0)this.addPage();if(updateFieldAppearances){form=this.formCache.getValue();if(form)form.updateFieldAppearances()}return[4,this.flush()];case 1:_e.sent();Writer=useObjectStreams?PDFStreamWriter_default:PDFWriter_default;return[2,Writer.forContext(this.context,objectsPerTick).serializeToBuffer()]}})})};PDFDocument2.prototype.saveAsBase64=function(options){if(options===undefined){options={}}return __awaiter(this,undefined,undefined,function(){var _a,dataUri,otherOptions,bytes,base642;return __generator(this,function(_b){switch(_b.label){case 0:_a=options.dataUri,dataUri=_a===undefined?false:_a,otherOptions=__rest2(options,["dataUri"]);assertIs(dataUri,"dataUri",["boolean"]);return[4,this.save(otherOptions)];case 1:bytes=_b.sent();base642=encodeToBase64(bytes);return[2,dataUri?"data:application/pdf;base64,"+base642:base642]}})})};PDFDocument2.prototype.findPageForAnnotationRef=function(ref){var pages=this.getPages();for(var idx4=0,len3=pages.length;idx4<len3;idx4++){var page=pages[idx4];var annotations=page.node.Annots();if((annotations===null||annotations===undefined?undefined:annotations.indexOf(ref))!==undefined){return page}}return};PDFDocument2.prototype.embedAll=function(embeddables){return __awaiter(this,undefined,undefined,function(){var idx4,len3;return __generator(this,function(_a){switch(_a.label){case 0:idx4=0,len3=embeddables.length;_a.label=1;case 1:if(!(idx4<len3))return[3,4];return[4,embeddables[idx4].embed()];case 2:_a.sent();_a.label=3;case 3:idx4++;return[3,1];case 4:return[2]}})})};PDFDocument2.prototype.updateInfoDict=function(){var pdfLib="pdf-lib (https://github.com/Hopding/pdf-lib)";var now=new Date;var info=this.getInfoDict();this.setProducer(pdfLib);this.setModificationDate(now);if(!info.get(PDFName_default.of("Creator")))this.setCreator(pdfLib);if(!info.get(PDFName_default.of("CreationDate")))this.setCreationDate(now)};PDFDocument2.prototype.getInfoDict=function(){var existingInfo=this.context.lookup(this.context.trailerInfo.Info);if(existingInfo instanceof PDFDict_default)return existingInfo;var newInfo=this.context.obj({});this.context.trailerInfo.Info=this.context.register(newInfo);return newInfo};PDFDocument2.prototype.assertFontkit=function(){if(!this.fontkit)throw new FontkitNotRegisteredError;return this.fontkit};return PDFDocument2}();PDFDocument_default=PDFDocument});var BlendMode;var init_PDFPageOptions=__esm(()=>{(function(BlendMode2){BlendMode2["Normal"]="Normal";BlendMode2["Multiply"]="Multiply";BlendMode2["Screen"]="Screen";BlendMode2["Overlay"]="Overlay";BlendMode2["Darken"]="Darken";BlendMode2["Lighten"]="Lighten";BlendMode2["ColorDodge"]="ColorDodge";BlendMode2["ColorBurn"]="ColorBurn";BlendMode2["HardLight"]="HardLight";BlendMode2["SoftLight"]="SoftLight";BlendMode2["Difference"]="Difference";BlendMode2["Exclusion"]="Exclusion"})(BlendMode||(BlendMode={}))});var PDFPage,PDFPage_default;var init_PDFPage=__esm(()=>{init_tslib_es62();init_colors();init_operations();init_operators();init_PDFDocument();init_PDFEmbeddedPage();init_PDFFont();init_PDFImage();init_PDFPageOptions();init_rotations();init_StandardFonts();init_core();init_utils2();PDFPage=function(){function PDFPage2(leafNode,ref,doc){this.fontSize=24;this.fontColor=rgb(0,0,0);this.lineHeight=24;this.x=0;this.y=0;assertIs(leafNode,"leafNode",[[PDFPageLeaf_default,"PDFPageLeaf"]]);assertIs(ref,"ref",[[PDFRef_default,"PDFRef"]]);assertIs(doc,"doc",[[PDFDocument_default,"PDFDocument"]]);this.node=leafNode;this.ref=ref;this.doc=doc}PDFPage2.prototype.setRotation=function(angle){var degreesAngle=toDegrees(angle);assertMultiple(degreesAngle,"degreesAngle",90);this.node.set(PDFName_default.of("Rotate"),this.doc.context.obj(degreesAngle))};PDFPage2.prototype.getRotation=function(){var Rotate=this.node.Rotate();return degrees(Rotate?Rotate.asNumber():0)};PDFPage2.prototype.setSize=function(width,height){assertIs(width,"width",["number"]);assertIs(height,"height",["number"]);var mediaBox=this.getMediaBox();this.setMediaBox(mediaBox.x,mediaBox.y,width,height);var cropBox=this.getCropBox();var bleedBox=this.getBleedBox();var trimBox=this.getTrimBox();var artBox=this.getArtBox();var hasCropBox=this.node.CropBox();var hasBleedBox=this.node.BleedBox();var hasTrimBox=this.node.TrimBox();var hasArtBox=this.node.ArtBox();if(hasCropBox&&rectanglesAreEqual(cropBox,mediaBox)){this.setCropBox(mediaBox.x,mediaBox.y,width,height)}if(hasBleedBox&&rectanglesAreEqual(bleedBox,mediaBox)){this.setBleedBox(mediaBox.x,mediaBox.y,width,height)}if(hasTrimBox&&rectanglesAreEqual(trimBox,mediaBox)){this.setTrimBox(mediaBox.x,mediaBox.y,width,height)}if(hasArtBox&&rectanglesAreEqual(artBox,mediaBox)){this.setArtBox(mediaBox.x,mediaBox.y,width,height)}};PDFPage2.prototype.setWidth=function(width){assertIs(width,"width",["number"]);this.setSize(width,this.getSize().height)};PDFPage2.prototype.setHeight=function(height){assertIs(height,"height",["number"]);this.setSize(this.getSize().width,height)};PDFPage2.prototype.setMediaBox=function(x,y,width,height){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);assertIs(width,"width",["number"]);assertIs(height,"height",["number"]);var mediaBox=this.doc.context.obj([x,y,x+width,y+height]);this.node.set(PDFName_default.MediaBox,mediaBox)};PDFPage2.prototype.setCropBox=function(x,y,width,height){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);assertIs(width,"width",["number"]);assertIs(height,"height",["number"]);var cropBox=this.doc.context.obj([x,y,x+width,y+height]);this.node.set(PDFName_default.CropBox,cropBox)};PDFPage2.prototype.setBleedBox=function(x,y,width,height){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);assertIs(width,"width",["number"]);assertIs(height,"height",["number"]);var bleedBox=this.doc.context.obj([x,y,x+width,y+height]);this.node.set(PDFName_default.BleedBox,bleedBox)};PDFPage2.prototype.setTrimBox=function(x,y,width,height){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);assertIs(width,"width",["number"]);assertIs(height,"height",["number"]);var trimBox=this.doc.context.obj([x,y,x+width,y+height]);this.node.set(PDFName_default.TrimBox,trimBox)};PDFPage2.prototype.setArtBox=function(x,y,width,height){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);assertIs(width,"width",["number"]);assertIs(height,"height",["number"]);var artBox=this.doc.context.obj([x,y,x+width,y+height]);this.node.set(PDFName_default.ArtBox,artBox)};PDFPage2.prototype.getSize=function(){var _a=this.getMediaBox(),width=_a.width,height=_a.height;return{width,height}};PDFPage2.prototype.getWidth=function(){return this.getSize().width};PDFPage2.prototype.getHeight=function(){return this.getSize().height};PDFPage2.prototype.getMediaBox=function(){var mediaBox=this.node.MediaBox();return mediaBox.asRectangle()};PDFPage2.prototype.getCropBox=function(){var _a;var cropBox=this.node.CropBox();return(_a=cropBox===null||cropBox===undefined?undefined:cropBox.asRectangle())!==null&&_a!==undefined?_a:this.getMediaBox()};PDFPage2.prototype.getBleedBox=function(){var _a;var bleedBox=this.node.BleedBox();return(_a=bleedBox===null||bleedBox===undefined?undefined:bleedBox.asRectangle())!==null&&_a!==undefined?_a:this.getCropBox()};PDFPage2.prototype.getTrimBox=function(){var _a;var trimBox=this.node.TrimBox();return(_a=trimBox===null||trimBox===undefined?undefined:trimBox.asRectangle())!==null&&_a!==undefined?_a:this.getCropBox()};PDFPage2.prototype.getArtBox=function(){var _a;var artBox=this.node.ArtBox();return(_a=artBox===null||artBox===undefined?undefined:artBox.asRectangle())!==null&&_a!==undefined?_a:this.getCropBox()};PDFPage2.prototype.translateContent=function(x,y){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);this.node.normalize();this.getContentStream();var start=this.createContentStream(pushGraphicsState(),translate(x,y));var startRef=this.doc.context.register(start);var end=this.createContentStream(popGraphicsState());var endRef=this.doc.context.register(end);this.node.wrapContentStreams(startRef,endRef)};PDFPage2.prototype.scale=function(x,y){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);this.setSize(this.getWidth()*x,this.getHeight()*y);this.scaleContent(x,y);this.scaleAnnotations(x,y)};PDFPage2.prototype.scaleContent=function(x,y){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);this.node.normalize();this.getContentStream();var start=this.createContentStream(pushGraphicsState(),scale(x,y));var startRef=this.doc.context.register(start);var end=this.createContentStream(popGraphicsState());var endRef=this.doc.context.register(end);this.node.wrapContentStreams(startRef,endRef)};PDFPage2.prototype.scaleAnnotations=function(x,y){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);var annots=this.node.Annots();if(!annots)return;for(var idx4=0;idx4<annots.size();idx4++){var annot=annots.lookup(idx4);if(annot instanceof PDFDict_default)this.scaleAnnot(annot,x,y)}};PDFPage2.prototype.resetPosition=function(){this.getContentStream(false);this.x=0;this.y=0};PDFPage2.prototype.setFont=function(font){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);this.font=font;this.fontKey=this.node.newFontDictionary(this.font.name,this.font.ref)};PDFPage2.prototype.setFontSize=function(fontSize){assertIs(fontSize,"fontSize",["number"]);this.fontSize=fontSize};PDFPage2.prototype.setFontColor=function(fontColor){assertIs(fontColor,"fontColor",[[Object,"Color"]]);this.fontColor=fontColor};PDFPage2.prototype.setLineHeight=function(lineHeight){assertIs(lineHeight,"lineHeight",["number"]);this.lineHeight=lineHeight};PDFPage2.prototype.getPosition=function(){return{x:this.x,y:this.y}};PDFPage2.prototype.getX=function(){return this.x};PDFPage2.prototype.getY=function(){return this.y};PDFPage2.prototype.moveTo=function(x,y){assertIs(x,"x",["number"]);assertIs(y,"y",["number"]);this.x=x;this.y=y};PDFPage2.prototype.moveDown=function(yDecrease){assertIs(yDecrease,"yDecrease",["number"]);this.y-=yDecrease};PDFPage2.prototype.moveUp=function(yIncrease){assertIs(yIncrease,"yIncrease",["number"]);this.y+=yIncrease};PDFPage2.prototype.moveLeft=function(xDecrease){assertIs(xDecrease,"xDecrease",["number"]);this.x-=xDecrease};PDFPage2.prototype.moveRight=function(xIncrease){assertIs(xIncrease,"xIncrease",["number"]);this.x+=xIncrease};PDFPage2.prototype.pushOperators=function(){var operator=[];for(var _i=0;_i<arguments.length;_i++){operator[_i]=arguments[_i]}assertEachIs(operator,"operator",[[PDFOperator_default,"PDFOperator"]]);var contentStream=this.getContentStream();contentStream.push.apply(contentStream,operator)};PDFPage2.prototype.drawText=function(text4,options){var _a,_b,_c,_d,_e,_f,_g;if(options===undefined){options={}}assertIs(text4,"text",["string"]);assertOrUndefined(options.color,"options.color",[[Object,"Color"]]);assertRangeOrUndefined(options.opacity,"opacity.opacity",0,1);assertOrUndefined(options.font,"options.font",[[PDFFont_default,"PDFFont"]]);assertOrUndefined(options.size,"options.size",["number"]);assertOrUndefined(options.rotate,"options.rotate",[[Object,"Rotation"]]);assertOrUndefined(options.xSkew,"options.xSkew",[[Object,"Rotation"]]);assertOrUndefined(options.ySkew,"options.ySkew",[[Object,"Rotation"]]);assertOrUndefined(options.x,"options.x",["number"]);assertOrUndefined(options.y,"options.y",["number"]);assertOrUndefined(options.lineHeight,"options.lineHeight",["number"]);assertOrUndefined(options.maxWidth,"options.maxWidth",["number"]);assertOrUndefined(options.wordBreaks,"options.wordBreaks",[Array]);assertIsOneOfOrUndefined(options.blendMode,"options.blendMode",BlendMode);var _h=this.setOrEmbedFont(options.font),oldFont=_h.oldFont,newFont=_h.newFont,newFontKey=_h.newFontKey;var fontSize=options.size||this.fontSize;var wordBreaks=options.wordBreaks||this.doc.defaultWordBreaks;var textWidth=function(t){return newFont.widthOfTextAtSize(t,fontSize)};var lines=options.maxWidth===undefined?lineSplit(cleanText(text4)):breakTextIntoLines(text4,wordBreaks,options.maxWidth,textWidth);var encodedLines=new Array(lines.length);for(var idx4=0,len3=lines.length;idx4<len3;idx4++){encodedLines[idx4]=newFont.encodeText(lines[idx4])}var graphicsStateKey=this.maybeEmbedGraphicsState({opacity:options.opacity,blendMode:options.blendMode});var contentStream=this.getContentStream();contentStream.push.apply(contentStream,drawLinesOfText(encodedLines,{color:(_a=options.color)!==null&&_a!==undefined?_a:this.fontColor,font:newFontKey,size:fontSize,rotate:(_b=options.rotate)!==null&&_b!==undefined?_b:degrees(0),xSkew:(_c=options.xSkew)!==null&&_c!==undefined?_c:degrees(0),ySkew:(_d=options.ySkew)!==null&&_d!==undefined?_d:degrees(0),x:(_e=options.x)!==null&&_e!==undefined?_e:this.x,y:(_f=options.y)!==null&&_f!==undefined?_f:this.y,lineHeight:(_g=options.lineHeight)!==null&&_g!==undefined?_g:this.lineHeight,graphicsState:graphicsStateKey}));if(options.font){if(oldFont)this.setFont(oldFont);else this.resetFont()}};PDFPage2.prototype.drawImage=function(image,options){var _a,_b,_c,_d,_e,_f,_g;if(options===undefined){options={}}assertIs(image,"image",[[PDFImage_default,"PDFImage"]]);assertOrUndefined(options.x,"options.x",["number"]);assertOrUndefined(options.y,"options.y",["number"]);assertOrUndefined(options.width,"options.width",["number"]);assertOrUndefined(options.height,"options.height",["number"]);assertOrUndefined(options.rotate,"options.rotate",[[Object,"Rotation"]]);assertOrUndefined(options.xSkew,"options.xSkew",[[Object,"Rotation"]]);assertOrUndefined(options.ySkew,"options.ySkew",[[Object,"Rotation"]]);assertRangeOrUndefined(options.opacity,"opacity.opacity",0,1);assertIsOneOfOrUndefined(options.blendMode,"options.blendMode",BlendMode);var xObjectKey=this.node.newXObject("Image",image.ref);var graphicsStateKey=this.maybeEmbedGraphicsState({opacity:options.opacity,blendMode:options.blendMode});var contentStream=this.getContentStream();contentStream.push.apply(contentStream,drawImage(xObjectKey,{x:(_a=options.x)!==null&&_a!==undefined?_a:this.x,y:(_b=options.y)!==null&&_b!==undefined?_b:this.y,width:(_c=options.width)!==null&&_c!==undefined?_c:image.size().width,height:(_d=options.height)!==null&&_d!==undefined?_d:image.size().height,rotate:(_e=options.rotate)!==null&&_e!==undefined?_e:degrees(0),xSkew:(_f=options.xSkew)!==null&&_f!==undefined?_f:degrees(0),ySkew:(_g=options.ySkew)!==null&&_g!==undefined?_g:degrees(0),graphicsState:graphicsStateKey}))};PDFPage2.prototype.drawPage=function(embeddedPage,options){var _a,_b,_c,_d,_e;if(options===undefined){options={}}assertIs(embeddedPage,"embeddedPage",[[PDFEmbeddedPage_default,"PDFEmbeddedPage"]]);assertOrUndefined(options.x,"options.x",["number"]);assertOrUndefined(options.y,"options.y",["number"]);assertOrUndefined(options.xScale,"options.xScale",["number"]);assertOrUndefined(options.yScale,"options.yScale",["number"]);assertOrUndefined(options.width,"options.width",["number"]);assertOrUndefined(options.height,"options.height",["number"]);assertOrUndefined(options.rotate,"options.rotate",[[Object,"Rotation"]]);assertOrUndefined(options.xSkew,"options.xSkew",[[Object,"Rotation"]]);assertOrUndefined(options.ySkew,"options.ySkew",[[Object,"Rotation"]]);assertRangeOrUndefined(options.opacity,"opacity.opacity",0,1);assertIsOneOfOrUndefined(options.blendMode,"options.blendMode",BlendMode);var xObjectKey=this.node.newXObject("EmbeddedPdfPage",embeddedPage.ref);var graphicsStateKey=this.maybeEmbedGraphicsState({opacity:options.opacity,blendMode:options.blendMode});var xScale=options.width!==undefined?options.width/embeddedPage.width:options.xScale!==undefined?options.xScale:1;var yScale=options.height!==undefined?options.height/embeddedPage.height:options.yScale!==undefined?options.yScale:1;var contentStream=this.getContentStream();contentStream.push.apply(contentStream,drawPage(xObjectKey,{x:(_a=options.x)!==null&&_a!==undefined?_a:this.x,y:(_b=options.y)!==null&&_b!==undefined?_b:this.y,xScale,yScale,rotate:(_c=options.rotate)!==null&&_c!==undefined?_c:degrees(0),xSkew:(_d=options.xSkew)!==null&&_d!==undefined?_d:degrees(0),ySkew:(_e=options.ySkew)!==null&&_e!==undefined?_e:degrees(0),graphicsState:graphicsStateKey}))};PDFPage2.prototype.drawSvgPath=function(path,options){var _a,_b,_c,_d,_e,_f,_g,_h,_j;if(options===undefined){options={}}assertIs(path,"path",["string"]);assertOrUndefined(options.x,"options.x",["number"]);assertOrUndefined(options.y,"options.y",["number"]);assertOrUndefined(options.scale,"options.scale",["number"]);assertOrUndefined(options.rotate,"options.rotate",[[Object,"Rotation"]]);assertOrUndefined(options.borderWidth,"options.borderWidth",["number"]);assertOrUndefined(options.color,"options.color",[[Object,"Color"]]);assertRangeOrUndefined(options.opacity,"opacity.opacity",0,1);assertOrUndefined(options.borderColor,"options.borderColor",[[Object,"Color"]]);assertOrUndefined(options.borderDashArray,"options.borderDashArray",[Array]);assertOrUndefined(options.borderDashPhase,"options.borderDashPhase",["number"]);assertIsOneOfOrUndefined(options.borderLineCap,"options.borderLineCap",LineCapStyle);assertRangeOrUndefined(options.borderOpacity,"options.borderOpacity",0,1);assertIsOneOfOrUndefined(options.blendMode,"options.blendMode",BlendMode);var graphicsStateKey=this.maybeEmbedGraphicsState({opacity:options.opacity,borderOpacity:options.borderOpacity,blendMode:options.blendMode});if(!("color"in options)&&!("borderColor"in options)){options.borderColor=rgb(0,0,0)}var contentStream=this.getContentStream();contentStream.push.apply(contentStream,drawSvgPath(path,{x:(_a=options.x)!==null&&_a!==undefined?_a:this.x,y:(_b=options.y)!==null&&_b!==undefined?_b:this.y,scale:options.scale,rotate:(_c=options.rotate)!==null&&_c!==undefined?_c:degrees(0),color:(_d=options.color)!==null&&_d!==undefined?_d:undefined,borderColor:(_e=options.borderColor)!==null&&_e!==undefined?_e:undefined,borderWidth:(_f=options.borderWidth)!==null&&_f!==undefined?_f:0,borderDashArray:(_g=options.borderDashArray)!==null&&_g!==undefined?_g:undefined,borderDashPhase:(_h=options.borderDashPhase)!==null&&_h!==undefined?_h:undefined,borderLineCap:(_j=options.borderLineCap)!==null&&_j!==undefined?_j:undefined,graphicsState:graphicsStateKey}))};PDFPage2.prototype.drawLine=function(options){var _a,_b,_c,_d,_e;assertIs(options.start,"options.start",[[Object,"{ x: number, y: number }"]]);assertIs(options.end,"options.end",[[Object,"{ x: number, y: number }"]]);assertIs(options.start.x,"options.start.x",["number"]);assertIs(options.start.y,"options.start.y",["number"]);assertIs(options.end.x,"options.end.x",["number"]);assertIs(options.end.y,"options.end.y",["number"]);assertOrUndefined(options.thickness,"options.thickness",["number"]);assertOrUndefined(options.color,"options.color",[[Object,"Color"]]);assertOrUndefined(options.dashArray,"options.dashArray",[Array]);assertOrUndefined(options.dashPhase,"options.dashPhase",["number"]);assertIsOneOfOrUndefined(options.lineCap,"options.lineCap",LineCapStyle);assertRangeOrUndefined(options.opacity,"opacity.opacity",0,1);assertIsOneOfOrUndefined(options.blendMode,"options.blendMode",BlendMode);var graphicsStateKey=this.maybeEmbedGraphicsState({borderOpacity:options.opacity,blendMode:options.blendMode});if(!("color"in options)){options.color=rgb(0,0,0)}var contentStream=this.getContentStream();contentStream.push.apply(contentStream,drawLine({start:options.start,end:options.end,thickness:(_a=options.thickness)!==null&&_a!==undefined?_a:1,color:(_b=options.color)!==null&&_b!==undefined?_b:undefined,dashArray:(_c=options.dashArray)!==null&&_c!==undefined?_c:undefined,dashPhase:(_d=options.dashPhase)!==null&&_d!==undefined?_d:undefined,lineCap:(_e=options.lineCap)!==null&&_e!==undefined?_e:undefined,graphicsState:graphicsStateKey}))};PDFPage2.prototype.drawRectangle=function(options){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o;if(options===undefined){options={}}assertOrUndefined(options.x,"options.x",["number"]);assertOrUndefined(options.y,"options.y",["number"]);assertOrUndefined(options.width,"options.width",["number"]);assertOrUndefined(options.height,"options.height",["number"]);assertOrUndefined(options.rotate,"options.rotate",[[Object,"Rotation"]]);assertOrUndefined(options.xSkew,"options.xSkew",[[Object,"Rotation"]]);assertOrUndefined(options.ySkew,"options.ySkew",[[Object,"Rotation"]]);assertOrUndefined(options.borderWidth,"options.borderWidth",["number"]);assertOrUndefined(options.color,"options.color",[[Object,"Color"]]);assertRangeOrUndefined(options.opacity,"opacity.opacity",0,1);assertOrUndefined(options.borderColor,"options.borderColor",[[Object,"Color"]]);assertOrUndefined(options.borderDashArray,"options.borderDashArray",[Array]);assertOrUndefined(options.borderDashPhase,"options.borderDashPhase",["number"]);assertIsOneOfOrUndefined(options.borderLineCap,"options.borderLineCap",LineCapStyle);assertRangeOrUndefined(options.borderOpacity,"options.borderOpacity",0,1);assertIsOneOfOrUndefined(options.blendMode,"options.blendMode",BlendMode);var graphicsStateKey=this.maybeEmbedGraphicsState({opacity:options.opacity,borderOpacity:options.borderOpacity,blendMode:options.blendMode});if(!("color"in options)&&!("borderColor"in options)){options.color=rgb(0,0,0)}var contentStream=this.getContentStream();contentStream.push.apply(contentStream,drawRectangle({x:(_a=options.x)!==null&&_a!==undefined?_a:this.x,y:(_b=options.y)!==null&&_b!==undefined?_b:this.y,width:(_c=options.width)!==null&&_c!==undefined?_c:150,height:(_d=options.height)!==null&&_d!==undefined?_d:100,rotate:(_e=options.rotate)!==null&&_e!==undefined?_e:degrees(0),xSkew:(_f=options.xSkew)!==null&&_f!==undefined?_f:degrees(0),ySkew:(_g=options.ySkew)!==null&&_g!==undefined?_g:degrees(0),borderWidth:(_h=options.borderWidth)!==null&&_h!==undefined?_h:0,color:(_j=options.color)!==null&&_j!==undefined?_j:undefined,borderColor:(_k=options.borderColor)!==null&&_k!==undefined?_k:undefined,borderDashArray:(_l=options.borderDashArray)!==null&&_l!==undefined?_l:undefined,borderDashPhase:(_m=options.borderDashPhase)!==null&&_m!==undefined?_m:undefined,graphicsState:graphicsStateKey,borderLineCap:(_o=options.borderLineCap)!==null&&_o!==undefined?_o:undefined}))};PDFPage2.prototype.drawSquare=function(options){if(options===undefined){options={}}var size=options.size;assertOrUndefined(size,"size",["number"]);this.drawRectangle(__assign(__assign({},options),{width:size,height:size}))};PDFPage2.prototype.drawEllipse=function(options){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l;if(options===undefined){options={}}assertOrUndefined(options.x,"options.x",["number"]);assertOrUndefined(options.y,"options.y",["number"]);assertOrUndefined(options.xScale,"options.xScale",["number"]);assertOrUndefined(options.yScale,"options.yScale",["number"]);assertOrUndefined(options.rotate,"options.rotate",[[Object,"Rotation"]]);assertOrUndefined(options.color,"options.color",[[Object,"Color"]]);assertRangeOrUndefined(options.opacity,"opacity.opacity",0,1);assertOrUndefined(options.borderColor,"options.borderColor",[[Object,"Color"]]);assertRangeOrUndefined(options.borderOpacity,"options.borderOpacity",0,1);assertOrUndefined(options.borderWidth,"options.borderWidth",["number"]);assertOrUndefined(options.borderDashArray,"options.borderDashArray",[Array]);assertOrUndefined(options.borderDashPhase,"options.borderDashPhase",["number"]);assertIsOneOfOrUndefined(options.borderLineCap,"options.borderLineCap",LineCapStyle);assertIsOneOfOrUndefined(options.blendMode,"options.blendMode",BlendMode);var graphicsStateKey=this.maybeEmbedGraphicsState({opacity:options.opacity,borderOpacity:options.borderOpacity,blendMode:options.blendMode});if(!("color"in options)&&!("borderColor"in options)){options.color=rgb(0,0,0)}var contentStream=this.getContentStream();contentStream.push.apply(contentStream,drawEllipse({x:(_a=options.x)!==null&&_a!==undefined?_a:this.x,y:(_b=options.y)!==null&&_b!==undefined?_b:this.y,xScale:(_c=options.xScale)!==null&&_c!==undefined?_c:100,yScale:(_d=options.yScale)!==null&&_d!==undefined?_d:100,rotate:(_e=options.rotate)!==null&&_e!==undefined?_e:undefined,color:(_f=options.color)!==null&&_f!==undefined?_f:undefined,borderColor:(_g=options.borderColor)!==null&&_g!==undefined?_g:undefined,borderWidth:(_h=options.borderWidth)!==null&&_h!==undefined?_h:0,borderDashArray:(_j=options.borderDashArray)!==null&&_j!==undefined?_j:undefined,borderDashPhase:(_k=options.borderDashPhase)!==null&&_k!==undefined?_k:undefined,borderLineCap:(_l=options.borderLineCap)!==null&&_l!==undefined?_l:undefined,graphicsState:graphicsStateKey}))};PDFPage2.prototype.drawCircle=function(options){if(options===undefined){options={}}var _a=options.size,size=_a===undefined?100:_a;assertOrUndefined(size,"size",["number"]);this.drawEllipse(__assign(__assign({},options),{xScale:size,yScale:size}))};PDFPage2.prototype.setOrEmbedFont=function(font){var oldFont=this.font;var oldFontKey=this.fontKey;if(font)this.setFont(font);else this.getFont();var newFont=this.font;var newFontKey=this.fontKey;return{oldFont,oldFontKey,newFont,newFontKey}};PDFPage2.prototype.getFont=function(){if(!this.font||!this.fontKey){var font=this.doc.embedStandardFont(StandardFonts.Helvetica);this.setFont(font)}return[this.font,this.fontKey]};PDFPage2.prototype.resetFont=function(){this.font=undefined;this.fontKey=undefined};PDFPage2.prototype.getContentStream=function(useExisting){if(useExisting===undefined){useExisting=true}if(useExisting&&this.contentStream)return this.contentStream;this.contentStream=this.createContentStream();this.contentStreamRef=this.doc.context.register(this.contentStream);this.node.addContentStream(this.contentStreamRef);return this.contentStream};PDFPage2.prototype.createContentStream=function(){var operators=[];for(var _i=0;_i<arguments.length;_i++){operators[_i]=arguments[_i]}var dict=this.doc.context.obj({});var contentStream=PDFContentStream_default.of(dict,operators);return contentStream};PDFPage2.prototype.maybeEmbedGraphicsState=function(options){var{opacity,borderOpacity,blendMode}=options;if(opacity===undefined&&borderOpacity===undefined&&blendMode===undefined){return}var graphicsState=this.doc.context.obj({Type:"ExtGState",ca:opacity,CA:borderOpacity,BM:blendMode});var key=this.node.newExtGState("GS",graphicsState);return key};PDFPage2.prototype.scaleAnnot=function(annot,x,y){var selectors=["RD","CL","Vertices","QuadPoints","L","Rect"];for(var idx4=0,len3=selectors.length;idx4<len3;idx4++){var list2=annot.lookup(PDFName_default.of(selectors[idx4]));if(list2 instanceof PDFArray_default)list2.scalePDFNumbers(x,y)}var inkLists=annot.lookup(PDFName_default.of("InkList"));if(inkLists instanceof PDFArray_default){for(var idx4=0,len3=inkLists.size();idx4<len3;idx4++){var arr=inkLists.lookup(idx4);if(arr instanceof PDFArray_default)arr.scalePDFNumbers(x,y)}}};PDFPage2.of=function(leafNode,ref,doc){return new PDFPage2(leafNode,ref,doc)};PDFPage2.create=function(doc){assertIs(doc,"doc",[[PDFDocument_default,"PDFDocument"]]);var dummyRef=PDFRef_default.of(-1);var pageLeaf=PDFPageLeaf_default.withContextAndParent(doc.context,dummyRef);var pageRef=doc.context.register(pageLeaf);return new PDFPage2(pageLeaf,pageRef,doc)};return PDFPage2}();PDFPage_default=PDFPage});var PDFButton,PDFButton_default;var init_PDFButton=__esm(()=>{init_tslib_es62();init_PDFPage();init_PDFFont();init_alignment2();init_appearances();init_PDFField();init_colors();init_rotations();init_core();init_utils2();PDFButton=function(_super){__extends(PDFButton2,_super);function PDFButton2(acroPushButton,ref,doc){var _this=_super.call(this,acroPushButton,ref,doc)||this;assertIs(acroPushButton,"acroButton",[[PDFAcroPushButton_default,"PDFAcroPushButton"]]);_this.acroField=acroPushButton;return _this}PDFButton2.prototype.setImage=function(image,alignment2){if(alignment2===undefined){alignment2=ImageAlignment.Center}var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var streamRef=this.createImageAppearanceStream(widget,image,alignment2);this.updateWidgetAppearances(widget,{normal:streamRef})}this.markAsClean()};PDFButton2.prototype.setFontSize=function(fontSize){assertPositive(fontSize,"fontSize");this.acroField.setFontSize(fontSize);this.markAsDirty()};PDFButton2.prototype.addToPage=function(text4,page,options){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l;assertOrUndefined(text4,"text",["string"]);assertOrUndefined(page,"page",[[PDFPage_default,"PDFPage"]]);assertFieldAppearanceOptions(options);var widget=this.createWidget({x:((_a=options===null||options===undefined?undefined:options.x)!==null&&_a!==undefined?_a:0)-((_b=options===null||options===undefined?undefined:options.borderWidth)!==null&&_b!==undefined?_b:0)/2,y:((_c=options===null||options===undefined?undefined:options.y)!==null&&_c!==undefined?_c:0)-((_d=options===null||options===undefined?undefined:options.borderWidth)!==null&&_d!==undefined?_d:0)/2,width:(_e=options===null||options===undefined?undefined:options.width)!==null&&_e!==undefined?_e:100,height:(_f=options===null||options===undefined?undefined:options.height)!==null&&_f!==undefined?_f:50,textColor:(_g=options===null||options===undefined?undefined:options.textColor)!==null&&_g!==undefined?_g:rgb(0,0,0),backgroundColor:(_h=options===null||options===undefined?undefined:options.backgroundColor)!==null&&_h!==undefined?_h:rgb(0.75,0.75,0.75),borderColor:options===null||options===undefined?undefined:options.borderColor,borderWidth:(_j=options===null||options===undefined?undefined:options.borderWidth)!==null&&_j!==undefined?_j:0,rotate:(_k=options===null||options===undefined?undefined:options.rotate)!==null&&_k!==undefined?_k:degrees(0),caption:text4,hidden:options===null||options===undefined?undefined:options.hidden,page:page.ref});var widgetRef=this.doc.context.register(widget.dict);this.acroField.addWidget(widgetRef);var font=(_l=options===null||options===undefined?undefined:options.font)!==null&&_l!==undefined?_l:this.doc.getForm().getDefaultFont();this.updateWidgetAppearance(widget,font);page.node.addAnnot(widgetRef)};PDFButton2.prototype.needsAppearancesUpdate=function(){var _a;if(this.isDirty())return true;var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];var hasAppearances=((_a=widget.getAppearances())===null||_a===undefined?undefined:_a.normal)instanceof PDFStream_default;if(!hasAppearances)return true}return false};PDFButton2.prototype.defaultUpdateAppearances=function(font){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);this.updateAppearances(font)};PDFButton2.prototype.updateAppearances=function(font,provider2){assertIs(font,"font",[[PDFFont_default,"PDFFont"]]);assertOrUndefined(provider2,"provider",[Function]);var widgets=this.acroField.getWidgets();for(var idx4=0,len3=widgets.length;idx4<len3;idx4++){var widget=widgets[idx4];this.updateWidgetAppearance(widget,font,provider2)}};PDFButton2.prototype.updateWidgetAppearance=function(widget,font,provider2){var apProvider=provider2!==null&&provider2!==undefined?provider2:defaultButtonAppearanceProvider;var appearances=normalizeAppearance(apProvider(this,widget,font));this.updateWidgetAppearanceWithFont(widget,font,appearances)};PDFButton2.of=function(acroPushButton,ref,doc){return new PDFButton2(acroPushButton,ref,doc)};return PDFButton2}(PDFField_default);PDFButton_default=PDFButton});var init_form=__esm(()=>{init_PDFButton();init_PDFCheckBox();init_PDFDropdown();init_PDFField();init_PDFForm();init_PDFOptionList();init_PDFRadioGroup();init_PDFSignature();init_PDFTextField();init_appearances()});var init_text=__esm(()=>{init_alignment();init_layout()});var init_api=__esm(()=>{init_PDFDocument();init_PDFFont();init_PDFImage();init_PDFPage();init_PDFEmbeddedPage();init_PDFJavaScript();init_form();init_text();init_colors();init_errors3();init_image();init_objects2();init_operations();init_operators();init_rotations();init_sizes();init_PDFPageOptions();init_PDFDocumentOptions();init_StandardFonts()});var exports_es={};__export(exports_es,{waitForTick:()=>waitForTick,values:()=>values,utf8Encode:()=>utf8Encode,utf16Encode:()=>utf16Encode,utf16Decode:()=>utf16Decode,typedArrayFor:()=>typedArrayFor,translate:()=>translate,toUint8Array:()=>toUint8Array,toRadians:()=>toRadians,toHexStringOfMinLength:()=>toHexStringOfMinLength,toHexString:()=>toHexString,toDegrees:()=>toDegrees,toCodePoint:()=>toCodePoint,toCharCode:()=>toCharCode,sum:()=>sum,stroke:()=>stroke,square:()=>square,sortedUniq:()=>sortedUniq,skewRadians:()=>skewRadians,skewDegrees:()=>skewDegrees,sizeInBytes:()=>sizeInBytes,singleQuote:()=>singleQuote,showText:()=>showText,setWordSpacing:()=>setWordSpacing,setTextRise:()=>setTextRise,setTextRenderingMode:()=>setTextRenderingMode,setTextMatrix:()=>setTextMatrix,setStrokingRgbColor:()=>setStrokingRgbColor,setStrokingGrayscaleColor:()=>setStrokingGrayscaleColor,setStrokingColor:()=>setStrokingColor,setStrokingCmykColor:()=>setStrokingCmykColor,setLineWidth:()=>setLineWidth,setLineJoin:()=>setLineJoin,setLineHeight:()=>setLineHeight,setLineCap:()=>setLineCap,setGraphicsState:()=>setGraphicsState,setFontAndSize:()=>setFontAndSize,setFillingRgbColor:()=>setFillingRgbColor,setFillingGrayscaleColor:()=>setFillingGrayscaleColor,setFillingColor:()=>setFillingColor,setFillingCmykColor:()=>setFillingCmykColor,setDashPattern:()=>setDashPattern,setCharacterSqueeze:()=>setCharacterSqueeze,setCharacterSpacing:()=>setCharacterSpacing,scale:()=>scale,rotateRectangle:()=>rotateRectangle,rotateRadians:()=>rotateRadians,rotateInPlace:()=>rotateInPlace,rotateDegrees:()=>rotateDegrees,rotateAndSkewTextRadiansAndTranslate:()=>rotateAndSkewTextRadiansAndTranslate,rotateAndSkewTextDegreesAndTranslate:()=>rotateAndSkewTextDegreesAndTranslate,rgb:()=>rgb,reverseArray:()=>reverseArray,restoreDashPattern:()=>restoreDashPattern,reduceRotation:()=>reduceRotation,rectanglesAreEqual:()=>rectanglesAreEqual,rectangle:()=>rectangle,range:()=>range,radiansToDegrees:()=>radiansToDegrees,radians:()=>radians,pushGraphicsState:()=>pushGraphicsState,popGraphicsState:()=>popGraphicsState,pluckIndices:()=>pluckIndices,pdfDocEncodingDecode:()=>pdfDocEncodingDecode,parseDate:()=>parseDate,padStart:()=>padStart,numberToString:()=>numberToString,normalizeAppearance:()=>normalizeAppearance,nextLine:()=>nextLine,newlineChars:()=>newlineChars,moveTo:()=>moveTo,moveText:()=>moveText,mergeUint8Arrays:()=>mergeUint8Arrays,mergeLines:()=>mergeLines,mergeIntoTypedArray:()=>mergeIntoTypedArray,lowSurrogate:()=>lowSurrogate,lineTo:()=>lineTo,lineSplit:()=>lineSplit,layoutSinglelineText:()=>layoutSinglelineText,layoutMultilineText:()=>layoutMultilineText,layoutCombedText:()=>layoutCombedText,last:()=>last,isWithinBMP:()=>isWithinBMP,isType:()=>isType,isStandardFont:()=>isStandardFont,isNewlineChar:()=>isNewlineChar,highSurrogate:()=>highSurrogate,hasUtf16BOM:()=>hasUtf16BOM,hasSurrogates:()=>hasSurrogates,grayscale:()=>grayscale,getType:()=>getType,findLastMatch:()=>findLastMatch,fillAndStroke:()=>fillAndStroke,fill:()=>fill,escapedNewlineChars:()=>escapedNewlineChars,escapeRegExp:()=>escapeRegExp,error:()=>error,endText:()=>endText,endPath:()=>endPath,endMarkedContent:()=>endMarkedContent,encodeToBase64:()=>encodeToBase64,drawTextLines:()=>drawTextLines,drawTextField:()=>drawTextField,drawText:()=>drawText,drawSvgPath:()=>drawSvgPath,drawRectangle:()=>drawRectangle,drawRadioButton:()=>drawRadioButton,drawPage:()=>drawPage,drawOptionList:()=>drawOptionList,drawObject:()=>drawObject,drawLinesOfText:()=>drawLinesOfText,drawLine:()=>drawLine,drawImage:()=>drawImage,drawEllipsePath:()=>drawEllipsePath,drawEllipse:()=>drawEllipse,drawCheckMark:()=>drawCheckMark,drawCheckBox:()=>drawCheckBox,drawButton:()=>drawButton,degreesToRadians:()=>degreesToRadians,degrees:()=>degrees,defaultTextFieldAppearanceProvider:()=>defaultTextFieldAppearanceProvider,defaultRadioGroupAppearanceProvider:()=>defaultRadioGroupAppearanceProvider,defaultOptionListAppearanceProvider:()=>defaultOptionListAppearanceProvider,defaultDropdownAppearanceProvider:()=>defaultDropdownAppearanceProvider,defaultCheckBoxAppearanceProvider:()=>defaultCheckBoxAppearanceProvider,defaultButtonAppearanceProvider:()=>defaultButtonAppearanceProvider,decodePDFRawStream:()=>decodePDFRawStream,decodeFromBase64DataUri:()=>decodeFromBase64DataUri,decodeFromBase64:()=>decodeFromBase64,createValueErrorMsg:()=>createValueErrorMsg,createTypeErrorMsg:()=>createTypeErrorMsg,createPDFAcroFields:()=>createPDFAcroFields,createPDFAcroField:()=>createPDFAcroField,copyStringIntoBuffer:()=>copyStringIntoBuffer,concatTransformationMatrix:()=>concatTransformationMatrix,componentsToColor:()=>componentsToColor,colorToComponents:()=>colorToComponents,cmyk:()=>cmyk,closePath:()=>closePath,clipEvenOdd:()=>clipEvenOdd,clip:()=>clip,cleanText:()=>cleanText,charSplit:()=>charSplit,charFromHexCode:()=>charFromHexCode,charFromCode:()=>charFromCode,charAtIndex:()=>charAtIndex,canBeConvertedToUint8Array:()=>canBeConvertedToUint8Array,bytesFor:()=>bytesFor,byAscendingId:()=>byAscendingId,breakTextIntoLines:()=>breakTextIntoLines,beginText:()=>beginText,beginMarkedContent:()=>beginMarkedContent,backtick:()=>backtick,assertRangeOrUndefined:()=>assertRangeOrUndefined,assertRange:()=>assertRange,assertPositive:()=>assertPositive,assertOrUndefined:()=>assertOrUndefined,assertMultiple:()=>assertMultiple,assertIsSubset:()=>assertIsSubset,assertIsOneOfOrUndefined:()=>assertIsOneOfOrUndefined,assertIsOneOf:()=>assertIsOneOf,assertIs:()=>assertIs,assertInteger:()=>assertInteger,assertEachIs:()=>assertEachIs,asPDFNumber:()=>asPDFNumber,asPDFName:()=>asPDFName,asNumber:()=>asNumber,arrayAsString:()=>arrayAsString,appendQuadraticCurve:()=>appendQuadraticCurve,appendBezierCurve:()=>appendBezierCurve,adjustDimsForRotation:()=>adjustDimsForRotation,addRandomSuffix:()=>addRandomSuffix,ViewerPreferences:()=>ViewerPreferences_default,UnsupportedEncodingError:()=>UnsupportedEncodingError,UnrecognizedStreamTypeError:()=>UnrecognizedStreamTypeError,UnexpectedObjectTypeError:()=>UnexpectedObjectTypeError,UnexpectedFieldTypeError:()=>UnexpectedFieldTypeError,UnbalancedParenthesisError:()=>UnbalancedParenthesisError,TextRenderingMode:()=>TextRenderingMode,TextAlignment:()=>TextAlignment,StandardFonts:()=>StandardFonts,StandardFontValues:()=>StandardFontValues,StandardFontEmbedder:()=>StandardFontEmbedder_default,StalledParserError:()=>StalledParserError,RotationTypes:()=>RotationTypes,RichTextFieldReadError:()=>RichTextFieldReadError,ReparseError:()=>ReparseError,RemovePageFromEmptyDocumentError:()=>RemovePageFromEmptyDocumentError,ReadingDirection:()=>ReadingDirection,PrivateConstructorError:()=>PrivateConstructorError,PrintScaling:()=>PrintScaling,PngEmbedder:()=>PngEmbedder_default,ParseSpeeds:()=>ParseSpeeds,PageSizes:()=>PageSizes,PageEmbeddingMismatchedContextError:()=>PageEmbeddingMismatchedContextError,PDFXRefStreamParser:()=>PDFXRefStreamParser_default,PDFWriter:()=>PDFWriter_default,PDFWidgetAnnotation:()=>PDFWidgetAnnotation_default,PDFTrailerDict:()=>PDFTrailerDict_default,PDFTrailer:()=>PDFTrailer_default,PDFTextField:()=>PDFTextField_default,PDFString:()=>PDFString_default,PDFStreamWriter:()=>PDFStreamWriter_default,PDFStreamParsingError:()=>PDFStreamParsingError,PDFStream:()=>PDFStream_default,PDFSignature:()=>PDFSignature_default,PDFRef:()=>PDFRef_default,PDFRawStream:()=>PDFRawStream_default,PDFRadioGroup:()=>PDFRadioGroup_default,PDFParsingError:()=>PDFParsingError,PDFParser:()=>PDFParser_default,PDFPageTree:()=>PDFPageTree_default,PDFPageLeaf:()=>PDFPageLeaf_default,PDFPageEmbedder:()=>PDFPageEmbedder_default,PDFPage:()=>PDFPage_default,PDFOptionList:()=>PDFOptionList_default,PDFOperatorNames:()=>PDFOperatorNames_default,PDFOperator:()=>PDFOperator_default,PDFObjectStreamParser:()=>PDFObjectStreamParser_default,PDFObjectStream:()=>PDFObjectStream_default,PDFObjectParsingError:()=>PDFObjectParsingError,PDFObjectParser:()=>PDFObjectParser_default,PDFObjectCopier:()=>PDFObjectCopier_default,PDFObject:()=>PDFObject_default,PDFNumber:()=>PDFNumber_default,PDFNull:()=>PDFNull_default,PDFName:()=>PDFName_default,PDFJavaScript:()=>PDFJavaScript_default,PDFInvalidObjectParsingError:()=>PDFInvalidObjectParsingError,PDFInvalidObject:()=>PDFInvalidObject_default,PDFImage:()=>PDFImage_default,PDFHexString:()=>PDFHexString_default,PDFHeader:()=>PDFHeader_default,PDFForm:()=>PDFForm_default,PDFFont:()=>PDFFont_default,PDFFlateStream:()=>PDFFlateStream_default,PDFField:()=>PDFField_default,PDFEmbeddedPage:()=>PDFEmbeddedPage_default,PDFDropdown:()=>PDFDropdown_default,PDFDocument:()=>PDFDocument_default,PDFDict:()=>PDFDict_default,PDFCrossRefStream:()=>PDFCrossRefStream_default,PDFCrossRefSection:()=>PDFCrossRefSection_default,PDFContext:()=>PDFContext_default,PDFContentStream:()=>PDFContentStream_default,PDFCheckBox:()=>PDFCheckBox_default,PDFCatalog:()=>PDFCatalog_default,PDFButton:()=>PDFButton_default,PDFBool:()=>PDFBool_default,PDFArrayIsNotRectangleError:()=>PDFArrayIsNotRectangleError,PDFArray:()=>PDFArray_default,PDFAnnotation:()=>PDFAnnotation_default,PDFAcroText:()=>PDFAcroText_default,PDFAcroTerminal:()=>PDFAcroTerminal_default,PDFAcroSignature:()=>PDFAcroSignature_default,PDFAcroRadioButton:()=>PDFAcroRadioButton_default,PDFAcroPushButton:()=>PDFAcroPushButton_default,PDFAcroNonTerminal:()=>PDFAcroNonTerminal_default,PDFAcroListBox:()=>PDFAcroListBox_default,PDFAcroForm:()=>PDFAcroForm_default,PDFAcroField:()=>PDFAcroField_default,PDFAcroComboBox:()=>PDFAcroComboBox_default,PDFAcroChoice:()=>PDFAcroChoice_default,PDFAcroCheckBox:()=>PDFAcroCheckBox_default,PDFAcroButton:()=>PDFAcroButton_default,NumberParsingError:()=>NumberParsingError,NonFullScreenPageMode:()=>NonFullScreenPageMode,NoSuchFieldError:()=>NoSuchFieldError,NextByteAssertionError:()=>NextByteAssertionError,MultiSelectValueError:()=>MultiSelectValueError,MissingTfOperatorError:()=>MissingTfOperatorError,MissingPageContentsEmbeddingError:()=>MissingPageContentsEmbeddingError,MissingPDFHeaderError:()=>MissingPDFHeaderError,MissingOnValueCheckError:()=>MissingOnValueCheckError,MissingKeywordError:()=>MissingKeywordError,MissingDAEntryError:()=>MissingDAEntryError,MissingCatalogError:()=>MissingCatalogError,MethodNotImplementedError:()=>MethodNotImplementedError,LineJoinStyle:()=>LineJoinStyle,LineCapStyle:()=>LineCapStyle,JpegEmbedder:()=>JpegEmbedder_default,InvalidTargetIndexError:()=>InvalidTargetIndexError,InvalidPDFDateStringError:()=>InvalidPDFDateStringError,InvalidMaxLengthError:()=>InvalidMaxLengthError,InvalidFieldNamePartError:()=>InvalidFieldNamePartError,InvalidAcroFieldValueError:()=>InvalidAcroFieldValueError,IndexOutOfBoundsError:()=>IndexOutOfBoundsError,ImageAlignment:()=>ImageAlignment,ForeignPageError:()=>ForeignPageError,FontkitNotRegisteredError:()=>FontkitNotRegisteredError,FileEmbedder:()=>FileEmbedder_default,FieldExistsAsNonTerminalError:()=>FieldExistsAsNonTerminalError,FieldAlreadyExistsError:()=>FieldAlreadyExistsError,ExceededMaxLengthError:()=>ExceededMaxLengthError,EncryptedPDFError:()=>EncryptedPDFError,Duplex:()=>Duplex,CustomFontSubsetEmbedder:()=>CustomFontSubsetEmbedder_default,CustomFontEmbedder:()=>CustomFontEmbedder_default,CorruptPageTreeError:()=>CorruptPageTreeError,CombedTextLayoutError:()=>CombedTextLayoutError,ColorTypes:()=>ColorTypes,CharCodes:()=>CharCodes_default,Cache:()=>Cache_default,BlendMode:()=>BlendMode,AppearanceCharacteristics:()=>AppearanceCharacteristics_default,AnnotationFlags:()=>AnnotationFlags,AcroTextFlags:()=>AcroTextFlags,AcroFieldFlags:()=>AcroFieldFlags,AcroChoiceFlags:()=>AcroChoiceFlags,AcroButtonFlags:()=>AcroButtonFlags,AFRelationship:()=>AFRelationship});var init_es2=__esm(()=>{init_api();init_core();init_utils2()});function validateFileAddOptions(value){const v=serializable(value);if(!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some((k)=>!["path","name","csv"].includes(k))||typeof v.path!=="string"||!v.path||v.path!==v.path.trim()||/[\\\x00-\x1f]/.test(v.path)||v.path.split("/").some((part)=>!part||part==="."||part==="..")||/^[A-Za-z]:/.test(v.path))throw new InboxContractError("File path must be relative to the configured working root");if(v.name!==undefined&&(typeof v.name!=="string"||!v.name||v.name!==v.name.trim()||v.name.length>255||/[\x00-\x1f\x7f/\\]/.test(v.name)))throw new InboxContractError("File name must be a safe filename");if(v.csv!==undefined)validateCsvHints(v.csv);return v}function validateCsvHints(value){const v=serializable(value);if(!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some((k)=>!["encoding","delimiter","headerRow"].includes(k))||v.encoding!==undefined&&!["utf-8","windows-1252"].includes(v.encoding)||v.delimiter!==undefined&&![",",";","\t"].includes(v.delimiter)||v.headerRow!==undefined&&(!Number.isSafeInteger(v.headerRow)||v.headerRow<0))throw new InboxContractError("Invalid CSV parsing hints");return v}function csvRows(bytes,details){let decoded;try{decoded=new TextDecoder(details.encoding,{fatal:true}).decode(bytes)}catch{throw new InboxContractError("CSV does not match its encoding")}if(/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(decoded))throw new InboxContractError("CSV contains binary bytes");let rows;try{rows=parseDelimitedText(decoded,details.delimiter)}catch{throw new InboxContractError("CSV contains malformed quoted fields")}if(details.headerRow>=rows.length||rows[details.headerRow].every((cell)=>!cell.trim())||delimitedDataRowCount(rows,details.headerRow)!==details.dataRows||rows.slice(details.headerRow+1).some((row)=>row.length!==rows[details.headerRow].length))throw new InboxContractError("CSV header, column shape or row count differs from bytes");return rows}async function pdfDetails(bytes){if(!/^%PDF-(1\.[0-7]|2\.0)[\r\n]/.test(new TextDecoder().decode(bytes.slice(0,16)))||!/%%EOF\s*$/.test(new TextDecoder().decode(bytes.slice(-1024))))throw new InboxContractError("PDF signature or end marker is missing");try{const{PDFDocument:PDFDocument2}=await Promise.resolve().then(() => (init_es2(),exports_es));const pdf=await PDFDocument2.load(bytes,{updateMetadata:false,throwOnInvalidObject:true});const pages=pdf.getPages();if(!pages.length||pages.some((page)=>!Number.isFinite(page.getWidth())||!Number.isFinite(page.getHeight())||page.getWidth()<=0||page.getHeight()<=0))throw new Error("Invalid page tree");return{kind:"pdf",pages:pages.length}}catch{throw new InboxContractError("PDF bytes could not be verified")}}async function deriveInboxFile(bytes,name,csv){if(bytes.length>26214400)throw new InboxContractError("File exceeds supported size");let details={kind:"other"},mediaType="application/octet-stream";const isPdf=new TextDecoder().decode(bytes.slice(0,5))==="%PDF-";if(isPdf){if(csv)throw new InboxContractError("CSV hints do not match PDF bytes");try{details=await pdfDetails(bytes);mediaType="application/pdf"}catch{}}else if(csv||/\.csv$/i.test(name)){const hints=csv===undefined?{}:validateCsvHints(csv);let encoding=hints.encoding;if(!encoding){try{new TextDecoder("utf-8",{fatal:true}).decode(bytes);encoding="utf-8"}catch{encoding="windows-1252"}}const decoded=new TextDecoder(encoding,{fatal:true}).decode(bytes),headerRow=hints.headerRow??0;const delimiters=hints.delimiter?[hints.delimiter]:[",",";","\t"];const candidates=delimiters.flatMap((delimiter)=>{try{const rows=parseDelimitedText(decoded,delimiter);const d={kind:"csv",encoding,delimiter,headerRow,dataRows:delimitedDataRowCount(rows,headerRow)};csvRows(bytes,d);return[{details:d,width:rows[headerRow].length}]}catch{return[]}}).sort((a,b)=>b.width-a.width);if(!candidates.length||!csv&&candidates[0].width<2){if(csv)throw new InboxContractError("CSV hints do not match file bytes")}else{details=candidates[0].details;mediaType="text/csv"}}const sha2562=[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(bytes)))].map((n)=>n.toString(16).padStart(2,"0")).join("");const{id:_id,...file2}=validateInboxFile({id:crypto.randomUUID(),name,mediaType,size:bytes.length,sha256:sha2562,details});return file2}async function verifyInboxFile(bytes,value){const file2=validateInboxFile(value);const derived=await deriveInboxFile(bytes,file2.name,file2.details.kind==="csv"?{encoding:file2.details.encoding,delimiter:file2.details.delimiter,headerRow:file2.details.headerRow}:undefined);const expectedDetails=file2.details.kind==="pdf"&&file2.details.pages===undefined&&derived.details.kind==="pdf"?{kind:"pdf"}:derived.details;if(file2.sha256!==derived.sha256||file2.size!==derived.size||file2.mediaType!==derived.mediaType||JSON.stringify(file2.details)!==JSON.stringify(expectedDetails))throw new InboxContractError("Retained file integrity or type metadata changed");return file2}var init_inbox_files=__esm(()=>{init_inbox_contract()});var exports_inbox_publication_file={};__export(exports_inbox_publication_file,{readInboxPublicationFile:()=>readInboxPublicationFile});async function readInboxPublicationFile(checkout,options){const{readFile,realpath}=await import("node:fs/promises");const{isAbsolute,relative,resolve,sep}=await import("node:path");const{path}=validateFileAddOptions(options);const root=await realpath(checkout),file2=await realpath(resolve(root,path));const rel=relative(root,file2);if(rel===".."||rel.startsWith(`..${sep}`)||isAbsolute(rel))throw new Error("Inbox file escapes working root");return new Uint8Array(await readFile(file2))}var init_inbox_publication_file=__esm(()=>{init_inbox_files()});init_inbox_contract();var REPOSITORY=/^[a-z0-9][a-z0-9._/-]{0,127}$/;function validRepositoryAlias(value){return typeof value==="string"&&REPOSITORY.test(value)&&!value.includes("//")&&!value.includes("..")}var RECORD_READ_INPUT_LIMIT=1024*1024;var RECORD_CAPTURE_OUTPUT_LIMIT=25*1024*1024;function validRecordRef(value){return typeof value==="string"&&value.length<=512&&/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(value)}function validateRecordRead(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new InboxContractError("Invalid selected-record read");const input=value;if(Object.keys(input).some((key)=>!["repository","refs","atCommit"].includes(key))||!validRepositoryAlias(input.repository)||!Array.isArray(input.refs)||!input.refs.length||input.refs.length>1e4||input.refs.some((ref)=>!validRecordRef(ref))||new Set(input.refs).size!==input.refs.length||input.atCommit!==undefined&&(typeof input.atCommit!=="string"||!/^[0-9a-f]{40}$/.test(input.atCommit)))throw new InboxContractError("Invalid selected-record read");return{repository:input.repository,refs:[...input.refs],...input.atCommit===undefined?{}:{atCommit:input.atCommit}}}class FileOperationError extends Error{code;status;retryable;constructor(code,status,retryable=false){super(code);this.code=code;this.status=status;this.retryable=retryable}}var FILE_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;var FILE_ORIGINAL_MAX_BYTES=5*1024**3;function parseFileDescriptor(value){const invalid=()=>{throw new FileOperationError("unavailable",503,true)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const f=value;if(Object.keys(f).sort().join(",")!=="details,enrichments,id,mediaType,name,path,sha256,size"||typeof f.id!=="string"||!FILE_ID_PATTERN.test(f.id)||!safeFileName(f.name)||!safeFilePath(f.path)||!Number.isSafeInteger(f.size)||f.size<0||f.size>FILE_ORIGINAL_MAX_BYTES||typeof f.sha256!=="string"||!/^[0-9a-f]{64}$/.test(f.sha256)||!f.enrichments||typeof f.enrichments!=="object"||Array.isArray(f.enrichments)||!f.details||typeof f.details!=="object"||Array.isArray(f.details))return invalid();const d=f.details;if(d.kind==="other"){if(Object.keys(d).length!==1||f.mediaType!=="application/octet-stream")return invalid()}else if(d.kind==="csv"){if(Object.keys(d).sort().join(",")!=="dataRows,delimiter,encoding,headerRow,kind"||f.mediaType!=="text/csv"||!["utf-8","windows-1252"].includes(d.encoding)||![",",";","\t"].includes(d.delimiter)||!Number.isSafeInteger(d.headerRow)||d.headerRow<1||!Number.isSafeInteger(d.dataRows)||d.dataRows<0)return invalid()}else if(d.kind==="pdf"){if(f.mediaType!=="application/pdf"||Object.keys(d).some((key)=>!["kind","pages"].includes(key))||"pages"in d&&(!Number.isSafeInteger(d.pages)||d.pages<1))return invalid()}else return invalid();for(const[name,descriptor]of Object.entries(f.enrichments)){if(!safeEnrichmentName(name))return invalid();parseEnrichmentDescriptor(descriptor)}if(new TextEncoder().encode(JSON.stringify(f)).byteLength>16*1024)return invalid();return f}function parseEnrichmentDescriptor(value){const invalid=()=>{throw new FileOperationError("unavailable",503,true)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const d=value;if(Object.keys(d).sort().join(",")!=="mediaType,sha256,size"||!["application/octet-stream","text/plain","text/markdown","application/json"].includes(d.mediaType)||!Number.isSafeInteger(d.size)||d.size<0||d.size>16*1024*1024||typeof d.sha256!=="string"||!/^[0-9a-f]{64}$/.test(d.sha256))return invalid();return d}function safeEnrichmentName(value){return safeFileName(value)&&!/^original(?:\.|$)/i.test(value)}function parseFileEnrichMetadata(value,maxBytes){const invalid=()=>{throw new FileOperationError("invalid_input",400)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const d=value;if(Object.keys(d).some((key)=>!["name","size","mediaType","replace"].includes(key))||!safeEnrichmentName(d.name)||!Number.isSafeInteger(d.size)||d.size<0||d.mediaType!==undefined&&(typeof d.mediaType!=="string"||d.mediaType.length>255||/[\u0000-\u001f\u007f]/.test(d.mediaType))||d.replace!==undefined&&(typeof d.replace!=="string"||!/^[0-9a-f]{64}$/.test(d.replace)))return invalid();if(d.size>maxBytes)throw new FileOperationError("request_too_large",413);return d}function safeFileName(value){return typeof value==="string"&&value.length>0&&value.length<=255&&value===value.trim()&&value!=="."&&value!==".."&&!/[\u0000-\u001f\u007f-\u009f/\\:*?"<>|]/u.test(value)&&!/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(value)&&!/[. ]$/.test(value)&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value)}function safeFilePath(value){return typeof value==="string"&&value.length<=1024&&value.split("/").every(safeFileName)}function parseFileCreateMetadata(value,maxBytes){const invalid=()=>{throw new FileOperationError("invalid_input",400)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const input=value;if(Object.keys(input).some((key)=>!["name","path","storage","csv","inputMediaType","size","requestKey"].includes(key)))return invalid();const path=input.path===undefined?"Files":input.path;if(!safeFileName(input.name)||!safeFilePath(path)||path.split("/")[0].toLowerCase()===".os")return invalid();if(input.storage!==undefined&&input.storage!=="remote"&&input.storage!=="local")return invalid();if(input.inputMediaType!==undefined&&input.inputMediaType!=="application/pdf")return invalid();if(!Number.isSafeInteger(input.size)||input.size<0)return invalid();if(input.size>maxBytes)throw new FileOperationError("request_too_large",413);if(typeof input.requestKey!=="string"||input.requestKey.length<1||input.requestKey.length>256||input.requestKey!==input.requestKey.trim()||/[\u0000-\u001f\u007f]/.test(input.requestKey))return invalid();let csv;if(input.csv!==undefined){if(!input.csv||typeof input.csv!=="object"||Array.isArray(input.csv))return invalid();const hints=input.csv;if(Object.keys(hints).some((key)=>!["encoding","delimiter","headerRow"].includes(key)))return invalid();const encoding=hints.encoding===undefined?"utf-8":hints.encoding;const delimiter=hints.delimiter===undefined?",":hints.delimiter;const headerRow=hints.headerRow===undefined?1:hints.headerRow;if(encoding!=="utf-8"&&encoding!=="windows-1252"||![",",";","\t"].includes(delimiter)||!Number.isSafeInteger(headerRow)||headerRow<1||headerRow>1e5)return invalid();csv={encoding,delimiter,headerRow}}return{name:input.name,path,...input.storage?{storage:input.storage}:{},...input.inputMediaType==="application/pdf"?{inputMediaType:input.inputMediaType}:{},...csv?{csv}:{},size:input.size,requestKey:input.requestKey}}class AppRoutineContractError extends Error{code;constructor(code){super(code);this.code=code}}var propertyName=/^[a-z][A-Za-z0-9]*(?![\s\S])/;var stepId=/^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/;var routineName=/^[a-z0-9][a-z0-9-]{0,62}(?![\s\S])/;function isAppRoutineName(value){return typeof value==="string"&&routineName.test(value)}var owns=(value,key)=>Object.hasOwn(value,key);var invalidContract=()=>{throw new AppRoutineContractError("invalid_contract")};var invalidValue=()=>{throw new AppRoutineContractError("invalid_value")};function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)&&(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null)}function fields2(value,required,optional=[]){return required.every((key)=>owns(value,key))&&Object.keys(value).every((key)=>required.includes(key)||optional.includes(key))}function denseArray(value){return Array.isArray(value)&&Object.keys(value).length===value.length&&Array.from({length:value.length},(_,index)=>owns(value,String(index))).every(Boolean)}function parseAppRoutineContract(value){let properties=0;function schema(value2,depth=1){if(depth>8||!record(value2))return invalidContract();switch(value2.type){case"object":{if(!fields2(value2,["type","properties","additionalProperties"],["required"])||value2.additionalProperties!==false||!record(value2.properties))return invalidContract();const entries=Object.entries(value2.properties);properties+=entries.length;if(properties>64||entries.some(([key])=>!propertyName.test(key)))return invalidContract();let required;if(owns(value2,"required")){if(!denseArray(value2.required)||value2.required.some((key)=>typeof key!=="string"||!owns(value2.properties,key))||new Set(value2.required).size!==value2.required.length)return invalidContract();required=[...value2.required]}return{type:"object",properties:Object.fromEntries(entries.map(([key,child])=>[key,schema(child,depth+1)])),...required===undefined?{}:{required},additionalProperties:false}}case"array":if(!fields2(value2,["type","items","maxItems"])||!Number.isSafeInteger(value2.maxItems)||value2.maxItems<1||value2.maxItems>64)return invalidContract();return{type:"array",items:schema(value2.items,depth+1),maxItems:value2.maxItems};case"boolean":case"file":if(!fields2(value2,["type"]))return invalidContract();return{type:value2.type};case"string":if(!fields2(value2,["type"],["maxLength"])||owns(value2,"maxLength")&&(!Number.isSafeInteger(value2.maxLength)||value2.maxLength<0||value2.maxLength>4096))return invalidContract();return{type:"string",...owns(value2,"maxLength")?{maxLength:value2.maxLength}:{}};case"integer":case"number":{const validNumber=value2.type==="integer"?Number.isSafeInteger:Number.isFinite;if(!fields2(value2,["type"],["minimum","maximum"])||owns(value2,"minimum")&&!validNumber(value2.minimum)||owns(value2,"maximum")&&!validNumber(value2.maximum)||owns(value2,"minimum")&&owns(value2,"maximum")&&value2.minimum>value2.maximum)return invalidContract();return{type:value2.type,...owns(value2,"minimum")?{minimum:value2.minimum}:{},...owns(value2,"maximum")?{maximum:value2.maximum}:{}}}default:return invalidContract()}}if(!record(value)||!fields2(value,["routine","input","steps"],["result"])||!isAppRoutineName(value.routine)||!denseArray(value.steps)||value.steps.length<1||value.steps.length>64)return invalidContract();const input=schema(value.input);const result=owns(value,"result")?schema(value.result):undefined;const ids=new Set;const steps=value.steps.map((step)=>{if(!record(step)||!fields2(step,["id"],["summary"])||typeof step.id!=="string"||!stepId.test(step.id)||ids.has(step.id))return invalidContract();ids.add(step.id);return{id:step.id,...owns(step,"summary")?{summary:schema(step.summary)}:{}}});return{routine:value.routine,input,steps,...result===undefined?{}:{result}}}function jsonData(value,ancestors=new Set){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return;if(!record(value)&&!denseArray(value))return invalidValue();if(ancestors.has(value))return invalidValue();ancestors.add(value);for(const child of Object.values(value))jsonData(child,ancestors);ancestors.delete(value)}function validateRoutineSchemaValue(schema,value){switch(schema.type){case"object":if(!record(value)||(schema.required??[]).some((key)=>!owns(value,key))||Object.keys(value).some((key)=>!owns(schema.properties,key)))return invalidValue();for(const[key,child]of Object.entries(value))validateRoutineSchemaValue(schema.properties[key],child);return;case"array":if(!denseArray(value)||value.length>schema.maxItems)return invalidValue();for(const child of value)validateRoutineSchemaValue(schema.items,child);return;case"boolean":if(typeof value!=="boolean")return invalidValue();return;case"string":if(typeof value!=="string"||Array.from(value).length>(schema.maxLength??4096))return invalidValue();return;case"integer":case"number":if(typeof value!=="number"||!(schema.type==="integer"?Number.isSafeInteger(value):Number.isFinite(value))||schema.minimum!==undefined&&value<schema.minimum||schema.maximum!==undefined&&value>schema.maximum)return invalidValue();return;case"file":try{jsonData(value);parseFileDescriptor(value)}catch{return invalidValue()}}}function boundedValue(schema,value){validateRoutineSchemaValue(schema,value);if(new TextEncoder().encode(JSON.stringify(value)).byteLength>16*1024)return invalidValue()}function validateAppRoutineInput(contract,value){boundedValue(contract.input,value)}function validateAppRoutineResult(contract,value){if(contract.result===undefined){if(value!==undefined)return invalidValue()}else boundedValue(contract.result,value)}function validateAppRoutineStep(contract,id2,summary){const step=contract.steps.find((step2)=>step2.id===id2);if(!step)return invalidValue();if(step.summary===undefined){if(summary!==undefined)return invalidValue()}else validateRoutineSchemaValue(step.summary,summary)}init_inbox_contract();var ROUTINE_DECLARATION_SCHEMA="https://schemas.oddington.ai/routine/v1.json";var ROUTINE_SOURCE_LIMITS={files:20000,bytes:256*1024*1024,declarationBytes:64*1024};var invalid=(field)=>{throw new Error(`Invalid routine declaration: ${field}`)};var object2=(value,fields3,field)=>{if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).some((key)=>!fields3.includes(key)))invalid(field);return value};var routineAlias=(value)=>typeof value==="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(value);var list=(value,field,allowed)=>{if(value===undefined)return[];if(!Array.isArray(value)||value.length>64||value.some((item)=>!routineAlias(item)||allowed&&!allowed.includes(item))||new Set(value).size!==value.length)invalid(field);return[...value].sort()};function routineAssetPattern(value){return typeof value==="string"&&value.length<=512&&!value.startsWith("/")&&!value.includes("\\")&&!value.includes(":")&&value.split("/").every((part)=>!!part&&part!=="."&&part!==".."&&/^[a-zA-Z0-9_.*-]+$/.test(part))}function parseRoutineDeclaration(value){const v=object2(value,["$schema","access","runtime","retry","assets"],"fields");if(v.$schema!==ROUTINE_DECLARATION_SCHEMA)invalid("$schema");const access=object2(v.access===undefined?{}:v.access,["repositories","connections","models","files","publish"],"access");const rawRepositories=access.repositories===undefined?{}:access.repositories;const repositories=object2(rawRepositories,rawRepositories&&typeof rawRepositories==="object"?Object.keys(rawRepositories):[],"access.repositories");if(Object.keys(repositories).length>64)invalid("access.repositories");const grants={};for(const key of Object.keys(repositories).sort()){if(!routineAlias(key)||!["read","write"].includes(repositories[key]))invalid(`access.repositories.${key}`);grants[key]=repositories[key]}if(access.files!==undefined&&!["read","read-write"].includes(access.files))invalid("access.files");const runtime=object2(v.runtime===undefined?{}:v.runtime,["features","resources","maxDuration"],"runtime");if(runtime.resources!==undefined&&!["standard","large"].includes(runtime.resources))invalid("runtime.resources");const duration=runtime.maxDuration===undefined?"15m":runtime.maxDuration;if(typeof duration!=="string"||!/^(?:[1-5][0-9]|60)m$/.test(duration)||Number(duration.slice(0,-1))<15)invalid("runtime.maxDuration");const retry=object2(v.retry===undefined?{}:v.retry,["maxAttempts"],"retry");const maxAttempts=retry.maxAttempts===undefined?1:retry.maxAttempts;if(!Number.isInteger(maxAttempts)||maxAttempts<1||maxAttempts>3)invalid("retry.maxAttempts");const assets=v.assets===undefined?[]:v.assets;if(!Array.isArray(assets)||assets.length>64||assets.some((item)=>!routineAssetPattern(item))||new Set(assets).size!==assets.length)invalid("assets");return{$schema:ROUTINE_DECLARATION_SCHEMA,access:{repositories:grants,connections:list(access.connections,"access.connections"),models:list(access.models,"access.models"),...access.files===undefined?{}:{files:access.files},publish:list(access.publish,"access.publish",["asks","digests"])},runtime:{features:list(runtime.features,"runtime.features",["python","documents","browser"]),resources:runtime.resources??"standard",maxDuration:duration},retry:{maxAttempts},assets:[...assets].sort()}}var LIMIT=256*1024;var invalid2=()=>{throw new AppRoutineContractError("invalid_value")};var invalidContract2=()=>{throw new AppRoutineContractError("invalid_contract")};var empty={type:"object",properties:{},required:[],additionalProperties:false};function freeze(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))freeze(child);Object.freeze(value)}return value}function json(value,ancestors=new Set){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return;if(!value||typeof value!=="object"||ancestors.has(value))return invalid2();const array2=Array.isArray(value);if(!array2&&Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)return invalid2();const keys2=Reflect.ownKeys(value);if(array2&&(keys2.length!==value.length+1||!Array.from({length:value.length},(_,index)=>Object.hasOwn(value,index)).every(Boolean)))return invalid2();ancestors.add(value);for(const key of keys2){if(array2&&key==="length")continue;if(typeof key!=="string")return invalid2();const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor.enumerable||!Object.hasOwn(descriptor,"value"))return invalid2();json(descriptor.value,ancestors)}ancestors.delete(value)}function captureJson(value){json(value);const encoded=JSON.stringify(value);if(new TextEncoder().encode(encoded).byteLength>LIMIT)return invalid2();return freeze(JSON.parse(encoded))}function capture(schema,value){const captured=captureJson(value);validateRoutineSchemaValue(schema,captured);return captured}var schemas=new WeakMap;function nestedSchema(value){const metadata=schemaMetadata(value);if(Object.hasOwn(metadata,"default"))return invalidContract2();return metadata.schema}function schemaMetadata(value){if(!value||typeof value!=="object")return invalidContract2();const registered=schemas.get(value);if(registered)return registered;try{json(value)}catch{return invalidContract2()}return{schema:parseAppRoutineContract({routine:"definition",input:value,steps:[{id:"inspect"}]}).input}}function declaration(value,defaults){try{json(value)}catch{return invalidContract2()}const parsed=freeze(parseAppRoutineContract({routine:"definition",input:value,steps:[{id:"inspect"}]}).input);const captured=defaults?capture(parsed,defaults.value):undefined;const builder=Object.defineProperty({...parsed},"default",{value:(value2)=>declaration(parsed,{value:value2})});schemas.set(builder,{schema:parsed,...defaults?{default:captured}:{}});return Object.freeze(builder)}var schema={object(properties){return declaration({type:"object",properties:Object.fromEntries(Object.entries(properties).map(([key,value])=>[key,nestedSchema(value)])),required:Object.keys(properties),additionalProperties:false})},array(items,options){return declaration({type:"array",items:nestedSchema(items),maxItems:options.maxItems})},string(options={}){return declaration({type:"string",...options})},integer(options={}){return declaration({type:"integer",...options})},number(options={}){return declaration({type:"number",...options})},boolean(){return declaration({type:"boolean"})}};var file=()=>declaration({type:"file"});var definitions=new WeakMap;function fields3(value,allowed){if(!value||typeof value!=="object"||Object.getPrototypeOf(value)!==Object.prototype||Reflect.ownKeys(value).some((key)=>typeof key!=="string"||allowed&&!allowed.includes(key)||!Object.getOwnPropertyDescriptor(value,key).enumerable||!Object.hasOwn(Object.getOwnPropertyDescriptor(value,key),"value")))return invalidContract2()}var title=(value)=>typeof value==="string"&&value.trim().length>0&&value.length<=256;function accessMetadata(value){try{if(value!==undefined)json(value);fields3(value??{},["repositories","connections","models","files","publish"]);const access=value;const names=access?.connections??[];if(!Array.isArray(names)||names.length>64||new Set(names).size!==names.length||names.some((name)=>typeof name!=="string"||name.split("/").length!==2||name.split("/").some((part)=>!isAppRoutineName(part))))return invalidContract2();const parsed=parseRoutineDeclaration({$schema:ROUTINE_DECLARATION_SCHEMA,access:{...access,connections:[]}}).access;return freeze({...parsed,connections:[...names]})}catch{return invalidContract2()}}var defineRoutine=(definition)=>{fields3(definition,["id","title","input","steps","result","access","responses","run"]);if(!isAppRoutineName(definition.id)||definition.title!==undefined&&!title(definition.title)||typeof definition.run!=="function")return invalidContract2();const input=definition.input===undefined?{schema:empty,default:{}}:schemaMetadata(definition.input);const result=definition.result===undefined?undefined:schemaMetadata(definition.result).schema;const access=accessMetadata(definition.access);fields3(definition.steps??{});const executable=Object.fromEntries(Object.entries(definition.steps??{}).map(([id2,step])=>{fields3(step,["title","run"]);if(!title(step.title)||typeof step.run!=="function")return invalidContract2();return[id2,Object.freeze({title:step.title,run:step.run})]}));const steps=Object.entries(executable).map(([id2,step])=>({id:id2,title:step.title}));parseAppRoutineContract({routine:definition.id,input:input.schema,steps:steps.length?steps.map(({id:id2})=>({id:id2})):[{id:"inspect"}],...result?{result}:{}});const responses=[];const ids=new Set;if(definition.responses!==undefined){if(!Array.isArray(definition.responses)||definition.responses.length>64||Reflect.ownKeys(definition.responses).length!==definition.responses.length+1)return invalidContract2();for(let index=0;index<definition.responses.length;index++){const descriptor=Object.getOwnPropertyDescriptor(definition.responses,String(index));if(!descriptor||!Object.hasOwn(descriptor,"value"))return invalidContract2();const response=descriptor.value;fields3(response,["id","results","run"]);if(!isAppRoutineName(response.id)||ids.has(response.id))return invalidContract2();ids.add(response.id);if(response.results!==undefined){try{json(response.results)}catch{return invalidContract2()}}try{responses.push(defineHandler(response))}catch{return invalidContract2()}}}const contract=freeze({id:definition.id,...definition.title===undefined?{}:{title:definition.title},input:input.schema,...Object.hasOwn(input,"default")?{inputDefault:input.default}:{},access,responses:responses.map(({id:id2})=>({id:id2})),steps,...result?{result}:{}});const captured=Object.freeze({...definition,access,steps:Object.freeze(executable),responses:Object.freeze(responses),...definition.input===undefined?{}:{input:declaration(input.schema,Object.hasOwn(input,"default")?{value:input.default}:undefined)},...result===undefined?{}:{result:declaration(result)},run:(input2,os)=>executeRoutineDefinition(captured,input2,os)});definitions.set(captured,{contract,steps:executable,run:definition.run});return captured};function inspectRoutineDefinition(definition){if(!definition||typeof definition!=="object")return invalidContract2();const registered=definitions.get(definition);if(!registered)return invalidContract2();return registered.contract}function captureRoutineInput(definition,input){const contract=inspectRoutineDefinition(definition);return capture(contract.input,input===undefined&&Object.hasOwn(contract,"inputDefault")?contract.inputDefault:input)}async function executeRoutineDefinition(definition,input,runtime){const captured=captureRoutineInput(definition,input);const{contract,steps,run}=definitions.get(definition);let active=true,accepting=true,broken=false;let work=Promise.resolve();const called=new Set;const reached=new Set;const guarded=(value,receiver)=>typeof value==="function"?(...args)=>{if(!active||broken)throw new Error("Run authority ended");return guarded(Reflect.apply(value,receiver,args))}:value&&typeof value==="object"&&!(value instanceof Promise)?new Proxy({...value},{get(_target,key){return guarded(Reflect.get(value,key,value),value)}}):value;const qualify=(value)=>value.questions===undefined?value:{...value,questions:value.questions.map((question2)=>{if(!question2.handler)return question2;if(!contract.responses.some((handler)=>handler.id===question2.handler.id))return invalid2();return{...question2,handler:{...question2.handler,id:`${contract.id}/${question2.handler.id}`}}})};const os=Object.freeze({...guarded({...runtime,run:freeze({...runtime.run}),inbox:{...runtime.inbox,publishAsk:(value,options)=>runtime.inbox.publishAsk(qualify(value),options)}}),step(id2,...input2){let saved;try{if(!active||!accepting||broken||!Object.hasOwn(steps,id2)||called.has(id2)||input2.length>1)return invalid2();if(input2.length)saved=captureJson(input2[0]);called.add(id2)}catch(error){broken=true;return Promise.reject(error)}const next=work.then(async()=>{if(broken)return invalid2();reached.add(id2);try{await runtime.step(id2,{status:"running"});const output=await steps[id2].run(saved,os);fields3(output,["summary","data"]);if(!Object.hasOwn(output,"summary")||!Object.hasOwn(output,"data"))return invalid2();const summary=captureJson(output.summary),data=captureJson(output.data);await runtime.step(id2,{status:"completed",summary,data});return freeze({summary,data})}catch(error){broken=true;await runtime.step(id2,{status:"failed"});throw error}});work=next.then(()=>{},()=>{broken=true});return next}});let result,failure;try{result=await run(captured,os)}catch(error){failure=error;broken=true}accepting=false;await work;active=false;for(const step of contract.steps)if(!reached.has(step.id))await runtime.step(step.id,{status:"skipped"});if(broken)throw failure??new AppRoutineContractError("invalid_value");if(contract.result!==undefined)return capture(contract.result,result);if(result!==undefined)return invalid2();return}class DataOperationError extends Error{code;retryable;effect;component;constructor(code,retryable=false,effect,component){super(`Data operation failed: ${code}`);this.code=code;this.retryable=retryable;this.effect=effect;this.component=component;this.name="DataOperationError"}}var invalid3=()=>{throw new DataOperationError("invalid_query")};var historyText=(value)=>typeof value==="string"&&!/[\u0000\uD800-\uDFFF]/u.test(value);function historyVersion(value){return historyText(value)&&value.length>0&&new TextEncoder().encode(value).length<=1024&&!/[\u0000-\u001f\u007f-\u009f]/.test(value)&&!/^[0-9a-f]{40}$/i.test(value)}function historyProperties(value){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))return invalid3();const descriptors=Object.getOwnPropertyDescriptors(value);if(Reflect.ownKeys(value).some((key)=>typeof key!=="string"||!descriptors[key]?.enumerable||!Object.hasOwn(descriptors[key],"value")))return invalid3();return descriptors}var historyCollection=(value)=>typeof value==="string"&&value.length<=512&&/^[_a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(value);var historyCursor=(value)=>typeof value==="string"&&value.length<=128*1024&&/^history-cursor-v1\.[A-Za-z0-9_-]{1,64}\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+$/.test(value);function historyArray(value){if(!Array.isArray(value)||Object.getPrototypeOf(value)!==Array.prototype)return invalid3();const descriptors=Object.getOwnPropertyDescriptors(value);if(Reflect.ownKeys(value).length!==value.length+1)return invalid3();const result=[];for(let i=0;i<value.length;i++){const descriptor=descriptors[i];if(!descriptor?.enumerable||!Object.hasOwn(descriptor,"value"))return invalid3();result.push(descriptor.value)}return result}function captureOptions(value,changes){if(value===undefined)return{};const descriptors=historyProperties(value),result={};const allowed=changes?["collections","refs","from","through","limit","after"]:["limit","before"];if(Object.keys(descriptors).some((key)=>!allowed.includes(key)))return invalid3();for(const key of allowed){if(!Object.hasOwn(descriptors,key))continue;const scalar=descriptors[key].value;if(key==="collections"||key==="refs"){const values=historyArray(scalar);if(!values.length||values.length>(key==="collections"?16:100)||!values.every(key==="collections"?historyCollection:validRecordRef)||new Set(values).size!==values.length)return invalid3();result[key]=values}else if(key==="limit"){if(!Number.isInteger(scalar)||scalar<1||scalar>(changes?500:100))return invalid3();result.limit=scalar}else{if(!(key==="after"?historyCursor(scalar):historyVersion(scalar)))return invalid3();result[key]=scalar}}return result}var captureHistoryListOptions=(value)=>captureOptions(value,false);var captureHistoryChangesOptions=(value)=>captureOptions(value,true);function captureHistoryInstant(value){if(!historyText(value)||value.length>1024)return invalid3();const match=/^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?([Zz]|([+-])(\d{2}):(\d{2}))$/.exec(value);if(!match)return invalid3();const[year,month,day,hour,minute,second]=match.slice(1,7).map(Number);const days=new Date(Date.UTC(year,month,0));days.setUTCFullYear(year);if(year<1||month<1||month>12||day<1||day>days.getUTCDate()||hour>23||minute>59||second>59||Number(match[9]??0)>23||Number(match[10]??0)>59)return invalid3();return value}var invalid4=()=>{throw new DataOperationError("invalid_query")};function captureRecordsSearchInput(query,options){if(!historyText(query))return invalid4();const length=[...query.trim()].length;if(length<1||length>256)return invalid4();if(options===undefined)return{query};const descriptors=historyProperties(options);if(Object.keys(descriptors).some((key)=>!["collections","limit"].includes(key)))return invalid4();const captured={};if(Object.hasOwn(descriptors,"collections")){const supplied=descriptors.collections.value;if(!Array.isArray(supplied)||supplied.length<1||supplied.length>16||Reflect.ownKeys(supplied).length!==supplied.length+1)return invalid4();const collections=[];for(let index=0;index<supplied.length;index++){const descriptor=Object.getOwnPropertyDescriptor(supplied,String(index));if(!descriptor?.enumerable||!Object.hasOwn(descriptor,"value")||!historyText(descriptor.value))return invalid4();collections.push(descriptor.value)}if(new Set(collections).size!==collections.length)return invalid4();captured.collections=collections}if(Object.hasOwn(descriptors,"limit")){const supplied=descriptors.limit.value;if(!Number.isInteger(supplied)||supplied<1||supplied>100)return invalid4();captured.limit=supplied}return{query,options:captured}}var DATA_REQUEST_LIMIT=256*1024;var invalidChange=()=>{throw new DataOperationError("invalid_change",false,"unapplied")};function mapping(value){try{historyProperties(value);return value}catch{return invalidChange()}}function captureValue(value,ancestors=new Set,depth=0){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return value;if(!value||typeof value!=="object"||ancestors.has(value)||depth>32)return invalidChange();ancestors.add(value);try{if(Array.isArray(value)){if(value.length>1e5||Object.keys(value).length!==value.length||Object.getOwnPropertySymbols(value).length)return invalidChange();return Array.from(value,(item)=>captureValue(item,ancestors,depth+1))}return Object.fromEntries(Object.entries(mapping(value)).map(([key,item])=>{if(["__proto__","constructor","prototype"].includes(key))return invalidChange();return[key,captureValue(item,ancestors,depth+1)]}))}finally{ancestors.delete(value)}}function captureDataDelete(record2){const identity=mapping(record2);if(!validRecordRef(identity.$ref)||typeof identity.$version!=="string"||!identity.$version.length||identity.$version.length>512)return invalidChange();return{ref:identity.$ref,expectedVersion:identity.$version}}function captureDataUpdate(record2,set){const identity=captureDataDelete(record2),fields4=mapping(set);if(!Object.keys(fields4).length||Object.keys(fields4).some((key)=>key.startsWith("$")||["id","type"].includes(key)))return invalidChange();return{...identity,set:captureValue(fields4)}}function captureIdentities(value,update,allowEmpty=true){if(!Array.isArray(value)||!allowEmpty&&!value.length||value.length>1e4)return invalidChange();const captured=value.map((item)=>{const row=mapping(item);if(Object.keys(row).sort().join(",")!==(update?"expectedVersion,ref,set":"expectedVersion,ref"))return invalidChange();const identity={$ref:row.ref,$version:row.expectedVersion};return update?captureDataUpdate(identity,row.set):captureDataDelete(identity)});if(new Set(captured.map((item)=>item.ref)).size!==captured.length)return invalidChange();return captured}function captureDataUpdates(value,allowEmpty=false){return captureIdentities(value,true,allowEmpty)}function captureDataCreate(value){const row=mapping(value);if(!validRecordRef(row.$ref)||Object.keys(row).some((key)=>key.startsWith("$")&&!["$ref","$filing"].includes(key)))return invalidChange();const{$ref:ref,$filing,...fields4}=row;let filing;if($filing!==undefined){const components=mapping($filing);if(Object.entries(components).some(([name,value2])=>!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name)||["constructor","prototype"].includes(name)||typeof value2!=="string"||!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(value2)))return invalidChange();filing={...components}}return{ref,fields:captureValue(fields4),...filing?{filing}:{}}}function captureDataChanges(updatesValue,createsValue=[],deletesValue=[]){const updates=captureDataUpdates(updatesValue,true);if(!Array.isArray(createsValue)||createsValue.length>1e4)return invalidChange();const creates=createsValue.map((item)=>{const row=mapping(item);if(Object.keys(row).some((key)=>!["ref","fields","filing"].includes(key))||!Object.hasOwn(row,"ref")||!Object.hasOwn(row,"fields"))return invalidChange();const fields4=mapping(row.fields);if(Object.keys(fields4).some((key)=>key.startsWith("$")))return invalidChange();return captureDataCreate({...fields4,$ref:row.ref,...Object.hasOwn(row,"filing")?{$filing:row.filing}:{}})});const deletes=captureIdentities(deletesValue,false);const refs=[...updates,...creates,...deletes].map((item)=>item.ref);if(!refs.length||refs.length>1e4||new Set(refs).size!==refs.length)return invalidChange();return{updates,creates,deletes}}function checkDataRequestSize(input){if(new TextEncoder().encode(JSON.stringify(input)).byteLength>DATA_REQUEST_LIMIT)throw new DataOperationError("request_too_large",false,"unapplied")}function dataTransportError(status,value){const failures={400:["invalid_query","invalid_change"],401:["unauthenticated"],403:["access_denied"],409:["conflict","publication_pending"],413:["request_too_large"],429:["capacity"],503:["unavailable","publication_pending"]};const error=value&&typeof value==="object"&&"error"in value?value.error:undefined;const row=error&&typeof error==="object"?error:undefined;const code=failures[status]?.find((allowed)=>allowed===row?.code)??"unavailable";const effect=["unapplied","uncertain","applied"].includes(String(row?.effect))?row.effect:undefined;return new DataOperationError(code,["capacity","unavailable","publication_pending"].includes(code),code==="conflict"?"unapplied":effect,code==="invalid_change"&&typeof row?.component==="string"&&/^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/.test(row.component)?row.component:undefined)}var AUTH_ORIGIN="https://auth.oddington.ai";function oddingtonOrigin(environment=process.env){const value=environment.ODDINGTON_OS_ORIGIN??AUTH_ORIGIN;const url=new URL(value);if(url.protocol!=="https:"&&url.hostname!=="127.0.0.1")throw new Error("ODDINGTON_OS_ORIGIN must use HTTPS");return url.origin}var nodeRequest;var nodeReadable;if(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__){({request:nodeRequest}=await import("node:http"));({Readable:nodeReadable}=await import("node:stream"))}function privateRoutineRequest(environment=typeof __ODDINGTON_BROWSER__!=="undefined"&&__ODDINGTON_BROWSER__?{}:typeof process==="undefined"?{}:process.env){if(typeof __ODDINGTON_BROWSER__!=="undefined"&&__ODDINGTON_BROWSER__)return;const prepared=["ODDINGTON_ROUTINE_LOCAL","ODDINGTON_ROUTINE_LOCAL_SOCKET","ODDINGTON_ROUTINE_LOCAL_TOKEN"].some((key)=>environment[key]!==undefined);const managed=["ODDINGTON_FILES_SOCKET","ODDINGTON_FILES_TOKEN"].some((key)=>environment[key]!==undefined);if(!prepared&&!managed)return;const socket=prepared?environment.ODDINGTON_ROUTINE_LOCAL_SOCKET:environment.ODDINGTON_FILES_SOCKET;const token=prepared?environment.ODDINGTON_ROUTINE_LOCAL_TOKEN:environment.ODDINGTON_FILES_TOKEN;const request=localRoutineRequest(prepared?environment:{ODDINGTON_ROUTINE_LOCAL:"1",ODDINGTON_ROUTINE_LOCAL_SOCKET:socket,ODDINGTON_ROUTINE_LOCAL_TOKEN:token});const isCurrent=()=>prepared?environment.ODDINGTON_ROUTINE_LOCAL==="1"&&environment.ODDINGTON_ROUTINE_LOCAL_SOCKET===socket&&environment.ODDINGTON_ROUTINE_LOCAL_TOKEN===token:environment.ODDINGTON_FILES_SOCKET===socket&&environment.ODDINGTON_FILES_TOKEN===token;if(!nodeRequest||!nodeReadable)throw new Error("Files transport unavailable");const httpRequest=nodeRequest,Readable=nodeReadable;const files=async(suffix,init,signal)=>{if(!isCurrent())throw new FileOperationError("unsupported_context",400);const tcp=/^tcp:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/.exec(socket);const endpoint=tcp?{hostname:"127.0.0.1",port:Number(tcp[1])}:{socketPath:socket};const id2=crypto.randomUUID();if(init.body instanceof ReadableStream||suffix===""&&init.method==="POST"){await new Promise((resolve,reject)=>{const admission=httpRequest({...endpoint,path:"/files/admit",method:"POST",timeout:30000,signal,agent:false,headers:{...Object.fromEntries(new Headers(init.headers)),authorization:`Bearer ${token}`,"x-oddington-files-suffix":encodeURIComponent(suffix),"x-oddington-files-method":init.method??"GET"}},(response)=>{const bytes=Buffer.alloc(16384);let size=0;response.on("data",(chunk)=>{size+=chunk.length;if(size>16384)response.destroy(new Error("Files admission result exceeds supported size"));else bytes.set(chunk,size-chunk.length)});response.once("error",reject);response.once("end",()=>{if(response.statusCode===204){resolve();return}try{const value=JSON.parse(bytes.subarray(0,size).toString());const code=value?.error?.code;const status=response.statusCode??503;if(["invalid_input","request_too_large","unsupported_context","access_denied","capacity","unavailable"].includes(code))reject(new FileOperationError(code,status,code==="capacity"||code==="unavailable"));else reject(new FileOperationError("unavailable",503,true))}catch{reject(new FileOperationError("unavailable",503,true))}})});admission.once("error",()=>reject(new FileOperationError("unavailable",503,true)));admission.once("timeout",()=>admission.destroy(new Error("Files admission stalled")));admission.end()});if(!isCurrent())throw new FileOperationError("unsupported_context",400)}let cancellation;const cancelCall=()=>cancellation??=new Promise((resolve,reject)=>{const cancel=httpRequest({...endpoint,path:"/files/cancel",method:"POST",timeout:30000,headers:{authorization:`Bearer ${token}`,"x-oddington-files-call":id2}},(response)=>{response.resume();response.once("end",resolve);response.once("error",reject)});cancel.once("error",reject);cancel.once("timeout",()=>cancel.destroy(new Error("Files cancellation stalled")));cancel.end()});let pumping=Promise.resolve();let sourceReader;const result=new Promise((resolve,reject)=>{const call=httpRequest({...endpoint,path:"/files/stream",method:"POST",headers:{...Object.fromEntries(new Headers(init.headers)),authorization:`Bearer ${token}`,"x-oddington-files-call":id2,"x-oddington-files-suffix":encodeURIComponent(suffix),"x-oddington-files-method":init.method??"GET"},signal,timeout:30000,agent:false},async(response)=>{try{call.setTimeout(0);if((response.statusCode??503)>=400){await sourceReader?.cancel().catch(()=>{});call.end()}await pumping;if(!isCurrent()){response.destroy();reject(new FileOperationError("unsupported_context",400));return}const headers=new Headers;for(const[key,value]of Object.entries(response.headers))if(value!==undefined)headers.set(key,Array.isArray(value)?value.join(", "):value);const source=Readable.toWeb(response,{strategy:{highWaterMark:65536,size:(chunk)=>chunk.byteLength}});const reader=source.getReader();if(response.statusCode===204){const timer=setTimeout(()=>response.destroy(new Error("Files completion stalled")),30000);try{if(!(await reader.read()).done)throw new FileOperationError("unavailable",503,true);if(!isCurrent())throw new FileOperationError("unsupported_context",400);resolve(new Response(null,{status:204,headers}))}finally{clearTimeout(timer);reader.releaseLock()}return}let closed=false;const body=new ReadableStream({async pull(controller){let timer;try{if(!isCurrent())throw new FileOperationError("unsupported_context",400);timer=setTimeout(()=>response.destroy(new Error("Files delivery stalled")),30000);const next=await reader.read();if(closed)return;if(next.done){closed=true;reader.releaseLock();controller.close()}else controller.enqueue(next.value)}catch(error){closed=true;controller.error(error);await cancelCall().catch(()=>{});response.socket?.destroy();response.destroy();await reader.cancel(error).catch(()=>{});reader.releaseLock()}finally{clearTimeout(timer)}},async cancel(reason){closed=true;await cancelCall().catch(()=>{});response.socket?.destroy();response.destroy();call.destroy();await reader.cancel(reason).catch(()=>{});reader.releaseLock()}},{highWaterMark:0});resolve(new Response(body,{status:response.statusCode??503,headers}))}catch(error){response.destroy();reject(error instanceof FileOperationError?error:new FileOperationError("unavailable",503,true))}});call.on("error",(error)=>{cancelCall().catch(()=>{});reject(error instanceof FileOperationError?error:new FileOperationError("unavailable",503,true))});call.on("timeout",()=>call.destroy(new Error("Files I/O stalled")));call.on("information",()=>call.setTimeout(30000));if(init.body instanceof ReadableStream){call.flushHeaders();const reader=sourceReader=init.body.getReader();const abort=()=>{reader.cancel(signal.reason).catch(()=>{})};signal.addEventListener("abort",abort,{once:true});call.once("close",abort);pumping=(async()=>{try{for(;;){const next=await reader.read();if(next.done)break;if(!(next.value instanceof Uint8Array))throw new FileOperationError("invalid_input",400);if(!isCurrent())throw new FileOperationError("unsupported_context",400);for(let offset=0;offset<next.value.byteLength;offset+=262144){if(call.destroyed)throw new Error("Files parent disconnected");await new Promise((done,fail2)=>{const closed=()=>fail2(new Error("Files parent disconnected"));call.once("close",closed);call.write(next.value.subarray(offset,offset+262144),(error)=>{call.removeListener("close",closed);error?fail2(error):done()})})}}call.end()}catch(error){call.destroy(error instanceof Error?error:new Error("Files transport failed"))}finally{await reader.cancel().catch(()=>{});signal.removeEventListener("abort",abort);call.removeListener("close",abort);reader.releaseLock()}})()}else call.end(init.body===undefined?undefined:Buffer.from(init.body))});try{return await result}finally{await pumping}};return{request,files,isCurrent,identity:`private:${socket}`}}function localRoutineRequest(environment=typeof __ODDINGTON_BROWSER__!=="undefined"&&__ODDINGTON_BROWSER__?{}:typeof process==="undefined"?{}:process.env){if(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__){const{ODDINGTON_ROUTINE_LOCAL:mode,ODDINGTON_ROUTINE_LOCAL_SOCKET:socket,ODDINGTON_ROUTINE_LOCAL_TOKEN:token}=environment;if(mode===undefined&&socket===undefined&&token===undefined)return;if(mode!=="1"||!socket||!token||!/^[0-9a-f]{64}$/.test(token))throw new Error("Preparation transport unavailable; nothing can publish");const tcp=/^tcp:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/.exec(socket);const endpoint=tcp&&tcp[0]===socket&&Number(tcp[1])<=65535?{hostname:"127.0.0.1",port:Number(tcp[1])}:socket.startsWith("/")&&!socket.startsWith("//")&&!socket.includes("\x00")?{socketPath:socket}:undefined;if(!endpoint)throw new Error("Preparation transport unavailable; nothing can publish");return async(operation,input)=>{const{request}=await import("node:http");return await new Promise((resolve,reject)=>{const call=request({...endpoint,path:`/${operation}`,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${token}`},timeout:120000},(response)=>{const bytes=Buffer.alloc(33554432);let size=0;response.on("data",(chunk)=>{size+=chunk.length;if(size>33554432){response.destroy();reject(new Error("Local result exceeds supported size"))}else bytes.set(chunk,size-chunk.length)});response.on("error",reject);response.on("end",()=>{try{const result=JSON.parse(bytes.subarray(0,size).toString());if(response.statusCode!==200){if(operation==="files/request"){const error=result.error;const status=response.statusCode??503;const codes=["invalid_input","unsupported_context","unauthenticated","access_denied","request_too_large","conflict","local_only","integrity","unavailable","capacity","method_not_allowed"];if(error?.code&&codes.includes(error.code))throw new FileOperationError(error.code,status,error.code==="capacity"||error.code==="unavailable");throw new FileOperationError("unavailable",503,true)}if(operation==="data/query"){throw dataTransportError(response.statusCode??0,result)}throw new Error(typeof result.error==="string"?result.error:"Preparation failed")}resolve(result)}catch(error){reject(error)}})});call.on("error",()=>reject(operation==="data/query"?dataTransportError(503,{error:{code:"unavailable"}}):new Error("Preparation transport unavailable; nothing was published")));call.on("timeout",()=>call.destroy(new Error("Preparation timed out")));call.end(JSON.stringify(input))})}}}var installed;var ended=false;function routineTransport(){if(ended||installed&&!installed.isCurrent())throw new Error("Routine authority ended");return installed}var memberContext;function installMemberContext(resolve){memberContext=resolve;return()=>{if(memberContext===resolve)memberContext=undefined}}async function resolveAppContext(){const host=memberContext;if(!host)throw new Error("App context unavailable.");const context=await host();if(host!==memberContext||!context.isCurrent()||context.expiresAt<=Date.now()||context.kind!=="local"&&(typeof context.accessToken!=="string"||!/^[^\s]{1,8192}$/.test(context.accessToken))){throw new Error("App context unavailable.")}return context}async function resolveDataContext(){try{if(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__){const installed2=routineTransport();if(installed2)return{local:installed2.request};const local=localRoutineRequest();if(local)return{local};const managed=privateRoutineRequest();if(managed)return{local:managed.request}}const host=memberContext;if(host!==undefined){const context=await host();if(host!==memberContext||!context.isCurrent()||context.expiresAt<=Date.now())throw new Error;if(context.kind==="local")return{local:context.requestData};if(!context||!Number.isFinite(context.expiresAt)||context.expiresAt<=Date.now()||typeof context.accessToken!=="string"||!/^[^\s]{1,8192}$/.test(context.accessToken))throw new Error;return checked(context.workspace,context.endpoint,{authorization:`Bearer ${context.accessToken}`})}if(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__){const environment=typeof process==="undefined"?undefined:process.env;if(!environment||!/^[0-9a-f]{64}$/.test(environment.ODDINGTON_ROUTINE_RUN??""))throw new Error;return checked(environment.ODDINGTON_ROUTINE_WORKSPACE,oddingtonOrigin(environment),{"x-oddington-run":environment.ODDINGTON_ROUTINE_RUN})}throw new Error}catch{throw new DataOperationError("context_unavailable")}}async function resolveFilesContext(){try{const environment=typeof __ODDINGTON_BROWSER__!=="undefined"&&__ODDINGTON_BROWSER__?{}:typeof process==="undefined"?{}:process.env;if(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__){const installed2=routineTransport();if(installed2)return{url:"private:installed",headers:{},isCurrent:installed2.isCurrent,local:installed2.request,localFiles:installed2.files};const local=privateRoutineRequest(environment);if(local)return{url:local.identity,headers:{},isCurrent:local.isCurrent,local:local.request,localFiles:local.files}}const host=memberContext;if(host){const context=await host();if(context.kind==="local")throw new Error;if(!Number.isFinite(context.expiresAt)||context.expiresAt<=Date.now()||typeof context.accessToken!=="string"||!/^[^\s]{1,8192}$/.test(context.accessToken))throw new Error;return{...filesContext(context.workspace,context.endpoint,{authorization:`Bearer ${context.accessToken}`}),isCurrent:context.isCurrent,local:undefined,localFiles:undefined}}if(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__){if(!/^[0-9a-f]{64}$/.test(environment.ODDINGTON_ROUTINE_RUN??""))throw new Error;const workspace=environment.ODDINGTON_ROUTINE_WORKSPACE;return{...filesContext(workspace,`https://${workspace}.oddington.ai`,{"x-oddington-run":environment.ODDINGTON_ROUTINE_RUN}),local:undefined,localFiles:undefined}}throw new Error}catch{throw new FileOperationError("unsupported_context",400)}}function filesContext(workspace,endpoint,headers){if(!workspace||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(workspace)||workspace.length>63||["auth","www","api","os"].includes(workspace)||endpoint!==`https://${workspace}.oddington.ai`)throw new Error;return{url:`${endpoint}/api/files`,headers:{...headers,"x-oddington-workspace":workspace},isCurrent:()=>true}}function checked(workspace,endpoint,headers){if(!workspace||!/^[a-z0-9][a-z0-9-]{0,127}$/.test(workspace))throw new Error;const origin=new URL(endpoint);if(origin.protocol!=="https:"||origin.username||origin.password||origin.search||origin.hash||origin.pathname!=="/")throw new Error;return{url:`${origin.origin}/api/data`,headers:{...headers,"x-oddington-workspace":workspace}}}var data={repository(repository){async function send(input){const context=await resolveDataContext();const envelope={repository,...input};checkDataRequestSize(envelope);if("local"in context)return await context.local("data/query",envelope);try{const response=await fetch(context.url,{method:"POST",redirect:"error",cache:"no-store",headers:{"content-type":"application/json",...context.headers},body:JSON.stringify(envelope)});const result=await response.json();if(!response.ok){throw dataTransportError(response.status,result)}return result}catch(error){if(error instanceof DataOperationError)throw error;throw new DataOperationError("unavailable",true)}}return{collections:{list:()=>send({operation:"collections.list"}),schema:(name)=>send({operation:"collections.schema",name})},records:{select:(query)=>send({operation:"records.select",query}),search:async(query,options)=>send({operation:"records.search",...captureRecordsSearchInput(query,options)})},history:{list:async(options)=>send({operation:"history.list",options:captureHistoryListOptions(options)}),at:async(instant)=>send({operation:"history.at",instant:captureHistoryInstant(instant)}),changes:async(options)=>send({operation:"history.changes",options:captureHistoryChangesOptions(options)})},changes(){let updates=[],creates=[],deletes=[],publicationId;let pending,confirmed;const assertMutable=()=>{if(publicationId)throw new DataOperationError("invalid_change",false,"unapplied")};const snapshot=(nextUpdates=updates,nextCreates=creates,nextDeletes=deletes)=>{const{updates:updates2,creates:creates2,deletes:deletes2}=captureDataChanges(nextUpdates,nextCreates,nextDeletes);const input={updates:updates2,...creates2.length?{creates:creates2}:{},...deletes2.length?{deletes:deletes2}:{}};checkDataRequestSize({repository,operation:"changes.publish",...input,publicationId:publicationId??"00000000-0000-4000-8000-000000000000"});return input};return{create(record2){assertMutable();const next=[...creates,captureDataCreate(record2)];snapshot(updates,next,deletes);creates=next},update(record2,set){assertMutable();const next=[...updates,captureDataUpdate(record2,set)];snapshot(next,creates,deletes);updates=next},delete(record2){assertMutable();const next=[...deletes,captureDataDelete(record2)];snapshot(updates,creates,next);deletes=next},async validate(){await send({operation:"changes.validate",...snapshot()})},publish(){if(confirmed)return Promise.resolve(structuredClone(confirmed));if(!pending){let captured;try{captured=snapshot()}catch(error){return Promise.reject(error)}publicationId??=routineTransport()?.key("data")??crypto.randomUUID();pending=send({operation:"changes.publish",...captured,publicationId}).then((result)=>{confirmed=structuredClone(result);return result}).catch((error)=>{if(error instanceof DataOperationError)throw new DataOperationError(error.code,error.retryable,error.effect??(["unavailable","publication_pending"].includes(error.code)?"uncertain":"unapplied"),error.component);throw new DataOperationError("unavailable",true,"uncertain")}).finally(()=>{pending=undefined})}return pending.then((result)=>structuredClone(result))}}}}}};var MAX_BYTES=16*1024*1024;var PART_BYTES=8*1024*1024;var METADATA_BYTES=4096;var RESULT_BYTES=16*1024;var CONTROL_RESULT_BYTES=128*1024;var TIMEOUT_MS=30000;var MAX_ACTIVE=4;var ATTEMPTS=2;var active=0;var invalid5=()=>new FileOperationError("invalid_input",400);var unavailable=()=>new FileOperationError("unavailable",503,true);var failures={400:["invalid_input","unsupported_context"],401:["unauthenticated"],403:["access_denied"],405:["method_not_allowed"],409:["conflict","local_only"],413:["request_too_large"],429:["capacity"],503:["integrity","unavailable"]};async function boundedBytes(stream,limit){if(!stream)return new Uint8Array;const reader=stream.getReader();const bytes=new Uint8Array(limit);let size=0;try{for(;;){const{done,value}=await reader.read();if(done)break;if(!(value instanceof Uint8Array))throw invalid5();size+=value.byteLength;if(size>limit)throw new FileOperationError("request_too_large",413);bytes.set(value,size-value.byteLength)}}finally{reader.releaseLock()}return bytes.slice(0,size)}async function timed(work,parent,timeout=TIMEOUT_MS){const controller=new AbortController;let timer;let abort;const expiry=new Promise((_,reject)=>{abort=()=>{controller.abort();reject(unavailable())};timer=setTimeout(abort,timeout);parent?.addEventListener("abort",abort,{once:true});if(parent?.aborted)abort()});try{return await Promise.race([work(controller.signal),expiry])}finally{clearTimeout(timer);parent?.removeEventListener("abort",abort)}}async function result(response,maximum=RESULT_BYTES){try{const bytes=await boundedBytes(response.body,maximum);return JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes))}catch{throw unavailable()}}async function hostedContent(url,init,parent,upstream=fetch){const delivery=new AbortController;const abort=()=>delivery.abort(parent.reason);parent.addEventListener("abort",abort,{once:true});if(parent.aborted)abort();const detach=()=>parent.removeEventListener("abort",abort);try{const response=await upstream(url,{...init,signal:delivery.signal});if(delivery.signal.aborted){response.body?.cancel().catch(()=>{});throw unavailable()}if(!response.body){detach();return response}const source=response.body;let reader;let settled=false;const cancel=async(reason)=>{if(settled)return;settled=true;detach();delivery.abort(reason);try{await(reader?reader.cancel(reason):source.cancel(reason))}catch(error){if(error!==delivery.signal.reason&&!(error instanceof Error&&error.name==="AbortError"))throw error}finally{reader?.releaseLock()}};const body=new ReadableStream({async pull(controller){try{reader??=source.getReader();const{done,value}=await reader.read();if(settled)return;if(done){settled=true;detach();reader.releaseLock();controller.close()}else controller.enqueue(value)}catch(error){if(settled)return;controller.error(error);await cancel(error).catch(()=>{})}},cancel},{highWaterMark:0});const wrapped=new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers});for(const key of["url","redirected","type"])Object.defineProperty(wrapped,key,{value:response[key]});return wrapped}catch(error){detach();delivery.abort(error);throw error}}async function send(suffix,init,descriptor,initial,parent){const original=initial;const checkCurrent=(context=original)=>{if(parent?.aborted)throw unavailable();if(!original.isCurrent()||context.url!==original.url)throw new FileOperationError("unsupported_context",400)};for(let attempt=0;attempt<ATTEMPTS;attempt++){checkCurrent();const context=await resolveFilesContext();checkCurrent(context);try{const response=(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__)&&context.localFiles?await context.localFiles(suffix,init,parent):await(async()=>{const url=`${context.url}${suffix}`;const request={...init,signal:parent,headers:{...context.headers,...init.headers},redirect:"error",cache:"no-store"};return descriptor?fetch(url,request):hostedContent(url,request,parent)})();if(!response.ok){const value2=await result(response);const error=value2&&typeof value2==="object"&&"error"in value2?value2.error:undefined;const received=error&&typeof error==="object"&&"code"in error?error.code:undefined;const code=failures[response.status]?.find((code2)=>code2===received);throw code?new FileOperationError(code,response.status,code==="capacity"||code==="unavailable"):unavailable()}if(response.status!==(descriptor===204?204:200)||descriptor===204&&response.body!==null){response.body?.cancel().catch(()=>{});throw unavailable()}try{checkCurrent()}catch(error){response.body?.cancel().catch(()=>{});throw error}if(descriptor===204)return;if(!descriptor)return response;const value=await result(response,descriptor==="control"?CONTROL_RESULT_BYTES:RESULT_BYTES);if(descriptor==="control"){checkCurrent();return value}let parsed;if(descriptor==="enrichment"){if(!value||typeof value!=="object"||Array.isArray(value))throw unavailable();const{name,...metadata}=value;if(!safeEnrichmentName(name))throw unavailable();parsed={name,...parseEnrichmentDescriptor(metadata)}}else parsed=parseFileDescriptor(value);checkCurrent();return parsed}catch(error){const failure=error instanceof FileOperationError?error:unavailable();if(init.body instanceof ReadableStream||!failure.retryable||attempt+1===ATTEMPTS)throw failure}}throw unavailable()}function idPath(id2){if(typeof id2!=="string"||!FILE_ID_PATTERN.test(id2))throw invalid5();return`/${id2}`}async function multipartCreate(input,metadata,exchange,release=()=>{active--},upload){const route=upload?`${idPath(upload.file.id)}/upload/multipart`:"/multipart";let ticket;let reader;let chunk,offset=0;const receipts=[];const pending=new Set;const request=(work,timeout=TIMEOUT_MS)=>timed((signal)=>{const task=work(signal);pending.add(task);task.then(()=>pending.delete(task),()=>pending.delete(task));return task},undefined,timeout);const control=(body)=>({method:"POST",headers:{"content-type":"application/json",...ticket?{"x-oddington-transfer":ticket}:{}},body:JSON.stringify(body)});try{const start=await request((signal)=>exchange(`${route}/start`,control(upload?.file??metadata),"control",signal));if(!start||typeof start!=="object"||Array.isArray(start))throw unavailable();const session=start;if(Object.keys(session).sort().join(",")!=="partBytes,ticket"||session.partBytes!==PART_BYTES||typeof session.ticket!=="string"||!session.ticket||session.ticket.length>64*1024)throw unavailable();ticket=session.ticket;if(input.file instanceof ReadableStream)reader=input.file.getReader();let lastProgress=Date.now();const next=async()=>{try{if(Date.now()-lastProgress>=TIMEOUT_MS)throw unavailable();const value=await request(()=>reader.read(),Math.max(1,TIMEOUT_MS-(Date.now()-lastProgress)));if(value.value?.byteLength)lastProgress=Date.now();return value}catch(error){await reader.cancel(error).catch(()=>{});throw error}};for(let sent=0,partNumber=1;sent<metadata.size||metadata.size===0&&partNumber===1;partNumber++){const length=Math.min(PART_BYTES,metadata.size-sent);let part;if(input.file instanceof Uint8Array)part=input.file.subarray(sent,sent+length).slice();else if(input.file instanceof Blob){const slice=input.file.slice(sent,sent+length);part=new Uint8Array(await request(()=>slice.arrayBuffer()))}else{part=new Uint8Array(length);let filled=0;while(filled<length){if(!chunk||offset===chunk.byteLength){chunk=undefined;offset=0;const value2=await next();if(value2.done)throw invalid5();if(!(value2.value instanceof Uint8Array))throw invalid5();chunk=value2.value;if(chunk.byteLength>metadata.size-sent-filled)throw invalid5()}const take=Math.min(length-filled,chunk.byteLength-offset);part.set(chunk.subarray(offset,offset+take),filled);filled+=take;offset+=take;if(offset===chunk.byteLength){chunk=undefined;offset=0}}}if(part.byteLength!==length)throw invalid5();if(reader&&sent+length===metadata.size){lastProgress=Date.now();for(;;){const value2=await next();if(value2.done)break;if(!(value2.value instanceof Uint8Array)||value2.value.byteLength)throw invalid5()}}const value=await request((signal)=>exchange(`${route}/part`,{method:"POST",headers:{"content-type":"application/octet-stream","x-oddington-transfer":ticket,"x-oddington-part":String(partNumber)},body:part.buffer},"control",signal));part=undefined;const receipt=value;if(!receipt||typeof receipt!=="object"||Object.keys(receipt).sort().join(",")!=="etag,partNumber"||receipt.partNumber!==partNumber||typeof receipt.etag!=="string"||!receipt.etag||receipt.etag.length>256||/[\u0000-\u001f\u007f]/.test(receipt.etag))throw unavailable();receipts.push({partNumber,etag:receipt.etag});sent+=length;lastProgress=Date.now()}if(upload)for(const name of Object.keys(upload.file.enrichments)){const bytes=await request(()=>upload.enrichment(name));if(bytes.byteLength!==upload.file.enrichments[name].size||bytes.byteLength>MAX_BYTES)throw invalid5();await request((signal)=>exchange(`${route}/enrichments/${encodeURIComponent(name)}`,{method:"POST",headers:{"content-type":"application/octet-stream","x-oddington-transfer":ticket},body:bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.byteLength)},"control",signal))}await upload?.beforeComplete();const completion=control({parts:receipts});if(new TextEncoder().encode(completion.body).byteLength>128*1024)throw unavailable();return parseFileDescriptor(await request((signal)=>exchange(`${route}/complete`,completion,true,signal),TIMEOUT_MS+Math.ceil(metadata.size/(1024*1024))*1000))}catch(error){if(reader)await reader.cancel(error).catch(()=>{});if(ticket)await request((signal)=>exchange(`${route}/abort`,control({}),"control",signal)).catch(()=>{});throw error instanceof FileOperationError?error:unavailable()}finally{chunk=undefined;reader?.releaseLock();if(pending.size)Promise.allSettled([...pending]).then(release);else release()}}async function operation(work,initial,parent){const context=initial??await resolveFilesContext();if(active>=MAX_ACTIVE)throw new FileOperationError("capacity",429,true);active++;const execute=async(signal)=>{try{return await work(context,signal)}finally{active--}};if((typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__)&&context.localFiles)return execute(parent??new AbortController().signal);return timed(execute,parent).catch((error)=>{throw error instanceof FileOperationError?error:unavailable()})}function contentPath(id2,name){const path=idPath(id2);if(name===undefined)return`${path}/content`;if(!safeEnrichmentName(name))throw invalid5();return`${path}/enrichments/${encodeURIComponent(name)}/content`}async function read(id2,names){const context=await resolveFilesContext();idPath(id2);if(names===undefined||typeof names==="string"){const path=contentPath(id2,names);return operation((context2,signal)=>send(path,{method:"GET"},false,context2,signal),context)}if(!Array.isArray(names))throw invalid5();const distinct=[];const seen=new Set;for(const name of names){if(typeof name!=="string"||!safeEnrichmentName(name))throw invalid5();if(seen.has(name))continue;if(seen.size===16)throw invalid5();seen.add(name);distinct.push(name)}const paths=distinct.map((name)=>contentPath(id2,name));return timed(async(parent)=>{const responses={};try{for(let i=0;i<paths.length;i++){const response=await operation((context2,signal)=>send(paths[i],{method:"GET"},false,context2,signal),context,parent);Object.defineProperty(responses,distinct[i],{value:response,enumerable:true})}if(!context.isCurrent())throw new FileOperationError("unsupported_context",400);return responses}catch(error){for(const response of Object.values(responses))response.body?.cancel().catch(()=>{});throw error}})}var files={delete(id2){return operation((context,signal)=>send(idPath(id2),{method:"DELETE"},204,context,signal))},async upload(id2){return operation(async(context,signal)=>{const file2=await send(`${idPath(id2)}/upload`,{method:"POST"},true,context,signal);if(file2.id!==id2)throw unavailable();return file2})},async create(input,options){const context=await resolveFilesContext();if(!input||typeof input!=="object"||Array.isArray(input)||Object.keys(input).some((key)=>!["file","size","path","name","storage","csv"].includes(key))||options!==undefined&&(!options||typeof options!=="object"||Array.isArray(options)||Object.keys(options).some((key)=>key!=="requestKey")))throw invalid5();const blob=input.file instanceof Blob;const array2=input.file instanceof Uint8Array;const stream=input.file instanceof ReadableStream;if(!blob&&!array2&&!stream)throw invalid5();const intrinsic=blob?input.file.size:array2?input.file.byteLength:undefined;if(intrinsic!==undefined&&input.size!==undefined&&input.size!==intrinsic)throw invalid5();let name=input.name;if(name===undefined&&blob&&"name"in input.file&&typeof input.file.name==="string"){name=typeof globalThis.File!=="undefined"&&input.file instanceof globalThis.File?input.file.name:input.file.name.split(/[\\/]/).at(-1)}const metadata=parseFileCreateMetadata({name,size:intrinsic??input.size,path:input.path,storage:input.storage,csv:input.csv,...blob&&input.file.type==="application/pdf"?{inputMediaType:"application/pdf"}:{},requestKey:options?.requestKey===undefined?routineTransport()?.key("files")??crypto.randomUUID():options.requestKey},FILE_ORIGINAL_MAX_BYTES);if(!context.local&&metadata.storage==="local")throw new FileOperationError("unsupported_context",400);const header=encodeURIComponent(JSON.stringify(metadata));if(new TextEncoder().encode(header).byteLength>METADATA_BYTES)throw invalid5();if(active>=MAX_ACTIVE)throw new FileOperationError("capacity",429,true);active++;if((typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__)&&context.localFiles&&!routineTransport()&&metadata.size>MAX_BYTES){const controller=new AbortController;const file2=input.file;let offset=0;const body=file2 instanceof ReadableStream?file2:file2 instanceof Blob?file2.stream():new ReadableStream({pull(controller2){if(offset===file2.byteLength){controller2.close();return}const end=Math.min(offset+256*1024,file2.byteLength);controller2.enqueue(file2.subarray(offset,end));offset=end}},{highWaterMark:0});try{return await send("",{method:"POST",headers:{"content-type":"application/octet-stream","x-oddington-file":header},body},true,context,controller.signal)}finally{active--}}if(metadata.size>MAX_BYTES)return multipartCreate(input,metadata,(suffix,init,kind,signal)=>kind===true?send(suffix,init,true,context,signal):send(suffix,init,"control",context,signal));return timed(async(signal)=>{try{const bytes=array2?input.file.slice():await boundedBytes(blob?input.file.stream():input.file,metadata.size);if(bytes.byteLength!==metadata.size)throw invalid5();if(signal.aborted)throw unavailable();return await send("",{method:"POST",headers:{"content-type":"application/octet-stream","x-oddington-file":header},body:bytes.buffer},true,context,signal)}finally{active--}}).catch((error)=>{throw error instanceof FileOperationError?error:unavailable()})},async enrich(input){const context=await resolveFilesContext();if(!input||typeof input!=="object"||Array.isArray(input)||Object.keys(input).some((key)=>!["file","name","content","mediaType","replace"].includes(key))||typeof input.content!=="string"&&!(input.content instanceof Uint8Array))throw invalid5();const path=`${idPath(input.file)}/enrichments`;if(typeof input.content==="string"?input.content.length>MAX_BYTES:input.content.byteLength>MAX_BYTES)throw new FileOperationError("request_too_large",413);return operation(async(context2,signal)=>{let bytes;if(typeof input.content==="string"){const buffer=new Uint8Array(Math.min(MAX_BYTES,input.content.length*3));const encoded=new TextEncoder().encodeInto(input.content,buffer);if(encoded.read!==input.content.length)throw new FileOperationError("request_too_large",413);bytes=buffer.slice(0,encoded.written)}else bytes=input.content.slice();const metadata=parseFileEnrichMetadata({name:input.name,size:bytes.byteLength,...input.mediaType===undefined?{}:{mediaType:input.mediaType},...input.replace===undefined?{}:{replace:input.replace}},MAX_BYTES);const header=encodeURIComponent(JSON.stringify(metadata));if(new TextEncoder().encode(header).byteLength>METADATA_BYTES)throw invalid5();const result2=await send(path,{method:"POST",headers:{"content-type":"application/octet-stream","x-oddington-enrichment":header},body:bytes.buffer},"enrichment",context2,signal);if(result2.name!==metadata.name)throw unavailable();return result2},context)},async get(id2){return operation((context,signal)=>send(idPath(id2),{method:"GET"},true,context,signal))},read};function validGoogleScopes(value){return Array.isArray(value)&&value.length>0&&value.length<=32&&value.every((scope)=>typeof scope==="string"&&scope.length<=256&&/^(https:\/\/www\.googleapis\.com\/auth\/[A-Za-z0-9._-]+|https:\/\/mail\.google\.com\/|openid|email|profile)$/.test(scope))&&new Set(value).size===value.length}var ROUTINE_CONNECTION_CREDENTIALS_ENV="ODDINGTON_ROUTINE_CONNECTION_CREDENTIALS";var connectionUuid=(v)=>typeof v==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(v);function parseConnectionLease(raw,now=Date.now()){const v=raw;if(!v||typeof v!=="object"||Array.isArray(v)||!connectionUuid(v.connectionId)||!connectionUuid(v.runId)||typeof v.name!=="string"||!/^[a-z0-9][a-z0-9-]{0,62}$/.test(v.name)||typeof v.accessToken!=="string"||!/^[A-Za-z0-9._~+/-]{1,8192}={0,2}$/.test(v.accessToken))throw new Error("Invalid connection credential");if(v.provider==="gmail"){if(Object.keys(v).sort().join(",")!=="accessToken,accountEmail,connectionId,expiresAt,name,provider,runId,scopes"||typeof v.accountEmail!=="string"||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.accountEmail)||!validGoogleScopes(v.scopes)||typeof v.expiresAt!=="string"||!Number.isFinite(Date.parse(v.expiresAt))||Date.parse(v.expiresAt)<=now+60000||Date.parse(v.expiresAt)>now+3600000)throw new Error("Invalid connection credential");return v}if(v.provider==="airtable"&&Object.keys(v).sort().join(",")==="accessToken,baseId,connectionId,name,provider,runExpiresAt,runId"&&typeof v.baseId==="string"&&/^app[A-Za-z0-9]+$/.test(v.baseId)&&typeof v.runExpiresAt==="string"&&Number.isFinite(Date.parse(v.runExpiresAt))&&Date.parse(v.runExpiresAt)>now+60000&&Date.parse(v.runExpiresAt)<=now+15*60000)return v;throw new Error("Invalid connection credential")}init_inbox_contract();class AirtableOperationError extends Error{effect;receipts;constructor(message,effect="unapplied",receipts=[]){super(message);this.effect=effect;this.receipts=receipts;this.name="AirtableOperationError"}}var recordId=(v)=>typeof v==="string"&&/^rec[A-Za-z0-9]+$/.test(v);var tableId=(v)=>typeof v==="string"&&/^tbl[A-Za-z0-9]+$/.test(v);function fail2(message){throw new AirtableOperationError(message)}function object3(v){if(!v||typeof v!=="object"||Array.isArray(v)||![null,Object.prototype].includes(Object.getPrototypeOf(v)))fail2("Invalid Airtable data");return v}function keys2(v,allowed,required=allowed){if(Object.keys(v).some((k)=>!allowed.includes(k))||required.some((k)=>!Object.hasOwn(v,k)))fail2("Invalid Airtable input")}function text2(v){return typeof v==="string"&&v.length>0&&v.length<=1024}function fields4(v,nonempty=false){const result2=object3(v);if(nonempty&&!Object.keys(result2).length||Object.keys(result2).some((k)=>!text2(k)))fail2("Invalid Airtable fields");try{return serializable(result2)}catch{return fail2("Invalid Airtable fields")}}function record2(v){const r=object3(v);if(!recordId(r.id)||r.createdTime!==undefined&&(typeof r.createdTime!=="string"||!Number.isFinite(Date.parse(r.createdTime))))fail2("Malformed Airtable record");return{id:r.id,...r.createdTime===undefined?{}:{createdTime:r.createdTime},fields:fields4(r.fields)}}function equal(a,b){if(a===b)return true;if(!a||!b||typeof a!=="object"||typeof b!=="object"||Array.isArray(a)!==Array.isArray(b))return false;const left=Object.keys(a),right=Object.keys(b);return left.length===right.length&&left.every((k)=>Object.hasOwn(b,k)&&equal(a[k],b[k]))}function createConnections(transport){return{airtable(name){if(typeof name!=="string"||!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name))fail2("Invalid Airtable connection name");const call=(operation2,input)=>transport(name,operation2,input);return{tables:{list:async()=>await call("tables.list",{})},records:{list:async(input)=>await call("records.list",input),get:async(input)=>await call("records.get",input),create:async(input)=>await call("records.create",input),update:async(input)=>await call("records.update",input),delete:async(input)=>await call("records.delete",input)}}}}}async function executeAirtableOperation(authority,operation2,raw,options={}){const{name,baseId,accessToken}=authority;if(!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name)||!/^app[A-Za-z0-9]+$/.test(baseId)||!/^[A-Za-z0-9._~+/-]{1,8192}={0,2}$/.test(accessToken))fail2("Airtable connection unavailable");let input;try{input=object3(serializable(raw))}catch{return fail2("Invalid Airtable input")}const mutation=["records.create","records.update","records.delete"].includes(operation2);const receipt=(ids2)=>({provider:"airtable",connection:`airtable/${name}`,baseId,table:input.table,operation:operation2.slice(8),records:ids2.map((id2)=>({id:id2}))});async function request(path2,init={},write=false){let response;try{response=await(options.fetch??fetch)(`https://api.airtable.com/v0/${path2}`,{...init,headers:{authorization:`Bearer ${accessToken}`,"content-type":"application/json"},redirect:"manual",signal:options.signal?AbortSignal.any([options.signal,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})}catch{throw new AirtableOperationError("Airtable request acknowledgment unavailable",write?"uncertain":"unapplied")}if(!response.ok){await response.body?.cancel().catch(()=>{});throw new AirtableOperationError("Airtable request rejected",write&&(response.status>=500||response.status===408||response.status<400)?"uncertain":"unapplied")}try{if(!response.headers.get("content-type")?.toLowerCase().includes("application/json"))throw new Error;const value=object3(await response.json());const safe=serializable(value);if(Object.hasOwn(value,"error")||JSON.stringify(safe).includes(accessToken))throw new Error;return value}catch{throw new AirtableOperationError("Malformed Airtable acknowledgment",write?"uncertain":"unapplied")}}if(operation2==="tables.list"){keys2(input,[]);const tables=[],seen=new Set;let offset;do{const query2=new URLSearchParams(offset?{offset}:{});const page=await request(`meta/bases/${baseId}/tables?${query2}`);if(!Array.isArray(page.tables))fail2("Malformed Airtable tables");for(const value of page.tables){const t=object3(value);if(!tableId(t.id)||!text2(t.name)||!text2(t.primaryFieldId)||!Array.isArray(t.fields)||tables.some((existing)=>existing.id===t.id))fail2("Malformed Airtable table");const metadata=t.fields.map((value2)=>{const f=object3(value2);if(typeof f.id!=="string"||!/^fld[A-Za-z0-9]+$/.test(f.id)||!text2(f.name)||!text2(f.type))fail2("Malformed Airtable field");return{id:f.id,name:f.name,type:f.type,...f.options===undefined?{}:{options:serializable(f.options)}}});if(!metadata.some((f)=>f.id===t.primaryFieldId)||new Set(metadata.map((f)=>f.id)).size!==metadata.length)fail2("Malformed Airtable fields");tables.push({id:t.id,name:t.name,primaryFieldId:t.primaryFieldId,fields:metadata})}offset=nextOffset(page.offset,seen)}while(offset);return tables}if(!text2(input.table)||input.table==="."||input.table==="..")fail2("Invalid Airtable table");if(mutation&&!tableId(input.table))fail2("Airtable writes require a stable table ID");const path=`${baseId}/${encodeURIComponent(input.table)}`;if(operation2==="records.get"){keys2(input,["table","id"]);if(!recordId(input.id))fail2("Invalid Airtable record ID");const result3=record2(await request(`${path}/${input.id}`));if(result3.id!==input.id)fail2("Malformed Airtable record");return result3}if(operation2==="records.list"){keys2(input,["table","fields"],["table"]);if(input.fields!==undefined&&(!Array.isArray(input.fields)||!input.fields.length||input.fields.some((f)=>!text2(f))||new Set(input.fields).size!==input.fields.length))fail2("Invalid Airtable field selection");const records2=[],ids2=new Set,seen=new Set;let offset;do{const query2=new URLSearchParams;for(const field of input.fields??[])query2.append("fields[]",field);if(offset)query2.set("offset",offset);const page=await request(`${path}?${query2}`);if(!Array.isArray(page.records))fail2("Malformed Airtable records");for(const value of page.records){const r=record2(value);if(ids2.has(r.id))fail2("Malformed Airtable pagination");ids2.add(r.id);records2.push(r)}offset=nextOffset(page.offset,seen)}while(offset);return records2}if(!mutation)fail2("Unsupported Airtable operation");keys2(input,["table","records"]);if(!Array.isArray(input.records)||!input.records.length||input.records.length>10)fail2("Invalid Airtable batch");const kind=operation2.slice(8),ids=new Set;const records=input.records.map((value)=>{const r=object3(value);keys2(r,kind==="create"?["fields"]:kind==="update"?["id","expected","set"]:["id","expected"]);if(kind==="create")return{fields:fields4(r.fields,true)};if(!recordId(r.id)||ids.has(r.id))fail2("Invalid Airtable batch record ID");ids.add(r.id);const set=kind==="update"?fields4(r.set,true):undefined;if(set&&Object.values(set).some((value2)=>value2===null))fail2("Airtable guard null cannot be an update value");return{id:r.id,expected:fields4(r.expected),...set?{set}:{}}});for(const r of records){if(!("id"in r))continue;const current=record2(await request(`${path}/${r.id}`));if(current.id!==r.id)fail2("Malformed Airtable record");for(const[key,value]of Object.entries(r.expected)){if(value===null?Object.hasOwn(current.fields,key):!Object.hasOwn(current.fields,key)||!equal(current.fields[key],value))fail2("Airtable reviewed values are stale")}}await options.beforeMutation?.();const query=new URLSearchParams;if(kind==="delete")for(const id2 of ids)query.append("records[]",id2);const result2=await request(`${path}${kind==="delete"?`?${query}`:""}`,{method:kind==="create"?"POST":kind==="update"?"PATCH":"DELETE",...kind==="delete"?{}:{body:JSON.stringify({records:records.map((r)=>("id"in r)?{id:r.id,fields:r.set}:r)})}},true);const acknowledged=[],returned=[];try{if(!Array.isArray(result2.records))throw new Error;for(const value of result2.records){const r=object3(value);if(!recordId(r.id)||acknowledged.includes(r.id)||kind!=="create"&&!ids.has(r.id)||kind==="delete"&&r.deleted!==true)throw new Error;acknowledged.push(r.id);if(kind!=="delete")returned.push(record2(r))}if(acknowledged.length!==records.length)throw new Error}catch{throw new AirtableOperationError("Incomplete Airtable mutation acknowledgment",acknowledged.length?"partial":"uncertain",acknowledged.length?[receipt(acknowledged)]:[])}return{receipt:receipt(acknowledged),...kind==="delete"?{}:{records:returned}}}function nextOffset(value,seen){if(value===undefined)return;if(!text2(value)||seen.has(value))fail2("Malformed Airtable pagination");seen.add(value);return value}init_inbox_contract();var MANAGED_CONNECTION_CAPABILITY_ENV="ODDINGTON_MANAGED_CONNECTION_CAPABILITY";function managedConnections(capability){const endpoint=new URL(capability.endpoint);if(endpoint.protocol!=="http:"||endpoint.hostname!=="127.0.0.1"||!endpoint.port||endpoint.pathname!=="/"||endpoint.search||endpoint.hash||endpoint.username||endpoint.password||!/^[0-9a-f-]{36}$/.test(capability.token))throw new AirtableOperationError("Airtable capability unavailable");const transport=async(name,operation2,input)=>{let safeInput;try{safeInput=serializable(input)}catch{safeInput=null}try{const response=await fetch(new URL("airtable",endpoint),{method:"POST",redirect:"error",headers:{authorization:`Bearer ${capability.token}`,"content-type":"application/json"},body:JSON.stringify({name,operation:operation2,input:safeInput}),signal:AbortSignal.timeout(125000)});const value=await response.json();if(!response.ok)throw new AirtableOperationError("Airtable operation failed; the execution retains its evidence",value.effect==="partial"||value.effect==="uncertain"?value.effect:"unapplied",value.receipts??[]);return value}catch(error){if(error instanceof AirtableOperationError)throw error;throw new AirtableOperationError("Airtable parent acknowledgment unavailable",["records.create","records.update","records.delete"].includes(operation2)?"uncertain":"unapplied")}};return createConnections(transport)}var observer;function observeLocalRoutineEffects(value){observer=value}async function reportLocalRoutineEffect(value){await observer?.(value)}init_inbox_contract();var connections=createConnections(async(name,operation2,input)=>{try{const installed2=routineTransport();if(installed2)return await installed2.request("airtable",{name,operation:operation2,input:serializable(input)});const managed=process.env[MANAGED_CONNECTION_CAPABILITY_ENV];if(managed){const client=managedConnections(JSON.parse(managed)).airtable(name);if(operation2==="tables.list")return await client.tables.list();return await client.records[operation2.slice(8)](input)}const raw=JSON.parse(process.env[ROUTINE_CONNECTION_CREDENTIALS_ENV]??"[]");if(!Array.isArray(raw))throw new Error;const leases=raw.map((value)=>parseConnectionLease(value));if(leases.some((lease2)=>lease2.provider!=="airtable")||new Set(leases.map((lease2)=>lease2.name)).size!==leases.length)throw new Error;const lease=leases.find((lease2)=>lease2.name===name);if(!lease||lease.provider!=="airtable")throw new Error;const writing=["records.create","records.update","records.delete"].includes(operation2);const captured=serializable(input);let result2;try{result2=await executeAirtableOperation(lease,operation2,captured)}catch(error){if(writing&&error instanceof AirtableOperationError)await reportLocalRoutineEffect({type:"effect",connection:`airtable/${name}`,operation:operation2,input:captured,effect:error.effect,receipts:error.receipts});throw error}if(writing)await reportLocalRoutineEffect({type:"effect",connection:`airtable/${name}`,operation:operation2,input:captured,effect:"confirmed",receipts:[result2.receipt]});return result2}catch(error){if(error instanceof AirtableOperationError)throw error;throw new AirtableOperationError("Airtable connection unavailable")}});var LOCAL_ROUTINE_VALUE_BYTES=256*1024;if((typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__)&&typeof process!=="undefined"&&process.env.ODDINGTON_LOCAL_ROUTINE_HOST==="1"){Object.defineProperty(globalThis,Symbol.for("oddington.private.local-routine-host"),{value:async()=>{const{readSync,closeSync}=await import("node:fs");const{Socket}=await import("node:net");const{pathToFileURL}=await import("node:url");const chunks=[];let size=0;for(;;){const chunk=Buffer.alloc(4096),count=readSync(4,chunk,0,chunk.length,null);if(!count)break;if((size+=count)>524288)throw new Error("Invalid routine bootstrap");chunks.push(chunk.subarray(0,count))}closeSync(4);const bootstrap=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(Buffer.concat(chunks)));const channel=new Socket({fd:3,readable:true,writable:true});let sequence=0,broken=false,settled=false;let pending;let buffer="";const fail3=()=>{broken=true;pending?.reject();pending=undefined;channel.destroy();if(!settled){if(process.platform!=="win32"){try{process.kill(-process.pid,"SIGKILL")}catch{}}process.exit(1)}};channel.on("error",fail3);channel.on("end",fail3);channel.on("close",fail3);channel.on("data",(bytes)=>{buffer+=bytes.toString("utf8");if(Buffer.byteLength(buffer)>1024)return fail3();const end=buffer.indexOf(`
|
|
75
75
|
`);if(end<0)return;try{const ack=JSON.parse(buffer.slice(0,end));if(end!==buffer.length-1||!pending||Object.keys(ack).sort().join(",")!=="accepted,sequence"||ack.sequence!==pending.sequence||ack.accepted!==true)return fail3();buffer="";pending.resolve();pending=undefined}catch{fail3()}});const sendReport=async(value)=>{if(broken||pending)throw new Error("Routine reporting unavailable");const frame=JSON.stringify({...value,sequence:++sequence});if(Buffer.byteLength(frame)>LOCAL_ROUTINE_VALUE_BYTES+65536)throw new Error("Routine reporting unavailable");await new Promise((resolve,reject)=>{const timeout=setTimeout(fail3,30000);pending={sequence,resolve(){clearTimeout(timeout);resolve()},reject(){clearTimeout(timeout);reject(new Error("Routine reporting unavailable"))}};channel.write(`${frame}
|
|
76
|
-
`,(error)=>{if(error)fail3()})})};let reporting=Promise.resolve();const report=(value)=>{const captured=structuredClone(value);const next=reporting.then(()=>sendReport(captured));reporting=next;return next};const flush=(stream)=>new Promise((resolve)=>{let timer,settled2=false;const complete=()=>{if(settled2)return;settled2=true;if(timer)clearTimeout(timer);resolve()};timer=setTimeout(complete,1000);if(stream.destroyed||stream.writableEnded)complete();else stream.write("",complete)});let exitCode=0;try{const definition=(await import(pathToFileURL(bootstrap.entry).href)).default;const contract=inspectRoutineDefinition(definition);const input=captureRoutineInput(definition,bootstrap.input);if(bootstrap.mode==="inspect")await report({type:"contract",contract});else if(bootstrap.mode==="execute"&&typeof bootstrap.runId==="string"){if(JSON.stringify(contract)!==JSON.stringify(bootstrap.contract))throw new Error("Routine definition changed");observeLocalRoutineEffects(report);const result2=await executeRoutineDefinition(definition,input,{run:{id:bootstrap.runId},data,files,connections,inbox:routinePublicationClient(),step:async(id2,summary)=>report({type:"step",id:id2,...summary===undefined?{}:{summary}})});await report({type:"finish",...result2===undefined?{}:{result:result2}})}else throw new Error("Invalid routine bootstrap")}catch{exitCode=1}finally{settled=true;observeLocalRoutineEffects(undefined);if(exitCode===0)channel.end();else channel.destroy();await Promise.allSettled([flush(process.stdout),flush(process.stderr)]);process.exit(exitCode)}}})}init_inbox_contract();var RECORD_WRITE_INPUT_LIMIT=8*1024*1024;class RoutineRecordWriteError extends Error{effect;constructor(message,effect){super(message);this.effect=effect;this.name="RoutineRecordWriteError"}}function validateRecordWrite(value){const input=serializable(value);if(!input||Array.isArray(input)||typeof input!=="object"||Object.keys(input).sort().join(",")!=="records,repository"||!validRepositoryAlias(input.repository)||!Array.isArray(input.records)||!input.records.length||input.records.length>1e4||new Set(input.records.map((edit)=>edit?.ref)).size!==input.records.length)throw new InboxContractError("Invalid record update batch");for(const edit of input.records){if(!edit||Array.isArray(edit)||typeof edit!=="object"||!validRecordRef(edit.ref))throw new InboxContractError("Invalid record edit");if("expectedVersion"in edit){if(Object.keys(edit).sort().join(",")!=="expectedVersion,ref,set"||typeof edit.expectedVersion!=="string"||!/^record-v1:[0-9a-f]{64}$/.test(edit.expectedVersion)||!edit.set||Array.isArray(edit.set)||typeof edit.set!=="object"||!Object.keys(edit.set).length)throw new InboxContractError("Invalid record edit");continue}if(Object.keys(edit).sort().join(",")!=="fields,path,ref"||typeof edit.path!=="string"||!validCreatePath(edit.path)||!edit.fields||Array.isArray(edit.fields)||typeof edit.fields!=="object"||!Object.keys(edit.fields).length)throw new InboxContractError("Invalid record creation")}return structuredClone(input)}function validateRecordUpdate(value){const input=validateRecordWrite(value);if(input.records.some((record3)=>!("expectedVersion"in record3)))throw new InboxContractError("Record creation is unavailable for this operation");return input}function validateRecordDelete(value){const input=serializable(value);if(!input||Array.isArray(input)||typeof input!=="object"||Object.keys(input).sort().join(",")!=="records,repository"||!validRepositoryAlias(input.repository)||!Array.isArray(input.records)||!input.records.length||input.records.length>1e4||new Set(input.records.map((record3)=>record3?.ref)).size!==input.records.length)throw new InboxContractError("Invalid record deletion batch");for(const record3 of input.records){if(!record3||Array.isArray(record3)||typeof record3!=="object"||Object.keys(record3).sort().join(",")!=="expectedVersion,ref"||!validRecordRef(record3.ref)||typeof record3.expectedVersion!=="string"||!/^record-v1:[0-9a-f]{64}$/.test(record3.expectedVersion))throw new InboxContractError("Invalid record deletion")}return structuredClone(input)}function validateRecordChange(value){const input=serializable(value);if(!input||Array.isArray(input)||typeof input!=="object"||Object.keys(input).sort().join(",")!=="records,repository"||!validRepositoryAlias(input.repository)||!Array.isArray(input.records)||!input.records.length||input.records.length>1e4||new Set(input.records.map((record3)=>record3?.ref)).size!==input.records.length||new TextEncoder().encode(JSON.stringify(input)).byteLength>RECORD_WRITE_INPUT_LIMIT)throw new InboxContractError("Invalid record change batch");const writes=[],deletes=[];for(const record3 of input.records){if(!record3||typeof record3!=="object"||Array.isArray(record3))throw new InboxContractError("Invalid record change");if("set"in record3||"fields"in record3)writes.push(record3);else deletes.push(record3)}if(writes.length)validateRecordWrite({repository:input.repository,records:writes});if(deletes.length)validateRecordDelete({repository:input.repository,records:deletes});return structuredClone(input)}function validateRoutineRecordWrite(value){const body=serializable(value);if(!body||typeof body!=="object"||Array.isArray(body)||Object.keys(body).sort().join(",")!=="input,requestKey"||typeof body.requestKey!=="string"||!body.requestKey.trim()||body.requestKey!==body.requestKey.trim()||body.requestKey.length>512)throw new InboxContractError("A stable routine request key is required");return{input:validateRecordChange(body.input),requestKey:body.requestKey}}function validCreatePath(value){return value===value.trim()&&value.endsWith(".md")&&!value.startsWith("/")&&value.split("/").every((segment)=>!!segment&&![".",".."].includes(segment)&&/^[a-zA-Z0-9_.-]+$/.test(segment))}class InboxOperationError extends Error{status;reason;constructor(status,reason){super(reason==="conflict"?"This question already has an accepted answer":reason==="unavailable"?"Inbox request unavailable. Retry the same action.":reason==="invalid_input"?"Invalid Inbox request":"Inbox access unavailable");this.status=status;this.reason=reason}}var INBOX_RESULT_BYTES=8*1024*1024;var INBOX_INPUT_BYTES=8192;var INBOX_LOCAL_INPUT_BYTES=256*1024;var INBOX_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function isAppQuestionOperation(operation2){return operation2==="questions.list"||operation2==="questions.answer"||operation2==="questions.searchRecords"}var operations={current:[],"items.list":[],"questions.list":[],"items.read":["itemId"],"items.see":["itemId"],"items.markDigestRead":["itemId"],"items.rename":["itemId","revision","title"],"items.setLifecycle":["itemId","revision","lifecycle"],"items.listRecipientCandidates":["itemId"],"items.addRecipient":["itemId","personId"],"questions.answer":["itemId","revision","questionId","response"],"questions.searchRecords":["itemId","revision","questionId","query"],"files.read":["itemId","fileId"]};function assert(value){if(!value)throw new Error("Invalid Inbox result")}function object3(value){assert(value&&typeof value==="object"&&!Array.isArray(value)&&[Object.prototype,null].includes(Object.getPrototypeOf(value))&&Reflect.ownKeys(value).every((key)=>{const descriptor=typeof key==="string"?Object.getOwnPropertyDescriptor(value,key):undefined;return!!descriptor?.enumerable&&"value"in descriptor}));return value}function keys3(value,allowed,required=allowed){assert(Object.keys(value).every((key)=>allowed.includes(key))&&required.every((key)=>Object.hasOwn(value,key)))}function text3(value,empty2=false){return typeof value==="string"&&(empty2||!!value.trim())}function id2(value){return typeof value==="string"&&INBOX_UUID.test(value)}function integer(value,minimum=1){return Number.isSafeInteger(value)&&Number(value)>=minimum}function date(value){return text3(value)&&Number.isFinite(Date.parse(value))}function optionalDate(value){return value===null||date(value)}function array2(value){assert(Array.isArray(value)&&Object.getPrototypeOf(value)===Array.prototype&&Reflect.ownKeys(value).length===value.length+1&&value.every((_entry,index)=>{const descriptor=Object.getOwnPropertyDescriptor(value,String(index));return!!descriptor?.enumerable&&"value"in descriptor}));return value}function json2(value,ancestors=new Set){if(value===null||typeof value==="boolean"||typeof value==="string"||typeof value==="number"&&Number.isFinite(value))return value;assert(value&&typeof value==="object"&&!ancestors.has(value));ancestors.add(value);try{if(Array.isArray(value))return array2(value).map((entry)=>json2(entry,ancestors));return Object.fromEntries(Object.entries(object3(value)).map(([key,entry])=>[key,json2(entry,ancestors)]))}finally{ancestors.delete(value)}}function recordReference(value){const record3=object3(value);keys3(record3,["repository","ref"]);assert(text3(record3.repository)&&record3.repository===record3.repository.trim()&&/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(record3.repository)&&!/\.\.|\/\//.test(record3.repository)&&text3(record3.ref)&&record3.ref===record3.ref.trim()&&record3.ref.length<=512&&/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(record3.ref));return record3}function responseDefinition(value){const definition=object3(value);keys3(definition,["type","source"]);assert(definition.type==="selection");const source=object3(definition.source);if(source.type==="authored"){keys3(source,["type","options","suggestions","search"],["type","options"]);const options=array2(source.options);assert(options.length>0);const values=options.map((value2)=>{const option=object3(value2);keys3(option,["value","label","description","note"],["value","label"]);assert(text3(option.value)&&option.value===option.value.trim()&&text3(option.label));if("description"in option)assert(text3(option.description));if("note"in option){const note=object3(option.note);keys3(note,["placeholder"]);assert(text3(note.placeholder))}return option.value});assert(new Set(values).size===values.length);if("search"in source||"suggestions"in source){const search=object3(source.search);keys3(search,["triggerLabel","placeholder","emptyLabel"]);assert(text3(search.triggerLabel)&&text3(search.placeholder)&&text3(search.emptyLabel));const suggestions2=array2(source.suggestions);assert(suggestions2.length<=8&&suggestions2.every((value2)=>text3(value2)&&values.includes(value2))&&new Set(suggestions2).size===suggestions2.length)}else assert(options.length<=9);return}assert(source.type==="records");keys3(source,["type","collection","refPrefix","where","display","suggestions"],["type","collection","display"]);const collection=object3(source.collection);keys3(collection,["repository","name"]);recordReference({repository:collection.repository,ref:"records/example"});assert(text3(collection.name)&&/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(collection.name));if("refPrefix"in source)assert(text3(source.refPrefix)&&source.refPrefix.length<=512&&/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)*\/$/.test(source.refPrefix));const where=object3(source.where??{});assert(Object.entries(where).every(([name,value2])=>/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name)&&!["constructor","prototype"].includes(name)&&(value2===null||typeof value2==="string"||typeof value2==="boolean"||typeof value2==="number"&&Number.isFinite(value2))));const display=object3(source.display);keys3(display,["labelFields"]);const labels=array2(display.labelFields);assert(labels.length>0&&labels.length<=2&&new Set(labels).size===labels.length&&labels.every((value2)=>text3(value2)&&/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(value2)));const suggestions=array2(source.suggestions??[]);const refs=suggestions.map((value2)=>{const suggestion=object3(value2);keys3(suggestion,["record","reason"],["record"]);const record3=recordReference(suggestion.record);assert(record3.repository===collection.repository);if("reason"in suggestion)assert(text3(suggestion.reason));return record3.ref});assert(suggestions.length<=8&&new Set(refs).size===refs.length)}function inboxFile(value){const file2=object3(value);keys3(file2,["id","name","mediaType","size","sha256","details"]);assert(id2(file2.id)&&text3(file2.name)&&!/[\x00-\x1f\x7f/\\]/.test(file2.name)&&text3(file2.mediaType)&&/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(file2.mediaType)&&integer(file2.size,0)&&file2.size<=25*1024*1024&&typeof file2.sha256==="string"&&/^[0-9a-f]{64}$/.test(file2.sha256));const details=object3(file2.details);if(details.kind==="csv"){keys3(details,["kind","encoding","delimiter","headerRow","dataRows"]);assert(file2.mediaType==="text/csv"&&["utf-8","windows-1252"].includes(String(details.encoding))&&[",",";","\t"].includes(String(details.delimiter))&&integer(details.headerRow,0)&&integer(details.dataRows,0))}else if(details.kind==="pdf"){keys3(details,["kind","pages"],["kind"]);assert(file2.mediaType==="application/pdf"&&(!("pages"in details)||integer(details.pages)))}else{keys3(details,["kind"]);assert(details.kind==="other"&&!["text/csv","application/pdf"].includes(file2.mediaType))}}function fields4(value){const labels=array2(value).map((value2)=>{const field=object3(value2);keys3(field,["label","value"]);assert(text3(field.label)&&text3(field.value));return field.label});assert(new Set(labels).size===labels.length)}function block(value){const entry=object3(value);if(entry.kind==="rich-text"){keys3(entry,["kind","markdown"]);assert(text3(entry.markdown));return}if(entry.kind==="asks"){keys3(entry,["kind","problem","asks"]);const asks=array2(entry.asks);assert(text3(entry.problem)&&asks.length>0&&asks.every(id2)&&new Set(asks).size===asks.length);return}assert(["record","records","files"].includes(String(entry.kind)));keys3(entry,["kind","label","initiallyExpanded",...entry.kind==="record"?["record","view"]:entry.kind==="records"?["records","view"]:["files"]],["kind","label",entry.kind==="record"?"record":entry.kind==="records"?"records":"files"]);assert(text3(entry.label)&&(!("initiallyExpanded"in entry)||typeof entry.initiallyExpanded==="boolean")&&(!("view"in entry)||text3(entry.view)&&entry.view===entry.view.trim()));if(entry.kind==="record"){const record3=object3(entry.record);keys3(record3,["ref","title","fields"]);assert(text3(record3.ref)&&record3.ref===record3.ref.trim()&&text3(record3.title));fields4(record3.fields);return}if(entry.kind==="records"){const records=array2(entry.records);const refs=records.map((value2)=>{const record3=object3(value2);keys3(record3,["ref","title","description","facts","view"],["ref","title"]);assert(text3(record3.ref)&&record3.ref===record3.ref.trim()&&text3(record3.title));if("description"in record3)assert(text3(record3.description));if("facts"in record3)fields4(record3.facts);if("view"in record3)assert(text3(record3.view)&&record3.view===record3.view.trim());return record3.ref});assert(records.length>0&&new Set(refs).size===refs.length);return}const files2=array2(entry.files);files2.forEach(inboxFile);assert(files2.length>0&&new Set(files2.map((value2)=>object3(value2).id)).size===files2.length)}function response(value){const answer=object3(value);assert(Object.keys(answer).every((key)=>["selection","note"].includes(key)));if(typeof answer.selection==="string")assert(text3(answer.selection)&&answer.selection===answer.selection.trim());else recordReference(answer.selection);if(Object.hasOwn(answer,"note"))assert(text3(answer.note));return answer}function parseInboxRequest(value){try{const envelope=object3(value);assert(Object.keys(envelope).sort().join(",")==="input,operation");assert(typeof envelope.operation==="string"&&Object.hasOwn(operations,envelope.operation));const operation2=envelope.operation;const input=object3(envelope.input);const required=operations[operation2];assert(required.every((key)=>Object.hasOwn(input,key))&&Object.keys(input).every((key)=>required.includes(key)||operation2==="questions.searchRecords"&&key==="selected"||(operation2==="items.list"||operation2==="questions.list")&&key==="beforeNumber"));for(const key of["itemId","personId","fileId"])if(key in input)assert(id2(input[key]));if("revision"in input)assert(integer(input.revision));if("beforeNumber"in input)assert(integer(input.beforeNumber));if("questionId"in input)assert(text3(input.questionId)&&input.questionId===input.questionId.trim());if("title"in input)assert(text3(input.title));if("lifecycle"in input)assert(input.lifecycle==="open"||input.lifecycle==="closed");if("query"in input)assert(text3(input.query,true)&&input.query.length<=256);if("selected"in input)recordReference(input.selected);if("response"in input)response(input.response);assert(new TextEncoder().encode(JSON.stringify(envelope)).byteLength<=INBOX_INPUT_BYTES);return{operation:operation2,input}}catch{throw new InboxOperationError(400,"invalid_input")}}function parseInboxCurrent(value){const current=object3(value),workspace=object3(current.workspace),viewer=object3(current.viewer);assert(id2(workspace.id)&&text3(workspace.slug)&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(workspace.slug)&&text3(workspace.name)&&text3(workspace.locale)&&text3(workspace.timezone));assert(id2(viewer.id)&&text3(viewer.name)&&text3(viewer.email));return{workspace:{id:workspace.id,slug:workspace.slug,name:workspace.name,locale:workspace.locale,timezone:workspace.timezone},viewer:{id:viewer.id,name:viewer.name,email:viewer.email}}}function parseInboxItem(value){const item=object3(json2(value));assert(id2(item.id)&&id2(item.workspaceId)&&integer(item.number)&&integer(item.revision)&&integer(item.activityVersion,0)&&["ask","digest"].includes(String(item.kind))&&["open","closed"].includes(String(item.lifecycle))&&text3(item.title)&&text3(item.description,true)&&text3(item.author)&&date(item.publishedAt)&&optionalDate(item.seenAt)&&optionalDate(item.digestReadAt));if(item.outcome!==null)assert(text3(object3(item.outcome).outcome));array2(item.body).forEach(block);array2(item.views).forEach((value2)=>{const view=object3(value2);assert(text3(view.id)&&text3(view.view)&&text3(view.implementation));json2(view.input)});array2(item.people).forEach((value2)=>{const person=object3(value2);assert(id2(person.id)&&text3(person.name))});array2(item.questions).forEach((value2)=>{const question2=object3(value2);assert(text3(question2.id)&&id2(question2.to)&&text3(question2.prompt)&&(question2.instructions===null||text3(question2.instructions,true))&&typeof question2.available==="boolean");responseDefinition(question2.response);assert(array2(question2.allowedResponders).every(id2));if(question2.acceptedResponse!==null){const accepted=object3(question2.acceptedResponse);assert(id2(accepted.id)&&id2(accepted.userId)&&date(accepted.acceptedAt));response(accepted.response);if(accepted.label===null)delete accepted.label;else if("label"in accepted)assert(text3(accepted.label));if("acceptanceOrder"in accepted)assert(integer(accepted.acceptanceOrder))}if(question2.execution!==null){const execution=object3(question2.execution);assert(id2(execution.id)&&["pending","running","completed","failed"].includes(String(execution.state))&&integer(execution.attempt,0));if("consequence"in execution){const consequence=object3(execution.consequence);assert(["pending","running","applied","no-write","stopped","partial","uncertain"].includes(String(consequence.state))&&(consequence.phase===null||["loading","invoking","committing"].includes(String(consequence.phase)))&&date(consequence.updatedAt)&&typeof consequence.needsReconciliation==="boolean"&&(consequence.reason===null||text3(consequence.reason,true)));array2(consequence.evidence).forEach((value3)=>{const receipt=object3(value3);assert(text3(receipt.repository)&&text3(receipt.commit)&&text3(receipt.diff,true))})}}});array2(item.linkedAsks).forEach((value2)=>{const linked=object3(value2);assert(id2(linked.id));if(linked.state==="unavailable")assert(typeof linked.done==="boolean");else{assert(["yours","done","open","theirs"].includes(String(linked.state))&&text3(linked.title));if(linked.state==="theirs"){const assignee=object3(linked.assignee);assert(id2(assignee.id)&&text3(assignee.name))}}});array2(item.activity).forEach((value2)=>{const event=object3(value2);assert(integer(event.id)&&text3(event.type)&&(event.actorId===null||id2(event.actorId))&&(event.questionId===null||text3(event.questionId))&&integer(event.revision)&&date(event.createdAt));object3(event.data)});array2(item.work).forEach((value2)=>{const work=object3(value2);assert(id2(work.id)&&text3(work.questionId)&&text3(work.reason)&&optionalDate(work.settledAt))});return item}function parseAnswerableQuestion(value){const entry=object3(json2(value));keys3(entry,["item","origin","question","recordRefs"]);const item=object3(entry.item);keys3(item,["id","number","revision","title","href"]);assert(id2(item.id)&&integer(item.number)&&integer(item.revision)&&text3(item.title)&&text3(item.href));const link=new URL(item.href);const slug=link.hostname.slice(0,-".oddington.ai".length);assert(link.hostname.endsWith(".oddington.ai")&&slug.length<=63&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)&&!["auth","www","api","os"].includes(slug)&&item.href===`https://${slug}.oddington.ai/inbox/${item.id}`);const origin=object3(entry.origin);keys3(origin,["routine"]);assert(text3(origin.routine)&&origin.routine===origin.routine.trim());const question2=object3(entry.question);keys3(question2,["id","prompt","instructions","response"]);assert(text3(question2.id)&&question2.id===question2.id.trim()&&text3(question2.prompt)&&(question2.instructions===null||text3(question2.instructions,true)));responseDefinition(question2.response);const refs=array2(entry.recordRefs);assert(refs.every((ref)=>text3(ref)&&ref===ref.trim())&&new Set(refs).size===refs.length);return entry}function parseInboxAcceptance(value){const accepted=object3(value);assert(id2(accepted.responseId)&&date(accepted.acceptedAt));if("executionId"in accepted)assert(id2(accepted.executionId));if("acceptanceOrder"in accepted)assert(integer(accepted.acceptanceOrder));if("label"in accepted)assert(text3(accepted.label));return accepted}function parseInboxResult(operation2,value){if(operation2==="current")return parseInboxCurrent(value);if(operation2==="questions.list"){const page=object3(value);keys3(page,["questions","nextBeforeNumber"]);const questions=array2(page.questions).map(parseAnswerableQuestion);assert(page.nextBeforeNumber===null||integer(page.nextBeforeNumber));return{questions,nextBeforeNumber:page.nextBeforeNumber}}if(operation2==="items.read")return parseInboxItem(value);if(operation2==="items.list"){const page=object3(value);const items=array2(page.items).map(parseInboxItem);assert(items.length<=100&&(page.nextBeforeNumber===null||integer(page.nextBeforeNumber)));return{items,nextBeforeNumber:page.nextBeforeNumber}}if(operation2==="items.see"){assert(date(value));return}if(operation2==="items.markDigestRead"){const read2=object3(value);assert(integer(read2.activityId)&&date(read2.readAt));return read2}if(operation2==="items.rename"||operation2==="items.setLifecycle"){const update=object3(value);const item=parseInboxItem(update.item);assert((update.activityId===null||integer(update.activityId))&&optionalDate(update.changedAt));return{...update,item}}if(operation2==="items.listRecipientCandidates"){const candidates=array2(value);candidates.forEach((value2)=>{const person=object3(value2);assert(id2(person.id)&&text3(person.name)&&text3(person.email))});assert(new Set(candidates.map((value2)=>object3(value2).id)).size===candidates.length);return candidates}if(operation2==="items.addRecipient"){const addition=object3(value);const item=parseInboxItem(addition.item);assert(id2(addition.addedPersonId)&&item.people.some((person)=>person.id===addition.addedPersonId));return{...addition,item}}if(operation2==="questions.answer")return parseInboxAcceptance(value);if(operation2==="questions.searchRecords"){const result2=object3(value);assert(text3(result2.recordType)&&integer(result2.eligibleCount,0)&&integer(result2.matchCount,0)&&Number(result2.matchCount)<=Number(result2.eligibleCount));const labeled=(value2)=>{const record3=object3(value2);recordReference({repository:record3.repository,ref:record3.ref});assert(text3(record3.label));if("reason"in record3)assert(text3(record3.reason))};array2(result2.matches).forEach(labeled);array2(result2.suggestions).forEach(labeled);if("selected"in result2)labeled(result2.selected);return result2}throw new Error("File content is not a JSON result")}async function limitedBody(request,limit,timeoutMs){if(!request.body)return new Uint8Array;const reader=request.body.getReader();let expired=false;const timer=timeoutMs===undefined?undefined:setTimeout(()=>{expired=true;reader.cancel().catch(()=>{})},timeoutMs);const chunks=[];let length=0;try{while(true){const{done,value}=await reader.read();if(done)break;length+=value.byteLength;if(length>limit){await reader.cancel();return}chunks.push(value)}if(expired)return;const contents=new Uint8Array(length);let offset=0;for(const chunk of chunks){contents.set(chunk,offset);offset+=chunk.byteLength}return contents}finally{if(timer!==undefined)clearTimeout(timer)}}var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function parseInboxHostContext(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Inbox context unavailable");const v=value;if(v.kind!=="inbox"&&v.kind!=="focused"||Object.keys(v).sort().join(",")!==(v.kind==="inbox"?"generation,kind,memberId,workspaceId":"appId,generation,kind,memberId,workspaceId")||typeof v.workspaceId!=="string"||!UUID.test(v.workspaceId)||typeof v.memberId!=="string"||!UUID.test(v.memberId)||typeof v.generation!=="string"||!UUID.test(v.generation)||v.kind==="focused"&&(typeof v.appId!=="string"||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(v.appId)))throw new Error("Inbox context unavailable");const base={workspaceId:v.workspaceId,memberId:v.memberId,generation:v.generation};return Object.freeze(v.kind==="inbox"?{...base,kind:"inbox"}:{...base,kind:"focused",appId:v.appId})}class InboxContextError extends Error{status;constructor(status){super("Inbox context unavailable");this.status=status}}var contexts=new WeakMap;function resolveHostedInboxContext(host){if(!host.binding||!host.memberId)throw new Error("Inbox context unavailable");let resolve=contexts.get(host.binding);if(!resolve){resolve=hostedInboxContext();contexts.set(host.binding,resolve)}return resolve({...host,memberId:host.memberId})}function hostedInboxContext(){let installed2;let revision=0,issued=0,settled=0;return async(host)=>{const started=++issued;const check=()=>{if(!host.isCurrent()||host.expiresAt<=Date.now())throw new Error("Inbox context unavailable")};check();const response2=await fetch(`${host.endpoint}/api/inbox/context`,{method:"GET",headers:{authorization:`Bearer ${host.accessToken}`},credentials:"omit",redirect:"error",cache:"no-store",signal:AbortSignal.timeout(15000)});try{check();if(response2.status===401||response2.status===403){installed2=undefined;revision++;settled=Math.max(settled,started)}if(!response2.ok||response2.status!==200)throw new InboxContextError(response2.status);const bytes=await limitedBody(response2,4096);check();if(!bytes)throw new Error("Inbox context unavailable");const context=parseInboxHostContext(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)));if(context.memberId!==host.memberId)throw new Error("Inbox context unavailable");if(JSON.stringify(installed2)!==JSON.stringify(context)){if(started<settled)throw new Error("Inbox context unavailable");installed2=context;revision++}settled=Math.max(settled,started);const current=revision;return Object.freeze({context,isCurrent:()=>host.isCurrent()&&host.expiresAt>Date.now()&¤t===revision})}finally{response2.body?.cancel().catch(()=>{})}}}var sessionKey="_os.app.session";var responseChecks=new WeakMap;class AppResponseReadError extends Error{}class AppContextDenied extends Error{}class AppRenewalUnavailable extends Error{}async function untilAborted(work,signal){if(signal.aborted){work.catch(()=>{});throw new AppRenewalUnavailable}let abort;const cancelled=new Promise((_resolve,reject)=>{abort=()=>reject(new AppRenewalUnavailable);signal.addEventListener("abort",abort,{once:true})});try{return await Promise.race([work,cancelled])}finally{signal.removeEventListener("abort",abort)}}async function appResponse(response2,maximum,signal){if(signal.aborted||!response2.body||response2.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json")throw new Error;const reader=response2.body.getReader();const abort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",abort,{once:true});let bytes=0,text4="";const decoder=new TextDecoder("utf-8",{fatal:true});try{while(true){let chunk;try{chunk=await reader.read()}catch{throw new AppResponseReadError}if(signal.aborted)throw new Error;if(chunk.done){const value=JSON.parse(text4+decoder.decode());await responseChecks.get(response2)?.(value);if(signal.aborted)throw new Error;return value}bytes+=chunk.value.byteLength;if(bytes>maximum){abort();throw new Error}text4+=decoder.decode(chunk.value,{stream:true})}}finally{signal.removeEventListener("abort",abort);reader.releaseLock()}}function isAppOrigin(value){try{const url=new URL(value);return url.protocol==="http:"&&url.hostname==="127.0.0.1"&&Boolean(url.port)&&url.port!=="0"&&url.origin===value}catch{return false}}function appContext(origin,active2){let binding;let credential;let pair;let serialized;let denied=false;const controller=new AbortController;let access=new AbortController;let expiry;let startup;let renewalTimer;let renewal;let observation;let resolution2;let disposed=false;const stored=()=>globalThis.localStorage.getItem(sessionKey);const alive=()=>{try{return!denied&&!disposed&&active2()&&globalThis.location.origin===origin}catch{return false}};const cancel=()=>{controller.abort();access.abort();clearTimeout(expiry);clearTimeout(startup);clearTimeout(renewalTimer);clearInterval(monitor);globalThis.removeEventListener?.("storage",storageChanged);for(const event of["pageshow","focus","visibilitychange"])globalThis.removeEventListener?.(event,wake)};const invalidate=()=>{denied=true;cancel();try{if(!disposed&&active2()&&globalThis.location.origin===origin&&(!serialized||globalThis.localStorage.getItem(sessionKey)===serialized)){globalThis.localStorage.removeItem(sessionKey)}}catch{}};const current=()=>{try{return alive()&&!!binding&&binding.expiresAt>Date.now()&&stored()===serialized}catch{return false}};const sameSession=(value)=>!binding||["appId","memberId","workspace","sessionId"].every((key)=>value[key]===binding[key]);const bounded=(value)=>validBinding(value)&&value.expiresAt>Date.now()&&value.expiresAt<=Date.now()+600000&&sameSession(value);const readPair=(candidate)=>{const value=JSON.parse(candidate??"null");if(!validPair(value)||value.context.expiresAt>Date.now()+600000||!sameSession(value.context))throw new Error;return value};const expireAccess=()=>{if(binding&&binding.expiresAt<=Date.now())access.abort()};async function send2(path,candidate,signal,init={}){const url=`${origin}/_os/app/${path}`;let response2;try{response2=await fetch(url,{...init,credentials:"omit",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer",signal,headers:{...init.body===undefined?{}:{"content-type":"application/json"},authorization:`Bearer ${candidate}`}})}catch{throw new AppRenewalUnavailable}if(response2.redirected||response2.url&&response2.url!==url)throw new Error;return response2}async function proof(candidate,signal=controller.signal){if(!alive()||!validProof(candidate))throw new Error;const response2=await send2("context",candidate,signal);if(response2.status===401||response2.status===403)throw new AppContextDenied;if(response2.status>=500)throw new AppRenewalUnavailable;if(!response2.ok)throw new Error;const value=await appResponse(response2,4096,signal);if(!alive()||!bounded(value))throw new Error;return value}function install(value,candidate,raw){expireAccess();if(access.signal.aborted)access=new AbortController;binding={...value};pair=candidate;credential=candidate.credential;serialized=raw;clearTimeout(expiry);clearTimeout(renewalTimer);const remaining=binding.expiresAt-Date.now();expiry=setTimeout(expireAccess,remaining);renewalTimer=setTimeout(()=>{renew().catch(()=>{})},remaining-Math.min(60000,remaining/5))}async function synchronize(signal=controller.signal){if(!alive())throw new Error;if(signal.aborted)throw new AppRenewalUnavailable;if(!credential)return;if(stored()===serialized)return;if(!binding)throw new Error;if(observation)return untilAborted(observation,signal);observation=(async()=>{while(alive()){const candidate=stored();if(!candidate)throw new Error;let value;let replacement;try{replacement=readPair(candidate);value=await proof(replacement.credential,signal)}catch(error){if(stored()!==candidate)continue;throw error}if(stored()!==candidate)continue;if(value.expiresAt!==replacement.context.expiresAt)throw new Error;install(value,replacement,candidate);return}throw new Error})();const observed=observation;try{await untilAborted(observed,signal)}catch(error){if(!(error instanceof AppRenewalUnavailable||error instanceof AppResponseReadError))invalidate();throw error}finally{if(observation===observed)observation=undefined}}async function renew(){if(renewal)return renewal;if(!binding||!pair||!alive())throw new Error;renewal=(async()=>{const requestController=new AbortController;const abort=()=>requestController.abort();controller.signal.addEventListener("abort",abort,{once:true});const timeout=setTimeout(abort,20000);const previous=serialized;try{await synchronize(requestController.signal);if(serialized!==previous)return;const response2=await send2("renew",pair.renewalCredential,requestController.signal,{method:"POST"});const value=await appResponse(response2,4096,requestController.signal);if(response2.status===503&&value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).join(",")==="error"&&"error"in value&&value.error==="renewal_unavailable")throw new AppRenewalUnavailable;if(response2.status===403&&value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).join(",")==="error"&&"error"in value&&value.error==="renewal_conflict"){while(alive()&&stored()===previous&&!requestController.signal.aborted){await new Promise((resolve2,reject)=>{const abortWait=()=>{clearTimeout(timer);reject(new Error)};const timer=setTimeout(()=>{requestController.signal.removeEventListener("abort",abortWait);resolve2()},100);requestController.signal.addEventListener("abort",abortWait,{once:true})})}if(requestController.signal.aborted)throw new Error;await synchronize(requestController.signal);return}if(!response2.ok)throw new Error;if(!alive()||!validPair(value)||!bounded(value.context)||new Set([value.credential,value.renewalCredential,pair.credential,pair.renewalCredential]).size!==4)throw new Error;if(stored()!==previous){await synchronize(requestController.signal);return}const raw=JSON.stringify(value);globalThis.localStorage.setItem(sessionKey,raw);install(value.context,value,raw)}catch(error){try{if(alive()&&stored()&&stored()!==previous){await synchronize(requestController.signal);return}}catch{}if((error instanceof AppRenewalUnavailable||error instanceof AppResponseReadError||requestController.signal.aborted)&&alive()){if(current())renewalTimer=setTimeout(()=>{renew().catch(()=>{})},Math.min(5000,(binding.expiresAt-Date.now())/5))}else invalidate();throw new AppRenewalUnavailable}finally{clearTimeout(timeout);controller.signal.removeEventListener("abort",abort)}})();try{await renewal}finally{renewal=undefined}}const storageChanged=()=>{if(!credential)return;if(!alive()){invalidate();return}expireAccess();synchronize().catch(()=>{})};const monitor=setInterval(()=>{storageChanged()},100);globalThis.addEventListener?.("storage",storageChanged);const wake=()=>{if(alive())resolve().catch(()=>{})};for(const event of["pageshow","focus","visibilitychange"])globalThis.addEventListener?.(event,wake);const dispose=()=>{disposed=true;cancel()};async function settledAccess(signal){await synchronize();while(alive()&&stored()!==serialized)await synchronize();if(signal.aborted||!current())throw new Error}async function requestData(operation2,input){try{if(operation2!=="data/query"||!current())throw new Error;const admitted=credential;const signal=access.signal;const response2=await send2("data",credential,signal,{method:"POST",body:JSON.stringify(input)});await settledAccess(signal);if(response2.status===401||response2.status===403){if(admitted===credential&¤t())invalidate();throw new DataOperationError("access_denied")}const result2=await appResponse(response2,Number.MAX_SAFE_INTEGER,signal);await settledAccess(signal);if(!response2.ok)throw dataTransportError(response2.status,result2);return result2}catch(error){if(error instanceof DataOperationError)throw error;if(!current()||controller.signal.aborted)throw new DataOperationError("context_unavailable");throw new DataOperationError("unavailable",true)}}async function requestInbox(operation2,input){if(!["questions.list","questions.answer","questions.searchRecords"].includes(operation2))throw new Error("Inbox operation unavailable");return requestChecked("inbox",{method:"POST",body:JSON.stringify({operation:operation2,input})},true)}async function requestRoutine(key,suffix,init={}){return requestChecked(`routines/${encodeURIComponent(key)}/${suffix}`,init)}async function requestChecked(path,init,inbox=false){if(!current())throw new Error("Local app context unavailable.");const admitted=credential;const signal=access.signal;const response2=await send2(path,credential,signal,init);await settledAccess(signal);if((response2.status===401||!inbox&&response2.status===403)&&admitted===credential&¤t())invalidate();responseChecks.set(response2,async(value)=>{await settledAccess(signal);if(admitted===credential&¤t()&&value&&typeof value==="object"&&"error"in value&&value.error==="authority_unavailable")invalidate()});return response2}function context(){const issued=credential;const signal=access.signal;return{kind:"local",...binding,get expiresAt(){return binding.expiresAt},isCurrent:()=>!signal.aborted&¤t(),signal,invalidate:()=>{if(issued===credential&¤t())invalidate()},requestRoutine,requestData,requestInbox,requestAvailability:(key)=>requestRoutine(key,"availability",{method:"GET"})}}const resolveOnce=async()=>{let attempted;try{if(!alive())throw new Error;if(!pair){const candidate2=stored();const retained2=readPair(candidate2);pair=retained2;binding={...retained2.context};credential=retained2.credential;serialized=candidate2}expireAccess();if(binding.expiresAt<=Date.now()){await renew();if(!current())throw new AppRenewalUnavailable;return context()}await synchronize();const candidate=stored();const retained=readPair(candidate);attempted=candidate??undefined;if(!current())throw new AppRenewalUnavailable;const value=await proof(retained.credential);if(stored()!==candidate||serialized!==candidate){await synchronize();return context()}if(!current())throw new Error;if(expiry&&binding&&value.expiresAt>binding.expiresAt)throw new Error;if(!expiry||value.expiresAt!==binding.expiresAt)install(value,retained,candidate);return context()}catch(error){if(alive()&&error instanceof AppRenewalUnavailable)throw new Error;try{if(binding&¤t()&&attempted&&attempted!==serialized)return context();if(binding&&alive()&&stored()&&stored()!==serialized){await synchronize();return context()}}catch{}if(error instanceof AppContextDenied&&binding&&alive()&&renewal)throw new Error;if(alive()&&(error instanceof AppResponseReadError||pair&&stored()===serialized&&!current()))throw new Error;invalidate();throw new Error}};const resolve=()=>{if(resolution2)return resolution2;resolution2=resolveOnce().finally(()=>{resolution2=undefined});return resolution2};const start=()=>{startup=setTimeout(()=>{if(alive()&&!resolution2&&!binding)resolve().catch(()=>{})},0)};return{resolve,start,invalidate,dispose}}function validProof(value){return typeof value==="string"&&/^[A-Za-z0-9_-]{43}$/.test(value)}function validBinding(value){if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).sort().join(",")!=="appId,expiresAt,memberId,sessionId,workspace")return false;const binding=value;return typeof binding.appId==="string"&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(binding.appId)&&typeof binding.workspace==="string"&&/^[a-z0-9][a-z0-9-]{0,62}$/.test(binding.workspace)&&typeof binding.memberId==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(binding.memberId)&&validProof(binding.sessionId)&&typeof binding.expiresAt==="number"&&Number.isFinite(binding.expiresAt)}function validPair(value){if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).sort().join(",")!=="context,credential,renewalCredential")return false;const pair=value;return validProof(pair.credential)&&validProof(pair.renewalCredential)&&pair.credential!==pair.renewalCredential&&validBinding(pair.context)}var unavailable2=()=>new InboxOperationError(503,"unavailable");var stale=()=>new InboxOperationError(401,"authority_unavailable");function hostFailure(error,context){if(!context.isCurrent()||context.expiresAt<=Date.now()||error instanceof InboxContextError&&error.status===401)return stale();return error instanceof InboxContextError&&error.status===403?new InboxOperationError(403,"access_denied"):unavailable2()}async function send2(operation2,input){const envelope=parseInboxRequest({operation:operation2,input});let context;try{context=await resolveAppContext()}catch{throw stale()}if(context.kind==="local"){if(!isAppQuestionOperation(operation2))throw new InboxOperationError(403,"access_denied");const check2=()=>{if(!context.isCurrent()||context.signal.aborted||context.expiresAt<=Date.now())throw stale()};try{const response2=await context.requestInbox(operation2,envelope.input);const value=await appResponse(response2,INBOX_RESULT_BYTES,context.signal);check2();if(!response2.ok)throw new InboxOperationError([400,401,403,409].includes(response2.status)?response2.status:503,response2.status===400?"invalid_input":response2.status===401?"authority_unavailable":response2.status===403?"access_denied":response2.status===409?"conflict":"unavailable");if(response2.status!==200)throw unavailable2();const parsed=parseInboxResult(operation2,value);check2();if(operation2==="questions.answer"&&typeof envelope.input.response.selection==="object"&&!parsed.label?.trim())throw unavailable2();return parsed}catch(error){check2();throw error instanceof InboxOperationError?error:unavailable2()}}if(context.endpoint!==`https://${context.workspace}.oddington.ai`||["auth","www","api","os"].includes(context.workspace))throw stale();let host;try{host=await resolveHostedInboxContext(context)}catch(error){throw hostFailure(error,context)}if(!host)throw unavailable2();const check=()=>{if(!context.isCurrent()||!host.isCurrent()||!Number.isFinite(context.expiresAt)||context.expiresAt<=Date.now())throw stale()};check();if(host.context.kind==="focused"&&!isAppQuestionOperation(operation2))throw new InboxOperationError(403,"access_denied");try{const response2=await fetch(`${context.endpoint}/api/inbox`,{method:"POST",headers:{authorization:`Bearer ${context.accessToken}`,"content-type":"application/json"},body:JSON.stringify(envelope),redirect:"error",cache:"no-store",signal:AbortSignal.timeout(30000)});try{check()}catch(error){response2.body?.cancel().catch(()=>{});throw error}if(!response2.ok){response2.body?.cancel().catch(()=>{});throw new InboxOperationError([400,401,403,409].includes(response2.status)?response2.status:503,response2.status===400?"invalid_input":response2.status===401?"authority_unavailable":response2.status===403?"access_denied":response2.status===409?"conflict":"unavailable")}if(response2.status!==200){response2.body?.cancel().catch(()=>{});throw unavailable2()}if(operation2==="files.read"){if(!response2.body)throw unavailable2();const source=response2.body;let reader;let size=0;const cancel=async(reason)=>{try{await(reader?reader.cancel(reason):source.cancel(reason))}finally{reader?.releaseLock()}};const body=new ReadableStream({async pull(controller){try{check();reader??=source.getReader();const next=await reader.read();check();if(next.done){reader.releaseLock();controller.close();return}size+=next.value.byteLength;if(size>25*1024*1024)throw unavailable2();controller.enqueue(next.value)}catch(error){controller.error(error);await cancel(error).catch(()=>{})}},cancel},{highWaterMark:0});return new Response(body,{status:response2.status,headers:response2.headers})}const bytes=await limitedBody(response2,INBOX_RESULT_BYTES);check();if(!bytes)throw unavailable2();const value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));const parsed=parseInboxResult(operation2,value);check();if(operation2==="current"&&parsed.workspace.slug!==context.workspace)throw unavailable2();if("itemId"in envelope.input){const item=operation2==="items.read"?parsed:operation2==="items.rename"||operation2==="items.setLifecycle"||operation2==="items.addRecipient"?parsed.item:undefined;if(item&&(item.id!==envelope.input.itemId||("revision"in envelope.input)&&item.revision!==envelope.input.revision))throw unavailable2();if(operation2==="items.addRecipient"&&parsed.addedPersonId!==envelope.input.personId)throw unavailable2();if(operation2==="questions.answer"&&typeof envelope.input.response.selection==="object"&&!parsed.label?.trim())throw unavailable2()}return parsed}catch(error){check();throw error instanceof InboxOperationError?error:unavailable2()}}var inbox={current:async()=>await send2("current",{}),items:{async list(){const items=[];let beforeNumber;let initial;try{initial=await resolveAppContext()}catch{throw stale()}let host;try{host=initial.kind!=="local"&&await resolveHostedInboxContext(initial)}catch(error){throw hostFailure(error,initial)}if(initial.kind==="local")throw new InboxOperationError(403,"access_denied");if(!host)throw unavailable2();const check=()=>{if(!initial.isCurrent()||!host.isCurrent()||initial.expiresAt<=Date.now())throw stale()};do{check();const page=await send2("items.list",beforeNumber===undefined?{}:{beforeNumber});check();if(beforeNumber!==undefined&&(page.items.some((item)=>item.number>=beforeNumber)||page.nextBeforeNumber!==null&&page.nextBeforeNumber>=beforeNumber))throw unavailable2();items.push(...page.items);if(page.nextBeforeNumber===null)return items;beforeNumber=page.nextBeforeNumber}while(true)},read:async(itemId)=>await send2("items.read",{itemId}),see:async(itemId)=>{await send2("items.see",{itemId})},markDigestRead:async(itemId)=>await send2("items.markDigestRead",{itemId}),rename:async(input)=>await send2("items.rename",input),setLifecycle:async(input)=>await send2("items.setLifecycle",input),listRecipientCandidates:async(itemId)=>await send2("items.listRecipientCandidates",{itemId}),addRecipient:async(input)=>await send2("items.addRecipient",input)},questions:{async list(){const questions=[];let beforeNumber;let initial;try{initial=await resolveAppContext()}catch{throw stale()}let host;try{host=initial.kind!=="local"&&await resolveHostedInboxContext(initial)}catch(error){throw hostFailure(error,initial)}if(initial.kind!=="local"&&!host)throw unavailable2();const check=()=>{if(!initial.isCurrent()||host&&!host.isCurrent()||initial.expiresAt<=Date.now())throw stale()};do{check();const page=await send2("questions.list",beforeNumber===undefined?{}:{beforeNumber});check();if(page.questions.some((question2)=>question2.item.href!==`https://${initial.workspace}.oddington.ai/inbox/${question2.item.id}`)||beforeNumber!==undefined&&(page.questions.some((question2)=>question2.item.number>=beforeNumber)||page.nextBeforeNumber!==null&&page.nextBeforeNumber>=beforeNumber))throw unavailable2();questions.push(...page.questions);if(page.nextBeforeNumber===null)return questions;beforeNumber=page.nextBeforeNumber}while(true)},answer:async(input)=>await send2("questions.answer",input),searchRecords:async(input)=>await send2("questions.searchRecords",input)},files:{read:async(input)=>await send2("files.read",input)}};var sources=new WeakMap;function registerBrowserAuth(handle,source){sources.set(handle,source)}function browserAuthSource(handle){return sources.get(handle)}var installedDispose;function init({auth:input}){installedDispose?.();const registered=browserAuthSource(input);const auth=registered??input;if(!registered&&input&&"getState"in input||typeof auth?.getSession!=="function"||typeof auth?.onAuthStateChange!=="function"){installedDispose=installMemberContext(async()=>{throw new Error("Hosted Data context unavailable.")});return}let endpoint;let workspace;let localOrigin;try{const url=new URL(globalThis.location.origin);if(isAppOrigin(globalThis.location.origin))localOrigin=url.origin;const slug=url.hostname.endsWith(".oddington.ai")?url.hostname.slice(0,-".oddington.ai".length):"";if(url.protocol==="https:"&&!url.port&&!url.username&&!url.password&&!url.search&&!url.hash&&url.pathname==="/"&&/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(slug)&&slug!=="auth"){endpoint=url.origin;workspace=slug}}catch{}let active2=true;let revision=0;let person;let token;const binding={};const local=localOrigin?appContext(localOrigin,()=>active2):undefined;let subscription;let stopDisposal;const resolve=async()=>{if(local)return local.resolve();if(!active2||!endpoint||!workspace||globalThis.location.origin!==endpoint)throw new Error("Hosted Data context unavailable.");const started=revision;const{data:{session},error}=await auth.getSession();if(!active2||globalThis.location.origin!==endpoint||started!==revision||error||!session||person!==undefined&&person!==session.user.id){throw new Error("Hosted Data context unavailable.")}const expiresAt=(session.expires_at??0)*1000;if(!Number.isFinite(expiresAt)||expiresAt<=Date.now()||!session.user.id){throw new Error("Hosted Data context unavailable.")}person=session.user.id;const isCurrent=()=>active2&&globalThis.location.origin===endpoint&&revision===started&&person===session.user.id;return{workspace,endpoint,accessToken:session.access_token,expiresAt,isCurrent,memberId:session.user.id,binding}};const uninstall=installMemberContext(resolve);const dispose=()=>{if(!active2)return;active2=false;local?.dispose();revision++;subscription?.unsubscribe();stopDisposal?.();uninstall();if(installedDispose===dispose)installedDispose=undefined};installedDispose=dispose;stopDisposal=registered?.onDispose(dispose);if(!active2)return;subscription=auth.onAuthStateChange((event,session)=>{const next=session?.user.id??null;if(event==="SIGNED_OUT"||person!==undefined&&next!==person||registered&&person!==undefined&&event==="SIGNED_IN"&&token!==session?.access_token){revision++;local?.invalidate()}person=next;token=session?.access_token}).data.subscription;local?.start()}var os={init};var CLI_CALLBACK="http://127.0.0.1:53682/oauth/callback";function authorizationConfiguration(value){const setup=value;if(!setup||typeof setup.clientId!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(setup.clientId)||setup.redirectUri!==CLI_CALLBACK||!Array.isArray(setup.scopes)||setup.scopes.length!==1||setup.scopes[0]!=="email")throw new Error("Unavailable");return{clientId:setup.clientId,redirectUri:CLI_CALLBACK,scopes:["email"]}}function authorizationDetails(value,id3,setup,userId,account){const details=value;if(!details||details.authorization_id!==id3||details.redirect_uri!==setup.redirectUri||details.client?.id!==setup.clientId||typeof details.client.name!=="string"||!details.client.name.trim()||details.client.name.length>128||/[\x00-\x1f\x7f]/.test(details.client.name)||details.user?.id!==userId||details.user.email!==account.email||typeof details.scope!=="string"||details.scope.trim()!=="email")return Object.freeze({status:"invalid"});return Object.freeze({status:"consent",clientName:details.client.name.trim(),account,scopes:Object.freeze([...setup.scopes]),callbackAddress:new URL(setup.redirectUri).host})}function authorizationReturn(value,decision){const returnUrl=value?.redirect_url;if(typeof returnUrl!=="string"||returnUrl.length>8192||!returnUrl.startsWith(`${CLI_CALLBACK}?`)||/[\x00-\x20\x7f]/.test(returnUrl))return Object.freeze({status:"invalid"});try{const url=new URL(returnUrl);if(url.origin+url.pathname!==CLI_CALLBACK||url.username||url.password||url.hash)return Object.freeze({status:"invalid"});const parameters=url.searchParams;const allowed=["code","state","error","error_description","error_uri"];for(const key of parameters.keys()){if(!allowed.includes(key)||parameters.getAll(key).length!==1)return Object.freeze({status:"invalid"})}const code=parameters.get("code");const error=parameters.get("error");if(!parameters.get("state")||Boolean(code)===Boolean(error)||decision==="deny"&&!error||decision==="approve"&&!code||parameters.has("code")&&!code||parameters.has("error")&&!error||code&&(parameters.has("error_description")||parameters.has("error_uri")))return Object.freeze({status:"invalid"});return Object.freeze({status:"return",returnUrl})}catch{return Object.freeze({status:"invalid"})}}function authorizationFailure(error){const status=error?.status;return Object.freeze({status:status===404||status===410||status===400?"expired":status===401?"signed_out":status===403||status===422?"invalid":"unavailable"})}function createBrowserAuth(runtime){const coordinators=new Map;function publish(c,state){c.state=Object.freeze(state);for(const listener of c.listeners){try{listener(c.state)}catch{}}}function notify(c,event){for(const listener of c.sessions){try{listener(event,event==="SIGNED_OUT"?null:c.session)}catch{}}}function expire(c){if(!c.active||!c.session&&c.state.status==="expired")return;c.revision++;if(c.timer)clearTimeout(c.timer);c.session=null;publish(c,{status:"expired"});notify(c,"SIGNED_OUT")}function accept(c,event,session){if(!c.active)return;if(event==="INITIAL_SESSION"&&c.state.status!=="initializing")return;if(event==="TOKEN_REFRESHED"&&!c.session&&c.state.status!=="initializing")return;const replaced=c.session?.user?.id!==session?.user?.id||event==="SIGNED_OUT"||!!(event==="SIGNED_IN"&&c.session&&session?.access_token!==c.session.access_token);if(replaced)c.revision++;if(c.timer)clearTimeout(c.timer);const pending=c.state.pending;if(!session){c.session=null;publish(c,{status:c.state.status==="expired"?"expired":"signed_out",...pending?{pending}:{}});notify(c,"SIGNED_OUT");return}if(!validSession(session)){c.session=session;expire(c);return}c.session=session;const email=typeof session.user.email==="string"?session.user.email.trim():"";const metadata=session.user.user_metadata;const displayName=["name","full_name","first_name"].map((key)=>metadata?.[key]).find((value)=>typeof value==="string"&&value.trim());const name=displayName?.trim()||email;const account=!replaced&&c.state.account?.email===email&&c.state.account.displayName===name?c.state.account:Object.freeze({email,displayName:name});publish(c,{status:"signed_in",account,...pending?{pending}:{}});notify(c,event);const checkExpiry=()=>{if(!c.active||!c.session)return;const remaining=c.session.expires_at*1000-Date.now();if(remaining<=0)expire(c);else c.timer=setTimeout(checkExpiry,Math.min(remaining,2147483647))};checkExpiry()}function validSession(session){return typeof session.access_token==="string"&&/^[^\s]{1,8192}$/.test(session.access_token)&&typeof session.user?.id==="string"&&!!session.user.id&&Number.isFinite(session.expires_at)&&session.expires_at*1000>Date.now()}function createCoordinator(origin){const c={state:Object.freeze({status:"initializing"}),session:null,revision:0,active:true,refs:0,listeners:new Set,sessions:new Set,ready:Promise.resolve()};c.ready=(async()=>{const revision=c.revision;try{if(!allowedOrigin(origin))throw runtime.failure("unavailable");const response2=await fetch(`${origin}/api/auth`,{method:"GET",credentials:"same-origin",redirect:"error",cache:"no-store"});if(!response2.ok)throw runtime.failure("unavailable");const configuration=validateConfiguration(await response2.json());if(configuration.authorization&&origin!=="https://auth.oddington.ai"&&origin!=="http://127.0.0.1:5176")throw runtime.failure("unavailable");c.authorization=configuration.authorization;if(!c.active||globalThis.location?.origin!==origin)return;c.provider=await runtime.provider(configuration,{revision:()=>c.revision,current:(revision2)=>current(c,origin,revision2),canPersistSession:()=>c.active&&(c.state.status==="initializing"||!!c.session||c.state.pending==="verify_code"),canAuthorize:(accessToken)=>current(c,origin,c.revision)&&!!c.session&&c.session.access_token===accessToken&&c.state.pending!=="sign_out"});if(!c.active||globalThis.location?.origin!==origin){c.provider.dispose();return}const subscription=c.provider.onAuthStateChange((event,session)=>{if(c.state.status==="initializing"&&c.state.pending==="sign_out")return;accept(c,event,session)}).data.subscription;c.unsubscribe=()=>subscription.unsubscribe();const started=c.revision;const{data:data2,error}=await c.provider.getSession();if(!current(c,origin,started))return;if(error){if(terminalSessionFailure(error))expire(c);else if(!c.session||!validSession(c.session))publish(c,{status:"unavailable",error:"unavailable"})}else if(c.state.pending!=="sign_out")accept(c,"INITIAL_SESSION",data2.session)}catch{if(current(c,origin,revision))publish(c,{status:"unavailable",error:"unavailable"})}})();return c}function current(c,origin,revision){if(c.session&&!validSession(c.session))expire(c);return c.active&&c.revision===revision&&globalThis.location?.origin===origin}return{create(){const origin=globalThis.location?.origin??"";let c=coordinators.get(origin);if(!c){c=createCoordinator(origin);coordinators.set(origin,c)}const coordinator=c;coordinator.refs++;let active2=true;let ownedAction;let authorizationId;let authorizationGeneration=0;let inspected;const observers=new Set;const sessionObservers=new Set;const disposalObservers=new Set;let lastState=coordinator.state;const observation=(state)=>{lastState=state;for(const listener of observers){try{listener(state)}catch{}}};coordinator.listeners.add(observation);const assertActive=()=>{if(!active2)throw runtime.failure("disposed")};async function action(kind,work){assertActive();if(coordinator.action&&kind!=="sign_out")throw runtime.failure("busy");if(kind==="sign_out"&&coordinator.state.pending==="sign_out")throw runtime.failure("busy");if(kind==="sign_out"){coordinator.revision++;notify(coordinator,"SIGNED_OUT")}const marker={};coordinator.action=marker;ownedAction=marker;const revision=coordinator.revision;publish(coordinator,{...coordinator.state,error:undefined,pending:kind});try{await coordinator.ready;assertActive();if(!coordinator.provider||!coordinator.active||globalThis.location?.origin!==origin)throw runtime.failure("unavailable");if(!current(coordinator,origin,revision))throw runtime.failure("stale");if(coordinator.action!==marker)throw runtime.failure("stale");await work(coordinator.provider);assertActive();if(coordinator.action!==marker)throw runtime.failure("stale");if(!current(coordinator,origin,revision)&&kind!=="verify_code"&&kind!=="sign_out")throw runtime.failure("stale")}catch(error){const reason=!active2?"disposed":!current(coordinator,origin,revision)?"stale":safeReason(error)??"unavailable";if(active2&¤t(coordinator,origin,revision))publish(coordinator,{...coordinator.state,error:reason});throw runtime.failure(reason)}finally{if(coordinator.action===marker){coordinator.action=undefined;if(coordinator.active){publish(coordinator,{...coordinator.state,pending:undefined});if(kind==="sign_out"&&coordinator.session)notify(coordinator,"TOKEN_REFRESHED")}}if(ownedAction===marker)ownedAction=undefined}}async function authorize(kind,id3){if(!active2)return Object.freeze({status:"disposed"});if(id3!==authorizationId){authorizationId=id3;authorizationGeneration++;inspected=undefined}if(!id3)return Object.freeze({status:"missing"});if(typeof id3!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(id3))return Object.freeze({status:"invalid"});const generation=authorizationGeneration;await coordinator.ready;if(!active2)return Object.freeze({status:"disposed"});if(generation!==authorizationGeneration)return Object.freeze({status:"stale"});const revision=coordinator.revision;if(!current(coordinator,origin,revision))return Object.freeze({status:"stale"});if(!coordinator.session||coordinator.state.pending==="sign_out")return Object.freeze({status:coordinator.state.status==="expired"?"expired":coordinator.state.status==="unavailable"?"unavailable":"signed_out"});if(!coordinator.authorization||!coordinator.provider)return Object.freeze({status:"unavailable"});if(coordinator.action)return Object.freeze({status:"busy"});if(kind!=="get"&&(!inspected||inspected.id!==id3||inspected.revision!==revision))return Object.freeze({status:"stale"});if(kind!=="get"&&inspected?.result.status!=="consent")return inspected.result;const marker={};coordinator.action=marker;ownedAction=marker;const requestCurrent=()=>active2&&generation===authorizationGeneration&¤t(coordinator,origin,revision)&&coordinator.action===marker&&!!coordinator.session&&coordinator.state.pending!=="sign_out";const stale2=()=>Object.freeze({status:active2?"stale":"disposed"});try{const provider=coordinator.provider;const response2=await provider.authorization.get(id3,requestCurrent);if(!requestCurrent())return stale2();if(response2.error){inspected=undefined;const failure=authorizationFailure(response2.error);if(failure.status==="signed_out")expire(coordinator);return failure}const account=coordinator.state.account;const result2=response2.data&&typeof response2.data==="object"&&"redirect_url"in response2.data?authorizationReturn(response2.data):authorizationDetails(response2.data,id3,coordinator.authorization,coordinator.session.user.id,account);inspected={id:id3,revision,result:result2};if(kind==="get"||result2.status!=="consent")return result2;if(!requestCurrent())return stale2();const decision=await provider.authorization[kind](id3,requestCurrent);if(!requestCurrent())return stale2();const returned=decision.error?authorizationFailure(decision.error):authorizationReturn(decision.data,kind);if(returned.status==="signed_out")expire(coordinator);inspected={id:id3,revision,result:returned};return returned}catch(error){if(!requestCurrent())return stale2();inspected=undefined;if(safeReason(error)==="stale")return stale2();return Object.freeze({status:"unavailable"})}finally{if(coordinator.action===marker)coordinator.action=undefined;if(ownedAction===marker)ownedAction=undefined}}const handle=Object.freeze({authorization:Object.freeze({get:(id3)=>authorize("get",id3),approve:(id3)=>authorize("approve",id3),deny:(id3)=>authorize("deny",id3)}),getState(){if(active2&&coordinator.session&&!validSession(coordinator.session))expire(coordinator);return lastState},subscribe(listener){assertActive();observers.add(listener);return()=>{observers.delete(listener)}},async sendCode(email){assertActive();if(!validEmail(email))throw runtime.failure("invalid_input");await action("send_code",async(provider)=>{const{error}=await provider.signInWithOtp({email:email.trim(),options:{shouldCreateUser:false}});if(error&&!accountRefusal(error))throw runtime.failure("unavailable")})},async verifyCode(email,code){assertActive();if(!validEmail(email)||typeof code!=="string"||!/^\d{6}$/.test(code))throw runtime.failure("invalid_input");await action("verify_code",async(provider)=>{const revision=coordinator.revision;const{data:data2,error}=await provider.verifyOtp({email:email.trim(),token:code,type:"email"});if(error)throw runtime.failure(accountRefusal(error)?"invalid_code":"unavailable");if(!data2.session||!validSession(data2.session))throw runtime.failure("invalid_code");if(!current(coordinator,origin,revision)&&(coordinator.session?.access_token!==data2.session.access_token||coordinator.revision!==revision+1||coordinator.state.pending!=="verify_code"))throw runtime.failure("stale");accept(coordinator,"SIGNED_IN",data2.session)})},async signOut(){assertActive();await action("sign_out",async(provider)=>{const revision=coordinator.revision;const{error}=await provider.signOut({scope:"local"});if(error)throw runtime.failure("unavailable");if(!current(coordinator,origin,revision)&&coordinator.session)throw runtime.failure("stale");accept(coordinator,"SIGNED_OUT",null)})},dispose(){if(!active2)return;active2=false;authorizationGeneration++;inspected=undefined;if(ownedAction&&coordinator.action===ownedAction)coordinator.revision++;observers.clear();coordinator.listeners.delete(observation);for(const listener of disposalObservers){try{listener()}catch{}}disposalObservers.clear();for(const listener of sessionObservers)coordinator.sessions.delete(listener);sessionObservers.clear();if(--coordinator.refs===0){coordinator.active=false;coordinator.revision++;if(coordinator.timer)clearTimeout(coordinator.timer);coordinator.unsubscribe?.();coordinator.provider?.dispose();coordinator.provider=undefined;coordinator.session=null;coordinator.listeners.clear();coordinator.sessions.clear();coordinators.delete(origin)}}});registerBrowserAuth(handle,{onDispose(callback){if(!active2){callback();return()=>{}}disposalObservers.add(callback);return()=>{disposalObservers.delete(callback)}},async getSession(){assertActive();await coordinator.ready;assertActive();const revision=coordinator.revision;if(!current(coordinator,origin,revision)||!coordinator.provider||!coordinator.session||coordinator.state.pending==="sign_out")return{data:{session:null},error:null};let result2;try{result2=await coordinator.provider.getSession()}catch{result2={data:{session:null},error:runtime.failure("unavailable")}}if(!active2||!current(coordinator,origin,revision))return{data:{session:null},error:runtime.failure("stale")};if(result2.error){if(!terminalSessionFailure(result2.error)&&coordinator.session&&validSession(coordinator.session))return{data:{session:coordinator.session},error:null};expire(coordinator);return{data:{session:null},error:runtime.failure("unavailable")}}accept(coordinator,"TOKEN_REFRESHED",result2.data.session);return{data:{session:coordinator.session},error:null}},onAuthStateChange(callback){if(!active2){callback("SIGNED_OUT",null);return{data:{subscription:{unsubscribe(){}}}}}const listener=(event,session)=>callback(event,session);coordinator.sessions.add(listener);sessionObservers.add(listener);callback("INITIAL_SESSION",coordinator.session);return{data:{subscription:{unsubscribe(){coordinator.sessions.delete(listener);sessionObservers.delete(listener)}}}}}});return handle}}}function safeReason(error){const reason=error?.reason;return["invalid_input","invalid_code","unavailable","busy","stale","disposed"].includes(reason)?reason:undefined}function accountRefusal(error){return[400,401,403,404,422].includes(error?.status??0)}function terminalSessionFailure(error){return[400,401,403,404,422].includes(error?.status??0)}function validEmail(email){return typeof email==="string"&&email.length<=320&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())}function allowedOrigin(origin){if(origin==="http://127.0.0.1:5176"||origin==="https://auth.oddington.ai")return true;try{const url=new URL(origin);const slug=url.hostname.endsWith(".oddington.ai")?url.hostname.slice(0,-".oddington.ai".length):"";return slug.length<=63&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)&&!["auth","api","os","www"].includes(slug)&&origin===`https://${slug}.oddington.ai`}catch{return false}}function validateConfiguration(value){const configuration=value;if(!configuration||typeof configuration.providerUrl!=="string"||typeof configuration.publishableKey!=="string")throw new Error("Unavailable");const url=new URL(configuration.providerUrl);if(url.origin!==configuration.providerUrl||url.protocol!=="https:"||url.username||url.password||url.port||!configuration.publishableKey)throw new Error("Unavailable");return{providerUrl:url.origin,publishableKey:configuration.publishableKey,...configuration.authorization===undefined?{}:{authorization:authorizationConfiguration(configuration.authorization)}}}class BrowserAuthError extends Error{reason;constructor(reason){super(`Browser authentication failed: ${reason}`);this.reason=reason;this.name="BrowserAuthError"}}async function provider(configuration,guard){const{AuthClient:AuthClient2}=await Promise.resolve().then(() => (init_auth_provider(),exports_auth_provider));if(!guard.current(guard.revision()))throw new BrowserAuthError("stale");const provenance=new Map;let removalRevision;let authorizationRequest;let authorizationQueue=Promise.resolve();const storage=globalThis.localStorage;const client=new AuthClient2({url:`${configuration.providerUrl}/auth/v1`,headers:{apikey:configuration.publishableKey,Authorization:`Bearer ${configuration.publishableKey}`},storageKey:`sb-${new URL(configuration.providerUrl).hostname.split(".")[0]}-auth-token`,persistSession:true,autoRefreshToken:true,detectSessionInUrl:false,storage:{getItem:(key)=>storage.getItem(key),removeItem(key){if(!guard.current(removalRevision??guard.revision()))throw new BrowserAuthError("stale");storage.removeItem(key)},setItem(key,value){const token=JSON.parse(value).access_token;const revision=token?provenance.get(token):undefined;if(!guard.current(revision??guard.revision())||token&&!guard.canPersistSession())throw new BrowserAuthError("stale");storage.setItem(key,value)}},fetch:Object.assign(async(input,init2)=>{const revision=guard.revision();const request=String(input).startsWith(`${configuration.providerUrl}/auth/v1/oauth/authorizations/`)?authorizationRequest:undefined;const rejectStale=()=>{if(request)request.rejected=true;throw new BrowserAuthError("stale")};if(request&&(!request.current()||!guard.canAuthorize(new Headers(init2?.headers).get("authorization")?.replace(/^Bearer /,"")??"")))rejectStale();const response2=await fetch(input,{...init2,redirect:"error"});const body=await response2.arrayBuffer();if(!guard.current(revision)||request&&!request.current())rejectStale();const result2=new Response([204,205,304].includes(response2.status)?null:body,{status:response2.status,statusText:response2.statusText,headers:response2.headers});const json3=result2.json.bind(result2);result2.json=async()=>{const value=await json3();if(!guard.current(revision)||request&&!request.current())rejectStale();if(value&&typeof value.access_token==="string")provenance.set(value.access_token,revision);return value};return result2},{preconnect:fetch.preconnect})});async function authorization(kind,id3,current){const previous=authorizationQueue;let release;authorizationQueue=new Promise((resolve)=>{release=resolve});await previous;const request={current,rejected:false};authorizationRequest=request;try{if(!current())throw new BrowserAuthError("stale");const result2=await(kind==="get"?client.oauth.getAuthorizationDetails(id3):kind==="approve"?client.oauth.approveAuthorization(id3,{skipBrowserRedirect:true}):client.oauth.denyAuthorization(id3,{skipBrowserRedirect:true}));if(request.rejected||!current())throw new BrowserAuthError("stale");return result2}catch(error){if(request.rejected||!current())throw new BrowserAuthError("stale");throw error}finally{authorizationRequest=undefined;release()}}return{authorization:{get:(id3,current)=>authorization("get",id3,current),approve:(id3,current)=>authorization("approve",id3,current),deny:(id3,current)=>authorization("deny",id3,current)},getSession:()=>client.getSession(),onAuthStateChange:(callback)=>client.onAuthStateChange((event,session)=>{const revision=session?provenance.get(session.access_token):undefined;if(revision!==undefined&&!guard.current(revision))return;callback(event,session);if(session)provenance.delete(session.access_token)}),signInWithOtp:(input)=>client.signInWithOtp(input),verifyOtp:(input)=>client.verifyOtp(input),async signOut(input){removalRevision=guard.revision();try{return await client.signOut(input)}finally{removalRevision=undefined}},dispose(){provenance.clear();client.dispose()}}}var auth=createBrowserAuth({provider,failure:(reason)=>new BrowserAuthError(reason)});var identifier=/^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/;var uuid=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;var isReason=(value)=>value==="not_enabled"||value==="authority_unavailable"||value==="execution_unavailable"||value==="invalid_input";class AppRoutineError extends Error{reason;constructor(reason){super(reason);this.reason=reason;this.name="AppRoutineError"}}function fail3(reason){throw new AppRoutineError(reason)}function object4(value){return Boolean(value)&&typeof value==="object"&&!Array.isArray(value)}function keys4(value,expected){return Object.keys(value).sort().join(",")===expected}function current(context){if(!context.isCurrent()||context.signal.aborted)fail3("authority_unavailable")}async function body(context,response2,maximum){try{const value=await appResponse(response2,maximum,context.signal);current(context);if(!response2.ok){if(object4(value)&&keys4(value,"error")&&isReason(value.error)){if(value.error==="authority_unavailable")context.invalidate();fail3(value.error)}fail3("authority_unavailable")}return value}catch(error){current(context);if(error instanceof AppResponseReadError)throw error;if(error instanceof AppRoutineError)throw error;return fail3("execution_unavailable")}}function descriptor(value,key){if(!object4(value)||!keys4(value,"after,key,routine,runId")||value.key!==key||typeof value.runId!=="string"||!uuid.test(value.runId)||value.after!==0||typeof value.routine!=="string"||!identifier.test(value.routine))fail3("execution_unavailable");return value}function safeValue(value,depth=0){if(depth>32)return false;if(value===null||typeof value==="string"||typeof value==="boolean")return true;if(typeof value==="number")return Number.isFinite(value);if(Array.isArray(value))return value.every((item)=>safeValue(item,depth+1));return object4(value)&&Object.entries(value).every(([key,item])=>!["__proto__","constructor","prototype"].includes(key)&&safeValue(item,depth+1))}function event(value,run,steps){if(!object4(value)||value.runId!==run.runId||value.key!==run.key||value.routine!==run.routine||!Number.isSafeInteger(value.sequence)||value.sequence<1||new TextEncoder().encode(JSON.stringify(value)).byteLength>16*1024)fail3("execution_unavailable");const common="key,routine,runId,sequence,";if(value.type==="started"&&keys4(value,common+"type")&&value.sequence===1)return{type:"started"};if(value.type==="step"&&typeof value.id==="string"&&identifier.test(value.id)&&(!steps||steps.includes(value.id))&&keys4(value,"id,"+common+(Object.hasOwn(value,"summary")?"summary,type":"type"))&&(!Object.hasOwn(value,"summary")||safeValue(value.summary))){return{type:"step",id:value.id,...Object.hasOwn(value,"summary")?{summary:value.summary}:{}}}if(value.type==="finished"){if(value.state==="succeeded"&&keys4(value,"key,"+(Object.hasOwn(value,"result")?"result,":"")+"routine,runId,sequence,state,type")&&(!Object.hasOwn(value,"result")||safeValue(value.result))){return{type:"finished",state:"succeeded",...Object.hasOwn(value,"result")?{result:value.result}:{}}}if(value.state==="failed"&&value.error==="execution_failed"&&keys4(value,"error,"+common+"state,type")){return{type:"finished",state:"failed",error:"execution_failed"}}if(value.state==="cancelled"&&keys4(value,common+"state,type"))return{type:"finished",state:"cancelled"}}return fail3("execution_unavailable")}async function pause(context,delay){current(context);await new Promise((resolve,reject)=>{const abort=()=>{clearTimeout(timer);reject(new AppRoutineError("authority_unavailable"))};const timer=setTimeout(()=>{context.signal.removeEventListener("abort",abort);resolve()},delay);context.signal.addEventListener("abort",abort,{once:true})});current(context)}function handle(context,run,steps){return Object.freeze({async*events(...args){if(args.length)fail3("invalid_input");let cursor=0,terminal=false,delay=100,retainedBytes=0;const seen=[];while(!terminal){current(context);let response2;try{response2=await context.requestRoutine(run.key,`runs/${run.runId}/events?after=${cursor}`)}catch{current(context);await pause(context,delay);delay=Math.min(delay*2,2000);continue}if(response2.status>=500){await response2.body?.cancel();await pause(context,delay);delay=Math.min(delay*2,2000);continue}let value;try{value=await body(context,response2,80*1024)}catch(error){if(!(error instanceof AppResponseReadError))throw error;await pause(context,delay);delay=Math.min(delay*2,2000);continue}if(!object4(value)||!keys4(value,"after,events,terminal")||!Array.isArray(value.events)||value.events.length>256||typeof value.terminal!=="boolean"||!Number.isSafeInteger(value.after))fail3("execution_unavailable");const delivery=[];for(const raw of value.events){const publicEvent=event(raw,run,steps);const encoded=JSON.stringify(raw);const sequence=raw.sequence;if(sequence<=cursor){if(seen[sequence-1]!==encoded)fail3("execution_unavailable");continue}if(terminal||sequence!==cursor+1||sequence>256||(cursor===0?publicEvent.type!=="started":publicEvent.type==="started"))fail3("execution_unavailable");retainedBytes+=new TextEncoder().encode(encoded).byteLength;if(retainedBytes>1024*1024)fail3("execution_unavailable");seen.push(encoded);cursor=sequence;terminal=publicEvent.type==="finished";delivery.push(publicEvent)}if(value.after!==cursor||value.terminal!==terminal)fail3("execution_unavailable");for(const item of delivery){current(context);yield item}delay=100;if(!terminal)await pause(context,delivery.length?100:250)}},async cancel(...args){if(args.length)fail3("invalid_input");try{const value=await body(context,await context.requestRoutine(run.key,`runs/${run.runId}/cancel`,{method:"POST"}),1024);if(!object4(value)||!keys4(value,"cancelled")||value.cancelled!==true)fail3("execution_unavailable")}catch(error){current(context);if(error instanceof AppRoutineError)throw error;fail3("execution_unavailable")}}})}async function appRoutineOperation(key,input,recover){let context;try{if(!identifier.test(key))fail3("authority_unavailable");const resolved=await resolveAppContext();if(resolved.kind!=="local")fail3("execution_unavailable");context=resolved;if(recover){const value2=await body(context,await context.requestRoutine(key,"runs"),16*1024);if(!object4(value2)||!keys4(value2,"runs")||!Array.isArray(value2.runs)||value2.runs.length>20)fail3("execution_unavailable");const runs=value2.runs.map((run)=>descriptor(run,key));if(new Set(runs.map((run)=>run.runId)).size!==runs.length||new Set(runs.map((run)=>run.routine)).size>1)fail3("execution_unavailable");return runs.map((run)=>handle(resolved,run))}const available=await body(context,await context.requestAvailability(key),16*1024);if(object4(available)&&keys4(available,"available,reason")&&available.available===false&&isReason(available.reason))fail3(available.reason);if(!object4(available)||!keys4(available,"available,steps")||available.available!==true||!Array.isArray(available.steps)||available.steps.length<1||available.steps.length>64||!available.steps.every((step)=>typeof step==="string"&&identifier.test(step))||new Set(available.steps).size!==available.steps.length)fail3("execution_unavailable");const steps=[...available.steps];let encoded;try{encoded=JSON.stringify(input);if(encoded===undefined||new TextEncoder().encode(encoded).byteLength>16*1024)fail3("invalid_input")}catch{fail3("invalid_input")}const value=await body(context,await context.requestRoutine(key,"runs",{method:"POST",body:`{"input":${encoded}}`}),16*1024);return handle(context,descriptor(value,key),steps)}catch(error){if(context)current(context);if(error instanceof AppRoutineError)throw error;return fail3(context?"execution_unavailable":"authority_unavailable")}}var authorityUnavailable=()=>({available:false,reason:"authority_unavailable"});var MAX_RESPONSE_BYTES=16*1024;async function availability(key){try{if(!/^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/.test(key))return authorityUnavailable();const context=await resolveAppContext();if(context.kind!=="local")return{available:false,reason:"execution_unavailable"};const response2=await context.requestAvailability(key);if(!response2.ok||response2.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json"){return authorityUnavailable()}const value=await appResponse(response2,MAX_RESPONSE_BYTES,context.signal);if(!context.isCurrent())return authorityUnavailable();if(!value||typeof value!=="object"||Array.isArray(value))return authorityUnavailable();const result2=value;if(result2.available===false&&Object.keys(result2).sort().join(",")==="available,reason"&&(result2.reason==="not_enabled"||result2.reason==="authority_unavailable"||result2.reason==="execution_unavailable")){return{available:false,reason:result2.reason}}if(result2.available!==true||Object.keys(result2).sort().join(",")!=="available,steps"||!Array.isArray(result2.steps)||result2.steps.length<1||result2.steps.length>64||!result2.steps.every((step)=>typeof step==="string"&&/^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/.test(step))||new Set(result2.steps).size!==result2.steps.length)return authorityUnavailable();return{available:true,steps:[...result2.steps]}}catch{return authorityUnavailable()}}var app=Object.freeze({routines:new Proxy(Object.create(null),{get(_target,key){if(typeof key!=="string")return;return Object.freeze({availability:(...args)=>args.length?Promise.resolve(authorityUnavailable()):availability(key),run:(...args)=>args.length===1?appRoutineOperation(key,args[0],false):Promise.reject(new AppRoutineError("invalid_input")),recover:(...args)=>args.length===0?appRoutineOperation(key,undefined,true):Promise.reject(new AppRoutineError("invalid_input"))})},set:()=>false,defineProperty:()=>false,deleteProperty:()=>false})});var LIMIT2=16*1024;var context;var unavailable3=()=>new Error("App routine reporting unavailable");function freeze2(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))freeze2(child);Object.freeze(value)}return value}if((typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__)&&typeof process!=="undefined"&&process.env.ODDINGTON_APP_RUN!==undefined){let fail4=function(){broken=true;pending?.reject(unavailable3());pending=undefined;channel.destroy()},report=function(value){let frame;try{frame=JSON.stringify({...value,sequence:++sequence});if(Buffer.byteLength(frame)>LIMIT2)return rejected()}catch{return rejected()}const operation2=queue.then(async()=>{if(broken)throw unavailable3();await new Promise((resolve,reject)=>{const timeout=setTimeout(fail4,30000);pending={sequence:JSON.parse(frame).sequence,resolve(){clearTimeout(timeout);resolve()},reject(error){clearTimeout(timeout);reject(error)}};channel.ref();channel.write(`${frame}
|
|
76
|
+
`,(error)=>{if(error)fail3()})})};let reporting=Promise.resolve();const report=(value)=>{const captured=structuredClone(value);const next=reporting.then(()=>sendReport(captured));reporting=next;return next};const flush=(stream)=>new Promise((resolve)=>{let timer,settled2=false;const complete=()=>{if(settled2)return;settled2=true;if(timer)clearTimeout(timer);resolve()};timer=setTimeout(complete,1000);if(stream.destroyed||stream.writableEnded)complete();else stream.write("",complete)});let exitCode=0;try{const definition=(await import(pathToFileURL(bootstrap.entry).href)).default;const contract=inspectRoutineDefinition(definition);if(bootstrap.mode==="inspect")await report({type:"contract",contract});else if(bootstrap.mode==="execute"&&typeof bootstrap.runId==="string"){const input=captureRoutineInput(definition,bootstrap.input);if(JSON.stringify(contract)!==JSON.stringify(bootstrap.contract))throw new Error("Routine definition changed");observeLocalRoutineEffects(report);const result2=await executeRoutineDefinition(definition,input,{run:{id:bootstrap.runId},data,files,connections,inbox:routinePublicationClient(),step:async(id2,fact)=>report({type:"step",id:id2,...fact})});await report({type:"finish",...result2===undefined?{}:{result:result2}})}else throw new Error("Invalid routine bootstrap")}catch{exitCode=1}finally{settled=true;observeLocalRoutineEffects(undefined);if(exitCode===0)channel.end();else channel.destroy();await Promise.allSettled([flush(process.stdout),flush(process.stderr)]);process.exit(exitCode)}}})}init_inbox_contract();var RECORD_WRITE_INPUT_LIMIT=8*1024*1024;class RoutineRecordWriteError extends Error{effect;constructor(message,effect){super(message);this.effect=effect;this.name="RoutineRecordWriteError"}}function validateRecordWrite(value){const input=serializable(value);if(!input||Array.isArray(input)||typeof input!=="object"||Object.keys(input).sort().join(",")!=="records,repository"||!validRepositoryAlias(input.repository)||!Array.isArray(input.records)||!input.records.length||input.records.length>1e4||new Set(input.records.map((edit)=>edit?.ref)).size!==input.records.length)throw new InboxContractError("Invalid record update batch");for(const edit of input.records){if(!edit||Array.isArray(edit)||typeof edit!=="object"||!validRecordRef(edit.ref))throw new InboxContractError("Invalid record edit");if("expectedVersion"in edit){if(Object.keys(edit).sort().join(",")!=="expectedVersion,ref,set"||typeof edit.expectedVersion!=="string"||!/^record-v1:[0-9a-f]{64}$/.test(edit.expectedVersion)||!edit.set||Array.isArray(edit.set)||typeof edit.set!=="object"||!Object.keys(edit.set).length)throw new InboxContractError("Invalid record edit");continue}if(Object.keys(edit).sort().join(",")!=="fields,path,ref"||typeof edit.path!=="string"||!validCreatePath(edit.path)||!edit.fields||Array.isArray(edit.fields)||typeof edit.fields!=="object"||!Object.keys(edit.fields).length)throw new InboxContractError("Invalid record creation")}return structuredClone(input)}function validateRecordUpdate(value){const input=validateRecordWrite(value);if(input.records.some((record3)=>!("expectedVersion"in record3)))throw new InboxContractError("Record creation is unavailable for this operation");return input}function validateRecordDelete(value){const input=serializable(value);if(!input||Array.isArray(input)||typeof input!=="object"||Object.keys(input).sort().join(",")!=="records,repository"||!validRepositoryAlias(input.repository)||!Array.isArray(input.records)||!input.records.length||input.records.length>1e4||new Set(input.records.map((record3)=>record3?.ref)).size!==input.records.length)throw new InboxContractError("Invalid record deletion batch");for(const record3 of input.records){if(!record3||Array.isArray(record3)||typeof record3!=="object"||Object.keys(record3).sort().join(",")!=="expectedVersion,ref"||!validRecordRef(record3.ref)||typeof record3.expectedVersion!=="string"||!/^record-v1:[0-9a-f]{64}$/.test(record3.expectedVersion))throw new InboxContractError("Invalid record deletion")}return structuredClone(input)}function validateRecordChange(value){const input=serializable(value);if(!input||Array.isArray(input)||typeof input!=="object"||Object.keys(input).sort().join(",")!=="records,repository"||!validRepositoryAlias(input.repository)||!Array.isArray(input.records)||!input.records.length||input.records.length>1e4||new Set(input.records.map((record3)=>record3?.ref)).size!==input.records.length||new TextEncoder().encode(JSON.stringify(input)).byteLength>RECORD_WRITE_INPUT_LIMIT)throw new InboxContractError("Invalid record change batch");const writes=[],deletes=[];for(const record3 of input.records){if(!record3||typeof record3!=="object"||Array.isArray(record3))throw new InboxContractError("Invalid record change");if("set"in record3||"fields"in record3)writes.push(record3);else deletes.push(record3)}if(writes.length)validateRecordWrite({repository:input.repository,records:writes});if(deletes.length)validateRecordDelete({repository:input.repository,records:deletes});return structuredClone(input)}function validateRoutineRecordWrite(value){const body=serializable(value);if(!body||typeof body!=="object"||Array.isArray(body)||Object.keys(body).sort().join(",")!=="input,requestKey"||typeof body.requestKey!=="string"||!body.requestKey.trim()||body.requestKey!==body.requestKey.trim()||body.requestKey.length>512)throw new InboxContractError("A stable routine request key is required");return{input:validateRecordChange(body.input),requestKey:body.requestKey}}function validCreatePath(value){return value===value.trim()&&value.endsWith(".md")&&!value.startsWith("/")&&value.split("/").every((segment)=>!!segment&&![".",".."].includes(segment)&&/^[a-zA-Z0-9_.-]+$/.test(segment))}class InboxOperationError extends Error{status;reason;constructor(status,reason){super(reason==="conflict"?"This question already has an accepted answer":reason==="unavailable"?"Inbox request unavailable. Retry the same action.":reason==="invalid_input"?"Invalid Inbox request":"Inbox access unavailable");this.status=status;this.reason=reason}}var INBOX_RESULT_BYTES=8*1024*1024;var INBOX_INPUT_BYTES=8192;var INBOX_LOCAL_INPUT_BYTES=256*1024;var INBOX_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function isAppQuestionOperation(operation2){return operation2==="questions.list"||operation2==="questions.answer"||operation2==="questions.searchRecords"}var operations={current:[],"items.list":[],"questions.list":[],"items.read":["itemId"],"items.see":["itemId"],"items.markDigestRead":["itemId"],"items.rename":["itemId","revision","title"],"items.setLifecycle":["itemId","revision","lifecycle"],"items.listRecipientCandidates":["itemId"],"items.addRecipient":["itemId","personId"],"questions.answer":["itemId","revision","questionId","response"],"questions.searchRecords":["itemId","revision","questionId","query"],"files.read":["itemId","fileId"]};function assert(value){if(!value)throw new Error("Invalid Inbox result")}function object4(value){assert(value&&typeof value==="object"&&!Array.isArray(value)&&[Object.prototype,null].includes(Object.getPrototypeOf(value))&&Reflect.ownKeys(value).every((key)=>{const descriptor=typeof key==="string"?Object.getOwnPropertyDescriptor(value,key):undefined;return!!descriptor?.enumerable&&"value"in descriptor}));return value}function keys3(value,allowed,required=allowed){assert(Object.keys(value).every((key)=>allowed.includes(key))&&required.every((key)=>Object.hasOwn(value,key)))}function text3(value,empty2=false){return typeof value==="string"&&(empty2||!!value.trim())}function id2(value){return typeof value==="string"&&INBOX_UUID.test(value)}function integer(value,minimum=1){return Number.isSafeInteger(value)&&Number(value)>=minimum}function date(value){return text3(value)&&Number.isFinite(Date.parse(value))}function optionalDate(value){return value===null||date(value)}function array2(value){assert(Array.isArray(value)&&Object.getPrototypeOf(value)===Array.prototype&&Reflect.ownKeys(value).length===value.length+1&&value.every((_entry,index)=>{const descriptor=Object.getOwnPropertyDescriptor(value,String(index));return!!descriptor?.enumerable&&"value"in descriptor}));return value}function json2(value,ancestors=new Set){if(value===null||typeof value==="boolean"||typeof value==="string"||typeof value==="number"&&Number.isFinite(value))return value;assert(value&&typeof value==="object"&&!ancestors.has(value));ancestors.add(value);try{if(Array.isArray(value))return array2(value).map((entry)=>json2(entry,ancestors));return Object.fromEntries(Object.entries(object4(value)).map(([key,entry])=>[key,json2(entry,ancestors)]))}finally{ancestors.delete(value)}}function recordReference(value){const record3=object4(value);keys3(record3,["repository","ref"]);assert(text3(record3.repository)&&record3.repository===record3.repository.trim()&&/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(record3.repository)&&!/\.\.|\/\//.test(record3.repository)&&text3(record3.ref)&&record3.ref===record3.ref.trim()&&record3.ref.length<=512&&/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(record3.ref));return record3}function responseDefinition(value){const definition=object4(value);keys3(definition,["type","source"]);assert(definition.type==="selection");const source=object4(definition.source);if(source.type==="authored"){keys3(source,["type","options","suggestions","search"],["type","options"]);const options=array2(source.options);assert(options.length>0);const values=options.map((value2)=>{const option=object4(value2);keys3(option,["value","label","description","note"],["value","label"]);assert(text3(option.value)&&option.value===option.value.trim()&&text3(option.label));if("description"in option)assert(text3(option.description));if("note"in option){const note=object4(option.note);keys3(note,["placeholder"]);assert(text3(note.placeholder))}return option.value});assert(new Set(values).size===values.length);if("search"in source||"suggestions"in source){const search=object4(source.search);keys3(search,["triggerLabel","placeholder","emptyLabel"]);assert(text3(search.triggerLabel)&&text3(search.placeholder)&&text3(search.emptyLabel));const suggestions2=array2(source.suggestions);assert(suggestions2.length<=8&&suggestions2.every((value2)=>text3(value2)&&values.includes(value2))&&new Set(suggestions2).size===suggestions2.length)}else assert(options.length<=9);return}assert(source.type==="records");keys3(source,["type","collection","refPrefix","where","display","suggestions"],["type","collection","display"]);const collection=object4(source.collection);keys3(collection,["repository","name"]);recordReference({repository:collection.repository,ref:"records/example"});assert(text3(collection.name)&&/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(collection.name));if("refPrefix"in source)assert(text3(source.refPrefix)&&source.refPrefix.length<=512&&/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)*\/$/.test(source.refPrefix));const where=object4(source.where??{});assert(Object.entries(where).every(([name,value2])=>/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name)&&!["constructor","prototype"].includes(name)&&(value2===null||typeof value2==="string"||typeof value2==="boolean"||typeof value2==="number"&&Number.isFinite(value2))));const display=object4(source.display);keys3(display,["labelFields"]);const labels=array2(display.labelFields);assert(labels.length>0&&labels.length<=2&&new Set(labels).size===labels.length&&labels.every((value2)=>text3(value2)&&/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(value2)));const suggestions=array2(source.suggestions??[]);const refs=suggestions.map((value2)=>{const suggestion=object4(value2);keys3(suggestion,["record","reason"],["record"]);const record3=recordReference(suggestion.record);assert(record3.repository===collection.repository);if("reason"in suggestion)assert(text3(suggestion.reason));return record3.ref});assert(suggestions.length<=8&&new Set(refs).size===refs.length)}function inboxFile(value){const file2=object4(value);keys3(file2,["id","name","mediaType","size","sha256","details"]);assert(id2(file2.id)&&text3(file2.name)&&!/[\x00-\x1f\x7f/\\]/.test(file2.name)&&text3(file2.mediaType)&&/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(file2.mediaType)&&integer(file2.size,0)&&file2.size<=25*1024*1024&&typeof file2.sha256==="string"&&/^[0-9a-f]{64}$/.test(file2.sha256));const details=object4(file2.details);if(details.kind==="csv"){keys3(details,["kind","encoding","delimiter","headerRow","dataRows"]);assert(file2.mediaType==="text/csv"&&["utf-8","windows-1252"].includes(String(details.encoding))&&[",",";","\t"].includes(String(details.delimiter))&&integer(details.headerRow,0)&&integer(details.dataRows,0))}else if(details.kind==="pdf"){keys3(details,["kind","pages"],["kind"]);assert(file2.mediaType==="application/pdf"&&(!("pages"in details)||integer(details.pages)))}else{keys3(details,["kind"]);assert(details.kind==="other"&&!["text/csv","application/pdf"].includes(file2.mediaType))}}function fields5(value){const labels=array2(value).map((value2)=>{const field=object4(value2);keys3(field,["label","value"]);assert(text3(field.label)&&text3(field.value));return field.label});assert(new Set(labels).size===labels.length)}function block(value){const entry=object4(value);if(entry.kind==="rich-text"){keys3(entry,["kind","markdown"]);assert(text3(entry.markdown));return}if(entry.kind==="asks"){keys3(entry,["kind","problem","asks"]);const asks=array2(entry.asks);assert(text3(entry.problem)&&asks.length>0&&asks.every(id2)&&new Set(asks).size===asks.length);return}assert(["record","records","files"].includes(String(entry.kind)));keys3(entry,["kind","label","initiallyExpanded",...entry.kind==="record"?["record","view"]:entry.kind==="records"?["records","view"]:["files"]],["kind","label",entry.kind==="record"?"record":entry.kind==="records"?"records":"files"]);assert(text3(entry.label)&&(!("initiallyExpanded"in entry)||typeof entry.initiallyExpanded==="boolean")&&(!("view"in entry)||text3(entry.view)&&entry.view===entry.view.trim()));if(entry.kind==="record"){const record3=object4(entry.record);keys3(record3,["ref","title","fields"]);assert(text3(record3.ref)&&record3.ref===record3.ref.trim()&&text3(record3.title));fields5(record3.fields);return}if(entry.kind==="records"){const records=array2(entry.records);const refs=records.map((value2)=>{const record3=object4(value2);keys3(record3,["ref","title","description","facts","view"],["ref","title"]);assert(text3(record3.ref)&&record3.ref===record3.ref.trim()&&text3(record3.title));if("description"in record3)assert(text3(record3.description));if("facts"in record3)fields5(record3.facts);if("view"in record3)assert(text3(record3.view)&&record3.view===record3.view.trim());return record3.ref});assert(records.length>0&&new Set(refs).size===refs.length);return}const files2=array2(entry.files);files2.forEach(inboxFile);assert(files2.length>0&&new Set(files2.map((value2)=>object4(value2).id)).size===files2.length)}function response(value){const answer=object4(value);assert(Object.keys(answer).every((key)=>["selection","note"].includes(key)));if(typeof answer.selection==="string")assert(text3(answer.selection)&&answer.selection===answer.selection.trim());else recordReference(answer.selection);if(Object.hasOwn(answer,"note"))assert(text3(answer.note));return answer}function parseInboxRequest(value,questionListContext="local"){try{const envelope=object4(value);assert(Object.keys(envelope).sort().join(",")==="input,operation");assert(typeof envelope.operation==="string"&&Object.hasOwn(operations,envelope.operation));const operation2=envelope.operation;const input={...object4(envelope.input)};const required=operations[operation2];assert(required.every((key)=>Object.hasOwn(input,key))&&Object.keys(input).every((key)=>required.includes(key)||operation2==="questions.searchRecords"&&key==="selected"||(operation2==="items.list"||operation2==="questions.list")&&key==="beforeNumber"||operation2==="questions.list"&&questionListContext==="hosted"&&key==="routines"));if(operation2==="questions.list"&&questionListContext==="hosted"){assert(Object.hasOwn(input,"routines"));assert(array2(input.routines).every(isAppRoutineName))}for(const key of["itemId","personId","fileId"])if(key in input)assert(id2(input[key]));if("revision"in input)assert(integer(input.revision));if("beforeNumber"in input)assert(integer(input.beforeNumber));if("questionId"in input)assert(text3(input.questionId)&&input.questionId===input.questionId.trim());if("title"in input)assert(text3(input.title));if("lifecycle"in input)assert(input.lifecycle==="open"||input.lifecycle==="closed");if("query"in input)assert(text3(input.query,true)&&input.query.length<=256);if("selected"in input)recordReference(input.selected);if("response"in input)response(input.response);assert(new TextEncoder().encode(JSON.stringify(envelope)).byteLength<=INBOX_INPUT_BYTES);if("routines"in input)input.routines=[...new Set(input.routines)];return{operation:operation2,input}}catch{throw new InboxOperationError(400,"invalid_input")}}function parseInboxCurrent(value){const current=object4(value),workspace=object4(current.workspace),viewer=object4(current.viewer);assert(id2(workspace.id)&&text3(workspace.slug)&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(workspace.slug)&&text3(workspace.name)&&text3(workspace.locale)&&text3(workspace.timezone));assert(id2(viewer.id)&&text3(viewer.name)&&text3(viewer.email));return{workspace:{id:workspace.id,slug:workspace.slug,name:workspace.name,locale:workspace.locale,timezone:workspace.timezone},viewer:{id:viewer.id,name:viewer.name,email:viewer.email}}}function parseInboxItem(value){const item=object4(json2(value));assert(id2(item.id)&&id2(item.workspaceId)&&integer(item.number)&&integer(item.revision)&&integer(item.activityVersion,0)&&["ask","digest"].includes(String(item.kind))&&["open","closed"].includes(String(item.lifecycle))&&text3(item.title)&&text3(item.description,true)&&text3(item.author)&&date(item.publishedAt)&&optionalDate(item.seenAt)&&optionalDate(item.digestReadAt));if(item.outcome!==null)assert(text3(object4(item.outcome).outcome));array2(item.body).forEach(block);array2(item.views).forEach((value2)=>{const view=object4(value2);assert(text3(view.id)&&text3(view.view)&&text3(view.implementation));json2(view.input)});array2(item.people).forEach((value2)=>{const person=object4(value2);assert(id2(person.id)&&text3(person.name))});array2(item.questions).forEach((value2)=>{const question2=object4(value2);assert(text3(question2.id)&&id2(question2.to)&&text3(question2.prompt)&&(question2.instructions===null||text3(question2.instructions,true))&&typeof question2.available==="boolean");responseDefinition(question2.response);assert(array2(question2.allowedResponders).every(id2));if(question2.acceptedResponse!==null){const accepted=object4(question2.acceptedResponse);assert(id2(accepted.id)&&id2(accepted.userId)&&date(accepted.acceptedAt));response(accepted.response);if(accepted.label===null)delete accepted.label;else if("label"in accepted)assert(text3(accepted.label));if("acceptanceOrder"in accepted)assert(integer(accepted.acceptanceOrder))}if(question2.execution!==null){const execution=object4(question2.execution);assert(id2(execution.id)&&["pending","running","completed","failed"].includes(String(execution.state))&&integer(execution.attempt,0));if("consequence"in execution){const consequence=object4(execution.consequence);assert(["pending","running","applied","no-write","stopped","partial","uncertain"].includes(String(consequence.state))&&(consequence.phase===null||["loading","invoking","committing"].includes(String(consequence.phase)))&&date(consequence.updatedAt)&&typeof consequence.needsReconciliation==="boolean"&&(consequence.reason===null||text3(consequence.reason,true)));array2(consequence.evidence).forEach((value3)=>{const receipt=object4(value3);assert(text3(receipt.repository)&&text3(receipt.commit)&&text3(receipt.diff,true))})}}});array2(item.linkedAsks).forEach((value2)=>{const linked=object4(value2);assert(id2(linked.id));if(linked.state==="unavailable")assert(typeof linked.done==="boolean");else{assert(["yours","done","open","theirs"].includes(String(linked.state))&&text3(linked.title));if(linked.state==="theirs"){const assignee=object4(linked.assignee);assert(id2(assignee.id)&&text3(assignee.name))}}});array2(item.activity).forEach((value2)=>{const event=object4(value2);assert(integer(event.id)&&text3(event.type)&&(event.actorId===null||id2(event.actorId))&&(event.questionId===null||text3(event.questionId))&&integer(event.revision)&&date(event.createdAt));object4(event.data)});array2(item.work).forEach((value2)=>{const work=object4(value2);assert(id2(work.id)&&text3(work.questionId)&&text3(work.reason)&&optionalDate(work.settledAt))});return item}function parseAnswerableQuestion(value){const entry=object4(json2(value));keys3(entry,["item","origin","question","recordRefs"]);const item=object4(entry.item);keys3(item,["id","number","revision","title","href"]);assert(id2(item.id)&&integer(item.number)&&integer(item.revision)&&text3(item.title)&&text3(item.href));const link=new URL(item.href);const slug=link.hostname.slice(0,-".oddington.ai".length);assert(link.hostname.endsWith(".oddington.ai")&&slug.length<=63&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)&&!["auth","www","api","os"].includes(slug)&&item.href===`https://${slug}.oddington.ai/inbox/${item.id}`);const origin=object4(entry.origin);keys3(origin,["routine"]);assert(text3(origin.routine)&&origin.routine===origin.routine.trim());const question2=object4(entry.question);keys3(question2,["id","prompt","instructions","response"]);assert(text3(question2.id)&&question2.id===question2.id.trim()&&text3(question2.prompt)&&(question2.instructions===null||text3(question2.instructions,true)));responseDefinition(question2.response);const refs=array2(entry.recordRefs);assert(refs.every((ref)=>text3(ref)&&ref===ref.trim())&&new Set(refs).size===refs.length);return entry}function parseInboxAcceptance(value){const accepted=object4(value);assert(id2(accepted.responseId)&&date(accepted.acceptedAt));if("executionId"in accepted)assert(id2(accepted.executionId));if("acceptanceOrder"in accepted)assert(integer(accepted.acceptanceOrder));if("label"in accepted)assert(text3(accepted.label));return accepted}function parseInboxResult(operation2,value){if(operation2==="current")return parseInboxCurrent(value);if(operation2==="questions.list"){const page=object4(value);keys3(page,["questions","nextBeforeNumber"]);const questions=array2(page.questions).map(parseAnswerableQuestion);assert(page.nextBeforeNumber===null||integer(page.nextBeforeNumber));return{questions,nextBeforeNumber:page.nextBeforeNumber}}if(operation2==="items.read")return parseInboxItem(value);if(operation2==="items.list"){const page=object4(value);const items=array2(page.items).map(parseInboxItem);assert(items.length<=100&&(page.nextBeforeNumber===null||integer(page.nextBeforeNumber)));return{items,nextBeforeNumber:page.nextBeforeNumber}}if(operation2==="items.see"){assert(date(value));return}if(operation2==="items.markDigestRead"){const read2=object4(value);assert(integer(read2.activityId)&&date(read2.readAt));return read2}if(operation2==="items.rename"||operation2==="items.setLifecycle"){const update=object4(value);const item=parseInboxItem(update.item);assert((update.activityId===null||integer(update.activityId))&&optionalDate(update.changedAt));return{...update,item}}if(operation2==="items.listRecipientCandidates"){const candidates=array2(value);candidates.forEach((value2)=>{const person=object4(value2);assert(id2(person.id)&&text3(person.name)&&text3(person.email))});assert(new Set(candidates.map((value2)=>object4(value2).id)).size===candidates.length);return candidates}if(operation2==="items.addRecipient"){const addition=object4(value);const item=parseInboxItem(addition.item);assert(id2(addition.addedPersonId)&&item.people.some((person)=>person.id===addition.addedPersonId));return{...addition,item}}if(operation2==="questions.answer")return parseInboxAcceptance(value);if(operation2==="questions.searchRecords"){const result2=object4(value);assert(text3(result2.recordType)&&integer(result2.eligibleCount,0)&&integer(result2.matchCount,0)&&Number(result2.matchCount)<=Number(result2.eligibleCount));const labeled=(value2)=>{const record3=object4(value2);recordReference({repository:record3.repository,ref:record3.ref});assert(text3(record3.label));if("reason"in record3)assert(text3(record3.reason))};array2(result2.matches).forEach(labeled);array2(result2.suggestions).forEach(labeled);if("selected"in result2)labeled(result2.selected);return result2}throw new Error("File content is not a JSON result")}async function limitedBody(request,limit,timeoutMs){if(!request.body)return new Uint8Array;const reader=request.body.getReader();let expired=false;const timer=timeoutMs===undefined?undefined:setTimeout(()=>{expired=true;reader.cancel().catch(()=>{})},timeoutMs);const chunks=[];let length=0;try{while(true){const{done,value}=await reader.read();if(done)break;length+=value.byteLength;if(length>limit){await reader.cancel();return}chunks.push(value)}if(expired)return;const contents=new Uint8Array(length);let offset=0;for(const chunk of chunks){contents.set(chunk,offset);offset+=chunk.byteLength}return contents}finally{if(timer!==undefined)clearTimeout(timer)}}var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function parseInboxHostContext(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Inbox context unavailable");const v=value;if(v.kind!=="inbox"&&v.kind!=="focused"||Object.keys(v).sort().join(",")!==(v.kind==="inbox"?"generation,kind,memberId,workspaceId":"appId,generation,kind,memberId,workspaceId")||typeof v.workspaceId!=="string"||!UUID.test(v.workspaceId)||typeof v.memberId!=="string"||!UUID.test(v.memberId)||typeof v.generation!=="string"||!UUID.test(v.generation)||v.kind==="focused"&&(typeof v.appId!=="string"||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(v.appId)))throw new Error("Inbox context unavailable");const base={workspaceId:v.workspaceId,memberId:v.memberId,generation:v.generation};return Object.freeze(v.kind==="inbox"?{...base,kind:"inbox"}:{...base,kind:"focused",appId:v.appId})}class InboxContextError extends Error{status;constructor(status){super("Inbox context unavailable");this.status=status}}var contexts=new WeakMap;function resolveHostedInboxContext(host){if(!host.binding||!host.memberId)throw new Error("Inbox context unavailable");let resolve=contexts.get(host.binding);if(!resolve){resolve=hostedInboxContext();contexts.set(host.binding,resolve)}return resolve({...host,memberId:host.memberId})}function hostedInboxContext(){let installed2;let revision=0,issued=0,settled=0;return async(host)=>{const started=++issued;const check=()=>{if(!host.isCurrent()||host.expiresAt<=Date.now())throw new Error("Inbox context unavailable")};check();const response2=await fetch(`${host.endpoint}/api/inbox/context`,{method:"GET",headers:{authorization:`Bearer ${host.accessToken}`},credentials:"omit",redirect:"error",cache:"no-store",signal:AbortSignal.timeout(15000)});try{check();if(response2.status===401||response2.status===403){installed2=undefined;revision++;settled=Math.max(settled,started)}if(!response2.ok||response2.status!==200)throw new InboxContextError(response2.status);const bytes=await limitedBody(response2,4096);check();if(!bytes)throw new Error("Inbox context unavailable");const context=parseInboxHostContext(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)));if(context.memberId!==host.memberId)throw new Error("Inbox context unavailable");if(JSON.stringify(installed2)!==JSON.stringify(context)){if(started<settled)throw new Error("Inbox context unavailable");installed2=context;revision++}settled=Math.max(settled,started);const current=revision;return Object.freeze({context,isCurrent:()=>host.isCurrent()&&host.expiresAt>Date.now()&¤t===revision})}finally{response2.body?.cancel().catch(()=>{})}}}var sessionKey="_os.app.session";var responseChecks=new WeakMap;class AppResponseReadError extends Error{}class AppContextDenied extends Error{}class AppRenewalUnavailable extends Error{}async function untilAborted(work,signal){if(signal.aborted){work.catch(()=>{});throw new AppRenewalUnavailable}let abort;const cancelled=new Promise((_resolve,reject)=>{abort=()=>reject(new AppRenewalUnavailable);signal.addEventListener("abort",abort,{once:true})});try{return await Promise.race([work,cancelled])}finally{signal.removeEventListener("abort",abort)}}async function appResponse(response2,maximum,signal){if(signal.aborted||!response2.body||response2.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json")throw new Error;const reader=response2.body.getReader();const abort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",abort,{once:true});let bytes=0,text4="";const decoder=new TextDecoder("utf-8",{fatal:true});try{while(true){let chunk;try{chunk=await reader.read()}catch{throw new AppResponseReadError}if(signal.aborted)throw new Error;if(chunk.done){const value=JSON.parse(text4+decoder.decode());await responseChecks.get(response2)?.(value);if(signal.aborted)throw new Error;return value}bytes+=chunk.value.byteLength;if(bytes>maximum){abort();throw new Error}text4+=decoder.decode(chunk.value,{stream:true})}}finally{signal.removeEventListener("abort",abort);reader.releaseLock()}}function isAppOrigin(value){try{const url=new URL(value);return url.protocol==="http:"&&url.hostname==="127.0.0.1"&&Boolean(url.port)&&url.port!=="0"&&url.origin===value}catch{return false}}function appContext(origin,active2){let binding;let credential;let pair;let serialized;let denied=false;const controller=new AbortController;let access=new AbortController;let expiry;let startup;let renewalTimer;let renewal;let observation;let resolution2;let disposed=false;const stored=()=>globalThis.localStorage.getItem(sessionKey);const alive=()=>{try{return!denied&&!disposed&&active2()&&globalThis.location.origin===origin}catch{return false}};const cancel=()=>{controller.abort();access.abort();clearTimeout(expiry);clearTimeout(startup);clearTimeout(renewalTimer);clearInterval(monitor);globalThis.removeEventListener?.("storage",storageChanged);for(const event of["pageshow","focus","visibilitychange"])globalThis.removeEventListener?.(event,wake)};const invalidate=()=>{denied=true;cancel();try{if(!disposed&&active2()&&globalThis.location.origin===origin&&(!serialized||globalThis.localStorage.getItem(sessionKey)===serialized)){globalThis.localStorage.removeItem(sessionKey)}}catch{}};const current=()=>{try{return alive()&&!!binding&&binding.expiresAt>Date.now()&&stored()===serialized}catch{return false}};const sameSession=(value)=>!binding||["appId","memberId","workspace","sessionId"].every((key)=>value[key]===binding[key]);const bounded=(value)=>validBinding(value)&&value.expiresAt>Date.now()&&value.expiresAt<=Date.now()+600000&&sameSession(value);const readPair=(candidate)=>{const value=JSON.parse(candidate??"null");if(!validPair(value)||value.context.expiresAt>Date.now()+600000||!sameSession(value.context))throw new Error;return value};const expireAccess=()=>{if(binding&&binding.expiresAt<=Date.now())access.abort()};async function send2(path,candidate,signal,init={}){const url=`${origin}/_os/app/${path}`;let response2;try{response2=await fetch(url,{...init,credentials:"omit",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer",signal,headers:{...init.body===undefined?{}:{"content-type":"application/json"},authorization:`Bearer ${candidate}`}})}catch{throw new AppRenewalUnavailable}if(response2.redirected||response2.url&&response2.url!==url)throw new Error;return response2}async function proof(candidate,signal=controller.signal){if(!alive()||!validProof(candidate))throw new Error;const response2=await send2("context",candidate,signal);if(response2.status===401||response2.status===403)throw new AppContextDenied;if(response2.status>=500)throw new AppRenewalUnavailable;if(!response2.ok)throw new Error;const value=await appResponse(response2,4096,signal);if(!alive()||!bounded(value))throw new Error;return value}function install(value,candidate,raw){expireAccess();if(access.signal.aborted)access=new AbortController;binding={...value};pair=candidate;credential=candidate.credential;serialized=raw;clearTimeout(expiry);clearTimeout(renewalTimer);const remaining=binding.expiresAt-Date.now();expiry=setTimeout(expireAccess,remaining);renewalTimer=setTimeout(()=>{renew().catch(()=>{})},remaining-Math.min(60000,remaining/5))}async function synchronize(signal=controller.signal){if(!alive())throw new Error;if(signal.aborted)throw new AppRenewalUnavailable;if(!credential)return;if(stored()===serialized)return;if(!binding)throw new Error;if(observation)return untilAborted(observation,signal);observation=(async()=>{while(alive()){const candidate=stored();if(!candidate)throw new Error;let value;let replacement;try{replacement=readPair(candidate);value=await proof(replacement.credential,signal)}catch(error){if(stored()!==candidate)continue;throw error}if(stored()!==candidate)continue;if(value.expiresAt!==replacement.context.expiresAt)throw new Error;install(value,replacement,candidate);return}throw new Error})();const observed=observation;try{await untilAborted(observed,signal)}catch(error){if(!(error instanceof AppRenewalUnavailable||error instanceof AppResponseReadError))invalidate();throw error}finally{if(observation===observed)observation=undefined}}async function renew(){if(renewal)return renewal;if(!binding||!pair||!alive())throw new Error;renewal=(async()=>{const requestController=new AbortController;const abort=()=>requestController.abort();controller.signal.addEventListener("abort",abort,{once:true});const timeout=setTimeout(abort,20000);const previous=serialized;try{await synchronize(requestController.signal);if(serialized!==previous)return;const response2=await send2("renew",pair.renewalCredential,requestController.signal,{method:"POST"});const value=await appResponse(response2,4096,requestController.signal);if(response2.status===503&&value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).join(",")==="error"&&"error"in value&&value.error==="renewal_unavailable")throw new AppRenewalUnavailable;if(response2.status===403&&value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).join(",")==="error"&&"error"in value&&value.error==="renewal_conflict"){while(alive()&&stored()===previous&&!requestController.signal.aborted){await new Promise((resolve2,reject)=>{const abortWait=()=>{clearTimeout(timer);reject(new Error)};const timer=setTimeout(()=>{requestController.signal.removeEventListener("abort",abortWait);resolve2()},100);requestController.signal.addEventListener("abort",abortWait,{once:true})})}if(requestController.signal.aborted)throw new Error;await synchronize(requestController.signal);return}if(!response2.ok)throw new Error;if(!alive()||!validPair(value)||!bounded(value.context)||new Set([value.credential,value.renewalCredential,pair.credential,pair.renewalCredential]).size!==4)throw new Error;if(stored()!==previous){await synchronize(requestController.signal);return}const raw=JSON.stringify(value);globalThis.localStorage.setItem(sessionKey,raw);install(value.context,value,raw)}catch(error){try{if(alive()&&stored()&&stored()!==previous){await synchronize(requestController.signal);return}}catch{}if((error instanceof AppRenewalUnavailable||error instanceof AppResponseReadError||requestController.signal.aborted)&&alive()){if(current())renewalTimer=setTimeout(()=>{renew().catch(()=>{})},Math.min(5000,(binding.expiresAt-Date.now())/5))}else invalidate();throw new AppRenewalUnavailable}finally{clearTimeout(timeout);controller.signal.removeEventListener("abort",abort)}})();try{await renewal}finally{renewal=undefined}}const storageChanged=()=>{if(!credential)return;if(!alive()){invalidate();return}expireAccess();synchronize().catch(()=>{})};const monitor=setInterval(()=>{storageChanged()},100);globalThis.addEventListener?.("storage",storageChanged);const wake=()=>{if(alive())resolve().catch(()=>{})};for(const event of["pageshow","focus","visibilitychange"])globalThis.addEventListener?.(event,wake);const dispose=()=>{disposed=true;cancel()};async function settledAccess(signal){await synchronize();while(alive()&&stored()!==serialized)await synchronize();if(signal.aborted||!current())throw new Error}async function requestData(operation2,input){try{if(operation2!=="data/query"||!current())throw new Error;const admitted=credential;const signal=access.signal;const response2=await send2("data",credential,signal,{method:"POST",body:JSON.stringify(input)});await settledAccess(signal);if(response2.status===401||response2.status===403){if(admitted===credential&¤t())invalidate();throw new DataOperationError("access_denied")}const result2=await appResponse(response2,Number.MAX_SAFE_INTEGER,signal);await settledAccess(signal);if(!response2.ok)throw dataTransportError(response2.status,result2);return result2}catch(error){if(error instanceof DataOperationError)throw error;if(!current()||controller.signal.aborted)throw new DataOperationError("context_unavailable");throw new DataOperationError("unavailable",true)}}async function requestInbox(operation2,input){if(!["questions.list","questions.answer","questions.searchRecords"].includes(operation2))throw new Error("Inbox operation unavailable");return requestChecked("inbox",{method:"POST",body:JSON.stringify({operation:operation2,input})},true)}async function requestRoutine(key,suffix,init={}){return requestChecked(`routines/${encodeURIComponent(key)}/${suffix}`,init)}async function requestChecked(path,init,inbox=false){if(!current())throw new Error("Local app context unavailable.");const admitted=credential;const signal=access.signal;const response2=await send2(path,credential,signal,init);await settledAccess(signal);if((response2.status===401||!inbox&&response2.status===403)&&admitted===credential&¤t())invalidate();responseChecks.set(response2,async(value)=>{await settledAccess(signal);if(admitted===credential&¤t()&&value&&typeof value==="object"&&"error"in value&&value.error==="authority_unavailable")invalidate()});return response2}function context(){const issued=credential;const signal=access.signal;return{kind:"local",...binding,get expiresAt(){return binding.expiresAt},isCurrent:()=>!signal.aborted&¤t(),signal,invalidate:()=>{if(issued===credential&¤t())invalidate()},requestRoutine,requestData,requestInbox,requestAvailability:(key)=>requestRoutine(key,"availability",{method:"GET"})}}const resolveOnce=async()=>{let attempted;try{if(!alive())throw new Error;if(!pair){const candidate2=stored();const retained2=readPair(candidate2);pair=retained2;binding={...retained2.context};credential=retained2.credential;serialized=candidate2}expireAccess();if(binding.expiresAt<=Date.now()){await renew();if(!current())throw new AppRenewalUnavailable;return context()}await synchronize();const candidate=stored();const retained=readPair(candidate);attempted=candidate??undefined;if(!current())throw new AppRenewalUnavailable;const value=await proof(retained.credential);if(stored()!==candidate||serialized!==candidate){await synchronize();return context()}if(!current())throw new Error;if(expiry&&binding&&value.expiresAt>binding.expiresAt)throw new Error;if(!expiry||value.expiresAt!==binding.expiresAt)install(value,retained,candidate);return context()}catch(error){if(alive()&&error instanceof AppRenewalUnavailable)throw new Error;try{if(binding&¤t()&&attempted&&attempted!==serialized)return context();if(binding&&alive()&&stored()&&stored()!==serialized){await synchronize();return context()}}catch{}if(error instanceof AppContextDenied&&binding&&alive()&&renewal)throw new Error;if(alive()&&(error instanceof AppResponseReadError||pair&&stored()===serialized&&!current()))throw new Error;invalidate();throw new Error}};const resolve=()=>{if(resolution2)return resolution2;resolution2=resolveOnce().finally(()=>{resolution2=undefined});return resolution2};const start=()=>{startup=setTimeout(()=>{if(alive()&&!resolution2&&!binding)resolve().catch(()=>{})},0)};return{resolve,start,invalidate,dispose}}function validProof(value){return typeof value==="string"&&/^[A-Za-z0-9_-]{43}$/.test(value)}function validBinding(value){if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).sort().join(",")!=="appId,expiresAt,memberId,sessionId,workspace")return false;const binding=value;return typeof binding.appId==="string"&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(binding.appId)&&typeof binding.workspace==="string"&&/^[a-z0-9][a-z0-9-]{0,62}$/.test(binding.workspace)&&typeof binding.memberId==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(binding.memberId)&&validProof(binding.sessionId)&&typeof binding.expiresAt==="number"&&Number.isFinite(binding.expiresAt)}function validPair(value){if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).sort().join(",")!=="context,credential,renewalCredential")return false;const pair=value;return validProof(pair.credential)&&validProof(pair.renewalCredential)&&pair.credential!==pair.renewalCredential&&validBinding(pair.context)}var unavailable2=()=>new InboxOperationError(503,"unavailable");var stale=()=>new InboxOperationError(401,"authority_unavailable");function hostFailure(error,context){if(!context.isCurrent()||context.expiresAt<=Date.now()||error instanceof InboxContextError&&error.status===401)return stale();return error instanceof InboxContextError&&error.status===403?new InboxOperationError(403,"access_denied"):unavailable2()}async function send2(operation2,input){let envelope=operation2==="questions.list"?undefined:parseInboxRequest({operation:operation2,input});let context;try{context=await resolveAppContext()}catch{throw stale()}envelope??=parseInboxRequest({operation:operation2,input},context.kind==="local"?"local":"hosted");if(context.kind==="local"){if(!isAppQuestionOperation(operation2))throw new InboxOperationError(403,"access_denied");const check2=()=>{if(!context.isCurrent()||context.signal.aborted||context.expiresAt<=Date.now())throw stale()};try{const response2=await context.requestInbox(operation2,envelope.input);const value=await appResponse(response2,INBOX_RESULT_BYTES,context.signal);check2();if(!response2.ok)throw new InboxOperationError([400,401,403,409].includes(response2.status)?response2.status:503,response2.status===400?"invalid_input":response2.status===401?"authority_unavailable":response2.status===403?"access_denied":response2.status===409?"conflict":"unavailable");if(response2.status!==200)throw unavailable2();const parsed=parseInboxResult(operation2,value);check2();if(operation2==="questions.answer"&&typeof envelope.input.response.selection==="object"&&!parsed.label?.trim())throw unavailable2();return parsed}catch(error){check2();throw error instanceof InboxOperationError?error:unavailable2()}}if(context.endpoint!==`https://${context.workspace}.oddington.ai`||["auth","www","api","os"].includes(context.workspace))throw stale();let host;try{host=await resolveHostedInboxContext(context)}catch(error){throw hostFailure(error,context)}if(!host)throw unavailable2();const check=()=>{if(!context.isCurrent()||!host.isCurrent()||!Number.isFinite(context.expiresAt)||context.expiresAt<=Date.now())throw stale()};check();if(host.context.kind==="focused"&&!isAppQuestionOperation(operation2))throw new InboxOperationError(403,"access_denied");try{const response2=await fetch(`${context.endpoint}/api/inbox`,{method:"POST",headers:{authorization:`Bearer ${context.accessToken}`,"content-type":"application/json"},body:JSON.stringify(envelope),redirect:"error",cache:"no-store",signal:AbortSignal.timeout(30000)});try{check()}catch(error){response2.body?.cancel().catch(()=>{});throw error}if(!response2.ok){response2.body?.cancel().catch(()=>{});throw new InboxOperationError([400,401,403,409].includes(response2.status)?response2.status:503,response2.status===400?"invalid_input":response2.status===401?"authority_unavailable":response2.status===403?"access_denied":response2.status===409?"conflict":"unavailable")}if(response2.status!==200){response2.body?.cancel().catch(()=>{});throw unavailable2()}if(operation2==="files.read"){if(!response2.body)throw unavailable2();const source=response2.body;let reader;let size=0;const cancel=async(reason)=>{try{await(reader?reader.cancel(reason):source.cancel(reason))}finally{reader?.releaseLock()}};const body=new ReadableStream({async pull(controller){try{check();reader??=source.getReader();const next=await reader.read();check();if(next.done){reader.releaseLock();controller.close();return}size+=next.value.byteLength;if(size>25*1024*1024)throw unavailable2();controller.enqueue(next.value)}catch(error){controller.error(error);await cancel(error).catch(()=>{})}},cancel},{highWaterMark:0});return new Response(body,{status:response2.status,headers:response2.headers})}const bytes=await limitedBody(response2,INBOX_RESULT_BYTES);check();if(!bytes)throw unavailable2();const value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));const parsed=parseInboxResult(operation2,value);check();if(operation2==="current"&&parsed.workspace.slug!==context.workspace)throw unavailable2();if("itemId"in envelope.input){const item=operation2==="items.read"?parsed:operation2==="items.rename"||operation2==="items.setLifecycle"||operation2==="items.addRecipient"?parsed.item:undefined;if(item&&(item.id!==envelope.input.itemId||("revision"in envelope.input)&&item.revision!==envelope.input.revision))throw unavailable2();if(operation2==="items.addRecipient"&&parsed.addedPersonId!==envelope.input.personId)throw unavailable2();if(operation2==="questions.answer"&&typeof envelope.input.response.selection==="object"&&!parsed.label?.trim())throw unavailable2()}return parsed}catch(error){check();throw error instanceof InboxOperationError?error:unavailable2()}}var inbox={current:async()=>await send2("current",{}),items:{async list(){const items=[];let beforeNumber;let initial;try{initial=await resolveAppContext()}catch{throw stale()}let host;try{host=initial.kind!=="local"&&await resolveHostedInboxContext(initial)}catch(error){throw hostFailure(error,initial)}if(initial.kind==="local")throw new InboxOperationError(403,"access_denied");if(!host)throw unavailable2();const check=()=>{if(!initial.isCurrent()||!host.isCurrent()||initial.expiresAt<=Date.now())throw stale()};do{check();const page=await send2("items.list",beforeNumber===undefined?{}:{beforeNumber});check();if(beforeNumber!==undefined&&(page.items.some((item)=>item.number>=beforeNumber)||page.nextBeforeNumber!==null&&page.nextBeforeNumber>=beforeNumber))throw unavailable2();items.push(...page.items);if(page.nextBeforeNumber===null)return items;beforeNumber=page.nextBeforeNumber}while(true)},read:async(itemId)=>await send2("items.read",{itemId}),see:async(itemId)=>{await send2("items.see",{itemId})},markDigestRead:async(itemId)=>await send2("items.markDigestRead",{itemId}),rename:async(input)=>await send2("items.rename",input),setLifecycle:async(input)=>await send2("items.setLifecycle",input),listRecipientCandidates:async(itemId)=>await send2("items.listRecipientCandidates",{itemId}),addRecipient:async(input)=>await send2("items.addRecipient",input)},questions:{async list(input){const supplied=input===undefined?undefined:parseInboxRequest({operation:"questions.list",input},"hosted").input;if(supplied&&Object.hasOwn(supplied,"beforeNumber"))throw new InboxOperationError(400,"invalid_input");const routines=supplied?Object.freeze(supplied.routines):undefined;const questions=[];let beforeNumber;let initial;try{initial=await resolveAppContext()}catch{throw stale()}if(initial.kind==="local"?input!==undefined:routines===undefined)throw new InboxOperationError(400,"invalid_input");let host;try{host=initial.kind!=="local"&&await resolveHostedInboxContext(initial)}catch(error){throw hostFailure(error,initial)}if(initial.kind!=="local"&&!host)throw unavailable2();const check=()=>{if(!initial.isCurrent()||host&&!host.isCurrent()||initial.expiresAt<=Date.now())throw stale()};do{check();const page=await send2("questions.list",{...routines===undefined?{}:{routines},...beforeNumber===undefined?{}:{beforeNumber}});check();if(page.questions.some((question2)=>question2.item.href!==`https://${initial.workspace}.oddington.ai/inbox/${question2.item.id}`||routines!==undefined&&!routines.includes(question2.origin.routine))||beforeNumber!==undefined&&(page.questions.some((question2)=>question2.item.number>=beforeNumber)||page.nextBeforeNumber!==null&&page.nextBeforeNumber>=beforeNumber))throw unavailable2();questions.push(...page.questions);if(page.nextBeforeNumber===null)return questions;beforeNumber=page.nextBeforeNumber}while(true)},answer:async(input)=>await send2("questions.answer",input),searchRecords:async(input)=>await send2("questions.searchRecords",input)},files:{read:async(input)=>await send2("files.read",input)}};var sources=new WeakMap;function registerBrowserAuth(handle,source){sources.set(handle,source)}function browserAuthSource(handle){return sources.get(handle)}var installedDispose;function init({auth:input}){installedDispose?.();const registered=browserAuthSource(input);const auth=registered??input;if(!registered&&input&&"getState"in input||typeof auth?.getSession!=="function"||typeof auth?.onAuthStateChange!=="function"){installedDispose=installMemberContext(async()=>{throw new Error("Hosted Data context unavailable.")});return}let endpoint;let workspace;let localOrigin;try{const url=new URL(globalThis.location.origin);if(isAppOrigin(globalThis.location.origin))localOrigin=url.origin;const slug=url.hostname.endsWith(".oddington.ai")?url.hostname.slice(0,-".oddington.ai".length):"";if(url.protocol==="https:"&&!url.port&&!url.username&&!url.password&&!url.search&&!url.hash&&url.pathname==="/"&&/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(slug)&&slug!=="auth"){endpoint=url.origin;workspace=slug}}catch{}let active2=true;let revision=0;let person;let token;const binding={};const local=localOrigin?appContext(localOrigin,()=>active2):undefined;let subscription;let stopDisposal;const resolve=async()=>{if(local)return local.resolve();if(!active2||!endpoint||!workspace||globalThis.location.origin!==endpoint)throw new Error("Hosted Data context unavailable.");const started=revision;const{data:{session},error}=await auth.getSession();if(!active2||globalThis.location.origin!==endpoint||started!==revision||error||!session||person!==undefined&&person!==session.user.id){throw new Error("Hosted Data context unavailable.")}const expiresAt=(session.expires_at??0)*1000;if(!Number.isFinite(expiresAt)||expiresAt<=Date.now()||!session.user.id){throw new Error("Hosted Data context unavailable.")}person=session.user.id;const isCurrent=()=>active2&&globalThis.location.origin===endpoint&&revision===started&&person===session.user.id;return{workspace,endpoint,accessToken:session.access_token,expiresAt,isCurrent,memberId:session.user.id,binding}};const uninstall=installMemberContext(resolve);const dispose=()=>{if(!active2)return;active2=false;local?.dispose();revision++;subscription?.unsubscribe();stopDisposal?.();uninstall();if(installedDispose===dispose)installedDispose=undefined};installedDispose=dispose;stopDisposal=registered?.onDispose(dispose);if(!active2)return;subscription=auth.onAuthStateChange((event,session)=>{const next=session?.user.id??null;if(event==="SIGNED_OUT"||person!==undefined&&next!==person||registered&&person!==undefined&&event==="SIGNED_IN"&&token!==session?.access_token){revision++;local?.invalidate()}person=next;token=session?.access_token}).data.subscription;local?.start()}var os={init};var CLI_CALLBACK="http://127.0.0.1:53682/oauth/callback";function authorizationConfiguration(value){const setup=value;if(!setup||typeof setup.clientId!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(setup.clientId)||setup.redirectUri!==CLI_CALLBACK||!Array.isArray(setup.scopes)||setup.scopes.length!==1||setup.scopes[0]!=="email")throw new Error("Unavailable");return{clientId:setup.clientId,redirectUri:CLI_CALLBACK,scopes:["email"]}}function authorizationDetails(value,id3,setup,userId,account){const details=value;if(!details||details.authorization_id!==id3||details.redirect_uri!==setup.redirectUri||details.client?.id!==setup.clientId||typeof details.client.name!=="string"||!details.client.name.trim()||details.client.name.length>128||/[\x00-\x1f\x7f]/.test(details.client.name)||details.user?.id!==userId||details.user.email!==account.email||typeof details.scope!=="string"||details.scope.trim()!=="email")return Object.freeze({status:"invalid"});return Object.freeze({status:"consent",clientName:details.client.name.trim(),account,scopes:Object.freeze([...setup.scopes]),callbackAddress:new URL(setup.redirectUri).host})}function authorizationReturn(value,decision){const returnUrl=value?.redirect_url;if(typeof returnUrl!=="string"||returnUrl.length>8192||!returnUrl.startsWith(`${CLI_CALLBACK}?`)||/[\x00-\x20\x7f]/.test(returnUrl))return Object.freeze({status:"invalid"});try{const url=new URL(returnUrl);if(url.origin+url.pathname!==CLI_CALLBACK||url.username||url.password||url.hash)return Object.freeze({status:"invalid"});const parameters=url.searchParams;const allowed=["code","state","error","error_description","error_uri"];for(const key of parameters.keys()){if(!allowed.includes(key)||parameters.getAll(key).length!==1)return Object.freeze({status:"invalid"})}const code=parameters.get("code");const error=parameters.get("error");if(!parameters.get("state")||Boolean(code)===Boolean(error)||decision==="deny"&&!error||decision==="approve"&&!code||parameters.has("code")&&!code||parameters.has("error")&&!error||code&&(parameters.has("error_description")||parameters.has("error_uri")))return Object.freeze({status:"invalid"});return Object.freeze({status:"return",returnUrl})}catch{return Object.freeze({status:"invalid"})}}function authorizationFailure(error){const status=error?.status;return Object.freeze({status:status===404||status===410||status===400?"expired":status===401?"signed_out":status===403||status===422?"invalid":"unavailable"})}function createBrowserAuth(runtime){const coordinators=new Map;function publish(c,state){c.state=Object.freeze(state);for(const listener of c.listeners){try{listener(c.state)}catch{}}}function notify(c,event){for(const listener of c.sessions){try{listener(event,event==="SIGNED_OUT"?null:c.session)}catch{}}}function expire(c){if(!c.active||!c.session&&c.state.status==="expired")return;c.revision++;if(c.timer)clearTimeout(c.timer);c.session=null;publish(c,{status:"expired"});notify(c,"SIGNED_OUT")}function accept(c,event,session){if(!c.active)return;if(event==="INITIAL_SESSION"&&c.state.status!=="initializing")return;if(event==="TOKEN_REFRESHED"&&!c.session&&c.state.status!=="initializing")return;const replaced=c.session?.user?.id!==session?.user?.id||event==="SIGNED_OUT"||!!(event==="SIGNED_IN"&&c.session&&session?.access_token!==c.session.access_token);if(replaced)c.revision++;if(c.timer)clearTimeout(c.timer);const pending=c.state.pending;if(!session){c.session=null;publish(c,{status:c.state.status==="expired"?"expired":"signed_out",...pending?{pending}:{}});notify(c,"SIGNED_OUT");return}if(!validSession(session)){c.session=session;expire(c);return}c.session=session;const email=typeof session.user.email==="string"?session.user.email.trim():"";const metadata=session.user.user_metadata;const displayName=["name","full_name","first_name"].map((key)=>metadata?.[key]).find((value)=>typeof value==="string"&&value.trim());const name=displayName?.trim()||email;const account=!replaced&&c.state.account?.email===email&&c.state.account.displayName===name?c.state.account:Object.freeze({email,displayName:name});publish(c,{status:"signed_in",account,...pending?{pending}:{}});notify(c,event);const checkExpiry=()=>{if(!c.active||!c.session)return;const remaining=c.session.expires_at*1000-Date.now();if(remaining<=0)expire(c);else c.timer=setTimeout(checkExpiry,Math.min(remaining,2147483647))};checkExpiry()}function validSession(session){return typeof session.access_token==="string"&&/^[^\s]{1,8192}$/.test(session.access_token)&&typeof session.user?.id==="string"&&!!session.user.id&&Number.isFinite(session.expires_at)&&session.expires_at*1000>Date.now()}function createCoordinator(origin){const c={state:Object.freeze({status:"initializing"}),session:null,revision:0,active:true,refs:0,listeners:new Set,sessions:new Set,ready:Promise.resolve()};c.ready=(async()=>{const revision=c.revision;try{if(!allowedOrigin(origin))throw runtime.failure("unavailable");const response2=await fetch(`${origin}/api/auth`,{method:"GET",credentials:"same-origin",redirect:"error",cache:"no-store"});if(!response2.ok)throw runtime.failure("unavailable");const configuration=validateConfiguration(await response2.json());if(configuration.authorization&&origin!=="https://auth.oddington.ai"&&origin!=="http://127.0.0.1:5176")throw runtime.failure("unavailable");c.authorization=configuration.authorization;if(!c.active||globalThis.location?.origin!==origin)return;c.provider=await runtime.provider(configuration,{revision:()=>c.revision,current:(revision2)=>current(c,origin,revision2),canPersistSession:()=>c.active&&(c.state.status==="initializing"||!!c.session||c.state.pending==="verify_code"),canAuthorize:(accessToken)=>current(c,origin,c.revision)&&!!c.session&&c.session.access_token===accessToken&&c.state.pending!=="sign_out"});if(!c.active||globalThis.location?.origin!==origin){c.provider.dispose();return}const subscription=c.provider.onAuthStateChange((event,session)=>{if(c.state.status==="initializing"&&c.state.pending==="sign_out")return;accept(c,event,session)}).data.subscription;c.unsubscribe=()=>subscription.unsubscribe();const started=c.revision;const{data:data2,error}=await c.provider.getSession();if(!current(c,origin,started))return;if(error){if(terminalSessionFailure(error))expire(c);else if(!c.session||!validSession(c.session))publish(c,{status:"unavailable",error:"unavailable"})}else if(c.state.pending!=="sign_out")accept(c,"INITIAL_SESSION",data2.session)}catch{if(current(c,origin,revision))publish(c,{status:"unavailable",error:"unavailable"})}})();return c}function current(c,origin,revision){if(c.session&&!validSession(c.session))expire(c);return c.active&&c.revision===revision&&globalThis.location?.origin===origin}return{create(){const origin=globalThis.location?.origin??"";let c=coordinators.get(origin);if(!c){c=createCoordinator(origin);coordinators.set(origin,c)}const coordinator=c;coordinator.refs++;let active2=true;let ownedAction;let authorizationId;let authorizationGeneration=0;let inspected;const observers=new Set;const sessionObservers=new Set;const disposalObservers=new Set;let lastState=coordinator.state;const observation=(state)=>{lastState=state;for(const listener of observers){try{listener(state)}catch{}}};coordinator.listeners.add(observation);const assertActive=()=>{if(!active2)throw runtime.failure("disposed")};async function action(kind,work){assertActive();if(coordinator.action&&kind!=="sign_out")throw runtime.failure("busy");if(kind==="sign_out"&&coordinator.state.pending==="sign_out")throw runtime.failure("busy");if(kind==="sign_out"){coordinator.revision++;notify(coordinator,"SIGNED_OUT")}const marker={};coordinator.action=marker;ownedAction=marker;const revision=coordinator.revision;publish(coordinator,{...coordinator.state,error:undefined,pending:kind});try{await coordinator.ready;assertActive();if(!coordinator.provider||!coordinator.active||globalThis.location?.origin!==origin)throw runtime.failure("unavailable");if(!current(coordinator,origin,revision))throw runtime.failure("stale");if(coordinator.action!==marker)throw runtime.failure("stale");await work(coordinator.provider);assertActive();if(coordinator.action!==marker)throw runtime.failure("stale");if(!current(coordinator,origin,revision)&&kind!=="verify_code"&&kind!=="sign_out")throw runtime.failure("stale")}catch(error){const reason=!active2?"disposed":!current(coordinator,origin,revision)?"stale":safeReason(error)??"unavailable";if(active2&¤t(coordinator,origin,revision))publish(coordinator,{...coordinator.state,error:reason});throw runtime.failure(reason)}finally{if(coordinator.action===marker){coordinator.action=undefined;if(coordinator.active){publish(coordinator,{...coordinator.state,pending:undefined});if(kind==="sign_out"&&coordinator.session)notify(coordinator,"TOKEN_REFRESHED")}}if(ownedAction===marker)ownedAction=undefined}}async function authorize(kind,id3){if(!active2)return Object.freeze({status:"disposed"});if(id3!==authorizationId){authorizationId=id3;authorizationGeneration++;inspected=undefined}if(!id3)return Object.freeze({status:"missing"});if(typeof id3!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(id3))return Object.freeze({status:"invalid"});const generation=authorizationGeneration;await coordinator.ready;if(!active2)return Object.freeze({status:"disposed"});if(generation!==authorizationGeneration)return Object.freeze({status:"stale"});const revision=coordinator.revision;if(!current(coordinator,origin,revision))return Object.freeze({status:"stale"});if(!coordinator.session||coordinator.state.pending==="sign_out")return Object.freeze({status:coordinator.state.status==="expired"?"expired":coordinator.state.status==="unavailable"?"unavailable":"signed_out"});if(!coordinator.authorization||!coordinator.provider)return Object.freeze({status:"unavailable"});if(coordinator.action)return Object.freeze({status:"busy"});if(kind!=="get"&&(!inspected||inspected.id!==id3||inspected.revision!==revision))return Object.freeze({status:"stale"});if(kind!=="get"&&inspected?.result.status!=="consent")return inspected.result;const marker={};coordinator.action=marker;ownedAction=marker;const requestCurrent=()=>active2&&generation===authorizationGeneration&¤t(coordinator,origin,revision)&&coordinator.action===marker&&!!coordinator.session&&coordinator.state.pending!=="sign_out";const stale2=()=>Object.freeze({status:active2?"stale":"disposed"});try{const provider=coordinator.provider;const response2=await provider.authorization.get(id3,requestCurrent);if(!requestCurrent())return stale2();if(response2.error){inspected=undefined;const failure=authorizationFailure(response2.error);if(failure.status==="signed_out")expire(coordinator);return failure}const account=coordinator.state.account;const result2=response2.data&&typeof response2.data==="object"&&"redirect_url"in response2.data?authorizationReturn(response2.data):authorizationDetails(response2.data,id3,coordinator.authorization,coordinator.session.user.id,account);inspected={id:id3,revision,result:result2};if(kind==="get"||result2.status!=="consent")return result2;if(!requestCurrent())return stale2();const decision=await provider.authorization[kind](id3,requestCurrent);if(!requestCurrent())return stale2();const returned=decision.error?authorizationFailure(decision.error):authorizationReturn(decision.data,kind);if(returned.status==="signed_out")expire(coordinator);inspected={id:id3,revision,result:returned};return returned}catch(error){if(!requestCurrent())return stale2();inspected=undefined;if(safeReason(error)==="stale")return stale2();return Object.freeze({status:"unavailable"})}finally{if(coordinator.action===marker)coordinator.action=undefined;if(ownedAction===marker)ownedAction=undefined}}const handle=Object.freeze({authorization:Object.freeze({get:(id3)=>authorize("get",id3),approve:(id3)=>authorize("approve",id3),deny:(id3)=>authorize("deny",id3)}),getState(){if(active2&&coordinator.session&&!validSession(coordinator.session))expire(coordinator);return lastState},subscribe(listener){assertActive();observers.add(listener);return()=>{observers.delete(listener)}},async sendCode(email){assertActive();if(!validEmail(email))throw runtime.failure("invalid_input");await action("send_code",async(provider)=>{const{error}=await provider.signInWithOtp({email:email.trim(),options:{shouldCreateUser:false}});if(error&&!accountRefusal(error))throw runtime.failure("unavailable")})},async verifyCode(email,code){assertActive();if(!validEmail(email)||typeof code!=="string"||!/^\d{6}$/.test(code))throw runtime.failure("invalid_input");await action("verify_code",async(provider)=>{const revision=coordinator.revision;const{data:data2,error}=await provider.verifyOtp({email:email.trim(),token:code,type:"email"});if(error)throw runtime.failure(accountRefusal(error)?"invalid_code":"unavailable");if(!data2.session||!validSession(data2.session))throw runtime.failure("invalid_code");if(!current(coordinator,origin,revision)&&(coordinator.session?.access_token!==data2.session.access_token||coordinator.revision!==revision+1||coordinator.state.pending!=="verify_code"))throw runtime.failure("stale");accept(coordinator,"SIGNED_IN",data2.session)})},async signOut(){assertActive();await action("sign_out",async(provider)=>{const revision=coordinator.revision;const{error}=await provider.signOut({scope:"local"});if(error)throw runtime.failure("unavailable");if(!current(coordinator,origin,revision)&&coordinator.session)throw runtime.failure("stale");accept(coordinator,"SIGNED_OUT",null)})},dispose(){if(!active2)return;active2=false;authorizationGeneration++;inspected=undefined;if(ownedAction&&coordinator.action===ownedAction)coordinator.revision++;observers.clear();coordinator.listeners.delete(observation);for(const listener of disposalObservers){try{listener()}catch{}}disposalObservers.clear();for(const listener of sessionObservers)coordinator.sessions.delete(listener);sessionObservers.clear();if(--coordinator.refs===0){coordinator.active=false;coordinator.revision++;if(coordinator.timer)clearTimeout(coordinator.timer);coordinator.unsubscribe?.();coordinator.provider?.dispose();coordinator.provider=undefined;coordinator.session=null;coordinator.listeners.clear();coordinator.sessions.clear();coordinators.delete(origin)}}});registerBrowserAuth(handle,{onDispose(callback){if(!active2){callback();return()=>{}}disposalObservers.add(callback);return()=>{disposalObservers.delete(callback)}},async getSession(){assertActive();await coordinator.ready;assertActive();const revision=coordinator.revision;if(!current(coordinator,origin,revision)||!coordinator.provider||!coordinator.session||coordinator.state.pending==="sign_out")return{data:{session:null},error:null};let result2;try{result2=await coordinator.provider.getSession()}catch{result2={data:{session:null},error:runtime.failure("unavailable")}}if(!active2||!current(coordinator,origin,revision))return{data:{session:null},error:runtime.failure("stale")};if(result2.error){if(!terminalSessionFailure(result2.error)&&coordinator.session&&validSession(coordinator.session))return{data:{session:coordinator.session},error:null};expire(coordinator);return{data:{session:null},error:runtime.failure("unavailable")}}accept(coordinator,"TOKEN_REFRESHED",result2.data.session);return{data:{session:coordinator.session},error:null}},onAuthStateChange(callback){if(!active2){callback("SIGNED_OUT",null);return{data:{subscription:{unsubscribe(){}}}}}const listener=(event,session)=>callback(event,session);coordinator.sessions.add(listener);sessionObservers.add(listener);callback("INITIAL_SESSION",coordinator.session);return{data:{subscription:{unsubscribe(){coordinator.sessions.delete(listener);sessionObservers.delete(listener)}}}}}});return handle}}}function safeReason(error){const reason=error?.reason;return["invalid_input","invalid_code","unavailable","busy","stale","disposed"].includes(reason)?reason:undefined}function accountRefusal(error){return[400,401,403,404,422].includes(error?.status??0)}function terminalSessionFailure(error){return[400,401,403,404,422].includes(error?.status??0)}function validEmail(email){return typeof email==="string"&&email.length<=320&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())}function allowedOrigin(origin){if(origin==="http://127.0.0.1:5176"||origin==="https://auth.oddington.ai")return true;try{const url=new URL(origin);const slug=url.hostname.endsWith(".oddington.ai")?url.hostname.slice(0,-".oddington.ai".length):"";return slug.length<=63&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)&&!["auth","api","os","www"].includes(slug)&&origin===`https://${slug}.oddington.ai`}catch{return false}}function validateConfiguration(value){const configuration=value;if(!configuration||typeof configuration.providerUrl!=="string"||typeof configuration.publishableKey!=="string")throw new Error("Unavailable");const url=new URL(configuration.providerUrl);if(url.origin!==configuration.providerUrl||url.protocol!=="https:"||url.username||url.password||url.port||!configuration.publishableKey)throw new Error("Unavailable");return{providerUrl:url.origin,publishableKey:configuration.publishableKey,...configuration.authorization===undefined?{}:{authorization:authorizationConfiguration(configuration.authorization)}}}class BrowserAuthError extends Error{reason;constructor(reason){super(`Browser authentication failed: ${reason}`);this.reason=reason;this.name="BrowserAuthError"}}async function provider(configuration,guard){const{AuthClient:AuthClient2}=await Promise.resolve().then(() => (init_auth_provider(),exports_auth_provider));if(!guard.current(guard.revision()))throw new BrowserAuthError("stale");const provenance=new Map;let removalRevision;let authorizationRequest;let authorizationQueue=Promise.resolve();const storage=globalThis.localStorage;const client=new AuthClient2({url:`${configuration.providerUrl}/auth/v1`,headers:{apikey:configuration.publishableKey,Authorization:`Bearer ${configuration.publishableKey}`},storageKey:`sb-${new URL(configuration.providerUrl).hostname.split(".")[0]}-auth-token`,persistSession:true,autoRefreshToken:true,detectSessionInUrl:false,storage:{getItem:(key)=>storage.getItem(key),removeItem(key){if(!guard.current(removalRevision??guard.revision()))throw new BrowserAuthError("stale");storage.removeItem(key)},setItem(key,value){const token=JSON.parse(value).access_token;const revision=token?provenance.get(token):undefined;if(!guard.current(revision??guard.revision())||token&&!guard.canPersistSession())throw new BrowserAuthError("stale");storage.setItem(key,value)}},fetch:Object.assign(async(input,init2)=>{const revision=guard.revision();const request=String(input).startsWith(`${configuration.providerUrl}/auth/v1/oauth/authorizations/`)?authorizationRequest:undefined;const rejectStale=()=>{if(request)request.rejected=true;throw new BrowserAuthError("stale")};if(request&&(!request.current()||!guard.canAuthorize(new Headers(init2?.headers).get("authorization")?.replace(/^Bearer /,"")??"")))rejectStale();const response2=await fetch(input,{...init2,redirect:"error"});const body=await response2.arrayBuffer();if(!guard.current(revision)||request&&!request.current())rejectStale();const result2=new Response([204,205,304].includes(response2.status)?null:body,{status:response2.status,statusText:response2.statusText,headers:response2.headers});const json3=result2.json.bind(result2);result2.json=async()=>{const value=await json3();if(!guard.current(revision)||request&&!request.current())rejectStale();if(value&&typeof value.access_token==="string")provenance.set(value.access_token,revision);return value};return result2},{preconnect:fetch.preconnect})});async function authorization(kind,id3,current){const previous=authorizationQueue;let release;authorizationQueue=new Promise((resolve)=>{release=resolve});await previous;const request={current,rejected:false};authorizationRequest=request;try{if(!current())throw new BrowserAuthError("stale");const result2=await(kind==="get"?client.oauth.getAuthorizationDetails(id3):kind==="approve"?client.oauth.approveAuthorization(id3,{skipBrowserRedirect:true}):client.oauth.denyAuthorization(id3,{skipBrowserRedirect:true}));if(request.rejected||!current())throw new BrowserAuthError("stale");return result2}catch(error){if(request.rejected||!current())throw new BrowserAuthError("stale");throw error}finally{authorizationRequest=undefined;release()}}return{authorization:{get:(id3,current)=>authorization("get",id3,current),approve:(id3,current)=>authorization("approve",id3,current),deny:(id3,current)=>authorization("deny",id3,current)},getSession:()=>client.getSession(),onAuthStateChange:(callback)=>client.onAuthStateChange((event,session)=>{const revision=session?provenance.get(session.access_token):undefined;if(revision!==undefined&&!guard.current(revision))return;callback(event,session);if(session)provenance.delete(session.access_token)}),signInWithOtp:(input)=>client.signInWithOtp(input),verifyOtp:(input)=>client.verifyOtp(input),async signOut(input){removalRevision=guard.revision();try{return await client.signOut(input)}finally{removalRevision=undefined}},dispose(){provenance.clear();client.dispose()}}}var auth=createBrowserAuth({provider,failure:(reason)=>new BrowserAuthError(reason)});var identifier=/^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/;var uuid=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}(?![\s\S])/i;var SUMMARY_BYTES=17*1024*1024;class AppRoutineError extends Error{reason;constructor(reason){super(reason);this.reason=reason;this.name="AppRoutineError"}}var fail3=(reason)=>{throw new AppRoutineError(reason)};function current(context){if(!context.isCurrent()||context.signal.aborted)fail3("authority_unavailable")}function appDescriptors(){const value=globalThis[Symbol.for("oddington.app.descriptor")];return value?.routines??[]}async function local(){const context=await resolveAppContext().catch(()=>fail3("authority_unavailable"));if(context.kind!=="local")return fail3("execution_unavailable");current(context);return context}async function request(key,suffix,init2,maximum=SUMMARY_BYTES,retained){if(!identifier.test(key)||!appDescriptors().some((item)=>item.id===key))fail3("authority_unavailable");const context=retained??await local();current(context);try{const response2=await context.requestRoutine(key,suffix,init2);const value=await appResponse(response2,maximum,context.signal);current(context);if(!response2.ok){const reason=value?.error;if(reason==="authority_unavailable"){context.invalidate();fail3(reason)}if(reason==="invalid_input"||reason==="execution_unavailable")fail3(reason);fail3("execution_unavailable")}return value}catch(error){current(context);if(error instanceof AppRoutineError)throw error;fail3("execution_unavailable")}}function summary(value,key,id3){const run=value;if(!only(run,"id,routine,placement,status,createdAt,startedAt,finishedAt,steps,result,failure,publication")||typeof run.id!=="string"||!uuid.test(run.id)||id3!==undefined&&run.id!==id3||run.routine!==key||run.placement!=="local"||!["queued","running","succeeded","failed"].includes(run.status)||!timestamp(run.createdAt)||!optionalTimes(run)||!Array.isArray(run.steps)||run.steps.length>64||run.steps.some((step)=>!only(step,"id,title,status,startedAt,finishedAt,summary,detailAvailable")||typeof step.detailAvailable!=="boolean"||!validStep(step))||new Set(run.steps.map((step)=>step.id)).size!==run.steps.length||Object.hasOwn(run,"result")&&(run.status!=="succeeded"||!bounded(run.result))||run.failure!==undefined&&(run.status!=="failed"||!only(run.failure,"message")||!message(run.failure.message))||run.publication!==undefined&&(run.status!=="succeeded"||!validPublication(run.publication)))fail3("execution_unavailable");return run}function only(value,allowed){return!!value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).every((key)=>allowed.split(",").includes(key))}var timestamp=(value)=>typeof value==="string"&&value.length<=32&&Number.isFinite(Date.parse(value));var message=(value)=>typeof value==="string"&&value.length>0&&value.length<=512;var bounded=(value)=>new TextEncoder().encode(JSON.stringify(value)).byteLength<=256*1024;function optionalTimes(value){return(value.startedAt===undefined||timestamp(value.startedAt))&&(value.finishedAt===undefined||timestamp(value.finishedAt))}function validStep(step){return typeof step.id==="string"&&identifier.test(step.id)&&typeof step.title==="string"&&step.title.length>0&&step.title.length<=256&&["pending","running","completed","failed","skipped"].includes(step.status)&&optionalTimes(step)&&(!Object.hasOwn(step,"summary")||bounded(step.summary))&&(!Object.hasOwn(step,"data")||bounded(step.data))}function validPublication(value){return value&&only(value,value.state==="failed"?"state,message":"state")&&(["not_needed","ready","published"].includes(value.state)||value.state==="failed"&&message(value.message))}function jsonInput(value,ancestors=new Set){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return;if(!value||typeof value!=="object"||ancestors.has(value))return fail3("invalid_input");const array3=Array.isArray(value),keys4=Reflect.ownKeys(value);if(!array3&&![Object.prototype,null].includes(Object.getPrototypeOf(value))||array3&&(keys4.length!==value.length+1||!Array.from({length:value.length},(_,index)=>Object.hasOwn(value,index)).every(Boolean)))return fail3("invalid_input");ancestors.add(value);for(const key of keys4){if(array3&&key==="length")continue;const descriptor=Object.getOwnPropertyDescriptor(value,key);if(typeof key!=="string"||!descriptor.enumerable||!Object.hasOwn(descriptor,"value"))return fail3("invalid_input");jsonInput(descriptor.value,ancestors)}ancestors.delete(value)}function structure(value){return JSON.stringify(value,(_key,item)=>item&&typeof item==="object"&&!Array.isArray(item)?Object.fromEntries(Object.keys(item).sort().map((key)=>[key,item[key]])):item)}function handle(key,id3,context){if(typeof id3!=="string"||!uuid.test(id3))fail3("invalid_input");const read2=async()=>summary(await request(key,`runs/${id3}`,undefined,SUMMARY_BYTES,context),key,id3);return Object.freeze({current:read2,async*watch(){let previous;for(;;){const state=await read2(),encoded=JSON.stringify(state);if(encoded!==previous){previous=encoded;yield state}if(state.status==="succeeded"||state.status==="failed")return;await new Promise((resolve)=>setTimeout(resolve,100))}},async step(step){if(typeof step!=="string"||!identifier.test(step))fail3("invalid_input");const value=await request(key,`runs/${id3}/steps/${step}`,undefined,514*1024,context);if(!only(value,"id,title,status,startedAt,finishedAt,summary,data")||value.id!==step||!validStep(value))fail3("execution_unavailable");return value},async publish(){return summary(await request(key,`runs/${id3}/publish`,{method:"POST"},SUMMARY_BYTES,context),key,id3)}})}async function describeAppRoutine(key){const descriptor=appDescriptors().find((item)=>item.id===key);if(!descriptor)return fail3("authority_unavailable");const unavailable3=()=>({...structuredClone(descriptor),connections:descriptor.connections.map((connection)=>({...connection,available:false})),readiness:{state:"unavailable",reason:"capability_unavailable",message:"Routine capability unavailable."}});try{const value=await request(key,"describe",undefined,1024*1024);if(!only(value,"id,title,input,connections,steps,readiness")||!value.readiness||!Array.isArray(value.connections)||structure({...value,readiness:undefined,connections:value.connections.map(({available,...item})=>item)})!==structure(descriptor)||value.connections.some((item)=>typeof item.available!=="boolean")||!(value.readiness.state==="ready"&&only(value.readiness,"state,placement")&&value.readiness.placement==="local"||value.readiness.state==="unavailable"&&only(value.readiness,"state,reason,message")&&["not_deployed","definition_invalid","capability_unavailable"].includes(value.readiness.reason)&&message(value.readiness.message)))fail3("execution_unavailable");return value}catch{return unavailable3()}}function appRoutineBinding(key){return Object.freeze({describe:()=>describeAppRoutine(key),async run(...args){if(args.length>1)fail3("invalid_input");let encoded;try{if(args[0]===undefined)encoded="{}";else{jsonInput(args[0]);const input=JSON.stringify(args[0]);if(new TextEncoder().encode(input).byteLength>256*1024)fail3("invalid_input");encoded=`{"input":${input}}`}}catch{return fail3("invalid_input")}const context=await local();const run=summary(await request(key,"runs",{method:"POST",body:encoded},SUMMARY_BYTES,context),key);return handle(key,run.id,context)},runs:Object.freeze({async list(){const value=await request(key,"runs",undefined,20*SUMMARY_BYTES);if(!Array.isArray(value)||value.length>20)return fail3("execution_unavailable");const runs=value.map((run)=>summary(run,key));if(new Set(runs.map((run)=>run.id)).size!==runs.length)fail3("execution_unavailable");return runs},async get(id3){const run=handle(key,id3,await local());await run.current();return run}})})}var app=Object.freeze({listRoutines:()=>Promise.all(appDescriptors().map(({id:id3})=>describeAppRoutine(id3))),routines:new Proxy(Object.create(null),{get(_target,key){if(typeof key!=="string"||!appDescriptors().some((item)=>item.id===key))return;return appRoutineBinding(key)},set:()=>false,defineProperty:()=>false,deleteProperty:()=>false})});var LIMIT2=16*1024;var context;var unavailable3=()=>new Error("App routine reporting unavailable");function freeze2(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))freeze2(child);Object.freeze(value)}return value}if((typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__)&&typeof process!=="undefined"&&process.env.ODDINGTON_APP_RUN!==undefined){let fail4=function(){broken=true;pending?.reject(unavailable3());pending=undefined;channel.destroy()},report=function(value){let frame;try{frame=JSON.stringify({...value,sequence:++sequence});if(Buffer.byteLength(frame)>LIMIT2)return rejected()}catch{return rejected()}const operation2=queue.then(async()=>{if(broken)throw unavailable3();await new Promise((resolve,reject)=>{const timeout=setTimeout(fail4,30000);pending={sequence:JSON.parse(frame).sequence,resolve(){clearTimeout(timeout);resolve()},reject(error){clearTimeout(timeout);reject(error)}};channel.ref();channel.write(`${frame}
|
|
77
77
|
`,(error)=>{if(error)fail4()})})});queue=operation2.catch(()=>{});return operation2},rejected=function(){if(!broken)channel.end(`{"type":"invalid"}
|
|
78
78
|
`);broken=true;pending?.reject(unavailable3());pending=undefined;return Promise.reject(unavailable3())};if(process.env.ODDINGTON_APP_RUN!=="1")throw unavailable3();const{readSync,closeSync}=await import("node:fs");const{Socket}=await import("node:net");let bootstrap;try{const chunks=[];let size=0;for(;;){const bytes2=new Uint8Array(4096);const count=readSync(4,bytes2,0,bytes2.length,null);if(!count)break;size+=count;if(size>131072)throw unavailable3();chunks.push(bytes2.slice(0,count))}closeSync(4);const bytes=new Uint8Array(size);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.length}bootstrap=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));if(!bootstrap||Object.keys(bootstrap).sort().join(",")!=="contract,input")throw unavailable3()}catch{throw unavailable3()}const contract=parseAppRoutineContract(bootstrap.contract);validateAppRoutineInput(contract,bootstrap.input);const input=freeze2(bootstrap.input);const channel=new Socket({fd:3,readable:true,writable:true});channel.unref();let broken=false,finishing=false,sequence=0;let pending;let buffer="";channel.on("error",fail4);channel.on("close",fail4);channel.on("end",fail4);channel.on("data",(bytes)=>{buffer+=bytes.toString("utf8");if(Buffer.byteLength(buffer)>1024)return fail4();const end=buffer.indexOf(`
|
|
79
|
-
`);if(end<0)return;try{const ack=JSON.parse(buffer.slice(0,end));if(end!==buffer.length-1||!pending||!ack||Object.keys(ack).sort().join(",")!=="accepted,sequence"||ack.sequence!==pending.sequence||ack.accepted!==true)return fail4();buffer="";pending.resolve();pending=undefined;channel.unref()}catch{fail4()}});let queue=Promise.resolve();context={input,step(id3,...
|
|
79
|
+
`);if(end<0)return;try{const ack=JSON.parse(buffer.slice(0,end));if(end!==buffer.length-1||!pending||!ack||Object.keys(ack).sort().join(",")!=="accepted,sequence"||ack.sequence!==pending.sequence||ack.accepted!==true)return fail4();buffer="";pending.resolve();pending=undefined;channel.unref()}catch{fail4()}});let queue=Promise.resolve();context={input,step(id3,...summary2){if(finishing||broken||summary2.length>1)return rejected();try{validateAppRoutineStep(contract,id3,summary2[0])}catch{return rejected()}return report({type:"step",id:id3,...summary2.length?{summary:summary2[0]}:{}})},finish(...result2){if(finishing||broken||result2.length>1)return rejected();finishing=true;try{validateAppRoutineResult(contract,result2[0])}catch{return rejected()}return report({type:"finish",...result2.length?{result:result2[0]}:{}})}};Object.freeze(context)}var appRun={current(){return context}};init_inbox_contract();init_inbox_contract();init_inbox_contract();init_inbox_files();init_inbox_contract();init_inbox_contract();var PREPARED_RECORD_INPUT_LIMIT=64*1024*1024;function routineDataEnvelope(command){return"preflight"in command?{operation:"changes.validate",captured:command.preflight}:("apply"in command)?{operation:"changes.publish",captured:command.apply}:{operation:"changes.publish",request:command}}function routinePublicationClient(options={}){const environment=typeof __ODDINGTON_BROWSER__!=="undefined"&&__ODDINGTON_BROWSER__?{}:typeof process==="undefined"?{}:process.env;const installed2=routineTransport();const local2=installed2?.request??localRoutineRequest(environment);const workspace=installed2?"installed":options.workspace??environment.ODDINGTON_ROUTINE_WORKSPACE;const capability=options.capability??environment.ODDINGTON_ROUTINE_RUN;if(!workspace||!/^[a-z0-9][a-z0-9-]*$/.test(workspace)||capability!==undefined&&!/^[0-9a-f]{64}$/.test(capability))throw new Error("A workspace and valid optional routine capability are required");const workingRoot=options.workingRoot??environment.ODDINGTON_INBOX_WORKING_ROOT??(typeof __ODDINGTON_BROWSER__!=="undefined"&&__ODDINGTON_BROWSER__?undefined:typeof process==="undefined"?undefined:process.cwd());const headers=capability?{"x-oddington-run":capability}:{};const request2=options.request??(capability?async(path,init2)=>{if(path==="/api/data")return fetch(`https://${workspace}.oddington.ai/api/data`,{...init2,redirect:"error"});const origin=`https://${workspace}.oddington.ai`;const target=new URL(path,`${origin}/`);if(workspace.length>63||["auth","www","api","os"].includes(workspace)||target.origin!==origin||target.search||target.hash||target.username||target.password||!/^\/api\/inbox\/(check|publish|resolve|files)$/.test(path)||init2?.method!=="POST")throw new Error("Invalid routine endpoint");return fetch(target,{...init2,redirect:"error"})}:async()=>{throw new Error("Member publication requires a host-supplied request")});async function send3(operation2,body){if(local2)return await local2(operation2,body);const writing=operation2==="records/update";const reading=operation2==="records/read";const response2=await request2(writing||reading?"/api/data":`/api/inbox/${operation2}`,{method:"POST",headers:{"content-type":"application/json",...headers,...writing||reading?{"x-oddington-workspace":workspace,"x-oddington-captured-records":"1"}:{}},body:JSON.stringify(writing?routineDataEnvelope(validateRoutineRecordWrite(body)):reading?{operation:"records.select",request:validateRecordRead(body)}:body)});const result2=await response2.json();if(!response2.ok&&operation2==="records/update")throw new RoutineRecordWriteError(result2.error??"Could not confirm routine preparation",result2.effect??"uncertain");if(!response2.ok)throw new Error(result2.error??"Could not confirm routine publication");return result2}const transport={async publish(body){return await send3("publish",body)},async resolve(body){await send3("resolve",body)}};async function readRecords(input){return await send3("records/read",validateRecordRead(input))}return{...createInboxPublisher(transport),readRecords,repository:{readRecords,async writeRecords(input,options2){if(!capability&&!installed2)throw new Error("A trusted routine launch is required");return await send3("records/update",validateRoutineRecordWrite({input,requestKey:options2?.requestKey}))},async updateRecords(input,options2){if(!capability&&!installed2)throw new Error("A trusted routine launch is required");return await send3("records/update",validateRoutineRecordWrite({input:validateRecordUpdate(input),requestKey:options2?.requestKey}))},async deleteRecords(input,options2){if(!capability&&!installed2)throw new Error("A trusted routine launch is required");return await send3("records/update",validateRoutineRecordWrite({input:validateRecordDelete(input),requestKey:options2?.requestKey}))}},files:{async add(value){const input=validateFileAddOptions(value);if(local2)return validateInboxFile(await local2("files/add",input));if(!workingRoot)throw new Error("Inbox file reads require a working root");if(typeof __ODDINGTON_BROWSER__==="undefined"||!__ODDINGTON_BROWSER__){const{readInboxPublicationFile:readInboxPublicationFile2}=await Promise.resolve().then(() => (init_inbox_publication_file(),exports_inbox_publication_file));const bytes=await readInboxPublicationFile2(workingRoot,input);const name=input.name??input.path.split("/").at(-1);const response2=await request2("/api/inbox/files",{method:"POST",headers:{"content-type":"application/octet-stream",...headers,"x-oddington-file":JSON.stringify({name,...input.csv?{csv:input.csv}:{}})},body:Uint8Array.from(bytes).buffer});const result2=await response2.json();if(!response2.ok)throw new Error(result2.error??"Could not retain file");return await verifyInboxFile(bytes,validateInboxFile(result2))}throw new Error("Inbox file reads require a Node working root")}},async check(body){await send3("check",{requestKey:body.requestKey,item:validatePublication(body.item)})}}}export{selection,schema,routinePublicationClient,richTextBlock,respond,resolveAsk,recordsBlock,recordBlock,question,os,inbox,files,fileBlock,file,defineRoutine,defineHandler,data,continueAsk,connections,auth,asksBlock,appRun,app,RoutineRecordWriteError,InboxOperationError,InboxContractError,FileOperationError,DataOperationError,BrowserAuthError,AppRoutineError,AirtableOperationError};
|